bitburner-src/editor.main.js
2021-12-13 19:46:08 -05:00

136615 lines
6.4 MiB
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*!-----------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Version: 0.27.0(730c98dfd4e771a851edf1bc944ea5c5018ee8cb)
* Released under the MIT license
* https://github.com/microsoft/vscode/blob/main/LICENSE.txt
*-----------------------------------------------------------*/
(function() {
var __m = ["require","exports","vs/base/common/lifecycle","vs/editor/common/core/range","vs/nls","vs/nls!vs/editor/editor.main","vs/base/common/event","vs/base/browser/dom","vs/base/common/strings","vs/platform/instantiation/common/instantiation","vs/css!vs/editor/editor.main","vs/platform/theme/common/themeService","vs/base/common/errors","vs/editor/common/core/position","vs/editor/browser/editorExtensions","vs/base/common/async","vs/platform/contextkey/common/contextkey","vs/base/common/platform","vs/editor/common/modes","vs/base/common/arrays","vs/base/common/types","vs/editor/common/core/selection","vs/platform/theme/common/colorRegistry","vs/base/common/cancellation","vs/base/common/uri","vs/editor/common/editorContextKeys","vs/platform/commands/common/commands","vs/base/common/codicons","vs/editor/browser/services/codeEditorService","vs/base/common/color","vs/base/browser/fastDomNode","vs/editor/common/model/textModel","vs/platform/registry/common/platform","vs/platform/actions/common/actions","vs/platform/notification/common/notification","vs/editor/common/config/editorOptions","vs/editor/common/services/modelService","vs/platform/keybinding/common/keybinding","vs/platform/configuration/common/configuration","vs/base/browser/browser","vs/editor/common/controller/cursorCommon","vs/base/common/keyCodes","vs/base/common/objects","vs/base/common/resources","vs/base/browser/ui/aria/aria","vs/editor/common/modes/languageConfigurationRegistry","vs/base/common/network","vs/editor/browser/view/viewPart","vs/editor/common/view/editorColorRegistry","vs/base/common/map","vs/base/common/actions","vs/base/browser/keyboardEvent","vs/base/browser/ui/widget","vs/editor/common/model","vs/base/common/iterator","vs/base/browser/mouseEvent","vs/editor/common/core/editOperation","vs/editor/common/services/modeService","vs/platform/opener/common/opener","vs/platform/progress/common/progress","vs/base/browser/touch","vs/base/browser/ui/scrollbar/scrollableElement","vs/editor/common/viewModel/viewModel","vs/editor/common/standaloneStrings","vs/platform/accessibility/common/accessibility","vs/editor/browser/config/configuration","vs/editor/browser/core/editorState","vs/base/common/filters","vs/editor/common/services/resolverService","vs/platform/contextview/browser/contextView","vs/platform/log/common/log","vs/platform/storage/common/storage","vs/base/common/linkedList","vs/base/common/path","vs/base/common/severity","vs/platform/instantiation/common/extensions","vs/editor/common/services/editorWorkerService","vs/editor/common/modes/nullMode","vs/platform/quickinput/common/quickInput","vs/platform/theme/common/iconRegistry","vs/base/common/functional","vs/base/common/stopwatch","vs/base/common/htmlContent","vs/editor/common/core/stringBuilder","vs/base/browser/ui/actionbar/actionbar","vs/editor/common/core/lineTokens","vs/platform/clipboard/common/clipboardService","vs/platform/markers/common/markers","vs/platform/keybinding/common/keybindingsRegistry","vs/platform/telemetry/common/telemetry","vs/base/common/decorators","vs/base/browser/event","vs/base/common/hash","vs/base/browser/globalMouseMoveMonitor","vs/editor/common/core/characterClassifier","vs/editor/common/commands/replaceCommand","vs/editor/common/model/textModelEvents","vs/editor/browser/view/dynamicViewOverlay","vs/platform/configuration/common/configurationRegistry","vs/platform/quickinput/common/quickAccess","vs/platform/theme/common/theme","vs/base/browser/ui/tree/tree","vs/base/common/numbers","vs/base/common/buffer","vs/base/common/iconLabels","vs/base/browser/ui/iconLabel/iconLabels","vs/base/common/mime","vs/base/browser/ui/sash/sash","vs/base/browser/ui/list/listWidget","vs/editor/common/controller/wordCharacterClassifier","vs/editor/common/editorCommon","vs/editor/browser/editorBrowser","vs/editor/common/modes/languageConfiguration","vs/editor/common/view/renderingContext","vs/editor/common/viewLayout/viewLineRenderer","vs/editor/common/viewModel/viewEventHandler","vs/editor/contrib/snippet/snippetParser","vs/base/browser/ui/actionbar/actionViewItems","vs/editor/contrib/gotoSymbol/referencesModel","vs/editor/standalone/common/standaloneThemeService","vs/platform/dialogs/common/dialogs","vs/platform/label/common/label","vs/platform/theme/common/styler","vs/editor/contrib/suggest/suggest","vs/editor/contrib/peekView/peekView","vs/base/common/idGenerator","vs/base/common/range","vs/base/common/scrollable","vs/base/common/diff/diff","vs/base/common/uint","vs/base/browser/ui/codicons/codiconStyles","vs/base/browser/ui/mouseCursor/mouseCursor","vs/css!vs/base/parts/quickinput/browser/media/quickInput","vs/editor/common/config/editorZoom","vs/editor/common/core/token","vs/editor/common/model/wordHelper","vs/editor/common/viewLayout/lineDecorations","vs/editor/contrib/codeAction/types","vs/editor/browser/services/bulkEditService","vs/editor/common/modes/languageFeatureRegistry","vs/editor/common/model/tokensStore","vs/editor/common/controller/cursorWordOperations","vs/editor/common/services/textResourceConfigurationService","vs/platform/instantiation/common/serviceCollection","vs/platform/layout/browser/layoutService","vs/editor/browser/core/markdownRenderer","vs/editor/common/modes/modesRegistry","vs/editor/contrib/find/findModel","vs/editor/browser/controller/coreCommands","vs/editor/browser/widget/codeEditorWidget","vs/editor/browser/widget/embeddedCodeEditorWidget","vs/editor/contrib/codeAction/codeAction","vs/editor/contrib/message/messageController","vs/platform/list/browser/listService","vs/platform/undoRedo/common/undoRedo","vs/base/common/lazy","vs/base/browser/canIUse","vs/base/common/extpath","vs/base/browser/ui/tree/indexTreeModel","vs/base/browser/ui/tree/objectTreeModel","vs/base/browser/formattedTextRenderer","vs/base/browser/ui/highlightedlabel/highlightedLabel","vs/base/browser/ui/scrollbar/scrollbarArrow","vs/base/common/labels","vs/base/browser/dnd","vs/base/browser/ui/checkbox/checkbox","vs/base/browser/ui/list/listView","vs/editor/browser/editorDom","vs/editor/common/config/fontInfo","vs/editor/browser/controller/textAreaInput","vs/editor/browser/view/viewLayer","vs/editor/common/model/textModelSearch","vs/editor/common/modes/supports","vs/editor/common/modes/supports/richEditBrackets","vs/editor/common/standalone/standaloneEnums","vs/editor/common/view/viewEvents","vs/editor/browser/viewParts/glyphMargin/glyphMargin","vs/editor/common/viewModel/viewModelEventDispatcher","vs/editor/contrib/folding/foldingRanges","vs/base/browser/ui/iconLabel/iconLabel","vs/base/browser/ui/tree/abstractTree","vs/base/browser/ui/inputbox/inputBox","vs/base/common/keybindingLabels","vs/editor/common/services/markersDecorationService","vs/editor/common/commands/shiftCommand","vs/editor/common/controller/cursorMoveOperations","vs/editor/common/controller/cursorDeleteOperations","vs/editor/common/controller/cursorTypeOperations","vs/editor/contrib/parameterHints/provideSignatureHelp","vs/platform/jsonschemas/common/jsonContributionRegistry","vs/editor/common/config/commonEditorConfig","vs/editor/browser/controller/mouseTarget","vs/platform/actions/browser/menuEntryActionViewItem","vs/platform/workspace/common/workspace","vs/editor/standalone/browser/simpleServices","vs/editor/contrib/snippet/snippetController2","vs/base/browser/iframe","vs/base/browser/ui/scrollbar/scrollbarState","vs/base/common/assert","vs/base/common/collections","vs/base/browser/ui/tree/treeIcons","vs/base/common/glob","vs/base/common/marshalling","vs/base/browser/ui/scrollbar/abstractScrollbar","vs/base/common/worker/simpleWorker","vs/base/parts/quickinput/common/quickInput","vs/css!vs/base/browser/ui/actionbar/actionbar","vs/base/browser/ui/contextview/contextview","vs/base/browser/ui/countBadge/countBadge","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/base/browser/ui/splitview/splitview","vs/base/parts/quickinput/browser/quickInputUtils","vs/editor/browser/config/elementSizeObserver","vs/editor/browser/viewParts/minimap/minimapCharSheet","vs/editor/browser/controller/textAreaState","vs/editor/browser/widget/diffNavigator","vs/editor/common/core/rgba","vs/editor/common/editorAction","vs/editor/common/model/textChange","vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase","vs/editor/common/standalone/standaloneBase","vs/editor/common/view/overviewZoneManager","vs/editor/common/viewModel/prefixSumComputer","vs/editor/browser/viewParts/margin/margin","vs/editor/contrib/comment/blockCommentCommand","vs/editor/contrib/folding/syntaxRangeProvider","vs/editor/contrib/format/formattingEdit","vs/editor/contrib/gotoSymbol/link/clickLinkGesture","vs/editor/contrib/hover/hoverOperation","vs/editor/contrib/hover/hoverTypes","vs/editor/contrib/indentation/indentUtils","vs/editor/contrib/inlineCompletions/ghostText","vs/editor/contrib/smartSelect/bracketSelections","vs/editor/contrib/suggest/resizable","vs/editor/standalone/common/monarch/monarchCommon","vs/base/browser/ui/findinput/findInputCheckboxes","vs/base/browser/ui/tree/objectTree","vs/editor/common/model/editStack","vs/platform/files/common/files","vs/platform/instantiation/common/descriptors","vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer","vs/editor/common/controller/cursorAtomicMoveOperations","vs/editor/common/controller/cursorMoveCommands","vs/editor/common/controller/cursor","vs/editor/common/modes/textToHtmlTokenizer","vs/editor/common/viewModel/minimapTokensColorTracker","vs/editor/contrib/documentSymbols/outlineModel","vs/editor/standalone/common/monarch/monarchLexer","vs/editor/common/services/getSemanticTokens","vs/editor/contrib/codelens/codelens","vs/editor/contrib/colorPicker/color","vs/platform/contextkey/common/contextkeys","vs/platform/keybinding/common/keybindingResolver","vs/editor/common/services/editorWorkerServiceImpl","vs/editor/common/services/semanticTokensProviderStyling","vs/editor/contrib/suggest/suggestWidgetDetails","vs/editor/browser/viewParts/lines/viewLine","vs/editor/browser/view/viewUserInputEvents","vs/editor/browser/viewParts/lineNumbers/lineNumbers","vs/editor/contrib/quickAccess/editorNavigationQuickAccess","vs/editor/contrib/symbolIcons/symbolIcons","vs/editor/standalone/browser/standaloneCodeServiceImpl","vs/editor/contrib/colorPicker/colorDetector","vs/editor/contrib/format/format","vs/editor/contrib/gotoSymbol/goToSymbol","vs/editor/contrib/inlineCompletions/inlineCompletionsModel","vs/editor/contrib/codeAction/codeActionCommands","vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode","vs/editor/contrib/wordOperations/wordOperations","vs/editor/browser/widget/diffEditorWidget","vs/editor/contrib/find/findController","vs/editor/contrib/gotoError/gotoError","vs/editor/common/services/modelServiceImpl","vs/editor/contrib/gotoSymbol/peek/referencesController","vs/editor/contrib/gotoSymbol/goToCommands","vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition","vs/editor/standalone/browser/standaloneServices","vs/editor/contrib/snippet/snippetSession","vs/editor/contrib/suggest/suggestController","vs/editor/contrib/inlineCompletions/ghostTextController","vs/editor/contrib/hover/hover","vs/base/browser/ui/list/list","vs/base/browser/ui/list/splice","vs/base/common/diff/diffChange","vs/base/common/navigator","vs/base/common/history","vs/base/common/process","vs/base/browser/ui/list/rangeMap","vs/base/browser/ui/scrollbar/scrollbarVisibilityController","vs/base/common/comparers","vs/base/browser/ui/tree/compressedObjectTreeModel","vs/base/common/search","vs/base/common/fuzzyScorer","vs/base/browser/ui/list/rowCache","vs/base/browser/ui/scrollbar/horizontalScrollbar","vs/base/browser/ui/scrollbar/verticalScrollbar","vs/base/browser/markdownRenderer","vs/base/common/uuid","vs/base/parts/storage/common/storage","vs/base/worker/defaultWorkerFactory","vs/css!vs/base/browser/ui/aria/aria","vs/css!vs/base/browser/ui/button/button","vs/base/browser/ui/button/button","vs/css!vs/base/browser/ui/checkbox/checkbox","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/hover","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/base/browser/ui/progressbar/progressbar","vs/css!vs/base/browser/ui/sash/sash","vs/css!vs/base/browser/ui/scrollbar/media/scrollbars","vs/base/browser/ui/hover/hoverWidget","vs/base/browser/ui/list/listPaging","vs/css!vs/base/browser/ui/splitview/splitview","vs/css!vs/base/browser/ui/table/table","vs/base/browser/ui/table/tableWidget","vs/css!vs/base/browser/ui/tree/media/tree","vs/css!vs/editor/browser/controller/textAreaHandler","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/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/widget/media/diffEditor","vs/css!vs/editor/browser/widget/media/diffReview","vs/css!vs/editor/browser/widget/media/editor","vs/css!vs/editor/contrib/anchorSelect/anchorSelect","vs/css!vs/editor/contrib/bracketMatching/bracketMatching","vs/css!vs/editor/contrib/codeAction/lightBulbWidget","vs/css!vs/editor/contrib/codelens/codelensWidget","vs/css!vs/editor/contrib/colorPicker/colorPicker","vs/css!vs/editor/contrib/dnd/dnd","vs/css!vs/editor/contrib/find/findWidget","vs/css!vs/editor/contrib/folding/folding","vs/css!vs/editor/contrib/gotoError/media/gotoErrorWidget","vs/css!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition","vs/css!vs/editor/contrib/gotoSymbol/peek/referencesWidget","vs/css!vs/editor/contrib/inlineCompletions/ghostText","vs/css!vs/editor/contrib/links/links","vs/css!vs/editor/contrib/message/messageController","vs/css!vs/editor/contrib/parameterHints/parameterHints","vs/css!vs/editor/contrib/peekView/media/peekViewWidget","vs/css!vs/editor/contrib/rename/renameInputField","vs/css!vs/editor/contrib/snippet/snippetSession","vs/css!vs/editor/contrib/suggest/media/suggest","vs/css!vs/editor/contrib/zoneWidget/zoneWidget","vs/css!vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp","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/contextview/browser/contextMenuHandler","vs/editor/browser/config/charWidthReader","vs/editor/browser/services/abstractCodeEditorService","vs/editor/browser/viewParts/minimap/minimapCharRenderer","vs/editor/browser/viewParts/minimap/minimapPreBaked","vs/editor/browser/viewParts/minimap/minimapCharRendererFactory","vs/editor/common/commands/trimTrailingWhitespaceCommand","vs/editor/common/commands/surroundSelectionCommand","vs/editor/common/diff/diffComputer","vs/editor/common/model/indentationGuesser","vs/editor/common/model/intervalTree","vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase","vs/editor/common/modes/abstractMode","vs/editor/common/modes/languageSelector","vs/editor/common/modes/linkComputer","vs/editor/common/modes/supports/characterPair","vs/editor/common/modes/supports/indentRules","vs/editor/common/modes/supports/inplaceReplaceSupport","vs/editor/common/modes/supports/onEnter","vs/editor/common/modes/supports/electricCharacter","vs/editor/common/modes/supports/tokenization","vs/editor/common/modes/tokenizationRegistry","vs/editor/common/services/semanticTokensDto","vs/editor/browser/viewParts/lines/rangeUtil","vs/editor/common/view/viewContext","vs/editor/common/viewLayout/linesLayout","vs/editor/common/viewLayout/viewLinesViewportData","vs/editor/common/model/mirrorTextModel","vs/editor/common/services/editorSimpleWorker","vs/editor/browser/viewParts/contentWidgets/contentWidgets","vs/editor/browser/viewParts/decorations/decorations","vs/editor/browser/viewParts/linesDecorations/linesDecorations","vs/editor/browser/viewParts/marginDecorations/marginDecorations","vs/editor/browser/viewParts/overlayWidgets/overlayWidgets","vs/editor/browser/viewParts/overviewRuler/overviewRuler","vs/editor/browser/viewParts/viewZones/viewZones","vs/editor/common/viewModel/monospaceLineBreaksComputer","vs/editor/common/viewLayout/viewLayout","vs/editor/contrib/caretOperations/moveCaretCommand","vs/editor/contrib/colorPicker/colorPickerModel","vs/editor/contrib/comment/lineCommentCommand","vs/editor/contrib/dnd/dragAndDropCommand","vs/editor/contrib/find/replaceAllCommand","vs/editor/contrib/find/replacePattern","vs/editor/contrib/folding/foldingModel","vs/editor/contrib/folding/hiddenRangeModel","vs/editor/contrib/folding/intializingRangeProvider","vs/editor/contrib/hover/hoverWidgets","vs/editor/contrib/inPlaceReplace/inPlaceReplaceCommand","vs/editor/contrib/inlineCompletions/utils","vs/editor/contrib/linesOperations/copyLinesCommand","vs/editor/contrib/linesOperations/sortLinesCommand","vs/editor/contrib/smartSelect/wordSelections","vs/editor/contrib/suggest/completionModel","vs/editor/contrib/suggest/suggestCommitCharacters","vs/editor/contrib/suggest/suggestOvertypingCapturer","vs/editor/contrib/suggest/wordDistance","vs/editor/standalone/common/monarch/monarchCompile","vs/nls!vs/base/browser/ui/actionbar/actionViewItems","vs/nls!vs/base/browser/ui/findinput/findInput","vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes","vs/nls!vs/base/browser/ui/findinput/replaceInput","vs/nls!vs/base/browser/ui/iconLabel/iconLabelHover","vs/base/browser/ui/iconLabel/iconLabelHover","vs/nls!vs/base/browser/ui/inputbox/inputBox","vs/nls!vs/base/browser/ui/keybindingLabel/keybindingLabel","vs/nls!vs/base/browser/ui/menu/menu","vs/nls!vs/base/browser/ui/tree/abstractTree","vs/base/browser/ui/tree/dataTree","vs/base/browser/ui/tree/asyncDataTree","vs/nls!vs/base/common/actions","vs/base/browser/ui/dropdown/dropdown","vs/base/browser/ui/dropdown/dropdownActionViewItem","vs/base/browser/ui/findinput/findInput","vs/base/browser/ui/findinput/replaceInput","vs/base/browser/ui/menu/menu","vs/base/parts/quickinput/browser/quickInputBox","vs/nls!vs/base/common/errorMessage","vs/base/common/errorMessage","vs/nls!vs/base/common/keybindingLabels","vs/base/browser/ui/keybindingLabel/keybindingLabel","vs/nls!vs/base/parts/quickinput/browser/quickInput","vs/nls!vs/base/parts/quickinput/browser/quickInputList","vs/base/parts/quickinput/browser/quickInputList","vs/base/parts/quickinput/browser/quickInput","vs/nls!vs/editor/browser/controller/coreCommands","vs/nls!vs/editor/browser/controller/textAreaHandler","vs/nls!vs/editor/browser/core/keybindingCancellation","vs/nls!vs/editor/browser/editorExtensions","vs/nls!vs/editor/browser/widget/codeEditorWidget","vs/nls!vs/editor/browser/widget/diffEditorWidget","vs/nls!vs/editor/browser/widget/diffReview","vs/nls!vs/editor/browser/widget/inlineDiffMargin","vs/editor/browser/widget/inlineDiffMargin","vs/nls!vs/editor/common/config/commonEditorConfig","vs/nls!vs/editor/common/config/editorOptions","vs/editor/common/viewModel/viewModelDecorations","vs/nls!vs/editor/common/editorContextKeys","vs/nls!vs/editor/common/model/editStack","vs/nls!vs/editor/common/modes/modesRegistry","vs/nls!vs/editor/common/standaloneStrings","vs/nls!vs/editor/common/view/editorColorRegistry","vs/nls!vs/editor/contrib/anchorSelect/anchorSelect","vs/nls!vs/editor/contrib/bracketMatching/bracketMatching","vs/nls!vs/editor/contrib/caretOperations/caretOperations","vs/nls!vs/editor/contrib/caretOperations/transpose","vs/nls!vs/editor/contrib/clipboard/clipboard","vs/nls!vs/editor/contrib/codeAction/codeActionCommands","vs/nls!vs/editor/contrib/codeAction/lightBulbWidget","vs/nls!vs/editor/contrib/codelens/codelensController","vs/nls!vs/editor/contrib/comment/comment","vs/nls!vs/editor/contrib/contextmenu/contextmenu","vs/nls!vs/editor/contrib/cursorUndo/cursorUndo","vs/nls!vs/editor/contrib/find/findController","vs/nls!vs/editor/contrib/find/findWidget","vs/nls!vs/editor/contrib/folding/folding","vs/nls!vs/editor/contrib/folding/foldingDecorations","vs/nls!vs/editor/contrib/fontZoom/fontZoom","vs/nls!vs/editor/contrib/format/format","vs/nls!vs/editor/contrib/format/formatActions","vs/nls!vs/editor/contrib/gotoError/gotoError","vs/nls!vs/editor/contrib/gotoError/gotoErrorWidget","vs/nls!vs/editor/contrib/gotoSymbol/goToCommands","vs/nls!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition","vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesController","vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesTree","vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesWidget","vs/nls!vs/editor/contrib/gotoSymbol/referencesModel","vs/nls!vs/editor/contrib/gotoSymbol/symbolNavigation","vs/nls!vs/editor/contrib/hover/hover","vs/nls!vs/editor/contrib/hover/markdownHoverParticipant","vs/nls!vs/editor/contrib/hover/markerHoverParticipant","vs/nls!vs/editor/contrib/inPlaceReplace/inPlaceReplace","vs/nls!vs/editor/contrib/indentation/indentation","vs/nls!vs/editor/contrib/inlineCompletions/ghostTextController","vs/nls!vs/editor/contrib/inlineCompletions/inlineCompletionsHoverParticipant","vs/nls!vs/editor/contrib/linesOperations/linesOperations","vs/nls!vs/editor/contrib/linkedEditing/linkedEditing","vs/nls!vs/editor/contrib/links/links","vs/nls!vs/editor/contrib/message/messageController","vs/nls!vs/editor/contrib/multicursor/multicursor","vs/nls!vs/editor/contrib/parameterHints/parameterHints","vs/nls!vs/editor/contrib/parameterHints/parameterHintsWidget","vs/nls!vs/editor/contrib/peekView/peekView","vs/nls!vs/editor/contrib/quickAccess/gotoLineQuickAccess","vs/nls!vs/editor/contrib/quickAccess/gotoSymbolQuickAccess","vs/nls!vs/editor/contrib/rename/rename","vs/nls!vs/editor/contrib/rename/renameInputField","vs/nls!vs/editor/contrib/smartSelect/smartSelect","vs/nls!vs/editor/contrib/snippet/snippetController2","vs/nls!vs/editor/contrib/snippet/snippetVariables","vs/nls!vs/editor/contrib/suggest/suggest","vs/nls!vs/editor/contrib/suggest/suggestController","vs/nls!vs/editor/contrib/suggest/suggestWidget","vs/nls!vs/editor/contrib/suggest/suggestWidgetDetails","vs/nls!vs/editor/contrib/suggest/suggestWidgetRenderer","vs/nls!vs/editor/contrib/suggest/suggestWidgetStatus","vs/nls!vs/editor/contrib/symbolIcons/symbolIcons","vs/nls!vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode","vs/nls!vs/editor/contrib/tokenization/tokenization","vs/nls!vs/editor/contrib/unusualLineTerminators/unusualLineTerminators","vs/nls!vs/editor/contrib/wordHighlighter/wordHighlighter","vs/nls!vs/editor/contrib/wordOperations/wordOperations","vs/nls!vs/platform/actions/browser/menuEntryActionViewItem","vs/nls!vs/platform/configuration/common/configurationRegistry","vs/nls!vs/platform/contextkey/browser/contextKeyService","vs/nls!vs/platform/contextkey/common/contextkeys","vs/nls!vs/platform/keybinding/common/abstractKeybindingService","vs/nls!vs/platform/list/browser/listService","vs/nls!vs/platform/markers/common/markers","vs/nls!vs/platform/quickinput/browser/commandsQuickAccess","vs/nls!vs/platform/quickinput/browser/helpQuickAccess","vs/nls!vs/platform/theme/common/colorRegistry","vs/nls!vs/platform/theme/common/iconRegistry","vs/nls!vs/platform/undoRedo/common/undoRedoService","vs/platform/clipboard/browser/clipboardService","vs/platform/editor/common/editor","vs/platform/extensions/common/extensions","vs/platform/instantiation/common/graph","vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder","vs/editor/common/model/textModelTokens","vs/editor/common/controller/cursorColumnSelection","vs/editor/common/controller/oneCursor","vs/editor/common/controller/cursorCollection","vs/editor/common/viewModel/splitLinesCollection","vs/editor/common/viewModel/viewModelImpl","vs/editor/contrib/folding/indentRangeProvider","vs/editor/contrib/linesOperations/moveLinesCommand","vs/editor/contrib/zoneWidget/zoneWidget","vs/editor/standalone/browser/colorizer","vs/editor/contrib/documentSymbols/documentSymbols","vs/editor/contrib/links/getLinks","vs/editor/contrib/parameterHints/parameterHintsModel","vs/editor/contrib/suggest/suggestAlternatives","vs/editor/contrib/suggest/wordContextKey","vs/platform/instantiation/common/instantiationService","vs/platform/keybinding/common/abstractKeybindingService","vs/platform/keybinding/common/baseResolvedKeybinding","vs/platform/keybinding/common/resolvedKeybindingItem","vs/platform/keybinding/common/usLayoutResolvedKeybinding","vs/platform/contextview/browser/contextViewService","vs/editor/common/services/webWorker","vs/editor/contrib/gotoError/markerNavigationService","vs/platform/markers/common/markerService","vs/editor/browser/services/openerService","vs/editor/contrib/hover/modesGlyphHover","vs/platform/quickinput/browser/pickerQuickAccess","vs/editor/common/services/getIconClasses","vs/editor/browser/view/domLineBreaksComputer","vs/editor/browser/view/viewOverlays","vs/editor/browser/viewParts/viewCursors/viewCursor","vs/editor/common/services/languagesRegistry","vs/editor/common/services/modeServiceImpl","vs/platform/accessibility/common/accessibilityService","vs/platform/configuration/common/configurationModels","vs/platform/contextkey/browser/contextKeyService","vs/platform/browser/contextScopedHistoryWidget","vs/platform/quickinput/browser/helpQuickAccess","vs/editor/standalone/browser/quickAccess/standaloneHelpQuickAccess","vs/platform/quickinput/browser/quickAccess","vs/editor/contrib/codelens/codeLensCache","vs/editor/contrib/suggest/suggestMemory","vs/platform/quickinput/browser/commandsQuickAccess","vs/editor/contrib/quickAccess/commandsQuickAccess","vs/platform/contextview/browser/contextMenuHandler","vs/editor/browser/controller/mouseHandler","vs/editor/browser/controller/pointerHandler","vs/editor/browser/viewParts/lines/viewLines","vs/editor/browser/services/codeEditorServiceImpl","vs/editor/browser/viewParts/editorScrollbar/editorScrollbar","vs/editor/browser/viewParts/minimap/minimap","vs/editor/browser/viewParts/scrollDecoration/scrollDecoration","vs/editor/browser/viewParts/selections/selections","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/rulers/rulers","vs/editor/browser/viewParts/viewCursors/viewCursors","vs/editor/common/services/markerDecorationsServiceImpl","vs/editor/contrib/codeAction/lightBulbWidget","vs/editor/contrib/codelens/codelensWidget","vs/editor/contrib/colorPicker/colorPickerWidget","vs/editor/contrib/find/findDecorations","vs/editor/contrib/find/findOptionsWidget","vs/editor/contrib/find/findState","vs/editor/contrib/gotoSymbol/peek/referencesTree","vs/editor/contrib/inlineCompletions/ghostTextWidget","vs/editor/contrib/quickAccess/gotoLineQuickAccess","vs/editor/contrib/quickAccess/gotoSymbolQuickAccess","vs/editor/contrib/rename/renameInputField","vs/editor/standalone/common/themes","vs/editor/browser/core/keybindingCancellation","vs/editor/browser/services/markerDecorations","vs/editor/browser/view/viewController","vs/editor/browser/view/viewImpl","vs/editor/contrib/anchorSelect/anchorSelect","vs/editor/contrib/bracketMatching/bracketMatching","vs/editor/contrib/caretOperations/caretOperations","vs/editor/contrib/caretOperations/transpose","vs/editor/contrib/clipboard/clipboard","vs/editor/contrib/codeAction/codeActionMenu","vs/editor/contrib/codeAction/codeActionModel","vs/editor/contrib/codelens/codelensController","vs/editor/contrib/comment/comment","vs/editor/contrib/contextmenu/contextmenu","vs/editor/contrib/cursorUndo/cursorUndo","vs/editor/contrib/dnd/dnd","vs/editor/contrib/fontZoom/fontZoom","vs/editor/contrib/format/formatActions","vs/editor/contrib/gotoSymbol/symbolNavigation","vs/editor/contrib/hover/colorHoverParticipant","vs/editor/contrib/hover/getHover","vs/editor/contrib/hover/markdownHoverParticipant","vs/editor/contrib/inPlaceReplace/inPlaceReplace","vs/editor/contrib/indentation/indentation","vs/editor/contrib/inlayHints/inlayHintsController","vs/editor/contrib/linesOperations/linesOperations","vs/editor/contrib/linkedEditing/linkedEditing","vs/editor/contrib/links/links","vs/editor/contrib/codeAction/codeActionUi","vs/editor/contrib/codeAction/codeActionContributions","vs/editor/contrib/rename/rename","vs/editor/contrib/smartSelect/smartSelect","vs/editor/contrib/tokenization/tokenization","vs/editor/contrib/unusualLineTerminators/unusualLineTerminators","vs/editor/contrib/wordHighlighter/wordHighlighter","vs/editor/contrib/wordPartOperations/wordPartOperations","vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp","vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard","vs/editor/standalone/browser/inspectTokens/inspectTokens","vs/editor/standalone/browser/quickAccess/standaloneCommandsQuickAccess","vs/editor/standalone/browser/quickAccess/standaloneGotoLineQuickAccess","vs/editor/standalone/browser/quickAccess/standaloneGotoSymbolQuickAccess","vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast","vs/editor/contrib/suggest/suggestWidgetStatus","vs/platform/actions/common/menuService","vs/platform/contextview/browser/contextMenuService","vs/platform/quickinput/browser/quickInput","vs/editor/standalone/browser/quickInput/standaloneQuickInputServiceImpl","vs/platform/severityIcon/common/severityIcon","vs/editor/contrib/gotoError/gotoErrorWidget","vs/editor/browser/widget/diffReview","vs/editor/contrib/find/findWidget","vs/editor/contrib/folding/foldingDecorations","vs/editor/contrib/folding/folding","vs/editor/contrib/hover/markerHoverParticipant","vs/editor/contrib/multicursor/multicursor","vs/editor/contrib/parameterHints/parameterHintsWidget","vs/editor/contrib/parameterHints/parameterHints","vs/editor/contrib/suggest/suggestWidgetRenderer","vs/editor/contrib/suggest/suggestWidget","vs/platform/theme/browser/iconsStyleSheet","vs/editor/standalone/browser/standaloneThemeServiceImpl","vs/editor/contrib/gotoSymbol/peek/referencesWidget","vs/editor/contrib/viewportSemanticTokens/viewportSemanticTokens","vs/editor/standalone/browser/referenceSearch/standaloneReferenceSearch","vs/platform/undoRedo/common/undoRedoService","vs/editor/standalone/browser/standaloneCodeEditor","vs/editor/standalone/browser/standaloneEditor","vs/editor/standalone/browser/standaloneLanguages","vs/editor/editor.api","vs/platform/workspaces/common/workspaces","vs/editor/contrib/snippet/snippetVariables","vs/editor/contrib/suggest/suggestModel","vs/editor/contrib/inlineCompletions/suggestWidgetAdapterModel","vs/editor/contrib/inlineCompletions/ghostTextModel","vs/editor/contrib/inlineCompletions/inlineCompletionsHoverParticipant","vs/editor/contrib/hover/modesContentHover","vs/editor/contrib/colorPicker/colorContributions","vs/editor/editor.all","vs/base/common/marked/marked","vs/base/common/insane/insane","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.
*--------------------------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
* Please make sure to make edits in the .ts file at https://github.com/microsoft/vscode-loader/
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*--------------------------------------------------------------------------------------------*/
'use strict';
var CSSLoaderPlugin;
(function (CSSLoaderPlugin) {
/**
* Known issue:
* - In IE there is no way to know if the CSS file loaded successfully or not.
*/
var BrowserCSSLoader = /** @class */ (function () {
function BrowserCSSLoader() {
this._pendingLoads = 0;
}
BrowserCSSLoader.prototype.attachListeners = function (name, linkNode, callback, errorback) {
var unbind = function () {
linkNode.removeEventListener('load', loadEventListener);
linkNode.removeEventListener('error', errorEventListener);
};
var loadEventListener = function (e) {
unbind();
callback();
};
var errorEventListener = function (e) {
unbind();
errorback(e);
};
linkNode.addEventListener('load', loadEventListener);
linkNode.addEventListener('error', errorEventListener);
};
BrowserCSSLoader.prototype._onLoad = function (name, callback) {
this._pendingLoads--;
callback();
};
BrowserCSSLoader.prototype._onLoadError = function (name, errorback, err) {
this._pendingLoads--;
errorback(err);
};
BrowserCSSLoader.prototype._insertLinkNode = function (linkNode) {
this._pendingLoads++;
var head = document.head || document.getElementsByTagName('head')[0];
var other = head.getElementsByTagName('link') || head.getElementsByTagName('script');
if (other.length > 0) {
head.insertBefore(linkNode, other[other.length - 1]);
}
else {
head.appendChild(linkNode);
}
};
BrowserCSSLoader.prototype.createLinkTag = function (name, cssUrl, externalCallback, externalErrorback) {
var _this = this;
var linkNode = document.createElement('link');
linkNode.setAttribute('rel', 'stylesheet');
linkNode.setAttribute('type', 'text/css');
linkNode.setAttribute('data-name', name);
var callback = function () { return _this._onLoad(name, externalCallback); };
var errorback = function (err) { return _this._onLoadError(name, externalErrorback, err); };
this.attachListeners(name, linkNode, callback, errorback);
linkNode.setAttribute('href', cssUrl);
return linkNode;
};
BrowserCSSLoader.prototype._linkTagExists = function (name, cssUrl) {
var i, len, nameAttr, hrefAttr, links = document.getElementsByTagName('link');
for (i = 0, len = links.length; i < len; i++) {
nameAttr = links[i].getAttribute('data-name');
hrefAttr = links[i].getAttribute('href');
if (nameAttr === name || hrefAttr === cssUrl) {
return true;
}
}
return false;
};
BrowserCSSLoader.prototype.load = function (name, cssUrl, externalCallback, externalErrorback) {
if (this._linkTagExists(name, cssUrl)) {
externalCallback();
return;
}
var linkNode = this.createLinkTag(name, cssUrl, externalCallback, externalErrorback);
this._insertLinkNode(linkNode);
};
return BrowserCSSLoader;
}());
// ------------------------------ Finally, the plugin
var CSSPlugin = /** @class */ (function () {
function CSSPlugin() {
this._cssLoader = new BrowserCSSLoader();
}
CSSPlugin.prototype.load = function (name, req, load, config) {
config = config || {};
var cssConfig = config['vs/css'] || {};
if (cssConfig.disabled) {
// the plugin is asked to not create any style sheets
load({});
return;
}
var cssUrl = req.toUrl(name + '.css');
this._cssLoader.load(name, cssUrl, function (contents) {
load({});
}, function (err) {
if (typeof load.error === 'function') {
load.error('Could not find ' + cssUrl + ' or it was empty');
}
});
};
return CSSPlugin;
}());
CSSLoaderPlugin.CSSPlugin = CSSPlugin;
define('vs/css', new CSSPlugin());
})(CSSLoaderPlugin || (CSSLoaderPlugin = {}));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
* Please make sure to make edits in the .ts file at https://github.com/microsoft/vscode-loader/
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*--------------------------------------------------------------------------------------------*/
'use strict';
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
var NLSLoaderPlugin;
(function (NLSLoaderPlugin) {
var Environment = /** @class */ (function () {
function Environment() {
this._detected = false;
this._isPseudo = false;
}
Object.defineProperty(Environment.prototype, "isPseudo", {
get: function () {
this._detect();
return this._isPseudo;
},
enumerable: true,
configurable: true
});
Environment.prototype._detect = function () {
if (this._detected) {
return;
}
this._detected = true;
this._isPseudo = (typeof document !== 'undefined' && document.location && document.location.hash.indexOf('pseudo=true') >= 0);
};
return Environment;
}());
function _format(message, args, env) {
var result;
if (args.length === 0) {
result = message;
}
else {
result = message.replace(/\{(\d+)\}/g, function (match, rest) {
var index = rest[0];
var arg = args[index];
var 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 (env.isPseudo) {
// FF3B and FF3D is the Unicode zenkaku representation for [ and ]
result = '\uFF3B' + result.replace(/[aouei]/g, '$&$&') + '\uFF3D';
}
return result;
}
function findLanguageForModule(config, name) {
var result = config[name];
if (result)
return result;
result = config['*'];
if (result)
return result;
return null;
}
function localize(env, data, message) {
var args = [];
for (var _i = 3; _i < arguments.length; _i++) {
args[_i - 3] = arguments[_i];
}
return _format(message, args, env);
}
function createScopedLocalize(scope, env) {
return function (idx, defaultValue) {
var restArgs = Array.prototype.slice.call(arguments, 2);
return _format(scope[idx], restArgs, env);
};
}
var NLSPlugin = /** @class */ (function () {
function NLSPlugin(env) {
var _this = this;
this._env = env;
this.localize = function (data, message) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
return localize.apply(void 0, __spreadArrays([_this._env, data, message], args));
};
}
NLSPlugin.prototype.setPseudoTranslation = function (value) {
this._env._isPseudo = value;
};
NLSPlugin.prototype.create = function (key, data) {
return {
localize: createScopedLocalize(data[key], this._env)
};
};
NLSPlugin.prototype.load = function (name, req, load, config) {
var _this = this;
config = config || {};
if (!name || name.length === 0) {
load({
localize: this.localize
});
}
else {
var pluginConfig = config['vs/nls'] || {};
var language = pluginConfig.availableLanguages ? findLanguageForModule(pluginConfig.availableLanguages, name) : null;
var suffix = '.nls';
if (language !== null && language !== NLSPlugin.DEFAULT_TAG) {
suffix = suffix + '.' + language;
}
var messagesLoaded_1 = function (messages) {
if (Array.isArray(messages)) {
messages.localize = createScopedLocalize(messages, _this._env);
}
else {
messages.localize = createScopedLocalize(messages[name], _this._env);
}
load(messages);
};
if (typeof pluginConfig.loadBundle === 'function') {
pluginConfig.loadBundle(name, language, function (err, messages) {
// We have an error. Load the English default strings to not fail
if (err) {
req([name + '.nls'], messagesLoaded_1);
}
else {
messagesLoaded_1(messages);
}
});
}
else {
req([name + suffix], messagesLoaded_1);
}
}
};
NLSPlugin.DEFAULT_TAG = 'i-default';
return NLSPlugin;
}());
NLSLoaderPlugin.NLSPlugin = NLSPlugin;
define('vs/nls', new NLSPlugin(new Environment()));
})(NLSLoaderPlugin || (NLSLoaderPlugin = {}));
/*---------------------------------------------------------------------------------------------
* 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/browser/fastDomNode*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createFastDomNode = exports.FastDomNode = void 0;
class FastDomNode {
constructor(domNode) {
this.domNode = domNode;
this._maxWidth = -1;
this._width = -1;
this._height = -1;
this._top = -1;
this._left = -1;
this._bottom = -1;
this._right = -1;
this._fontFamily = '';
this._fontWeight = '';
this._fontSize = -1;
this._fontFeatureSettings = '';
this._lineHeight = -1;
this._letterSpacing = -100;
this._className = '';
this._display = '';
this._position = '';
this._visibility = '';
this._backgroundColor = '';
this._layerHint = false;
this._contain = 'none';
this._boxShadow = '';
}
setMaxWidth(maxWidth) {
if (this._maxWidth === maxWidth) {
return;
}
this._maxWidth = maxWidth;
this.domNode.style.maxWidth = this._maxWidth + 'px';
}
setWidth(width) {
if (this._width === width) {
return;
}
this._width = width;
this.domNode.style.width = this._width + 'px';
}
setHeight(height) {
if (this._height === height) {
return;
}
this._height = height;
this.domNode.style.height = this._height + 'px';
}
setTop(top) {
if (this._top === top) {
return;
}
this._top = top;
this.domNode.style.top = this._top + 'px';
}
unsetTop() {
if (this._top === -1) {
return;
}
this._top = -1;
this.domNode.style.top = '';
}
setLeft(left) {
if (this._left === left) {
return;
}
this._left = left;
this.domNode.style.left = this._left + 'px';
}
setBottom(bottom) {
if (this._bottom === bottom) {
return;
}
this._bottom = bottom;
this.domNode.style.bottom = this._bottom + 'px';
}
setRight(right) {
if (this._right === right) {
return;
}
this._right = right;
this.domNode.style.right = this._right + 'px';
}
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) {
if (this._fontSize === fontSize) {
return;
}
this._fontSize = fontSize;
this.domNode.style.fontSize = this._fontSize + 'px';
}
setFontFeatureSettings(fontFeatureSettings) {
if (this._fontFeatureSettings === fontFeatureSettings) {
return;
}
this._fontFeatureSettings = fontFeatureSettings;
this.domNode.style.fontFeatureSettings = this._fontFeatureSettings;
}
setLineHeight(lineHeight) {
if (this._lineHeight === lineHeight) {
return;
}
this._lineHeight = lineHeight;
this.domNode.style.lineHeight = this._lineHeight + 'px';
}
setLetterSpacing(letterSpacing) {
if (this._letterSpacing === letterSpacing) {
return;
}
this._letterSpacing = letterSpacing;
this.domNode.style.letterSpacing = this._letterSpacing + 'px';
}
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;
}
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 createFastDomNode(domNode) {
return new FastDomNode(domNode);
}
exports.createFastDomNode = createFastDomNode;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[196/*vs/base/browser/iframe*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IframeUtils = void 0;
let hasDifferentOriginAncestorFlag = false;
let sameOriginWindowChainCache = null;
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 {
let location = w.location;
let parentLocation = w.parent.location;
if (location.origin !== 'null' && parentLocation.origin !== 'null') {
if (location.protocol !== parentLocation.protocol || location.hostname !== parentLocation.hostname || location.port !== parentLocation.port) {
hasDifferentOriginAncestorFlag = true;
return null;
}
}
}
catch (e) {
hasDifferentOriginAncestorFlag = true;
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.
* To distinguish if at one point the current execution environment is running inside a window with a different origin, see hasDifferentOriginAncestor()
*/
static getSameOriginWindowChain() {
if (!sameOriginWindowChainCache) {
sameOriginWindowChainCache = [];
let w = window;
let parent;
do {
parent = getParentWindowIfSameOrigin(w);
if (parent) {
sameOriginWindowChainCache.push({
window: w,
iframeElement: w.frameElement || null
});
}
else {
sameOriginWindowChainCache.push({
window: w,
iframeElement: null
});
}
w = parent;
} while (w);
}
return sameOriginWindowChainCache.slice(0);
}
/**
* Returns true if the current execution environment is chained in a list of iframes which at one point ends in a window with a different origin.
* Returns false if the current execution environment is not running inside an iframe or if the entire chain of iframes have the same origin.
*/
static hasDifferentOriginAncestor() {
if (!sameOriginWindowChainCache) {
this.getSameOriginWindowChain();
}
return hasDifferentOriginAncestorFlag;
}
/**
* 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;
let windowChain = this.getSameOriginWindowChain();
for (const windowChainEl of windowChain) {
top += windowChainEl.window.scrollY;
left += windowChainEl.window.scrollX;
if (windowChainEl.window === ancestorWindow) {
break;
}
if (!windowChainEl.iframeElement) {
break;
}
let 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[283/*vs/base/browser/ui/list/list*/], __M([0/*require*/,1/*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[284/*vs/base/browser/ui/list/splice*/], __M([0/*require*/,1/*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[197/*vs/base/browser/ui/scrollbar/scrollbarState*/], __M([0/*require*/,1/*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[101/*vs/base/browser/ui/tree/tree*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WeakMapper = exports.TreeError = exports.TreeMouseEventTarget = void 0;
var TreeMouseEventTarget;
(function (TreeMouseEventTarget) {
TreeMouseEventTarget[TreeMouseEventTarget["Unknown"] = 0] = "Unknown";
TreeMouseEventTarget[TreeMouseEventTarget["Twistie"] = 1] = "Twistie";
TreeMouseEventTarget[TreeMouseEventTarget["Element"] = 2] = "Element";
})(TreeMouseEventTarget = exports.TreeMouseEventTarget || (exports.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;
});
define(__m[19/*vs/base/common/arrays*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ArrayQueue = exports.splice = exports.insertInto = exports.asArray = exports.pushToEnd = exports.pushToStart = exports.arrayInsert = exports.range = exports.flatten = exports.firstOrDefault = exports.distinctES6 = exports.distinct = exports.isNonEmptyArray = exports.isFalsyOrEmpty = exports.coalesce = exports.groupBy = exports.quickSelect = exports.findFirstInSorted = exports.binarySearch = exports.equals = exports.tail2 = exports.tail = void 0;
/**
* 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)];
}
exports.tail = tail;
function tail2(arr) {
if (arr.length === 0) {
throw new Error('Invalid tail call');
}
return [arr.slice(0, arr.length - 1), arr[arr.length - 1]];
}
exports.tail2 = tail2;
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;
}
exports.equals = equals;
function binarySearch(array, key, comparator) {
let low = 0, high = array.length - 1;
while (low <= high) {
const mid = ((low + high) / 2) | 0;
const comp = comparator(array[mid], key);
if (comp < 0) {
low = mid + 1;
}
else if (comp > 0) {
high = mid - 1;
}
else {
return mid;
}
}
return -(low + 1);
}
exports.binarySearch = binarySearch;
/**
* Takes a sorted array and a function p. The array is sorted in such a way that all elements where p(x) is false
* are located before all elements where p(x) is true.
* @returns the least x for which p(x) is true or array.length if no element fullfills the given function.
*/
function findFirstInSorted(array, p) {
let low = 0, high = array.length;
if (high === 0) {
return 0; // no children
}
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (p(array[mid])) {
high = mid;
}
else {
low = mid + 1;
}
}
return low;
}
exports.findFirstInSorted = findFirstInSorted;
function quickSelect(nth, data, compare) {
nth = nth | 0;
if (nth >= data.length) {
throw new TypeError('invalid index');
}
let pivotValue = data[Math.floor(data.length * Math.random())];
let lower = [];
let higher = [];
let pivots = [];
for (let 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);
}
}
exports.quickSelect = quickSelect;
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;
}
exports.groupBy = groupBy;
/**
* @returns New array with all falsy values removed. The original array IS NOT modified.
*/
function coalesce(array) {
return array.filter(e => !!e);
}
exports.coalesce = coalesce;
/**
* @returns false if the provided object is an array and not empty.
*/
function isFalsyOrEmpty(obj) {
return !Array.isArray(obj) || obj.length === 0;
}
exports.isFalsyOrEmpty = isFalsyOrEmpty;
function isNonEmptyArray(obj) {
return Array.isArray(obj) && obj.length > 0;
}
exports.isNonEmptyArray = isNonEmptyArray;
/**
* Removes duplicates from the given array. The optional keyFn allows to specify
* how elements are checked for equalness by returning a unique string for each.
*/
function distinct(array, keyFn) {
if (!keyFn) {
return array.filter((element, position) => {
return array.indexOf(element) === position;
});
}
const seen = Object.create(null);
return array.filter((elem) => {
const key = keyFn(elem);
if (seen[key]) {
return false;
}
seen[key] = true;
return true;
});
}
exports.distinct = distinct;
function distinctES6(array) {
const seen = new Set();
return array.filter(element => {
if (seen.has(element)) {
return false;
}
seen.add(element);
return true;
});
}
exports.distinctES6 = distinctES6;
function firstOrDefault(array, notFoundValue) {
return array.length > 0 ? array[0] : notFoundValue;
}
exports.firstOrDefault = firstOrDefault;
function flatten(arr) {
return [].concat(...arr);
}
exports.flatten = flatten;
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;
}
exports.range = range;
/**
* 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);
}
exports.arrayInsert = arrayInsert;
/**
* 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);
}
}
exports.pushToStart = pushToStart;
/**
* 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);
}
}
exports.pushToEnd = pushToEnd;
function asArray(x) {
return Array.isArray(x) ? x : [x];
}
exports.asArray = asArray;
/**
* 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];
}
}
exports.insertInto = insertInto;
/**
* 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);
const result = array.splice(index, deleteCount);
insertInto(array, index, newItems);
return result;
}
exports.splice = splice;
/**
* 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);
}
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;
}
/**
* 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;
}
}
exports.ArrayQueue = ArrayQueue;
});
/*---------------------------------------------------------------------------------------------
* 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/base/common/assert*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ok = void 0;
/**
* Throws an error with the provided message if the provided value does not evaluate to a true Javascript value.
*/
function ok(value, message) {
if (!value) {
throw new Error(message ? `Assertion failed (${message})` : 'Assertion Failed');
}
}
exports.ok = ok;
});
/*---------------------------------------------------------------------------------------------
* 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/base/common/collections*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SetMap = exports.forEach = void 0;
const hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Iterates over each entry in the provided dictionary. The iterator allows
* to remove elements and will stop when the callback returns {{false}}.
*/
function forEach(from, callback) {
for (let key in from) {
if (hasOwnProperty.call(from, key)) {
const result = callback({ key: key, value: from[key] }, function () {
delete from[key];
});
if (result === false) {
return;
}
}
}
}
exports.forEach = forEach;
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);
}
}
exports.SetMap = SetMap;
});
/*---------------------------------------------------------------------------------------------
* 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/base/common/color*/], __M([0/*require*/,1/*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 {
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');
}
}
static fromHex(hex) {
return Color.Format.CSS.parseHex(hex) || Color.red;
}
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);
}
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));
}
toString() {
return '' + Color.Format.CSS.format(this);
}
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);
}
}
exports.Color = Color;
Color.white = new Color(new RGBA(255, 255, 255, 1));
Color.black = new Color(new RGBA(0, 0, 0, 1));
Color.red = new Color(new RGBA(255, 0, 0, 1));
Color.blue = new Color(new RGBA(0, 0, 255, 1));
Color.cyan = new Color(new RGBA(0, 255, 255, 1));
Color.lightgrey = new Color(new RGBA(211, 211, 211, 1));
Color.transparent = new Color(new RGBA(0, 0, 0, 0));
(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 /* 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 /* Digit0 */: return 0;
case 49 /* Digit1 */: return 1;
case 50 /* Digit2 */: return 2;
case 51 /* Digit3 */: return 3;
case 52 /* Digit4 */: return 4;
case 53 /* Digit5 */: return 5;
case 54 /* Digit6 */: return 6;
case 55 /* Digit7 */: return 7;
case 56 /* Digit8 */: return 8;
case 57 /* Digit9 */: return 9;
case 97 /* a */: return 10;
case 65 /* A */: return 10;
case 98 /* b */: return 11;
case 66 /* B */: return 11;
case 99 /* c */: return 12;
case 67 /* C */: return 12;
case 100 /* d */: return 13;
case 68 /* D */: return 13;
case 101 /* e */: return 14;
case 69 /* E */: return 14;
case 102 /* f */: return 15;
case 70 /* F */: return 15;
}
return 0;
}
})(CSS = Format.CSS || (Format.CSS = {}));
})(Format = Color.Format || (Color.Format = {}));
})(Color = exports.Color || (exports.Color = {}));
});
define(__m[90/*vs/base/common/decorators*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.memoize = void 0;
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];
};
}
exports.memoize = memoize;
});
/*---------------------------------------------------------------------------------------------
* 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/base/common/diff/diffChange*/], __M([0/*require*/,1/*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;
});
define(__m[12/*vs/base/common/errors*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.illegalState = exports.illegalArgument = exports.canceled = exports.isPromiseCanceledError = exports.transformErrorForSerialization = exports.onUnexpectedExternalError = exports.onUnexpectedError = exports.errorHandler = exports.ErrorHandler = void 0;
// 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) {
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 (!isPromiseCanceledError(e)) {
exports.errorHandler.onUnexpectedError(e);
}
return undefined;
}
exports.onUnexpectedError = onUnexpectedError;
function onUnexpectedExternalError(e) {
// ignore errors from cancelled promises
if (!isPromiseCanceledError(e)) {
exports.errorHandler.onUnexpectedExternalError(e);
}
return undefined;
}
exports.onUnexpectedExternalError = onUnexpectedExternalError;
function transformErrorForSerialization(error) {
if (error instanceof Error) {
let { name, message } = error;
const stack = error.stacktrace || error.stack;
return {
$isError: true,
name,
message,
stack
};
}
// return as is
return error;
}
exports.transformErrorForSerialization = transformErrorForSerialization;
const canceledName = 'Canceled';
/**
* Checks if the given error is a promise in canceled state
*/
function isPromiseCanceledError(error) {
return error instanceof Error && error.name === canceledName && error.message === canceledName;
}
exports.isPromiseCanceledError = isPromiseCanceledError;
/**
* Returns an error that signals cancellation.
*/
function canceled() {
const error = new Error(canceledName);
error.name = error.message;
return error;
}
exports.canceled = canceled;
function illegalArgument(name) {
if (name) {
return new Error(`Illegal argument: ${name}`);
}
else {
return new Error('Illegal argument');
}
}
exports.illegalArgument = illegalArgument;
function illegalState(name) {
if (name) {
return new Error(`Illegal state: ${name}`);
}
else {
return new Error('Illegal state');
}
}
exports.illegalState = illegalState;
});
/*---------------------------------------------------------------------------------------------
* 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/base/common/functional*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.once = void 0;
function once(fn) {
const _this = this;
let didCall = false;
let result;
return function () {
if (didCall) {
return result;
}
didCall = true;
result = fn.apply(_this, arguments);
return result;
};
}
exports.once = once;
});
/*---------------------------------------------------------------------------------------------
* 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/base/common/idGenerator*/], __M([0/*require*/,1/*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#');
});
/*
The MIT License (MIT)
Copyright © 2015 Nicolas Bevacqua
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
let __insane_func;
(function () { function r(e, n, t) { function o(i, f) { if (!n[i]) { if (!e[i]) { var c = "function" == typeof require && require; if (!f && c) return c(i, !0); if (u) return u(i, !0); var a = new Error("Cannot find module '" + i + "'"); throw a.code = "MODULE_NOT_FOUND", a } var p = n[i] = { exports: {} }; e[i][0].call(p.exports, function (r) { var n = e[i][1][r]; return o(n || r) }, p, p.exports, r, e, n, t) } return n[i].exports } for (var u = "function" == typeof require && require, i = 0; i < t.length; i++)o(t[i]); return o } return r })()({
1: [function (require, module, exports) {
'use strict';
var toMap = require('./toMap');
var uris = ['background', 'base', 'cite', 'href', 'longdesc', 'src', 'usemap'];
module.exports = {
uris: toMap(uris) // attributes that have an href and hence need to be sanitized
};
}, { "./toMap": 10 }], 2: [function (require, module, exports) {
'use strict';
var defaults = {
allowedAttributes: {
'*': ['title', 'accesskey'],
a: ['href', 'name', 'target', 'aria-label'],
iframe: ['allowfullscreen', 'frameborder', 'src'],
img: ['src', 'alt', 'title', 'aria-label']
},
allowedClasses: {},
allowedSchemes: ['http', 'https', 'mailto'],
allowedTags: [
'a', 'abbr', 'article', 'b', 'blockquote', 'br', 'caption', 'code', 'del', 'details', 'div', 'em',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'main', 'mark',
'ol', 'p', 'pre', 'section', 'span', 'strike', 'strong', 'sub', 'summary', 'sup', 'table',
'tbody', 'td', 'th', 'thead', 'tr', 'u', 'ul'
],
filter: null
};
module.exports = defaults;
}, {}], 3: [function (require, module, exports) {
'use strict';
var toMap = require('./toMap');
var voids = ['area', 'br', 'col', 'hr', 'img', 'wbr', 'input', 'base', 'basefont', 'link', 'meta'];
module.exports = {
voids: toMap(voids)
};
}, { "./toMap": 10 }], 4: [function (require, module, exports) {
'use strict';
var he = require('he');
var assign = require('assignment');
var parser = require('./parser');
var sanitizer = require('./sanitizer');
var defaults = require('./defaults');
function insane(html, options, strict) {
var buffer = [];
var configuration = strict === true ? options : assign({}, defaults, options);
var handler = sanitizer(buffer, configuration);
parser(html, handler);
return buffer.join('');
}
insane.defaults = defaults;
module.exports = insane;
__insane_func = insane;
}, { "./defaults": 2, "./parser": 7, "./sanitizer": 8, "assignment": 6, "he": 9 }], 5: [function (require, module, exports) {
'use strict';
module.exports = function lowercase(string) {
return typeof string === 'string' ? string.toLowerCase() : string;
};
}, {}], 6: [function (require, module, exports) {
'use strict';
function assignment(result) {
var stack = Array.prototype.slice.call(arguments, 1);
var item;
var key;
while (stack.length) {
item = stack.shift();
for (key in item) {
if (item.hasOwnProperty(key)) {
if (Object.prototype.toString.call(result[key]) === '[object Object]') {
result[key] = assignment(result[key], item[key]);
} else {
result[key] = item[key];
}
}
}
}
return result;
}
module.exports = assignment;
}, {}], 7: [function (require, module, exports) {
'use strict';
var he = require('he');
var lowercase = require('./lowercase');
var attributes = require('./attributes');
var elements = require('./elements');
var rstart = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/;
var rend = /^<\s*\/\s*([\w:-]+)[^>]*>/;
var rattrs = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g;
var rtag = /^</;
var rtagend = /^<\s*\//;
function createStack() {
var stack = [];
stack.lastItem = function lastItem() {
return stack[stack.length - 1];
};
return stack;
}
function parser(html, handler) {
var stack = createStack();
var last = html;
var chars;
while (html) {
parsePart();
}
parseEndTag(); // clean up any remaining tags
function parsePart() {
chars = true;
parseTag();
var same = html === last;
last = html;
if (same) { // discard, because it's invalid
html = '';
}
}
function parseTag() {
if (html.substr(0, 4) === '<!--') { // comments
parseComment();
} else if (rtagend.test(html)) {
parseEdge(rend, parseEndTag);
} else if (rtag.test(html)) {
parseEdge(rstart, parseStartTag);
}
parseTagDecode();
}
function parseEdge(regex, parser) {
var match = html.match(regex);
if (match) {
html = html.substring(match[0].length);
match[0].replace(regex, parser);
chars = false;
}
}
function parseComment() {
var index = html.indexOf('-->');
if (index >= 0) {
if (handler.comment) {
handler.comment(html.substring(4, index));
}
html = html.substring(index + 3);
chars = false;
}
}
function parseTagDecode() {
if (!chars) {
return;
}
var text;
var index = html.indexOf('<');
if (index >= 0) {
text = html.substring(0, index);
html = html.substring(index);
} else {
text = html;
html = '';
}
if (handler.chars) {
handler.chars(text);
}
}
function parseStartTag(tag, tagName, rest, unary) {
var attrs = {};
var low = lowercase(tagName);
var u = elements.voids[low] || !!unary;
rest.replace(rattrs, attrReplacer);
if (!u) {
stack.push(low);
}
if (handler.start) {
handler.start(low, attrs, u);
}
function attrReplacer(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) {
if (doubleQuotedValue === void 0 && singleQuotedValue === void 0 && unquotedValue === void 0) {
attrs[name] = void 0; // attribute is like <button disabled></button>
} else {
attrs[name] = he.decode(doubleQuotedValue || singleQuotedValue || unquotedValue || '');
}
}
}
function parseEndTag(tag, tagName) {
var i;
var pos = 0;
var low = lowercase(tagName);
if (low) {
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos] === low) {
break; // find the closest opened tag of the same type
}
}
}
if (pos >= 0) {
for (i = stack.length - 1; i >= pos; i--) {
if (handler.end) { // close all the open elements, up the stack
handler.end(stack[i]);
}
}
stack.length = pos;
}
}
}
module.exports = parser;
}, { "./attributes": 1, "./elements": 3, "./lowercase": 5, "he": 9 }], 8: [function (require, module, exports) {
'use strict';
var he = require('he');
var lowercase = require('./lowercase');
var attributes = require('./attributes');
var elements = require('./elements');
function sanitizer(buffer, options) {
var last;
var context;
var o = options || {};
reset();
return {
start: start,
end: end,
chars: chars
};
function out(value) {
buffer.push(value);
}
function start(tag, attrs, unary) {
var low = lowercase(tag);
if (context.ignoring) {
ignore(low); return;
}
if ((o.allowedTags || []).indexOf(low) === -1) {
ignore(low); return;
}
if (o.filter && !o.filter({ tag: low, attrs: attrs })) {
ignore(low); return;
}
out('<');
out(low);
Object.keys(attrs).forEach(parse);
out(unary ? '/>' : '>');
function parse(key) {
var value = attrs[key];
var classesOk = (o.allowedClasses || {})[low] || [];
var attrsOk = (o.allowedAttributes || {})[low] || [];
attrsOk = attrsOk.concat((o.allowedAttributes || {})['*'] || []);
var valid;
var lkey = lowercase(key);
if (lkey === 'class' && attrsOk.indexOf(lkey) === -1) {
value = value.split(' ').filter(isValidClass).join(' ').trim();
valid = value.length;
} else {
valid = attrsOk.indexOf(lkey) !== -1 && (attributes.uris[lkey] !== true || testUrl(value));
}
if (valid) {
out(' ');
out(key);
if (typeof value === 'string') {
out('="');
out(he.encode(value));
out('"');
}
}
function isValidClass(className) {
return classesOk && classesOk.indexOf(className) !== -1;
}
}
}
function end(tag) {
var low = lowercase(tag);
var allowed = (o.allowedTags || []).indexOf(low) !== -1;
if (allowed) {
if (context.ignoring === false) {
out('</');
out(low);
out('>');
} else {
unignore(low);
}
} else {
unignore(low);
}
}
function testUrl(text) {
var start = text[0];
if (start === '#' || start === '/') {
return true;
}
var colon = text.indexOf(':');
if (colon === -1) {
return true;
}
var questionmark = text.indexOf('?');
if (questionmark !== -1 && colon > questionmark) {
return true;
}
var hash = text.indexOf('#');
if (hash !== -1 && colon > hash) {
return true;
}
return o.allowedSchemes.some(matches);
function matches(scheme) {
return text.indexOf(scheme + ':') === 0;
}
}
function chars(text) {
if (context.ignoring === false) {
out(o.transformText ? o.transformText(text) : text);
}
}
function ignore(tag) {
if (elements.voids[tag]) {
return;
}
if (context.ignoring === false) {
context = { ignoring: tag, depth: 1 };
} else if (context.ignoring === tag) {
context.depth++;
}
}
function unignore(tag) {
if (context.ignoring === tag) {
if (--context.depth <= 0) {
reset();
}
}
}
function reset() {
context = { ignoring: false, depth: 0 };
}
}
module.exports = sanitizer;
}, { "./attributes": 1, "./elements": 3, "./lowercase": 5, "he": 9 }], 9: [function (require, module, exports) {
'use strict';
var escapes = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
};
var unescapes = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': "'"
};
var rescaped = /(&amp;|&lt;|&gt;|&quot;|&#39;)/g;
var runescaped = /[&<>"']/g;
function escapeHtmlChar(match) {
return escapes[match];
}
function unescapeHtmlChar(match) {
return unescapes[match];
}
function escapeHtml(text) {
return text == null ? '' : String(text).replace(runescaped, escapeHtmlChar);
}
function unescapeHtml(html) {
return html == null ? '' : String(html).replace(rescaped, unescapeHtmlChar);
}
escapeHtml.options = unescapeHtml.options = {};
module.exports = {
encode: escapeHtml,
escape: escapeHtml,
decode: unescapeHtml,
unescape: unescapeHtml,
version: '1.0.0-browser'
};
}, {}], 10: [function (require, module, exports) {
'use strict';
function toMap(list) {
return list.reduce(asKey, {});
}
function asKey(accumulator, item) {
accumulator[item] = true;
return accumulator;
}
module.exports = toMap;
}, {}]
}, {}, [4]);
// ESM-comment-begin
define("vs/base/common/insane/insane", function() { return { insane: __insane_func }; });
// ESM-comment-end
// ESM-uncomment-begin
// export var insane = __insane_func;
// 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[54/*vs/base/common/iterator*/], __M([0/*require*/,1/*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 from(iterable) {
return iterable || _empty;
}
Iterable.from = from;
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) {
for (const element of iterable) {
if (predicate(element)) {
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* concat(...iterables) {
for (const iterable of iterables) {
for (const element of iterable) {
yield element;
}
}
}
Iterable.concat = concat;
function* concatNested(iterables) {
for (const iterable of iterables) {
for (const element of iterable) {
yield element;
}
}
}
Iterable.concatNested = concatNested;
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;
/**
* Returns whether the iterables are the same length and all items are
* equal using the comparator function.
*/
function equals(a, b, comparator = (at, bt) => at === bt) {
const ai = a[Symbol.iterator]();
const bi = b[Symbol.iterator]();
while (true) {
const an = ai.next();
const bn = bi.next();
if (an.done !== bn.done) {
return false;
}
else if (an.done) {
return true;
}
else if (!comparator(an.value, bn.value)) {
return false;
}
}
}
Iterable.equals = equals;
})(Iterable = exports.Iterable || (exports.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[41/*vs/base/common/keyCodes*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/]), function (require, exports, errors_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResolvedKeybinding = exports.ResolvedKeybindingPart = exports.ChordKeybinding = exports.SimpleKeybinding = exports.createSimpleKeybinding = exports.createKeybinding = exports.KeyChord = exports.KeyCodeUtils = void 0;
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 /* Unknown */;
}
}
const uiMap = new KeyCodeStrMap();
const userSettingsUSMap = new KeyCodeStrMap();
const userSettingsGeneralMap = new KeyCodeStrMap();
(function () {
function define(keyCode, uiLabel, usUserSettingsLabel = uiLabel, generalUserSettingsLabel = usUserSettingsLabel) {
uiMap.define(keyCode, uiLabel);
userSettingsUSMap.define(keyCode, usUserSettingsLabel);
userSettingsGeneralMap.define(keyCode, generalUserSettingsLabel);
}
define(0 /* Unknown */, 'unknown');
define(1 /* Backspace */, 'Backspace');
define(2 /* Tab */, 'Tab');
define(3 /* Enter */, 'Enter');
define(4 /* Shift */, 'Shift');
define(5 /* Ctrl */, 'Ctrl');
define(6 /* Alt */, 'Alt');
define(7 /* PauseBreak */, 'PauseBreak');
define(8 /* CapsLock */, 'CapsLock');
define(9 /* Escape */, 'Escape');
define(10 /* Space */, 'Space');
define(11 /* PageUp */, 'PageUp');
define(12 /* PageDown */, 'PageDown');
define(13 /* End */, 'End');
define(14 /* Home */, 'Home');
define(15 /* LeftArrow */, 'LeftArrow', 'Left');
define(16 /* UpArrow */, 'UpArrow', 'Up');
define(17 /* RightArrow */, 'RightArrow', 'Right');
define(18 /* DownArrow */, 'DownArrow', 'Down');
define(19 /* Insert */, 'Insert');
define(20 /* Delete */, 'Delete');
define(21 /* KEY_0 */, '0');
define(22 /* KEY_1 */, '1');
define(23 /* KEY_2 */, '2');
define(24 /* KEY_3 */, '3');
define(25 /* KEY_4 */, '4');
define(26 /* KEY_5 */, '5');
define(27 /* KEY_6 */, '6');
define(28 /* KEY_7 */, '7');
define(29 /* KEY_8 */, '8');
define(30 /* KEY_9 */, '9');
define(31 /* KEY_A */, 'A');
define(32 /* KEY_B */, 'B');
define(33 /* KEY_C */, 'C');
define(34 /* KEY_D */, 'D');
define(35 /* KEY_E */, 'E');
define(36 /* KEY_F */, 'F');
define(37 /* KEY_G */, 'G');
define(38 /* KEY_H */, 'H');
define(39 /* KEY_I */, 'I');
define(40 /* KEY_J */, 'J');
define(41 /* KEY_K */, 'K');
define(42 /* KEY_L */, 'L');
define(43 /* KEY_M */, 'M');
define(44 /* KEY_N */, 'N');
define(45 /* KEY_O */, 'O');
define(46 /* KEY_P */, 'P');
define(47 /* KEY_Q */, 'Q');
define(48 /* KEY_R */, 'R');
define(49 /* KEY_S */, 'S');
define(50 /* KEY_T */, 'T');
define(51 /* KEY_U */, 'U');
define(52 /* KEY_V */, 'V');
define(53 /* KEY_W */, 'W');
define(54 /* KEY_X */, 'X');
define(55 /* KEY_Y */, 'Y');
define(56 /* KEY_Z */, 'Z');
define(57 /* Meta */, 'Meta');
define(58 /* ContextMenu */, 'ContextMenu');
define(59 /* F1 */, 'F1');
define(60 /* F2 */, 'F2');
define(61 /* F3 */, 'F3');
define(62 /* F4 */, 'F4');
define(63 /* F5 */, 'F5');
define(64 /* F6 */, 'F6');
define(65 /* F7 */, 'F7');
define(66 /* F8 */, 'F8');
define(67 /* F9 */, 'F9');
define(68 /* F10 */, 'F10');
define(69 /* F11 */, 'F11');
define(70 /* F12 */, 'F12');
define(71 /* F13 */, 'F13');
define(72 /* F14 */, 'F14');
define(73 /* F15 */, 'F15');
define(74 /* F16 */, 'F16');
define(75 /* F17 */, 'F17');
define(76 /* F18 */, 'F18');
define(77 /* F19 */, 'F19');
define(78 /* NumLock */, 'NumLock');
define(79 /* ScrollLock */, 'ScrollLock');
define(80 /* US_SEMICOLON */, ';', ';', 'OEM_1');
define(81 /* US_EQUAL */, '=', '=', 'OEM_PLUS');
define(82 /* US_COMMA */, ',', ',', 'OEM_COMMA');
define(83 /* US_MINUS */, '-', '-', 'OEM_MINUS');
define(84 /* US_DOT */, '.', '.', 'OEM_PERIOD');
define(85 /* US_SLASH */, '/', '/', 'OEM_2');
define(86 /* US_BACKTICK */, '`', '`', 'OEM_3');
define(110 /* ABNT_C1 */, 'ABNT_C1');
define(111 /* ABNT_C2 */, 'ABNT_C2');
define(87 /* US_OPEN_SQUARE_BRACKET */, '[', '[', 'OEM_4');
define(88 /* US_BACKSLASH */, '\\', '\\', 'OEM_5');
define(89 /* US_CLOSE_SQUARE_BRACKET */, ']', ']', 'OEM_6');
define(90 /* US_QUOTE */, '\'', '\'', 'OEM_7');
define(91 /* OEM_8 */, 'OEM_8');
define(92 /* OEM_102 */, 'OEM_102');
define(93 /* NUMPAD_0 */, 'NumPad0');
define(94 /* NUMPAD_1 */, 'NumPad1');
define(95 /* NUMPAD_2 */, 'NumPad2');
define(96 /* NUMPAD_3 */, 'NumPad3');
define(97 /* NUMPAD_4 */, 'NumPad4');
define(98 /* NUMPAD_5 */, 'NumPad5');
define(99 /* NUMPAD_6 */, 'NumPad6');
define(100 /* NUMPAD_7 */, 'NumPad7');
define(101 /* NUMPAD_8 */, 'NumPad8');
define(102 /* NUMPAD_9 */, 'NumPad9');
define(103 /* NUMPAD_MULTIPLY */, 'NumPad_Multiply');
define(104 /* NUMPAD_ADD */, 'NumPad_Add');
define(105 /* NUMPAD_SEPARATOR */, 'NumPad_Separator');
define(106 /* NUMPAD_SUBTRACT */, 'NumPad_Subtract');
define(107 /* NUMPAD_DECIMAL */, 'NumPad_Decimal');
define(108 /* NUMPAD_DIVIDE */, 'NumPad_Divide');
})();
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;
})(KeyCodeUtils = exports.KeyCodeUtils || (exports.KeyCodeUtils = {}));
function KeyChord(firstPart, secondPart) {
const chordPart = ((secondPart & 0x0000FFFF) << 16) >>> 0;
return (firstPart | chordPart) >>> 0;
}
exports.KeyChord = KeyChord;
function createKeybinding(keybinding, OS) {
if (keybinding === 0) {
return null;
}
const firstPart = (keybinding & 0x0000FFFF) >>> 0;
const chordPart = (keybinding & 0xFFFF0000) >>> 16;
if (chordPart !== 0) {
return new ChordKeybinding([
createSimpleKeybinding(firstPart, OS),
createSimpleKeybinding(chordPart, OS)
]);
}
return new ChordKeybinding([createSimpleKeybinding(firstPart, OS)]);
}
exports.createKeybinding = createKeybinding;
function createSimpleKeybinding(keybinding, OS) {
const ctrlCmd = (keybinding & 2048 /* CtrlCmd */ ? true : false);
const winCtrl = (keybinding & 256 /* WinCtrl */ ? true : false);
const ctrlKey = (OS === 2 /* Macintosh */ ? winCtrl : ctrlCmd);
const shiftKey = (keybinding & 1024 /* Shift */ ? true : false);
const altKey = (keybinding & 512 /* Alt */ ? true : false);
const metaKey = (OS === 2 /* Macintosh */ ? ctrlCmd : winCtrl);
const keyCode = (keybinding & 255 /* KeyCode */);
return new SimpleKeybinding(ctrlKey, shiftKey, altKey, metaKey, keyCode);
}
exports.createSimpleKeybinding = createSimpleKeybinding;
class SimpleKeybinding {
constructor(ctrlKey, shiftKey, altKey, metaKey, keyCode) {
this.ctrlKey = ctrlKey;
this.shiftKey = shiftKey;
this.altKey = altKey;
this.metaKey = metaKey;
this.keyCode = keyCode;
}
equals(other) {
return (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 /* Unknown */
|| this.keyCode === 5 /* Ctrl */
|| this.keyCode === 57 /* Meta */
|| this.keyCode === 6 /* Alt */
|| this.keyCode === 4 /* Shift */);
}
toChord() {
return new ChordKeybinding([this]);
}
/**
* 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 /* Ctrl */)
|| (this.shiftKey && this.keyCode === 4 /* Shift */)
|| (this.altKey && this.keyCode === 6 /* Alt */)
|| (this.metaKey && this.keyCode === 57 /* Meta */));
}
}
exports.SimpleKeybinding = SimpleKeybinding;
class ChordKeybinding {
constructor(parts) {
if (parts.length === 0) {
throw (0, errors_1.illegalArgument)(`parts`);
}
this.parts = parts;
}
}
exports.ChordKeybinding = ChordKeybinding;
class ResolvedKeybindingPart {
constructor(ctrlKey, shiftKey, altKey, metaKey, kbLabel, kbAriaLabel) {
this.ctrlKey = ctrlKey;
this.shiftKey = shiftKey;
this.altKey = altKey;
this.metaKey = metaKey;
this.keyLabel = kbLabel;
this.keyAriaLabel = kbAriaLabel;
}
}
exports.ResolvedKeybindingPart = ResolvedKeybindingPart;
/**
* A resolved keybinding. Can be a simple keybinding or a chord keybinding.
*/
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[155/*vs/base/common/lazy*/], __M([0/*require*/,1/*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
*/
getValue() {
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[2/*vs/base/common/lifecycle*/], __M([0/*require*/,1/*exports*/,80/*vs/base/common/functional*/,54/*vs/base/common/iterator*/]), function (require, exports, functional_1, iterator_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImmortalReference = exports.MutableDisposable = exports.Disposable = exports.DisposableStore = exports.toDisposable = exports.combinedDisposable = exports.dispose = exports.isDisposable = exports.MultiDisposeError = exports.markAsSingleton = exports.setDisposableTracker = void 0;
/**
* 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;
}
exports.setDisposableTracker = setDisposableTracker;
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 (_a) {
// noop
}
}
}
markAsDisposed(disposable) {
if (disposable && disposable !== Disposable.None) {
try {
disposable[__is_disposable_tracked__] = true;
}
catch (_a) {
// noop
}
}
}
markAsSingleton(disposable) { }
});
}
function trackDisposable(x) {
disposableTracker === null || disposableTracker === void 0 ? void 0 : disposableTracker.trackDisposable(x);
return x;
}
function markAsDisposed(disposable) {
disposableTracker === null || disposableTracker === void 0 ? void 0 : disposableTracker.markAsDisposed(disposable);
}
function setParentOfDisposable(child, parent) {
disposableTracker === null || disposableTracker === void 0 ? void 0 : 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 === null || disposableTracker === void 0 ? void 0 : disposableTracker.markAsSingleton(singleton);
return singleton;
}
exports.markAsSingleton = markAsSingleton;
class MultiDisposeError extends Error {
constructor(errors) {
super(`Encountered errors while disposing of store. Errors: [${errors.join(', ')}]`);
this.errors = errors;
}
}
exports.MultiDisposeError = MultiDisposeError;
function isDisposable(thing) {
return typeof thing.dispose === 'function' && thing.dispose.length === 0;
}
exports.isDisposable = isDisposable;
function dispose(arg) {
if (iterator_1.Iterable.is(arg)) {
let 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 MultiDisposeError(errors);
}
return Array.isArray(arg) ? [] : arg;
}
else if (arg) {
arg.dispose();
return arg;
}
}
exports.dispose = dispose;
function combinedDisposable(...disposables) {
const parent = toDisposable(() => dispose(disposables));
setParentOfDisposables(disposables, parent);
return parent;
}
exports.combinedDisposable = combinedDisposable;
function toDisposable(fn) {
const self = trackDisposable({
dispose: (0, functional_1.once)(() => {
markAsDisposed(self);
fn();
})
});
return self;
}
exports.toDisposable = toDisposable;
class DisposableStore {
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();
}
/**
* Dispose of all registered disposables but do not mark this object as disposed.
*/
clear() {
try {
dispose(this._toDispose.values());
}
finally {
this._toDispose.clear();
}
}
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;
}
}
exports.DisposableStore = DisposableStore;
DisposableStore.DISABLE_DISPOSED_WARNING = false;
class Disposable {
constructor() {
this._store = new DisposableStore();
trackDisposable(this);
setParentOfDisposable(this._store, this);
}
dispose() {
markAsDisposed(this);
this._store.dispose();
}
_register(o) {
if (o === this) {
throw new Error('Cannot register a disposable on itself!');
}
return this._store.add(o);
}
}
exports.Disposable = Disposable;
Disposable.None = Object.freeze({ dispose() { } });
/**
* 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) {
var _a;
if (this._isDisposed || value === this._value) {
return;
}
(_a = this._value) === null || _a === void 0 ? void 0 : _a.dispose();
if (value) {
setParentOfDisposable(value, this);
}
this._value = value;
}
clear() {
this.value = undefined;
}
dispose() {
var _a;
this._isDisposed = true;
markAsDisposed(this);
(_a = this._value) === null || _a === void 0 ? void 0 : _a.dispose();
this._value = undefined;
}
/**
* Clears the value, but does not dispose it.
* The old value is returned.
*/
clearAndLeak() {
const oldValue = this._value;
this._value = undefined;
if (oldValue) {
setParentOfDisposable(oldValue, null);
}
return oldValue;
}
}
exports.MutableDisposable = MutableDisposable;
class ImmortalReference {
constructor(object) {
this.object = object;
}
dispose() { }
}
exports.ImmortalReference = ImmortalReference;
});
/*---------------------------------------------------------------------------------------------
* 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/linkedList*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LinkedList = void 0;
class Node {
constructor(element) {
this.element = element;
this.next = Node.Undefined;
this.prev = Node.Undefined;
}
}
Node.Undefined = new 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;
});
/**
* marked - a markdown parser
* Copyright (c) 2011-2021, 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/
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define("vs/base/common/marked/marked", factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.marked = factory());
}(this, (function () { 'use strict';
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelperLoose(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
it = o[Symbol.iterator]();
return it.next.bind(it);
}
function createCommonjsModule(fn) {
var module = { exports: {} };
return fn(module, module.exports), module.exports;
}
var defaults = createCommonjsModule(function (module) {
function getDefaults() {
return {
baseUrl: null,
breaks: false,
gfm: true,
headerIds: true,
headerPrefix: '',
highlight: null,
langPrefix: 'language-',
mangle: true,
pedantic: false,
renderer: null,
sanitize: false,
sanitizer: null,
silent: false,
smartLists: false,
smartypants: false,
tokenizer: null,
walkTokens: null,
xhtml: false
};
}
function changeDefaults(newDefaults) {
module.exports.defaults = newDefaults;
}
module.exports = {
defaults: getDefaults(),
getDefaults: getDefaults,
changeDefaults: changeDefaults
};
});
/**
* Helpers
*/
var escapeTest = /[&<>"']/;
var escapeReplace = /[&<>"']/g;
var escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/;
var escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g;
var escapeReplacements = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
};
var getEscapeReplacement = function getEscapeReplacement(ch) {
return escapeReplacements[ch];
};
function escape(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;
}
var unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;
function unescape(html) {
// explicitly match decimal, hex, and named HTML entities
return html.replace(unescapeTest, function (_, n) {
n = n.toLowerCase();
if (n === 'colon') return ':';
if (n.charAt(0) === '#') {
return n.charAt(1) === 'x' ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1));
}
return '';
});
}
var caret = /(^|[^\[])\^/g;
function edit(regex, opt) {
regex = regex.source || regex;
opt = opt || '';
var obj = {
replace: function replace(name, val) {
val = val.source || val;
val = val.replace(caret, '$1');
regex = regex.replace(name, val);
return obj;
},
getRegex: function getRegex() {
return new RegExp(regex, opt);
}
};
return obj;
}
var nonWordAndColonTest = /[^\w:]/g;
var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;
function cleanUrl(sanitize, base, href) {
if (sanitize) {
var prot;
try {
prot = decodeURIComponent(unescape(href)).replace(nonWordAndColonTest, '').toLowerCase();
} catch (e) {
return null;
}
if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
return null;
}
}
if (base && !originIndependentUrl.test(href)) {
href = resolveUrl(base, href);
}
try {
href = encodeURI(href).replace(/%25/g, '%');
} catch (e) {
return null;
}
return href;
}
var baseUrls = {};
var justDomain = /^[^:]+:\/*[^/]*$/;
var protocol = /^([^:]+:)[\s\S]*$/;
var domain = /^([^:]+:\/*[^/]*)[\s\S]*$/;
function resolveUrl(base, href) {
if (!baseUrls[' ' + base]) {
// we can ignore everything in base after the last slash of its path component,
// but we might need to add _that_
// https://tools.ietf.org/html/rfc3986#section-3
if (justDomain.test(base)) {
baseUrls[' ' + base] = base + '/';
} else {
baseUrls[' ' + base] = rtrim(base, '/', true);
}
}
base = baseUrls[' ' + base];
var relativeBase = base.indexOf(':') === -1;
if (href.substring(0, 2) === '//') {
if (relativeBase) {
return href;
}
return base.replace(protocol, '$1') + href;
} else if (href.charAt(0) === '/') {
if (relativeBase) {
return href;
}
return base.replace(domain, '$1') + href;
} else {
return base + href;
}
}
var noopTest = {
exec: function noopTest() {}
};
function merge(obj) {
var i = 1,
target,
key;
for (; i < arguments.length; i++) {
target = arguments[i];
for (key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
obj[key] = target[key];
}
}
}
return obj;
}
function splitCells(tableRow, count) {
// ensure that every cell-delimiting pipe has a space
// before it to distinguish it from an escaped pipe
var row = tableRow.replace(/\|/g, function (match, offset, str) {
var escaped = false,
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(/ \|/);
var i = 0;
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.
// invert: Remove suffix of non-c chars instead. Default falsey.
function rtrim(str, c, invert) {
var l = str.length;
if (l === 0) {
return '';
} // Length of suffix matching the invert condition.
var suffLen = 0; // Step left until we fail to match the invert condition.
while (suffLen < l) {
var currChar = str.charAt(l - suffLen - 1);
if (currChar === c && !invert) {
suffLen++;
} else if (currChar !== c && invert) {
suffLen++;
} else {
break;
}
}
return str.substr(0, l - suffLen);
}
function findClosingBracket(str, b) {
if (str.indexOf(b[1]) === -1) {
return -1;
}
var l = str.length;
var level = 0,
i = 0;
for (; i < l; 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 checkSanitizeDeprecation(opt) {
if (opt && opt.sanitize && !opt.silent) {
console.warn('marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options');
}
} // copied from https://stackoverflow.com/a/5450113/806777
function repeatString(pattern, count) {
if (count < 1) {
return '';
}
var result = '';
while (count > 1) {
if (count & 1) {
result += pattern;
}
count >>= 1;
pattern += pattern;
}
return result + pattern;
}
var helpers = {
escape: escape,
unescape: unescape,
edit: edit,
cleanUrl: cleanUrl,
resolveUrl: resolveUrl,
noopTest: noopTest,
merge: merge,
splitCells: splitCells,
rtrim: rtrim,
findClosingBracket: findClosingBracket,
checkSanitizeDeprecation: checkSanitizeDeprecation,
repeatString: repeatString
};
var defaults$1 = defaults.defaults;
var rtrim$1 = helpers.rtrim,
splitCells$1 = helpers.splitCells,
_escape = helpers.escape,
findClosingBracket$1 = helpers.findClosingBracket;
function outputLink(cap, link, raw) {
var href = link.href;
var title = link.title ? _escape(link.title) : null;
var text = cap[1].replace(/\\([\[\]])/g, '$1');
if (cap[0].charAt(0) !== '!') {
return {
type: 'link',
raw: raw,
href: href,
title: title,
text: text
};
} else {
return {
type: 'image',
raw: raw,
href: href,
title: title,
text: _escape(text)
};
}
}
function indentCodeCompensation(raw, text) {
var matchIndentToCode = raw.match(/^(\s+)(?:```)/);
if (matchIndentToCode === null) {
return text;
}
var indentToCode = matchIndentToCode[1];
return text.split('\n').map(function (node) {
var matchIndentInNode = node.match(/^\s+/);
if (matchIndentInNode === null) {
return node;
}
var indentInNode = matchIndentInNode[0];
if (indentInNode.length >= indentToCode.length) {
return node.slice(indentToCode.length);
}
return node;
}).join('\n');
}
/**
* Tokenizer
*/
var Tokenizer_1 = /*#__PURE__*/function () {
function Tokenizer(options) {
this.options = options || defaults$1;
}
var _proto = Tokenizer.prototype;
_proto.space = function space(src) {
var cap = this.rules.block.newline.exec(src);
if (cap) {
if (cap[0].length > 1) {
return {
type: 'space',
raw: cap[0]
};
}
return {
raw: '\n'
};
}
};
_proto.code = function code(src) {
var cap = this.rules.block.code.exec(src);
if (cap) {
var text = cap[0].replace(/^ {1,4}/gm, '');
return {
type: 'code',
raw: cap[0],
codeBlockStyle: 'indented',
text: !this.options.pedantic ? rtrim$1(text, '\n') : text
};
}
};
_proto.fences = function fences(src) {
var cap = this.rules.block.fences.exec(src);
if (cap) {
var raw = cap[0];
var text = indentCodeCompensation(raw, cap[3] || '');
return {
type: 'code',
raw: raw,
lang: cap[2] ? cap[2].trim() : cap[2],
text: text
};
}
};
_proto.heading = function heading(src) {
var cap = this.rules.block.heading.exec(src);
if (cap) {
var text = cap[2].trim(); // remove trailing #s
if (/#$/.test(text)) {
var trimmed = rtrim$1(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: text
};
}
};
_proto.nptable = function nptable(src) {
var cap = this.rules.block.nptable.exec(src);
if (cap) {
var item = {
type: 'table',
header: splitCells$1(cap[1].replace(/^ *| *\| *$/g, '')),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : [],
raw: cap[0]
};
if (item.header.length === item.align.length) {
var l = item.align.length;
var i;
for (i = 0; i < l; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
l = item.cells.length;
for (i = 0; i < l; i++) {
item.cells[i] = splitCells$1(item.cells[i], item.header.length);
}
return item;
}
}
};
_proto.hr = function hr(src) {
var cap = this.rules.block.hr.exec(src);
if (cap) {
return {
type: 'hr',
raw: cap[0]
};
}
};
_proto.blockquote = function blockquote(src) {
var cap = this.rules.block.blockquote.exec(src);
if (cap) {
var text = cap[0].replace(/^ *> ?/gm, '');
return {
type: 'blockquote',
raw: cap[0],
text: text
};
}
};
_proto.list = function list(src) {
var cap = this.rules.block.list.exec(src);
if (cap) {
var raw = cap[0];
var bull = cap[2];
var isordered = bull.length > 1;
var list = {
type: 'list',
raw: raw,
ordered: isordered,
start: isordered ? +bull.slice(0, -1) : '',
loose: false,
items: []
}; // Get each top-level item.
var itemMatch = cap[0].match(this.rules.block.item);
var next = false,
item,
space,
bcurr,
bnext,
addBack,
loose,
istask,
ischecked;
var l = itemMatch.length;
bcurr = this.rules.block.listItemStart.exec(itemMatch[0]);
for (var i = 0; i < l; i++) {
item = itemMatch[i];
raw = item; // Determine whether the next list item belongs here.
// Backpedal if it does not belong in this list.
if (i !== l - 1) {
bnext = this.rules.block.listItemStart.exec(itemMatch[i + 1]);
if (!this.options.pedantic ? bnext[1].length > bcurr[0].length || bnext[1].length > 3 : bnext[1].length > bcurr[1].length) {
// nested list
itemMatch.splice(i, 2, itemMatch[i] + '\n' + itemMatch[i + 1]);
i--;
l--;
continue;
} else {
if ( // different bullet style
!this.options.pedantic || this.options.smartLists ? bnext[2][bnext[2].length - 1] !== bull[bull.length - 1] : isordered === (bnext[2].length === 1)) {
addBack = itemMatch.slice(i + 1).join('\n');
list.raw = list.raw.substring(0, list.raw.length - addBack.length);
i = l - 1;
}
}
bcurr = bnext;
} // Remove the list item's bullet
// so it is seen as the next token.
space = item.length;
item = item.replace(/^ *([*+-]|\d+[.)]) ?/, ''); // Outdent whatever the
// list item contains. Hacky.
if (~item.indexOf('\n ')) {
space -= item.length;
item = !this.options.pedantic ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') : item.replace(/^ {1,4}/gm, '');
} // Determine whether item is loose or not.
// Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
// for discount behavior.
loose = next || /\n\n(?!\s*$)/.test(item);
if (i !== l - 1) {
next = item.charAt(item.length - 1) === '\n';
if (!loose) loose = next;
}
if (loose) {
list.loose = true;
} // Check for task list items
if (this.options.gfm) {
istask = /^\[[ xX]\] /.test(item);
ischecked = undefined;
if (istask) {
ischecked = item[1] !== ' ';
item = item.replace(/^\[[ xX]\] +/, '');
}
}
list.items.push({
type: 'list_item',
raw: raw,
task: istask,
checked: ischecked,
loose: loose,
text: item
});
}
return list;
}
};
_proto.html = function html(src) {
var cap = this.rules.block.html.exec(src);
if (cap) {
return {
type: this.options.sanitize ? 'paragraph' : 'html',
raw: cap[0],
pre: !this.options.sanitizer && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : _escape(cap[0]) : cap[0]
};
}
};
_proto.def = function def(src) {
var cap = this.rules.block.def.exec(src);
if (cap) {
if (cap[3]) cap[3] = cap[3].substring(1, cap[3].length - 1);
var tag = cap[1].toLowerCase().replace(/\s+/g, ' ');
return {
tag: tag,
raw: cap[0],
href: cap[2],
title: cap[3]
};
}
};
_proto.table = function table(src) {
var cap = this.rules.block.table.exec(src);
if (cap) {
var item = {
type: 'table',
header: splitCells$1(cap[1].replace(/^ *| *\| *$/g, '')),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : []
};
if (item.header.length === item.align.length) {
item.raw = cap[0];
var l = item.align.length;
var i;
for (i = 0; i < l; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
l = item.cells.length;
for (i = 0; i < l; i++) {
item.cells[i] = splitCells$1(item.cells[i].replace(/^ *\| *| *\| *$/g, ''), item.header.length);
}
return item;
}
}
};
_proto.lheading = function lheading(src) {
var 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]
};
}
};
_proto.paragraph = function paragraph(src) {
var cap = this.rules.block.paragraph.exec(src);
if (cap) {
return {
type: 'paragraph',
raw: cap[0],
text: cap[1].charAt(cap[1].length - 1) === '\n' ? cap[1].slice(0, -1) : cap[1]
};
}
};
_proto.text = function text(src) {
var cap = this.rules.block.text.exec(src);
if (cap) {
return {
type: 'text',
raw: cap[0],
text: cap[0]
};
}
};
_proto.escape = function escape(src) {
var cap = this.rules.inline.escape.exec(src);
if (cap) {
return {
type: 'escape',
raw: cap[0],
text: _escape(cap[1])
};
}
};
_proto.tag = function tag(src, inLink, inRawBlock) {
var cap = this.rules.inline.tag.exec(src);
if (cap) {
if (!inLink && /^<a /i.test(cap[0])) {
inLink = true;
} else if (inLink && /^<\/a>/i.test(cap[0])) {
inLink = false;
}
if (!inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
inRawBlock = true;
} else if (inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
inRawBlock = false;
}
return {
type: this.options.sanitize ? 'text' : 'html',
raw: cap[0],
inLink: inLink,
inRawBlock: inRawBlock,
text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : _escape(cap[0]) : cap[0]
};
}
};
_proto.link = function link(src) {
var cap = this.rules.inline.link.exec(src);
if (cap) {
var 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
var rtrimSlash = rtrim$1(trimmedUrl.slice(0, -1), '\\');
if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
return;
}
} else {
// find closing parenthesis
var lastParenIndex = findClosingBracket$1(cap[2], '()');
if (lastParenIndex > -1) {
var start = cap[0].indexOf('!') === 0 ? 5 : 4;
var linkLen = start + cap[1].length + lastParenIndex;
cap[2] = cap[2].substring(0, lastParenIndex);
cap[0] = cap[0].substring(0, linkLen).trim();
cap[3] = '';
}
}
var href = cap[2];
var title = '';
if (this.options.pedantic) {
// split pedantic href and title
var 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._escapes, '$1') : href,
title: title ? title.replace(this.rules.inline._escapes, '$1') : title
}, cap[0]);
}
};
_proto.reflink = function reflink(src, links) {
var cap;
if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {
var link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
link = links[link.toLowerCase()];
if (!link || !link.href) {
var text = cap[0].charAt(0);
return {
type: 'text',
raw: text,
text: text
};
}
return outputLink(cap, link, cap[0]);
}
};
_proto.emStrong = function emStrong(src, maskedSrc, prevChar) {
if (prevChar === void 0) {
prevChar = '';
}
var match = this.rules.inline.emStrong.lDelim.exec(src);
if (!match) return;
if (match[3] && prevChar.match(/(?:[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xBC-\xBE\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u0660-\u0669\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08C7\u0904-\u0939\u093D\u0950\u0958-\u0961\u0966-\u096F\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09F9\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AE6-\u0AEF\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F\u0B71-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0BE6-\u0BF2\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C78-\u0C7E\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D58-\u0D61\u0D66-\u0D78\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DE6-\u0DEF\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F20-\u0F33\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F-\u1049\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u1090-\u1099\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1369-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A20-\u1A54\u1A80-\u1A89\u1A90-\u1A99\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B50-\u1B59\u1B83-\u1BA0\u1BAE-\u1BE5\u1C00-\u1C23\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2150-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2CFD\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3192-\u3195\u31A0-\u31BF\u31F0-\u31FF\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\u3400-\u4DBF\u4E00-\u9FFC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7BF\uA7C2-\uA7CA\uA7F5-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA830-\uA835\uA840-\uA873\uA882-\uA8B3\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA900-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF-\uA9D9\uA9E0-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD07-\uDD33\uDD40-\uDD78\uDD8A\uDD8B\uDE80-\uDE9C\uDEA0-\uDED0\uDEE1-\uDEFB\uDF00-\uDF23\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC58-\uDC76\uDC79-\uDC9E\uDCA7-\uDCAF\uDCE0-\uDCF2\uDCF4\uDCF5\uDCFB-\uDD1B\uDD20-\uDD39\uDD80-\uDDB7\uDDBC-\uDDCF\uDDD2-\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE40-\uDE48\uDE60-\uDE7E\uDE80-\uDE9F\uDEC0-\uDEC7\uDEC9-\uDEE4\uDEEB-\uDEEF\uDF00-\uDF35\uDF40-\uDF55\uDF58-\uDF72\uDF78-\uDF91\uDFA9-\uDFAF]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDCFA-\uDD23\uDD30-\uDD39\uDE60-\uDE7E\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF27\uDF30-\uDF45\uDF51-\uDF54\uDFB0-\uDFCB\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC52-\uDC6F\uDC83-\uDCAF\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD03-\uDD26\uDD36-\uDD3F\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDD0-\uDDDA\uDDDC\uDDE1-\uDDF4\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDEF0-\uDEF9\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC50-\uDC59\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE50-\uDE59\uDE80-\uDEAA\uDEB8\uDEC0-\uDEC9\uDF00-\uDF1A\uDF30-\uDF3B]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCF2\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDD50-\uDD59\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC50-\uDC6C\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD50-\uDD59\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDDA0-\uDDA9\uDEE0-\uDEF2\uDFB0\uDFC0-\uDFD4]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF50-\uDF59\uDF5B-\uDF61\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE96\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82C[\uDC00-\uDD1E\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD834[\uDEE0-\uDEF3\uDF60-\uDF78]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD40-\uDD49\uDD4E\uDEC0-\uDEEB\uDEF0-\uDEF9]|\uD83A[\uDC00-\uDCC4\uDCC7-\uDCCF\uDD00-\uDD43\uDD4B\uDD50-\uDD59]|\uD83B[\uDC71-\uDCAB\uDCAD-\uDCAF\uDCB1-\uDCB4\uDD01-\uDD2D\uDD2F-\uDD3D\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD83C[\uDD00-\uDD0C]|\uD83E[\uDFF0-\uDFF9]|\uD869[\uDC00-\uDEDD\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])/)) return; // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well
var nextChar = match[1] || match[2] || '';
if (!nextChar || nextChar && (prevChar === '' || this.rules.inline.punctuation.exec(prevChar))) {
var lLength = match[0].length - 1;
var rDelim,
rLength,
delimTotal = lLength,
midDelimTotal = 0;
var endReg = match[0][0] === '*' ? this.rules.inline.emStrong.rDelimAst : this.rules.inline.emStrong.rDelimUnd;
endReg.lastIndex = 0;
maskedSrc = maskedSrc.slice(-1 * src.length + lLength); // Bump maskedSrc to same section of string as src (move to lexer?)
while ((match = endReg.exec(maskedSrc)) != null) {
rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];
if (!rDelim) continue; // matched the first alternative in rules.js (skip the * 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
// If this is the last rDelimiter, remove extra characters. *a*** -> *a*
if (delimTotal + midDelimTotal - rLength <= 0 && !maskedSrc.slice(endReg.lastIndex).match(endReg)) {
rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
}
if (Math.min(lLength, rLength) % 2) {
return {
type: 'em',
raw: src.slice(0, lLength + match.index + rLength + 1),
text: src.slice(1, lLength + match.index + rLength)
};
}
if (Math.min(lLength, rLength) % 2 === 0) {
return {
type: 'strong',
raw: src.slice(0, lLength + match.index + rLength + 1),
text: src.slice(2, lLength + match.index + rLength - 1)
};
}
}
}
};
_proto.codespan = function codespan(src) {
var cap = this.rules.inline.code.exec(src);
if (cap) {
var text = cap[2].replace(/\n/g, ' ');
var hasNonSpaceChars = /[^ ]/.test(text);
var hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text);
if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
text = text.substring(1, text.length - 1);
}
text = _escape(text, true);
return {
type: 'codespan',
raw: cap[0],
text: text
};
}
};
_proto.br = function br(src) {
var cap = this.rules.inline.br.exec(src);
if (cap) {
return {
type: 'br',
raw: cap[0]
};
}
};
_proto.del = function del(src) {
var cap = this.rules.inline.del.exec(src);
if (cap) {
return {
type: 'del',
raw: cap[0],
text: cap[2]
};
}
};
_proto.autolink = function autolink(src, mangle) {
var cap = this.rules.inline.autolink.exec(src);
if (cap) {
var text, href;
if (cap[2] === '@') {
text = _escape(this.options.mangle ? mangle(cap[1]) : cap[1]);
href = 'mailto:' + text;
} else {
text = _escape(cap[1]);
href = text;
}
return {
type: 'link',
raw: cap[0],
text: text,
href: href,
tokens: [{
type: 'text',
raw: text,
text: text
}]
};
}
};
_proto.url = function url(src, mangle) {
var cap;
if (cap = this.rules.inline.url.exec(src)) {
var text, href;
if (cap[2] === '@') {
text = _escape(this.options.mangle ? mangle(cap[0]) : cap[0]);
href = 'mailto:' + text;
} else {
// do extended autolink path validation
var prevCapZero;
do {
prevCapZero = cap[0];
cap[0] = this.rules.inline._backpedal.exec(cap[0])[0];
} while (prevCapZero !== cap[0]);
text = _escape(cap[0]);
if (cap[1] === 'www.') {
href = 'http://' + text;
} else {
href = text;
}
}
return {
type: 'link',
raw: cap[0],
text: text,
href: href,
tokens: [{
type: 'text',
raw: text,
text: text
}]
};
}
};
_proto.inlineText = function inlineText(src, inRawBlock, smartypants) {
var cap = this.rules.inline.text.exec(src);
if (cap) {
var text;
if (inRawBlock) {
text = this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : _escape(cap[0]) : cap[0];
} else {
text = _escape(this.options.smartypants ? smartypants(cap[0]) : cap[0]);
}
return {
type: 'text',
raw: cap[0],
text: text
};
}
};
return Tokenizer;
}();
var noopTest$1 = helpers.noopTest,
edit$1 = helpers.edit,
merge$1 = helpers.merge;
/**
* Block-Level Grammar
*/
var block = {
newline: /^(?: *(?:\n|$))+/,
code: /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,
fences: /^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/,
hr: /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,
heading: /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,
blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,
list: /^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?! {0,3}bull )\n*|\s*$)/,
html: '^ {0,3}(?:' // optional indentation
+ '<(script|pre|style)[\\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{2,}|$)' // (6)
+ '|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) open tag
+ '|</(?!script|pre|style)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) closing tag
+ ')',
def: /^ {0,3}\[(label)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,
nptable: noopTest$1,
table: noopTest$1,
lheading: /^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/,
// regex template, placeholders will be replaced according to different paragraph
// interruption rules of commonmark and the original markdown spec:
_paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html| +\n)[^\n]+)*)/,
text: /^[^\n]+/
};
block._label = /(?!\s*\])(?:\\[\[\]]|[^\[\]])+/;
block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;
block.def = edit$1(block.def).replace('label', block._label).replace('title', block._title).getRegex();
block.bullet = /(?:[*+-]|\d{1,9}[.)])/;
block.item = /^( *)(bull) ?[^\n]*(?:\n(?! *bull ?)[^\n]*)*/;
block.item = edit$1(block.item, 'gm').replace(/bull/g, block.bullet).getRegex();
block.listItemStart = edit$1(/^( *)(bull)/).replace('bull', block.bullet).getRegex();
block.list = edit$1(block.list).replace(/bull/g, block.bullet).replace('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))').replace('def', '\\n+(?=' + block.def.source + ')').getRegex();
block._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|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr' + '|track|ul';
block._comment = /<!--(?!-?>)[\s\S]*?(?:-->|$)/;
block.html = edit$1(block.html, 'i').replace('comment', block._comment).replace('tag', block._tag).replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
block.paragraph = edit$1(block._paragraph).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs
.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|!--)').replace('tag', block._tag) // pars can be interrupted by type (6) html blocks
.getRegex();
block.blockquote = edit$1(block.blockquote).replace('paragraph', block.paragraph).getRegex();
/**
* Normal Block Grammar
*/
block.normal = merge$1({}, block);
/**
* GFM Block Grammar
*/
block.gfm = merge$1({}, block.normal, {
nptable: '^ *([^|\\n ].*\\|.*)\\n' // Header
+ ' {0,3}([-:]+ *\\|[-| :]*)' // Align
+ '(?:\\n((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)',
// Cells
table: '^ *\\|(.+)\\n' // Header
+ ' {0,3}\\|?( *[-:]+[-| :]*)' // Align
+ '(?:\\n *((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)' // Cells
});
block.gfm.nptable = edit$1(block.gfm.nptable).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').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|!--)').replace('tag', block._tag) // tables can be interrupted by type (6) html blocks
.getRegex();
block.gfm.table = edit$1(block.gfm.table).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').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|!--)').replace('tag', block._tag) // tables can be interrupted by type (6) html blocks
.getRegex();
/**
* Pedantic grammar (original John Gruber's loose markdown specification)
*/
block.pedantic = merge$1({}, block.normal, {
html: edit$1('^ *(?:comment *(?:\\n|\\s*$)' + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag
+ '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))').replace('comment', block._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$1,
// fences not supported
paragraph: edit$1(block.normal._paragraph).replace('hr', block.hr).replace('heading', ' *#{1,6} *[^\n]').replace('lheading', block.lheading).replace('blockquote', ' {0,3}>').replace('|fences', '').replace('|list', '').replace('|html', '').getRegex()
});
/**
* Inline-Level Grammar
*/
var inline = {
escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,
autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/,
url: noopTest$1,
tag: '^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
link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,
reflink: /^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,
nolink: /^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,
reflinkSearch: 'reflink|nolink(?!\\()',
emStrong: {
lDelim: /^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,
// (1) and (2) can only be a Right Delimiter. (3) and (4) can only be Left. (5) and (6) can be either Left or Right.
// () Skip other delimiter (1) #*** (2) a***#, a*** (3) #***a, ***a (4) ***# (5) #***# (6) a***a
rDelimAst: /\_\_[^_]*?\*[^_]*?\_\_|[punct_](\*+)(?=[\s]|$)|[^punct*_\s](\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|[^punct*_\s](\*+)(?=[^punct*_\s])/,
rDelimUnd: /\*\*[^*]*?\_[^*]*?\*\*|[punct*](\_+)(?=[\s]|$)|[^punct*_\s](\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/ // ^- Not allowed for _
},
code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,
br: /^( {2,}|\\)\n(?!\s*$)/,
del: noopTest$1,
text: /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,
punctuation: /^([\spunctuation])/
}; // list of punctuation marks from CommonMark spec
// without * and _ to handle the different emphasis markers * and _
inline._punctuation = '!"#$%&\'()+\\-.,/:;<=>?@\\[\\]`^{|}~';
inline.punctuation = edit$1(inline.punctuation).replace(/punctuation/g, inline._punctuation).getRegex(); // sequences em should skip over [title](link), `code`, <html>
inline.blockSkip = /\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g;
inline.escapedEmSt = /\\\*|\\_/g;
inline._comment = edit$1(block._comment).replace('(?:-->|$)', '-->').getRegex();
inline.emStrong.lDelim = edit$1(inline.emStrong.lDelim).replace(/punct/g, inline._punctuation).getRegex();
inline.emStrong.rDelimAst = edit$1(inline.emStrong.rDelimAst, 'g').replace(/punct/g, inline._punctuation).getRegex();
inline.emStrong.rDelimUnd = edit$1(inline.emStrong.rDelimUnd, 'g').replace(/punct/g, inline._punctuation).getRegex();
inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g;
inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;
inline._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])?)+(?![-_])/;
inline.autolink = edit$1(inline.autolink).replace('scheme', inline._scheme).replace('email', inline._email).getRegex();
inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;
inline.tag = edit$1(inline.tag).replace('comment', inline._comment).replace('attribute', inline._attribute).getRegex();
inline._label = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
inline._href = /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/;
inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;
inline.link = edit$1(inline.link).replace('label', inline._label).replace('href', inline._href).replace('title', inline._title).getRegex();
inline.reflink = edit$1(inline.reflink).replace('label', inline._label).getRegex();
inline.reflinkSearch = edit$1(inline.reflinkSearch, 'g').replace('reflink', inline.reflink).replace('nolink', inline.nolink).getRegex();
/**
* Normal Inline Grammar
*/
inline.normal = merge$1({}, inline);
/**
* Pedantic Inline Grammar
*/
inline.pedantic = merge$1({}, inline.normal, {
strong: {
start: /^__|\*\*/,
middle: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
endAst: /\*\*(?!\*)/g,
endUnd: /__(?!_)/g
},
em: {
start: /^_|\*/,
middle: /^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,
endAst: /\*(?!\*)/g,
endUnd: /_(?!_)/g
},
link: edit$1(/^!?\[(label)\]\((.*?)\)/).replace('label', inline._label).getRegex(),
reflink: edit$1(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace('label', inline._label).getRegex()
});
/**
* GFM Inline Grammar
*/
inline.gfm = merge$1({}, inline.normal, {
escape: edit$1(inline.escape).replace('])', '~|])').getRegex(),
_extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,
url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,
_backpedal: /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,
del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,
text: /^([`~]+|[^`~])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))/
});
inline.gfm.url = edit$1(inline.gfm.url, 'i').replace('email', inline.gfm._extended_email).getRegex();
/**
* GFM + Line Breaks Inline Grammar
*/
inline.breaks = merge$1({}, inline.gfm, {
br: edit$1(inline.br).replace('{2,}', '*').getRegex(),
text: edit$1(inline.gfm.text).replace('\\b_', '\\b_| {2,}\\n').replace(/\{2,\}/g, '*').getRegex()
});
var rules = {
block: block,
inline: inline
};
var defaults$2 = defaults.defaults;
var block$1 = rules.block,
inline$1 = rules.inline;
var repeatString$1 = helpers.repeatString;
/**
* smartypants text replacement
*/
function smartypants(text) {
return text // em-dashes
.replace(/---/g, "\u2014") // en-dashes
.replace(/--/g, "\u2013") // opening singles
.replace(/(^|[-\u2014/(\[{"\s])'/g, "$1\u2018") // closing singles & apostrophes
.replace(/'/g, "\u2019") // opening doubles
.replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1\u201C") // closing doubles
.replace(/"/g, "\u201D") // ellipses
.replace(/\.{3}/g, "\u2026");
}
/**
* mangle email addresses
*/
function mangle(text) {
var out = '',
i,
ch;
var l = text.length;
for (i = 0; i < l; i++) {
ch = text.charCodeAt(i);
if (Math.random() > 0.5) {
ch = 'x' + ch.toString(16);
}
out += '&#' + ch + ';';
}
return out;
}
/**
* Block Lexer
*/
var Lexer_1 = /*#__PURE__*/function () {
function Lexer(options) {
this.tokens = [];
this.tokens.links = Object.create(null);
this.options = options || defaults$2;
this.options.tokenizer = this.options.tokenizer || new Tokenizer_1();
this.tokenizer = this.options.tokenizer;
this.tokenizer.options = this.options;
var rules = {
block: block$1.normal,
inline: inline$1.normal
};
if (this.options.pedantic) {
rules.block = block$1.pedantic;
rules.inline = inline$1.pedantic;
} else if (this.options.gfm) {
rules.block = block$1.gfm;
if (this.options.breaks) {
rules.inline = inline$1.breaks;
} else {
rules.inline = inline$1.gfm;
}
}
this.tokenizer.rules = rules;
}
/**
* Expose Rules
*/
/**
* Static Lex Method
*/
Lexer.lex = function lex(src, options) {
var lexer = new Lexer(options);
return lexer.lex(src);
}
/**
* Static Lex Inline Method
*/
;
Lexer.lexInline = function lexInline(src, options) {
var lexer = new Lexer(options);
return lexer.inlineTokens(src);
}
/**
* Preprocessing
*/
;
var _proto = Lexer.prototype;
_proto.lex = function lex(src) {
src = src.replace(/\r\n|\r/g, '\n').replace(/\t/g, ' ');
this.blockTokens(src, this.tokens, true);
this.inline(this.tokens);
return this.tokens;
}
/**
* Lexing
*/
;
_proto.blockTokens = function blockTokens(src, tokens, top) {
if (tokens === void 0) {
tokens = [];
}
if (top === void 0) {
top = true;
}
if (this.options.pedantic) {
src = src.replace(/^ +$/gm, '');
}
var token, i, l, lastToken;
while (src) {
// newline
if (token = this.tokenizer.space(src)) {
src = src.substring(token.raw.length);
if (token.type) {
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.raw += '\n' + token.raw;
lastToken.text += '\n' + token.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;
} // table no leading pipe (gfm)
if (token = this.tokenizer.nptable(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);
token.tokens = this.blockTokens(token.text, [], top);
tokens.push(token);
continue;
} // list
if (token = this.tokenizer.list(src)) {
src = src.substring(token.raw.length);
l = token.items.length;
for (i = 0; i < l; i++) {
token.items[i].tokens = this.blockTokens(token.items[i].text, [], false);
}
tokens.push(token);
continue;
} // html
if (token = this.tokenizer.html(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
} // def
if (top && (token = this.tokenizer.def(src))) {
src = src.substring(token.raw.length);
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
if (top && (token = this.tokenizer.paragraph(src))) {
src = src.substring(token.raw.length);
tokens.push(token);
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;
} else {
tokens.push(token);
}
continue;
}
if (src) {
var errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
if (this.options.silent) {
console.error(errMsg);
break;
} else {
throw new Error(errMsg);
}
}
}
return tokens;
};
_proto.inline = function inline(tokens) {
var i, j, k, l2, row, token;
var l = tokens.length;
for (i = 0; i < l; i++) {
token = tokens[i];
switch (token.type) {
case 'paragraph':
case 'text':
case 'heading':
{
token.tokens = [];
this.inlineTokens(token.text, token.tokens);
break;
}
case 'table':
{
token.tokens = {
header: [],
cells: []
}; // header
l2 = token.header.length;
for (j = 0; j < l2; j++) {
token.tokens.header[j] = [];
this.inlineTokens(token.header[j], token.tokens.header[j]);
} // cells
l2 = token.cells.length;
for (j = 0; j < l2; j++) {
row = token.cells[j];
token.tokens.cells[j] = [];
for (k = 0; k < row.length; k++) {
token.tokens.cells[j][k] = [];
this.inlineTokens(row[k], token.tokens.cells[j][k]);
}
}
break;
}
case 'blockquote':
{
this.inline(token.tokens);
break;
}
case 'list':
{
l2 = token.items.length;
for (j = 0; j < l2; j++) {
this.inline(token.items[j].tokens);
}
break;
}
}
}
return tokens;
}
/**
* Lexing/Compiling
*/
;
_proto.inlineTokens = function inlineTokens(src, tokens, inLink, inRawBlock) {
if (tokens === void 0) {
tokens = [];
}
if (inLink === void 0) {
inLink = false;
}
if (inRawBlock === void 0) {
inRawBlock = false;
}
var token, lastToken; // String with links masked to avoid interference with em and strong
var maskedSrc = src;
var match;
var keepPrevChar, prevChar; // Mask out reflinks
if (this.tokens.links) {
var 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) + '[' + repeatString$1('a', 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) + '[' + repeatString$1('a', match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
} // Mask out escaped em & strong delimiters
while ((match = this.tokenizer.rules.inline.escapedEmSt.exec(maskedSrc)) != null) {
maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex);
}
while (src) {
if (!keepPrevChar) {
prevChar = '';
}
keepPrevChar = false; // escape
if (token = this.tokenizer.escape(src)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
} // tag
if (token = this.tokenizer.tag(src, inLink, inRawBlock)) {
src = src.substring(token.raw.length);
inLink = token.inLink;
inRawBlock = token.inRawBlock;
var _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);
if (token.type === 'link') {
token.tokens = this.inlineTokens(token.text, [], true, inRawBlock);
}
tokens.push(token);
continue;
} // reflink, nolink
if (token = this.tokenizer.reflink(src, this.tokens.links)) {
src = src.substring(token.raw.length);
var _lastToken2 = tokens[tokens.length - 1];
if (token.type === 'link') {
token.tokens = this.inlineTokens(token.text, [], true, inRawBlock);
tokens.push(token);
} else if (_lastToken2 && token.type === 'text' && _lastToken2.type === 'text') {
_lastToken2.raw += token.raw;
_lastToken2.text += token.text;
} else {
tokens.push(token);
}
continue;
} // em & strong
if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
src = src.substring(token.raw.length);
token.tokens = this.inlineTokens(token.text, [], inLink, inRawBlock);
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);
token.tokens = this.inlineTokens(token.text, [], inLink, inRawBlock);
tokens.push(token);
continue;
} // autolink
if (token = this.tokenizer.autolink(src, mangle)) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
} // url (gfm)
if (!inLink && (token = this.tokenizer.url(src, mangle))) {
src = src.substring(token.raw.length);
tokens.push(token);
continue;
} // text
if (token = this.tokenizer.inlineText(src, inRawBlock, smartypants)) {
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) {
var errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
if (this.options.silent) {
console.error(errMsg);
break;
} else {
throw new Error(errMsg);
}
}
}
return tokens;
};
_createClass(Lexer, null, [{
key: "rules",
get: function get() {
return {
block: block$1,
inline: inline$1
};
}
}]);
return Lexer;
}();
var defaults$3 = defaults.defaults;
var cleanUrl$1 = helpers.cleanUrl,
escape$1 = helpers.escape;
/**
* Renderer
*/
var Renderer_1 = /*#__PURE__*/function () {
function Renderer(options) {
this.options = options || defaults$3;
}
var _proto = Renderer.prototype;
_proto.code = function code(_code, infostring, escaped) {
var lang = (infostring || '').match(/\S*/)[0];
if (this.options.highlight) {
var out = this.options.highlight(_code, lang);
if (out != null && out !== _code) {
escaped = true;
_code = out;
}
}
_code = _code.replace(/\n$/, '') + '\n';
if (!lang) {
return '<pre><code>' + (escaped ? _code : escape$1(_code, true)) + '</code></pre>\n';
}
return '<pre><code class="' + this.options.langPrefix + escape$1(lang, true) + '">' + (escaped ? _code : escape$1(_code, true)) + '</code></pre>\n';
};
_proto.blockquote = function blockquote(quote) {
return '<blockquote>\n' + quote + '</blockquote>\n';
};
_proto.html = function html(_html) {
return _html;
};
_proto.heading = function heading(text, level, raw, slugger) {
if (this.options.headerIds) {
return '<h' + level + ' id="' + this.options.headerPrefix + slugger.slug(raw) + '">' + text + '</h' + level + '>\n';
} // ignore IDs
return '<h' + level + '>' + text + '</h' + level + '>\n';
};
_proto.hr = function hr() {
return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
};
_proto.list = function list(body, ordered, start) {
var type = ordered ? 'ol' : 'ul',
startatt = ordered && start !== 1 ? ' start="' + start + '"' : '';
return '<' + type + startatt + '>\n' + body + '</' + type + '>\n';
};
_proto.listitem = function listitem(text) {
return '<li>' + text + '</li>\n';
};
_proto.checkbox = function checkbox(checked) {
return '<input ' + (checked ? 'checked="" ' : '') + 'disabled="" type="checkbox"' + (this.options.xhtml ? ' /' : '') + '> ';
};
_proto.paragraph = function paragraph(text) {
return '<p>' + text + '</p>\n';
};
_proto.table = function table(header, body) {
if (body) body = '<tbody>' + body + '</tbody>';
return '<table>\n' + '<thead>\n' + header + '</thead>\n' + body + '</table>\n';
};
_proto.tablerow = function tablerow(content) {
return '<tr>\n' + content + '</tr>\n';
};
_proto.tablecell = function tablecell(content, flags) {
var type = flags.header ? 'th' : 'td';
var tag = flags.align ? '<' + type + ' align="' + flags.align + '">' : '<' + type + '>';
return tag + content + '</' + type + '>\n';
} // span level renderer
;
_proto.strong = function strong(text) {
return '<strong>' + text + '</strong>';
};
_proto.em = function em(text) {
return '<em>' + text + '</em>';
};
_proto.codespan = function codespan(text) {
return '<code>' + text + '</code>';
};
_proto.br = function br() {
return this.options.xhtml ? '<br/>' : '<br>';
};
_proto.del = function del(text) {
return '<del>' + text + '</del>';
};
_proto.link = function link(href, title, text) {
href = cleanUrl$1(this.options.sanitize, this.options.baseUrl, href);
if (href === null) {
return text;
}
var out = '<a href="' + escape$1(href) + '"';
if (title) {
out += ' title="' + title + '"';
}
out += '>' + text + '</a>';
return out;
};
_proto.image = function image(href, title, text) {
href = cleanUrl$1(this.options.sanitize, this.options.baseUrl, href);
if (href === null) {
return text;
}
var out = '<img src="' + href + '" alt="' + text + '"';
if (title) {
out += ' title="' + title + '"';
}
out += this.options.xhtml ? '/>' : '>';
return out;
};
_proto.text = function text(_text) {
return _text;
};
return Renderer;
}();
/**
* TextRenderer
* returns only the textual part of the token
*/
var TextRenderer_1 = /*#__PURE__*/function () {
function TextRenderer() {}
var _proto = TextRenderer.prototype;
// no need for block level renderers
_proto.strong = function strong(text) {
return text;
};
_proto.em = function em(text) {
return text;
};
_proto.codespan = function codespan(text) {
return text;
};
_proto.del = function del(text) {
return text;
};
_proto.html = function html(text) {
return text;
};
_proto.text = function text(_text) {
return _text;
};
_proto.link = function link(href, title, text) {
return '' + text;
};
_proto.image = function image(href, title, text) {
return '' + text;
};
_proto.br = function br() {
return '';
};
return TextRenderer;
}();
/**
* Slugger generates header id
*/
var Slugger_1 = /*#__PURE__*/function () {
function Slugger() {
this.seen = {};
}
var _proto = Slugger.prototype;
_proto.serialize = function serialize(value) {
return value.toLowerCase().trim() // remove html tags
.replace(/<[!\/a-z].*?>/ig, '') // remove unwanted chars
.replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '').replace(/\s/g, '-');
}
/**
* Finds the next safe (unique) slug to use
*/
;
_proto.getNextSafeSlug = function getNextSafeSlug(originalSlug, isDryRun) {
var slug = originalSlug;
var occurenceAccumulator = 0;
if (this.seen.hasOwnProperty(slug)) {
occurenceAccumulator = this.seen[originalSlug];
do {
occurenceAccumulator++;
slug = originalSlug + '-' + occurenceAccumulator;
} while (this.seen.hasOwnProperty(slug));
}
if (!isDryRun) {
this.seen[originalSlug] = occurenceAccumulator;
this.seen[slug] = 0;
}
return slug;
}
/**
* Convert string to unique id
* @param {object} options
* @param {boolean} options.dryrun Generates the next unique slug without updating the internal accumulator.
*/
;
_proto.slug = function slug(value, options) {
if (options === void 0) {
options = {};
}
var slug = this.serialize(value);
return this.getNextSafeSlug(slug, options.dryrun);
};
return Slugger;
}();
var defaults$4 = defaults.defaults;
var unescape$1 = helpers.unescape;
/**
* Parsing & Compiling
*/
var Parser_1 = /*#__PURE__*/function () {
function Parser(options) {
this.options = options || defaults$4;
this.options.renderer = this.options.renderer || new Renderer_1();
this.renderer = this.options.renderer;
this.renderer.options = this.options;
this.textRenderer = new TextRenderer_1();
this.slugger = new Slugger_1();
}
/**
* Static Parse Method
*/
Parser.parse = function parse(tokens, options) {
var parser = new Parser(options);
return parser.parse(tokens);
}
/**
* Static Parse Inline Method
*/
;
Parser.parseInline = function parseInline(tokens, options) {
var parser = new Parser(options);
return parser.parseInline(tokens);
}
/**
* Parse Loop
*/
;
var _proto = Parser.prototype;
_proto.parse = function parse(tokens, top) {
if (top === void 0) {
top = true;
}
var out = '',
i,
j,
k,
l2,
l3,
row,
cell,
header,
body,
token,
ordered,
start,
loose,
itemBody,
item,
checked,
task,
checkbox;
var l = tokens.length;
for (i = 0; i < l; i++) {
token = tokens[i];
switch (token.type) {
case 'space':
{
continue;
}
case 'hr':
{
out += this.renderer.hr();
continue;
}
case 'heading':
{
out += this.renderer.heading(this.parseInline(token.tokens), token.depth, unescape$1(this.parseInline(token.tokens, this.textRenderer)), this.slugger);
continue;
}
case 'code':
{
out += this.renderer.code(token.text, token.lang, token.escaped);
continue;
}
case 'table':
{
header = ''; // header
cell = '';
l2 = token.header.length;
for (j = 0; j < l2; j++) {
cell += this.renderer.tablecell(this.parseInline(token.tokens.header[j]), {
header: true,
align: token.align[j]
});
}
header += this.renderer.tablerow(cell);
body = '';
l2 = token.cells.length;
for (j = 0; j < l2; j++) {
row = token.tokens.cells[j];
cell = '';
l3 = row.length;
for (k = 0; k < l3; k++) {
cell += this.renderer.tablecell(this.parseInline(row[k]), {
header: false,
align: token.align[k]
});
}
body += this.renderer.tablerow(cell);
}
out += this.renderer.table(header, body);
continue;
}
case 'blockquote':
{
body = this.parse(token.tokens);
out += this.renderer.blockquote(body);
continue;
}
case 'list':
{
ordered = token.ordered;
start = token.start;
loose = token.loose;
l2 = token.items.length;
body = '';
for (j = 0; j < l2; j++) {
item = token.items[j];
checked = item.checked;
task = item.task;
itemBody = '';
if (item.task) {
checkbox = this.renderer.checkbox(checked);
if (loose) {
if (item.tokens.length > 0 && item.tokens[0].type === 'text') {
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',
text: checkbox
});
}
} else {
itemBody += checkbox;
}
}
itemBody += this.parse(item.tokens, loose);
body += this.renderer.listitem(itemBody, task, checked);
}
out += this.renderer.list(body, ordered, start);
continue;
}
case 'html':
{
// TODO parse inline content if parameter markdown=1
out += this.renderer.html(token.text);
continue;
}
case 'paragraph':
{
out += this.renderer.paragraph(this.parseInline(token.tokens));
continue;
}
case 'text':
{
body = token.tokens ? this.parseInline(token.tokens) : token.text;
while (i + 1 < l && tokens[i + 1].type === 'text') {
token = tokens[++i];
body += '\n' + (token.tokens ? this.parseInline(token.tokens) : token.text);
}
out += top ? this.renderer.paragraph(body) : body;
continue;
}
default:
{
var 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
*/
;
_proto.parseInline = function parseInline(tokens, renderer) {
renderer = renderer || this.renderer;
var out = '',
i,
token;
var l = tokens.length;
for (i = 0; i < l; i++) {
token = tokens[i];
switch (token.type) {
case 'escape':
{
out += renderer.text(token.text);
break;
}
case 'html':
{
out += renderer.html(token.text);
break;
}
case 'link':
{
out += renderer.link(token.href, token.title, this.parseInline(token.tokens, renderer));
break;
}
case 'image':
{
out += renderer.image(token.href, token.title, token.text);
break;
}
case 'strong':
{
out += renderer.strong(this.parseInline(token.tokens, renderer));
break;
}
case 'em':
{
out += renderer.em(this.parseInline(token.tokens, renderer));
break;
}
case 'codespan':
{
out += renderer.codespan(token.text);
break;
}
case 'br':
{
out += renderer.br();
break;
}
case 'del':
{
out += renderer.del(this.parseInline(token.tokens, renderer));
break;
}
case 'text':
{
out += renderer.text(token.text);
break;
}
default:
{
var errMsg = 'Token with "' + token.type + '" type was not found.';
if (this.options.silent) {
console.error(errMsg);
return;
} else {
throw new Error(errMsg);
}
}
}
}
return out;
};
return Parser;
}();
var merge$2 = helpers.merge,
checkSanitizeDeprecation$1 = helpers.checkSanitizeDeprecation,
escape$2 = helpers.escape;
var getDefaults = defaults.getDefaults,
changeDefaults = defaults.changeDefaults,
defaults$5 = defaults.defaults;
/**
* Marked
*/
function marked(src, opt, callback) {
// throw error in case of non string input
if (typeof src === 'undefined' || src === null) {
throw new Error('marked(): input parameter is undefined or null');
}
if (typeof src !== 'string') {
throw new Error('marked(): input parameter is of type ' + Object.prototype.toString.call(src) + ', string expected');
}
if (typeof opt === 'function') {
callback = opt;
opt = null;
}
opt = merge$2({}, marked.defaults, opt || {});
checkSanitizeDeprecation$1(opt);
if (callback) {
var highlight = opt.highlight;
var tokens;
try {
tokens = Lexer_1.lex(src, opt);
} catch (e) {
return callback(e);
}
var done = function done(err) {
var out;
if (!err) {
try {
out = Parser_1.parse(tokens, opt);
} catch (e) {
err = e;
}
}
opt.highlight = highlight;
return err ? callback(err) : callback(null, out);
};
if (!highlight || highlight.length < 3) {
return done();
}
delete opt.highlight;
if (!tokens.length) return done();
var pending = 0;
marked.walkTokens(tokens, function (token) {
if (token.type === 'code') {
pending++;
setTimeout(function () {
highlight(token.text, token.lang, function (err, code) {
if (err) {
return done(err);
}
if (code != null && code !== token.text) {
token.text = code;
token.escaped = true;
}
pending--;
if (pending === 0) {
done();
}
});
}, 0);
}
});
if (pending === 0) {
done();
}
return;
}
try {
var _tokens = Lexer_1.lex(src, opt);
if (opt.walkTokens) {
marked.walkTokens(_tokens, opt.walkTokens);
}
return Parser_1.parse(_tokens, opt);
} catch (e) {
e.message += '\nPlease report this to https://github.com/markedjs/marked.';
if (opt.silent) {
return '<p>An error occurred:</p><pre>' + escape$2(e.message + '', true) + '</pre>';
}
throw e;
}
}
/**
* Options
*/
marked.options = marked.setOptions = function (opt) {
merge$2(marked.defaults, opt);
changeDefaults(marked.defaults);
return marked;
};
marked.getDefaults = getDefaults;
marked.defaults = defaults$5;
/**
* Use Extension
*/
marked.use = function (extension) {
var opts = merge$2({}, extension);
if (extension.renderer) {
(function () {
var renderer = marked.defaults.renderer || new Renderer_1();
var _loop = function _loop(prop) {
var prevRenderer = renderer[prop];
renderer[prop] = function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var ret = extension.renderer[prop].apply(renderer, args);
if (ret === false) {
ret = prevRenderer.apply(renderer, args);
}
return ret;
};
};
for (var prop in extension.renderer) {
_loop(prop);
}
opts.renderer = renderer;
})();
}
if (extension.tokenizer) {
(function () {
var tokenizer = marked.defaults.tokenizer || new Tokenizer_1();
var _loop2 = function _loop2(prop) {
var prevTokenizer = tokenizer[prop];
tokenizer[prop] = function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var ret = extension.tokenizer[prop].apply(tokenizer, args);
if (ret === false) {
ret = prevTokenizer.apply(tokenizer, args);
}
return ret;
};
};
for (var prop in extension.tokenizer) {
_loop2(prop);
}
opts.tokenizer = tokenizer;
})();
}
if (extension.walkTokens) {
var walkTokens = marked.defaults.walkTokens;
opts.walkTokens = function (token) {
extension.walkTokens(token);
if (walkTokens) {
walkTokens(token);
}
};
}
marked.setOptions(opts);
};
/**
* Run callback for every token
*/
marked.walkTokens = function (tokens, callback) {
for (var _iterator = _createForOfIteratorHelperLoose(tokens), _step; !(_step = _iterator()).done;) {
var token = _step.value;
callback(token);
switch (token.type) {
case 'table':
{
for (var _iterator2 = _createForOfIteratorHelperLoose(token.tokens.header), _step2; !(_step2 = _iterator2()).done;) {
var cell = _step2.value;
marked.walkTokens(cell, callback);
}
for (var _iterator3 = _createForOfIteratorHelperLoose(token.tokens.cells), _step3; !(_step3 = _iterator3()).done;) {
var row = _step3.value;
for (var _iterator4 = _createForOfIteratorHelperLoose(row), _step4; !(_step4 = _iterator4()).done;) {
var _cell = _step4.value;
marked.walkTokens(_cell, callback);
}
}
break;
}
case 'list':
{
marked.walkTokens(token.items, callback);
break;
}
default:
{
if (token.tokens) {
marked.walkTokens(token.tokens, callback);
}
}
}
}
};
/**
* Parse Inline
*/
marked.parseInline = function (src, opt) {
// throw error in case of non string input
if (typeof src === 'undefined' || src === null) {
throw new Error('marked.parseInline(): input parameter is undefined or null');
}
if (typeof src !== 'string') {
throw new Error('marked.parseInline(): input parameter is of type ' + Object.prototype.toString.call(src) + ', string expected');
}
opt = merge$2({}, marked.defaults, opt || {});
checkSanitizeDeprecation$1(opt);
try {
var tokens = Lexer_1.lexInline(src, opt);
if (opt.walkTokens) {
marked.walkTokens(tokens, opt.walkTokens);
}
return Parser_1.parseInline(tokens, opt);
} catch (e) {
e.message += '\nPlease report this to https://github.com/markedjs/marked.';
if (opt.silent) {
return '<p>An error occurred:</p><pre>' + escape$2(e.message + '', true) + '</pre>';
}
throw e;
}
};
/**
* Expose
*/
marked.Parser = Parser_1;
marked.parser = Parser_1.parse;
marked.Renderer = Renderer_1;
marked.TextRenderer = TextRenderer_1;
marked.Lexer = Lexer_1;
marked.lexer = Lexer_1.lex;
marked.Tokenizer = Tokenizer_1;
marked.Slugger = Slugger_1;
marked.parse = marked;
var marked_1 = marked;
return marked_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[286/*vs/base/common/navigator*/], __M([0/*require*/,1/*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;
});
/*---------------------------------------------------------------------------------------------
* 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/base/common/history*/], __M([0/*require*/,1/*exports*/,286/*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();
}
add(t) {
this._history.delete(t);
this._history.add(t);
this._onChange();
}
next() {
if (this._currentPosition() !== this._elements.length - 1) {
return this._navigator.next();
}
return null;
}
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();
}
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[102/*vs/base/common/numbers*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MovingAverage = exports.clamp = void 0;
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
exports.clamp = clamp;
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;
}
get value() {
return this._val;
}
}
exports.MovingAverage = MovingAverage;
});
/*---------------------------------------------------------------------------------------------
* 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/base/common/platform*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isLittleEndian = exports.OS = exports.setImmediate = exports.userAgent = exports.isIOS = exports.isWeb = exports.isNative = exports.isLinux = exports.isMacintosh = exports.isWindows = exports.isPreferringBrowserCodeLoad = exports.browserCodeLoadingCacheStrategy = exports.isElectronSandboxed = exports.globals = void 0;
const LANGUAGE_DEFAULT = 'en';
let _isWindows = false;
let _isMacintosh = false;
let _isLinux = false;
let _isLinuxSnap = false;
let _isNative = false;
let _isWeb = false;
let _isIOS = false;
let _locale = undefined;
let _language = LANGUAGE_DEFAULT;
let _translationsConfigFile = undefined;
let _userAgent = undefined;
exports.globals = (typeof self === 'object' ? self : typeof global === 'object' ? global : {});
let nodeProcess = undefined;
if (typeof exports.globals.vscode !== 'undefined' && typeof exports.globals.vscode.process !== 'undefined') {
// Native environment (sandboxed)
nodeProcess = exports.globals.vscode.process;
}
else if (typeof process !== 'undefined') {
// Native environment (non-sandboxed)
nodeProcess = process;
}
const isElectronRenderer = typeof ((_a = nodeProcess === null || nodeProcess === void 0 ? void 0 : nodeProcess.versions) === null || _a === void 0 ? void 0 : _a.electron) === 'string' && nodeProcess.type === 'renderer';
exports.isElectronSandboxed = isElectronRenderer && (nodeProcess === null || nodeProcess === void 0 ? void 0 : nodeProcess.sandboxed);
exports.browserCodeLoadingCacheStrategy = (() => {
// Always enabled when sandbox is enabled
if (exports.isElectronSandboxed) {
return 'bypassHeatCheck';
}
// Otherwise, only enabled conditionally
const env = nodeProcess === null || nodeProcess === void 0 ? void 0 : nodeProcess.env['VSCODE_BROWSER_CODE_LOADING'];
if (typeof env === 'string') {
if (env === 'none' || env === 'code' || env === 'bypassHeatCheck' || env === 'bypassHeatCheckAndEagerCompile') {
return env;
}
return 'bypassHeatCheck';
}
return undefined;
})();
exports.isPreferringBrowserCodeLoad = typeof exports.browserCodeLoadingCacheStrategy === 'string';
// Web environment
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;
_isWeb = true;
_locale = navigator.language;
_language = _locale;
}
// Native environment
else 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'];
_locale = LANGUAGE_DEFAULT;
_language = LANGUAGE_DEFAULT;
const rawNlsConfig = nodeProcess.env['VSCODE_NLS_CONFIG'];
if (rawNlsConfig) {
try {
const nlsConfig = JSON.parse(rawNlsConfig);
const resolved = nlsConfig.availableLanguages['*'];
_locale = nlsConfig.locale;
// VSCode's default language is 'en'
_language = resolved ? resolved : LANGUAGE_DEFAULT;
_translationsConfigFile = nlsConfig._translationsConfigFile;
}
catch (e) {
}
}
_isNative = true;
}
// Unknown environment
else {
console.error('Unable to resolve platform.');
}
let _platform = 0 /* Web */;
if (_isMacintosh) {
_platform = 1 /* Mac */;
}
else if (_isWindows) {
_platform = 3 /* Windows */;
}
else if (_isLinux) {
_platform = 2 /* Linux */;
}
exports.isWindows = _isWindows;
exports.isMacintosh = _isMacintosh;
exports.isLinux = _isLinux;
exports.isNative = _isNative;
exports.isWeb = _isWeb;
exports.isIOS = _isIOS;
exports.userAgent = _userAgent;
exports.setImmediate = (function defineSetImmediate() {
if (exports.globals.setImmediate) {
return exports.globals.setImmediate.bind(exports.globals);
}
if (typeof exports.globals.postMessage === 'function' && !exports.globals.importScripts) {
let pending = [];
exports.globals.addEventListener('message', (e) => {
if (e.data && e.data.vscodeSetImmediateId) {
for (let i = 0, len = pending.length; i < len; i++) {
const candidate = pending[i];
if (candidate.id === e.data.vscodeSetImmediateId) {
pending.splice(i, 1);
candidate.callback();
return;
}
}
}
});
let lastId = 0;
return (callback) => {
const myId = ++lastId;
pending.push({
id: myId,
callback: callback
});
exports.globals.postMessage({ vscodeSetImmediateId: myId }, '*');
};
}
if (typeof (nodeProcess === null || nodeProcess === void 0 ? void 0 : nodeProcess.nextTick) === 'function') {
return nodeProcess.nextTick.bind(nodeProcess);
}
const _promise = Promise.resolve();
return (callback) => _promise.then(callback);
})();
exports.OS = (_isMacintosh || _isIOS ? 2 /* Macintosh */ : (_isWindows ? 1 /* Windows */ : 3 /* 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.isLittleEndian = isLittleEndian;
});
/*---------------------------------------------------------------------------------------------
* 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/base/common/process*/], __M([0/*require*/,1/*exports*/,17/*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
if (typeof platform_1.globals.vscode !== 'undefined' && typeof platform_1.globals.vscode.process !== 'undefined') {
const sandboxProcess = platform_1.globals.vscode.process;
safeProcess = {
get platform() { return sandboxProcess.platform; },
get env() { return sandboxProcess.env; },
cwd() { return sandboxProcess.cwd(); },
nextTick(callback) { return (0, platform_1.setImmediate)(callback); }
};
}
// Native node.js environment
else if (typeof process !== 'undefined') {
safeProcess = {
get platform() { return process.platform; },
get env() { return process.env; },
cwd() { return process.env['VSCODE_CWD'] || process.cwd(); },
nextTick(callback) { return process.nextTick(callback); }
};
}
// Web environment
else {
safeProcess = {
// Supported
get platform() { return platform_1.isWindows ? 'win32' : platform_1.isMacintosh ? 'darwin' : 'linux'; },
nextTick(callback) { return (0, platform_1.setImmediate)(callback); },
// 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 `/`.
*/
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[73/*vs/base/common/path*/], __M([0/*require*/,1/*exports*/,288/*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.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 validateString(value, name) {
if (typeof value !== 'string') {
throw new ErrorInvalidArgType(name, 'string', value);
}
}
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 _format(sep, pathObject) {
if (pathObject === null || typeof pathObject !== 'object') {
throw new ErrorInvalidArgType('pathObject', 'Object', pathObject);
}
const dir = pathObject.dir || pathObject.root;
const base = pathObject.base ||
`${pathObject.name || ''}${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, 'path');
// 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 an UNC path then.
//
// This step is skipped when it is very clear that the user actually
// intended to point at an 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 an 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') {
return path;
}
if (path.length === 0) {
return '';
}
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, ext) {
if (ext !== undefined) {
validateString(ext, 'ext');
}
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 (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
if (ext === path) {
return '';
}
let extIdx = ext.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 === ext.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
};
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] : process.cwd();
validateString(path, 'path');
// 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, ext) {
if (ext !== undefined) {
validateString(ext, 'ext');
}
validateString(path, 'path');
let start = 0;
let end = -1;
let matchedSlash = true;
let i;
if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
if (ext === path) {
return '';
}
let extIdx = ext.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 === ext.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 = (process.platform === 'win32' ? exports.win32.normalize : exports.posix.normalize);
exports.resolve = (process.platform === 'win32' ? exports.win32.resolve : exports.posix.resolve);
exports.relative = (process.platform === 'win32' ? exports.win32.relative : exports.posix.relative);
exports.dirname = (process.platform === 'win32' ? exports.win32.dirname : exports.posix.dirname);
exports.basename = (process.platform === 'win32' ? exports.win32.basename : exports.posix.basename);
exports.extname = (process.platform === 'win32' ? exports.win32.extname : exports.posix.extname);
exports.sep = (process.platform === 'win32' ? 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[126/*vs/base/common/range*/], __M([0/*require*/,1/*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 || (exports.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[289/*vs/base/browser/ui/list/rangeMap*/], __M([0/*require*/,1/*exports*/,126/*vs/base/common/range*/]), function (require, exports, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RangeMap = exports.consolidate = exports.shift = exports.groupIntersect = void 0;
/**
* Returns the intersection between a ranged group and a range.
* Returns `[]` if the intersection is empty.
*/
function groupIntersect(range, groups) {
const result = [];
for (let 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;
}
exports.groupIntersect = groupIntersect;
/**
* Shifts a range by that `much`.
*/
function shift({ start, end }, much) {
return { start: start + much, end: end + much };
}
exports.shift = shift;
/**
* 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 (let 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;
}
exports.consolidate = consolidate;
/**
* Concatenates several collections of ranged groups into a single
* collection.
*/
function concat(...groups) {
return consolidate(groups.reduce((r, g) => r.concat(g), []));
}
class RangeMap {
constructor() {
this.groups = [];
this._size = 0;
}
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.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;
}
let index = 0;
let size = 0;
for (let 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 (let group of this.groups) {
const groupCount = group.range.end - group.range.start;
const newCount = count + groupCount;
if (index < newCount) {
return 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[81/*vs/base/common/stopwatch*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/]), function (require, exports, platform_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StopWatch = void 0;
const hasPerformanceNow = (platform_1.globals.performance && typeof platform_1.globals.performance.now === 'function');
class StopWatch {
constructor(highResolution) {
this._highResolution = hasPerformanceNow && highResolution;
this._startTime = this._now();
this._stopTime = -1;
}
static create(highResolution = true) {
return new StopWatch(highResolution);
}
stop() {
this._stopTime = this._now();
}
elapsed() {
if (this._stopTime !== -1) {
return this._stopTime - this._startTime;
}
return this._now() - this._startTime;
}
_now() {
return this._highResolution ? platform_1.globals.performance.now() : Date.now();
}
}
exports.StopWatch = StopWatch;
});
define(__m[6/*vs/base/common/event*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,72/*vs/base/common/linkedList*/,81/*vs/base/common/stopwatch*/]), function (require, exports, errors_1, lifecycle_1, linkedList_1, stopwatch_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Relay = exports.EventBufferer = exports.DebounceEmitter = exports.PauseableEmitter = exports.Emitter = exports.Event = void 0;
var Event;
(function (Event) {
Event.None = () => lifecycle_1.Disposable.None;
/**
* Given an event, returns another event which only fires once.
*/
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;
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;
/**
* @deprecated DO NOT use, this leaks memory
*/
function map(event, map) {
return snapshot((listener, thisArgs = null, disposables) => event(i => listener.call(thisArgs, map(i)), null, disposables));
}
Event.map = map;
/**
* @deprecated DO NOT use, this leaks memory
*/
function forEach(event, each) {
return snapshot((listener, thisArgs = null, disposables) => event(i => { each(i); listener.call(thisArgs, i); }, null, disposables));
}
Event.forEach = forEach;
function filter(event, filter) {
return snapshot((listener, thisArgs = null, disposables) => event(e => filter(e) && listener.call(thisArgs, e), null, disposables));
}
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) => (0, lifecycle_1.combinedDisposable)(...events.map(event => event(e => listener.call(thisArgs, e), null, disposables)));
}
Event.any = any;
/**
* @deprecated DO NOT use, this leaks memory
*/
function reduce(event, merge, initial) {
let output = initial;
return map(event, e => {
output = merge(output, e);
return output;
});
}
Event.reduce = reduce;
/**
* @deprecated DO NOT use, this leaks memory
*/
function snapshot(event) {
let listener;
const emitter = new Emitter({
onFirstListenerAdd() {
listener = event(emitter.fire, emitter);
},
onLastListenerRemove() {
listener.dispose();
}
});
return emitter.event;
}
/**
* @deprecated DO NOT use, this leaks memory
*/
function debounce(event, merge, delay = 100, leading = false, leakWarningThreshold) {
let subscription;
let output = undefined;
let handle = undefined;
let numDebouncedCalls = 0;
const emitter = new Emitter({
leakWarningThreshold,
onFirstListenerAdd() {
subscription = event(cur => {
numDebouncedCalls++;
output = merge(output, cur);
if (leading && !handle) {
emitter.fire(output);
output = undefined;
}
clearTimeout(handle);
handle = setTimeout(() => {
const _output = output;
output = undefined;
handle = undefined;
if (!leading || numDebouncedCalls > 1) {
emitter.fire(_output);
}
numDebouncedCalls = 0;
}, delay);
});
},
onLastListenerRemove() {
subscription.dispose();
}
});
return emitter.event;
}
Event.debounce = debounce;
/**
* @deprecated DO NOT use, this leaks memory
*/
function latch(event, equals = (a, b) => a === b) {
let firstCall = true;
let cache;
return filter(event, value => {
const shouldEmit = firstCall || !equals(value, cache);
firstCall = false;
cache = value;
return shouldEmit;
});
}
Event.latch = latch;
/**
* @deprecated DO NOT use, this leaks memory
*/
function split(event, isT) {
return [
Event.filter(event, isT),
Event.filter(event, e => !isT(e)),
];
}
Event.split = split;
/**
* @deprecated DO NOT use, this leaks memory
*/
function buffer(event, nextTick = false, _buffer = []) {
let buffer = _buffer.slice();
let listener = event(e => {
if (buffer) {
buffer.push(e);
}
else {
emitter.fire(e);
}
});
const flush = () => {
if (buffer) {
buffer.forEach(e => emitter.fire(e));
}
buffer = null;
};
const emitter = new Emitter({
onFirstListenerAdd() {
if (!listener) {
listener = event(e => emitter.fire(e));
}
},
onFirstListenerDidAdd() {
if (buffer) {
if (nextTick) {
setTimeout(flush);
}
else {
flush();
}
}
},
onLastListenerRemove() {
if (listener) {
listener.dispose();
}
listener = null;
}
});
return emitter.event;
}
Event.buffer = buffer;
class ChainableEvent {
constructor(event) {
this.event = event;
}
map(fn) {
return new ChainableEvent(map(this.event, fn));
}
forEach(fn) {
return new ChainableEvent(forEach(this.event, fn));
}
filter(fn) {
return new ChainableEvent(filter(this.event, fn));
}
reduce(merge, initial) {
return new ChainableEvent(reduce(this.event, merge, initial));
}
latch() {
return new ChainableEvent(latch(this.event));
}
debounce(merge, delay = 100, leading = false, leakWarningThreshold) {
return new ChainableEvent(debounce(this.event, merge, delay, leading, leakWarningThreshold));
}
on(listener, thisArgs, disposables) {
return this.event(listener, thisArgs, disposables);
}
once(listener, thisArgs, disposables) {
return once(this.event)(listener, thisArgs, disposables);
}
}
/**
* @deprecated DO NOT use, this leaks memory
*/
function chain(event) {
return new ChainableEvent(event);
}
Event.chain = chain;
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({ onFirstListenerAdd, onLastListenerRemove });
return result.event;
}
Event.fromNodeEventEmitter = fromNodeEventEmitter;
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({ onFirstListenerAdd, onLastListenerRemove });
return result.event;
}
Event.fromDOMEventEmitter = fromDOMEventEmitter;
function toPromise(event) {
return new Promise(resolve => once(event)(resolve));
}
Event.toPromise = toPromise;
})(Event = exports.Event || (exports.Event = {}));
class EventProfiling {
constructor(name) {
this._listenerCount = 0;
this._invocationCount = 0;
this._elapsedOverall = 0;
this._name = `${name}_${EventProfiling._idPool++}`;
}
start(listenerCount) {
this._stopWatch = new stopwatch_1.StopWatch(true);
this._listenerCount = listenerCount;
}
stop() {
if (this._stopWatch) {
const elapsed = this._stopWatch.elapsed();
this._elapsedOverall += elapsed;
this._invocationCount += 1;
console.info(`did FIRE ${this._name}: elapsed_ms: ${elapsed.toFixed(5)}, listener: ${this._listenerCount} (elapsed_overall: ${this._elapsedOverall.toFixed(2)}, invocations: ${this._invocationCount})`);
this._stopWatch = undefined;
}
}
}
EventProfiling._idPool = 0;
let _globalLeakWarningThreshold = -1;
class LeakageMonitor {
constructor(customThreshold, name = Math.random().toString(18).slice(2, 5)) {
this.customThreshold = customThreshold;
this.name = name;
this._warnCountdown = 0;
}
dispose() {
if (this._stacks) {
this._stacks.clear();
}
}
check(listenerCount) {
let threshold = _globalLeakWarningThreshold;
if (typeof this.customThreshold === 'number') {
threshold = this.customThreshold;
}
if (threshold <= 0 || listenerCount < threshold) {
return undefined;
}
if (!this._stacks) {
this._stacks = new Map();
}
const stack = new Error().stack.split('\n').slice(3).join('\n');
const count = (this._stacks.get(stack) || 0);
this._stacks.set(stack, 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;
// find most frequent listener and print warning
let topStack;
let topCount = 0;
for (const [stack, count] of this._stacks) {
if (!topStack || topCount < count) {
topStack = stack;
topCount = count;
}
}
console.warn(`[${this.name}] potential listener LEAK detected, having ${listenerCount} listeners already. MOST frequent listener (${topCount}):`);
console.warn(topStack);
}
return () => {
const count = (this._stacks.get(stack) || 0);
this._stacks.set(stack, count - 1);
};
}
}
/**
* 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) {
var _a;
this._disposed = false;
this._options = options;
this._leakageMon = _globalLeakWarningThreshold > 0 ? new LeakageMonitor(this._options && this._options.leakWarningThreshold) : undefined;
this._perfMon = ((_a = this._options) === null || _a === void 0 ? void 0 : _a._profName) ? new EventProfiling(this._options._profName) : undefined;
}
/**
* For the public to allow to subscribe
* to events from this Emitter
*/
get event() {
if (!this._event) {
this._event = (listener, thisArgs, disposables) => {
var _a;
if (!this._listeners) {
this._listeners = new linkedList_1.LinkedList();
}
const firstListener = this._listeners.isEmpty();
if (firstListener && this._options && this._options.onFirstListenerAdd) {
this._options.onFirstListenerAdd(this);
}
const remove = this._listeners.push(!thisArgs ? listener : [listener, thisArgs]);
if (firstListener && this._options && this._options.onFirstListenerDidAdd) {
this._options.onFirstListenerDidAdd(this);
}
if (this._options && this._options.onListenerDidAdd) {
this._options.onListenerDidAdd(this, listener, thisArgs);
}
// check and record this emitter for potential leakage
const removeMonitor = (_a = this._leakageMon) === null || _a === void 0 ? void 0 : _a.check(this._listeners.size);
const result = (0, lifecycle_1.toDisposable)(() => {
if (removeMonitor) {
removeMonitor();
}
if (!this._disposed) {
remove();
if (this._options && this._options.onLastListenerRemove) {
const hasListeners = (this._listeners && !this._listeners.isEmpty());
if (!hasListeners) {
this._options.onLastListenerRemove(this);
}
}
}
});
if (disposables instanceof lifecycle_1.DisposableStore) {
disposables.add(result);
}
else if (Array.isArray(disposables)) {
disposables.push(result);
}
return result;
};
}
return this._event;
}
/**
* To be kept private to fire an event to
* subscribers
*/
fire(event) {
var _a, _b;
if (this._listeners) {
// put all [listener,event]-pairs into delivery queue
// then emit all event. an inner/nested event might be
// the driver of this
if (!this._deliveryQueue) {
this._deliveryQueue = new linkedList_1.LinkedList();
}
for (let listener of this._listeners) {
this._deliveryQueue.push([listener, event]);
}
// start/stop performance insight collection
(_a = this._perfMon) === null || _a === void 0 ? void 0 : _a.start(this._deliveryQueue.size);
while (this._deliveryQueue.size > 0) {
const [listener, event] = this._deliveryQueue.shift();
try {
if (typeof listener === 'function') {
listener.call(undefined, event);
}
else {
listener[0].call(listener[1], event);
}
}
catch (e) {
(0, errors_1.onUnexpectedError)(e);
}
}
(_b = this._perfMon) === null || _b === void 0 ? void 0 : _b.stop();
}
}
dispose() {
var _a, _b, _c, _d, _e;
if (!this._disposed) {
this._disposed = true;
(_a = this._listeners) === null || _a === void 0 ? void 0 : _a.clear();
(_b = this._deliveryQueue) === null || _b === void 0 ? void 0 : _b.clear();
(_d = (_c = this._options) === null || _c === void 0 ? void 0 : _c.onLastListenerRemove) === null || _d === void 0 ? void 0 : _d.call(_c);
(_e = this._leakageMon) === null || _e === void 0 ? void 0 : _e.dispose();
}
}
}
exports.Emitter = Emitter;
class PauseableEmitter extends Emitter {
constructor(options) {
super(options);
this._isPaused = 0;
this._eventQueue = new linkedList_1.LinkedList();
this._mergeFn = options === null || options === void 0 ? void 0 : 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
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._listeners) {
if (this._isPaused !== 0) {
this._eventQueue.push(event);
}
else {
super.fire(event);
}
}
}
}
exports.PauseableEmitter = PauseableEmitter;
class DebounceEmitter extends PauseableEmitter {
constructor(options) {
var _a;
super(options);
this._delay = (_a = options.delay) !== null && _a !== void 0 ? _a : 100;
}
fire(event) {
if (!this._handle) {
this.pause();
this._handle = setTimeout(() => {
this._handle = undefined;
this.resume();
}, this._delay);
}
super.fire(event);
}
}
exports.DebounceEmitter = DebounceEmitter;
/**
* 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.buffers = [];
}
wrapEvent(event) {
return (listener, thisArgs, disposables) => {
return event(i => {
const buffer = this.buffers[this.buffers.length - 1];
if (buffer) {
buffer.push(() => listener.call(thisArgs, i));
}
else {
listener.call(thisArgs, i);
}
}, undefined, disposables);
};
}
bufferEvents(fn) {
const buffer = [];
this.buffers.push(buffer);
const r = fn();
this.buffers.pop();
buffer.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({
onFirstListenerDidAdd: () => {
this.listening = true;
this.inputEventListener = this.inputEvent(this.emitter.fire, this.emitter);
},
onLastListenerRemove: () => {
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[39/*vs/base/browser/browser*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/]), function (require, exports, event_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isStandalone = exports.isAndroid = exports.isWebkitWebView = exports.isSafari = exports.isChrome = exports.isWebKit = exports.isFirefox = exports.getPixelRatio = exports.getZoomFactor = exports.onDidChangeZoomLevel = exports.getTimeSinceLastZoomLevelChanged = exports.getZoomLevel = void 0;
class WindowManager {
constructor() {
// --- Zoom Level
this._zoomLevel = 0;
this._lastZoomLevelChangeTime = 0;
this._onDidChangeZoomLevel = new event_1.Emitter();
this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event;
// --- Zoom Factor
this._zoomFactor = 1;
}
getZoomLevel() {
return this._zoomLevel;
}
getTimeSinceLastZoomLevelChanged() {
return Date.now() - this._lastZoomLevelChangeTime;
}
getZoomFactor() {
return this._zoomFactor;
}
// --- Pixel Ratio
getPixelRatio() {
let ctx = document.createElement('canvas').getContext('2d');
let dpr = window.devicePixelRatio || 1;
let bsr = ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio || 1;
return dpr / bsr;
}
}
WindowManager.INSTANCE = new WindowManager();
function getZoomLevel() {
return WindowManager.INSTANCE.getZoomLevel();
}
exports.getZoomLevel = getZoomLevel;
/** Returns the time (in ms) since the zoom level was changed */
function getTimeSinceLastZoomLevelChanged() {
return WindowManager.INSTANCE.getTimeSinceLastZoomLevelChanged();
}
exports.getTimeSinceLastZoomLevelChanged = getTimeSinceLastZoomLevelChanged;
function onDidChangeZoomLevel(callback) {
return WindowManager.INSTANCE.onDidChangeZoomLevel(callback);
}
exports.onDidChangeZoomLevel = onDidChangeZoomLevel;
/** The zoom scale for an index, e.g. 1, 1.2, 1.4 */
function getZoomFactor() {
return WindowManager.INSTANCE.getZoomFactor();
}
exports.getZoomFactor = getZoomFactor;
function getPixelRatio() {
return WindowManager.INSTANCE.getPixelRatio();
}
exports.getPixelRatio = getPixelRatio;
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.isAndroid = (userAgent.indexOf('Android') >= 0);
exports.isStandalone = (window.matchMedia && window.matchMedia('(display-mode: standalone)').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[156/*vs/base/browser/canIUse*/], __M([0/*require*/,1/*exports*/,39/*vs/base/browser/browser*/,17/*vs/base/common/platform*/]), function (require, exports, browser, 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 /* Always */;
}
if (navigator.keyboard || browser.isSafari) {
return 1 /* FullScreen */;
}
return 2 /* 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 || navigator.maxTouchPoints > 0,
pointerEvents: window.PointerEvent && ('ontouchstart' in window || window.navigator.maxTouchPoints > 0 || 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[91/*vs/base/browser/event*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/]), function (require, exports, event_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.stopEvent = exports.DomEmitter = void 0;
class DomEmitter {
constructor(element, type, useCapture) {
const fn = (e) => this.emitter.fire(e);
this.emitter = new event_1.Emitter({
onFirstListenerAdd: () => element.addEventListener(type, fn, useCapture),
onLastListenerRemove: () => element.removeEventListener(type, fn, useCapture)
});
}
get event() {
return this.emitter.event;
}
dispose() {
this.emitter.dispose();
}
}
exports.DomEmitter = DomEmitter;
function stopEvent(event) {
event.preventDefault();
event.stopPropagation();
return event;
}
exports.stopEvent = stopEvent;
});
/*---------------------------------------------------------------------------------------------
* 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/base/browser/keyboardEvent*/], __M([0/*require*/,1/*exports*/,39/*vs/base/browser/browser*/,41/*vs/base/common/keyCodes*/,17/*vs/base/common/platform*/]), function (require, exports, browser, keyCodes_1, platform) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StandardKeyboardEvent = void 0;
let KEY_CODE_MAP = new Array(230);
let INVERSE_KEY_CODE_MAP = new Array(112 /* MAX_VALUE */);
(function () {
for (let i = 0; i < INVERSE_KEY_CODE_MAP.length; i++) {
INVERSE_KEY_CODE_MAP[i] = -1;
}
function define(code, keyCode) {
KEY_CODE_MAP[code] = keyCode;
INVERSE_KEY_CODE_MAP[keyCode] = code;
}
define(3, 7 /* PauseBreak */); // VK_CANCEL 0x03 Control-break processing
define(8, 1 /* Backspace */);
define(9, 2 /* Tab */);
define(13, 3 /* Enter */);
define(16, 4 /* Shift */);
define(17, 5 /* Ctrl */);
define(18, 6 /* Alt */);
define(19, 7 /* PauseBreak */);
define(20, 8 /* CapsLock */);
define(27, 9 /* Escape */);
define(32, 10 /* Space */);
define(33, 11 /* PageUp */);
define(34, 12 /* PageDown */);
define(35, 13 /* End */);
define(36, 14 /* Home */);
define(37, 15 /* LeftArrow */);
define(38, 16 /* UpArrow */);
define(39, 17 /* RightArrow */);
define(40, 18 /* DownArrow */);
define(45, 19 /* Insert */);
define(46, 20 /* Delete */);
define(48, 21 /* KEY_0 */);
define(49, 22 /* KEY_1 */);
define(50, 23 /* KEY_2 */);
define(51, 24 /* KEY_3 */);
define(52, 25 /* KEY_4 */);
define(53, 26 /* KEY_5 */);
define(54, 27 /* KEY_6 */);
define(55, 28 /* KEY_7 */);
define(56, 29 /* KEY_8 */);
define(57, 30 /* KEY_9 */);
define(65, 31 /* KEY_A */);
define(66, 32 /* KEY_B */);
define(67, 33 /* KEY_C */);
define(68, 34 /* KEY_D */);
define(69, 35 /* KEY_E */);
define(70, 36 /* KEY_F */);
define(71, 37 /* KEY_G */);
define(72, 38 /* KEY_H */);
define(73, 39 /* KEY_I */);
define(74, 40 /* KEY_J */);
define(75, 41 /* KEY_K */);
define(76, 42 /* KEY_L */);
define(77, 43 /* KEY_M */);
define(78, 44 /* KEY_N */);
define(79, 45 /* KEY_O */);
define(80, 46 /* KEY_P */);
define(81, 47 /* KEY_Q */);
define(82, 48 /* KEY_R */);
define(83, 49 /* KEY_S */);
define(84, 50 /* KEY_T */);
define(85, 51 /* KEY_U */);
define(86, 52 /* KEY_V */);
define(87, 53 /* KEY_W */);
define(88, 54 /* KEY_X */);
define(89, 55 /* KEY_Y */);
define(90, 56 /* KEY_Z */);
define(93, 58 /* ContextMenu */);
define(96, 93 /* NUMPAD_0 */);
define(97, 94 /* NUMPAD_1 */);
define(98, 95 /* NUMPAD_2 */);
define(99, 96 /* NUMPAD_3 */);
define(100, 97 /* NUMPAD_4 */);
define(101, 98 /* NUMPAD_5 */);
define(102, 99 /* NUMPAD_6 */);
define(103, 100 /* NUMPAD_7 */);
define(104, 101 /* NUMPAD_8 */);
define(105, 102 /* NUMPAD_9 */);
define(106, 103 /* NUMPAD_MULTIPLY */);
define(107, 104 /* NUMPAD_ADD */);
define(108, 105 /* NUMPAD_SEPARATOR */);
define(109, 106 /* NUMPAD_SUBTRACT */);
define(110, 107 /* NUMPAD_DECIMAL */);
define(111, 108 /* NUMPAD_DIVIDE */);
define(112, 59 /* F1 */);
define(113, 60 /* F2 */);
define(114, 61 /* F3 */);
define(115, 62 /* F4 */);
define(116, 63 /* F5 */);
define(117, 64 /* F6 */);
define(118, 65 /* F7 */);
define(119, 66 /* F8 */);
define(120, 67 /* F9 */);
define(121, 68 /* F10 */);
define(122, 69 /* F11 */);
define(123, 70 /* F12 */);
define(124, 71 /* F13 */);
define(125, 72 /* F14 */);
define(126, 73 /* F15 */);
define(127, 74 /* F16 */);
define(128, 75 /* F17 */);
define(129, 76 /* F18 */);
define(130, 77 /* F19 */);
define(144, 78 /* NumLock */);
define(145, 79 /* ScrollLock */);
define(186, 80 /* US_SEMICOLON */);
define(187, 81 /* US_EQUAL */);
define(188, 82 /* US_COMMA */);
define(189, 83 /* US_MINUS */);
define(190, 84 /* US_DOT */);
define(191, 85 /* US_SLASH */);
define(192, 86 /* US_BACKTICK */);
define(193, 110 /* ABNT_C1 */);
define(194, 111 /* ABNT_C2 */);
define(219, 87 /* US_OPEN_SQUARE_BRACKET */);
define(220, 88 /* US_BACKSLASH */);
define(221, 89 /* US_CLOSE_SQUARE_BRACKET */);
define(222, 90 /* US_QUOTE */);
define(223, 91 /* OEM_8 */);
define(226, 92 /* OEM_102 */);
/**
* 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.
*/
define(229, 109 /* KEY_IN_COMPOSITION */);
if (browser.isFirefox) {
define(59, 80 /* US_SEMICOLON */);
define(107, 81 /* US_EQUAL */);
define(109, 83 /* US_MINUS */);
if (platform.isMacintosh) {
define(224, 57 /* Meta */);
}
}
else if (browser.isWebKit) {
define(91, 57 /* Meta */);
if (platform.isMacintosh) {
// the two meta keys in the Mac have different key codes (91 and 93)
define(93, 57 /* Meta */);
}
else {
define(92, 57 /* Meta */);
}
}
})();
function extractKeyCode(e) {
if (e.charCode) {
// "keypress" events mostly
let char = String.fromCharCode(e.charCode).toUpperCase();
return keyCodes_1.KeyCodeUtils.fromString(char);
}
return KEY_CODE_MAP[e.keyCode] || 0 /* Unknown */;
}
const ctrlKeyMod = (platform.isMacintosh ? 256 /* WinCtrl */ : 2048 /* CtrlCmd */);
const altKeyMod = 512 /* Alt */;
const shiftKeyMod = 1024 /* Shift */;
const metaKeyMod = (platform.isMacintosh ? 2048 /* CtrlCmd */ : 256 /* WinCtrl */);
class StandardKeyboardEvent {
constructor(source) {
this._standardKeyboardEventBrand = true;
let 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.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 /* Ctrl */;
this.altKey = this.altKey || this.keyCode === 6 /* Alt */;
this.shiftKey = this.shiftKey || this.keyCode === 4 /* Shift */;
this.metaKey = this.metaKey || this.keyCode === 57 /* Meta */;
this._asKeybinding = this._computeKeybinding();
this._asRuntimeKeybinding = this._computeRuntimeKeybinding();
// 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();
}
}
toKeybinding() {
return this._asRuntimeKeybinding;
}
equals(other) {
return this._asKeybinding === other;
}
_computeKeybinding() {
let key = 0 /* Unknown */;
if (this.keyCode !== 5 /* Ctrl */ && this.keyCode !== 4 /* Shift */ && this.keyCode !== 6 /* Alt */ && this.keyCode !== 57 /* 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;
}
_computeRuntimeKeybinding() {
let key = 0 /* Unknown */;
if (this.keyCode !== 5 /* Ctrl */ && this.keyCode !== 4 /* Shift */ && this.keyCode !== 6 /* Alt */ && this.keyCode !== 57 /* Meta */) {
key = this.keyCode;
}
return new keyCodes_1.SimpleKeybinding(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[55/*vs/base/browser/mouseEvent*/], __M([0/*require*/,1/*exports*/,39/*vs/base/browser/browser*/,196/*vs/base/browser/iframe*/,17/*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(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 + document.body.scrollLeft + document.documentElement.scrollLeft;
this.posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
// Find the position of the iframe this code is executing in relative to the iframe where the event was captured.
let iframeOffsets = iframe_1.IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(self, 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;
if (e) {
// Old (deprecated) wheel events
let e1 = e;
let e2 = e;
// vertical delta scroll
if (typeof e1.wheelDeltaY !== 'undefined') {
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 {
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) {
this.deltaY = e.wheelDelta / 120;
}
}
}
preventDefault() {
if (this.browserEvent) {
this.browserEvent.preventDefault();
}
}
stopPropagation() {
if (this.browserEvent) {
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[23/*vs/base/common/cancellation*/], __M([0/*require*/,1/*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;
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 || (exports.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();
}
if (this._parentListener) {
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;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
define(__m[15/*vs/base/common/async*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/]), function (require, exports, cancellation_1, errors_1, lifecycle_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Promises = exports.IdleValue = exports.runWhenIdle = exports.RunOnceScheduler = exports.IntervalTimer = exports.TimeoutTimer = exports.first = exports.disposableTimeout = exports.timeout = exports.ThrottledDelayer = exports.Delayer = exports.Throttler = exports.raceCancellation = exports.createCancelablePromise = exports.isThenable = void 0;
function isThenable(obj) {
return !!obj && typeof obj.then === 'function';
}
exports.isThenable = isThenable;
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();
source.dispose();
reject((0, errors_1.canceled)());
});
Promise.resolve(thenable).then(value => {
subscription.dispose();
source.dispose();
resolve(value);
}, err => {
subscription.dispose();
source.dispose();
reject(err);
});
});
return new class {
cancel() {
source.cancel();
}
then(resolve, reject) {
return promise.then(resolve, reject);
}
catch(reject) {
return this.then(undefined, reject);
}
finally(onfinally) {
return promise.finally(onfinally);
}
};
}
exports.createCancelablePromise = createCancelablePromise;
function raceCancellation(promise, token, defaultValue) {
return Promise.race([promise, new Promise(resolve => token.onCancellationRequested(() => resolve(defaultValue)))]);
}
exports.raceCancellation = raceCancellation;
/**
* 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.activePromise = null;
this.queuedPromise = null;
this.queuedPromiseFactory = null;
}
queue(promiseFactory) {
if (this.activePromise) {
this.queuedPromiseFactory = promiseFactory;
if (!this.queuedPromise) {
const onComplete = () => {
this.queuedPromise = null;
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);
});
});
}
}
exports.Throttler = Throttler;
/**
* 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.timeout = 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;
});
}
this.timeout = setTimeout(() => {
this.timeout = null;
if (this.doResolve) {
this.doResolve(null);
}
}, delay);
return this.completionPromise;
}
isTriggered() {
return this.timeout !== null;
}
cancel() {
this.cancelTimeout();
if (this.completionPromise) {
if (this.doReject) {
this.doReject((0, errors_1.canceled)());
}
this.completionPromise = null;
}
}
cancelTimeout() {
if (this.timeout !== null) {
clearTimeout(this.timeout);
this.timeout = 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);
}
dispose() {
this.delayer.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((0, errors_1.canceled)());
});
});
}
exports.timeout = timeout;
function disposableTimeout(handler, timeout = 0) {
const timer = setTimeout(handler, timeout);
return (0, lifecycle_1.toDisposable)(() => clearTimeout(timer));
}
exports.disposableTimeout = disposableTimeout;
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();
}
exports.first = first;
class TimeoutTimer {
constructor(runner, timeout) {
this._token = -1;
if (typeof runner === 'function' && typeof timeout === 'number') {
this.setIfNotSet(runner, timeout);
}
}
dispose() {
this.cancel();
}
cancel() {
if (this._token !== -1) {
clearTimeout(this._token);
this._token = -1;
}
}
cancelAndSet(runner, timeout) {
this.cancel();
this._token = setTimeout(() => {
this._token = -1;
runner();
}, timeout);
}
setIfNotSet(runner, timeout) {
if (this._token !== -1) {
// timer is already set
return;
}
this._token = setTimeout(() => {
this._token = -1;
runner();
}, timeout);
}
}
exports.TimeoutTimer = TimeoutTimer;
class IntervalTimer {
constructor() {
this._token = -1;
}
dispose() {
this.cancel();
}
cancel() {
if (this._token !== -1) {
clearInterval(this._token);
this._token = -1;
}
}
cancelAndSet(runner, interval) {
this.cancel();
this._token = setInterval(() => {
runner();
}, interval);
}
}
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() {
if (this.runner) {
this.runner();
}
}
}
exports.RunOnceScheduler = RunOnceScheduler;
(function () {
if (typeof requestIdleCallback !== 'function' || typeof cancelIdleCallback !== 'function') {
const dummyIdle = Object.freeze({
didTimeout: true,
timeRemaining() { return 15; }
});
exports.runWhenIdle = (runner) => {
const handle = setTimeout(() => runner(dummyIdle));
let disposed = false;
return {
dispose() {
if (disposed) {
return;
}
disposed = true;
clearTimeout(handle);
}
};
};
}
else {
exports.runWhenIdle = (runner, timeout) => {
const handle = requestIdleCallback(runner, typeof timeout === 'number' ? { timeout } : undefined);
let disposed = false;
return {
dispose() {
if (disposed) {
return;
}
disposed = true;
cancelIdleCallback(handle);
}
};
};
}
})();
/**
* An implementation of the "idle-until-urgent"-strategy as introduced
* here: https://philipwalton.com/articles/idle-until-urgent/
*/
class IdleValue {
constructor(executor) {
this._didRun = false;
this._executor = () => {
try {
this._value = executor();
}
catch (err) {
this._error = err;
}
finally {
this._didRun = true;
}
};
this._handle = (0, exports.runWhenIdle)(() => 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;
}
}
exports.IdleValue = IdleValue;
//#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.
*/
function settled(promises) {
return __awaiter(this, void 0, void 0, function* () {
let firstError = undefined;
const result = yield 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;
})(Promises = exports.Promises || (exports.Promises = {}));
});
//#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[290/*vs/base/browser/ui/scrollbar/scrollbarVisibilityController*/], __M([0/*require*/,1/*exports*/,15/*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 /* Hidden */) {
return false;
}
if (this._visibility === 3 /* 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(() => {
if (this._domNode) {
this._domNode.setClassName(this._visibleClassName);
}
}, 0);
}
_hide(withFadeAway) {
this._revealTimer.cancel();
if (!this._isVisible) {
return;
}
this._isVisible = false;
if (this._domNode) {
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[27/*vs/base/common/codicons*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/]), function (require, exports, event_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CSSIcon = exports.Codicon = exports.getCodiconAriaLabel = exports.registerCodicon = exports.iconRegistry = void 0;
class Registry {
constructor() {
this._icons = new Map();
this._onDidRegister = new event_1.Emitter();
}
add(icon) {
const existing = this._icons.get(icon.id);
if (!existing) {
this._icons.set(icon.id, icon);
this._onDidRegister.fire(icon);
}
else if (icon.description) {
existing.description = icon.description;
}
else {
console.error(`Duplicate registration of codicon ${icon.id}`);
}
}
get(id) {
return this._icons.get(id);
}
get all() {
return this._icons.values();
}
get onDidRegister() {
return this._onDidRegister.event;
}
}
const _registry = new Registry();
exports.iconRegistry = _registry;
function registerCodicon(id, def) {
return new Codicon(id, def);
}
exports.registerCodicon = registerCodicon;
// Selects all codicon names encapsulated in the `$()` syntax and wraps the
// results with spaces so that screen readers can read the text better.
function getCodiconAriaLabel(text) {
if (!text) {
return '';
}
return text.replace(/\$\((.*?)\)/g, (_match, codiconName) => ` ${codiconName} `).trim();
}
exports.getCodiconAriaLabel = getCodiconAriaLabel;
class Codicon {
constructor(id, definition, description) {
this.id = id;
this.definition = definition;
this.description = description;
_registry.add(this);
}
get classNames() { return 'codicon codicon-' + this.id; }
// classNamesArray is useful for migrating to ES6 classlist
get classNamesArray() { return ['codicon', 'codicon-' + this.id]; }
get cssSelector() { return '.codicon.codicon-' + this.id; }
}
exports.Codicon = Codicon;
var CSSIcon;
(function (CSSIcon) {
CSSIcon.iconNameSegment = '[A-Za-z0-9]+';
CSSIcon.iconNameExpression = '[A-Za-z0-9\\-]+';
CSSIcon.iconModifierExpression = '~[A-Za-z]+';
const cssIconIdRegex = new RegExp(`^(${CSSIcon.iconNameExpression})(${CSSIcon.iconModifierExpression})?$`);
function asClassNameArray(icon) {
if (icon instanceof Codicon) {
return ['codicon', 'codicon-' + icon.id];
}
const match = cssIconIdRegex.exec(icon.id);
if (!match) {
return asClassNameArray(Codicon.error);
}
let [, id, modifier] = match;
const classNames = ['codicon', 'codicon-' + id];
if (modifier) {
classNames.push('codicon-modifier-' + modifier.substr(1));
}
return classNames;
}
CSSIcon.asClassNameArray = asClassNameArray;
function asClassName(icon) {
return asClassNameArray(icon).join(' ');
}
CSSIcon.asClassName = asClassName;
function asCSSSelector(icon) {
return '.' + asClassNameArray(icon).join('.');
}
CSSIcon.asCSSSelector = asCSSSelector;
})(CSSIcon = exports.CSSIcon || (exports.CSSIcon = {}));
(function (Codicon) {
// built-in icons, with image name
Codicon.add = new Codicon('add', { fontCharacter: '\\ea60' });
Codicon.plus = new Codicon('plus', { fontCharacter: '\\ea60' });
Codicon.gistNew = new Codicon('gist-new', { fontCharacter: '\\ea60' });
Codicon.repoCreate = new Codicon('repo-create', { fontCharacter: '\\ea60' });
Codicon.lightbulb = new Codicon('lightbulb', { fontCharacter: '\\ea61' });
Codicon.lightBulb = new Codicon('light-bulb', { fontCharacter: '\\ea61' });
Codicon.repo = new Codicon('repo', { fontCharacter: '\\ea62' });
Codicon.repoDelete = new Codicon('repo-delete', { fontCharacter: '\\ea62' });
Codicon.gistFork = new Codicon('gist-fork', { fontCharacter: '\\ea63' });
Codicon.repoForked = new Codicon('repo-forked', { fontCharacter: '\\ea63' });
Codicon.gitPullRequest = new Codicon('git-pull-request', { fontCharacter: '\\ea64' });
Codicon.gitPullRequestAbandoned = new Codicon('git-pull-request-abandoned', { fontCharacter: '\\ea64' });
Codicon.recordKeys = new Codicon('record-keys', { fontCharacter: '\\ea65' });
Codicon.keyboard = new Codicon('keyboard', { fontCharacter: '\\ea65' });
Codicon.tag = new Codicon('tag', { fontCharacter: '\\ea66' });
Codicon.tagAdd = new Codicon('tag-add', { fontCharacter: '\\ea66' });
Codicon.tagRemove = new Codicon('tag-remove', { fontCharacter: '\\ea66' });
Codicon.person = new Codicon('person', { fontCharacter: '\\ea67' });
Codicon.personFollow = new Codicon('person-follow', { fontCharacter: '\\ea67' });
Codicon.personOutline = new Codicon('person-outline', { fontCharacter: '\\ea67' });
Codicon.personFilled = new Codicon('person-filled', { fontCharacter: '\\ea67' });
Codicon.gitBranch = new Codicon('git-branch', { fontCharacter: '\\ea68' });
Codicon.gitBranchCreate = new Codicon('git-branch-create', { fontCharacter: '\\ea68' });
Codicon.gitBranchDelete = new Codicon('git-branch-delete', { fontCharacter: '\\ea68' });
Codicon.sourceControl = new Codicon('source-control', { fontCharacter: '\\ea68' });
Codicon.mirror = new Codicon('mirror', { fontCharacter: '\\ea69' });
Codicon.mirrorPublic = new Codicon('mirror-public', { fontCharacter: '\\ea69' });
Codicon.star = new Codicon('star', { fontCharacter: '\\ea6a' });
Codicon.starAdd = new Codicon('star-add', { fontCharacter: '\\ea6a' });
Codicon.starDelete = new Codicon('star-delete', { fontCharacter: '\\ea6a' });
Codicon.starEmpty = new Codicon('star-empty', { fontCharacter: '\\ea6a' });
Codicon.comment = new Codicon('comment', { fontCharacter: '\\ea6b' });
Codicon.commentAdd = new Codicon('comment-add', { fontCharacter: '\\ea6b' });
Codicon.alert = new Codicon('alert', { fontCharacter: '\\ea6c' });
Codicon.warning = new Codicon('warning', { fontCharacter: '\\ea6c' });
Codicon.search = new Codicon('search', { fontCharacter: '\\ea6d' });
Codicon.searchSave = new Codicon('search-save', { fontCharacter: '\\ea6d' });
Codicon.logOut = new Codicon('log-out', { fontCharacter: '\\ea6e' });
Codicon.signOut = new Codicon('sign-out', { fontCharacter: '\\ea6e' });
Codicon.logIn = new Codicon('log-in', { fontCharacter: '\\ea6f' });
Codicon.signIn = new Codicon('sign-in', { fontCharacter: '\\ea6f' });
Codicon.eye = new Codicon('eye', { fontCharacter: '\\ea70' });
Codicon.eyeUnwatch = new Codicon('eye-unwatch', { fontCharacter: '\\ea70' });
Codicon.eyeWatch = new Codicon('eye-watch', { fontCharacter: '\\ea70' });
Codicon.circleFilled = new Codicon('circle-filled', { fontCharacter: '\\ea71' });
Codicon.primitiveDot = new Codicon('primitive-dot', { fontCharacter: '\\ea71' });
Codicon.closeDirty = new Codicon('close-dirty', { fontCharacter: '\\ea71' });
Codicon.debugBreakpoint = new Codicon('debug-breakpoint', { fontCharacter: '\\ea71' });
Codicon.debugBreakpointDisabled = new Codicon('debug-breakpoint-disabled', { fontCharacter: '\\ea71' });
Codicon.debugHint = new Codicon('debug-hint', { fontCharacter: '\\ea71' });
Codicon.primitiveSquare = new Codicon('primitive-square', { fontCharacter: '\\ea72' });
Codicon.edit = new Codicon('edit', { fontCharacter: '\\ea73' });
Codicon.pencil = new Codicon('pencil', { fontCharacter: '\\ea73' });
Codicon.info = new Codicon('info', { fontCharacter: '\\ea74' });
Codicon.issueOpened = new Codicon('issue-opened', { fontCharacter: '\\ea74' });
Codicon.gistPrivate = new Codicon('gist-private', { fontCharacter: '\\ea75' });
Codicon.gitForkPrivate = new Codicon('git-fork-private', { fontCharacter: '\\ea75' });
Codicon.lock = new Codicon('lock', { fontCharacter: '\\ea75' });
Codicon.mirrorPrivate = new Codicon('mirror-private', { fontCharacter: '\\ea75' });
Codicon.close = new Codicon('close', { fontCharacter: '\\ea76' });
Codicon.removeClose = new Codicon('remove-close', { fontCharacter: '\\ea76' });
Codicon.x = new Codicon('x', { fontCharacter: '\\ea76' });
Codicon.repoSync = new Codicon('repo-sync', { fontCharacter: '\\ea77' });
Codicon.sync = new Codicon('sync', { fontCharacter: '\\ea77' });
Codicon.clone = new Codicon('clone', { fontCharacter: '\\ea78' });
Codicon.desktopDownload = new Codicon('desktop-download', { fontCharacter: '\\ea78' });
Codicon.beaker = new Codicon('beaker', { fontCharacter: '\\ea79' });
Codicon.microscope = new Codicon('microscope', { fontCharacter: '\\ea79' });
Codicon.vm = new Codicon('vm', { fontCharacter: '\\ea7a' });
Codicon.deviceDesktop = new Codicon('device-desktop', { fontCharacter: '\\ea7a' });
Codicon.file = new Codicon('file', { fontCharacter: '\\ea7b' });
Codicon.fileText = new Codicon('file-text', { fontCharacter: '\\ea7b' });
Codicon.more = new Codicon('more', { fontCharacter: '\\ea7c' });
Codicon.ellipsis = new Codicon('ellipsis', { fontCharacter: '\\ea7c' });
Codicon.kebabHorizontal = new Codicon('kebab-horizontal', { fontCharacter: '\\ea7c' });
Codicon.mailReply = new Codicon('mail-reply', { fontCharacter: '\\ea7d' });
Codicon.reply = new Codicon('reply', { fontCharacter: '\\ea7d' });
Codicon.organization = new Codicon('organization', { fontCharacter: '\\ea7e' });
Codicon.organizationFilled = new Codicon('organization-filled', { fontCharacter: '\\ea7e' });
Codicon.organizationOutline = new Codicon('organization-outline', { fontCharacter: '\\ea7e' });
Codicon.newFile = new Codicon('new-file', { fontCharacter: '\\ea7f' });
Codicon.fileAdd = new Codicon('file-add', { fontCharacter: '\\ea7f' });
Codicon.newFolder = new Codicon('new-folder', { fontCharacter: '\\ea80' });
Codicon.fileDirectoryCreate = new Codicon('file-directory-create', { fontCharacter: '\\ea80' });
Codicon.trash = new Codicon('trash', { fontCharacter: '\\ea81' });
Codicon.trashcan = new Codicon('trashcan', { fontCharacter: '\\ea81' });
Codicon.history = new Codicon('history', { fontCharacter: '\\ea82' });
Codicon.clock = new Codicon('clock', { fontCharacter: '\\ea82' });
Codicon.folder = new Codicon('folder', { fontCharacter: '\\ea83' });
Codicon.fileDirectory = new Codicon('file-directory', { fontCharacter: '\\ea83' });
Codicon.symbolFolder = new Codicon('symbol-folder', { fontCharacter: '\\ea83' });
Codicon.logoGithub = new Codicon('logo-github', { fontCharacter: '\\ea84' });
Codicon.markGithub = new Codicon('mark-github', { fontCharacter: '\\ea84' });
Codicon.github = new Codicon('github', { fontCharacter: '\\ea84' });
Codicon.terminal = new Codicon('terminal', { fontCharacter: '\\ea85' });
Codicon.console = new Codicon('console', { fontCharacter: '\\ea85' });
Codicon.repl = new Codicon('repl', { fontCharacter: '\\ea85' });
Codicon.zap = new Codicon('zap', { fontCharacter: '\\ea86' });
Codicon.symbolEvent = new Codicon('symbol-event', { fontCharacter: '\\ea86' });
Codicon.error = new Codicon('error', { fontCharacter: '\\ea87' });
Codicon.stop = new Codicon('stop', { fontCharacter: '\\ea87' });
Codicon.variable = new Codicon('variable', { fontCharacter: '\\ea88' });
Codicon.symbolVariable = new Codicon('symbol-variable', { fontCharacter: '\\ea88' });
Codicon.array = new Codicon('array', { fontCharacter: '\\ea8a' });
Codicon.symbolArray = new Codicon('symbol-array', { fontCharacter: '\\ea8a' });
Codicon.symbolModule = new Codicon('symbol-module', { fontCharacter: '\\ea8b' });
Codicon.symbolPackage = new Codicon('symbol-package', { fontCharacter: '\\ea8b' });
Codicon.symbolNamespace = new Codicon('symbol-namespace', { fontCharacter: '\\ea8b' });
Codicon.symbolObject = new Codicon('symbol-object', { fontCharacter: '\\ea8b' });
Codicon.symbolMethod = new Codicon('symbol-method', { fontCharacter: '\\ea8c' });
Codicon.symbolFunction = new Codicon('symbol-function', { fontCharacter: '\\ea8c' });
Codicon.symbolConstructor = new Codicon('symbol-constructor', { fontCharacter: '\\ea8c' });
Codicon.symbolBoolean = new Codicon('symbol-boolean', { fontCharacter: '\\ea8f' });
Codicon.symbolNull = new Codicon('symbol-null', { fontCharacter: '\\ea8f' });
Codicon.symbolNumeric = new Codicon('symbol-numeric', { fontCharacter: '\\ea90' });
Codicon.symbolNumber = new Codicon('symbol-number', { fontCharacter: '\\ea90' });
Codicon.symbolStructure = new Codicon('symbol-structure', { fontCharacter: '\\ea91' });
Codicon.symbolStruct = new Codicon('symbol-struct', { fontCharacter: '\\ea91' });
Codicon.symbolParameter = new Codicon('symbol-parameter', { fontCharacter: '\\ea92' });
Codicon.symbolTypeParameter = new Codicon('symbol-type-parameter', { fontCharacter: '\\ea92' });
Codicon.symbolKey = new Codicon('symbol-key', { fontCharacter: '\\ea93' });
Codicon.symbolText = new Codicon('symbol-text', { fontCharacter: '\\ea93' });
Codicon.symbolReference = new Codicon('symbol-reference', { fontCharacter: '\\ea94' });
Codicon.goToFile = new Codicon('go-to-file', { fontCharacter: '\\ea94' });
Codicon.symbolEnum = new Codicon('symbol-enum', { fontCharacter: '\\ea95' });
Codicon.symbolValue = new Codicon('symbol-value', { fontCharacter: '\\ea95' });
Codicon.symbolRuler = new Codicon('symbol-ruler', { fontCharacter: '\\ea96' });
Codicon.symbolUnit = new Codicon('symbol-unit', { fontCharacter: '\\ea96' });
Codicon.activateBreakpoints = new Codicon('activate-breakpoints', { fontCharacter: '\\ea97' });
Codicon.archive = new Codicon('archive', { fontCharacter: '\\ea98' });
Codicon.arrowBoth = new Codicon('arrow-both', { fontCharacter: '\\ea99' });
Codicon.arrowDown = new Codicon('arrow-down', { fontCharacter: '\\ea9a' });
Codicon.arrowLeft = new Codicon('arrow-left', { fontCharacter: '\\ea9b' });
Codicon.arrowRight = new Codicon('arrow-right', { fontCharacter: '\\ea9c' });
Codicon.arrowSmallDown = new Codicon('arrow-small-down', { fontCharacter: '\\ea9d' });
Codicon.arrowSmallLeft = new Codicon('arrow-small-left', { fontCharacter: '\\ea9e' });
Codicon.arrowSmallRight = new Codicon('arrow-small-right', { fontCharacter: '\\ea9f' });
Codicon.arrowSmallUp = new Codicon('arrow-small-up', { fontCharacter: '\\eaa0' });
Codicon.arrowUp = new Codicon('arrow-up', { fontCharacter: '\\eaa1' });
Codicon.bell = new Codicon('bell', { fontCharacter: '\\eaa2' });
Codicon.bold = new Codicon('bold', { fontCharacter: '\\eaa3' });
Codicon.book = new Codicon('book', { fontCharacter: '\\eaa4' });
Codicon.bookmark = new Codicon('bookmark', { fontCharacter: '\\eaa5' });
Codicon.debugBreakpointConditionalUnverified = new Codicon('debug-breakpoint-conditional-unverified', { fontCharacter: '\\eaa6' });
Codicon.debugBreakpointConditional = new Codicon('debug-breakpoint-conditional', { fontCharacter: '\\eaa7' });
Codicon.debugBreakpointConditionalDisabled = new Codicon('debug-breakpoint-conditional-disabled', { fontCharacter: '\\eaa7' });
Codicon.debugBreakpointDataUnverified = new Codicon('debug-breakpoint-data-unverified', { fontCharacter: '\\eaa8' });
Codicon.debugBreakpointData = new Codicon('debug-breakpoint-data', { fontCharacter: '\\eaa9' });
Codicon.debugBreakpointDataDisabled = new Codicon('debug-breakpoint-data-disabled', { fontCharacter: '\\eaa9' });
Codicon.debugBreakpointLogUnverified = new Codicon('debug-breakpoint-log-unverified', { fontCharacter: '\\eaaa' });
Codicon.debugBreakpointLog = new Codicon('debug-breakpoint-log', { fontCharacter: '\\eaab' });
Codicon.debugBreakpointLogDisabled = new Codicon('debug-breakpoint-log-disabled', { fontCharacter: '\\eaab' });
Codicon.briefcase = new Codicon('briefcase', { fontCharacter: '\\eaac' });
Codicon.broadcast = new Codicon('broadcast', { fontCharacter: '\\eaad' });
Codicon.browser = new Codicon('browser', { fontCharacter: '\\eaae' });
Codicon.bug = new Codicon('bug', { fontCharacter: '\\eaaf' });
Codicon.calendar = new Codicon('calendar', { fontCharacter: '\\eab0' });
Codicon.caseSensitive = new Codicon('case-sensitive', { fontCharacter: '\\eab1' });
Codicon.check = new Codicon('check', { fontCharacter: '\\eab2' });
Codicon.checklist = new Codicon('checklist', { fontCharacter: '\\eab3' });
Codicon.chevronDown = new Codicon('chevron-down', { fontCharacter: '\\eab4' });
Codicon.chevronLeft = new Codicon('chevron-left', { fontCharacter: '\\eab5' });
Codicon.chevronRight = new Codicon('chevron-right', { fontCharacter: '\\eab6' });
Codicon.chevronUp = new Codicon('chevron-up', { fontCharacter: '\\eab7' });
Codicon.chromeClose = new Codicon('chrome-close', { fontCharacter: '\\eab8' });
Codicon.chromeMaximize = new Codicon('chrome-maximize', { fontCharacter: '\\eab9' });
Codicon.chromeMinimize = new Codicon('chrome-minimize', { fontCharacter: '\\eaba' });
Codicon.chromeRestore = new Codicon('chrome-restore', { fontCharacter: '\\eabb' });
Codicon.circleOutline = new Codicon('circle-outline', { fontCharacter: '\\eabc' });
Codicon.debugBreakpointUnverified = new Codicon('debug-breakpoint-unverified', { fontCharacter: '\\eabc' });
Codicon.circleSlash = new Codicon('circle-slash', { fontCharacter: '\\eabd' });
Codicon.circuitBoard = new Codicon('circuit-board', { fontCharacter: '\\eabe' });
Codicon.clearAll = new Codicon('clear-all', { fontCharacter: '\\eabf' });
Codicon.clippy = new Codicon('clippy', { fontCharacter: '\\eac0' });
Codicon.closeAll = new Codicon('close-all', { fontCharacter: '\\eac1' });
Codicon.cloudDownload = new Codicon('cloud-download', { fontCharacter: '\\eac2' });
Codicon.cloudUpload = new Codicon('cloud-upload', { fontCharacter: '\\eac3' });
Codicon.code = new Codicon('code', { fontCharacter: '\\eac4' });
Codicon.collapseAll = new Codicon('collapse-all', { fontCharacter: '\\eac5' });
Codicon.colorMode = new Codicon('color-mode', { fontCharacter: '\\eac6' });
Codicon.commentDiscussion = new Codicon('comment-discussion', { fontCharacter: '\\eac7' });
Codicon.compareChanges = new Codicon('compare-changes', { fontCharacter: '\\eafd' });
Codicon.creditCard = new Codicon('credit-card', { fontCharacter: '\\eac9' });
Codicon.dash = new Codicon('dash', { fontCharacter: '\\eacc' });
Codicon.dashboard = new Codicon('dashboard', { fontCharacter: '\\eacd' });
Codicon.database = new Codicon('database', { fontCharacter: '\\eace' });
Codicon.debugContinue = new Codicon('debug-continue', { fontCharacter: '\\eacf' });
Codicon.debugDisconnect = new Codicon('debug-disconnect', { fontCharacter: '\\ead0' });
Codicon.debugPause = new Codicon('debug-pause', { fontCharacter: '\\ead1' });
Codicon.debugRestart = new Codicon('debug-restart', { fontCharacter: '\\ead2' });
Codicon.debugStart = new Codicon('debug-start', { fontCharacter: '\\ead3' });
Codicon.debugStepInto = new Codicon('debug-step-into', { fontCharacter: '\\ead4' });
Codicon.debugStepOut = new Codicon('debug-step-out', { fontCharacter: '\\ead5' });
Codicon.debugStepOver = new Codicon('debug-step-over', { fontCharacter: '\\ead6' });
Codicon.debugStop = new Codicon('debug-stop', { fontCharacter: '\\ead7' });
Codicon.debug = new Codicon('debug', { fontCharacter: '\\ead8' });
Codicon.deviceCameraVideo = new Codicon('device-camera-video', { fontCharacter: '\\ead9' });
Codicon.deviceCamera = new Codicon('device-camera', { fontCharacter: '\\eada' });
Codicon.deviceMobile = new Codicon('device-mobile', { fontCharacter: '\\eadb' });
Codicon.diffAdded = new Codicon('diff-added', { fontCharacter: '\\eadc' });
Codicon.diffIgnored = new Codicon('diff-ignored', { fontCharacter: '\\eadd' });
Codicon.diffModified = new Codicon('diff-modified', { fontCharacter: '\\eade' });
Codicon.diffRemoved = new Codicon('diff-removed', { fontCharacter: '\\eadf' });
Codicon.diffRenamed = new Codicon('diff-renamed', { fontCharacter: '\\eae0' });
Codicon.diff = new Codicon('diff', { fontCharacter: '\\eae1' });
Codicon.discard = new Codicon('discard', { fontCharacter: '\\eae2' });
Codicon.editorLayout = new Codicon('editor-layout', { fontCharacter: '\\eae3' });
Codicon.emptyWindow = new Codicon('empty-window', { fontCharacter: '\\eae4' });
Codicon.exclude = new Codicon('exclude', { fontCharacter: '\\eae5' });
Codicon.extensions = new Codicon('extensions', { fontCharacter: '\\eae6' });
Codicon.eyeClosed = new Codicon('eye-closed', { fontCharacter: '\\eae7' });
Codicon.fileBinary = new Codicon('file-binary', { fontCharacter: '\\eae8' });
Codicon.fileCode = new Codicon('file-code', { fontCharacter: '\\eae9' });
Codicon.fileMedia = new Codicon('file-media', { fontCharacter: '\\eaea' });
Codicon.filePdf = new Codicon('file-pdf', { fontCharacter: '\\eaeb' });
Codicon.fileSubmodule = new Codicon('file-submodule', { fontCharacter: '\\eaec' });
Codicon.fileSymlinkDirectory = new Codicon('file-symlink-directory', { fontCharacter: '\\eaed' });
Codicon.fileSymlinkFile = new Codicon('file-symlink-file', { fontCharacter: '\\eaee' });
Codicon.fileZip = new Codicon('file-zip', { fontCharacter: '\\eaef' });
Codicon.files = new Codicon('files', { fontCharacter: '\\eaf0' });
Codicon.filter = new Codicon('filter', { fontCharacter: '\\eaf1' });
Codicon.flame = new Codicon('flame', { fontCharacter: '\\eaf2' });
Codicon.foldDown = new Codicon('fold-down', { fontCharacter: '\\eaf3' });
Codicon.foldUp = new Codicon('fold-up', { fontCharacter: '\\eaf4' });
Codicon.fold = new Codicon('fold', { fontCharacter: '\\eaf5' });
Codicon.folderActive = new Codicon('folder-active', { fontCharacter: '\\eaf6' });
Codicon.folderOpened = new Codicon('folder-opened', { fontCharacter: '\\eaf7' });
Codicon.gear = new Codicon('gear', { fontCharacter: '\\eaf8' });
Codicon.gift = new Codicon('gift', { fontCharacter: '\\eaf9' });
Codicon.gistSecret = new Codicon('gist-secret', { fontCharacter: '\\eafa' });
Codicon.gist = new Codicon('gist', { fontCharacter: '\\eafb' });
Codicon.gitCommit = new Codicon('git-commit', { fontCharacter: '\\eafc' });
Codicon.gitCompare = new Codicon('git-compare', { fontCharacter: '\\eafd' });
Codicon.gitMerge = new Codicon('git-merge', { fontCharacter: '\\eafe' });
Codicon.githubAction = new Codicon('github-action', { fontCharacter: '\\eaff' });
Codicon.githubAlt = new Codicon('github-alt', { fontCharacter: '\\eb00' });
Codicon.globe = new Codicon('globe', { fontCharacter: '\\eb01' });
Codicon.grabber = new Codicon('grabber', { fontCharacter: '\\eb02' });
Codicon.graph = new Codicon('graph', { fontCharacter: '\\eb03' });
Codicon.gripper = new Codicon('gripper', { fontCharacter: '\\eb04' });
Codicon.heart = new Codicon('heart', { fontCharacter: '\\eb05' });
Codicon.home = new Codicon('home', { fontCharacter: '\\eb06' });
Codicon.horizontalRule = new Codicon('horizontal-rule', { fontCharacter: '\\eb07' });
Codicon.hubot = new Codicon('hubot', { fontCharacter: '\\eb08' });
Codicon.inbox = new Codicon('inbox', { fontCharacter: '\\eb09' });
Codicon.issueClosed = new Codicon('issue-closed', { fontCharacter: '\\eba4' });
Codicon.issueReopened = new Codicon('issue-reopened', { fontCharacter: '\\eb0b' });
Codicon.issues = new Codicon('issues', { fontCharacter: '\\eb0c' });
Codicon.italic = new Codicon('italic', { fontCharacter: '\\eb0d' });
Codicon.jersey = new Codicon('jersey', { fontCharacter: '\\eb0e' });
Codicon.json = new Codicon('json', { fontCharacter: '\\eb0f' });
Codicon.kebabVertical = new Codicon('kebab-vertical', { fontCharacter: '\\eb10' });
Codicon.key = new Codicon('key', { fontCharacter: '\\eb11' });
Codicon.law = new Codicon('law', { fontCharacter: '\\eb12' });
Codicon.lightbulbAutofix = new Codicon('lightbulb-autofix', { fontCharacter: '\\eb13' });
Codicon.linkExternal = new Codicon('link-external', { fontCharacter: '\\eb14' });
Codicon.link = new Codicon('link', { fontCharacter: '\\eb15' });
Codicon.listOrdered = new Codicon('list-ordered', { fontCharacter: '\\eb16' });
Codicon.listUnordered = new Codicon('list-unordered', { fontCharacter: '\\eb17' });
Codicon.liveShare = new Codicon('live-share', { fontCharacter: '\\eb18' });
Codicon.loading = new Codicon('loading', { fontCharacter: '\\eb19' });
Codicon.location = new Codicon('location', { fontCharacter: '\\eb1a' });
Codicon.mailRead = new Codicon('mail-read', { fontCharacter: '\\eb1b' });
Codicon.mail = new Codicon('mail', { fontCharacter: '\\eb1c' });
Codicon.markdown = new Codicon('markdown', { fontCharacter: '\\eb1d' });
Codicon.megaphone = new Codicon('megaphone', { fontCharacter: '\\eb1e' });
Codicon.mention = new Codicon('mention', { fontCharacter: '\\eb1f' });
Codicon.milestone = new Codicon('milestone', { fontCharacter: '\\eb20' });
Codicon.mortarBoard = new Codicon('mortar-board', { fontCharacter: '\\eb21' });
Codicon.move = new Codicon('move', { fontCharacter: '\\eb22' });
Codicon.multipleWindows = new Codicon('multiple-windows', { fontCharacter: '\\eb23' });
Codicon.mute = new Codicon('mute', { fontCharacter: '\\eb24' });
Codicon.noNewline = new Codicon('no-newline', { fontCharacter: '\\eb25' });
Codicon.note = new Codicon('note', { fontCharacter: '\\eb26' });
Codicon.octoface = new Codicon('octoface', { fontCharacter: '\\eb27' });
Codicon.openPreview = new Codicon('open-preview', { fontCharacter: '\\eb28' });
Codicon.package_ = new Codicon('package', { fontCharacter: '\\eb29' });
Codicon.paintcan = new Codicon('paintcan', { fontCharacter: '\\eb2a' });
Codicon.pin = new Codicon('pin', { fontCharacter: '\\eb2b' });
Codicon.play = new Codicon('play', { fontCharacter: '\\eb2c' });
Codicon.run = new Codicon('run', { fontCharacter: '\\eb2c' });
Codicon.plug = new Codicon('plug', { fontCharacter: '\\eb2d' });
Codicon.preserveCase = new Codicon('preserve-case', { fontCharacter: '\\eb2e' });
Codicon.preview = new Codicon('preview', { fontCharacter: '\\eb2f' });
Codicon.project = new Codicon('project', { fontCharacter: '\\eb30' });
Codicon.pulse = new Codicon('pulse', { fontCharacter: '\\eb31' });
Codicon.question = new Codicon('question', { fontCharacter: '\\eb32' });
Codicon.quote = new Codicon('quote', { fontCharacter: '\\eb33' });
Codicon.radioTower = new Codicon('radio-tower', { fontCharacter: '\\eb34' });
Codicon.reactions = new Codicon('reactions', { fontCharacter: '\\eb35' });
Codicon.references = new Codicon('references', { fontCharacter: '\\eb36' });
Codicon.refresh = new Codicon('refresh', { fontCharacter: '\\eb37' });
Codicon.regex = new Codicon('regex', { fontCharacter: '\\eb38' });
Codicon.remoteExplorer = new Codicon('remote-explorer', { fontCharacter: '\\eb39' });
Codicon.remote = new Codicon('remote', { fontCharacter: '\\eb3a' });
Codicon.remove = new Codicon('remove', { fontCharacter: '\\eb3b' });
Codicon.replaceAll = new Codicon('replace-all', { fontCharacter: '\\eb3c' });
Codicon.replace = new Codicon('replace', { fontCharacter: '\\eb3d' });
Codicon.repoClone = new Codicon('repo-clone', { fontCharacter: '\\eb3e' });
Codicon.repoForcePush = new Codicon('repo-force-push', { fontCharacter: '\\eb3f' });
Codicon.repoPull = new Codicon('repo-pull', { fontCharacter: '\\eb40' });
Codicon.repoPush = new Codicon('repo-push', { fontCharacter: '\\eb41' });
Codicon.report = new Codicon('report', { fontCharacter: '\\eb42' });
Codicon.requestChanges = new Codicon('request-changes', { fontCharacter: '\\eb43' });
Codicon.rocket = new Codicon('rocket', { fontCharacter: '\\eb44' });
Codicon.rootFolderOpened = new Codicon('root-folder-opened', { fontCharacter: '\\eb45' });
Codicon.rootFolder = new Codicon('root-folder', { fontCharacter: '\\eb46' });
Codicon.rss = new Codicon('rss', { fontCharacter: '\\eb47' });
Codicon.ruby = new Codicon('ruby', { fontCharacter: '\\eb48' });
Codicon.saveAll = new Codicon('save-all', { fontCharacter: '\\eb49' });
Codicon.saveAs = new Codicon('save-as', { fontCharacter: '\\eb4a' });
Codicon.save = new Codicon('save', { fontCharacter: '\\eb4b' });
Codicon.screenFull = new Codicon('screen-full', { fontCharacter: '\\eb4c' });
Codicon.screenNormal = new Codicon('screen-normal', { fontCharacter: '\\eb4d' });
Codicon.searchStop = new Codicon('search-stop', { fontCharacter: '\\eb4e' });
Codicon.server = new Codicon('server', { fontCharacter: '\\eb50' });
Codicon.settingsGear = new Codicon('settings-gear', { fontCharacter: '\\eb51' });
Codicon.settings = new Codicon('settings', { fontCharacter: '\\eb52' });
Codicon.shield = new Codicon('shield', { fontCharacter: '\\eb53' });
Codicon.smiley = new Codicon('smiley', { fontCharacter: '\\eb54' });
Codicon.sortPrecedence = new Codicon('sort-precedence', { fontCharacter: '\\eb55' });
Codicon.splitHorizontal = new Codicon('split-horizontal', { fontCharacter: '\\eb56' });
Codicon.splitVertical = new Codicon('split-vertical', { fontCharacter: '\\eb57' });
Codicon.squirrel = new Codicon('squirrel', { fontCharacter: '\\eb58' });
Codicon.starFull = new Codicon('star-full', { fontCharacter: '\\eb59' });
Codicon.starHalf = new Codicon('star-half', { fontCharacter: '\\eb5a' });
Codicon.symbolClass = new Codicon('symbol-class', { fontCharacter: '\\eb5b' });
Codicon.symbolColor = new Codicon('symbol-color', { fontCharacter: '\\eb5c' });
Codicon.symbolConstant = new Codicon('symbol-constant', { fontCharacter: '\\eb5d' });
Codicon.symbolEnumMember = new Codicon('symbol-enum-member', { fontCharacter: '\\eb5e' });
Codicon.symbolField = new Codicon('symbol-field', { fontCharacter: '\\eb5f' });
Codicon.symbolFile = new Codicon('symbol-file', { fontCharacter: '\\eb60' });
Codicon.symbolInterface = new Codicon('symbol-interface', { fontCharacter: '\\eb61' });
Codicon.symbolKeyword = new Codicon('symbol-keyword', { fontCharacter: '\\eb62' });
Codicon.symbolMisc = new Codicon('symbol-misc', { fontCharacter: '\\eb63' });
Codicon.symbolOperator = new Codicon('symbol-operator', { fontCharacter: '\\eb64' });
Codicon.symbolProperty = new Codicon('symbol-property', { fontCharacter: '\\eb65' });
Codicon.wrench = new Codicon('wrench', { fontCharacter: '\\eb65' });
Codicon.wrenchSubaction = new Codicon('wrench-subaction', { fontCharacter: '\\eb65' });
Codicon.symbolSnippet = new Codicon('symbol-snippet', { fontCharacter: '\\eb66' });
Codicon.tasklist = new Codicon('tasklist', { fontCharacter: '\\eb67' });
Codicon.telescope = new Codicon('telescope', { fontCharacter: '\\eb68' });
Codicon.textSize = new Codicon('text-size', { fontCharacter: '\\eb69' });
Codicon.threeBars = new Codicon('three-bars', { fontCharacter: '\\eb6a' });
Codicon.thumbsdown = new Codicon('thumbsdown', { fontCharacter: '\\eb6b' });
Codicon.thumbsup = new Codicon('thumbsup', { fontCharacter: '\\eb6c' });
Codicon.tools = new Codicon('tools', { fontCharacter: '\\eb6d' });
Codicon.triangleDown = new Codicon('triangle-down', { fontCharacter: '\\eb6e' });
Codicon.triangleLeft = new Codicon('triangle-left', { fontCharacter: '\\eb6f' });
Codicon.triangleRight = new Codicon('triangle-right', { fontCharacter: '\\eb70' });
Codicon.triangleUp = new Codicon('triangle-up', { fontCharacter: '\\eb71' });
Codicon.twitter = new Codicon('twitter', { fontCharacter: '\\eb72' });
Codicon.unfold = new Codicon('unfold', { fontCharacter: '\\eb73' });
Codicon.unlock = new Codicon('unlock', { fontCharacter: '\\eb74' });
Codicon.unmute = new Codicon('unmute', { fontCharacter: '\\eb75' });
Codicon.unverified = new Codicon('unverified', { fontCharacter: '\\eb76' });
Codicon.verified = new Codicon('verified', { fontCharacter: '\\eb77' });
Codicon.versions = new Codicon('versions', { fontCharacter: '\\eb78' });
Codicon.vmActive = new Codicon('vm-active', { fontCharacter: '\\eb79' });
Codicon.vmOutline = new Codicon('vm-outline', { fontCharacter: '\\eb7a' });
Codicon.vmRunning = new Codicon('vm-running', { fontCharacter: '\\eb7b' });
Codicon.watch = new Codicon('watch', { fontCharacter: '\\eb7c' });
Codicon.whitespace = new Codicon('whitespace', { fontCharacter: '\\eb7d' });
Codicon.wholeWord = new Codicon('whole-word', { fontCharacter: '\\eb7e' });
Codicon.window = new Codicon('window', { fontCharacter: '\\eb7f' });
Codicon.wordWrap = new Codicon('word-wrap', { fontCharacter: '\\eb80' });
Codicon.zoomIn = new Codicon('zoom-in', { fontCharacter: '\\eb81' });
Codicon.zoomOut = new Codicon('zoom-out', { fontCharacter: '\\eb82' });
Codicon.listFilter = new Codicon('list-filter', { fontCharacter: '\\eb83' });
Codicon.listFlat = new Codicon('list-flat', { fontCharacter: '\\eb84' });
Codicon.listSelection = new Codicon('list-selection', { fontCharacter: '\\eb85' });
Codicon.selection = new Codicon('selection', { fontCharacter: '\\eb85' });
Codicon.listTree = new Codicon('list-tree', { fontCharacter: '\\eb86' });
Codicon.debugBreakpointFunctionUnverified = new Codicon('debug-breakpoint-function-unverified', { fontCharacter: '\\eb87' });
Codicon.debugBreakpointFunction = new Codicon('debug-breakpoint-function', { fontCharacter: '\\eb88' });
Codicon.debugBreakpointFunctionDisabled = new Codicon('debug-breakpoint-function-disabled', { fontCharacter: '\\eb88' });
Codicon.debugStackframeActive = new Codicon('debug-stackframe-active', { fontCharacter: '\\eb89' });
Codicon.debugStackframeDot = new Codicon('debug-stackframe-dot', { fontCharacter: '\\eb8a' });
Codicon.debugStackframe = new Codicon('debug-stackframe', { fontCharacter: '\\eb8b' });
Codicon.debugStackframeFocused = new Codicon('debug-stackframe-focused', { fontCharacter: '\\eb8b' });
Codicon.debugBreakpointUnsupported = new Codicon('debug-breakpoint-unsupported', { fontCharacter: '\\eb8c' });
Codicon.symbolString = new Codicon('symbol-string', { fontCharacter: '\\eb8d' });
Codicon.debugReverseContinue = new Codicon('debug-reverse-continue', { fontCharacter: '\\eb8e' });
Codicon.debugStepBack = new Codicon('debug-step-back', { fontCharacter: '\\eb8f' });
Codicon.debugRestartFrame = new Codicon('debug-restart-frame', { fontCharacter: '\\eb90' });
Codicon.callIncoming = new Codicon('call-incoming', { fontCharacter: '\\eb92' });
Codicon.callOutgoing = new Codicon('call-outgoing', { fontCharacter: '\\eb93' });
Codicon.menu = new Codicon('menu', { fontCharacter: '\\eb94' });
Codicon.expandAll = new Codicon('expand-all', { fontCharacter: '\\eb95' });
Codicon.feedback = new Codicon('feedback', { fontCharacter: '\\eb96' });
Codicon.groupByRefType = new Codicon('group-by-ref-type', { fontCharacter: '\\eb97' });
Codicon.ungroupByRefType = new Codicon('ungroup-by-ref-type', { fontCharacter: '\\eb98' });
Codicon.account = new Codicon('account', { fontCharacter: '\\eb99' });
Codicon.bellDot = new Codicon('bell-dot', { fontCharacter: '\\eb9a' });
Codicon.debugConsole = new Codicon('debug-console', { fontCharacter: '\\eb9b' });
Codicon.library = new Codicon('library', { fontCharacter: '\\eb9c' });
Codicon.output = new Codicon('output', { fontCharacter: '\\eb9d' });
Codicon.runAll = new Codicon('run-all', { fontCharacter: '\\eb9e' });
Codicon.syncIgnored = new Codicon('sync-ignored', { fontCharacter: '\\eb9f' });
Codicon.pinned = new Codicon('pinned', { fontCharacter: '\\eba0' });
Codicon.githubInverted = new Codicon('github-inverted', { fontCharacter: '\\eba1' });
Codicon.debugAlt = new Codicon('debug-alt', { fontCharacter: '\\eb91' });
Codicon.serverProcess = new Codicon('server-process', { fontCharacter: '\\eba2' });
Codicon.serverEnvironment = new Codicon('server-environment', { fontCharacter: '\\eba3' });
Codicon.pass = new Codicon('pass', { fontCharacter: '\\eba4' });
Codicon.stopCircle = new Codicon('stop-circle', { fontCharacter: '\\eba5' });
Codicon.playCircle = new Codicon('play-circle', { fontCharacter: '\\eba6' });
Codicon.record = new Codicon('record', { fontCharacter: '\\eba7' });
Codicon.debugAltSmall = new Codicon('debug-alt-small', { fontCharacter: '\\eba8' });
Codicon.vmConnect = new Codicon('vm-connect', { fontCharacter: '\\eba9' });
Codicon.cloud = new Codicon('cloud', { fontCharacter: '\\ebaa' });
Codicon.merge = new Codicon('merge', { fontCharacter: '\\ebab' });
Codicon.exportIcon = new Codicon('export', { fontCharacter: '\\ebac' });
Codicon.graphLeft = new Codicon('graph-left', { fontCharacter: '\\ebad' });
Codicon.magnet = new Codicon('magnet', { fontCharacter: '\\ebae' });
Codicon.notebook = new Codicon('notebook', { fontCharacter: '\\ebaf' });
Codicon.redo = new Codicon('redo', { fontCharacter: '\\ebb0' });
Codicon.checkAll = new Codicon('check-all', { fontCharacter: '\\ebb1' });
Codicon.pinnedDirty = new Codicon('pinned-dirty', { fontCharacter: '\\ebb2' });
Codicon.passFilled = new Codicon('pass-filled', { fontCharacter: '\\ebb3' });
Codicon.circleLargeFilled = new Codicon('circle-large-filled', { fontCharacter: '\\ebb4' });
Codicon.circleLargeOutline = new Codicon('circle-large-outline', { fontCharacter: '\\ebb5' });
Codicon.combine = new Codicon('combine', { fontCharacter: '\\ebb6' });
Codicon.gather = new Codicon('gather', { fontCharacter: '\\ebb6' });
Codicon.table = new Codicon('table', { fontCharacter: '\\ebb7' });
Codicon.variableGroup = new Codicon('variable-group', { fontCharacter: '\\ebb8' });
Codicon.typeHierarchy = new Codicon('type-hierarchy', { fontCharacter: '\\ebb9' });
Codicon.typeHierarchySub = new Codicon('type-hierarchy-sub', { fontCharacter: '\\ebba' });
Codicon.typeHierarchySuper = new Codicon('type-hierarchy-super', { fontCharacter: '\\ebbb' });
Codicon.gitPullRequestCreate = new Codicon('git-pull-request-create', { fontCharacter: '\\ebbc' });
Codicon.runAbove = new Codicon('run-above', { fontCharacter: '\\ebbd' });
Codicon.runBelow = new Codicon('run-below', { fontCharacter: '\\ebbe' });
Codicon.notebookTemplate = new Codicon('notebook-template', { fontCharacter: '\\ebbf' });
Codicon.debugRerun = new Codicon('debug-rerun', { fontCharacter: '\\ebc0' });
Codicon.workspaceTrusted = new Codicon('workspace-trusted', { fontCharacter: '\\ebc1' });
Codicon.workspaceUntrusted = new Codicon('workspace-untrusted', { fontCharacter: '\\ebc2' });
Codicon.workspaceUnspecified = new Codicon('workspace-unspecified', { fontCharacter: '\\ebc3' });
Codicon.terminalCmd = new Codicon('terminal-cmd', { fontCharacter: '\\ebc4' });
Codicon.terminalDebian = new Codicon('terminal-debian', { fontCharacter: '\\ebc5' });
Codicon.terminalLinux = new Codicon('terminal-linux', { fontCharacter: '\\ebc6' });
Codicon.terminalPowershell = new Codicon('terminal-powershell', { fontCharacter: '\\ebc7' });
Codicon.terminalTmux = new Codicon('terminal-tmux', { fontCharacter: '\\ebc8' });
Codicon.terminalUbuntu = new Codicon('terminal-ubuntu', { fontCharacter: '\\ebc9' });
Codicon.terminalBash = new Codicon('terminal-bash', { fontCharacter: '\\ebca' });
Codicon.arrowSwap = new Codicon('arrow-swap', { fontCharacter: '\\ebcb' });
Codicon.copy = new Codicon('copy', { fontCharacter: '\\ebcc' });
Codicon.personAdd = new Codicon('person-add', { fontCharacter: '\\ebcd' });
Codicon.filterFilled = new Codicon('filter-filled', { fontCharacter: '\\ebce' });
Codicon.wand = new Codicon('wand', { fontCharacter: '\\ebcf' });
Codicon.debugLineByLine = new Codicon('debug-line-by-line', { fontCharacter: '\\ebd0' });
Codicon.inspect = new Codicon('inspect', { fontCharacter: '\\ebd1' });
Codicon.layers = new Codicon('layers', { fontCharacter: '\\ebd2' });
Codicon.layersDot = new Codicon('layers-dot', { fontCharacter: '\\ebd3' });
Codicon.layersActive = new Codicon('layers-active', { fontCharacter: '\\ebd4' });
Codicon.compass = new Codicon('compass', { fontCharacter: '\\ebd5' });
Codicon.compassDot = new Codicon('compass-dot', { fontCharacter: '\\ebd6' });
Codicon.compassActive = new Codicon('compass-active', { fontCharacter: '\\ebd7' });
Codicon.azure = new Codicon('azure', { fontCharacter: '\\ebd8' });
Codicon.issueDraft = new Codicon('issue-draft', { fontCharacter: '\\ebd9' });
Codicon.gitPullRequestClosed = new Codicon('git-pull-request-closed', { fontCharacter: '\\ebda' });
Codicon.gitPullRequestDraft = new Codicon('git-pull-request-draft', { fontCharacter: '\\ebdb' });
Codicon.debugAll = new Codicon('debug-all', { fontCharacter: '\\ebdc' });
Codicon.debugCoverage = new Codicon('debug-coverage', { fontCharacter: '\\ebdd' });
Codicon.dropDownButton = new Codicon('drop-down-button', Codicon.chevronDown.definition);
})(Codicon = exports.Codicon || (exports.Codicon = {}));
});
/*---------------------------------------------------------------------------------------------
* 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/base/browser/ui/tree/treeIcons*/], __M([0/*require*/,1/*exports*/,27/*vs/base/common/codicons*/]), function (require, exports, codicons_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.treeItemLoadingIcon = exports.treeFilterClearIcon = exports.treeFilterOnTypeOffIcon = exports.treeFilterOnTypeOnIcon = exports.treeItemExpandedIcon = void 0;
exports.treeItemExpandedIcon = (0, codicons_1.registerCodicon)('tree-item-expanded', codicons_1.Codicon.chevronDown); // collapsed is done with rotation
exports.treeFilterOnTypeOnIcon = (0, codicons_1.registerCodicon)('tree-filter-on-type-on', codicons_1.Codicon.listFilter);
exports.treeFilterOnTypeOffIcon = (0, codicons_1.registerCodicon)('tree-filter-on-type-off', codicons_1.Codicon.listSelection);
exports.treeFilterClearIcon = (0, codicons_1.registerCodicon)('tree-filter-clear', codicons_1.Codicon.close);
exports.treeItemLoadingIcon = (0, codicons_1.registerCodicon)('tree-item-loading', codicons_1.Codicon.loading);
});
define(__m[291/*vs/base/common/comparers*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/]), function (require, exports, async_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compareByPrefix = exports.compareAnything = exports.compareFileNames = void 0;
// 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 async_1.IdleValue(() => {
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
return {
collator: collator,
collatorIsNumeric: collator.resolvedOptions().numeric
};
});
/** 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;
}
exports.compareFileNames = compareFileNames;
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);
}
exports.compareAnything = compareAnything;
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;
}
exports.compareByPrefix = compareByPrefix;
});
/*---------------------------------------------------------------------------------------------
* 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/scrollable*/], __M([0/*require*/,1/*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(width, scrollWidth, scrollLeft, height, scrollHeight, scrollTop) {
this._scrollStateBrand = undefined;
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((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.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(smoothScrollDuration, scheduleAtNextAnimationFrame) {
super();
this._scrollableBrand = undefined;
this._onScroll = this._register(new event_1.Emitter());
this.onScroll = this._onScroll.event;
this._smoothScrollDuration = smoothScrollDuration;
this._scheduleAtNextAnimationFrame = scheduleAtNextAnimationFrame;
this._state = new ScrollState(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
if (this._smoothScrolling) {
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();
});
}
_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[8/*vs/base/common/strings*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLeftDeleteOffset = exports.breakBetweenGraphemeBreakType = exports.getGraphemeBreakType = exports.singleLetterHash = exports.containsUppercaseCharacter = exports.startsWithUTF8BOM = exports.UTF8_BOM_CHARACTER = exports.isEmojiImprecise = exports.isFullWidthCharacter = exports.containsFullWidthCharacter = exports.containsUnusualLineTerminators = exports.UNUSUAL_LINE_TERMINATORS = exports.isBasicASCII = exports.containsEmoji = exports.containsRTL = exports.decodeUTF8 = exports.prevCharLength = exports.nextCharLength = exports.getNextCodePoint = exports.computeCodePoint = exports.isLowSurrogate = exports.isHighSurrogate = exports.commonSuffixLength = exports.commonPrefixLength = exports.startsWithIgnoreCase = exports.equalsIgnoreCase = exports.isUpperAsciiLetter = exports.isLowerAsciiLetter = exports.compareSubstringIgnoreCase = exports.compareIgnoreCase = exports.compareSubstring = exports.compare = exports.lastNonWhitespaceIndex = exports.getLeadingWhitespace = exports.firstNonWhitespaceIndex = exports.splitLines = exports.regExpFlags = exports.regExpLeadsToEndlessLoop = exports.createRegExp = exports.stripWildcards = exports.convertSimple2RegExpPattern = exports.rtrim = exports.ltrim = exports.trim = exports.escapeRegExpCharacters = exports.escape = exports.format = exports.isFalsyOrWhitespace = void 0;
function isFalsyOrWhitespace(str) {
if (!str || typeof str !== 'string') {
return true;
}
return str.trim().length === 0;
}
exports.isFalsyOrWhitespace = isFalsyOrWhitespace;
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];
});
}
exports.format = format;
/**
* 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;
}
});
}
exports.escape = escape;
/**
* Escapes regular expression characters in a given string
*/
function escapeRegExpCharacters(value) {
return value.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g, '\\$&');
}
exports.escapeRegExpCharacters = escapeRegExpCharacters;
/**
* 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);
}
exports.trim = trim;
/**
* 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);
}
exports.ltrim = ltrim;
/**
* 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);
}
exports.rtrim = rtrim;
function convertSimple2RegExpPattern(pattern) {
return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*');
}
exports.convertSimple2RegExpPattern = convertSimple2RegExpPattern;
function stripWildcards(pattern) {
return pattern.replace(/\*/g, '');
}
exports.stripWildcards = stripWildcards;
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);
}
exports.createRegExp = createRegExp;
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);
}
exports.regExpLeadsToEndlessLoop = regExpLeadsToEndlessLoop;
function regExpFlags(regexp) {
return (regexp.global ? 'g' : '')
+ (regexp.ignoreCase ? 'i' : '')
+ (regexp.multiline ? 'm' : '')
+ (regexp /* standalone editor compilation */.unicode ? 'u' : '');
}
exports.regExpFlags = regExpFlags;
function splitLines(str) {
return str.split(/\r\n|\r|\n/);
}
exports.splitLines = splitLines;
/**
* 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 /* Space */ && chCode !== 9 /* Tab */) {
return i;
}
}
return -1;
}
exports.firstNonWhitespaceIndex = firstNonWhitespaceIndex;
/**
* 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 /* Space */ && chCode !== 9 /* Tab */) {
return str.substring(start, i);
}
}
return str.substring(start, end);
}
exports.getLeadingWhitespace = getLeadingWhitespace;
/**
* 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 /* Space */ && chCode !== 9 /* Tab */) {
return i;
}
}
return -1;
}
exports.lastNonWhitespaceIndex = lastNonWhitespaceIndex;
function compare(a, b) {
if (a < b) {
return -1;
}
else if (a > b) {
return 1;
}
else {
return 0;
}
}
exports.compare = compare;
function compareSubstring(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) {
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;
}
exports.compareSubstring = compareSubstring;
function compareIgnoreCase(a, b) {
return compareSubstringIgnoreCase(a, b, 0, a.length, 0, b.length);
}
exports.compareIgnoreCase = compareIgnoreCase;
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;
}
const diff = codeA - codeB;
if (diff === 32 && isUpperAsciiLetter(codeB)) { //codeB =[65-90] && codeA =[97-122]
continue;
}
else if (diff === -32 && isUpperAsciiLetter(codeA)) { //codeB =[97-122] && codeA =[65-90]
continue;
}
if (isLowerAsciiLetter(codeA) && isLowerAsciiLetter(codeB)) {
//
return diff;
}
else {
return compareSubstring(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd);
}
}
const aLen = aEnd - aStart;
const bLen = bEnd - bStart;
if (aLen < bLen) {
return -1;
}
else if (aLen > bLen) {
return 1;
}
return 0;
}
exports.compareSubstringIgnoreCase = compareSubstringIgnoreCase;
function isLowerAsciiLetter(code) {
return code >= 97 /* a */ && code <= 122 /* z */;
}
exports.isLowerAsciiLetter = isLowerAsciiLetter;
function isUpperAsciiLetter(code) {
return code >= 65 /* A */ && code <= 90 /* Z */;
}
exports.isUpperAsciiLetter = isUpperAsciiLetter;
function isAsciiLetter(code) {
return isLowerAsciiLetter(code) || isUpperAsciiLetter(code);
}
function equalsIgnoreCase(a, b) {
return a.length === b.length && doEqualsIgnoreCase(a, b);
}
exports.equalsIgnoreCase = equalsIgnoreCase;
function doEqualsIgnoreCase(a, b, stopAt = a.length) {
for (let i = 0; i < stopAt; i++) {
const codeA = a.charCodeAt(i);
const codeB = b.charCodeAt(i);
if (codeA === codeB) {
continue;
}
// a-z A-Z
if (isAsciiLetter(codeA) && isAsciiLetter(codeB)) {
const diff = Math.abs(codeA - codeB);
if (diff !== 0 && diff !== 32) {
return false;
}
}
// Any other charcode
else {
if (String.fromCharCode(codeA).toLowerCase() !== String.fromCharCode(codeB).toLowerCase()) {
return false;
}
}
}
return true;
}
function startsWithIgnoreCase(str, candidate) {
const candidateLength = candidate.length;
if (candidate.length > str.length) {
return false;
}
return doEqualsIgnoreCase(str, candidate, candidateLength);
}
exports.startsWithIgnoreCase = startsWithIgnoreCase;
/**
* @returns the length of the common prefix of the two strings.
*/
function commonPrefixLength(a, b) {
let i, len = Math.min(a.length, b.length);
for (i = 0; i < len; i++) {
if (a.charCodeAt(i) !== b.charCodeAt(i)) {
return i;
}
}
return len;
}
exports.commonPrefixLength = commonPrefixLength;
/**
* @returns the length of the common suffix of the two strings.
*/
function commonSuffixLength(a, b) {
let i, len = Math.min(a.length, b.length);
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;
}
exports.commonSuffixLength = commonSuffixLength;
/**
* See http://en.wikipedia.org/wiki/Surrogate_pair
*/
function isHighSurrogate(charCode) {
return (0xD800 <= charCode && charCode <= 0xDBFF);
}
exports.isHighSurrogate = isHighSurrogate;
/**
* See http://en.wikipedia.org/wiki/Surrogate_pair
*/
function isLowSurrogate(charCode) {
return (0xDC00 <= charCode && charCode <= 0xDFFF);
}
exports.isLowSurrogate = isLowSurrogate;
/**
* See http://en.wikipedia.org/wiki/Surrogate_pair
*/
function computeCodePoint(highSurrogate, lowSurrogate) {
return ((highSurrogate - 0xD800) << 10) + (lowSurrogate - 0xDC00) + 0x10000;
}
exports.computeCodePoint = computeCodePoint;
/**
* 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;
}
exports.getNextCodePoint = getNextCodePoint;
/**
* 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;
}
function nextCharLength(str, offset) {
const graphemeBreakTree = GraphemeBreakTree.getInstance();
const initialOffset = offset;
const len = str.length;
const initialCodePoint = getNextCodePoint(str, len, offset);
offset += (initialCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(initialCodePoint);
while (offset < len) {
const nextCodePoint = getNextCodePoint(str, len, offset);
const nextGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(nextCodePoint);
if (breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) {
break;
}
offset += (nextCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
graphemeBreakType = nextGraphemeBreakType;
}
return (offset - initialOffset);
}
exports.nextCharLength = nextCharLength;
function prevCharLength(str, offset) {
const graphemeBreakTree = GraphemeBreakTree.getInstance();
const initialOffset = offset;
const initialCodePoint = getPrevCodePoint(str, offset);
offset -= (initialCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(initialCodePoint);
while (offset > 0) {
const prevCodePoint = getPrevCodePoint(str, offset);
const prevGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(prevCodePoint);
if (breakBetweenGraphemeBreakType(prevGraphemeBreakType, graphemeBreakType)) {
break;
}
offset -= (prevCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
graphemeBreakType = prevGraphemeBreakType;
}
return (initialOffset - offset);
}
exports.prevCharLength = prevCharLength;
/**
* A manual decoding of a UTF8 string.
* Use only in environments which do not offer native conversion methods!
*/
function decodeUTF8(buffer) {
// https://en.wikipedia.org/wiki/UTF-8
const len = buffer.byteLength;
const result = [];
let offset = 0;
while (offset < len) {
const v0 = buffer[offset];
let codePoint;
if (v0 >= 0b11110000 && offset + 3 < len) {
// 4 bytes
codePoint = ((((buffer[offset++] & 0b00000111) << 18) >>> 0)
| (((buffer[offset++] & 0b00111111) << 12) >>> 0)
| (((buffer[offset++] & 0b00111111) << 6) >>> 0)
| (((buffer[offset++] & 0b00111111) << 0) >>> 0));
}
else if (v0 >= 0b11100000 && offset + 2 < len) {
// 3 bytes
codePoint = ((((buffer[offset++] & 0b00001111) << 12) >>> 0)
| (((buffer[offset++] & 0b00111111) << 6) >>> 0)
| (((buffer[offset++] & 0b00111111) << 0) >>> 0));
}
else if (v0 >= 0b11000000 && offset + 1 < len) {
// 2 bytes
codePoint = ((((buffer[offset++] & 0b00011111) << 6) >>> 0)
| (((buffer[offset++] & 0b00111111) << 0) >>> 0));
}
else {
// 1 byte
codePoint = buffer[offset++];
}
if ((codePoint >= 0 && codePoint <= 0xD7FF) || (codePoint >= 0xE000 && codePoint <= 0xFFFF)) {
// Basic Multilingual Plane
result.push(String.fromCharCode(codePoint));
}
else if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
// Supplementary Planes
const uPrime = codePoint - 0x10000;
const w1 = 0xD800 + ((uPrime & 0b11111111110000000000) >>> 10);
const w2 = 0xDC00 + ((uPrime & 0b00000000001111111111) >>> 0);
result.push(String.fromCharCode(w1));
result.push(String.fromCharCode(w2));
}
else {
// illegal code point
result.push(String.fromCharCode(0xFFFD));
}
}
return result.join('');
}
exports.decodeUTF8 = decodeUTF8;
/**
* Generated using https://github.com/alexdima/unicode-utils/blob/master/generate-rtl-test.js
*/
const CONTAINS_RTL = /(?:[\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-\u0815\u081A\u0824\u0828\u0830-\u0858\u085E-\u08BD\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFD3D\uFD50-\uFDFC\uFE70-\uFEFC]|\uD802[\uDC00-\uDD1B\uDD20-\uDE00\uDE10-\uDE33\uDE40-\uDEE4\uDEEB-\uDF35\uDF40-\uDFFF]|\uD803[\uDC00-\uDCFF]|\uD83A[\uDC00-\uDCCF\uDD00-\uDD43\uDD50-\uDFFF]|\uD83B[\uDC00-\uDEBB])/;
/**
* Returns true if `str` contains any Unicode character that is classified as "R" or "AL".
*/
function containsRTL(str) {
return CONTAINS_RTL.test(str);
}
exports.containsRTL = containsRTL;
/**
* Generated using https://github.com/alexdima/unicode-utils/blob/master/generate-emoji-test.js
*/
const CONTAINS_EMOJI = /(?:[\u231A\u231B\u23F0\u23F3\u2600-\u27BF\u2B50\u2B55]|\uD83C[\uDDE6-\uDDFF\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F\uDE80-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD00-\uDDFF\uDE70-\uDED6])/;
function containsEmoji(str) {
return CONTAINS_EMOJI.test(str);
}
exports.containsEmoji = containsEmoji;
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.isBasicASCII = isBasicASCII;
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);
}
exports.containsUnusualLineTerminators = containsUnusualLineTerminators;
function containsFullWidthCharacter(str) {
for (let i = 0, len = str.length; i < len; i++) {
if (isFullWidthCharacter(str.charCodeAt(i))) {
return true;
}
}
return false;
}
exports.containsFullWidthCharacter = containsFullWidthCharacter;
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
charCode = +charCode; // @perf
return ((charCode >= 0x2E80 && charCode <= 0xD7AF)
|| (charCode >= 0xF900 && charCode <= 0xFAFF)
|| (charCode >= 0xFF01 && charCode <= 0xFF5E));
}
exports.isFullWidthCharacter = isFullWidthCharacter;
/**
* A fast function (therefore imprecise) to check if code points are emojis.
* Generated using https://github.com/alexdima/unicode-utils/blob/master/generate-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 <= 129003) || (x >= 129280 && x <= 129535)
|| (x >= 129648 && x <= 129750));
}
exports.isEmojiImprecise = isEmojiImprecise;
// -- UTF-8 BOM
exports.UTF8_BOM_CHARACTER = String.fromCharCode(65279 /* UTF8_BOM */);
function startsWithUTF8BOM(str) {
return !!(str && str.length > 0 && str.charCodeAt(0) === 65279 /* UTF8_BOM */);
}
exports.startsWithUTF8BOM = startsWithUTF8BOM;
function containsUppercaseCharacter(target, ignoreEscapedChars = false) {
if (!target) {
return false;
}
if (ignoreEscapedChars) {
target = target.replace(/\\./g, '');
}
return target.toLowerCase() !== target;
}
exports.containsUppercaseCharacter = containsUppercaseCharacter;
/**
* Produces 'a'-'z', followed by 'A'-'Z'... followed by 'a'-'z', etc.
*/
function singleLetterHash(n) {
const LETTERS_CNT = (90 /* Z */ - 65 /* A */ + 1);
n = n % (2 * LETTERS_CNT);
if (n < LETTERS_CNT) {
return String.fromCharCode(97 /* a */ + n);
}
return String.fromCharCode(65 /* A */ + n - LETTERS_CNT);
}
exports.singleLetterHash = singleLetterHash;
//#region Unicode Grapheme Break
function getGraphemeBreakType(codePoint) {
const graphemeBreakTree = GraphemeBreakTree.getInstance();
return graphemeBreakTree.getGraphemeBreakType(codePoint);
}
exports.getGraphemeBreakType = getGraphemeBreakType;
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 /* Other */) {
// see https://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakTest-13.0.0d10.html#table
return (breakTypeB !== 5 /* Extend */ && breakTypeB !== 7 /* 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 /* CR */) {
if (breakTypeB === 3 /* LF */) {
return false; // GB3
}
}
if (breakTypeA === 4 /* Control */ || breakTypeA === 2 /* CR */ || breakTypeA === 3 /* LF */) {
return true; // GB4
}
if (breakTypeB === 4 /* Control */ || breakTypeB === 2 /* CR */ || breakTypeB === 3 /* 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 /* L */) {
if (breakTypeB === 8 /* L */ || breakTypeB === 9 /* V */ || breakTypeB === 11 /* LV */ || breakTypeB === 12 /* LVT */) {
return false; // GB6
}
}
if (breakTypeA === 11 /* LV */ || breakTypeA === 9 /* V */) {
if (breakTypeB === 9 /* V */ || breakTypeB === 10 /* T */) {
return false; // GB7
}
}
if (breakTypeA === 12 /* LVT */ || breakTypeA === 10 /* T */) {
if (breakTypeB === 10 /* T */) {
return false; // GB8
}
}
// Do not break before extending characters or ZWJ.
// GB9 × (Extend | ZWJ)
if (breakTypeB === 5 /* Extend */ || breakTypeB === 13 /* 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 /* SpacingMark */) {
return false; // GB9a
}
if (breakTypeA === 1 /* 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 /* ZWJ */ && breakTypeB === 14 /* 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 /* Regional_Indicator */ && breakTypeB === 6 /* Regional_Indicator */) {
// Note: we are not implementing the rule entirely here to avoid introducing states
return false; // GB12 & GB13
}
// GB999 Any ÷ Any
return true;
}
exports.breakBetweenGraphemeBreakType = breakBetweenGraphemeBreakType;
class GraphemeBreakTree {
constructor() {
this._data = getGraphemeBreakRawData();
}
static getInstance() {
if (!GraphemeBreakTree._INSTANCE) {
GraphemeBreakTree._INSTANCE = new GraphemeBreakTree();
}
return GraphemeBreakTree._INSTANCE;
}
getGraphemeBreakType(codePoint) {
// !!! Let's make 7bit ASCII a bit faster: 0..31
if (codePoint < 32) {
if (codePoint === 10 /* LineFeed */) {
return 3 /* LF */;
}
if (codePoint === 13 /* CarriageReturn */) {
return 2 /* CR */;
}
return 4 /* Control */;
}
// !!! Let's make 7bit ASCII a bit faster: 32..126
if (codePoint < 127) {
return 0 /* 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 /* Other */;
}
}
GraphemeBreakTree._INSTANCE = null;
function getGraphemeBreakRawData() {
// generated using https://github.com/alexdima/unicode-utils/blob/master/generate-grapheme-break.js
return JSON.parse('[0,0,0,51592,51592,11,44424,44424,11,72251,72254,5,7150,7150,7,48008,48008,11,55176,55176,11,128420,128420,14,3276,3277,5,9979,9980,14,46216,46216,11,49800,49800,11,53384,53384,11,70726,70726,5,122915,122916,5,129320,129327,14,2558,2558,5,5906,5908,5,9762,9763,14,43360,43388,8,45320,45320,11,47112,47112,11,48904,48904,11,50696,50696,11,52488,52488,11,54280,54280,11,70082,70083,1,71350,71350,7,73111,73111,5,127892,127893,14,128726,128727,14,129473,129474,14,2027,2035,5,2901,2902,5,3784,3789,5,6754,6754,5,8418,8420,5,9877,9877,14,11088,11088,14,44008,44008,5,44872,44872,11,45768,45768,11,46664,46664,11,47560,47560,11,48456,48456,11,49352,49352,11,50248,50248,11,51144,51144,11,52040,52040,11,52936,52936,11,53832,53832,11,54728,54728,11,69811,69814,5,70459,70460,5,71096,71099,7,71998,71998,5,72874,72880,5,119149,119149,7,127374,127374,14,128335,128335,14,128482,128482,14,128765,128767,14,129399,129400,14,129680,129685,14,1476,1477,5,2377,2380,7,2759,2760,5,3137,3140,7,3458,3459,7,4153,4154,5,6432,6434,5,6978,6978,5,7675,7679,5,9723,9726,14,9823,9823,14,9919,9923,14,10035,10036,14,42736,42737,5,43596,43596,5,44200,44200,11,44648,44648,11,45096,45096,11,45544,45544,11,45992,45992,11,46440,46440,11,46888,46888,11,47336,47336,11,47784,47784,11,48232,48232,11,48680,48680,11,49128,49128,11,49576,49576,11,50024,50024,11,50472,50472,11,50920,50920,11,51368,51368,11,51816,51816,11,52264,52264,11,52712,52712,11,53160,53160,11,53608,53608,11,54056,54056,11,54504,54504,11,54952,54952,11,68108,68111,5,69933,69940,5,70197,70197,7,70498,70499,7,70845,70845,5,71229,71229,5,71727,71735,5,72154,72155,5,72344,72345,5,73023,73029,5,94095,94098,5,121403,121452,5,126981,127182,14,127538,127546,14,127990,127990,14,128391,128391,14,128445,128449,14,128500,128505,14,128752,128752,14,129160,129167,14,129356,129356,14,129432,129442,14,129648,129651,14,129751,131069,14,173,173,4,1757,1757,1,2274,2274,1,2494,2494,5,2641,2641,5,2876,2876,5,3014,3016,7,3262,3262,7,3393,3396,5,3570,3571,7,3968,3972,5,4228,4228,7,6086,6086,5,6679,6680,5,6912,6915,5,7080,7081,5,7380,7392,5,8252,8252,14,9096,9096,14,9748,9749,14,9784,9786,14,9833,9850,14,9890,9894,14,9938,9938,14,9999,9999,14,10085,10087,14,12349,12349,14,43136,43137,7,43454,43456,7,43755,43755,7,44088,44088,11,44312,44312,11,44536,44536,11,44760,44760,11,44984,44984,11,45208,45208,11,45432,45432,11,45656,45656,11,45880,45880,11,46104,46104,11,46328,46328,11,46552,46552,11,46776,46776,11,47000,47000,11,47224,47224,11,47448,47448,11,47672,47672,11,47896,47896,11,48120,48120,11,48344,48344,11,48568,48568,11,48792,48792,11,49016,49016,11,49240,49240,11,49464,49464,11,49688,49688,11,49912,49912,11,50136,50136,11,50360,50360,11,50584,50584,11,50808,50808,11,51032,51032,11,51256,51256,11,51480,51480,11,51704,51704,11,51928,51928,11,52152,52152,11,52376,52376,11,52600,52600,11,52824,52824,11,53048,53048,11,53272,53272,11,53496,53496,11,53720,53720,11,53944,53944,11,54168,54168,11,54392,54392,11,54616,54616,11,54840,54840,11,55064,55064,11,65438,65439,5,69633,69633,5,69837,69837,1,70018,70018,7,70188,70190,7,70368,70370,7,70465,70468,7,70712,70719,5,70835,70840,5,70850,70851,5,71132,71133,5,71340,71340,7,71458,71461,5,71985,71989,7,72002,72002,7,72193,72202,5,72281,72283,5,72766,72766,7,72885,72886,5,73104,73105,5,92912,92916,5,113824,113827,4,119173,119179,5,121505,121519,5,125136,125142,5,127279,127279,14,127489,127490,14,127570,127743,14,127900,127901,14,128254,128254,14,128369,128370,14,128400,128400,14,128425,128432,14,128468,128475,14,128489,128494,14,128715,128720,14,128745,128745,14,128759,128760,14,129004,129023,14,129296,129304,14,129340,129342,14,129388,129392,14,129404,129407,14,129454,129455,14,129485,129487,14,129659,129663,14,129719,129727,14,917536,917631,5,13,13,2,1160,1161,5,1564,1564,4,1807,1807,1,2085,2087,5,2363,2363,7,2402,2403,5,2507,2508,7,2622,2624,7,2691,2691,7,2786,2787,5,2881,2884,5,3006,3006,5,3072,3072,5,3170,3171,5,3267,3268,7,3330,3331,7,3406,3406,1,3538,3540,5,3655,3662,5,3897,3897,5,4038,4038,5,4184,4185,5,4352,4447,8,6068,6069,5,6155,6157,5,6448,6449,7,6742,6742,5,6783,6783,5,6966,6970,5,7042,7042,7,7143,7143,7,7212,7219,5,7412,7412,5,8206,8207,4,8294,8303,4,8596,8601,14,9410,9410,14,9742,9742,14,9757,9757,14,9770,9770,14,9794,9794,14,9828,9828,14,9855,9855,14,9882,9882,14,9900,9903,14,9929,9933,14,9963,9967,14,9987,9988,14,10006,10006,14,10062,10062,14,10175,10175,14,11744,11775,5,42607,42607,5,43043,43044,7,43263,43263,5,43444,43445,7,43569,43570,5,43698,43700,5,43766,43766,5,44032,44032,11,44144,44144,11,44256,44256,11,44368,44368,11,44480,44480,11,44592,44592,11,44704,44704,11,44816,44816,11,44928,44928,11,45040,45040,11,45152,45152,11,45264,45264,11,45376,45376,11,45488,45488,11,45600,45600,11,45712,45712,11,45824,45824,11,45936,45936,11,46048,46048,11,46160,46160,11,46272,46272,11,46384,46384,11,46496,46496,11,46608,46608,11,46720,46720,11,46832,46832,11,46944,46944,11,47056,47056,11,47168,47168,11,47280,47280,11,47392,47392,11,47504,47504,11,47616,47616,11,47728,47728,11,47840,47840,11,47952,47952,11,48064,48064,11,48176,48176,11,48288,48288,11,48400,48400,11,48512,48512,11,48624,48624,11,48736,48736,11,48848,48848,11,48960,48960,11,49072,49072,11,49184,49184,11,49296,49296,11,49408,49408,11,49520,49520,11,49632,49632,11,49744,49744,11,49856,49856,11,49968,49968,11,50080,50080,11,50192,50192,11,50304,50304,11,50416,50416,11,50528,50528,11,50640,50640,11,50752,50752,11,50864,50864,11,50976,50976,11,51088,51088,11,51200,51200,11,51312,51312,11,51424,51424,11,51536,51536,11,51648,51648,11,51760,51760,11,51872,51872,11,51984,51984,11,52096,52096,11,52208,52208,11,52320,52320,11,52432,52432,11,52544,52544,11,52656,52656,11,52768,52768,11,52880,52880,11,52992,52992,11,53104,53104,11,53216,53216,11,53328,53328,11,53440,53440,11,53552,53552,11,53664,53664,11,53776,53776,11,53888,53888,11,54000,54000,11,54112,54112,11,54224,54224,11,54336,54336,11,54448,54448,11,54560,54560,11,54672,54672,11,54784,54784,11,54896,54896,11,55008,55008,11,55120,55120,11,64286,64286,5,66272,66272,5,68900,68903,5,69762,69762,7,69817,69818,5,69927,69931,5,70003,70003,5,70070,70078,5,70094,70094,7,70194,70195,7,70206,70206,5,70400,70401,5,70463,70463,7,70475,70477,7,70512,70516,5,70722,70724,5,70832,70832,5,70842,70842,5,70847,70848,5,71088,71089,7,71102,71102,7,71219,71226,5,71231,71232,5,71342,71343,7,71453,71455,5,71463,71467,5,71737,71738,5,71995,71996,5,72000,72000,7,72145,72147,7,72160,72160,5,72249,72249,7,72273,72278,5,72330,72342,5,72752,72758,5,72850,72871,5,72882,72883,5,73018,73018,5,73031,73031,5,73109,73109,5,73461,73462,7,94031,94031,5,94192,94193,7,119142,119142,7,119155,119162,4,119362,119364,5,121476,121476,5,122888,122904,5,123184,123190,5,126976,126979,14,127184,127231,14,127344,127345,14,127405,127461,14,127514,127514,14,127561,127567,14,127778,127779,14,127896,127896,14,127985,127986,14,127995,127999,5,128326,128328,14,128360,128366,14,128378,128378,14,128394,128397,14,128405,128406,14,128422,128423,14,128435,128443,14,128453,128464,14,128479,128480,14,128484,128487,14,128496,128498,14,128640,128709,14,128723,128724,14,128736,128741,14,128747,128748,14,128755,128755,14,128762,128762,14,128981,128991,14,129096,129103,14,129292,129292,14,129311,129311,14,129329,129330,14,129344,129349,14,129360,129374,14,129394,129394,14,129402,129402,14,129413,129425,14,129445,129450,14,129466,129471,14,129483,129483,14,129511,129535,14,129653,129655,14,129667,129670,14,129705,129711,14,129731,129743,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,2307,2307,7,2366,2368,7,2382,2383,7,2434,2435,7,2497,2500,5,2519,2519,5,2563,2563,7,2631,2632,5,2677,2677,5,2750,2752,7,2763,2764,7,2817,2817,5,2879,2879,5,2891,2892,7,2914,2915,5,3008,3008,5,3021,3021,5,3076,3076,5,3146,3149,5,3202,3203,7,3264,3265,7,3271,3272,7,3298,3299,5,3390,3390,5,3402,3404,7,3426,3427,5,3535,3535,5,3544,3550,7,3635,3635,7,3763,3763,7,3893,3893,5,3953,3966,5,3981,3991,5,4145,4145,7,4157,4158,5,4209,4212,5,4237,4237,5,4520,4607,10,5970,5971,5,6071,6077,5,6089,6099,5,6277,6278,5,6439,6440,5,6451,6456,7,6683,6683,5,6744,6750,5,6765,6770,7,6846,6846,5,6964,6964,5,6972,6972,5,7019,7027,5,7074,7077,5,7083,7085,5,7146,7148,7,7154,7155,7,7222,7223,5,7394,7400,5,7416,7417,5,8204,8204,5,8233,8233,4,8288,8292,4,8413,8416,5,8482,8482,14,8986,8987,14,9193,9203,14,9654,9654,14,9733,9733,14,9745,9745,14,9752,9752,14,9760,9760,14,9766,9766,14,9774,9775,14,9792,9792,14,9800,9811,14,9825,9826,14,9831,9831,14,9852,9853,14,9872,9873,14,9880,9880,14,9885,9887,14,9896,9897,14,9906,9916,14,9926,9927,14,9936,9936,14,9941,9960,14,9974,9974,14,9982,9985,14,9992,9997,14,10002,10002,14,10017,10017,14,10055,10055,14,10071,10071,14,10145,10145,14,11013,11015,14,11503,11505,5,12334,12335,5,12951,12951,14,42612,42621,5,43014,43014,5,43047,43047,7,43204,43205,5,43335,43345,5,43395,43395,7,43450,43451,7,43561,43566,5,43573,43574,5,43644,43644,5,43710,43711,5,43758,43759,7,44005,44005,5,44012,44012,7,44060,44060,11,44116,44116,11,44172,44172,11,44228,44228,11,44284,44284,11,44340,44340,11,44396,44396,11,44452,44452,11,44508,44508,11,44564,44564,11,44620,44620,11,44676,44676,11,44732,44732,11,44788,44788,11,44844,44844,11,44900,44900,11,44956,44956,11,45012,45012,11,45068,45068,11,45124,45124,11,45180,45180,11,45236,45236,11,45292,45292,11,45348,45348,11,45404,45404,11,45460,45460,11,45516,45516,11,45572,45572,11,45628,45628,11,45684,45684,11,45740,45740,11,45796,45796,11,45852,45852,11,45908,45908,11,45964,45964,11,46020,46020,11,46076,46076,11,46132,46132,11,46188,46188,11,46244,46244,11,46300,46300,11,46356,46356,11,46412,46412,11,46468,46468,11,46524,46524,11,46580,46580,11,46636,46636,11,46692,46692,11,46748,46748,11,46804,46804,11,46860,46860,11,46916,46916,11,46972,46972,11,47028,47028,11,47084,47084,11,47140,47140,11,47196,47196,11,47252,47252,11,47308,47308,11,47364,47364,11,47420,47420,11,47476,47476,11,47532,47532,11,47588,47588,11,47644,47644,11,47700,47700,11,47756,47756,11,47812,47812,11,47868,47868,11,47924,47924,11,47980,47980,11,48036,48036,11,48092,48092,11,48148,48148,11,48204,48204,11,48260,48260,11,48316,48316,11,48372,48372,11,48428,48428,11,48484,48484,11,48540,48540,11,48596,48596,11,48652,48652,11,48708,48708,11,48764,48764,11,48820,48820,11,48876,48876,11,48932,48932,11,48988,48988,11,49044,49044,11,49100,49100,11,49156,49156,11,49212,49212,11,49268,49268,11,49324,49324,11,49380,49380,11,49436,49436,11,49492,49492,11,49548,49548,11,49604,49604,11,49660,49660,11,49716,49716,11,49772,49772,11,49828,49828,11,49884,49884,11,49940,49940,11,49996,49996,11,50052,50052,11,50108,50108,11,50164,50164,11,50220,50220,11,50276,50276,11,50332,50332,11,50388,50388,11,50444,50444,11,50500,50500,11,50556,50556,11,50612,50612,11,50668,50668,11,50724,50724,11,50780,50780,11,50836,50836,11,50892,50892,11,50948,50948,11,51004,51004,11,51060,51060,11,51116,51116,11,51172,51172,11,51228,51228,11,51284,51284,11,51340,51340,11,51396,51396,11,51452,51452,11,51508,51508,11,51564,51564,11,51620,51620,11,51676,51676,11,51732,51732,11,51788,51788,11,51844,51844,11,51900,51900,11,51956,51956,11,52012,52012,11,52068,52068,11,52124,52124,11,52180,52180,11,52236,52236,11,52292,52292,11,52348,52348,11,52404,52404,11,52460,52460,11,52516,52516,11,52572,52572,11,52628,52628,11,52684,52684,11,52740,52740,11,52796,52796,11,52852,52852,11,52908,52908,11,52964,52964,11,53020,53020,11,53076,53076,11,53132,53132,11,53188,53188,11,53244,53244,11,53300,53300,11,53356,53356,11,53412,53412,11,53468,53468,11,53524,53524,11,53580,53580,11,53636,53636,11,53692,53692,11,53748,53748,11,53804,53804,11,53860,53860,11,53916,53916,11,53972,53972,11,54028,54028,11,54084,54084,11,54140,54140,11,54196,54196,11,54252,54252,11,54308,54308,11,54364,54364,11,54420,54420,11,54476,54476,11,54532,54532,11,54588,54588,11,54644,54644,11,54700,54700,11,54756,54756,11,54812,54812,11,54868,54868,11,54924,54924,11,54980,54980,11,55036,55036,11,55092,55092,11,55148,55148,11,55216,55238,9,65056,65071,5,65529,65531,4,68097,68099,5,68159,68159,5,69446,69456,5,69688,69702,5,69808,69810,7,69815,69816,7,69821,69821,1,69888,69890,5,69932,69932,7,69957,69958,7,70016,70017,5,70067,70069,7,70079,70080,7,70089,70092,5,70095,70095,5,70191,70193,5,70196,70196,5,70198,70199,5,70367,70367,5,70371,70378,5,70402,70403,7,70462,70462,5,70464,70464,5,70471,70472,7,70487,70487,5,70502,70508,5,70709,70711,7,70720,70721,7,70725,70725,7,70750,70750,5,70833,70834,7,70841,70841,7,70843,70844,7,70846,70846,7,70849,70849,7,71087,71087,5,71090,71093,5,71100,71101,5,71103,71104,5,71216,71218,7,71227,71228,7,71230,71230,7,71339,71339,5,71341,71341,5,71344,71349,5,71351,71351,5,71456,71457,7,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,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,123628,123631,5,125252,125258,5,126980,126980,14,127183,127183,14,127245,127247,14,127340,127343,14,127358,127359,14,127377,127386,14,127462,127487,6,127491,127503,14,127535,127535,14,127548,127551,14,127568,127569,14,127744,127777,14,127780,127891,14,127894,127895,14,127897,127899,14,127902,127984,14,127987,127989,14,127991,127994,14,128000,128253,14,128255,128317,14,128329,128334,14,128336,128359,14,128367,128368,14,128371,128377,14,128379,128390,14,128392,128393,14,128398,128399,14,128401,128404,14,128407,128419,14,128421,128421,14,128424,128424,14,128433,128434,14,128444,128444,14,128450,128452,14,128465,128467,14,128476,128478,14,128481,128481,14,128483,128483,14,128488,128488,14,128495,128495,14,128499,128499,14,128506,128591,14,128710,128714,14,128721,128722,14,128725,128725,14,128728,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,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,129664,129666,14,129671,129679,14,129686,129704,14,129712,129718,14,129728,129730,14,129744,129750,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,2259,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,3134,3136,5,3142,3144,5,3157,3158,5,3201,3201,5,3260,3260,5,3263,3263,5,3266,3266,5,3270,3270,5,3274,3275,7,3285,3286,5,3328,3329,5,3387,3388,5,3391,3392,7,3398,3400,7,3405,3405,5,3415,3415,5,3457,3457,5,3530,3530,5,3536,3537,7,3542,3542,5,3551,3551,5,3633,3633,5,3636,3642,5,3761,3761,5,3764,3772,5,3864,3865,5,3895,3895,5,3902,3903,7,3967,3967,7,3974,3975,5,3993,4028,5,4141,4144,5,4146,4151,5,4155,4156,7,4182,4183,7,4190,4192,5,4226,4226,5,4229,4230,5,4253,4253,5,4448,4519,9,4957,4959,5,5938,5940,5,6002,6003,5,6070,6070,7,6078,6085,7,6087,6088,7,6109,6109,5,6158,6158,4,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,6848,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,7673,5,8203,8203,4,8205,8205,13,8232,8232,4,8234,8238,4,8265,8265,14,8293,8293,4,8400,8412,5,8417,8417,5,8421,8432,5,8505,8505,14,8617,8618,14,9000,9000,14,9167,9167,14,9208,9210,14,9642,9643,14,9664,9664,14,9728,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,9776,9783,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,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,9935,14,9937,9937,14,9939,9940,14,9961,9962,14,9968,9973,14,9975,9978,14,9981,9981,14,9986,9986,14,9989,9989,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,10084,14,10133,10135,14,10160,10160,14,10548,10549,14,11035,11036,14,11093,11093,14,11647,11647,5,12330,12333,5,12336,12336,14,12441,12442,5,12953,12953,14,42608,42610,5,42654,42655,5,43010,43010,5,43019,43019,5,43045,43046,5,43052,43052,5,43188,43203,7,43232,43249,5,43302,43309,5,43346,43347,7,43392,43394,5,43443,43443,5,43446,43449,5,43452,43453,5,43493,43493,5,43567,43568,7,43571,43572,7,43587,43587,5,43597,43597,7,43696,43696,5,43703,43704,5,43713,43713,5,43756,43757,5,43765,43765,7,44003,44004,7,44006,44007,7,44009,44010,7,44013,44013,5,44033,44059,12,44061,44087,12,44089,44115,12,44117,44143,12,44145,44171,12,44173,44199,12,44201,44227,12,44229,44255,12,44257,44283,12,44285,44311,12,44313,44339,12,44341,44367,12,44369,44395,12,44397,44423,12,44425,44451,12,44453,44479,12,44481,44507,12,44509,44535,12,44537,44563,12,44565,44591,12,44593,44619,12,44621,44647,12,44649,44675,12,44677,44703,12,44705,44731,12,44733,44759,12,44761,44787,12,44789,44815,12,44817,44843,12,44845,44871,12,44873,44899,12,44901,44927,12,44929,44955,12,44957,44983,12,44985,45011,12,45013,45039,12,45041,45067,12,45069,45095,12,45097,45123,12,45125,45151,12,45153,45179,12,45181,45207,12,45209,45235,12,45237,45263,12,45265,45291,12,45293,45319,12,45321,45347,12,45349,45375,12,45377,45403,12,45405,45431,12,45433,45459,12,45461,45487,12,45489,45515,12,45517,45543,12,45545,45571,12,45573,45599,12,45601,45627,12,45629,45655,12,45657,45683,12,45685,45711,12,45713,45739,12,45741,45767,12,45769,45795,12,45797,45823,12,45825,45851,12,45853,45879,12,45881,45907,12,45909,45935,12,45937,45963,12,45965,45991,12,45993,46019,12,46021,46047,12,46049,46075,12,46077,46103,12,46105,46131,12,46133,46159,12,46161,46187,12,46189,46215,12,46217,46243,12,46245,46271,12,46273,46299,12,46301,46327,12,46329,46355,12,46357,46383,12,46385,46411,12,46413,46439,12,46441,46467,12,46469,46495,12,46497,46523,12,46525,46551,12,46553,46579,12,46581,46607,12,46609,46635,12,46637,46663,12,46665,46691,12,46693,46719,12,46721,46747,12,46749,46775,12,46777,46803,12,46805,46831,12,46833,46859,12,46861,46887,12,46889,46915,12,46917,46943,12,46945,46971,12,46973,46999,12,47001,47027,12,47029,47055,12,47057,47083,12,47085,47111,12,47113,47139,12,47141,47167,12,47169,47195,12,47197,47223,12,47225,47251,12,47253,47279,12,47281,47307,12,47309,47335,12,47337,47363,12,47365,47391,12,47393,47419,12,47421,47447,12,47449,47475,12,47477,47503,12,47505,47531,12,47533,47559,12,47561,47587,12,47589,47615,12,47617,47643,12,47645,47671,12,47673,47699,12,47701,47727,12,47729,47755,12,47757,47783,12,47785,47811,12,47813,47839,12,47841,47867,12,47869,47895,12,47897,47923,12,47925,47951,12,47953,47979,12,47981,48007,12,48009,48035,12,48037,48063,12,48065,48091,12,48093,48119,12,48121,48147,12,48149,48175,12,48177,48203,12,48205,48231,12,48233,48259,12,48261,48287,12,48289,48315,12,48317,48343,12,48345,48371,12,48373,48399,12,48401,48427,12,48429,48455,12,48457,48483,12,48485,48511,12,48513,48539,12,48541,48567,12,48569,48595,12,48597,48623,12,48625,48651,12,48653,48679,12,48681,48707,12,48709,48735,12,48737,48763,12,48765,48791,12,48793,48819,12,48821,48847,12,48849,48875,12,48877,48903,12,48905,48931,12,48933,48959,12,48961,48987,12,48989,49015,12,49017,49043,12,49045,49071,12,49073,49099,12,49101,49127,12,49129,49155,12,49157,49183,12,49185,49211,12,49213,49239,12,49241,49267,12,49269,49295,12,49297,49323,12,49325,49351,12,49353,49379,12,49381,49407,12,49409,49435,12,49437,49463,12,49465,49491,12,49493,49519,12,49521,49547,12,49549,49575,12,49577,49603,12,49605,49631,12,49633,49659,12,49661,49687,12,49689,49715,12,49717,49743,12,49745,49771,12,49773,49799,12,49801,49827,12,49829,49855,12,49857,49883,12,49885,49911,12,49913,49939,12,49941,49967,12,49969,49995,12,49997,50023,12,50025,50051,12,50053,50079,12,50081,50107,12,50109,50135,12,50137,50163,12,50165,50191,12,50193,50219,12,50221,50247,12,50249,50275,12,50277,50303,12,50305,50331,12,50333,50359,12,50361,50387,12,50389,50415,12,50417,50443,12,50445,50471,12,50473,50499,12,50501,50527,12,50529,50555,12,50557,50583,12,50585,50611,12,50613,50639,12,50641,50667,12,50669,50695,12,50697,50723,12,50725,50751,12,50753,50779,12,50781,50807,12,50809,50835,12,50837,50863,12,50865,50891,12,50893,50919,12,50921,50947,12,50949,50975,12,50977,51003,12,51005,51031,12,51033,51059,12,51061,51087,12,51089,51115,12,51117,51143,12,51145,51171,12,51173,51199,12,51201,51227,12,51229,51255,12,51257,51283,12,51285,51311,12,51313,51339,12,51341,51367,12,51369,51395,12,51397,51423,12,51425,51451,12,51453,51479,12,51481,51507,12,51509,51535,12,51537,51563,12,51565,51591,12,51593,51619,12,51621,51647,12,51649,51675,12,51677,51703,12,51705,51731,12,51733,51759,12,51761,51787,12,51789,51815,12,51817,51843,12,51845,51871,12,51873,51899,12,51901,51927,12,51929,51955,12,51957,51983,12,51985,52011,12,52013,52039,12,52041,52067,12,52069,52095,12,52097,52123,12,52125,52151,12,52153,52179,12,52181,52207,12,52209,52235,12,52237,52263,12,52265,52291,12,52293,52319,12,52321,52347,12,52349,52375,12,52377,52403,12,52405,52431,12,52433,52459,12,52461,52487,12,52489,52515,12,52517,52543,12,52545,52571,12,52573,52599,12,52601,52627,12,52629,52655,12,52657,52683,12,52685,52711,12,52713,52739,12,52741,52767,12,52769,52795,12,52797,52823,12,52825,52851,12,52853,52879,12,52881,52907,12,52909,52935,12,52937,52963,12,52965,52991,12,52993,53019,12,53021,53047,12,53049,53075,12,53077,53103,12,53105,53131,12,53133,53159,12,53161,53187,12,53189,53215,12,53217,53243,12,53245,53271,12,53273,53299,12,53301,53327,12,53329,53355,12,53357,53383,12,53385,53411,12,53413,53439,12,53441,53467,12,53469,53495,12,53497,53523,12,53525,53551,12,53553,53579,12,53581,53607,12,53609,53635,12,53637,53663,12,53665,53691,12,53693,53719,12,53721,53747,12,53749,53775,12,53777,53803,12,53805,53831,12,53833,53859,12,53861,53887,12,53889,53915,12,53917,53943,12,53945,53971,12,53973,53999,12,54001,54027,12,54029,54055,12,54057,54083,12,54085,54111,12,54113,54139,12,54141,54167,12,54169,54195,12,54197,54223,12,54225,54251,12,54253,54279,12,54281,54307,12,54309,54335,12,54337,54363,12,54365,54391,12,54393,54419,12,54421,54447,12,54449,54475,12,54477,54503,12,54505,54531,12,54533,54559,12,54561,54587,12,54589,54615,12,54617,54643,12,54645,54671,12,54673,54699,12,54701,54727,12,54729,54755,12,54757,54783,12,54785,54811,12,54813,54839,12,54841,54867,12,54869,54895,12,54897,54923,12,54925,54951,12,54953,54979,12,54981,55007,12,55009,55035,12,55037,55063,12,55065,55091,12,55093,55119,12,55121,55147,12,55149,55175,12,55177,55203,12,55243,55291,10,65024,65039,5,65279,65279,4,65520,65528,4,66045,66045,5,66422,66426,5,68101,68102,5,68152,68154,5,68325,68326,5,69291,69292,5,69632,69632,7,69634,69634,7,69759,69761,5]');
}
//#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 codePoint = getPrevCodePoint(str, offset);
offset -= getUTF16Length(codePoint);
return offset;
}
exports.getLeftDeleteOffset = getLeftDeleteOffset;
function getOffsetBeforeLastEmojiComponent(offset, str) {
// See https://www.unicode.org/reports/tr51/tr51-14.html#EBNF_and_Regex for the
// structure of emojis.
let codePoint = getPrevCodePoint(str, offset);
offset -= getUTF16Length(codePoint);
// Skip modifiers
while ((isEmojiModifier(codePoint) || codePoint === 65039 /* emojiVariantSelector */ || codePoint === 8419 /* enclosingKeyCap */)) {
if (offset === 0) {
// Cannot skip modifier, no preceding emoji base.
return undefined;
}
codePoint = getPrevCodePoint(str, offset);
offset -= getUTF16Length(codePoint);
}
// Expect base emoji
if (!isEmojiImprecise(codePoint)) {
// Unexpected code point, not a valid emoji.
return undefined;
}
if (offset >= 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 = getPrevCodePoint(str, offset);
if (optionalZwjCodePoint === 8205 /* zwj */) {
offset -= getUTF16Length(optionalZwjCodePoint);
}
}
return offset;
}
function getUTF16Length(codePoint) {
return codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1;
}
function isEmojiModifier(codePoint) {
return 0x1F3FB <= codePoint && codePoint <= 0x1F3FF;
}
});
/*---------------------------------------------------------------------------------------------
* 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/common/buffer*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/]), function (require, exports, strings) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeUInt8 = exports.readUInt8 = exports.writeUInt32BE = exports.readUInt32BE = exports.writeUInt16LE = exports.readUInt16LE = exports.VSBuffer = void 0;
const hasBuffer = (typeof Buffer !== 'undefined');
const hasTextDecoder = (typeof TextDecoder !== 'undefined');
let textDecoder;
class VSBuffer {
constructor(buffer) {
this.buffer = buffer;
this.byteLength = this.buffer.byteLength;
}
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);
}
toString() {
if (hasBuffer) {
return this.buffer.toString();
}
else if (hasTextDecoder) {
if (!textDecoder) {
textDecoder = new TextDecoder();
}
return textDecoder.decode(this.buffer);
}
else {
return strings.decodeUTF8(this.buffer);
}
}
}
exports.VSBuffer = VSBuffer;
function readUInt16LE(source, offset) {
return (((source[offset + 0] << 0) >>> 0) |
((source[offset + 1] << 8) >>> 0));
}
exports.readUInt16LE = readUInt16LE;
function writeUInt16LE(destination, value, offset) {
destination[offset + 0] = (value & 0b11111111);
value = value >>> 8;
destination[offset + 1] = (value & 0b11111111);
}
exports.writeUInt16LE = writeUInt16LE;
function readUInt32BE(source, offset) {
return (source[offset] * Math.pow(2, 24)
+ source[offset + 1] * Math.pow(2, 16)
+ source[offset + 2] * Math.pow(2, 8)
+ source[offset + 3]);
}
exports.readUInt32BE = readUInt32BE;
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;
}
exports.writeUInt32BE = writeUInt32BE;
function readUInt8(source, offset) {
return source[offset];
}
exports.readUInt8 = readUInt8;
function writeUInt8(destination, value, offset) {
destination[offset] = value;
}
exports.writeUInt8 = writeUInt8;
});
/*---------------------------------------------------------------------------------------------
* 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/base/common/extpath*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,8/*vs/base/common/strings*/,73/*vs/base/common/path*/]), function (require, exports, platform_1, strings_1, path_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasDriveLetter = exports.isRootOrDriveLetter = exports.isWindowsDriveLetter = exports.isEqualOrParent = exports.toPosixPath = exports.toSlashes = void 0;
/**
* 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);
}
exports.toSlashes = toSlashes;
/**
* 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;
}
exports.toPosixPath = toPosixPath;
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;
}
exports.isEqualOrParent = isEqualOrParent;
function isWindowsDriveLetter(char0) {
return char0 >= 65 /* A */ && char0 <= 90 /* Z */ || char0 >= 97 /* a */ && char0 <= 122 /* z */;
}
exports.isWindowsDriveLetter = isWindowsDriveLetter;
function isRootOrDriveLetter(path) {
const pathNormalized = (0, path_1.normalize)(path);
if (platform_1.isWindows) {
if (path.length > 3) {
return false;
}
return hasDriveLetter(pathNormalized) &&
(path.length === 2 || pathNormalized.charCodeAt(2) === 92 /* Backslash */);
}
return pathNormalized === path_1.posix.sep;
}
exports.isRootOrDriveLetter = isRootOrDriveLetter;
function hasDriveLetter(path) {
if (platform_1.isWindows) {
return isWindowsDriveLetter(path.charCodeAt(0)) && path.charCodeAt(1) === 58 /* Colon */;
}
return false;
}
exports.hasDriveLetter = hasDriveLetter;
});
/*---------------------------------------------------------------------------------------------
* 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/hash*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/]), function (require, exports, strings) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StringSHA1 = exports.toHexString = exports.stringHash = exports.doHash = exports.hash = void 0;
/**
* Return a hash value for an object.
*/
function hash(obj) {
return doHash(obj, 0);
}
exports.hash = hash;
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);
}
}
exports.doHash = doHash;
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;
}
exports.stringHash = stringHash;
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);
}
exports.toHexString = toHexString;
/**
* A SHA1 implementation that works with strings and does not allocate.
*/
class StringSHA1 {
constructor() {
this._h0 = 0x67452301;
this._h1 = 0xEFCDAB89;
this._h2 = 0x98BADCFE;
this._h3 = 0x10325476;
this._h4 = 0xC3D2E1F0;
this._buff = new Uint8Array(64 /* 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 /* UNICODE_REPLACEMENT */;
}
}
else {
// last character is a surrogate pair
leftoverHighSurrogate = charCode;
break;
}
}
else if (strings.isLowSurrogate(charCode)) {
// illegal => unicode replacement character
codePoint = 65533 /* 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 /* BLOCK_SIZE */) {
this._step();
buffLen -= 64 /* BLOCK_SIZE */;
this._totalLen += 64 /* BLOCK_SIZE */;
// take last 3 in case of UTF8 overflow
buff[0] = buff[64 /* BLOCK_SIZE */ + 0];
buff[1] = buff[64 /* BLOCK_SIZE */ + 1];
buff[2] = buff[64 /* 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 /* 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;
StringSHA1._bigBlock32 = new DataView(new ArrayBuffer(320)); // 80 * 4 = 320
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[128/*vs/base/common/diff/diff*/], __M([0/*require*/,1/*exports*/,285/*vs/base/common/diff/diffChange*/,92/*vs/base/common/hash*/]), function (require, exports, diffChange_1, hash_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LcsDiff = exports.MyArray = exports.Debug = exports.stringDiff = exports.StringDiffSequence = void 0;
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;
}
exports.stringDiff = stringDiff;
//
// The code below has been ported from a C# implementation in VS
//
class Debug {
static Assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}
}
exports.Debug = Debug;
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];
}
}
}
exports.MyArray = MyArray;
/**
* 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
* MarktNextChange() 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 /* MAX_SAFE_SMALL_INTEGER */;
this.m_modifiedStart = 1073741824 /* 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 /* MAX_SAFE_SMALL_INTEGER */;
this.m_modifiedStart = 1073741824 /* 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 did'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 /* 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 /* 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 /* MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* 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 /* MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* 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 quiting 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 /* MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* 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 /* 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++;
}
let 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) {
let 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[158/*vs/base/browser/ui/tree/indexTreeModel*/], __M([0/*require*/,1/*exports*/,101/*vs/base/browser/ui/tree/tree*/,19/*vs/base/common/arrays*/,128/*vs/base/common/diff/diff*/,6/*vs/base/common/event*/,54/*vs/base/common/iterator*/]), function (require, exports, tree_1, arrays_1, diff_1, event_1, iterator_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IndexTreeModel = exports.getVisibleState = exports.isFilterResult = void 0;
function isFilterResult(obj) {
return typeof obj === 'object' && 'visibility' in obj && 'data' in obj;
}
exports.isFilterResult = isFilterResult;
function getVisibleState(visibility) {
switch (visibility) {
case true: return 1 /* Visible */;
case false: return 0 /* Hidden */;
default: return visibility;
}
}
exports.getVisibleState = getVisibleState;
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.collapseByDefault = typeof options.collapseByDefault === 'undefined' ? false : options.collapseByDefault;
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 /* 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, options, recurseLevels) {
var _a;
if (toInsertIterable === void 0) { toInsertIterable = iterator_1.Iterable.empty(); }
if (recurseLevels === void 0) { recurseLevels = (_a = options.diffDepth) !== null && _a !== void 0 ? _a : 0; }
const { parentNode } = this.getParentNodeWithListIndex(location);
const toInsert = [...toInsertIterable];
const index = location[location.length - 1];
const diff = new diff_1.LcsDiff({ getElements: () => parentNode.children.map(e => identity.getId(e.element).toString()) }, {
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) {
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 }) {
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 /* Visible */ : 0 /* Hidden */, revealed, treeListElementsToInsert, onDidCreateNode));
const lastIndex = location[location.length - 1];
const lastHadChildren = parentNode.children.length > 0;
// 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);
// 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);
}
const currentlyHasChildren = parentNode.children.length > 0;
if (lastHadChildren !== currentlyHasChildren) {
this.setCollapsible(location.slice(0, -1), currentlyHasChildren);
}
this._onDidSplice.fire({ insertedNodes: nodesToInsert, deletedNodes });
let node = parentNode;
while (node) {
if (node.visibility === 2 /* Recurse */) {
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);
}
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 /* 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 /* Hidden */ && !node.collapsed;
const childNodes = iterator_1.Iterable.map(childElements, el => this.createTreeNode(el, node, visibility, childRevealed, treeListElements, onDidCreateNode));
let visibleChildrenCount = 0;
let renderNodeCount = 1;
for (const child of childNodes) {
node.children.push(child);
renderNodeCount += child.renderNodeCount;
if (child.visible) {
child.visibleChildIndex = visibleChildrenCount++;
}
}
node.collapsible = node.collapsible || node.children.length > 0;
node.visibleChildrenCount = visibleChildrenCount;
node.visible = visibility === 2 /* Recurse */ ? visibleChildrenCount > 0 : (visibility === 1 /* Visible */);
if (!node.visible) {
node.renderNodeCount = 0;
if (revealed) {
treeListElements.pop();
}
}
else if (!node.collapsed) {
node.renderNodeCount = renderNodeCount;
}
if (onDidCreateNode) {
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 /* Visible */ : 0 /* 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 /* 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 /* 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 /* Recurse */ ? hasVisibleDescendants : (visibility === 1 /* Visible */);
}
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 /* Visible */;
if (typeof result === 'boolean') {
node.filterData = undefined;
return result ? 1 /* Visible */ : 0 /* 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];
}
}
}
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[159/*vs/base/browser/ui/tree/objectTreeModel*/], __M([0/*require*/,1/*exports*/,54/*vs/base/common/iterator*/,158/*vs/base/browser/ui/tree/indexTreeModel*/,101/*vs/base/browser/ui/tree/tree*/]), function (require, exports, iterator_1, indexTreeModel_1, tree_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) => {
var _a;
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);
}
(_a = options.onDidCreateNode) === null || _a === void 0 ? void 0 : _a.call(options, tnode);
};
const onDidDeleteNode = (node) => {
var _a;
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);
}
}
(_a = options.onDidDeleteNode) === null || _a === void 0 ? void 0 : _a.call(options, tnode);
};
this.model.splice([...location, 0], Number.MAX_VALUE, children, Object.assign(Object.assign({}, 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) {
return Object.assign(Object.assign({}, treeElement), { children: this.preserveCollapseState(treeElement.children) });
}
const collapsible = typeof treeElement.collapsible === 'boolean' ? treeElement.collapsible : node.collapsible;
const collapsed = typeof treeElement.collapsed !== 'undefined' ? treeElement.collapsed : node.collapsed;
return Object.assign(Object.assign({}, treeElement), { collapsible,
collapsed, children: this.preserveCollapseState(treeElement.children) });
});
}
rerender(element) {
const location = this.getElementLocation(element);
this.model.rerender(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[292/*vs/base/browser/ui/tree/compressedObjectTreeModel*/], __M([0/*require*/,1/*exports*/,54/*vs/base/common/iterator*/,6/*vs/base/common/event*/,101/*vs/base/browser/ui/tree/tree*/,159/*vs/base/browser/ui/tree/objectTreeModel*/]), function (require, exports, iterator_1, event_1, tree_1, objectTreeModel_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CompressibleObjectTreeModel = exports.DefaultElementMapper = exports.CompressedObjectTreeModel = exports.decompress = exports.compress = void 0;
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
};
}
exports.compress = compress;
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);
}
exports.decompress = decompress;
function splice(treeElement, element, children) {
if (treeElement.element === element) {
return Object.assign(Object.assign({}, treeElement), { children });
}
return Object.assign(Object.assign({}, 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 {
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;
}
get onDidSplice() { return this.model.onDidSplice; }
get onDidChangeCollapseState() { return this.model.onDidChangeCollapseState; }
get onDidChangeRenderNodeCount() { return this.model.onDidChangeRenderNodeCount; }
setChildren(element, children = iterator_1.Iterable.empty(), options) {
// Diffs must be deem, 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 Error('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);
const parentChildren = parent.children
.map(child => child === node ? recompressedElement : child);
this._setChildren(parent.element, parentChildren, {
diffIdentityProvider,
diffDepth: node.depth - parent.depth,
});
}
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, Object.assign(Object.assign({}, 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];
}
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 {
constructor(unwrapper, node) {
this.unwrapper = unwrapper;
this.node = node;
}
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; }
}
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 Object.assign(Object.assign({}, 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 {
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));
}
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));
}
setChildren(element, children = iterator_1.Iterable.empty(), options = {}) {
this.model.setChildren(element, children, options);
}
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);
}
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[293/*vs/base/common/search*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/]), function (require, exports, strings) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildReplaceStringWithCasePreserved = void 0;
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;
}
}
exports.buildReplaceStringWithCasePreserved = buildReplaceStringWithCasePreserved;
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[74/*vs/base/common/severity*/], __M([0/*require*/,1/*exports*/,8/*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;
});
define(__m[20/*vs/base/common/types*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertNever = exports.withNullAsUndefined = exports.createProxyObject = exports.getAllMethodNames = exports.getAllPropertyNames = exports.validateConstraint = exports.validateConstraints = exports.isFunction = exports.assertIsDefined = exports.assertType = exports.isUndefinedOrNull = exports.isUndefined = exports.isBoolean = exports.isNumber = exports.isObject = exports.isString = exports.isArray = void 0;
/**
* @returns whether the provided parameter is a JavaScript Array or not.
*/
function isArray(array) {
return Array.isArray(array);
}
exports.isArray = isArray;
/**
* @returns whether the provided parameter is a JavaScript String or not.
*/
function isString(str) {
return (typeof str === 'string');
}
exports.isString = isString;
/**
*
* @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);
}
exports.isObject = isObject;
/**
* 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));
}
exports.isNumber = isNumber;
/**
* @returns whether the provided parameter is a JavaScript Boolean or not.
*/
function isBoolean(obj) {
return (obj === true || obj === false);
}
exports.isBoolean = isBoolean;
/**
* @returns whether the provided parameter is undefined.
*/
function isUndefined(obj) {
return (typeof obj === 'undefined');
}
exports.isUndefined = isUndefined;
/**
* @returns whether the provided parameter is undefined or null.
*/
function isUndefinedOrNull(obj) {
return (isUndefined(obj) || obj === null);
}
exports.isUndefinedOrNull = isUndefinedOrNull;
function assertType(condition, type) {
if (!condition) {
throw new Error(type ? `Unexpected type, expected '${type}'` : 'Unexpected type');
}
}
exports.assertType = assertType;
/**
* 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;
}
exports.assertIsDefined = assertIsDefined;
/**
* @returns whether the provided parameter is a JavaScript Function or not.
*/
function isFunction(obj) {
return (typeof obj === 'function');
}
exports.isFunction = isFunction;
function validateConstraints(args, constraints) {
const len = Math.min(args.length, constraints.length);
for (let i = 0; i < len; i++) {
validateConstraint(args[i], constraints[i]);
}
}
exports.validateConstraints = validateConstraints;
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 (_a) {
// 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`);
}
}
exports.validateConstraint = validateConstraint;
function getAllPropertyNames(obj) {
let res = [];
let proto = Object.getPrototypeOf(obj);
while (Object.prototype !== proto) {
res = res.concat(Object.getOwnPropertyNames(proto));
proto = Object.getPrototypeOf(proto);
}
return res;
}
exports.getAllPropertyNames = getAllPropertyNames;
function getAllMethodNames(obj) {
const methods = [];
for (const prop of getAllPropertyNames(obj)) {
if (typeof obj[prop] === 'function') {
methods.push(prop);
}
}
return methods;
}
exports.getAllMethodNames = getAllMethodNames;
function createProxyObject(methodNames, invoke) {
const createProxyMethod = (method) => {
return function () {
const args = Array.prototype.slice.call(arguments, 0);
return invoke(method, args);
};
};
let result = {};
for (const methodName of methodNames) {
result[methodName] = createProxyMethod(methodName);
}
return result;
}
exports.createProxyObject = createProxyObject;
/**
* Converts null to undefined, passes all other values through.
*/
function withNullAsUndefined(x) {
return x === null ? undefined : x;
}
exports.withNullAsUndefined = withNullAsUndefined;
function assertNever(value, message = 'Unreachable') {
throw new Error(message);
}
exports.assertNever = assertNever;
});
/*---------------------------------------------------------------------------------------------
* 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/objects*/], __M([0/*require*/,1/*exports*/,20/*vs/base/common/types*/]), function (require, exports, types_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOrDefault = exports.equals = exports.mixin = exports.cloneAndChange = exports.deepFreeze = exports.deepClone = void 0;
function deepClone(obj) {
if (!obj || typeof obj !== 'object') {
return obj;
}
if (obj instanceof RegExp) {
// See https://github.com/microsoft/TypeScript/issues/10990
return obj;
}
const result = Array.isArray(obj) ? [] : {};
Object.keys(obj).forEach((key) => {
if (obj[key] && typeof obj[key] === 'object') {
result[key] = deepClone(obj[key]);
}
else {
result[key] = obj[key];
}
});
return result;
}
exports.deepClone = deepClone;
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)) {
stack.push(prop);
}
}
}
}
return obj;
}
exports.deepFreeze = deepFreeze;
const _hasOwnProperty = Object.prototype.hasOwnProperty;
function cloneAndChange(obj, changer) {
return _cloneAndChange(obj, changer, new Set());
}
exports.cloneAndChange = cloneAndChange;
function _cloneAndChange(obj, changer, seen) {
if ((0, types_1.isUndefinedOrNull)(obj)) {
return obj;
}
const changed = changer(obj);
if (typeof changed !== 'undefined') {
return changed;
}
if ((0, types_1.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 (let 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;
}
exports.mixin = mixin;
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;
}
exports.equals = equals;
function getOrDefault(obj, fn, defaultValue) {
const result = fn(obj);
return typeof result === 'undefined' ? defaultValue : result;
}
exports.getOrDefault = getOrDefault;
});
/*---------------------------------------------------------------------------------------------
* 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/uint*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toUint32 = exports.toUint8 = void 0;
function toUint8(v) {
if (v < 0) {
return 0;
}
if (v > 255 /* MAX_UINT_8 */) {
return 255 /* MAX_UINT_8 */;
}
return v | 0;
}
exports.toUint8 = toUint8;
function toUint32(v) {
if (v < 0) {
return 0;
}
if (v > 4294967295 /* MAX_UINT_32 */) {
return 4294967295 /* MAX_UINT_32 */;
}
return v | 0;
}
exports.toUint32 = toUint32;
});
/*---------------------------------------------------------------------------------------------
* 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/base/common/uri*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,73/*vs/base/common/path*/]), function (require, exports, platform_1, paths) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uriToFsPath = exports.URI = void 0;
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 {
/**
* @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);
}
}
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';
}
// ---- 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.msft.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);
}
static from(components) {
const result = new Uri(components.scheme, components.authority, components.path, components.query, components.fragment);
_validateUri(result, true);
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;
result._fsPath = data._sep === _pathSepMarker ? data.fsPath : null;
return result;
}
}
}
exports.URI = URI;
const _pathSepMarker = platform_1.isWindows ? 1 : undefined;
// This class exists so that URI is compatibile 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 /* 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;
}
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 /* Colon */]: '%3A',
[47 /* Slash */]: '%2F',
[63 /* QuestionMark */]: '%3F',
[35 /* Hash */]: '%23',
[91 /* OpenSquareBracket */]: '%5B',
[93 /* CloseSquareBracket */]: '%5D',
[64 /* AtSign */]: '%40',
[33 /* ExclamationMark */]: '%21',
[36 /* DollarSign */]: '%24',
[38 /* Ampersand */]: '%26',
[39 /* SingleQuote */]: '%27',
[40 /* OpenParen */]: '%28',
[41 /* CloseParen */]: '%29',
[42 /* Asterisk */]: '%2A',
[43 /* Plus */]: '%2B',
[44 /* Comma */]: '%2C',
[59 /* Semicolon */]: '%3B',
[61 /* Equals */]: '%3D',
[32 /* Space */]: '%20',
};
function encodeURIComponentFast(uriComponent, allowSlash) {
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 /* a */ && code <= 122 /* z */)
|| (code >= 65 /* A */ && code <= 90 /* Z */)
|| (code >= 48 /* Digit0 */ && code <= 57 /* Digit9 */)
|| code === 45 /* Dash */
|| code === 46 /* Period */
|| code === 95 /* Underline */
|| code === 126 /* Tilde */
|| (allowSlash && code === 47 /* Slash */)) {
// 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 /* Hash */ || code === 63 /* 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 /* Slash */
&& (uri.path.charCodeAt(1) >= 65 /* A */ && uri.path.charCodeAt(1) <= 90 /* Z */ || uri.path.charCodeAt(1) >= 97 /* a */ && uri.path.charCodeAt(1) <= 122 /* z */)
&& uri.path.charCodeAt(2) === 58 /* 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;
}
exports.uriToFsPath = uriToFsPath;
/**
* 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.indexOf(':');
if (idx === -1) {
res += encoder(userinfo, false);
}
else {
// <user>:<pass>@<auth>
res += encoder(userinfo.substr(0, idx), false);
res += ':';
res += encoder(userinfo.substr(idx + 1), false);
}
res += '@';
}
authority = authority.toLowerCase();
idx = authority.indexOf(':');
if (idx === -1) {
res += encoder(authority, false);
}
else {
// <auth>:<port>
res += encoder(authority.substr(0, idx), false);
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 /* Slash */ && path.charCodeAt(2) === 58 /* Colon */) {
const code = path.charCodeAt(1);
if (code >= 65 /* A */ && code <= 90 /* Z */) {
path = `/${String.fromCharCode(code + 32)}:${path.substr(3)}`; // "/c:".length === 3
}
}
else if (path.length >= 2 && path.charCodeAt(1) === 58 /* Colon */) {
const code = path.charCodeAt(0);
if (code >= 65 /* A */ && code <= 90 /* Z */) {
path = `${String.fromCharCode(code + 32)}:${path.substr(2)}`; // "/c:".length === 3
}
}
// encode the rest of the path
res += encoder(path, true);
}
if (query) {
res += '?';
res += encoder(query, false);
}
if (fragment) {
res += '#';
res += !skipEncoding ? encodeURIComponentFast(fragment, false) : fragment;
}
return res;
}
// --- decode
function decodeURIComponentGraceful(str) {
try {
return decodeURIComponent(str);
}
catch (_a) {
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[49/*vs/base/common/map*/], __M([0/*require*/,1/*exports*/,24/*vs/base/common/uri*/,8/*vs/base/common/strings*/]), function (require, exports, uri_1, strings_1) {
"use strict";
var _a, _b;
Object.defineProperty(exports, "__esModule", { value: true });
exports.LRUCache = exports.LinkedMap = exports.ResourceMap = 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 /* 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._value = key.replace(/\\$|\/$/, '');
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 === 47 /* Slash */ || this._splitOnBackslash && ch === 92 /* 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) {
this._ignorePathCasing = _ignorePathCasing;
this._states = [];
this._stateIdx = 0;
}
reset(key) {
this._value = key;
this._states = [];
if (this._value.scheme) {
this._states.push(1 /* Scheme */);
}
if (this._value.authority) {
this._states.push(2 /* 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 /* Path */);
}
}
if (this._value.query) {
this._states.push(4 /* Query */);
}
if (this._value.fragment) {
this._states.push(5 /* Fragment */);
}
this._stateIdx = 0;
return this;
}
next() {
if (this._states[this._stateIdx] === 3 /* Path */ && this._pathIterator.hasNext()) {
this._pathIterator.next();
}
else {
this._stateIdx += 1;
}
return this;
}
hasNext() {
return (this._states[this._stateIdx] === 3 /* Path */ && this._pathIterator.hasNext())
|| this._stateIdx < this._states.length - 1;
}
cmp(a) {
if (this._states[this._stateIdx] === 1 /* Scheme */) {
return (0, strings_1.compareIgnoreCase)(a, this._value.scheme);
}
else if (this._states[this._stateIdx] === 2 /* Authority */) {
return (0, strings_1.compareIgnoreCase)(a, this._value.authority);
}
else if (this._states[this._stateIdx] === 3 /* Path */) {
return this._pathIterator.cmp(a);
}
else if (this._states[this._stateIdx] === 4 /* Query */) {
return (0, strings_1.compare)(a, this._value.query);
}
else if (this._states[this._stateIdx] === 5 /* Fragment */) {
return (0, strings_1.compare)(a, this._value.fragment);
}
throw new Error();
}
value() {
if (this._states[this._stateIdx] === 1 /* Scheme */) {
return this._value.scheme;
}
else if (this._states[this._stateIdx] === 2 /* Authority */) {
return this._value.authority;
}
else if (this._states[this._stateIdx] === 3 /* Path */) {
return this._pathIterator.value();
}
else if (this._states[this._stateIdx] === 4 /* Query */) {
return this._value.query;
}
else if (this._states[this._stateIdx] === 5 /* Fragment */) {
return this._value.fragment;
}
throw new Error();
}
}
exports.UriIterator = UriIterator;
class TernarySearchTreeNode {
isEmpty() {
return !this.left && !this.mid && !this.right && !this.value;
}
}
class TernarySearchTree {
constructor(segments) {
this._iter = segments;
}
static forUris(ignorePathCasing = () => false) {
return new TernarySearchTree(new UriIterator(ignorePathCasing));
}
static forStrings() {
return new TernarySearchTree(new StringIterator());
}
static forConfigKeys() {
return new TernarySearchTree(new ConfigKeysIterator());
}
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();
}
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();
}
node = node.left;
}
else if (val < 0) {
// right
if (!node.right) {
node.right = new TernarySearchTreeNode();
node.right.segment = iter.value();
}
node = node.right;
}
else if (iter.hasNext()) {
// mid
iter.next();
if (!node.mid) {
node.mid = new TernarySearchTreeNode();
node.mid.segment = iter.value();
}
node = node.mid;
}
else {
break;
}
}
const oldElement = node.value;
node.value = element;
node.key = key;
return oldElement;
}
get(key) {
var _c;
return (_c = this._getNode(key)) === null || _c === void 0 ? void 0 : _c.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 === null || node === void 0 ? void 0 : node.value) === undefined && (node === null || node === void 0 ? void 0 : 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 and unset node
while (node) {
const val = iter.cmp(node.segment);
if (val > 0) {
// left
stack.push([1, node]);
node = node.left;
}
else if (val < 0) {
// right
stack.push([-1, node]);
node = node.right;
}
else if (iter.hasNext()) {
// mid
iter.next();
stack.push([0, node]);
node = node.mid;
}
else {
if (superStr) {
// remove children
node.left = undefined;
node.mid = undefined;
node.right = undefined;
}
else {
// remove element
node.value = undefined;
}
// clean up empty nodes
while (stack.length > 0 && node.isEmpty()) {
let [dir, parent] = stack.pop();
switch (dir) {
case 1:
parent.left = undefined;
break;
case 0:
parent.mid = undefined;
break;
case -1:
parent.right = undefined;
break;
}
node = parent;
}
break;
}
}
}
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) {
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) {
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) {
// DFS
if (!node) {
return;
}
const stack = [node];
while (stack.length > 0) {
const node = stack.pop();
if (node) {
if (node.value) {
yield [node.key, node.value];
}
if (node.left) {
stack.push(node.left);
}
if (node.mid) {
stack.push(node.mid);
}
if (node.right) {
stack.push(node.right);
}
}
}
}
}
exports.TernarySearchTree = TernarySearchTree;
class ResourceMap {
constructor(mapOrKeyFn, toKey) {
this[_a] = 'ResourceMap';
if (mapOrKeyFn instanceof ResourceMap) {
this.map = new Map(mapOrKeyFn.map);
this.toKey = toKey !== null && toKey !== void 0 ? toKey : ResourceMap.defaultToKey;
}
else {
this.map = new Map();
this.toKey = mapOrKeyFn !== null && mapOrKeyFn !== void 0 ? mapOrKeyFn : ResourceMap.defaultToKey;
}
}
set(resource, value) {
this.map.set(this.toKey(resource), value);
return this;
}
get(resource) {
return this.map.get(this.toKey(resource));
}
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 (let [index, value] of this.map) {
clb(value, uri_1.URI.parse(index), this);
}
}
values() {
return this.map.values();
}
*keys() {
for (let key of this.map.keys()) {
yield uri_1.URI.parse(key);
}
}
*entries() {
for (let tuple of this.map.entries()) {
yield [uri_1.URI.parse(tuple[0]), tuple[1]];
}
}
*[(_a = Symbol.toStringTag, Symbol.iterator)]() {
for (let item of this.map) {
yield [uri_1.URI.parse(item[0]), item[1]];
}
}
}
exports.ResourceMap = ResourceMap;
ResourceMap.defaultToKey = (resource) => resource.toString();
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() {
var _c;
return (_c = this._head) === null || _c === void 0 ? void 0 : _c.value;
}
get last() {
var _c;
return (_c = this._tail) === null || _c === void 0 ? void 0 : _c.value;
}
has(key) {
return this._map.has(key);
}
get(key, touch = 0 /* None */) {
const item = this._map.get(key);
if (!item) {
return undefined;
}
if (touch !== 0 /* None */) {
this.touch(item, touch);
}
return item.value;
}
set(key, value, touch = 0 /* None */) {
let item = this._map.get(key);
if (item) {
item.value = value;
if (touch !== 0 /* None */) {
this.touch(item, touch);
}
}
else {
item = { key, value, next: undefined, previous: undefined };
switch (touch) {
case 0 /* None */:
this.addItemLast(item);
break;
case 1 /* AsOld */:
this.addItemFirst(item);
break;
case 2 /* 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++;
}
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 /* AsOld */ && touch !== 2 /* AsNew */)) {
return;
}
if (touch === 1 /* 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 /* 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 LRUCache 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 /* AsNew */) {
return super.get(key, touch);
}
peek(key) {
return super.get(key, 0 /* None */);
}
set(key, value) {
super.set(key, value, 2 /* AsNew */);
this.checkTrim();
return this;
}
checkTrim() {
if (this.size > this._limit) {
this.trimOld(Math.round(this._limit * this._ratio));
}
}
}
exports.LRUCache = LRUCache;
});
/*---------------------------------------------------------------------------------------------
* 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/filters*/], __M([0/*require*/,1/*exports*/,49/*vs/base/common/map*/,8/*vs/base/common/strings*/]), function (require, exports, map_1, strings) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fuzzyScoreGracefulAggressive = exports.fuzzyScore = exports.FuzzyScore = exports.isPatternInWord = exports.createMatches = exports.anyScore = exports.matchesFuzzy = exports.matchesWords = exports.matchesCamelCase = exports.isUpper = exports.matchesSubString = exports.matchesContiguousSubString = exports.matchesPrefix = exports.or = void 0;
// 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;
};
}
exports.or = or;
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 }];
}
exports.matchesContiguousSubString = matchesContiguousSubString;
// Substring
function matchesSubString(word, wordToMatchAgainst) {
return _matchesSubString(word.toLowerCase(), wordToMatchAgainst.toLowerCase(), 0, 0);
}
exports.matchesSubString = matchesSubString;
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 /* a */ <= code && code <= 122 /* z */;
}
function isUpper(code) {
return 65 /* A */ <= code && code <= 90 /* Z */;
}
exports.isUpper = isUpper;
function isNumber(code) {
return 48 /* Digit0 */ <= code && code <= 57 /* Digit9 */;
}
function isWhitespace(code) {
return (code === 32 /* Space */
|| code === 9 /* Tab */
|| code === 10 /* LineFeed */
|| code === 13 /* CarriageReturn */);
}
const wordSeparators = new Set();
'`~!@#$%^&*()-=+[{]}\\|;:\'",.<>/?'
.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));
}
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;
}
if (camelCaseWord.length > 60) {
return null;
}
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;
}
exports.matchesCamelCase = matchesCamelCase;
// 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 i = 0;
word = word.toLowerCase();
target = target.toLowerCase();
while (i < target.length && (result = _matchesWords(word, target, 0, i, contiguous)) === null) {
i = nextWord(target, i + 1);
}
return result;
}
exports.matchesWords = matchesWords;
function _matchesWords(word, target, i, j, contiguous) {
if (i === word.length) {
return [];
}
else if (j === target.length) {
return null;
}
else if (!charactersMatch(word.charCodeAt(i), target.charCodeAt(j))) {
return null;
}
else {
let result = null;
let nextWordIndex = j + 1;
result = _matchesWords(word, target, i + 1, j + 1, contiguous);
if (!contiguous) {
while (!result && (nextWordIndex = nextWord(target, nextWordIndex)) < target.length) {
result = _matchesWords(word, target, i + 1, nextWordIndex, contiguous);
nextWordIndex++;
}
}
return result === null ? null : join({ start: j, end: j + 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);
}
exports.matchesFuzzy = matchesFuzzy;
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, false);
if (result) {
return result;
}
}
return [0, wordPos];
}
exports.anyScore = anyScore;
//#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;
}
exports.createMatches = createMatches;
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 /* Underline */:
case 45 /* Dash */:
case 46 /* Period */:
case 32 /* Space */:
case 47 /* Slash */:
case 92 /* Backslash */:
case 39 /* SingleQuote */:
case 34 /* DoubleQuote */:
case 58 /* Colon */:
case 36 /* DollarSign */:
case 60 /* LessThan */:
case 40 /* OpenParen */:
case 91 /* OpenSquareBracket */:
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 /* Space */:
case 9 /* 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
}
exports.isPatternInWord = isPatternInWord;
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 || (exports.FuzzyScore = {}));
function fuzzyScore(pattern, patternLow, patternStart, word, wordLow, wordStart, firstMatchCanBeWeak) {
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 /* 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 /* Left */;
_diag[row][column] = 0;
}
else if (canComeDiag) {
_table[row][column] = diagScore;
_arrows[row][column] = 1 /* 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] && !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 /* LeftLeft */) {
diagColumn = diagColumn - 2;
}
else if (arrow === 2 /* 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 === patternLen) {
// 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;
}
exports.fuzzyScore = fuzzyScore;
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 prefered 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, firstMatchCanBeWeak) {
return fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word, lowWord, wordPos, true, firstMatchCanBeWeak);
}
exports.fuzzyScoreGracefulAggressive = fuzzyScoreGracefulAggressive;
function fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word, lowWord, wordPos, aggressive, firstMatchCanBeWeak) {
let top = fuzzyScore(pattern, lowPattern, patternPos, word, lowWord, wordPos, firstMatchCanBeWeak);
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, firstMatchCanBeWeak);
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
define(__m[294/*vs/base/common/fuzzyScorer*/], __M([0/*require*/,1/*exports*/,67/*vs/base/common/filters*/,73/*vs/base/common/path*/,17/*vs/base/common/platform*/,8/*vs/base/common/strings*/]), function (require, exports, filters_1, path_1, platform_1, strings_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pieceToQuery = exports.prepareQuery = exports.scoreFuzzy2 = void 0;
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);
}
exports.scoreFuzzy2 = scoreFuzzy2;
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, true);
if (!score) {
return NO_SCORE2;
}
return [score[0], (0, filters_1.createMatches)(score)];
}
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;
}
/**
* 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;
let values = undefined;
const originalSplit = original.split(MULTIPLE_QUERY_VALUES_SEPARATOR);
if (originalSplit.length > 1) {
for (const originalPiece of originalSplit) {
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
});
}
}
}
return { original, originalLowercase, pathNormalized, normalized, normalizedLowercase, values, containsPathSeparator };
}
exports.prepareQuery = prepareQuery;
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
}
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);
}
exports.pieceToQuery = pieceToQuery;
});
//#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[201/*vs/base/common/glob*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,157/*vs/base/common/extpath*/,73/*vs/base/common/path*/,49/*vs/base/common/map*/,15/*vs/base/common/async*/]), function (require, exports, strings, extpath, paths, map_1, async_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isRelativePattern = exports.parse = exports.match = exports.splitGlobAware = void 0;
const GLOBSTAR = '**';
const 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) {
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 OR Path Sep followed by Path Val) 0-many times
// 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}|${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;
}
exports.splitGlobAware = splitGlobAware;
function parseRegExp(pattern) {
if (!pattern) {
return '';
}
let regEx = '';
// Split up into segments for each slash found
const segments = splitGlobAware(pattern, GLOB_SPLIT);
// Special case where we only have globstars
if (segments.every(s => s === GLOBSTAR)) {
regEx = '.*';
}
// Build regex over segments
else {
let previousSegmentWasGlobStar = false;
segments.forEach((segment, index) => {
// Globstar is special
if (segment === GLOBSTAR) {
// if we have more than one globstar after another, just ignore it
if (!previousSegmentWasGlobStar) {
regEx += starsToRegExp(2);
previousSegmentWasGlobStar = true;
}
return;
}
// 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 === GLOB_SPLIT) {
res = '';
}
// anything else gets escaped
else {
res = strings.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(c => parseRegExp(c)).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 += strings.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.
// However, if pattern: some/**, we tolerate that we also match on "something" because our globstar behaviour
// is to match 0-N segments.
if (index < segments.length - 1 && (segments[index + 1] !== GLOBSTAR || index + 2 < segments.length)) {
regEx += PATH_REGEX;
}
// reset state
previousSegmentWasGlobStar = false;
});
}
return regEx;
}
// regexes to check for trival 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 IRelativePattern
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 Trivias
let match;
if (T1.test(pattern)) { // common pattern: **/*.txt just need endsWith check
const base = pattern.substr(4); // '**/*'.length === 4
parsedPattern = function (path, basename) {
return typeof path === 'string' && path.endsWith(base) ? pattern : null;
};
}
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;
}
return function (path, basename) {
if (!extpath.isEqualOrParent(path, arg2.base)) {
return null;
}
return parsedPattern(paths.relative(arg2.base, path), basename);
};
}
function trimForExclusions(pattern, options) {
return options.trimForExclusions && pattern.endsWith('/**') ? pattern.substr(0, pattern.length - 2) : pattern; // dropping **, tailing / is dropped later
}
// common pattern: **/some.txt just need basename check
function trivia2(base, originalPattern) {
const slashBase = `/${base}`;
const backslashBase = `\\${base}`;
const parsedPattern = function (path, basename) {
if (typeof path !== 'string') {
return null;
}
if (basename) {
return basename === base ? originalPattern : null;
}
return path === base || path.endsWith(slashBase) || path.endsWith(backslashBase) ? originalPattern : null;
};
const basenames = [base];
parsedPattern.basenames = basenames;
parsedPattern.patterns = [originalPattern];
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 n = parsedPatterns.length;
if (!n) {
return NULL;
}
if (n === 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 = paths.sep === paths.posix.sep;
const nativePath = usingPosixSep ? targetPath : targetPath.replace(ALL_FORWARD_SLASHES, paths.sep);
const nativePathEnd = paths.sep + nativePath;
const targetPathEnd = paths.posix.sep + targetPath;
const parsedPattern = matchPathEnds ? function (testPath, basename) {
return typeof testPath === 'string' &&
((testPath === nativePath || testPath.endsWith(nativePathEnd))
|| !usingPosixSep && (testPath === targetPath || testPath.endsWith(targetPathEnd)))
? pattern : null;
} : function (testPath, basename) {
return typeof testPath === 'string' &&
(testPath === nativePath
|| (!usingPosixSep && testPath === 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);
}
exports.match = match;
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);
}
exports.parse = parse;
function isRelativePattern(obj) {
const rp = obj;
return rp && typeof rp.base === 'string' && typeof rp.pattern === 'string';
}
exports.isRelativePattern = isRelativePattern;
function parsedExpression(expression, options) {
const parsedPatterns = aggregateBasenameMatches(Object.getOwnPropertyNames(expression)
.map(pattern => parseExpressionPattern(pattern, expression[pattern], options))
.filter(pattern => pattern !== NULL));
const n = parsedPatterns.length;
if (!n) {
return NULL;
}
if (!parsedPatterns.some(parsedPattern => !!parsedPattern.requiresSiblings)) {
if (n === 1) {
return parsedPatterns[0];
}
const resultExpression = function (path, basename) {
for (let i = 0, n = parsedPatterns.length; i < n; i++) {
// Pattern matches path
const result = parsedPatterns[i](path, basename);
if (result) {
return result;
}
}
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, basename, hasSibling) {
let name = undefined;
for (let i = 0, n = parsedPatterns.length; i < n; i++) {
// Pattern matches path
const parsedPattern = parsedPatterns[i];
if (parsedPattern.requiresSiblings && hasSibling) {
if (!basename) {
basename = paths.basename(path);
}
if (!name) {
name = basename.substr(0, basename.length - paths.extname(path).length);
}
}
const result = parsedPattern(path, basename, name, hasSibling);
if (result) {
return result;
}
}
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(m => m ? 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 /* Slash */ || ch === 92 /* 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;
}
});
/*---------------------------------------------------------------------------------------------
* 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/base/common/iconLabels*/], __M([0/*require*/,1/*exports*/,27/*vs/base/common/codicons*/,67/*vs/base/common/filters*/,8/*vs/base/common/strings*/]), function (require, exports, codicons_1, filters_1, strings_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.matchesFuzzyIconAware = exports.parseLabelWithIcons = exports.stripIcons = exports.markdownEscapeEscapedIcons = exports.escapeIcons = exports.iconStartMarker = void 0;
exports.iconStartMarker = '$(';
const iconsRegex = new RegExp(`\\$\\(${codicons_1.CSSIcon.iconNameExpression}(?:${codicons_1.CSSIcon.iconModifierExpression})?\\)`, 'g'); // no capturing groups
const escapeIconsRegex = new RegExp(`(\\\\)?${iconsRegex.source}`, 'g');
function escapeIcons(text) {
return text.replace(escapeIconsRegex, (match, escaped) => escaped ? match : `\\${match}`);
}
exports.escapeIcons = escapeIcons;
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}`);
}
exports.markdownEscapeEscapedIcons = markdownEscapeEscapedIcons;
const stripIconsRegex = new RegExp(`(\\s)?(\\\\)?${iconsRegex.source}(\\s)?`, 'g');
function stripIcons(text) {
if (text.indexOf(exports.iconStartMarker) === -1) {
return text;
}
return text.replace(stripIconsRegex, (match, preWhitespace, escaped, postWhitespace) => escaped ? match : preWhitespace || postWhitespace || '');
}
exports.stripIcons = stripIcons;
function parseLabelWithIcons(text) {
const firstIconIndex = text.indexOf(exports.iconStartMarker);
if (firstIconIndex === -1) {
return { text }; // return early if the word does not include an icon
}
return doParseLabelWithIcons(text, firstIconIndex);
}
exports.parseLabelWithIcons = parseLabelWithIcons;
function doParseLabelWithIcons(text, firstIconIndex) {
const iconOffsets = [];
let textWithoutIcons = '';
function appendChars(chars) {
if (chars) {
textWithoutIcons += chars;
for (const _ of chars) {
iconOffsets.push(iconsOffset); // make sure to fill in icon offsets
}
}
}
let currentIconStart = -1;
let currentIconValue = '';
let iconsOffset = 0;
let char;
let nextChar;
let offset = firstIconIndex;
const length = text.length;
// Append all characters until the first icon
appendChars(text.substr(0, firstIconIndex));
// example: $(file-symlink-file) my cool $(other-icon) entry
while (offset < length) {
char = text[offset];
nextChar = text[offset + 1];
// beginning of icon: some value $( <--
if (char === exports.iconStartMarker[0] && nextChar === exports.iconStartMarker[1]) {
currentIconStart = offset;
// if we had a previous potential icon value without
// the closing ')', it was actually not an icon and
// so we have to add it to the actual value
appendChars(currentIconValue);
currentIconValue = exports.iconStartMarker;
offset++; // jump over '('
}
// end of icon: some value $(some-icon) <--
else if (char === ')' && currentIconStart !== -1) {
const currentIconLength = offset - currentIconStart + 1; // +1 to include the closing ')'
iconsOffset += currentIconLength;
currentIconStart = -1;
currentIconValue = '';
}
// within icon
else if (currentIconStart !== -1) {
// Make sure this is a real icon name
if (/^[a-z0-9\-]$/i.test(char)) {
currentIconValue += char;
}
else {
// This is not a real icon, treat it as text
appendChars(currentIconValue);
currentIconStart = -1;
currentIconValue = '';
}
}
// any value outside of icon
else {
appendChars(char);
}
offset++;
}
// if we had a previous potential icon value without
// the closing ')', it was actually not an icon and
// so we have to add it to the actual value
appendChars(currentIconValue);
return { text: textWithoutIcons, 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;
}
exports.matchesFuzzyIconAware = matchesFuzzyIconAware;
});
/*---------------------------------------------------------------------------------------------
* 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/htmlContent*/], __M([0/*require*/,1/*exports*/,104/*vs/base/common/iconLabels*/,12/*vs/base/common/errors*/]), function (require, exports, iconLabels_1, errors_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseHrefAndDimensions = exports.removeMarkdownEscapes = exports.escapeMarkdownSyntaxTokens = exports.isMarkdownString = exports.isEmptyMarkdownString = exports.MarkdownString = void 0;
class MarkdownString {
constructor(value = '', isTrustedOrOptions = false) {
var _a, _b;
this.value = value;
if (typeof this.value !== 'string') {
throw (0, errors_1.illegalArgument)('value');
}
if (typeof isTrustedOrOptions === 'boolean') {
this.isTrusted = isTrustedOrOptions;
this.supportThemeIcons = false;
}
else {
this.isTrusted = (_a = isTrustedOrOptions.isTrusted) !== null && _a !== void 0 ? _a : undefined;
this.supportThemeIcons = (_b = isTrustedOrOptions.supportThemeIcons) !== null && _b !== void 0 ? _b : false;
}
}
appendText(value, newlineStyle = 0 /* Paragraph */) {
this.value += escapeMarkdownSyntaxTokens(this.supportThemeIcons ? (0, iconLabels_1.escapeIcons)(value) : value)
.replace(/([ \t]+)/g, (_match, g1) => '&nbsp;'.repeat(g1.length))
.replace(/^>/gm, '\\>')
.replace(/\n/g, newlineStyle === 1 /* Break */ ? '\\\n' : '\n\n');
return this;
}
appendMarkdown(value) {
this.value += value;
return this;
}
appendCodeblock(langId, code) {
this.value += '\n```';
this.value += langId;
this.value += '\n';
this.value += code;
this.value += '\n```\n';
return this;
}
}
exports.MarkdownString = MarkdownString;
function isEmptyMarkdownString(oneOrMany) {
if (isMarkdownString(oneOrMany)) {
return !oneOrMany.value;
}
else if (Array.isArray(oneOrMany)) {
return oneOrMany.every(isEmptyMarkdownString);
}
else {
return true;
}
}
exports.isEmptyMarkdownString = isEmptyMarkdownString;
function isMarkdownString(thing) {
if (thing instanceof MarkdownString) {
return true;
}
else if (thing && typeof thing === 'object') {
return typeof thing.value === 'string'
&& (typeof thing.isTrusted === 'boolean' || thing.isTrusted === undefined)
&& (typeof thing.supportThemeIcons === 'boolean' || thing.supportThemeIcons === undefined);
}
return false;
}
exports.isMarkdownString = isMarkdownString;
function escapeMarkdownSyntaxTokens(text) {
// escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
return text.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&');
}
exports.escapeMarkdownSyntaxTokens = escapeMarkdownSyntaxTokens;
function removeMarkdownEscapes(text) {
if (!text) {
return text;
}
return text.replace(/\\([\\`*_{}[\]()#+\-.!])/g, '$1');
}
exports.removeMarkdownEscapes = removeMarkdownEscapes;
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 };
}
exports.parseHrefAndDimensions = parseHrefAndDimensions;
});
/*---------------------------------------------------------------------------------------------
* 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/base/common/marshalling*/], __M([0/*require*/,1/*exports*/,103/*vs/base/common/buffer*/,24/*vs/base/common/uri*/]), function (require, exports, buffer_1, uri_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.revive = exports.parse = void 0;
function parse(text) {
let data = JSON.parse(text);
data = revive(data);
return data;
}
exports.parse = parse;
function revive(obj, depth = 0) {
if (!obj || depth > 200) {
return obj;
}
if (typeof obj === 'object') {
switch (obj.$mid) {
case 1 /* Uri */: return uri_1.URI.revive(obj);
case 2 /* Regexp */: return new RegExp(obj.source, obj.flags);
}
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;
}
exports.revive = revive;
});
/*---------------------------------------------------------------------------------------------
* 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/common/network*/], __M([0/*require*/,1/*exports*/,24/*vs/base/common/uri*/,17/*vs/base/common/platform*/]), function (require, exports, uri_1, platform) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileAccess = exports.RemoteAuthorities = exports.Schemas = void 0;
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.userData = 'vscode-userdata';
Schemas.vscodeCustomEditor = 'vscode-custom-editor';
Schemas.vscodeNotebook = 'vscode-notebook';
Schemas.vscodeNotebookCell = 'vscode-notebook-cell';
Schemas.vscodeNotebookCellMetadata = 'vscode-notebook-cell-metadata';
Schemas.vscodeNotebookCellOutput = 'vscode-notebook-cell-output';
Schemas.vscodeInteractive = 'vscode-interactive';
Schemas.vscodeInteractiveInput = 'vscode-interactive-input';
Schemas.vscodeSettings = 'vscode-settings';
Schemas.vscodeWorkspaceTrust = 'vscode-workspace-trust';
Schemas.vscodeTerminal = 'vscode-terminal';
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';
})(Schemas = exports.Schemas || (exports.Schemas = {}));
class RemoteAuthoritiesImpl {
constructor() {
this._hosts = Object.create(null);
this._ports = Object.create(null);
this._connectionTokens = Object.create(null);
this._preferredWebSchema = 'http';
this._delegate = null;
}
setPreferredWebSchema(schema) {
this._preferredWebSchema = schema;
}
rewrite(uri) {
if (this._delegate) {
return this._delegate(uri);
}
const authority = uri.authority;
let host = this._hosts[authority];
if (host && 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 += `&tkn=${encodeURIComponent(connectionToken)}`;
}
return uri_1.URI.from({
scheme: platform.isWeb ? this._preferredWebSchema : Schemas.vscodeRemoteResource,
authority: `${host}:${port}`,
path: `/vscode-remote-resource`,
query
});
}
}
exports.RemoteAuthorities = new RemoteAuthoritiesImpl();
class FileAccessImpl {
constructor() {
this.FALLBACK_AUTHORITY = 'vscode-app';
}
asBrowserUri(uriOrModule, moduleIdToUrl, __forceCodeFileUri) {
const uri = this.toUri(uriOrModule, moduleIdToUrl);
// Handle remote URIs via `RemoteAuthorities`
if (uri.scheme === Schemas.vscodeRemote) {
return exports.RemoteAuthorities.rewrite(uri);
}
let convertToVSCodeFileResource = false;
// Only convert the URI if we are in a native context and it has `file:` scheme
// and we have explicitly enabled the conversion (sandbox, or VSCODE_BROWSER_CODE_LOADING)
if (platform.isNative && (__forceCodeFileUri || platform.isPreferringBrowserCodeLoad) && uri.scheme === Schemas.file) {
convertToVSCodeFileResource = true;
}
// Also convert `file:` URIs in the web worker extension host (running in desktop) case
if (uri.scheme === Schemas.file && typeof platform.globals.importScripts === 'function' && platform.globals.origin === 'vscode-file://vscode-app') {
convertToVSCodeFileResource = true;
}
if (convertToVSCodeFileResource) {
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 || this.FALLBACK_AUTHORITY,
query: null,
fragment: null
});
}
return uri;
}
toUri(uriOrModule, moduleIdToUrl) {
if (uri_1.URI.isUri(uriOrModule)) {
return uriOrModule;
}
return uri_1.URI.parse(moduleIdToUrl.toUrl(uriOrModule));
}
}
exports.FileAccess = new FileAccessImpl();
});
/*---------------------------------------------------------------------------------------------
* 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/base/browser/dom*/], __M([0/*require*/,1/*exports*/,39/*vs/base/browser/browser*/,51/*vs/base/browser/keyboardEvent*/,55/*vs/base/browser/mouseEvent*/,15/*vs/base/common/async*/,12/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,46/*vs/base/common/network*/,156/*vs/base/browser/canIUse*/]), function (require, exports, browser, keyboardEvent_1, mouseEvent_1, async_1, errors_1, event_1, lifecycle_1, platform, network_1, canIUse_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addMatchMediaChangeListener = exports.ModifierKeyEmitter = exports.asCSSPropertyValue = exports.asCSSUrl = exports.animate = exports.windowOpenNoOpener = exports.computeScreenAwareSize = exports.getElementsByTagName = exports.hide = exports.show = exports.$ = exports.Namespace = exports.reset = exports.prepend = exports.append = exports.trackFocus = exports.restoreParentsScrollTop = exports.saveParentsScrollTop = exports.EventHelper = exports.EventType = exports.isHTMLElement = exports.removeCSSRulesContainingSelector = exports.createCSSRule = exports.createStyleSheet = exports.getActiveElement = exports.getShadowRoot = exports.isInShadowDOM = exports.isShadowRoot = exports.hasParentWithClass = exports.findParentWithClass = exports.isAncestor = exports.getTotalHeight = exports.getContentHeight = exports.getContentWidth = exports.getTotalWidth = exports.StandardWindow = exports.getDomNodePagePosition = exports.size = exports.getTopLeftOffset = exports.Dimension = exports.getClientArea = exports.getComputedStyle = exports.addDisposableThrottledListener = exports.scheduleAtNextAnimationFrame = exports.runAtThisOrScheduleAtNextAnimationFrame = exports.addDisposableNonBubblingPointerOutListener = exports.addDisposableNonBubblingMouseOutListener = exports.addDisposableGenericMouseUpListner = exports.addDisposableGenericMouseDownListner = exports.addStandardDisposableGenericMouseDownListner = exports.addStandardDisposableListener = exports.addDisposableListener = exports.isInDOM = exports.clearNode = void 0;
function clearNode(node) {
while (node.firstChild) {
node.firstChild.remove();
}
}
exports.clearNode = clearNode;
/**
* @deprecated Use node.isConnected directly
*/
function isInDOM(node) {
var _a;
return (_a = node === null || node === void 0 ? void 0 : node.isConnected) !== null && _a !== void 0 ? _a : false;
}
exports.isInDOM = isInDOM;
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);
}
exports.addDisposableListener = addDisposableListener;
function _wrapAsStandardMouseEvent(handler) {
return function (e) {
return handler(new mouseEvent_1.StandardMouseEvent(e));
};
}
function _wrapAsStandardKeyboardEvent(handler) {
return function (e) {
return handler(new keyboardEvent_1.StandardKeyboardEvent(e));
};
}
let addStandardDisposableListener = function addStandardDisposableListener(node, type, handler, useCapture) {
let wrapHandler = handler;
if (type === 'click' || type === 'mousedown') {
wrapHandler = _wrapAsStandardMouseEvent(handler);
}
else if (type === 'keydown' || type === 'keypress' || type === 'keyup') {
wrapHandler = _wrapAsStandardKeyboardEvent(handler);
}
return addDisposableListener(node, type, wrapHandler, useCapture);
};
exports.addStandardDisposableListener = addStandardDisposableListener;
let addStandardDisposableGenericMouseDownListner = function addStandardDisposableListener(node, handler, useCapture) {
let wrapHandler = _wrapAsStandardMouseEvent(handler);
return addDisposableGenericMouseDownListner(node, wrapHandler, useCapture);
};
exports.addStandardDisposableGenericMouseDownListner = addStandardDisposableGenericMouseDownListner;
function addDisposableGenericMouseDownListner(node, handler, useCapture) {
return addDisposableListener(node, platform.isIOS && canIUse_1.BrowserFeatures.pointerEvents ? exports.EventType.POINTER_DOWN : exports.EventType.MOUSE_DOWN, handler, useCapture);
}
exports.addDisposableGenericMouseDownListner = addDisposableGenericMouseDownListner;
function addDisposableGenericMouseUpListner(node, handler, useCapture) {
return addDisposableListener(node, platform.isIOS && canIUse_1.BrowserFeatures.pointerEvents ? exports.EventType.POINTER_UP : exports.EventType.MOUSE_UP, handler, useCapture);
}
exports.addDisposableGenericMouseUpListner = addDisposableGenericMouseUpListner;
function addDisposableNonBubblingMouseOutListener(node, handler) {
return addDisposableListener(node, 'mouseout', (e) => {
// Mouse out bubbles, so this is an attempt to ignore faux mouse outs coming from children elements
let toElement = (e.relatedTarget);
while (toElement && toElement !== node) {
toElement = toElement.parentNode;
}
if (toElement === node) {
return;
}
handler(e);
});
}
exports.addDisposableNonBubblingMouseOutListener = addDisposableNonBubblingMouseOutListener;
function addDisposableNonBubblingPointerOutListener(node, handler) {
return addDisposableListener(node, 'pointerout', (e) => {
// Mouse out bubbles, so this is an attempt to ignore faux mouse outs coming from children elements
let toElement = (e.relatedTarget);
while (toElement && toElement !== node) {
toElement = toElement.parentNode;
}
if (toElement === node) {
return;
}
handler(e);
});
}
exports.addDisposableNonBubblingPointerOutListener = addDisposableNonBubblingPointerOutListener;
let _animationFrame = null;
function doRequestAnimationFrame(callback) {
if (!_animationFrame) {
const emulatedRequestAnimationFrame = (callback) => {
return setTimeout(() => callback(new Date().getTime()), 0);
};
_animationFrame = (self.requestAnimationFrame
|| self.msRequestAnimationFrame
|| self.webkitRequestAnimationFrame
|| self.mozRequestAnimationFrame
|| self.oRequestAnimationFrame
|| emulatedRequestAnimationFrame);
}
return _animationFrame.call(self, callback);
}
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
*/
let NEXT_QUEUE = [];
/**
* The runners scheduled at the current animation frame
*/
let CURRENT_QUEUE = null;
/**
* A flag to keep track if the native requestAnimationFrame was already called
*/
let animFrameRequested = false;
/**
* A flag to indicate if currently handling a native requestAnimationFrame callback
*/
let inAnimationFrameRunner = false;
let animationFrameRunner = () => {
animFrameRequested = false;
CURRENT_QUEUE = NEXT_QUEUE;
NEXT_QUEUE = [];
inAnimationFrameRunner = true;
while (CURRENT_QUEUE.length > 0) {
CURRENT_QUEUE.sort(AnimationFrameQueueItem.sort);
let top = CURRENT_QUEUE.shift();
top.execute();
}
inAnimationFrameRunner = false;
};
exports.scheduleAtNextAnimationFrame = (runner, priority = 0) => {
let item = new AnimationFrameQueueItem(runner, priority);
NEXT_QUEUE.push(item);
if (!animFrameRequested) {
animFrameRequested = true;
doRequestAnimationFrame(animationFrameRunner);
}
return item;
};
exports.runAtThisOrScheduleAtNextAnimationFrame = (runner, priority) => {
if (inAnimationFrameRunner) {
let item = new AnimationFrameQueueItem(runner, priority);
CURRENT_QUEUE.push(item);
return item;
}
else {
return (0, exports.scheduleAtNextAnimationFrame)(runner, priority);
}
};
})();
const MINIMUM_TIME_MS = 8;
const DEFAULT_EVENT_MERGER = function (lastEvent, currentEvent) {
return currentEvent;
};
class TimeoutThrottledDomListener extends lifecycle_1.Disposable {
constructor(node, type, handler, eventMerger = DEFAULT_EVENT_MERGER, minimumTimeMs = MINIMUM_TIME_MS) {
super();
let lastEvent = null;
let lastHandlerTime = 0;
let timeout = this._register(new async_1.TimeoutTimer());
let invokeHandler = () => {
lastHandlerTime = (new Date()).getTime();
handler(lastEvent);
lastEvent = null;
};
this._register(addDisposableListener(node, type, (e) => {
lastEvent = eventMerger(lastEvent, e);
let elapsedTime = (new Date()).getTime() - lastHandlerTime;
if (elapsedTime >= minimumTimeMs) {
timeout.cancel();
invokeHandler();
}
else {
timeout.setIfNotSet(invokeHandler, minimumTimeMs - elapsedTime);
}
}));
}
}
function addDisposableThrottledListener(node, type, handler, eventMerger, minimumTimeMs) {
return new TimeoutThrottledDomListener(node, type, handler, eventMerger, minimumTimeMs);
}
exports.addDisposableThrottledListener = addDisposableThrottledListener;
function getComputedStyle(el) {
return document.defaultView.getComputedStyle(el, null);
}
exports.getComputedStyle = getComputedStyle;
function getClientArea(element) {
// Try with DOM clientWidth / clientHeight
if (element !== document.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 && window.visualViewport) {
return new Dimension(window.visualViewport.width, window.visualViewport.height);
}
// Try innerWidth / innerHeight
if (window.innerWidth && window.innerHeight) {
return new Dimension(window.innerWidth, window.innerHeight);
}
// Try with document.body.clientWidth / document.body.clientHeight
if (document.body && document.body.clientWidth && document.body.clientHeight) {
return new Dimension(document.body.clientWidth, document.body.clientHeight);
}
// Try with document.documentElement.clientWidth / document.documentElement.clientHeight
if (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientHeight) {
return new Dimension(document.documentElement.clientWidth, document.documentElement.clientHeight);
}
throw new Error('Unable to figure out browser width and height');
}
exports.getClientArea = getClientArea;
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) {
let computedStyle = getComputedStyle(element);
let value = '0';
if (computedStyle) {
if (computedStyle.getPropertyValue) {
value = computedStyle.getPropertyValue(cssPropertyName);
}
else {
// IE8
value = computedStyle.getAttribute(jsPropertyName);
}
}
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 {
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 !== document.body
&& element !== document.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
};
}
exports.getTopLeftOffset = getTopLeftOffset;
function size(element, width, height) {
if (typeof width === 'number') {
element.style.width = `${width}px`;
}
if (typeof height === 'number') {
element.style.height = `${height}px`;
}
}
exports.size = size;
/**
* Returns the position of a dom node relative to the entire page.
*/
function getDomNodePagePosition(domNode) {
let bb = domNode.getBoundingClientRect();
return {
left: bb.left + exports.StandardWindow.scrollX,
top: bb.top + exports.StandardWindow.scrollY,
width: bb.width,
height: bb.height
};
}
exports.getDomNodePagePosition = getDomNodePagePosition;
exports.StandardWindow = new class {
get scrollX() {
if (typeof window.scrollX === 'number') {
// modern browsers
return window.scrollX;
}
else {
return document.body.scrollLeft + document.documentElement.scrollLeft;
}
}
get scrollY() {
if (typeof window.scrollY === 'number') {
// modern browsers
return window.scrollY;
}
else {
return document.body.scrollTop + document.documentElement.scrollTop;
}
}
};
// Adapted from WinJS
// Gets the width of the element, including margins.
function getTotalWidth(element) {
let margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);
return element.offsetWidth + margin;
}
exports.getTotalWidth = getTotalWidth;
function getContentWidth(element) {
let border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element);
let padding = SizeUtils.getPaddingLeft(element) + SizeUtils.getPaddingRight(element);
return element.offsetWidth - border - padding;
}
exports.getContentWidth = getContentWidth;
// 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) {
let border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element);
let padding = SizeUtils.getPaddingTop(element) + SizeUtils.getPaddingBottom(element);
return element.offsetHeight - border - padding;
}
exports.getContentHeight = getContentHeight;
// Adapted from WinJS
// Gets the height of the element, including its margins.
function getTotalHeight(element) {
let margin = SizeUtils.getMarginTop(element) + SizeUtils.getMarginBottom(element);
return element.offsetHeight + margin;
}
exports.getTotalHeight = getTotalHeight;
// ----------------------------------------------------------------------------------------
function isAncestor(testChild, testAncestor) {
while (testChild) {
if (testChild === testAncestor) {
return true;
}
testChild = testChild.parentNode;
}
return false;
}
exports.isAncestor = isAncestor;
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;
}
exports.findParentWithClass = findParentWithClass;
function hasParentWithClass(node, clazz, stopAtClazzOrNode) {
return !!findParentWithClass(node, clazz, stopAtClazzOrNode);
}
exports.hasParentWithClass = hasParentWithClass;
function isShadowRoot(node) {
return (node && !!node.host && !!node.mode);
}
exports.isShadowRoot = isShadowRoot;
function isInShadowDOM(domNode) {
return !!getShadowRoot(domNode);
}
exports.isInShadowDOM = isInShadowDOM;
function getShadowRoot(domNode) {
while (domNode.parentNode) {
if (domNode === document.body) {
// reached the body
return null;
}
domNode = domNode.parentNode;
}
return isShadowRoot(domNode) ? domNode : null;
}
exports.getShadowRoot = getShadowRoot;
function getActiveElement() {
let result = document.activeElement;
while (result === null || result === void 0 ? void 0 : result.shadowRoot) {
result = result.shadowRoot.activeElement;
}
return result;
}
exports.getActiveElement = getActiveElement;
function createStyleSheet(container = document.getElementsByTagName('head')[0]) {
let style = document.createElement('style');
style.type = 'text/css';
style.media = 'screen';
container.appendChild(style);
return style;
}
exports.createStyleSheet = createStyleSheet;
let _sharedStyleSheet = null;
function getSharedStyleSheet() {
if (!_sharedStyleSheet) {
_sharedStyleSheet = createStyleSheet();
}
return _sharedStyleSheet;
}
function getDynamicStyleSheetRules(style) {
var _a, _b;
if ((_a = style === null || style === void 0 ? void 0 : style.sheet) === null || _a === void 0 ? void 0 : _a.rules) {
// Chrome, IE
return style.sheet.rules;
}
if ((_b = style === null || style === void 0 ? void 0 : style.sheet) === null || _b === void 0 ? void 0 : _b.cssRules) {
// FF
return style.sheet.cssRules;
}
return [];
}
function createCSSRule(selector, cssText, style = getSharedStyleSheet()) {
if (!style || !cssText) {
return;
}
style.sheet.insertRule(selector + '{' + cssText + '}', 0);
}
exports.createCSSRule = createCSSRule;
function removeCSSRulesContainingSelector(ruleName, style = getSharedStyleSheet()) {
if (!style) {
return;
}
let rules = getDynamicStyleSheetRules(style);
let toDelete = [];
for (let i = 0; i < rules.length; i++) {
let rule = rules[i];
if (rule.selectorText.indexOf(ruleName) !== -1) {
toDelete.push(i);
}
}
for (let i = toDelete.length - 1; i >= 0; i--) {
style.sheet.deleteRule(toDelete[i]);
}
}
exports.removeCSSRulesContainingSelector = removeCSSRulesContainingSelector;
function isHTMLElement(o) {
if (typeof HTMLElement === 'object') {
return o instanceof HTMLElement;
}
return o && typeof o === 'object' && o.nodeType === 1 && typeof o.nodeName === 'string';
}
exports.isHTMLElement = isHTMLElement;
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',
CONTEXT_MENU: 'contextmenu',
WHEEL: 'wheel',
// Keyboard
KEY_DOWN: 'keydown',
KEY_PRESS: 'keypress',
KEY_UP: 'keyup',
// HTML Document
LOAD: 'load',
BEFORE_UNLOAD: 'beforeunload',
UNLOAD: 'unload',
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'
};
exports.EventHelper = {
stop: function (e, cancelBubble) {
if (e.preventDefault) {
e.preventDefault();
}
else {
// IE8
e.returnValue = false;
}
if (cancelBubble) {
if (e.stopPropagation) {
e.stopPropagation();
}
else {
// IE8
e.cancelBubble = true;
}
}
}
};
function saveParentsScrollTop(node) {
let r = [];
for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
r[i] = node.scrollTop;
node = node.parentNode;
}
return r;
}
exports.saveParentsScrollTop = saveParentsScrollTop;
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;
}
}
exports.restoreParentsScrollTop = restoreParentsScrollTop;
class FocusTracker extends lifecycle_1.Disposable {
constructor(element) {
super();
this._onDidFocus = this._register(new event_1.Emitter());
this.onDidFocus = this._onDidFocus.event;
this._onDidBlur = this._register(new event_1.Emitter());
this.onDidBlur = this._onDidBlur.event;
let hasFocus = isAncestor(document.activeElement, element);
let loosingFocus = false;
const onFocus = () => {
loosingFocus = false;
if (!hasFocus) {
hasFocus = true;
this._onDidFocus.fire();
}
};
const onBlur = () => {
if (hasFocus) {
loosingFocus = true;
window.setTimeout(() => {
if (loosingFocus) {
loosingFocus = false;
hasFocus = false;
this._onDidBlur.fire();
}
}, 0);
}
};
this._refreshStateHandler = () => {
let currentNodeHasFocus = isAncestor(document.activeElement, 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));
}
}
function trackFocus(element) {
return new FocusTracker(element);
}
exports.trackFocus = trackFocus;
function append(parent, ...children) {
parent.append(...children);
if (children.length === 1 && typeof children[0] !== 'string') {
return children[0];
}
}
exports.append = append;
function prepend(parent, child) {
parent.insertBefore(child, parent.firstChild);
return child;
}
exports.prepend = prepend;
/**
* Removes all children from `parent` and appends `children`
*/
function reset(parent, ...children) {
parent.innerText = '';
append(parent, ...children);
}
exports.reset = reset;
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 || (exports.Namespace = {}));
function _$(namespace, description, attrs, ...children) {
let match = SELECTOR_REGEX.exec(description);
if (!match) {
throw new Error('Bad use of emmet');
}
attrs = Object.assign({}, (attrs || {}));
let 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();
}
Object.keys(attrs).forEach(name => {
const value = attrs[name];
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);
}
exports.$ = $;
$.SVG = function (description, attrs, ...children) {
return _$(Namespace.SVG, description, attrs, ...children);
};
function show(...elements) {
for (let element of elements) {
element.style.display = '';
element.removeAttribute('aria-hidden');
}
}
exports.show = show;
function hide(...elements) {
for (let element of elements) {
element.style.display = 'none';
element.setAttribute('aria-hidden', 'true');
}
}
exports.hide = hide;
function getElementsByTagName(tag) {
return Array.prototype.slice.call(document.getElementsByTagName(tag), 0);
}
exports.getElementsByTagName = getElementsByTagName;
/**
* 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(cssPx) {
const screenPx = window.devicePixelRatio * cssPx;
return Math.max(1, Math.floor(screenPx)) / window.devicePixelRatio;
}
exports.computeScreenAwareSize = computeScreenAwareSize;
/**
* 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 brower's popup blocker.
* If you want to tell if the browser blocked the new window, use `windowOpenNoOpenerWithSuccess`.
*
* 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.open(url, '_blank', 'noopener');
}
exports.windowOpenNoOpener = windowOpenNoOpener;
function animate(fn) {
const step = () => {
fn();
stepDisposable = (0, exports.scheduleAtNextAnimationFrame)(step);
};
let stepDisposable = (0, exports.scheduleAtNextAnimationFrame)(step);
return (0, lifecycle_1.toDisposable)(() => stepDisposable.dispose());
}
exports.animate = animate;
network_1.RemoteAuthorities.setPreferredWebSchema(/^https:/.test(window.location.href) ? 'https' : 'http');
/**
* returns url('...')
*/
function asCSSUrl(uri) {
if (!uri) {
return `url('')`;
}
return `url('${network_1.FileAccess.asBrowserUri(uri).toString(true).replace(/'/g, '%27')}')`;
}
exports.asCSSUrl = asCSSUrl;
function asCSSPropertyValue(value) {
return `'${value.replace(/'/g, '%27')}'`;
}
exports.asCSSPropertyValue = asCSSPropertyValue;
class ModifierKeyEmitter extends event_1.Emitter {
constructor() {
super();
this._subscriptions = new lifecycle_1.DisposableStore();
this._keyStatus = {
altKey: false,
shiftKey: false,
ctrlKey: false,
metaKey: false
};
this._subscriptions.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 /* 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 /* 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));
this._subscriptions.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));
this._subscriptions.add(addDisposableListener(document.body, 'mousedown', () => {
this._keyStatus.lastKeyPressed = undefined;
}, true));
this._subscriptions.add(addDisposableListener(document.body, 'mouseup', () => {
this._keyStatus.lastKeyPressed = undefined;
}, true));
this._subscriptions.add(addDisposableListener(document.body, 'mousemove', e => {
if (e.buttons) {
this._keyStatus.lastKeyPressed = undefined;
}
}, true));
this._subscriptions.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;
function addMatchMediaChangeListener(query, callback) {
const mediaQueryList = window.matchMedia(query);
if (typeof mediaQueryList.addEventListener === 'function') {
mediaQueryList.addEventListener('change', callback);
}
else {
// Safari 13.x
mediaQueryList.addListener(callback);
}
}
exports.addMatchMediaChangeListener = addMatchMediaChangeListener;
});
/*---------------------------------------------------------------------------------------------
* 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/browser/formattedTextRenderer*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/]), function (require, exports, DOM) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createElement = exports.renderFormattedText = exports.renderText = void 0;
function renderText(text, options = {}) {
const element = createElement(options);
element.textContent = text;
return element;
}
exports.renderText = renderText;
function renderFormattedText(formattedText, options = {}) {
const element = createElement(options);
_renderFormattedText(element, parseFormattedText(formattedText, !!options.renderCodeSegements), options.actionHandler, options.renderCodeSegements);
return element;
}
exports.renderFormattedText = renderFormattedText;
function createElement(options) {
const tagName = options.inline ? 'span' : 'div';
const element = document.createElement(tagName);
if (options.className) {
element.className = options.className;
}
return element;
}
exports.createElement = createElement;
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, renderCodeSegements) {
let child;
if (treeNode.type === 2 /* Text */) {
child = document.createTextNode(treeNode.content || '');
}
else if (treeNode.type === 3 /* Bold */) {
child = document.createElement('b');
}
else if (treeNode.type === 4 /* Italics */) {
child = document.createElement('i');
}
else if (treeNode.type === 7 /* Code */ && renderCodeSegements) {
child = document.createElement('code');
}
else if (treeNode.type === 5 /* Action */ && actionHandler) {
const a = document.createElement('a');
a.href = '#';
actionHandler.disposeables.add(DOM.addStandardDisposableListener(a, 'click', (event) => {
actionHandler.callback(String(treeNode.index), event);
}));
child = a;
}
else if (treeNode.type === 8 /* NewLine */) {
child = document.createElement('br');
}
else if (treeNode.type === 1 /* Root */) {
child = element;
}
if (child && element !== child) {
element.appendChild(child);
}
if (child && Array.isArray(treeNode.children)) {
treeNode.children.forEach((nodeChild) => {
_renderFormattedText(child, nodeChild, actionHandler, renderCodeSegements);
});
}
}
function parseFormattedText(content, parseCodeSegments) {
const root = {
type: 1 /* 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 /* 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 /* Text */) {
current = stack.pop();
}
const type = formatTagType(next, parseCodeSegments);
if (current.type === type || (current.type === 5 /* Action */ && type === 6 /* ActionClose */)) {
current = stack.pop();
}
else {
const newCurrent = {
type: type,
children: []
};
if (type === 5 /* Action */) {
newCurrent.index = actionViewItemIndex;
actionViewItemIndex++;
}
current.children.push(newCurrent);
stack.push(current);
current = newCurrent;
}
}
else if (next === '\n') {
if (current.type === 2 /* Text */) {
current = stack.pop();
}
current.children.push({
type: 8 /* NewLine */
});
}
else {
if (current.type !== 2 /* Text */) {
const textCurrent = {
type: 2 /* Text */,
content: next
};
current.children.push(textCurrent);
stack.push(current);
current = textCurrent;
}
else {
current.content += next;
}
}
}
if (current.type === 2 /* Text */) {
current = stack.pop();
}
if (stack.length) {
// incorrectly formatted string literal
}
return root;
}
function isFormatTag(char, supportCodeSegments) {
return formatTagType(char, supportCodeSegments) !== 0 /* Invalid */;
}
function formatTagType(char, supportCodeSegments) {
switch (char) {
case '*':
return 3 /* Bold */;
case '_':
return 4 /* Italics */;
case '[':
return 5 /* Action */;
case ']':
return 6 /* ActionClose */;
case '`':
return supportCodeSegments ? 7 /* Code */ : 0 /* Invalid */;
default:
return 0 /* 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[93/*vs/base/browser/globalMouseMoveMonitor*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,196/*vs/base/browser/iframe*/,55/*vs/base/browser/mouseEvent*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/]), function (require, exports, dom, iframe_1, mouseEvent_1, lifecycle_1, platform_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GlobalMouseMoveMonitor = exports.standardMouseMoveMerger = void 0;
function standardMouseMoveMerger(lastEvent, currentEvent) {
let ev = new mouseEvent_1.StandardMouseEvent(currentEvent);
ev.preventDefault();
return {
leftButton: ev.leftButton,
buttons: ev.buttons,
posx: ev.posx,
posy: ev.posy
};
}
exports.standardMouseMoveMerger = standardMouseMoveMerger;
class GlobalMouseMoveMonitor {
constructor() {
this._hooks = new lifecycle_1.DisposableStore();
this._mouseMoveEventMerger = null;
this._mouseMoveCallback = 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._mouseMoveEventMerger = null;
this._mouseMoveCallback = null;
const onStopCallback = this._onStopCallback;
this._onStopCallback = null;
if (invokeStopCallback && onStopCallback) {
onStopCallback(browserEvent);
}
}
isMonitoring() {
return !!this._mouseMoveEventMerger;
}
startMonitoring(initialElement, initialButtons, mouseMoveEventMerger, mouseMoveCallback, onStopCallback) {
if (this.isMonitoring()) {
// I am already hooked
return;
}
this._mouseMoveEventMerger = mouseMoveEventMerger;
this._mouseMoveCallback = mouseMoveCallback;
this._onStopCallback = onStopCallback;
const windowChain = iframe_1.IframeUtils.getSameOriginWindowChain();
const mouseMove = platform_1.isIOS ? 'pointermove' : 'mousemove'; // Safari sends wrong event, workaround for #122653
const mouseUp = 'mouseup';
const listenTo = windowChain.map(element => element.window.document);
const shadowRoot = dom.getShadowRoot(initialElement);
if (shadowRoot) {
listenTo.unshift(shadowRoot);
}
for (const element of listenTo) {
this._hooks.add(dom.addDisposableThrottledListener(element, mouseMove, (data) => {
if (data.buttons !== initialButtons) {
// Buttons state has changed in the meantime
this.stopMonitoring(true);
return;
}
this._mouseMoveCallback(data);
}, (lastEvent, currentEvent) => this._mouseMoveEventMerger(lastEvent, currentEvent)));
this._hooks.add(dom.addDisposableListener(element, mouseUp, (e) => this.stopMonitoring(true)));
}
if (iframe_1.IframeUtils.hasDifferentOriginAncestor()) {
let lastSameOriginAncestor = windowChain[windowChain.length - 1];
// We might miss a mouse up if it happens outside the iframe
// This one is for Chrome
this._hooks.add(dom.addDisposableListener(lastSameOriginAncestor.window.document, 'mouseout', (browserEvent) => {
let e = new mouseEvent_1.StandardMouseEvent(browserEvent);
if (e.target.tagName.toLowerCase() === 'html') {
this.stopMonitoring(true);
}
}));
// This one is for FF
this._hooks.add(dom.addDisposableListener(lastSameOriginAncestor.window.document, 'mouseover', (browserEvent) => {
let e = new mouseEvent_1.StandardMouseEvent(browserEvent);
if (e.target.tagName.toLowerCase() === 'html') {
this.stopMonitoring(true);
}
}));
// This one is for IE
this._hooks.add(dom.addDisposableListener(lastSameOriginAncestor.window.document.body, 'mouseleave', (browserEvent) => {
this.stopMonitoring(true);
}));
}
}
}
exports.GlobalMouseMoveMonitor = GlobalMouseMoveMonitor;
});
/*---------------------------------------------------------------------------------------------
* 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[60/*vs/base/browser/touch*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,7/*vs/base/browser/dom*/,90/*vs/base/common/decorators*/]), function (require, exports, arrays, lifecycle_1, DomUtils, decorators_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 || (exports.EventType = {}));
class Gesture extends lifecycle_1.Disposable {
constructor() {
super();
this.dispatched = false;
this.activeTouches = {};
this.handle = null;
this.targets = [];
this.ignoreTargets = [];
this._lastSetTapCountTime = 0;
this._register(DomUtils.addDisposableListener(document, 'touchstart', (e) => this.onTouchStart(e), { passive: false }));
this._register(DomUtils.addDisposableListener(document, 'touchend', (e) => this.onTouchEnd(e)));
this._register(DomUtils.addDisposableListener(document, 'touchmove', (e) => this.onTouchMove(e), { passive: false }));
}
static addTarget(element) {
if (!Gesture.isTouchDevice()) {
return lifecycle_1.Disposable.None;
}
if (!Gesture.INSTANCE) {
Gesture.INSTANCE = new Gesture();
}
Gesture.INSTANCE.targets.push(element);
return {
dispose: () => {
Gesture.INSTANCE.targets = Gesture.INSTANCE.targets.filter(t => t !== element);
}
};
}
static ignoreTarget(element) {
if (!Gesture.isTouchDevice()) {
return lifecycle_1.Disposable.None;
}
if (!Gesture.INSTANCE) {
Gesture.INSTANCE = new Gesture();
}
Gesture.INSTANCE.ignoreTargets.push(element);
return {
dispose: () => {
Gesture.INSTANCE.ignoreTargets = Gesture.INSTANCE.ignoreTargets.filter(t => t !== element);
}
};
}
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 || navigator.maxTouchPoints > 0;
}
dispose() {
if (this.handle) {
this.handle.dispose();
this.handle = null;
}
super.dispose();
}
onTouchStart(e) {
let 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++) {
let 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]
};
let 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(e) {
let timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
let activeTouchCount = Object.keys(this.activeTouches).length;
for (let i = 0, len = e.changedTouches.length; i < len; i++) {
let touch = e.changedTouches.item(i);
if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
console.warn('move of an UNKNOWN touch', touch);
continue;
}
let 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) {
let 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) {
let 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) {
let finalX = arrays.tail(data.rollingPageX);
let finalY = arrays.tail(data.rollingPageY);
let deltaT = arrays.tail(data.rollingTimestamps) - data.rollingTimestamps[0];
let deltaX = finalX - data.rollingPageX[0];
let 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(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) {
let 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;
}
for (let i = 0; i < this.ignoreTargets.length; i++) {
if (event.initialTarget instanceof Node && this.ignoreTargets[i].contains(event.initialTarget)) {
return;
}
}
this.targets.forEach(target => {
if (event.initialTarget instanceof Node && target.contains(event.initialTarget)) {
target.dispatchEvent(event);
this.dispatched = true;
}
});
}
inertia(dispatchTo, t1, vX, dirX, x, vY, dirY, y) {
this.handle = DomUtils.scheduleAtNextAnimationFrame(() => {
let now = Date.now();
// velocity: old speed + accel_over_time
let deltaT = now - t1, delta_pos_x = 0, delta_pos_y = 0, 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
let 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(dispatchTo, now, vX, dirX, x + delta_pos_x, vY, dirY, y + delta_pos_y);
}
});
}
onTouchMove(e) {
let 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++) {
let touch = e.changedTouches.item(i);
if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
console.warn('end of an UNKNOWN touch', touch);
continue;
}
let data = this.activeTouches[touch.identifier];
let 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;
}
}
}
Gesture.SCROLL_FRICTION = -0.005;
Gesture.HOLD_DELAY = 700;
Gesture.CLEAR_TAP_COUNT_TIME = 400; // ms
__decorate([
decorators_1.memoize
], Gesture, "isTouchDevice", null);
exports.Gesture = Gesture;
});
/*---------------------------------------------------------------------------------------------
* 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/base/browser/ui/iconLabel/iconLabels*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,27/*vs/base/common/codicons*/]), function (require, exports, dom, codicons_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderIcon = exports.renderLabelWithIcons = void 0;
const labelWithIconsRegex = new RegExp(`(\\\\)?\\$\\((${codicons_1.CSSIcon.iconNameExpression}(?:${codicons_1.CSSIcon.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;
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;
}
exports.renderLabelWithIcons = renderLabelWithIcons;
function renderIcon(icon) {
const node = dom.$(`span`);
node.classList.add(...codicons_1.CSSIcon.asClassNameArray(icon));
return node;
}
exports.renderIcon = renderIcon;
});
/*---------------------------------------------------------------------------------------------
* 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/browser/ui/highlightedlabel/highlightedLabel*/], __M([0/*require*/,1/*exports*/,42/*vs/base/common/objects*/,7/*vs/base/browser/dom*/,105/*vs/base/browser/ui/iconLabel/iconLabels*/]), function (require, exports, objects, dom, iconLabels_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HighlightedLabel = void 0;
class HighlightedLabel {
constructor(container, supportIcons) {
this.supportIcons = supportIcons;
this.text = '';
this.title = '';
this.highlights = [];
this.didEverRender = false;
this.domNode = document.createElement('span');
this.domNode.className = 'monaco-highlighted-label';
container.appendChild(this.domNode);
}
get element() {
return this.domNode;
}
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);
children.push(dom.$('span', undefined, ...this.supportIcons ? (0, iconLabels_1.renderLabelWithIcons)(substring) : [substring]));
pos = highlight.end;
}
const substring = this.text.substring(highlight.start, 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);
children.push(dom.$('span', undefined, ...this.supportIcons ? (0, iconLabels_1.renderLabelWithIcons)(substring) : [substring]));
}
dom.reset(this.domNode, ...children);
if (this.title) {
this.domNode.title = this.title;
}
else {
this.domNode.removeAttribute('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[295/*vs/base/browser/ui/list/rowCache*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/]), function (require, exports, dom_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RowCache = void 0;
function removeFromParent(element) {
try {
if (element.parentElement) {
element.parentElement.removeChild(element);
}
}
catch (e) {
// this will throw if this happens due to a blur event, nasty business
}
}
class RowCache {
constructor(renderers) {
this.renderers = renderers;
this.cache = new Map();
}
/**
* Returns a row either by creating a new one or reusing
* a previously released row which shares the same templateId.
*/
alloc(templateId) {
let result = this.getTemplateCache(templateId).pop();
if (!result) {
const domNode = (0, dom_1.$)('.monaco-list-row');
const renderer = this.getRenderer(templateId);
const templateData = renderer.renderTemplate(domNode);
result = { domNode, templateId, templateData };
}
return result;
}
/**
* Releases the row for eventual reuse.
*/
release(row) {
if (!row) {
return;
}
this.releaseRow(row);
}
releaseRow(row) {
const { domNode, templateId } = row;
if (domNode) {
domNode.classList.remove('scrolling');
removeFromParent(domNode);
}
const cache = this.getTemplateCache(templateId);
cache.push(row);
}
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();
}
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[52/*vs/base/browser/ui/widget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,51/*vs/base/browser/keyboardEvent*/,55/*vs/base/browser/mouseEvent*/,2/*vs/base/common/lifecycle*/,60/*vs/base/browser/touch*/]), function (require, exports, dom, keyboardEvent_1, mouseEvent_1, lifecycle_1, touch_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(e))));
}
onmousedown(domNode, listener) {
this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_DOWN, (e) => listener(new mouseEvent_1.StandardMouseEvent(e))));
}
onmouseover(domNode, listener) {
this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_OVER, (e) => listener(new mouseEvent_1.StandardMouseEvent(e))));
}
onnonbubblingmouseout(domNode, listener) {
this._register(dom.addDisposableNonBubblingMouseOutListener(domNode, (e) => listener(new mouseEvent_1.StandardMouseEvent(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) {
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[162/*vs/base/browser/ui/scrollbar/scrollbarArrow*/], __M([0/*require*/,1/*exports*/,93/*vs/base/browser/globalMouseMoveMonitor*/,52/*vs/base/browser/ui/widget*/,15/*vs/base/common/async*/]), function (require, exports, globalMouseMoveMonitor_1, widget_1, async_1) {
"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(...opts.icon.classNamesArray);
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._mouseMoveMonitor = this._register(new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor());
this.onmousedown(this.bgDomNode, (e) => this._arrowMouseDown(e));
this.onmousedown(this.domNode, (e) => this._arrowMouseDown(e));
this._mousedownRepeatTimer = this._register(new async_1.IntervalTimer());
this._mousedownScheduleRepeatTimer = this._register(new async_1.TimeoutTimer());
}
_arrowMouseDown(e) {
const scheduleRepeater = () => {
this._mousedownRepeatTimer.cancelAndSet(() => this._onActivate(), 1000 / 24);
};
this._onActivate();
this._mousedownRepeatTimer.cancel();
this._mousedownScheduleRepeatTimer.cancelAndSet(scheduleRepeater, 200);
this._mouseMoveMonitor.startMonitoring(e.target, e.buttons, globalMouseMoveMonitor_1.standardMouseMoveMerger, (mouseMoveData) => {
/* Intentional empty */
}, () => {
this._mousedownRepeatTimer.cancel();
this._mousedownScheduleRepeatTimer.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[203/*vs/base/browser/ui/scrollbar/abstractScrollbar*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,93/*vs/base/browser/globalMouseMoveMonitor*/,162/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,290/*vs/base/browser/ui/scrollbar/scrollbarVisibilityController*/,52/*vs/base/browser/ui/widget*/,17/*vs/base/common/platform*/]), function (require, exports, dom, fastDomNode_1, globalMouseMoveMonitor_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 MOUSE_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._mouseMoveMonitor = this._register(new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor());
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.onmousedown(this.domNode.domNode, (e) => this._domNodeMouseDown(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.onmousedown(this.slider.domNode, (e) => {
if (e.leftButton) {
e.preventDefault();
this._sliderMouseDown(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
_domNodeMouseDown(e) {
if (e.target !== this.domNode.domNode) {
return;
}
this._onMouseDown(e);
}
delegateMouseDown(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 mousePos = this._sliderMousePosition(e);
if (sliderStart <= mousePos && mousePos <= sliderStop) {
// Act as if it was a mouse down on the slider
if (e.leftButton) {
e.preventDefault();
this._sliderMouseDown(e, () => { });
}
}
else {
// Act as if it was a mouse down on the scrollbar
this._onMouseDown(e);
}
}
_onMouseDown(e) {
let offsetX;
let offsetY;
if (e.target === this.domNode.domNode && typeof e.browserEvent.offsetX === 'number' && typeof e.browserEvent.offsetY === 'number') {
offsetX = e.browserEvent.offsetX;
offsetY = e.browserEvent.offsetY;
}
else {
const domNodePosition = dom.getDomNodePagePosition(this.domNode.domNode);
offsetX = e.posx - domNodePosition.left;
offsetY = e.posy - domNodePosition.top;
}
const offset = this._mouseDownRelativePosition(offsetX, offsetY);
this._setDesiredScrollPositionNow(this._scrollByPage
? this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(offset)
: this._scrollbarState.getDesiredScrollPositionFromOffset(offset));
if (e.leftButton) {
e.preventDefault();
this._sliderMouseDown(e, () => { });
}
}
_sliderMouseDown(e, onDragFinished) {
const initialMousePosition = this._sliderMousePosition(e);
const initialMouseOrthogonalPosition = this._sliderOrthogonalMousePosition(e);
const initialScrollbarState = this._scrollbarState.clone();
this.slider.toggleClassName('active', true);
this._mouseMoveMonitor.startMonitoring(e.target, e.buttons, globalMouseMoveMonitor_1.standardMouseMoveMerger, (mouseMoveData) => {
const mouseOrthogonalPosition = this._sliderOrthogonalMousePosition(mouseMoveData);
const mouseOrthogonalDelta = Math.abs(mouseOrthogonalPosition - initialMouseOrthogonalPosition);
if (platform.isWindows && mouseOrthogonalDelta > MOUSE_DRAG_RESET_DISTANCE) {
// The mouse has wondered away from the scrollbar => reset dragging
this._setDesiredScrollPositionNow(initialScrollbarState.getScrollPosition());
return;
}
const mousePosition = this._sliderMousePosition(mouseMoveData);
const mouseDelta = mousePosition - initialMousePosition;
this._setDesiredScrollPositionNow(initialScrollbarState.getDesiredScrollPositionFromDelta(mouseDelta));
}, () => {
this.slider.toggleClassName('active', false);
this._host.onDragEnd();
onDragFinished();
});
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[296/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/], __M([0/*require*/,1/*exports*/,55/*vs/base/browser/mouseEvent*/,203/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,162/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,197/*vs/base/browser/ui/scrollbar/scrollbarState*/,27/*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;
const scrollbarButtonLeftIcon = (0, codicons_1.registerCodicon)('scrollbar-button-left', codicons_1.Codicon.triangleLeft);
const scrollbarButtonRightIcon = (0, codicons_1.registerCodicon)('scrollbar-button-right', codicons_1.Codicon.triangleRight);
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 /* Hidden */ ? 0 : options.horizontalScrollbarSize), (options.vertical === 2 /* 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: scrollbarButtonLeftIcon,
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: scrollbarButtonRightIcon,
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;
}
_mouseDownRelativePosition(offsetX, offsetY) {
return offsetX;
}
_sliderMousePosition(e) {
return e.posx;
}
_sliderOrthogonalMousePosition(e) {
return e.posy;
}
_updateScrollbarSize(size) {
this.slider.setHeight(size);
}
writeScrollPosition(target, scrollPosition) {
target.scrollLeft = scrollPosition;
}
updateOptions(options) {
this.updateScrollbarSize(options.horizontal === 2 /* Hidden */ ? 0 : options.horizontalScrollbarSize);
this._scrollbarState.setOppositeScrollbarSize(options.vertical === 2 /* 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[297/*vs/base/browser/ui/scrollbar/verticalScrollbar*/], __M([0/*require*/,1/*exports*/,55/*vs/base/browser/mouseEvent*/,203/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,162/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,197/*vs/base/browser/ui/scrollbar/scrollbarState*/,27/*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;
const scrollbarButtonUpIcon = (0, codicons_1.registerCodicon)('scrollbar-button-up', codicons_1.Codicon.triangleUp);
const scrollbarButtonDownIcon = (0, codicons_1.registerCodicon)('scrollbar-button-down', codicons_1.Codicon.triangleDown);
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 /* 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: scrollbarButtonUpIcon,
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: scrollbarButtonDownIcon,
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;
}
_mouseDownRelativePosition(offsetX, offsetY) {
return offsetY;
}
_sliderMousePosition(e) {
return e.posy;
}
_sliderOrthogonalMousePosition(e) {
return e.posx;
}
_updateScrollbarSize(size) {
this.slider.setWidth(size);
}
writeScrollPosition(target, scrollPosition) {
target.scrollTop = scrollPosition;
}
updateOptions(options) {
this.updateScrollbarSize(options.vertical === 2 /* 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[43/*vs/base/common/resources*/], __M([0/*require*/,1/*exports*/,157/*vs/base/common/extpath*/,73/*vs/base/common/path*/,24/*vs/base/common/uri*/,8/*vs/base/common/strings*/,46/*vs/base/common/network*/]), function (require, exports, extpath, paths, uri_1, strings_1, network_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataUri = exports.resolvePath = exports.normalizePath = exports.joinPath = exports.dirname = exports.basename = exports.basenameOrAuthority = exports.isEqual = exports.extUri = exports.ExtUri = exports.originalFSPath = void 0;
function originalFSPath(uri) {
return (0, uri_1.uriToFsPath)(uri, true);
}
exports.originalFSPath = originalFSPath;
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();
}
// --- 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);
}
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 /* 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
});
}
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)
});
}
}
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);
exports.isEqual = exports.extUri.isEqual.bind(exports.extUri);
exports.basenameOrAuthority = exports.extUri.basenameOrAuthority.bind(exports.extUri);
exports.basename = exports.extUri.basename.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.resolvePath = exports.extUri.resolvePath.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 || (exports.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[298/*vs/base/browser/markdownRenderer*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,160/*vs/base/browser/formattedTextRenderer*/,12/*vs/base/common/errors*/,82/*vs/base/common/htmlContent*/,125/*vs/base/common/idGenerator*/,700/*vs/base/common/marked/marked*/,701/*vs/base/common/insane/insane*/,202/*vs/base/common/marshalling*/,42/*vs/base/common/objects*/,8/*vs/base/common/strings*/,24/*vs/base/common/uri*/,46/*vs/base/common/network*/,104/*vs/base/common/iconLabels*/,43/*vs/base/common/resources*/,55/*vs/base/browser/mouseEvent*/,105/*vs/base/browser/ui/iconLabel/iconLabels*/,6/*vs/base/common/event*/,91/*vs/base/browser/event*/]), function (require, exports, DOM, formattedTextRenderer_1, errors_1, htmlContent_1, idGenerator_1, marked, insane_1, marshalling_1, objects_1, strings_1, uri_1, network_1, iconLabels_1, resources_1, mouseEvent_1, iconLabels_2, event_1, event_2) {
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderMarkdown = void 0;
const _ttpInsane = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('insane', {
createHTML(value, options) {
return (0, insane_1.insane)(value, options);
}
});
/**
* Low-level way create a html element from a markdown string.
*
* **Note** that for most cases you should be using [`MarkdownRenderer`](./src/vs/editor/browser/core/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 = {}) {
var _a;
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];
if (!data) {
return href; // no uri exists
}
let uri = uri_1.URI.revive(data);
if (uri_1.URI.parse(href).toString() === uri.toString()) {
return href; // no tranformation performed
}
if (isDomUri) {
// 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.asBrowserUri(uri).toString(true);
}
if (uri.query) {
uri = uri.with({ query: _uriMassage(uri.query) });
}
return uri.toString();
};
// signal to code-block render that the
// element has been created
let signalInnerHTML;
const withInnerHTML = new Promise(c => signalInnerHTML = c);
const renderer = new marked.Renderer();
renderer.image = (href, title, text) => {
let dimensions = [];
let attributes = [];
if (href) {
({ href, dimensions } = (0, htmlContent_1.parseHrefAndDimensions)(href));
href = _href(href, true);
try {
const hrefAsUri = uri_1.URI.parse(href);
if (options.baseUrl && hrefAsUri.scheme === network_1.Schemas.file) { // absolute or relative local path, or file: uri
href = (0, resources_1.resolvePath)(options.baseUrl, href).toString();
}
}
catch (err) { }
attributes.push(`src="${href}"`);
}
if (text) {
attributes.push(`alt="${text}"`);
}
if (title) {
attributes.push(`title="${title}"`);
}
if (dimensions.length) {
attributes = attributes.concat(dimensions);
}
return '<img ' + attributes.join(' ') + '>';
};
renderer.link = (href, title, text) => {
// Remove markdown escapes. Workaround for https://github.com/chjj/marked/issues/829
if (href === text) { // raw link case
text = (0, htmlContent_1.removeMarkdownEscapes)(text);
}
href = _href(href, false);
if (options.baseUrl) {
const hasScheme = /^\w[\w\d+.-]*:/.test(href);
if (!hasScheme) {
href = (0, resources_1.resolvePath)(options.baseUrl, href).toString();
}
}
title = (0, htmlContent_1.removeMarkdownEscapes)(title);
href = (0, htmlContent_1.removeMarkdownEscapes)(href);
if (!href
|| href.match(/^data:|javascript:/i)
|| (href.match(/^command:/i) && !markdown.isTrusted)
|| href.match(/^command:(\/\/\/)?_workbench\.downloadResource/i)) {
// drop the link
return text;
}
else {
// HTML Encode href
href = href.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
return `<a href="#" data-href="${href}" title="${title || href}">${text}</a>`;
}
};
renderer.paragraph = (text) => {
if (markdown.supportThemeIcons) {
const elements = (0, iconLabels_2.renderLabelWithIcons)(text);
text = elements.map(e => typeof e === 'string' ? e : e.outerHTML).join('');
}
return `<p>${text}</p>`;
};
if (options.codeBlockRenderer) {
renderer.code = (code, lang) => {
const value = options.codeBlockRenderer(lang, code);
// when code-block rendering is async we return sync
// but update the node with the real result later.
const id = idGenerator_1.defaultGenerator.nextId();
const promise = Promise.all([value, withInnerHTML]).then(values => {
const span = element.querySelector(`div[data-code="${id}"]`);
if (span) {
DOM.reset(span, values[0]);
}
}).catch(_err => {
// ignore
});
if (options.asyncRenderCallback) {
promise.then(options.asyncRenderCallback);
}
return `<div class="code" data-code="${id}">${(0, strings_1.escape)(code)}</div>`;
};
}
if (options.actionHandler) {
const onClick = options.actionHandler.disposeables.add(new event_2.DomEmitter(element, 'click'));
const onAuxClick = options.actionHandler.disposeables.add(new event_2.DomEmitter(element, 'auxclick'));
options.actionHandler.disposeables.add(event_1.Event.any(onClick.event, onAuxClick.event)(e => {
const mouseEvent = new mouseEvent_1.StandardMouseEvent(e);
if (!mouseEvent.leftButton && !mouseEvent.middleButton) {
return;
}
let target = mouseEvent.target;
if (target.tagName !== 'A') {
target = target.parentElement;
if (!target || target.tagName !== 'A') {
return;
}
}
try {
const href = target.dataset['href'];
if (href) {
options.actionHandler.callback(href, mouseEvent);
}
}
catch (err) {
(0, errors_1.onUnexpectedError)(err);
}
finally {
mouseEvent.preventDefault();
}
}));
}
// Use our own sanitizer so that we can let through only spans.
// Otherwise, we'd be letting all html be rendered.
// If we want to allow markdown permitted tags, then we can delete sanitizer and sanitize.
// We always pass the output through insane after this so that we don't rely on
// marked for sanitization.
markedOptions.sanitizer = (html) => {
const match = markdown.isTrusted ? html.match(/^(<span[^>]+>)|(<\/\s*span>)$/) : undefined;
return match ? html : '';
};
markedOptions.sanitize = true;
markedOptions.silent = true;
markedOptions.renderer = renderer;
// values that are too long will freeze the UI
let value = (_a = markdown.value) !== null && _a !== void 0 ? _a : '';
if (value.length > 100000) {
value = `${value.substr(0, 100000)}…`;
}
// escape theme icons
if (markdown.supportThemeIcons) {
value = (0, iconLabels_1.markdownEscapeEscapedIcons)(value);
}
const renderedMarkdown = marked.parse(value, markedOptions);
// sanitize with insane
element.innerHTML = sanitizeRenderedMarkdown(markdown, renderedMarkdown);
// signal that async code blocks can be now be inserted
signalInnerHTML();
// signal size changes for image tags
if (options.asyncRenderCallback) {
for (const img of element.getElementsByTagName('img')) {
const listener = DOM.addDisposableListener(img, 'load', () => {
listener.dispose();
options.asyncRenderCallback();
});
}
}
return element;
}
exports.renderMarkdown = renderMarkdown;
function sanitizeRenderedMarkdown(options, renderedMarkdown) {
var _a;
const insaneOptions = getInsaneOptions(options);
return (_a = _ttpInsane === null || _ttpInsane === void 0 ? void 0 : _ttpInsane.createHTML(renderedMarkdown, insaneOptions)) !== null && _a !== void 0 ? _a : (0, insane_1.insane)(renderedMarkdown, insaneOptions);
}
function getInsaneOptions(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.vscodeRemote,
network_1.Schemas.vscodeRemoteResource,
];
if (options.isTrusted) {
allowedSchemes.push(network_1.Schemas.command);
}
return {
allowedSchemes,
// 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 insane 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-
allowedTags: ['ul', 'li', 'p', 'code', 'blockquote', 'ol', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'em', 'pre', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'div', 'del', 'a', 'strong', 'br', 'img', 'span'],
allowedAttributes: {
'a': ['href', 'name', 'target', 'data-href'],
'img': ['src', 'title', 'alt', 'width', 'height'],
'div': ['class', 'data-code'],
'span': ['class', 'style'],
// https://github.com/microsoft/vscode/issues/95937
'th': ['align'],
'td': ['align']
},
filter(token) {
if (token.tag === 'span' && options.isTrusted) {
if (token.attrs['style'] && (Object.keys(token.attrs).length === 1)) {
return !!token.attrs['style'].match(/^(color\:#[0-9a-fA-F]+;)?(background-color\:#[0-9a-fA-F]+;)?$/);
}
else if (token.attrs['class']) {
// The class should match codicon rendering in src\vs\base\common\codicons.ts
return !!token.attrs['class'].match(/^codicon codicon-[a-z\-]+( codicon-modifier-[a-z\-]+)?$/);
}
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[163/*vs/base/common/labels*/], __M([0/*require*/,1/*exports*/,24/*vs/base/common/uri*/,46/*vs/base/common/network*/,17/*vs/base/common/platform*/,43/*vs/base/common/resources*/,157/*vs/base/common/extpath*/]), function (require, exports, uri_1, network_1, platform_1, resources_1, extpath_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeDriveLetter = exports.getBaseLabel = void 0;
function getBaseLabel(resource) {
if (!resource) {
return undefined;
}
if (typeof resource === 'string') {
resource = uri_1.URI.file(resource);
}
const base = (0, resources_1.basename)(resource) || (resource.scheme === network_1.Schemas.file ? resource.fsPath : resource.path) /* can be empty string if '/' is passed in */;
// convert c: => C:
if (platform_1.isWindows && (0, extpath_1.isRootOrDriveLetter)(base)) {
return normalizeDriveLetter(base);
}
return base;
}
exports.getBaseLabel = getBaseLabel;
function normalizeDriveLetter(path) {
if ((0, extpath_1.hasDriveLetter)(path)) {
return path.charAt(0).toUpperCase() + path.slice(1);
}
return path;
}
exports.normalizeDriveLetter = normalizeDriveLetter;
});
/*---------------------------------------------------------------------------------------------
* 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/base/common/mime*/], __M([0/*require*/,1/*exports*/,73/*vs/base/common/path*/,8/*vs/base/common/strings*/,201/*vs/base/common/glob*/,46/*vs/base/common/network*/,43/*vs/base/common/resources*/]), function (require, exports, path_1, strings_1, glob_1, network_1, resources_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.guessMimeTypes = exports.registerTextMime = exports.Mimes = void 0;
var Mimes;
(function (Mimes) {
Mimes.text = 'text/plain';
Mimes.binary = 'application/octet-stream';
Mimes.unknown = 'application/unknown';
Mimes.markdown = 'text/markdown';
})(Mimes = exports.Mimes || (exports.Mimes = {}));
let registeredAssociations = [];
let nonUserRegisteredAssociations = [];
let userRegisteredAssociations = [];
/**
* Associate a text mime to the registry.
*/
function registerTextMime(association, warnOnOverwrite = false) {
// Register
const associationItem = toTextMimeAssociationItem(association);
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}>>`);
}
});
}
}
exports.registerTextMime = registerTextMime;
function toTextMimeAssociationItem(association) {
return {
id: association.id,
mime: association.mime,
filename: association.filename,
extension: association.extension,
filepattern: association.filepattern,
firstline: association.firstline,
userConfigured: association.userConfigured,
filenameLowercase: association.filename ? association.filename.toLowerCase() : undefined,
extensionLowercase: association.extension ? association.extension.toLowerCase() : undefined,
filepatternLowercase: association.filepattern ? association.filepattern.toLowerCase() : undefined,
filepatternOnPath: association.filepattern ? association.filepattern.indexOf(path_1.posix.sep) >= 0 : false
};
}
/**
* Given a file, return the best matching mime type for it
*/
function guessMimeTypes(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;
default:
path = resource.path;
}
}
if (!path) {
return [Mimes.unknown];
}
path = path.toLowerCase();
const filename = (0, path_1.basename)(path);
// 1.) User configured mappings have highest priority
const configuredMime = guessMimeTypeByPath(path, filename, userRegisteredAssociations);
if (configuredMime) {
return [configuredMime, Mimes.text];
}
// 2.) Registered mappings have middle priority
const registeredMime = guessMimeTypeByPath(path, filename, nonUserRegisteredAssociations);
if (registeredMime) {
return [registeredMime, Mimes.text];
}
// 3.) Firstline has lowest priority
if (firstLine) {
const firstlineMime = guessMimeTypeByFirstline(firstLine);
if (firstlineMime) {
return [firstlineMime, Mimes.text];
}
}
return [Mimes.unknown];
}
exports.guessMimeTypes = guessMimeTypes;
function guessMimeTypeByPath(path, filename, associations) {
let filenameMatch = null;
let patternMatch = null;
let extensionMatch = null;
// 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 ((0, glob_1.match)(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 prio
if (filenameMatch) {
return filenameMatch.mime;
}
// 2.) Match on pattern
if (patternMatch) {
return patternMatch.mime;
}
// 3.) Match on extension comes next
if (extensionMatch) {
return extensionMatch.mime;
}
return null;
}
function guessMimeTypeByFirstline(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.mime;
}
}
}
return null;
}
});
define(__m[164/*vs/base/browser/dnd*/], __M([0/*require*/,1/*exports*/,106/*vs/base/common/mime*/]), function (require, exports, mime_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StaticDND = exports.DragAndDropData = 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,
/**
* Application specific terminal transfer type.
*/
TERMINALS: 'Terminals'
};
class DragAndDropData {
constructor(data) {
this.data = data;
}
update() {
// noop
}
getData() {
return this.data;
}
}
exports.DragAndDropData = DragAndDropData;
exports.StaticDND = {
CurrentDragAndDropData: undefined
};
});
define(__m[299/*vs/base/common/uuid*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateUuid = void 0;
// prep-work
const _data = new Uint8Array(16);
const _hex = [];
for (let i = 0; i < 256; i++) {
_hex.push(i.toString(16).padStart(2, '0'));
}
// todo@jrieken - with node@15 crypto#getRandomBytes is available everywhere, https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#browser_compatibility
let _fillRandomValues;
if (typeof crypto === 'object' && typeof crypto.getRandomValues === 'function') {
// browser
_fillRandomValues = crypto.getRandomValues.bind(crypto);
}
else {
_fillRandomValues = function (bucket) {
for (let i = 0; i < bucket.length; i++) {
bucket[i] = Math.floor(Math.random() * 256);
}
return bucket;
};
}
function generateUuid() {
// get data
_fillRandomValues(_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;
}
exports.generateUuid = generateUuid;
});
/*---------------------------------------------------------------------------------------------
* 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/base/common/worker/simpleWorker*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,20/*vs/base/common/types*/]), function (require, exports, errors_1, lifecycle_1, platform_1, types) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.create = exports.SimpleWorkerServer = exports.SimpleWorkerClient = exports.logOnceWebWorkerWarning = void 0;
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);
}
exports.logOnceWebWorkerWarning = logOnceWebWorkerWarning;
class SimpleWorkerProtocol {
constructor(handler) {
this._workerId = -1;
this._handler = handler;
this._lastSentReq = 0;
this._pendingReplies = Object.create(null);
}
setWorkerId(workerId) {
this._workerId = workerId;
}
sendMessage(method, args) {
let req = String(++this._lastSentReq);
return new Promise((resolve, reject) => {
this._pendingReplies[req] = {
resolve: resolve,
reject: reject
};
this._send({
vsWorker: this._workerId,
req: req,
method: method,
args: args
});
});
}
handleMessage(message) {
if (!message || !message.vsWorker) {
return;
}
if (this._workerId !== -1 && message.vsWorker !== this._workerId) {
return;
}
this._handleMessage(message);
}
_handleMessage(msg) {
if (msg.seq) {
let replyMessage = msg;
if (!this._pendingReplies[replyMessage.seq]) {
console.warn('Got reply to unknown seq');
return;
}
let 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);
return;
}
let requestMessage = msg;
let req = requestMessage.req;
let result = this._handler.handleMessage(requestMessage.method, requestMessage.args);
result.then((r) => {
this._send({
vsWorker: this._workerId,
seq: req,
res: r,
err: 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({
vsWorker: this._workerId,
seq: req,
res: undefined,
err: (0, errors_1.transformErrorForSerialization)(e)
});
});
}
_send(msg) {
let transfer = [];
if (msg.req) {
const m = msg;
for (let i = 0; i < m.args.length; i++) {
if (m.args[i] instanceof ArrayBuffer) {
transfer.push(m.args[i]);
}
}
}
else {
const m = msg;
if (m.res instanceof ArrayBuffer) {
transfer.push(m.res);
}
}
this._handler.sendMessage(msg, transfer);
}
}
/**
* Main thread side
*/
class SimpleWorkerClient extends lifecycle_1.Disposable {
constructor(workerFactory, moduleId, host) {
super();
let lazyProxyReject = null;
this._worker = this._register(workerFactory.create('vs/base/common/worker/simpleWorker', (msg) => {
this._protocol.handleMessage(msg);
}, (err) => {
// in Firefox, web workers fail lazily :(
// we will reject the proxy
if (lazyProxyReject) {
lazyProxyReject(err);
}
}));
this._protocol = new SimpleWorkerProtocol({
sendMessage: (msg, transfer) => {
this._worker.postMessage(msg, transfer);
},
handleMessage: (method, args) => {
if (typeof host[method] !== 'function') {
return Promise.reject(new Error('Missing method ' + method + ' on main thread host.'));
}
try {
return Promise.resolve(host[method].apply(host, args));
}
catch (e) {
return Promise.reject(e);
}
}
});
this._protocol.setWorkerId(this._worker.getId());
// Gather loader configuration
let loaderConfiguration = null;
if (typeof self.require !== 'undefined' && typeof self.require.getConfig === 'function') {
// Get the configuration from the Monaco AMD Loader
loaderConfiguration = self.require.getConfig();
}
else if (typeof self.requirejs !== 'undefined') {
// Get the configuration from requirejs
loaderConfiguration = self.requirejs.s.contexts._.config;
}
const hostMethods = types.getAllMethodNames(host);
// Send initialize message
this._onModuleLoaded = this._protocol.sendMessage(INITIALIZE, [
this._worker.getId(),
JSON.parse(JSON.stringify(loaderConfiguration)),
moduleId,
hostMethods,
]);
// Create proxy to loaded code
const proxyMethodRequest = (method, args) => {
return this._request(method, args);
};
this._lazyProxy = new Promise((resolve, reject) => {
lazyProxyReject = reject;
this._onModuleLoaded.then((availableMethods) => {
resolve(types.createProxyObject(availableMethods, proxyMethodRequest));
}, (e) => {
reject(e);
this._onError('Worker failed to load ' + moduleId, e);
});
});
}
getProxyObject() {
return this._lazyProxy;
}
_request(method, args) {
return new Promise((resolve, reject) => {
this._onModuleLoaded.then(() => {
this._protocol.sendMessage(method, args).then(resolve, reject);
}, reject);
});
}
_onError(message, error) {
console.error(message);
console.info(error);
}
}
exports.SimpleWorkerClient = SimpleWorkerClient;
/**
* Worker side
*/
class SimpleWorkerServer {
constructor(postMessage, requestHandlerFactory) {
this._requestHandlerFactory = requestHandlerFactory;
this._requestHandler = null;
this._protocol = new SimpleWorkerProtocol({
sendMessage: (msg, transfer) => {
postMessage(msg, transfer);
},
handleMessage: (method, args) => this._handleMessage(method, args)
});
}
onmessage(msg) {
this._protocol.handleMessage(msg);
}
_handleMessage(method, args) {
if (method === INITIALIZE) {
return this.initialize(args[0], args[1], args[2], args[3]);
}
if (!this._requestHandler || typeof this._requestHandler[method] !== 'function') {
return Promise.reject(new Error('Missing requestHandler or method: ' + method));
}
try {
return Promise.resolve(this._requestHandler[method].apply(this._requestHandler, args));
}
catch (e) {
return Promise.reject(e);
}
}
initialize(workerId, loaderConfig, moduleId, hostMethods) {
this._protocol.setWorkerId(workerId);
const proxyMethodRequest = (method, args) => {
return this._protocol.sendMessage(method, args);
};
const hostProxy = types.createProxyObject(hostMethods, proxyMethodRequest);
if (this._requestHandlerFactory) {
// static request handler
this._requestHandler = this._requestHandlerFactory(hostProxy);
return Promise.resolve(types.getAllMethodNames(this._requestHandler));
}
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;
self.require.config(loaderConfig);
}
return new Promise((resolve, reject) => {
// Use the global require to be sure to get the global config
self.require([moduleId], (module) => {
this._requestHandler = module.create(hostProxy);
if (!this._requestHandler) {
reject(new Error(`No RequestHandler!`));
return;
}
resolve(types.getAllMethodNames(this._requestHandler));
}, reject);
});
}
}
exports.SimpleWorkerServer = SimpleWorkerServer;
/**
* Called on the worker side
*/
function create(postMessage) {
return new SimpleWorkerServer(postMessage, null);
}
exports.create = create;
});
/*---------------------------------------------------------------------------------------------
* 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/base/parts/quickinput/common/quickInput*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
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 || (exports.QuickInputHideReason = {}));
var ItemActivation;
(function (ItemActivation) {
ItemActivation[ItemActivation["NONE"] = 0] = "NONE";
ItemActivation[ItemActivation["FIRST"] = 1] = "FIRST";
ItemActivation[ItemActivation["SECOND"] = 2] = "SECOND";
ItemActivation[ItemActivation["LAST"] = 3] = "LAST";
})(ItemActivation = exports.ItemActivation || (exports.ItemActivation = {}));
});
//#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[300/*vs/base/parts/storage/common/storage*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/,15/*vs/base/common/async*/,20/*vs/base/common/types*/]), function (require, exports, lifecycle_1, event_1, async_1, types_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InMemoryStorageDatabase = exports.Storage = void 0;
var StorageState;
(function (StorageState) {
StorageState[StorageState["None"] = 0] = "None";
StorageState[StorageState["Initialized"] = 1] = "Initialized";
StorageState[StorageState["Closed"] = 2] = "Closed";
})(StorageState || (StorageState = {}));
class Storage extends lifecycle_1.Disposable {
constructor(database, options = Object.create(null)) {
super();
this.database = database;
this.options = options;
this._onDidChangeStorage = this._register(new event_1.Emitter());
this.onDidChangeStorage = this._onDidChangeStorage.event;
this.state = StorageState.None;
this.cache = new Map();
this.flushDelayer = 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) {
var _a, _b;
// 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.
(_a = e.changed) === null || _a === void 0 ? void 0 : _a.forEach((value, key) => this.accept(key, value));
(_b = e.deleted) === null || _b === void 0 ? void 0 : _b.forEach(key => this.accept(key, undefined));
}
accept(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);
}
}
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);
}
set(key, value) {
return __awaiter(this, void 0, void 0, function* () {
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);
}
// Otherwise, convert to String and store
const valueStr = 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);
// Accumulate work by scheduling after timeout
return this.flushDelayer.trigger(() => this.flushPending());
});
}
delete(key) {
return __awaiter(this, void 0, void 0, function* () {
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);
// Accumulate work by scheduling after timeout
return this.flushDelayer.trigger(() => this.flushPending());
});
}
get hasPending() {
return this.pendingInserts.size > 0 || this.pendingDeletes.size > 0;
}
flushPending() {
return __awaiter(this, void 0, void 0, function* () {
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(() => {
var _a;
if (!this.hasPending) {
while (this.whenFlushedCallbacks.length) {
(_a = this.whenFlushedCallbacks.pop()) === null || _a === void 0 ? void 0 : _a();
}
}
});
});
}
dispose() {
this.flushDelayer.dispose();
super.dispose();
}
}
exports.Storage = Storage;
Storage.DEFAULT_FLUSH_DELAY = 100;
class InMemoryStorageDatabase {
constructor() {
this.onDidChangeItemsExternal = event_1.Event.None;
this.items = new Map();
}
updateItems(request) {
return __awaiter(this, void 0, void 0, function* () {
if (request.insert) {
request.insert.forEach((value, key) => this.items.set(key, value));
}
if (request.delete) {
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[301/*vs/base/worker/defaultWorkerFactory*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,204/*vs/base/common/worker/simpleWorker*/]), function (require, exports, platform_1, simpleWorker_1) {
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultWorkerFactory = exports.getWorkerBootstrapUrl = void 0;
const ttPolicy = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('defaultWorkerFactory', { createScriptURL: value => value });
function getWorker(workerId, label) {
// Option for hosts to overwrite the worker script (used in the standalone editor)
if (platform_1.globals.MonacoEnvironment) {
if (typeof platform_1.globals.MonacoEnvironment.getWorker === 'function') {
return platform_1.globals.MonacoEnvironment.getWorker(workerId, label);
}
if (typeof platform_1.globals.MonacoEnvironment.getWorkerUrl === 'function') {
const wokerUrl = platform_1.globals.MonacoEnvironment.getWorkerUrl(workerId, label);
return new Worker(ttPolicy ? ttPolicy.createScriptURL(wokerUrl) : wokerUrl, { name: label });
}
}
// ESM-comment-begin
if (typeof require === 'function') {
// check if the JS lives on a different origin
const workerMain = require.toUrl('./' + workerId); // explicitly using require.toUrl(), see https://github.com/microsoft/vscode/issues/107440#issuecomment-698982321
const workerUrl = getWorkerBootstrapUrl(workerMain, label);
return new Worker(ttPolicy ? ttPolicy.createScriptURL(workerUrl) : workerUrl, { name: label });
}
// ESM-comment-end
throw new Error(`You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker`);
}
// ESM-comment-begin
function getWorkerBootstrapUrl(scriptPath, label) {
if (/^((http:)|(https:)|(file:))/.test(scriptPath) && scriptPath.substring(0, self.origin.length) !== self.origin) {
// this is the cross-origin case
// i.e. the webpage is running at a different origin than where the scripts are loaded from
const myPath = 'vs/base/worker/defaultWorkerFactory.js';
const workerBaseUrl = require.toUrl(myPath).slice(0, -myPath.length); // explicitly using require.toUrl(), see https://github.com/microsoft/vscode/issues/107440#issuecomment-698982321
const js = `/*${label}*/self.MonacoEnvironment={baseUrl: '${workerBaseUrl}'};const ttPolicy = self.trustedTypes?.createPolicy('defaultWorkerFactory', { createScriptURL: value => value });importScripts(ttPolicy?.createScriptURL('${scriptPath}') ?? '${scriptPath}');/*${label}*/`;
const blob = new Blob([js], { type: 'application/javascript' });
return URL.createObjectURL(blob);
}
return scriptPath + '#' + label;
}
exports.getWorkerBootstrapUrl = getWorkerBootstrapUrl;
// ESM-comment-end
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 {
constructor(moduleId, id, label, onMessageCallback, onErrorCallback) {
this.id = id;
const workerOrPromise = getWorker('workerMain.js', label);
if (isPromiseLike(workerOrPromise)) {
this.worker = workerOrPromise;
}
else {
this.worker = Promise.resolve(workerOrPromise);
}
this.postMessage(moduleId, []);
this.worker.then((w) => {
w.onmessage = function (ev) {
onMessageCallback(ev.data);
};
w.onmessageerror = onErrorCallback;
if (typeof w.addEventListener === 'function') {
w.addEventListener('error', onErrorCallback);
}
});
}
getId() {
return this.id;
}
postMessage(message, transfer) {
if (this.worker) {
this.worker.then(w => w.postMessage(message, transfer));
}
}
dispose() {
if (this.worker) {
this.worker.then(w => w.terminate());
}
this.worker = null;
}
}
class DefaultWorkerFactory {
constructor(label) {
this._label = label;
this._webWorkerFailedBeforeError = false;
}
create(moduleId, onMessageCallback, onErrorCallback) {
let workerId = (++DefaultWorkerFactory.LAST_WORKER_ID);
if (this._webWorkerFailedBeforeError) {
throw this._webWorkerFailedBeforeError;
}
return new WebWorker(moduleId, workerId, this._label || 'anonymous' + workerId, onMessageCallback, (err) => {
(0, simpleWorker_1.logOnceWebWorkerWarning)(err);
this._webWorkerFailedBeforeError = err;
onErrorCallback(err);
});
}
}
exports.DefaultWorkerFactory = DefaultWorkerFactory;
DefaultWorkerFactory.LAST_WORKER_ID = 0;
});
define(__m[206/*vs/css!vs/base/browser/ui/actionbar/actionbar*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[302/*vs/css!vs/base/browser/ui/aria/aria*/], __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[44/*vs/base/browser/ui/aria/aria*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,7/*vs/base/browser/dom*/,302/*vs/css!vs/base/browser/ui/aria/aria*/]), function (require, exports, platform_1, dom) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.status = exports.alert = exports.setARIAContainer = void 0;
// 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('role', 'complementary');
element.setAttribute('aria-live', 'polite');
element.setAttribute('aria-atomic', 'true');
ariaContainer.appendChild(element);
return element;
};
statusContainer = createStatusContainer();
statusContainer2 = createStatusContainer();
parent.appendChild(ariaContainer);
}
exports.setARIAContainer = setARIAContainer;
/**
* 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);
}
}
exports.alert = alert;
/**
* Given the provided message, will make sure that it is read as status to screen readers.
*/
function status(msg) {
if (!ariaContainer) {
return;
}
if (platform_1.isMacintosh) {
alert(msg); // VoiceOver does not seem to support status role
}
else {
if (statusContainer.textContent !== msg) {
dom.clearNode(statusContainer2);
insertMessage(statusContainer, msg);
}
else {
dom.clearNode(statusContainer);
insertMessage(statusContainer2, msg);
}
}
}
exports.status = status;
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';
}
});
define(__m[303/*vs/css!vs/base/browser/ui/button/button*/], __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[304/*vs/base/browser/ui/button/button*/], __M([0/*require*/,1/*exports*/,51/*vs/base/browser/keyboardEvent*/,29/*vs/base/common/color*/,42/*vs/base/common/objects*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,60/*vs/base/browser/touch*/,105/*vs/base/browser/ui/iconLabel/iconLabels*/,7/*vs/base/browser/dom*/,303/*vs/css!vs/base/browser/ui/button/button*/]), function (require, exports, keyboardEvent_1, color_1, objects_1, event_1, lifecycle_1, touch_1, iconLabels_1, dom_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Button = void 0;
const defaultOptions = {
buttonBackground: color_1.Color.fromHex('#0E639C'),
buttonHoverBackground: color_1.Color.fromHex('#006BB3'),
buttonForeground: color_1.Color.white
};
class Button extends lifecycle_1.Disposable {
constructor(container, options) {
super();
this._onDidClick = this._register(new event_1.Emitter());
this.options = options || Object.create(null);
(0, objects_1.mixin)(this.options, defaultOptions, false);
this.buttonForeground = this.options.buttonForeground;
this.buttonBackground = this.options.buttonBackground;
this.buttonHoverBackground = this.options.buttonHoverBackground;
this.buttonSecondaryForeground = this.options.buttonSecondaryForeground;
this.buttonSecondaryBackground = this.options.buttonSecondaryBackground;
this.buttonSecondaryHoverBackground = this.options.buttonSecondaryHoverBackground;
this.buttonBorder = this.options.buttonBorder;
this._element = document.createElement('a');
this._element.classList.add('monaco-button');
this._element.tabIndex = 0;
this._element.setAttribute('role', 'button');
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 /* Enter */) || event.equals(10 /* Space */))) {
this._onDidClick.fire(e);
eventHandled = true;
}
else if (event.equals(9 /* Escape */)) {
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.setHoverBackground();
}
}));
this._register((0, dom_1.addDisposableListener)(this._element, dom_1.EventType.MOUSE_OUT, e => {
this.applyStyles(); // 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(() => this.setHoverBackground()));
this._register(this.focusTracker.onDidBlur(() => this.applyStyles())); // restore standard styles
this.applyStyles();
}
get onDidClick() { return this._onDidClick.event; }
setHoverBackground() {
let hoverBackground;
if (this.options.secondary) {
hoverBackground = this.buttonSecondaryHoverBackground ? this.buttonSecondaryHoverBackground.toString() : null;
}
else {
hoverBackground = this.buttonHoverBackground ? this.buttonHoverBackground.toString() : null;
}
if (hoverBackground) {
this._element.style.backgroundColor = hoverBackground;
}
}
style(styles) {
this.buttonForeground = styles.buttonForeground;
this.buttonBackground = styles.buttonBackground;
this.buttonHoverBackground = styles.buttonHoverBackground;
this.buttonSecondaryForeground = styles.buttonSecondaryForeground;
this.buttonSecondaryBackground = styles.buttonSecondaryBackground;
this.buttonSecondaryHoverBackground = styles.buttonSecondaryHoverBackground;
this.buttonBorder = styles.buttonBorder;
this.applyStyles();
}
applyStyles() {
if (this._element) {
let background, foreground;
if (this.options.secondary) {
foreground = this.buttonSecondaryForeground ? this.buttonSecondaryForeground.toString() : '';
background = this.buttonSecondaryBackground ? this.buttonSecondaryBackground.toString() : '';
}
else {
foreground = this.buttonForeground ? this.buttonForeground.toString() : '';
background = this.buttonBackground ? this.buttonBackground.toString() : '';
}
const border = this.buttonBorder ? this.buttonBorder.toString() : '';
this._element.style.color = foreground;
this._element.style.backgroundColor = background;
this._element.style.borderWidth = border ? '1px' : '';
this._element.style.borderStyle = border ? 'solid' : '';
this._element.style.borderColor = border;
}
}
get element() {
return this._element;
}
set label(value) {
this._element.classList.add('monaco-text-button');
if (this.options.supportIcons) {
(0, dom_1.reset)(this._element, ...(0, iconLabels_1.renderLabelWithIcons)(value));
}
else {
this._element.textContent = value;
}
if (typeof this.options.title === 'string') {
this._element.title = this.options.title;
}
else if (this.options.title) {
this._element.title = value;
}
}
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');
}
}
exports.Button = Button;
});
define(__m[305/*vs/css!vs/base/browser/ui/checkbox/checkbox*/], __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[165/*vs/base/browser/ui/checkbox/checkbox*/], __M([0/*require*/,1/*exports*/,52/*vs/base/browser/ui/widget*/,29/*vs/base/common/color*/,6/*vs/base/common/event*/,27/*vs/base/common/codicons*/,305/*vs/css!vs/base/browser/ui/checkbox/checkbox*/]), function (require, exports, widget_1, color_1, event_1, codicons_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Checkbox = void 0;
const defaultOpts = {
inputActiveOptionBorder: color_1.Color.fromHex('#007ACC00'),
inputActiveOptionForeground: color_1.Color.fromHex('#FFFFFF'),
inputActiveOptionBackground: color_1.Color.fromHex('#0E639C50')
};
class Checkbox 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 = Object.assign(Object.assign({}, defaultOpts), opts);
this._checked = this._opts.isChecked;
const classes = ['monaco-custom-checkbox'];
if (this._opts.icon) {
classes.push(...codicons_1.CSSIcon.asClassNameArray(this._opts.icon));
}
if (this._opts.actionClassName) {
classes.push(...this._opts.actionClassName.split(' '));
}
if (this._checked) {
classes.push('checked');
}
this.domNode = document.createElement('div');
this.domNode.title = 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) => {
this.checked = !this._checked;
this._onChange.fire(false);
ev.preventDefault();
});
this.ignoreGesture(this.domNode);
this.onkeydown(this.domNode, (keyboardEvent) => {
if (keyboardEvent.keyCode === 10 /* Space */ || keyboardEvent.keyCode === 3 /* Enter */) {
this.checked = !this._checked;
this._onChange.fire(true);
keyboardEvent.preventDefault();
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 /*marginleft*/ + 2 /*border*/ + 2 /*padding*/ + 16 /* icon width */;
}
style(styles) {
if (styles.inputActiveOptionBorder) {
this._opts.inputActiveOptionBorder = styles.inputActiveOptionBorder;
}
if (styles.inputActiveOptionForeground) {
this._opts.inputActiveOptionForeground = styles.inputActiveOptionForeground;
}
if (styles.inputActiveOptionBackground) {
this._opts.inputActiveOptionBackground = styles.inputActiveOptionBackground;
}
this.applyStyles();
}
applyStyles() {
if (this.domNode) {
this.domNode.style.borderColor = this._checked && this._opts.inputActiveOptionBorder ? this._opts.inputActiveOptionBorder.toString() : 'transparent';
this.domNode.style.color = this._checked && this._opts.inputActiveOptionForeground ? this._opts.inputActiveOptionForeground.toString() : 'inherit';
this.domNode.style.backgroundColor = this._checked && this._opts.inputActiveOptionBackground ? this._opts.inputActiveOptionBackground.toString() : 'transparent';
}
}
enable() {
this.domNode.setAttribute('aria-disabled', String(false));
}
disable() {
this.domNode.setAttribute('aria-disabled', String(true));
}
}
exports.Checkbox = Checkbox;
});
define(__m[306/*vs/css!vs/base/browser/ui/codicons/codicon/codicon*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[307/*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[130/*vs/base/browser/ui/codicons/codiconStyles*/], __M([0/*require*/,1/*exports*/,27/*vs/base/common/codicons*/,306/*vs/css!vs/base/browser/ui/codicons/codicon/codicon*/,307/*vs/css!vs/base/browser/ui/codicons/codicon/codicon-modifiers*/]), function (require, exports, codicons_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatRule = void 0;
function formatRule(c) {
let def = c.definition;
while (def instanceof codicons_1.Codicon) {
def = def.definition;
}
return `.codicon-${c.id}:before { content: '${def.fontCharacter}'; }`;
}
exports.formatRule = formatRule;
});
define(__m[308/*vs/css!vs/base/browser/ui/contextview/contextview*/], __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[207/*vs/base/browser/ui/contextview/contextview*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,17/*vs/base/common/platform*/,2/*vs/base/common/lifecycle*/,126/*vs/base/common/range*/,156/*vs/base/browser/canIUse*/,308/*vs/css!vs/base/browser/ui/contextview/contextview*/]), function (require, exports, DOM, platform, lifecycle_1, range_1, canIUse_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextView = exports.layout = exports.LayoutAnchorMode = void 0;
var LayoutAnchorMode;
(function (LayoutAnchorMode) {
LayoutAnchorMode[LayoutAnchorMode["AVOID"] = 0] = "AVOID";
LayoutAnchorMode[LayoutAnchorMode["ALIGN"] = 1] = "ALIGN";
})(LayoutAnchorMode = exports.LayoutAnchorMode || (exports.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 /* 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
}
}
exports.layout = layout;
class ContextView extends lifecycle_1.Disposable {
constructor(container, domPosition) {
super();
this.container = null;
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');
this.useFixedPosition = false;
this.useShadowDOM = false;
DOM.hide(this.view);
this.setContainer(container, domPosition);
this._register((0, lifecycle_1.toDisposable)(() => this.setContainer(null, 1 /* ABSOLUTE */)));
}
setContainer(container, domPosition) {
var _a;
if (this.container) {
this.toDisposeOnSetContainer.dispose();
if (this.shadowRoot) {
this.shadowRoot.removeChild(this.view);
this.shadowRoot = null;
(_a = this.shadowRootHostElement) === null || _a === void 0 ? void 0 : _a.remove();
this.shadowRootHostElement = null;
}
else {
this.container.removeChild(this.view);
}
this.container = null;
}
if (container) {
this.container = container;
this.useFixedPosition = domPosition !== 1 /* ABSOLUTE */;
this.useShadowDOM = domPosition === 3 /* FIXED_SHADOW */;
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';
this.view.style.top = '0px';
this.view.style.left = '0px';
this.view.style.zIndex = '2500';
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
if (this.delegate.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;
}
if (this.delegate.layout) {
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
let anchor = this.delegate.getAnchor();
// Compute around
let around;
// Get the element's position and size (to anchor the view)
if (DOM.isHTMLElement(anchor)) {
let elementPosition = DOM.getDomNodePagePosition(anchor);
around = {
top: elementPosition.top,
left: elementPosition.left,
width: elementPosition.width,
height: elementPosition.height
};
}
else {
around = {
top: anchor.y,
left: anchor.x,
width: anchor.width || 1,
height: anchor.height || 2
};
}
const viewSizeWidth = DOM.getTotalWidth(this.view);
const viewSizeHeight = DOM.getTotalHeight(this.view);
const anchorPosition = this.delegate.anchorPosition || 0 /* BELOW */;
const anchorAlignment = this.delegate.anchorAlignment || 0 /* LEFT */;
const anchorAxisAlignment = this.delegate.anchorAxisAlignment || 0 /* VERTICAL */;
let top;
let left;
if (anchorAxisAlignment === 0 /* VERTICAL */) {
const verticalAnchor = { offset: around.top - window.pageYOffset, size: around.height, position: anchorPosition === 0 /* BELOW */ ? 0 /* Before */ : 1 /* After */ };
const horizontalAnchor = { offset: around.left, size: around.width, position: anchorAlignment === 0 /* LEFT */ ? 0 /* Before */ : 1 /* After */, mode: LayoutAnchorMode.ALIGN };
top = layout(window.innerHeight, viewSizeHeight, verticalAnchor) + window.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(window.innerWidth, viewSizeWidth, horizontalAnchor);
}
else {
const horizontalAnchor = { offset: around.left, size: around.width, position: anchorAlignment === 0 /* LEFT */ ? 0 /* Before */ : 1 /* After */ };
const verticalAnchor = { offset: around.top, size: around.height, position: anchorPosition === 0 /* BELOW */ ? 0 /* Before */ : 1 /* After */, mode: LayoutAnchorMode.ALIGN };
left = layout(window.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(window.innerHeight, viewSizeHeight, verticalAnchor) + window.pageYOffset;
}
this.view.classList.remove('top', 'bottom', 'left', 'right');
this.view.classList.add(anchorPosition === 0 /* BELOW */ ? 'bottom' : 'top');
this.view.classList.add(anchorAlignment === 0 /* 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 === null || delegate === void 0 ? void 0 : 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, document.activeElement);
}
else if (onCapture && !DOM.isAncestor(e.target, this.container)) {
this.hide();
}
}
}
dispose() {
this.hide();
super.dispose();
}
}
exports.ContextView = ContextView;
ContextView.BUBBLE_UP_EVENTS = ['click', 'keydown', 'focus', 'blur'];
ContextView.BUBBLE_DOWN_EVENTS = ['click'];
let SHADOW_ROOT_CSS = /* css */ `
:host {
all: initial; /* 1st rule so subsequent properties are reset. */
}
@font-face {
font-family: "codicon";
src: url("./codicon.ttf?5d4d76ab2ce5108968ad644d591a16a6") format("truetype");
}
.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; }
`;
});
define(__m[309/*vs/css!vs/base/browser/ui/countBadge/countBadge*/], __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[208/*vs/base/browser/ui/countBadge/countBadge*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,8/*vs/base/common/strings*/,29/*vs/base/common/color*/,42/*vs/base/common/objects*/,309/*vs/css!vs/base/browser/ui/countBadge/countBadge*/]), function (require, exports, dom_1, strings_1, color_1, objects_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CountBadge = void 0;
const defaultOpts = {
badgeBackground: color_1.Color.fromHex('#4D4D4D'),
badgeForeground: color_1.Color.fromHex('#FFFFFF')
};
class CountBadge {
constructor(container, options) {
this.count = 0;
this.options = options || Object.create(null);
(0, objects_1.mixin)(this.options, defaultOpts, false);
this.badgeBackground = this.options.badgeBackground;
this.badgeForeground = this.options.badgeForeground;
this.badgeBorder = this.options.badgeBorder;
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.applyStyles();
}
style(styles) {
this.badgeBackground = styles.badgeBackground;
this.badgeForeground = styles.badgeForeground;
this.badgeBorder = styles.badgeBorder;
this.applyStyles();
}
applyStyles() {
if (this.element) {
const background = this.badgeBackground ? this.badgeBackground.toString() : '';
const foreground = this.badgeForeground ? this.badgeForeground.toString() : '';
const border = this.badgeBorder ? this.badgeBorder.toString() : '';
this.element.style.backgroundColor = background;
this.element.style.color = foreground;
this.element.style.borderWidth = border ? '1px' : '';
this.element.style.borderStyle = border ? 'solid' : '';
this.element.style.borderColor = border;
}
}
}
exports.CountBadge = CountBadge;
});
define(__m[209/*vs/css!vs/base/browser/ui/dropdown/dropdown*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[210/*vs/css!vs/base/browser/ui/findinput/findInput*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[310/*vs/css!vs/base/browser/ui/hover/hover*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[311/*vs/css!vs/base/browser/ui/iconLabel/iconlabel*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[312/*vs/css!vs/base/browser/ui/inputbox/inputBox*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[313/*vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[211/*vs/css!vs/base/browser/ui/list/list*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[314/*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[131/*vs/base/browser/ui/mouseCursor/mouseCursor*/], __M([0/*require*/,1/*exports*/,314/*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[315/*vs/css!vs/base/browser/ui/progressbar/progressbar*/], __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[316/*vs/base/browser/ui/progressbar/progressbar*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,29/*vs/base/common/color*/,42/*vs/base/common/objects*/,7/*vs/base/browser/dom*/,15/*vs/base/common/async*/,315/*vs/css!vs/base/browser/ui/progressbar/progressbar*/]), function (require, exports, lifecycle_1, color_1, objects_1, dom_1, async_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_DISCRETE = 'discrete';
const defaultOpts = {
progressBarBackground: color_1.Color.fromHex('#0E70C0')
};
/**
* A progress bar with support for infinite or discrete progress.
*/
class ProgressBar extends lifecycle_1.Disposable {
constructor(container, options) {
super();
this.options = options || Object.create(null);
(0, objects_1.mixin)(this.options, defaultOpts, false);
this.workedVal = 0;
this.progressBarBackground = this.options.progressBarBackground;
this._register(this.showDelayedScheduler = new async_1.RunOnceScheduler(() => (0, dom_1.show)(this.element), 0));
this.create(container);
}
create(container) {
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.element.appendChild(this.bit);
this.applyStyles();
}
off() {
this.bit.style.width = 'inherit';
this.bit.style.opacity = '1';
this.element.classList.remove(CSS_ACTIVE, CSS_INFINITE, CSS_DISCRETE);
this.workedVal = 0;
this.totalWork = undefined;
}
/**
* Stops the progressbar from showing any progress instantly without fading out.
*/
stop() {
return this.doDone(false);
}
doDone(delayed) {
this.element.classList.add(CSS_DONE);
// 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();
}
}
// 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);
this.element.classList.add(CSS_ACTIVE, CSS_INFINITE);
return this;
}
getContainer() {
return this.element;
}
style(styles) {
this.progressBarBackground = styles.progressBarBackground;
this.applyStyles();
}
applyStyles() {
if (this.bit) {
const background = this.progressBarBackground ? this.progressBarBackground.toString() : '';
this.bit.style.backgroundColor = background;
}
}
}
exports.ProgressBar = ProgressBar;
});
define(__m[317/*vs/css!vs/base/browser/ui/sash/sash*/], __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[107/*vs/base/browser/ui/sash/sash*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,60/*vs/base/browser/touch*/,6/*vs/base/common/event*/,7/*vs/base/browser/dom*/,91/*vs/base/browser/event*/,15/*vs/base/common/async*/,90/*vs/base/common/decorators*/,317/*vs/css!vs/base/browser/ui/sash/sash*/]), function (require, exports, lifecycle_1, platform_1, touch_1, event_1, dom_1, event_2, async_1, decorators_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Sash = exports.OrthogonalEdge = void 0;
let DEBUG = false;
var OrthogonalEdge;
(function (OrthogonalEdge) {
OrthogonalEdge["North"] = "north";
OrthogonalEdge["South"] = "south";
OrthogonalEdge["East"] = "east";
OrthogonalEdge["West"] = "west";
})(OrthogonalEdge = exports.OrthogonalEdge || (exports.OrthogonalEdge = {}));
let globalSize = 4;
const onDidChangeGlobalSize = new event_1.Emitter();
let globalHoverDelay = 300;
const onDidChangeHoverDelay = new event_1.Emitter();
class MouseEventFactory {
constructor() {
this.disposables = new lifecycle_1.DisposableStore();
}
get onPointerMove() {
return this.disposables.add(new event_2.DomEmitter(window, 'mousemove')).event;
}
get onPointerUp() {
return this.disposables.add(new event_2.DomEmitter(window, 'mouseup')).event;
}
dispose() {
this.disposables.dispose();
}
}
__decorate([
decorators_1.memoize
], MouseEventFactory.prototype, "onPointerMove", null);
__decorate([
decorators_1.memoize
], MouseEventFactory.prototype, "onPointerUp", null);
class GestureEventFactory {
constructor(el) {
this.el = el;
this.disposables = new lifecycle_1.DisposableStore();
}
get onPointerMove() {
return this.disposables.add(new event_2.DomEmitter(this.el, touch_1.EventType.Change)).event;
}
get onPointerUp() {
return this.disposables.add(new event_2.DomEmitter(this.el, touch_1.EventType.End)).event;
}
dispose() {
this.disposables.dispose();
}
}
__decorate([
decorators_1.memoize
], GestureEventFactory.prototype, "onPointerMove", null);
__decorate([
decorators_1.memoize
], GestureEventFactory.prototype, "onPointerUp", null);
class OrthogonalPointerEventFactory {
constructor(factory) {
this.factory = factory;
}
get onPointerMove() {
return this.factory.onPointerMove;
}
get onPointerUp() {
return this.factory.onPointerUp;
}
dispose() {
// noop
}
}
__decorate([
decorators_1.memoize
], OrthogonalPointerEventFactory.prototype, "onPointerMove", null);
__decorate([
decorators_1.memoize
], OrthogonalPointerEventFactory.prototype, "onPointerUp", null);
class Sash extends lifecycle_1.Disposable {
constructor(container, layoutProvider, options) {
super();
this.hoverDelay = globalHoverDelay;
this.hoverDelayer = this._register(new async_1.Delayer(this.hoverDelay));
this._state = 3 /* Enabled */;
this._onDidEnablementChange = this._register(new event_1.Emitter());
this.onDidEnablementChange = this._onDidEnablementChange.event;
this._onDidStart = this._register(new event_1.Emitter());
this.onDidStart = this._onDidStart.event;
this._onDidChange = this._register(new event_1.Emitter());
this.onDidChange = this._onDidChange.event;
this._onDidReset = this._register(new event_1.Emitter());
this.onDidReset = this._onDidReset.event;
this._onDidEnd = this._register(new event_1.Emitter());
this.onDidEnd = this._onDidEnd.event;
this.linkedSash = undefined;
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());
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_2.DomEmitter(this.el, 'mousedown')).event;
this._register(onMouseDown(e => this.onPointerStart(e, new MouseEventFactory()), this));
const onMouseDoubleClick = this._register(new event_2.DomEmitter(this.el, 'dblclick')).event;
this._register(onMouseDoubleClick(this.onPointerDoublePress, this));
const onMouseEnter = this._register(new event_2.DomEmitter(this.el, 'mouseenter')).event;
this._register(onMouseEnter(() => Sash.onMouseEnter(this)));
const onMouseLeave = this._register(new event_2.DomEmitter(this.el, 'mouseleave')).event;
this._register(onMouseLeave(() => Sash.onMouseLeave(this)));
this._register(touch_1.Gesture.addTarget(this.el));
const onTouchStart = event_1.Event.map(this._register(new event_2.DomEmitter(this.el, touch_1.EventType.Start)).event, e => { var _a; return (Object.assign(Object.assign({}, e), { target: (_a = e.initialTarget) !== null && _a !== void 0 ? _a : null })); });
this._register(onTouchStart(e => this.onPointerStart(e, new GestureEventFactory(this.el)), this));
const onTap = this._register(new event_2.DomEmitter(this.el, touch_1.EventType.Tap)).event;
const onDoubleTap = event_1.Event.map(event_1.Event.filter(event_1.Event.debounce(onTap, (res, event) => { var _a; return ({ event, count: ((_a = res === null || res === void 0 ? void 0 : res.count) !== null && _a !== void 0 ? _a : 0) + 1 }); }, 250), ({ count }) => count === 2), ({ event }) => { var _a; return (Object.assign(Object.assign({}, event), { target: (_a = event.initialTarget) !== null && _a !== void 0 ? _a : null })); });
this._register(onDoubleTap(this.onPointerDoublePress, this));
if (typeof options.size === 'number') {
this.size = options.size;
if (options.orientation === 0 /* 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.hidden = false;
this.layoutProvider = layoutProvider;
this.orthogonalStartSash = options.orthogonalStartSash;
this.orthogonalEndSash = options.orthogonalEndSash;
this.orientation = options.orientation || 0 /* VERTICAL */;
if (this.orientation === 1 /* 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();
}
get state() { return this._state; }
set state(state) {
if (this._state === state) {
return;
}
this.el.classList.toggle('disabled', state === 0 /* Disabled */);
this.el.classList.toggle('minimum', state === 1 /* Minimum */);
this.el.classList.toggle('maximum', state === 2 /* Maximum */);
this._state = state;
this._onDidEnablementChange.fire(state);
}
get orthogonalStartSash() { return this._orthogonalStartSash; }
set orthogonalStartSash(sash) {
this.orthogonalStartDragHandleDisposables.clear();
this.orthogonalStartSashDisposables.clear();
if (sash) {
const onChange = (state) => {
this.orthogonalStartDragHandleDisposables.clear();
if (state !== 0 /* 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_2.DomEmitter(this._orthogonalStartDragHandle, 'mouseenter')).event(() => Sash.onMouseEnter(sash), undefined, this.orthogonalStartDragHandleDisposables);
this.orthogonalStartDragHandleDisposables.add(new event_2.DomEmitter(this._orthogonalStartDragHandle, 'mouseleave')).event(() => Sash.onMouseLeave(sash), undefined, this.orthogonalStartDragHandleDisposables);
}
};
this.orthogonalStartSashDisposables.add(sash.onDidEnablementChange(onChange, this));
onChange(sash.state);
}
this._orthogonalStartSash = sash;
}
get orthogonalEndSash() { return this._orthogonalEndSash; }
set orthogonalEndSash(sash) {
this.orthogonalEndDragHandleDisposables.clear();
this.orthogonalEndSashDisposables.clear();
if (sash) {
const onChange = (state) => {
this.orthogonalEndDragHandleDisposables.clear();
if (state !== 0 /* 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_2.DomEmitter(this._orthogonalEndDragHandle, 'mouseenter')).event(() => Sash.onMouseEnter(sash), undefined, this.orthogonalEndDragHandleDisposables);
this.orthogonalEndDragHandleDisposables.add(new event_2.DomEmitter(this._orthogonalEndDragHandle, 'mouseleave')).event(() => Sash.onMouseLeave(sash), undefined, this.orthogonalEndDragHandleDisposables);
}
};
this.orthogonalEndSashDisposables.add(sash.onDidEnablementChange(onChange, this));
onChange(sash.state);
}
this._orthogonalEndSash = sash;
}
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 = (0, dom_1.getElementsByTagName)('iframe');
for (const iframe of iframes) {
iframe.style.pointerEvents = 'none'; // 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 /* HORIZONTAL */) {
if (this.state === 1 /* Minimum */) {
cursor = 's-resize';
}
else if (this.state === 2 /* Maximum */) {
cursor = 'n-resize';
}
else {
cursor = platform_1.isMacintosh ? 'row-resize' : 'ns-resize';
}
}
else {
if (this.state === 1 /* Minimum */) {
cursor = 'e-resize';
}
else if (this.state === 2 /* Maximum */) {
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(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);
this.el.removeChild(style);
this.el.classList.remove('active');
this._onDidEnd.fire();
disposables.dispose();
for (const iframe of iframes) {
iframe.style.pointerEvents = 'auto';
}
};
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);
}
}
clearSashHoverState() {
Sash.onMouseLeave(this);
}
layout() {
if (this.orientation === 0 /* 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';
}
}
}
hide() {
this.hidden = true;
this.el.style.display = 'none';
this.el.setAttribute('aria-hidden', 'true');
}
getOrthogonalSash(e) {
if (!e.target || !(e.target instanceof HTMLElement)) {
return undefined;
}
if (e.target.classList.contains('orthogonal-drag-handle')) {
return e.target.classList.contains('start') ? this.orthogonalStartSash : this.orthogonalEndSash;
}
return undefined;
}
dispose() {
super.dispose();
this.el.remove();
}
}
exports.Sash = Sash;
});
define(__m[318/*vs/css!vs/base/browser/ui/scrollbar/media/scrollbars*/], __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[61/*vs/base/browser/ui/scrollbar/scrollableElement*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,55/*vs/base/browser/mouseEvent*/,296/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/,297/*vs/base/browser/ui/scrollbar/verticalScrollbar*/,52/*vs/base/browser/ui/widget*/,15/*vs/base/common/async*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,127/*vs/base/common/scrollable*/,39/*vs/base/browser/browser*/,318/*vs/css!vs/base/browser/ui/scrollbar/media/scrollbars*/]), function (require, exports, dom, fastDomNode_1, mouseEvent_1, horizontalScrollbar_1, verticalScrollbar_1, widget_1, async_1, event_1, lifecycle_1, platform, scrollable_1, browser_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 {
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);
}
accept(timestamp, deltaX, deltaY) {
const item = new MouseWheelClassifierItem(timestamp, deltaX, deltaY);
item.score = this._computeScore(item);
if (this._front === -1 && this._rear === -1) {
this._memory[0] = item;
this._front = 0;
this._rear = 0;
}
else {
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;
}
}
/**
* 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) {
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;
const prev = (this._front === -1 && this._rear === -1 ? null : this._memory[this._rear]);
if (prev) {
// const deltaT = item.timestamp - prev.timestamp;
// if (deltaT < 1000 / 30) {
// // sooner than X times per second => indicator that this is not a physical mouse wheel
// score += 0.25;
// }
// if (item.deltaX === prev.deltaX && item.deltaY === prev.deltaY) {
// // equal amplitude => indicator that this is a physical mouse wheel
// score -= 0.25;
// }
}
if (!this._isAlmostInt(item.deltaX) || !this._isAlmostInt(item.deltaY)) {
// non-integer deltas => indicator that this is not a physical mouse wheel
score += 0.25;
}
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;
MouseWheelClassifier.INSTANCE = new MouseWheelClassifier();
class AbstractScrollableElement extends widget_1.Widget {
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.onnonbubblingmouseout(this._listenOnDomNode, (e) => this._onMouseOut(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 mouse down event to the vertical scrollbar.
* This is to help with clicking somewhere else and having the scrollbar react.
*/
delegateVerticalScrollbarMouseDown(browserEvent) {
this._verticalScrollbar.delegateMouseDown(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();
}
}
// -------------------- 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) {
const classifier = MouseWheelClassifier.INSTANCE;
if (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED) {
const osZoomFactor = window.devicePixelRatio / (0, browser_1.getZoomFactor)();
if (platform.isWindows || platform.isLinux) {
// On Windows and Linux, 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.
classifier.accept(Date.now(), e.deltaX / osZoomFactor, e.deltaY / osZoomFactor);
}
else {
classifier.accept(Date.now(), e.deltaX, e.deltaY);
}
}
// 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 (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 desiredScrollTop = futureScrollPosition.scrollTop - SCROLL_WHEEL_SENSITIVITY * deltaY;
this._verticalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollTop);
}
if (deltaX) {
const desiredScrollLeft = futureScrollPosition.scrollLeft - SCROLL_WHEEL_SENSITIVITY * deltaX;
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();
}
_onMouseOut(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(0, (callback) => dom.scheduleAtNextAnimationFrame(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 ScrollableElement {
constructor(element, options) {
super(element, options);
this._element = element;
this.onScroll((e) => {
if (e.scrollTopChanged) {
this._element.scrollTop = e.scrollTop;
}
if (e.scrollLeftChanged) {
this._element.scrollLeft = e.scrollLeft;
}
});
this.scanDomNode();
}
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 /* 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 /* 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[319/*vs/base/browser/ui/hover/hoverWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,310/*vs/css!vs/base/browser/ui/hover/hover*/]), function (require, exports, dom, lifecycle_1, scrollableElement_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HoverAction = exports.HoverWidget = void 0;
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 {
constructor(parent, actionOptions, keybindingLabel) {
super();
this.actionContainer = dom.append(parent, $('div.action-container'));
this.action = dom.append(this.actionContainer, $('a.action'));
this.action.setAttribute('href', '#');
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._register(dom.addDisposableListener(this.actionContainer, dom.EventType.CLICK, e => {
e.stopPropagation();
e.preventDefault();
actionOptions.run(this.actionContainer);
}));
this.setEnabled(true);
}
static render(parent, actionOptions, keybindingLabel) {
return new HoverAction(parent, actionOptions, keybindingLabel);
}
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;
});
/*---------------------------------------------------------------------------------------------
* 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/base/browser/ui/list/listView*/], __M([0/*require*/,1/*exports*/,42/*vs/base/common/objects*/,2/*vs/base/common/lifecycle*/,60/*vs/base/browser/touch*/,6/*vs/base/common/event*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,127/*vs/base/common/scrollable*/,289/*vs/base/browser/ui/list/rangeMap*/,295/*vs/base/browser/ui/list/rowCache*/,90/*vs/base/common/decorators*/,126/*vs/base/common/range*/,19/*vs/base/common/arrays*/,164/*vs/base/browser/dnd*/,15/*vs/base/common/async*/,39/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,91/*vs/base/browser/event*/]), function (require, exports, objects_1, lifecycle_1, touch_1, event_1, scrollableElement_1, scrollable_1, rangeMap_1, rowCache_1, decorators_1, range_1, arrays_1, dnd_1, async_1, browser_1, dom_1, event_2) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ListView = exports.NativeDragAndDropData = exports.ExternalElementsDragAndDropData = exports.ElementsDragAndDropData = void 0;
const DefaultOptions = {
useShadows: true,
verticalScrollMode: 1 /* Auto */,
setRowLineHeight: true,
setRowHeight: true,
supportDynamicHeights: false,
dnd: {
getDragElements(e) { return [e]; },
getDragURI() { return null; },
onDragStart() { },
onDragOver() { return false; },
drop() { }
},
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 === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.getSetSize) {
this.getSetSize = accessibilityProvider.getSetSize.bind(accessibilityProvider);
}
else {
this.getSetSize = (e, i, l) => l;
}
if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.getPosInSet) {
this.getPosInSet = accessibilityProvider.getPosInSet.bind(accessibilityProvider);
}
else {
this.getPosInSet = (e, i) => i + 1;
}
if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.getRole) {
this.getRole = accessibilityProvider.getRole.bind(accessibilityProvider);
}
else {
this.getRole = _ => 'listitem';
}
if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.isChecked) {
this.isChecked = accessibilityProvider.isChecked.bind(accessibilityProvider);
}
else {
this.isChecked = _ => undefined;
}
}
}
class ListView {
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_1.Emitter();
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 = new rangeMap_1.RangeMap();
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 = (0, objects_1.getOrDefault)(options, o => o.horizontalScrolling, DefaultOptions.horizontalScrolling);
this.domNode.classList.toggle('horizontal-scrolling', this._horizontalScrolling);
this.additionalScrollHeight = typeof options.additionalScrollHeight === 'undefined' ? 0 : options.additionalScrollHeight;
this.accessibilityProvider = new ListViewAccessibilityProvider(options.accessibilityProvider);
this.rowsContainer = document.createElement('div');
this.rowsContainer.className = 'monaco-list-rows';
const transformOptimization = (0, objects_1.getOrDefault)(options, o => o.transformOptimization, DefaultOptions.transformOptimization);
if (transformOptimization) {
this.rowsContainer.style.transform = 'translate3d(0px, 0px, 0px)';
}
this.disposables.add(touch_1.Gesture.addTarget(this.rowsContainer));
this.scrollable = new scrollable_1.Scrollable((0, objects_1.getOrDefault)(options, o => o.smoothScrolling, false) ? 125 : 0, cb => (0, dom_1.scheduleAtNextAnimationFrame)(cb));
this.scrollableElement = this.disposables.add(new scrollableElement_1.SmoothScrollableElement(this.rowsContainer, {
alwaysConsumeMouseWheel: (0, objects_1.getOrDefault)(options, o => o.alwaysConsumeMouseWheel, DefaultOptions.alwaysConsumeMouseWheel),
horizontal: 1 /* Auto */,
vertical: (0, objects_1.getOrDefault)(options, o => o.verticalScrollMode, DefaultOptions.verticalScrollMode),
useShadows: (0, objects_1.getOrDefault)(options, o => o.useShadows, DefaultOptions.useShadows),
mouseWheelScrollSensitivity: options.mouseWheelScrollSensitivity,
fastScrollSensitivity: options.fastScrollSensitivity
}, 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 = (0, objects_1.getOrDefault)(options, o => o.setRowLineHeight, DefaultOptions.setRowLineHeight);
this.setRowHeight = (0, objects_1.getOrDefault)(options, o => o.setRowHeight, DefaultOptions.setRowHeight);
this.supportDynamicHeights = (0, objects_1.getOrDefault)(options, o => o.supportDynamicHeights, DefaultOptions.supportDynamicHeights);
this.dnd = (0, objects_1.getOrDefault)(options, o => o.dnd, DefaultOptions.dnd);
this.layout();
}
get contentHeight() { return this.rangeMap.size; }
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 = '';
}
}
updateOptions(options) {
if (options.additionalScrollHeight !== undefined) {
this.additionalScrollHeight = options.additionalScrollHeight;
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;
}
if (options.mouseWheelScrollSensitivity !== undefined) {
this.scrollableElement.updateOptions({ mouseWheelScrollSensitivity: options.mouseWheelScrollSensitivity });
}
if (options.fastScrollSensitivity !== undefined) {
this.scrollableElement.updateOptions({ fastScrollSensitivity: options.fastScrollSensitivity });
}
}
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.start; i < removeRange.end; i++) {
const item = this.items[i];
item.dragStartDisposable.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.push(item.row);
}
item.row = null;
}
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
}));
let deleted;
// TODO@joao: improve this optimization to catch even more cases
if (start === 0 && deleteCount >= this.items.length) {
this.rangeMap = new rangeMap_1.RangeMap();
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));
const beforeElement = this.getNextToLastElement(insertRanges);
for (const range of insertRanges) {
for (let i = range.start; i < range.end; i++) {
const item = this.items[i];
const rows = rowsToDispose.get(item.templateId);
const row = rows === null || rows === void 0 ? void 0 : rows.pop();
this.insertItemInDOM(i, beforeElement, 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)(() => {
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) });
}
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;
}
element(index) {
return this.items[index].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) {
let 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);
const rangesToRemove = range_1.Range.relativeComplement(previousRenderRange, renderRange);
const beforeElement = this.getNextToLastElement(rangesToInsert);
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);
}
}
for (const range of rangesToInsert) {
for (let i = range.start; i < range.end; i++) {
this.insertItemInDOM(i, beforeElement);
}
}
for (const range of rangesToRemove) {
for (let i = range.start; i < range.end; i++) {
this.removeItemFromDOM(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, beforeElement, row) {
const item = this.items[index];
if (!item.row) {
item.row = row !== null && row !== void 0 ? row : this.cache.alloc(item.templateId);
}
const role = this.accessibilityProvider.getRole(item.element) || 'listitem';
item.row.domNode.setAttribute('role', role);
const checked = this.accessibilityProvider.isChecked(item.element);
if (typeof checked !== 'undefined') {
item.row.domNode.setAttribute('aria-checked', String(!!checked));
}
if (!item.row.domNode.parentElement) {
if (beforeElement) {
this.rowsContainer.insertBefore(item.row.domNode, beforeElement);
}
else {
this.rowsContainer.appendChild(item.row.domNode);
}
}
this.updateItemInDOM(item, index);
const renderer = this.renderers.get(item.templateId);
if (!renderer) {
throw new Error(`No renderer found for template id ${item.templateId}`);
}
if (renderer) {
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 = browser_1.isFirefox ? '-moz-fit-content' : 'fit-content';
item.width = (0, dom_1.getContentWidth)(item.row.domNode);
const style = window.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('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();
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.additionalScrollHeight;
}
// Events
get onMouseClick() { return event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.domNode, 'click')).event, e => this.toMouseEvent(e)); }
get onMouseDblClick() { return event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.domNode, 'dblclick')).event, e => this.toMouseEvent(e)); }
get onMouseMiddleClick() { return event_1.Event.filter(event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.domNode, 'auxclick')).event, e => this.toMouseEvent(e)), e => e.browserEvent.button === 1); }
get onMouseDown() { return event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.domNode, 'mousedown')).event, e => this.toMouseEvent(e)); }
get onContextMenu() { return event_1.Event.any(event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.domNode, 'contextmenu')).event, e => this.toMouseEvent(e)), event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.domNode, touch_1.EventType.Contextmenu)).event, e => this.toGestureEvent(e))); }
get onTouchStart() { return event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.domNode, 'touchstart')).event, e => this.toTouchEvent(e)); }
get onTap() { return event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.rowsContainer, touch_1.EventType.Tap)).event, e => this.toGestureEvent(e)); }
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;
return { browserEvent, index, element };
}
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;
document.body.appendChild(dragImage);
event.dataTransfer.setDragImage(dragImage, -10, -10);
setTimeout(() => document.body.removeChild(dragImage), 0);
}
this.currentDragData = new ElementsDragAndDropData(elements);
dnd_1.StaticDND.CurrentDragAndDropData = new ExternalElementsDragAndDropData(elements);
if (this.dnd.onDragStart) {
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 (dnd_1.StaticDND.CurrentDragAndDropData && dnd_1.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 (dnd_1.StaticDND.CurrentDragAndDropData) {
// Drag over from another list
this.currentDragData = dnd_1.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.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 === 0 /* 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;
if (equalsDragFeedback(this.currentDragFeedback, feedback)) {
return true;
}
this.currentDragFeedback = feedback;
this.currentDragFeedbackDisposable.dispose();
if (feedback[0] === -1) { // entire list feedback
this.domNode.classList.add('drop-target');
this.rowsContainer.classList.add('drop-target');
this.currentDragFeedbackDisposable = (0, lifecycle_1.toDisposable)(() => {
this.domNode.classList.remove('drop-target');
this.rowsContainer.classList.remove('drop-target');
});
}
else {
for (const index of feedback) {
const item = this.items[index];
item.dropTarget = true;
if (item.row) {
item.row.domNode.classList.add('drop-target');
}
}
this.currentDragFeedbackDisposable = (0, lifecycle_1.toDisposable)(() => {
for (const index of feedback) {
const item = this.items[index];
item.dropTarget = false;
if (item.row) {
item.row.domNode.classList.remove('drop-target');
}
}
});
}
return true;
}
onDragLeave(event) {
var _a, _b;
this.onDragLeaveTimeout.dispose();
this.onDragLeaveTimeout = (0, async_1.disposableTimeout)(() => this.clearDragOverFeedback(), 100);
if (this.currentDragData) {
(_b = (_a = this.dnd).onDragLeave) === null || _b === void 0 ? void 0 : _b.call(_a, this.currentDragData, event.element, event.index, event.browserEvent);
}
}
onDrop(event) {
if (!this.canDrop) {
return;
}
const dragData = this.currentDragData;
this.teardownDragAndDropScrollTopAnimation();
this.clearDragOverFeedback();
this.currentDragData = undefined;
dnd_1.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.browserEvent);
}
onDragEnd(event) {
this.canDrop = false;
this.teardownDragAndDropScrollTopAnimation();
this.clearDragOverFeedback();
this.currentDragData = undefined;
dnd_1.StaticDND.CurrentDragAndDropData = undefined;
if (this.dnd.onDragEnd) {
this.dnd.onDragEnd(event);
}
}
clearDragOverFeedback() {
this.currentDragFeedback = 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)(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.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
getItemIndexFromEventTarget(target) {
const scrollableElement = this.scrollableElement.getDomNode();
let element = target;
while (element instanceof HTMLElement && 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);
for (const range of renderRanges) {
for (let i = range.start; i < range.end; i++) {
const afterIndex = i + 1;
const beforeRow = afterIndex < this.items.length ? this.items[afterIndex].row : null;
const beforeElement = beforeRow ? beforeRow.domNode : null;
this.insertItemInDOM(i, beforeElement);
}
}
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 (!item.hasDynamicHeight || item.lastDynamicHeightWidth === this.renderWidth) {
return 0;
}
if (!!this.virtualDelegate.hasDynamicHeight && !this.virtualDelegate.hasDynamicHeight(item.element)) {
return 0;
}
const size = item.size;
if (!this.setRowHeight && item.row) {
let newSize = item.row.domNode.offsetHeight;
item.size = newSize;
item.lastDynamicHeightWidth = this.renderWidth;
return newSize - 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) {
renderer.renderElement(item.element, index, row.templateData, undefined);
if (renderer.disposeElement) {
renderer.disposeElement(item.element, index, row.templateData, undefined);
}
}
item.size = row.domNode.offsetHeight;
if (this.virtualDelegate.setDynamicHeight) {
this.virtualDelegate.setDynamicHeight(item.element, item.size);
}
item.lastDynamicHeightWidth = this.renderWidth;
this.rowsContainer.removeChild(row.domNode);
this.cache.release(row);
return item.size - size;
}
getNextToLastElement(ranges) {
const lastRange = ranges[ranges.length - 1];
if (!lastRange) {
return null;
}
const nextToLastItem = this.items[lastRange.end];
if (!nextToLastItem) {
return null;
}
if (!nextToLastItem.row) {
return null;
}
return nextToLastItem.row.domNode;
}
getElementDomId(index) {
return `${this.domId}_${index}`;
}
// Dispose
dispose() {
if (this.items) {
for (const item of this.items) {
if (item.row) {
const renderer = this.renderers.get(item.row.templateId);
if (renderer) {
if (renderer.disposeElement) {
renderer.disposeElement(item.element, -1, item.row.templateData, undefined);
}
renderer.disposeTemplate(item.row.templateData);
}
}
}
this.items = [];
}
if (this.domNode && this.domNode.parentNode) {
this.domNode.parentNode.removeChild(this.domNode);
}
(0, lifecycle_1.dispose)(this.disposables);
}
}
ListView.InstanceCount = 0;
__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, "onContextMenu", null);
__decorate([
decorators_1.memoize
], ListView.prototype, "onTouchStart", null);
__decorate([
decorators_1.memoize
], ListView.prototype, "onTap", null);
exports.ListView = ListView;
});
/*---------------------------------------------------------------------------------------------
* 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/base/browser/ui/list/listWidget*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/,19/*vs/base/common/arrays*/,90/*vs/base/common/decorators*/,17/*vs/base/common/platform*/,60/*vs/base/browser/touch*/,51/*vs/base/browser/keyboardEvent*/,6/*vs/base/common/event*/,91/*vs/base/browser/event*/,283/*vs/base/browser/ui/list/list*/,166/*vs/base/browser/ui/list/listView*/,29/*vs/base/common/color*/,42/*vs/base/common/objects*/,284/*vs/base/browser/ui/list/splice*/,102/*vs/base/common/numbers*/,67/*vs/base/common/filters*/,44/*vs/base/browser/ui/aria/aria*/,7/*vs/base/browser/dom*/,15/*vs/base/common/async*/,211/*vs/css!vs/base/browser/ui/list/list*/]), function (require, exports, lifecycle_1, types_1, arrays_1, decorators_1, platform, touch_1, keyboardEvent_1, event_1, event_2, list_1, listView_1, color_1, objects_1, splice_1, numbers_1, filters_1, aria_1, dom_1, async_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.List = exports.DefaultStyleController = exports.MouseController = exports.isSelectionRangeChangeEvent = exports.isSelectionSingleChangeEvent = exports.DefaultKeyboardNavigationDelegate = exports.isMonacoEditor = exports.isInputElement = void 0;
class TraitRenderer {
constructor(trait) {
this.trait = trait;
this.renderedElements = [];
}
get templateId() {
return `template:${this.trait.trait}`;
}
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 {
constructor(_trait) {
this._trait = _trait;
this.length = 0;
this.indexes = [];
this.sortedIndexes = [];
this._onChange = new event_1.Emitter();
this.onChange = this._onChange.event;
}
get trait() { return this._trait; }
get renderer() {
return new TraitRenderer(this);
}
splice(start, deleteCount, elements) {
var _a;
deleteCount = Math.max(0, Math.min(deleteCount, this.length - start));
const diff = elements.length - deleteCount;
const end = start + deleteCount;
const sortedIndexes = [
...this.sortedIndexes.filter(i => i < start),
...elements.map((hasTrait, i) => hasTrait ? i + start : -1).filter(i => i !== -1),
...this.sortedIndexes.filter(i => i >= end).map(i => i + diff)
];
const length = this.length + diff;
if (this.sortedIndexes.length > 0 && sortedIndexes.length === 0 && length > 0) {
const first = (_a = this.sortedIndexes.find(index => index >= start)) !== null && _a !== void 0 ? _a : length - 1;
sortedIndexes.push(Math.min(first, length - 1));
}
this.renderer.splice(start, deleteCount, elements.length);
this._set(sortedIndexes, sortedIndexes);
this.length = length;
}
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, elements.map(() => false));
}
const pastElementsWithTrait = this.trait.get().map(i => this.identityProvider.getId(this.view.element(i)).toString());
const elementsWithTrait = elements.map(e => pastElementsWithTrait.indexOf(this.identityProvider.getId(e).toString()) > -1);
this.trait.splice(start, deleteCount, elementsWithTrait);
}
}
function isInputElement(e) {
return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA';
}
exports.isInputElement = isInputElement;
function isMonacoEditor(e) {
if (e.classList.contains('monaco-editor')) {
return true;
}
if (e.classList.contains('monaco-list')) {
return false;
}
if (!e.parentElement) {
return false;
}
return isMonacoEditor(e.parentElement);
}
exports.isMonacoEditor = isMonacoEditor;
class KeyboardController {
constructor(list, view, options) {
this.list = list;
this.view = view;
this.disposables = new lifecycle_1.DisposableStore();
this.multipleSelectionDisposables = new lifecycle_1.DisposableStore();
this.onKeyDown.filter(e => e.keyCode === 3 /* Enter */).on(this.onEnter, this, this.disposables);
this.onKeyDown.filter(e => e.keyCode === 16 /* UpArrow */).on(this.onUpArrow, this, this.disposables);
this.onKeyDown.filter(e => e.keyCode === 18 /* DownArrow */).on(this.onDownArrow, this, this.disposables);
this.onKeyDown.filter(e => e.keyCode === 11 /* PageUp */).on(this.onPageUpArrow, this, this.disposables);
this.onKeyDown.filter(e => e.keyCode === 12 /* PageDown */).on(this.onPageDownArrow, this, this.disposables);
this.onKeyDown.filter(e => e.keyCode === 9 /* Escape */).on(this.onEscape, this, this.disposables);
if (options.multipleSelectionSupport !== false) {
this.onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === 31 /* KEY_A */).on(this.onCtrlA, this, this.multipleSelectionDisposables);
}
}
get onKeyDown() {
return event_1.Event.chain(this.disposables.add(new event_2.DomEmitter(this.view.domNode, 'keydown')).event)
.filter(e => !isInputElement(e.target))
.map(e => new keyboardEvent_1.StandardKeyboardEvent(e));
}
updateOptions(optionsUpdate) {
if (optionsUpdate.multipleSelectionSupport !== undefined) {
this.multipleSelectionDisposables.clear();
if (optionsUpdate.multipleSelectionSupport) {
this.onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === 31 /* KEY_A */).on(this.onCtrlA, this, this.multipleSelectionDisposables);
}
}
}
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);
this.list.reveal(this.list.getFocus()[0]);
this.view.domNode.focus();
}
onDownArrow(e) {
e.preventDefault();
e.stopPropagation();
this.list.focusNext(1, false, e.browserEvent);
this.list.reveal(this.list.getFocus()[0]);
this.view.domNode.focus();
}
onPageUpArrow(e) {
e.preventDefault();
e.stopPropagation();
this.list.focusPreviousPage(e.browserEvent);
this.list.reveal(this.list.getFocus()[0]);
this.view.domNode.focus();
}
onPageDownArrow(e) {
e.preventDefault();
e.stopPropagation();
this.list.focusNextPage(e.browserEvent);
this.list.reveal(this.list.getFocus()[0]);
this.view.domNode.focus();
}
onCtrlA(e) {
e.preventDefault();
e.stopPropagation();
this.list.setSelection((0, arrays_1.range)(this.list.length), e.browserEvent);
this.view.domNode.focus();
}
onEscape(e) {
if (this.list.getSelection().length) {
e.preventDefault();
e.stopPropagation();
this.list.setSelection([], e.browserEvent);
this.view.domNode.focus();
}
}
dispose() {
this.disposables.dispose();
this.multipleSelectionDisposables.dispose();
}
}
__decorate([
decorators_1.memoize
], KeyboardController.prototype, "onKeyDown", null);
var TypeLabelControllerState;
(function (TypeLabelControllerState) {
TypeLabelControllerState[TypeLabelControllerState["Idle"] = 0] = "Idle";
TypeLabelControllerState[TypeLabelControllerState["Typing"] = 1] = "Typing";
})(TypeLabelControllerState || (TypeLabelControllerState = {}));
exports.DefaultKeyboardNavigationDelegate = new class {
mightProducePrintableCharacter(event) {
if (event.ctrlKey || event.metaKey || event.altKey) {
return false;
}
return (event.keyCode >= 31 /* KEY_A */ && event.keyCode <= 56 /* KEY_Z */)
|| (event.keyCode >= 21 /* KEY_0 */ && event.keyCode <= 30 /* KEY_9 */)
|| (event.keyCode >= 93 /* NUMPAD_0 */ && event.keyCode <= 102 /* NUMPAD_9 */)
|| (event.keyCode >= 80 /* US_SEMICOLON */ && event.keyCode <= 90 /* US_QUOTE */);
}
};
class TypeLabelController {
constructor(list, view, keyboardNavigationLabelProvider, delegate) {
this.list = list;
this.view = view;
this.keyboardNavigationLabelProvider = keyboardNavigationLabelProvider;
this.delegate = delegate;
this.enabled = false;
this.state = TypeLabelControllerState.Idle;
this.automaticKeyboardNavigation = true;
this.triggered = false;
this.previouslyFocused = -1;
this.enabledDisposables = new lifecycle_1.DisposableStore();
this.disposables = new lifecycle_1.DisposableStore();
this.updateOptions(list.options);
}
updateOptions(options) {
const enableKeyboardNavigation = typeof options.enableKeyboardNavigation === 'undefined' ? true : !!options.enableKeyboardNavigation;
if (enableKeyboardNavigation) {
this.enable();
}
else {
this.disable();
}
if (typeof options.automaticKeyboardNavigation !== 'undefined') {
this.automaticKeyboardNavigation = options.automaticKeyboardNavigation;
}
}
enable() {
if (this.enabled) {
return;
}
const onChar = event_1.Event.chain(this.enabledDisposables.add(new event_2.DomEmitter(this.view.domNode, 'keydown')).event)
.filter(e => !isInputElement(e.target))
.filter(() => this.automaticKeyboardNavigation || this.triggered)
.map(event => new keyboardEvent_1.StandardKeyboardEvent(event))
.filter(e => this.delegate.mightProducePrintableCharacter(e))
.forEach(e => { e.stopPropagation(); e.preventDefault(); })
.map(event => event.browserEvent.key)
.event;
const onClear = event_1.Event.debounce(onChar, () => null, 800);
const onInput = event_1.Event.reduce(event_1.Event.any(onChar, onClear), (r, i) => i === null ? null : ((r || '') + i));
onInput(this.onInput, this, this.enabledDisposables);
onClear(this.onClear, this, this.enabledDisposables);
this.enabled = true;
this.triggered = false;
}
disable() {
if (!this.enabled) {
return;
}
this.enabledDisposables.clear();
this.enabled = false;
this.triggered = false;
}
onClear() {
var _a;
const focus = this.list.getFocus();
if (focus.length > 0 && focus[0] === this.previouslyFocused) {
// List: re-anounce element on typing end since typed keys will interupt 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 = (_a = this.list.options.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.getAriaLabel(this.list.element(focus[0]));
if (ariaLabel) {
(0, aria_1.alert)(ariaLabel);
}
}
this.previouslyFocused = -1;
}
onInput(word) {
if (!word) {
this.state = TypeLabelControllerState.Idle;
this.triggered = false;
return;
}
const focus = this.list.getFocus();
const start = focus.length > 0 ? focus[0] : 0;
const delta = this.state === TypeLabelControllerState.Idle ? 1 : 0;
this.state = TypeLabelControllerState.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 (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_1.Event.chain(this.disposables.add(new event_2.DomEmitter(view.domNode, 'keydown')).event)
.filter(e => !isInputElement(e.target))
.map(e => new keyboardEvent_1.StandardKeyboardEvent(e));
onKeyDown.filter(e => e.keyCode === 2 /* Tab */ && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey)
.on(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 || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) {
return;
}
const style = window.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;
}
exports.isSelectionSingleChangeEvent = isSelectionSingleChangeEvent;
function isSelectionRangeChangeEvent(event) {
return event.browserEvent.shiftKey;
}
exports.isSelectionRangeChangeEvent = isSelectionRangeChangeEvent;
function isMouseRightClick(event) {
return event instanceof MouseEvent && event.button === 2;
}
const DefaultMultipleSelectionController = {
isSelectionSingleChangeEvent,
isSelectionRangeChangeEvent
};
class MouseController {
constructor(list) {
this.list = list;
this.disposables = new lifecycle_1.DisposableStore();
this._onPointer = new event_1.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_1.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 (document.activeElement !== e.browserEvent.target) {
this.list.domFocus();
}
}
onContextMenu(e) {
if (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;
}
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.isSelectionRangeChangeEvent(e)) {
return this.changeSelection(e);
}
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;
}
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 !== null && currentFocus !== void 0 ? 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) {
if (styles.listBackground.isOpaque()) {
content.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles.listBackground}; }`);
}
else if (!platform.isMacintosh) { // subpixel AA doesn't exist in macOS
console.warn(`List with id '${this.selectorSuffix}' was styled with a non-opaque background color. This will break sub-pixel antialiasing.`);
}
}
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) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`);
}
if (styles.listHoverForeground) {
content.push(`.monaco-list${suffix} .monaco-list-row:hover:not(.selected):not(.focused) { color: ${styles.listHoverForeground}; }`);
}
if (styles.listSelectionOutline) {
content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`);
}
if (styles.listFocusOutline) {
content.push(`
.monaco-drag-image,
.monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }
`);
}
if (styles.listInactiveFocusOutline) {
content.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`);
}
if (styles.listHoverOutline) {
content.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`);
}
if (styles.listDropBackground) {
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.listDropBackground} !important; color: inherit !important; }
`);
}
if (styles.listFilterWidgetBackground) {
content.push(`.monaco-list-type-filter { background-color: ${styles.listFilterWidgetBackground} }`);
}
if (styles.listFilterWidgetOutline) {
content.push(`.monaco-list-type-filter { border: 1px solid ${styles.listFilterWidgetOutline}; }`);
}
if (styles.listFilterWidgetNoMatchesOutline) {
content.push(`.monaco-list-type-filter.no-matches { border: 1px solid ${styles.listFilterWidgetNoMatchesOutline}; }`);
}
if (styles.listMatchesShadow) {
content.push(`.monaco-list-type-filter { box-shadow: 1px 1px 1px ${styles.listMatchesShadow}; }`);
}
if (styles.tableColumnsBorder) {
content.push(`
.monaco-table:hover > .monaco-split-view2,
.monaco-table:hover > .monaco-split-view2 .monaco-sash.vertical::before {
border-color: ${styles.tableColumnsBorder};
}`);
}
this.styleElement.textContent = content.join('\n');
}
}
exports.DefaultStyleController = DefaultStyleController;
const defaultStyles = {
listFocusBackground: color_1.Color.fromHex('#7FB0D0'),
listActiveSelectionBackground: color_1.Color.fromHex('#0E639C'),
listActiveSelectionForeground: color_1.Color.fromHex('#FFFFFF'),
listActiveSelectionIconForeground: color_1.Color.fromHex('#FFFFFF'),
listFocusAndSelectionBackground: color_1.Color.fromHex('#094771'),
listFocusAndSelectionForeground: color_1.Color.fromHex('#FFFFFF'),
listInactiveSelectionBackground: color_1.Color.fromHex('#3F3F46'),
listInactiveSelectionIconForeground: color_1.Color.fromHex('#FFFFFF'),
listHoverBackground: color_1.Color.fromHex('#2A2D2E'),
listDropBackground: color_1.Color.fromHex('#383B3D'),
treeIndentGuidesStroke: color_1.Color.fromHex('#a9a9a9'),
tableColumnsBorder: color_1.Color.fromHex('#cccccc').transparent(0.2)
};
const DefaultOptions = {
keyboardSupport: true,
mouseSupport: true,
multipleSelectionSupport: true,
dnd: {
getDragURI() { return null; },
onDragStart() { },
onDragOver() { return false; },
drop() { }
}
};
// 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) {
if (renderer.disposeElement) {
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;
}
renderElement(element, index, container) {
const ariaLabel = this.accessibilityProvider.getAriaLabel(element);
if (ariaLabel) {
container.setAttribute('aria-label', ariaLabel);
}
else {
container.removeAttribute('aria-label');
}
const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element);
if (typeof ariaLevel === 'number') {
container.setAttribute('aria-level', `${ariaLevel}`);
}
else {
container.removeAttribute('aria-level');
}
}
disposeTemplate(templateData) {
// noop
}
}
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) {
if (this.dnd.onDragStart) {
this.dnd.onDragStart(data, originalEvent);
}
}
onDragOver(data, targetElement, targetIndex, originalEvent) {
return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent);
}
onDragLeave(data, targetElement, targetIndex, originalEvent) {
var _a, _b;
(_b = (_a = this.dnd).onDragLeave) === null || _b === void 0 ? void 0 : _b.call(_a, data, targetElement, targetIndex, originalEvent);
}
onDragEnd(originalEvent) {
if (this.dnd.onDragEnd) {
this.dnd.onDragEnd(originalEvent);
}
}
drop(data, targetElement, targetIndex, originalEvent) {
this.dnd.drop(data, targetElement, targetIndex, originalEvent);
}
}
class List {
constructor(user, container, virtualDelegate, renderers, _options = DefaultOptions) {
var _a;
this.user = user;
this._options = _options;
this.focus = new Trait('focused');
this.anchor = new Trait('anchor');
this.eventBufferer = new event_1.EventBufferer();
this._ariaLabel = '';
this.disposables = new lifecycle_1.DisposableStore();
this._onDidDispose = new event_1.Emitter();
this.onDidDispose = this._onDidDispose.event;
const role = this._options.accessibilityProvider && this._options.accessibilityProvider.getWidgetRole ? (_a = this._options.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.getWidgetRole() : 'list';
this.selection = new SelectionTrait(role !== 'listbox');
(0, objects_1.mixin)(_options, defaultStyles, false);
const baseRenderers = [this.focus.renderer, this.selection.renderer];
this.accessibilityProvider = _options.accessibilityProvider;
if (this.accessibilityProvider) {
baseRenderers.push(new AccessibiltyRenderer(this.accessibilityProvider));
if (this.accessibilityProvider.onDidChangeActiveDescendant) {
this.accessibilityProvider.onDidChangeActiveDescendant(this.onDidChangeActiveDescendant, this, this.disposables);
}
}
renderers = renderers.map(r => new PipelineRenderer(r.templateId, [...baseRenderers, r]));
const viewOptions = Object.assign(Object.assign({}, _options), { dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd) });
this.view = new listView_1.ListView(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.typeLabelController = new TypeLabelController(this, this.view, _options.keyboardNavigationLabelProvider, delegate);
this.disposables.add(this.typeLabelController);
}
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');
}
}
get onDidChangeFocus() {
return event_1.Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), e => this.toListEvent(e));
}
get onDidChangeSelection() {
return event_1.Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), e => this.toListEvent(e));
}
get domId() { return this.view.domId; }
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 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_1.Event.chain(this.disposables.add(new event_2.DomEmitter(this.view.domNode, 'keydown')).event)
.map(e => new keyboardEvent_1.StandardKeyboardEvent(e))
.filter(e => didJustPressContextMenuKey = e.keyCode === 58 /* ContextMenu */ || (e.shiftKey && e.keyCode === 68 /* F10 */))
.map(event_2.stopEvent)
.filter(() => false)
.event;
const fromKeyUp = event_1.Event.chain(this.disposables.add(new event_2.DomEmitter(this.view.domNode, 'keyup')).event)
.forEach(() => didJustPressContextMenuKey = false)
.map(e => new keyboardEvent_1.StandardKeyboardEvent(e))
.filter(e => e.keyCode === 58 /* ContextMenu */ || (e.shiftKey && e.keyCode === 68 /* F10 */))
.map(event_2.stopEvent)
.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 };
})
.event;
const fromMouse = event_1.Event.chain(this.view.onContextMenu)
.filter(_ => !didJustPressContextMenuKey)
.map(({ element, index, browserEvent }) => ({ element, index, anchor: { x: browserEvent.pageX + 1, y: browserEvent.pageY }, browserEvent }))
.event;
return event_1.Event.any(fromKeyDown, fromKeyUp, fromMouse);
}
get onKeyDown() { return this.disposables.add(new event_2.DomEmitter(this.view.domNode, 'keydown')).event; }
get onDidFocus() { return event_1.Event.signal(this.disposables.add(new event_2.DomEmitter(this.view.domNode, 'focus', true)).event); }
createMouseController(options) {
return new MouseController(this);
}
updateOptions(optionsUpdate = {}) {
var _a;
this._options = Object.assign(Object.assign({}, this._options), optionsUpdate);
if (this.typeLabelController) {
this.typeLabelController.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);
(_a = this.keyboardController) === null || _a === void 0 ? void 0 : _a.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);
}
get length() {
return this.view.length;
}
get contentHeight() {
return this.view.contentHeight;
}
get scrollTop() {
return this.view.getScrollTop();
}
set scrollTop(scrollTop) {
this.view.setScrollTop(scrollTop);
}
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);
}
}
focusNextPage(browserEvent, filter) {
return __awaiter(this, void 0, void 0, function* () {
let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight);
lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1;
const lastPageElement = this.view.element(lastPageIndex);
const currentlyFocusedElement = this.getFocusedElements()[0];
if (currentlyFocusedElement !== lastPageElement) {
const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter);
if (lastGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(lastGoodPageIndex)) {
this.setFocus([lastGoodPageIndex], browserEvent);
}
else {
this.setFocus([lastPageIndex], browserEvent);
}
}
else {
const previousScrollTop = this.view.getScrollTop();
this.view.setScrollTop(previousScrollTop + this.view.renderHeight - this.view.elementHeight(lastPageIndex));
if (this.view.getScrollTop() !== previousScrollTop) {
this.setFocus([]);
// Let the scroll event listener run
yield (0, async_1.timeout)(0);
yield this.focusNextPage(browserEvent, filter);
}
}
});
}
focusPreviousPage(browserEvent, filter) {
return __awaiter(this, void 0, void 0, function* () {
let firstPageIndex;
const scrollTop = this.view.getScrollTop();
if (scrollTop === 0) {
firstPageIndex = this.view.indexAt(scrollTop);
}
else {
firstPageIndex = this.view.indexAfter(scrollTop - 1);
}
const firstPageElement = this.view.element(firstPageIndex);
const currentlyFocusedElement = this.getFocusedElements()[0];
if (currentlyFocusedElement !== firstPageElement) {
const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter);
if (firstGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(firstGoodPageIndex)) {
this.setFocus([firstGoodPageIndex], browserEvent);
}
else {
this.setFocus([firstPageIndex], browserEvent);
}
}
else {
const previousScrollTop = scrollTop;
this.view.setScrollTop(scrollTop - this.view.renderHeight);
if (this.view.getScrollTop() !== previousScrollTop) {
this.setFocus([]);
// Let the scroll event listener run
yield (0, async_1.timeout)(0);
yield this.focusPreviousPage(browserEvent, filter);
}
}
});
}
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) {
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;
this.view.setScrollTop(m * (0, numbers_1.clamp)(relativeTop, 0, 1) + elementTop);
}
else {
const viewItemBottom = elementTop + elementHeight;
const scrollBottom = scrollTop + this.view.renderHeight;
if (elementTop < scrollTop && viewItemBottom >= scrollBottom) {
// The element is already overflowing the viewport, no-op
}
else if (elementTop < scrollTop || (viewItemBottom >= scrollBottom && elementHeight >= this.view.renderHeight)) {
this.view.setScrollTop(elementTop);
}
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) {
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 || elementTop + elementHeight > scrollTop + this.view.renderHeight) {
return null;
}
// y = mx + b
const m = elementHeight - this.view.renderHeight;
return Math.abs((scrollTop - elementTop) / m);
}
getHTMLElement() {
return this.view.domNode;
}
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() {
var _a;
const focus = this.focus.get();
if (focus.length > 0) {
let id;
if ((_a = this.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.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();
}
}
__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);
exports.List = 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/base/browser/ui/list/listPaging*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,19/*vs/base/common/arrays*/,108/*vs/base/browser/ui/list/listWidget*/,6/*vs/base/common/event*/,23/*vs/base/common/cancellation*/,211/*vs/css!vs/base/browser/ui/list/list*/]), function (require, exports, lifecycle_1, arrays_1, listWidget_1, event_1, cancellation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PagedList = void 0;
class PagedRenderer {
constructor(renderer, modelProvider) {
this.renderer = renderer;
this.modelProvider = modelProvider;
}
get templateId() { return this.renderer.templateId; }
renderTemplate(container) {
const data = this.renderer.renderTemplate(container);
return { data, disposable: lifecycle_1.Disposable.None };
}
renderElement(index, _, data, height) {
if (data.disposable) {
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 Object.assign(Object.assign({}, 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 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;
});
define(__m[321/*vs/css!vs/base/browser/ui/splitview/splitview*/], __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[212/*vs/base/browser/ui/splitview/splitview*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/,20/*vs/base/common/types*/,102/*vs/base/common/numbers*/,19/*vs/base/common/arrays*/,107/*vs/base/browser/ui/sash/sash*/,29/*vs/base/common/color*/,7/*vs/base/browser/dom*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,127/*vs/base/common/scrollable*/,321/*vs/css!vs/base/browser/ui/splitview/splitview*/]), function (require, exports, lifecycle_1, event_1, types, numbers_1, arrays_1, sash_1, color_1, dom_1, scrollableElement_1, scrollable_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SplitView = exports.Sizing = void 0;
const defaultStyles = {
separatorBorder: color_1.Color.transparent
};
class ViewItem {
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;
}
}
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);
if (this.view.setVisible) {
this.view.setVisible(visible);
}
}
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 snap() { return !!this.view.snap; }
set enabled(enabled) {
this.container.style.pointerEvents = enabled ? '' : 'none';
}
layout(offset, layoutContext) {
this.layoutContainer(offset);
this.view.layout(this.size, offset, layoutContext);
}
dispose() {
this.disposable.dispose();
return this.view;
}
}
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) {
Sizing.Distribute = { type: 'distribute' };
function Split(index) { return { type: 'split', index }; }
Sizing.Split = Split;
function Invisible(cachedVisibleSize) { return { type: 'invisible', cachedVisibleSize }; }
Sizing.Invisible = Invisible;
})(Sizing = exports.Sizing || (exports.Sizing = {}));
class SplitView extends lifecycle_1.Disposable {
constructor(container, options = {}) {
var _a, _b;
super();
this.size = 0;
this.contentSize = 0;
this.proportions = undefined;
this.viewItems = [];
this.sashItems = [];
this.state = State.Idle;
this._onDidSashChange = this._register(new event_1.Emitter());
this.onDidSashChange = this._onDidSashChange.event;
this._onDidSashReset = this._register(new event_1.Emitter());
this._startSnappingEnabled = true;
this._endSnappingEnabled = true;
this.orientation = types.isUndefined(options.orientation) ? 0 /* VERTICAL */ : options.orientation;
this.inverseAltBehavior = !!options.inverseAltBehavior;
this.proportionalLayout = types.isUndefined(options.proportionalLayout) ? true : !!options.proportionalLayout;
this.getSashOrthogonalSize = options.getSashOrthogonalSize;
this.el = document.createElement('div');
this.el.classList.add('monaco-split-view2');
this.el.classList.add(this.orientation === 0 /* 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 = new scrollable_1.Scrollable(125, dom_1.scheduleAtNextAnimationFrame);
this.scrollableElement = this._register(new scrollableElement_1.SmoothScrollableElement(this.viewContainer, {
vertical: this.orientation === 0 /* VERTICAL */ ? ((_a = options.scrollbarVisibility) !== null && _a !== void 0 ? _a : 1 /* Auto */) : 2 /* Hidden */,
horizontal: this.orientation === 1 /* HORIZONTAL */ ? ((_b = options.scrollbarVisibility) !== null && _b !== void 0 ? _b : 1 /* Auto */) : 2 /* Hidden */
}, this.scrollable));
this.onDidScroll = this.scrollableElement.onScroll;
this._register(this.onDidScroll(e => {
this.viewContainer.scrollTop = e.scrollTop;
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();
}
}
get orthogonalStartSash() { return this._orthogonalStartSash; }
set orthogonalStartSash(sash) {
for (const sashItem of this.sashItems) {
sashItem.sash.orthogonalStartSash = sash;
}
this._orthogonalStartSash = sash;
}
get orthogonalEndSash() { return this._orthogonalEndSash; }
set orthogonalEndSash(sash) {
for (const sashItem of this.sashItems) {
sashItem.sash.orthogonalEndSash = sash;
}
this._orthogonalEndSash = sash;
}
get startSnappingEnabled() { return this._startSnappingEnabled; }
set startSnappingEnabled(startSnappingEnabled) {
if (this._startSnappingEnabled === startSnappingEnabled) {
return;
}
this._startSnappingEnabled = startSnappingEnabled;
this.updateSashEnablement();
}
get endSnappingEnabled() { return this._endSnappingEnabled; }
set endSnappingEnabled(endSnappingEnabled) {
if (this._endSnappingEnabled === endSnappingEnabled) {
return;
}
this._endSnappingEnabled = endSnappingEnabled;
this.updateSashEnablement();
}
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());
}
}
addView(view, size, index = this.viewItems.length, skipLayout) {
this.doAddView(view, size, index, skipLayout);
}
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 /* Low */);
const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* High */);
this.resize(this.viewItems.length - 1, size - previousSize, undefined, lowPriorityIndexes, highPriorityIndexes);
}
else {
for (let i = 0; i < this.viewItems.length; i++) {
const item = this.viewItems[i];
item.size = (0, numbers_1.clamp)(Math.round(this.proportions[i] * size), item.minimumSize, item.maximumSize);
}
}
this.distributeEmptySpace();
this.layoutViews();
}
saveProportions() {
if (this.proportionalLayout && this.contentSize > 0) {
this.proportions = this.viewItems.map(i => i.size / this.contentSize);
}
}
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)(document.body, 'keydown', e => resetSashDragState(this.sashDragState.current, e.altKey)), (0, dom_1.addDisposableListener)(document.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);
}
}
resizeView(index, size) {
if (this.state !== State.Idle) {
throw new Error('Cant modify splitview');
}
this.state = State.Busy;
if (index < 0 || index >= this.viewItems.length) {
return;
}
const indexes = (0, arrays_1.range)(this.viewItems.length).filter(i => i !== index);
const lowPriorityIndexes = [...indexes.filter(i => this.viewItems[i].priority === 1 /* Low */), index];
const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* 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);
this.state = State.Idle;
}
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 /* Low */);
const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* High */);
this.relayout(lowPriorityIndexes, highPriorityIndexes);
}
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;
// 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)(() => this.viewContainer.removeChild(container));
const disposable = (0, lifecycle_1.combinedDisposable)(onChangeDisposable, containerDisposable);
let viewSize;
if (typeof size === 'number') {
viewSize = size;
}
else 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 /* 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) {
let opts = { orthogonalStartSash: this.orthogonalStartSash, orthogonalEndSash: this.orthogonalEndSash };
const sash = this.orientation === 0 /* VERTICAL */
? new sash_1.Sash(this.sashContainer, { getHorizontalSashTop: s => this.getSashPosition(s), getHorizontalSashWidth: this.getSashOrthogonalSize }, Object.assign(Object.assign({}, opts), { orientation: 1 /* HORIZONTAL */ }))
: new sash_1.Sash(this.sashContainer, { getVerticalSashLeft: s => this.getSashPosition(s), getVerticalSashHeight: this.getSashOrthogonalSize }, Object.assign(Object.assign({}, opts), { orientation: 0 /* VERTICAL */ }));
const sashEventMapper = this.orientation === 0 /* 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_1.Event.map(sash.onDidStart, sashEventMapper);
const onStartDisposable = onStart(this.onSashStart, this);
const onChange = event_1.Event.map(sash.onDidChange, sashEventMapper);
const onChangeDisposable = onChange(this.onSashChange, this);
const onEnd = event_1.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);
}
this.state = State.Idle;
if (!skipLayout && typeof size !== 'number' && size.type === 'distribute') {
this.distributeViewSizes();
}
}
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 /* Low */);
const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* 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 /* 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 /* Minimum */;
}
else if (snappedAfter && collapsesDown[index] && (position < this.contentSize || this.endSnappingEnabled)) {
sash.state = 2 /* Maximum */;
}
else {
sash.state = 0 /* Disabled */;
}
}
else if (min && !max) {
sash.state = 1 /* Minimum */;
}
else if (!min && max) {
sash.state = 2 /* Maximum */;
}
else {
sash.state = 3 /* 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;
}
dispose() {
super.dispose();
this.viewItems.forEach(i => i.dispose());
this.viewItems = [];
this.sashItems.forEach(i => i.disposable.dispose());
this.sashItems = [];
}
}
exports.SplitView = SplitView;
});
define(__m[322/*vs/css!vs/base/browser/ui/table/table*/], __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[323/*vs/base/browser/ui/table/tableWidget*/], __M([0/*require*/,1/*exports*/,108/*vs/base/browser/ui/list/listWidget*/,7/*vs/base/browser/dom*/,212/*vs/base/browser/ui/splitview/splitview*/,6/*vs/base/common/event*/,322/*vs/css!vs/base/browser/ui/table/table*/]), function (require, exports, listWidget_1, dom_1, splitview_1, event_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Table = void 0;
class TableListRenderer {
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`;
}
}
}
TableListRenderer.TemplateId = 'row';
function asListVirtualDelegate(delegate) {
return {
getHeight(row) { return delegate.getHeight(row); },
getTemplateId() { return TableListRenderer.TemplateId; },
};
}
class ColumnHeader {
constructor(column, index) {
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, title: column.tooltip }, column.label);
}
get minimumSize() { var _a; return (_a = this.column.minimumWidth) !== null && _a !== void 0 ? _a : 120; }
get maximumSize() { var _a; return (_a = this.column.maximumWidth) !== null && _a !== void 0 ? _a : Number.POSITIVE_INFINITY; }
get onDidChange() { var _a; return (_a = this.column.onDidChangeWidthConstraints) !== null && _a !== void 0 ? _a : event_1.Event.None; }
layout(size) {
this._onDidLayout.fire([this.index, size]);
}
}
class Table {
constructor(user, container, virtualDelegate, columns, renderers, _options) {
this.virtualDelegate = virtualDelegate;
this.domId = `table_id_${++Table.InstanceCount}`;
this.cachedHeight = 0;
this.domNode = (0, dom_1.append)(container, (0, dom_1.$)(`.monaco-table.${this.domId}`));
const headers = columns.map((c, i) => 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 = new splitview_1.SplitView(this.domNode, {
orientation: 1 /* HORIZONTAL */,
scrollbarVisibility: 2 /* 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 = new listWidget_1.List(user, this.domNode, asListVirtualDelegate(virtualDelegate), [renderer], _options);
this.columnLayoutDisposable = event_1.Event.any(...headers.map(h => h.onDidLayout))(([index, size]) => renderer.layoutColumn(index, size));
this.styleElement = (0, dom_1.createStyleSheet)(this.domNode);
this.style({});
}
get onDidChangeFocus() { return this.list.onDidChangeFocus; }
get onDidChangeSelection() { return this.list.onDidChangeSelection; }
get onMouseDblClick() { return this.list.onMouseDblClick; }
get onPointer() { return this.list.onPointer; }
get onDidFocus() { return this.list.onDidFocus; }
get onDidDispose() { return this.list.onDidDispose; }
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.splitview.dispose();
this.list.dispose();
this.columnLayoutDisposable.dispose();
}
}
exports.Table = Table;
Table.InstanceCount = 0;
});
define(__m[324/*vs/css!vs/base/browser/ui/tree/media/tree*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[132/*vs/css!vs/base/parts/quickinput/browser/media/quickInput*/], __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[213/*vs/base/parts/quickinput/browser/quickInputUtils*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,125/*vs/base/common/idGenerator*/,132/*vs/css!vs/base/parts/quickinput/browser/media/quickInput*/]), function (require, exports, dom, idGenerator_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getIconClass = void 0;
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}`, `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;
}
exports.getIconClass = getIconClass;
});
define(__m[325/*vs/css!vs/editor/browser/controller/textAreaHandler*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[326/*vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[327/*vs/css!vs/editor/browser/viewParts/decorations/decorations*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[328/*vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[329/*vs/css!vs/editor/browser/viewParts/indentGuides/indentGuides*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[330/*vs/css!vs/editor/browser/viewParts/lineNumbers/lineNumbers*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[331/*vs/css!vs/editor/browser/viewParts/lines/viewLines*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[332/*vs/css!vs/editor/browser/viewParts/linesDecorations/linesDecorations*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[333/*vs/css!vs/editor/browser/viewParts/marginDecorations/marginDecorations*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[334/*vs/css!vs/editor/browser/viewParts/minimap/minimap*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[335/*vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[336/*vs/css!vs/editor/browser/viewParts/rulers/rulers*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[337/*vs/css!vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[338/*vs/css!vs/editor/browser/viewParts/selections/selections*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[339/*vs/css!vs/editor/browser/viewParts/viewCursors/viewCursors*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[340/*vs/css!vs/editor/browser/widget/media/diffEditor*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[341/*vs/css!vs/editor/browser/widget/media/diffReview*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[342/*vs/css!vs/editor/browser/widget/media/editor*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[343/*vs/css!vs/editor/contrib/anchorSelect/anchorSelect*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[344/*vs/css!vs/editor/contrib/bracketMatching/bracketMatching*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[345/*vs/css!vs/editor/contrib/codeAction/lightBulbWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[346/*vs/css!vs/editor/contrib/codelens/codelensWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[347/*vs/css!vs/editor/contrib/colorPicker/colorPicker*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[348/*vs/css!vs/editor/contrib/dnd/dnd*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[349/*vs/css!vs/editor/contrib/find/findWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[350/*vs/css!vs/editor/contrib/folding/folding*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[351/*vs/css!vs/editor/contrib/gotoError/media/gotoErrorWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[352/*vs/css!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[353/*vs/css!vs/editor/contrib/gotoSymbol/peek/referencesWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[354/*vs/css!vs/editor/contrib/inlineCompletions/ghostText*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[355/*vs/css!vs/editor/contrib/links/links*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[356/*vs/css!vs/editor/contrib/message/messageController*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[357/*vs/css!vs/editor/contrib/parameterHints/parameterHints*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[358/*vs/css!vs/editor/contrib/peekView/media/peekViewWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[359/*vs/css!vs/editor/contrib/rename/renameInputField*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[360/*vs/css!vs/editor/contrib/snippet/snippetSession*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[361/*vs/css!vs/editor/contrib/suggest/media/suggest*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[362/*vs/css!vs/editor/contrib/zoneWidget/zoneWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[363/*vs/css!vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[364/*vs/css!vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[365/*vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[366/*vs/css!vs/editor/standalone/browser/quickInput/standaloneQuickInput*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[367/*vs/css!vs/editor/standalone/browser/standalone-tokens*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[368/*vs/css!vs/platform/actions/browser/menuEntryActionViewItem*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[369/*vs/css!vs/platform/contextview/browser/contextMenuHandler*/], __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[370/*vs/editor/browser/config/charWidthReader*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.readCharWidths = exports.CharWidthRequest = void 0;
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() {
// Create a test container with all these test elements
this._createDomElements();
// Add the container to the DOM
document.body.appendChild(this._container);
// Read character widths
this._readFromDomElements();
// Remove the container from the DOM
document.body.removeChild(this._container);
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');
regularDomNode.style.fontFamily = this._bareFontInfo.getMassagedFontFamily();
regularDomNode.style.fontWeight = this._bareFontInfo.fontWeight;
regularDomNode.style.fontSize = this._bareFontInfo.fontSize + 'px';
regularDomNode.style.fontFeatureSettings = this._bareFontInfo.fontFeatureSettings;
regularDomNode.style.lineHeight = this._bareFontInfo.lineHeight + 'px';
regularDomNode.style.letterSpacing = this._bareFontInfo.letterSpacing + 'px';
container.appendChild(regularDomNode);
const boldDomNode = document.createElement('div');
boldDomNode.style.fontFamily = this._bareFontInfo.getMassagedFontFamily();
boldDomNode.style.fontWeight = 'bold';
boldDomNode.style.fontSize = this._bareFontInfo.fontSize + 'px';
boldDomNode.style.fontFeatureSettings = this._bareFontInfo.fontFeatureSettings;
boldDomNode.style.lineHeight = this._bareFontInfo.lineHeight + 'px';
boldDomNode.style.letterSpacing = this._bareFontInfo.letterSpacing + 'px';
container.appendChild(boldDomNode);
const italicDomNode = document.createElement('div');
italicDomNode.style.fontFamily = this._bareFontInfo.getMassagedFontFamily();
italicDomNode.style.fontWeight = this._bareFontInfo.fontWeight;
italicDomNode.style.fontSize = this._bareFontInfo.fontSize + 'px';
italicDomNode.style.fontFeatureSettings = this._bareFontInfo.fontFeatureSettings;
italicDomNode.style.lineHeight = this._bareFontInfo.lineHeight + 'px';
italicDomNode.style.letterSpacing = this._bareFontInfo.letterSpacing + 'px';
italicDomNode.style.fontStyle = 'italic';
container.appendChild(italicDomNode);
const testElements = [];
for (const request of this._requests) {
let parent;
if (request.type === 0 /* Regular */) {
parent = regularDomNode;
}
if (request.type === 2 /* Bold */) {
parent = boldDomNode;
}
if (request.type === 1 /* 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(bareFontInfo, requests) {
const reader = new DomCharWidthReader(bareFontInfo, requests);
reader.read();
}
exports.readCharWidths = readCharWidths;
});
/*---------------------------------------------------------------------------------------------
* 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/config/elementSizeObserver*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/]), function (require, exports, lifecycle_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ElementSizeObserver = void 0;
class ElementSizeObserver extends lifecycle_1.Disposable {
constructor(referenceDomElement, dimension, changeCallback) {
super();
this.referenceDomElement = referenceDomElement;
this.changeCallback = changeCallback;
this.width = -1;
this.height = -1;
this.resizeObserver = null;
this.measureReferenceDomElementToken = -1;
this.measureReferenceDomElement(false, dimension);
}
dispose() {
this.stopObserving();
super.dispose();
}
getWidth() {
return this.width;
}
getHeight() {
return this.height;
}
startObserving() {
if (typeof ResizeObserver !== 'undefined') {
if (!this.resizeObserver && this.referenceDomElement) {
this.resizeObserver = new ResizeObserver((entries) => {
if (entries && entries[0] && entries[0].contentRect) {
this.observe({ width: entries[0].contentRect.width, height: entries[0].contentRect.height });
}
else {
this.observe();
}
});
this.resizeObserver.observe(this.referenceDomElement);
}
}
else {
if (this.measureReferenceDomElementToken === -1) {
// setInterval type defaults to NodeJS.Timeout instead of number, so specify it as a number
this.measureReferenceDomElementToken = setInterval(() => this.observe(), 100);
}
}
}
stopObserving() {
if (this.resizeObserver) {
this.resizeObserver.disconnect();
this.resizeObserver = null;
}
if (this.measureReferenceDomElementToken !== -1) {
clearInterval(this.measureReferenceDomElementToken);
this.measureReferenceDomElementToken = -1;
}
}
observe(dimension) {
this.measureReferenceDomElement(true, dimension);
}
measureReferenceDomElement(callChangeCallback, 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 (callChangeCallback) {
this.changeCallback();
}
}
}
}
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[167/*vs/editor/browser/editorDom*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,93/*vs/base/browser/globalMouseMoveMonitor*/,55/*vs/base/browser/mouseEvent*/,2/*vs/base/common/lifecycle*/]), function (require, exports, dom, globalMouseMoveMonitor_1, mouseEvent_1, lifecycle_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GlobalEditorMouseMoveMonitor = exports.EditorPointerEventFactory = exports.EditorMouseEventFactory = exports.EditorMouseEvent = exports.createEditorPagePosition = exports.EditorPagePosition = exports.ClientCoordinates = exports.PageCoordinates = void 0;
/**
* 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() {
return new ClientCoordinates(this.x - dom.StandardWindow.scrollX, this.y - dom.StandardWindow.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() {
return new PageCoordinates(this.clientX + dom.StandardWindow.scrollX, this.clientY + dom.StandardWindow.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;
function createEditorPagePosition(editorViewDomNode) {
const editorPos = dom.getDomNodePagePosition(editorViewDomNode);
return new EditorPagePosition(editorPos.left, editorPos.top, editorPos.width, editorPos.height);
}
exports.createEditorPagePosition = createEditorPagePosition;
class EditorMouseEvent extends mouseEvent_1.StandardMouseEvent {
constructor(e, editorViewDomNode) {
super(e);
this._editorMouseEventBrand = undefined;
this.pos = new PageCoordinates(this.posx, this.posy);
this.editorPos = createEditorPagePosition(editorViewDomNode);
}
}
exports.EditorMouseEvent = EditorMouseEvent;
class EditorMouseEventFactory {
constructor(editorViewDomNode) {
this._editorViewDomNode = editorViewDomNode;
}
_create(e) {
return new EditorMouseEvent(e, 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, 'mousedown', (e) => {
callback(this._create(e));
});
}
onMouseLeave(target, callback) {
return dom.addDisposableNonBubblingMouseOutListener(target, (e) => {
callback(this._create(e));
});
}
onMouseMoveThrottled(target, callback, merger, minimumTimeMs) {
const myMerger = (lastEvent, currentEvent) => {
return merger(lastEvent, this._create(currentEvent));
};
return dom.addDisposableThrottledListener(target, 'mousemove', callback, myMerger, minimumTimeMs);
}
}
exports.EditorMouseEventFactory = EditorMouseEventFactory;
class EditorPointerEventFactory {
constructor(editorViewDomNode) {
this._editorViewDomNode = editorViewDomNode;
}
_create(e) {
return new EditorMouseEvent(e, this._editorViewDomNode);
}
onPointerUp(target, callback) {
return dom.addDisposableListener(target, 'pointerup', (e) => {
callback(this._create(e));
});
}
onPointerDown(target, callback) {
return dom.addDisposableListener(target, 'pointerdown', (e) => {
callback(this._create(e));
});
}
onPointerLeave(target, callback) {
return dom.addDisposableNonBubblingPointerOutListener(target, (e) => {
callback(this._create(e));
});
}
onPointerMoveThrottled(target, callback, merger, minimumTimeMs) {
const myMerger = (lastEvent, currentEvent) => {
return merger(lastEvent, this._create(currentEvent));
};
return dom.addDisposableThrottledListener(target, 'pointermove', callback, myMerger, minimumTimeMs);
}
}
exports.EditorPointerEventFactory = EditorPointerEventFactory;
class GlobalEditorMouseMoveMonitor extends lifecycle_1.Disposable {
constructor(editorViewDomNode) {
super();
this._editorViewDomNode = editorViewDomNode;
this._globalMouseMoveMonitor = this._register(new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor());
this._keydownListener = null;
}
startMonitoring(initialElement, initialButtons, merger, mouseMoveCallback, 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(document, 'keydown', (e) => {
const kb = e.toKeybinding();
if (kb.isModifierKey()) {
// Allow modifier keys
return;
}
this._globalMouseMoveMonitor.stopMonitoring(true, e.browserEvent);
}, true);
const myMerger = (lastEvent, currentEvent) => {
return merger(lastEvent, new EditorMouseEvent(currentEvent, this._editorViewDomNode));
};
this._globalMouseMoveMonitor.startMonitoring(initialElement, initialButtons, myMerger, mouseMoveCallback, (e) => {
this._keydownListener.dispose();
onStopCallback(e);
});
}
stopMonitoring() {
this._globalMouseMoveMonitor.stopMonitoring(true);
}
}
exports.GlobalEditorMouseMoveMonitor = GlobalEditorMouseMoveMonitor;
});
/*---------------------------------------------------------------------------------------------
* 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/browser/services/abstractCodeEditorService*/], __M([0/*require*/,1/*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.AbstractCodeEditorService = void 0;
class AbstractCodeEditorService extends lifecycle_1.Disposable {
constructor() {
super();
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._onDiffEditorAdd = this._register(new event_1.Emitter());
this._onDiffEditorRemove = this._register(new event_1.Emitter());
this._onDecorationTypeRegistered = this._register(new event_1.Emitter());
this._modelProperties = new Map();
this._codeEditors = Object.create(null);
this._diffEditors = Object.create(null);
}
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]);
}
addDiffEditor(editor) {
this._diffEditors[editor.getId()] = editor;
this._onDiffEditorAdd.fire(editor);
}
removeDiffEditor(editor) {
if (delete this._diffEditors[editor.getId()]) {
this._onDiffEditorRemove.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;
}
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;
}
}
exports.AbstractCodeEditorService = AbstractCodeEditorService;
});
/*---------------------------------------------------------------------------------------------
* 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/viewParts/minimap/minimapCharSheet*/], __M([0/*require*/,1/*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 /* START_CH_CODE */; i <= 126 /* END_CH_CODE */; i++) {
v.push(i);
}
v.push(65533 /* UNKNOWN_CODE */);
return v;
})();
const getCharIndex = (chCode, fontScale) => {
chCode -= 32 /* START_CH_CODE */;
if (chCode < 0 || chCode > 96 /* CHAR_COUNT */) {
if (fontScale <= 2) {
// for smaller scales, we can get away with using any ASCII character...
return (chCode + 96 /* CHAR_COUNT */) % 96 /* CHAR_COUNT */;
}
return 96 /* 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[372/*vs/editor/browser/viewParts/minimap/minimapCharRenderer*/], __M([0/*require*/,1/*exports*/,215/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/,129/*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) {
let 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, backgroundColor, fontScale, useLighterFont, force1pxHeight) {
const charWidth = 1 /* BASE_CHAR_WIDTH */ * this.scale;
const charHeight = 2 /* 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 /* 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 dest = target.data;
let sourceOffset = charIndex * charWidth * charHeight;
let row = dy * destWidth + dx * 4 /* 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;
dest[column++] = backgroundR + deltaR * c;
dest[column++] = backgroundG + deltaG * c;
dest[column++] = backgroundB + deltaB * c;
column++;
}
row += destWidth;
}
}
blockRenderChar(target, dx, dy, color, backgroundColor, useLighterFont, force1pxHeight) {
const charWidth = 1 /* BASE_CHAR_WIDTH */ * this.scale;
const charHeight = 2 /* 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 /* RGBA_CHANNELS_CNT */;
const c = 0.5;
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 dest = target.data;
let row = dy * destWidth + dx * 4 /* 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;
column++;
}
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[373/*vs/editor/browser/viewParts/minimap/minimapPreBaked*/], __M([0/*require*/,1/*exports*/,80/*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.once)(() => decodeData('0000511D6300CF609C709645A78432005642574171487021003C451900274D35D762755E8B629C5BA856AF57BA649530C167D1512A272A3F6038604460398526BCA2A968DB6F8957C768BE5FBE2FB467CF5D8D5B795DC7625B5DFF50DE64C466DB2FC47CD860A65E9A2EB96CB54CE06DA763AB2EA26860524D3763536601005116008177A8705E53AB738E6A982F88BAA35B5F5B626D9C636B449B737E5B7B678598869A662F6B5B8542706C704C80736A607578685B70594A49715A4522E792')),
2: (0, functional_1.once)(() => 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[374/*vs/editor/browser/viewParts/minimap/minimapCharRendererFactory*/], __M([0/*require*/,1/*exports*/,372/*vs/editor/browser/viewParts/minimap/minimapCharRenderer*/,215/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/,373/*vs/editor/browser/viewParts/minimap/minimapPreBaked*/,129/*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 /* SAMPLED_CHAR_HEIGHT */}px`;
canvas.height = 16 /* SAMPLED_CHAR_HEIGHT */;
canvas.width = 96 /* CHAR_COUNT */ * 10 /* SAMPLED_CHAR_WIDTH */;
canvas.style.width = 96 /* CHAR_COUNT */ * 10 /* SAMPLED_CHAR_WIDTH */ + 'px';
ctx.fillStyle = '#ffffff';
ctx.font = `bold ${16 /* 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 /* SAMPLED_CHAR_HEIGHT */ / 2);
x += 10 /* SAMPLED_CHAR_WIDTH */;
}
return ctx.getImageData(0, 0, 96 /* CHAR_COUNT */ * 10 /* SAMPLED_CHAR_WIDTH */, 16 /* SAMPLED_CHAR_HEIGHT */);
}
/**
* Creates a character renderer from the canvas sample data.
*/
static createFromSampleData(source, scale) {
const expectedLength = 16 /* SAMPLED_CHAR_HEIGHT */ * 10 /* SAMPLED_CHAR_WIDTH */ * 4 /* RGBA_CHANNELS_CNT */ * 96 /* CHAR_COUNT */;
if (source.length !== expectedLength) {
throw new Error('Unexpected source in MinimapCharRenderer');
}
let charData = MinimapCharRendererFactory._downsample(source, scale);
return new minimapCharRenderer_1.MinimapCharRenderer(charData, scale);
}
static _downsampleChar(source, sourceOffset, dest, destOffset, scale) {
const width = 1 /* BASE_CHAR_WIDTH */ * scale;
const height = 2 /* 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 /* SAMPLED_CHAR_HEIGHT */;
const sourceY2 = ((y + 1) / height) * 16 /* SAMPLED_CHAR_HEIGHT */;
for (let x = 0; x < width; x++) {
const sourceX1 = (x / width) * 10 /* SAMPLED_CHAR_WIDTH */;
const sourceX2 = ((x + 1) / width) * 10 /* 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 /* 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 /* 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 /* BASE_CHAR_HEIGHT */ * scale * 1 /* BASE_CHAR_WIDTH */ * scale;
const resultLen = pixelsPerCharacter * 96 /* CHAR_COUNT */;
const result = new Uint8ClampedArray(resultLen);
let resultOffset = 0;
let sourceOffset = 0;
let brightest = 0;
for (let charIndex = 0; charIndex < 96 /* CHAR_COUNT */; charIndex++) {
brightest = Math.max(brightest, this._downsampleChar(data, sourceOffset, result, resultOffset, scale));
resultOffset += pixelsPerCharacter;
sourceOffset += 10 /* SAMPLED_CHAR_WIDTH */ * 4 /* 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[133/*vs/editor/common/config/editorZoom*/], __M([0/*require*/,1/*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[168/*vs/editor/common/config/fontInfo*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,133/*vs/editor/common/config/editorZoom*/]), function (require, exports, platform, 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
*/
constructor(opts) {
this._bareFontInfoBrand = undefined;
this.zoomLevel = opts.zoomLevel;
this.pixelRatio = opts.pixelRatio;
this.fontFamily = String(opts.fontFamily);
this.fontWeight = String(opts.fontWeight);
this.fontSize = opts.fontSize;
this.fontFeatureSettings = opts.fontFeatureSettings;
this.lineHeight = opts.lineHeight | 0;
this.letterSpacing = opts.letterSpacing;
}
/**
* @internal
*/
static createFromValidatedSettings(options, zoomLevel, pixelRatio, ignoreEditorZoom) {
const fontFamily = options.get(40 /* fontFamily */);
const fontWeight = options.get(44 /* fontWeight */);
const fontSize = options.get(43 /* fontSize */);
const fontFeatureSettings = options.get(42 /* fontLigatures */);
const lineHeight = options.get(57 /* lineHeight */);
const letterSpacing = options.get(54 /* letterSpacing */);
return BareFontInfo._create(fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, zoomLevel, pixelRatio, ignoreEditorZoom);
}
/**
* @internal
*/
static _create(fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, zoomLevel, 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 probably in ems. Accept them gracefully.
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;
return new BareFontInfo({
zoomLevel: zoomLevel,
pixelRatio: pixelRatio,
fontFamily: fontFamily,
fontWeight: fontWeight,
fontSize: fontSize,
fontFeatureSettings: fontFeatureSettings,
lineHeight: lineHeight,
letterSpacing: letterSpacing
});
}
/**
* @internal
*/
getId() {
return this.zoomLevel + '-' + this.pixelRatio + '-' + this.fontFamily + '-' + this.fontWeight + '-' + this.fontSize + '-' + this.fontFeatureSettings + '-' + this.lineHeight + '-' + this.letterSpacing;
}
/**
* @internal
*/
getMassagedFontFamily() {
if (/[,"']/.test(this.fontFamily)) {
// Looks like the font family might be already escaped
return this.fontFamily;
}
if (/[+ ]/.test(this.fontFamily)) {
// Wrap a font family using + or <space> with quotes
return `"${this.fontFamily}"`;
}
return this.fontFamily;
}
}
exports.BareFontInfo = BareFontInfo;
// change this whenever `FontInfo` members are changed
exports.SERIALIZED_FONT_INFO_VERSION = 1;
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.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[94/*vs/editor/common/core/characterClassifier*/], __M([0/*require*/,1/*exports*/,129/*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) {
let defaultValue = (0, uint_1.toUint8)(_defaultValue);
this._defaultValue = defaultValue;
this._asciiMap = CharacterClassifier._createAsciiMap(defaultValue);
this._map = new Map();
}
static _createAsciiMap(defaultValue) {
let asciiMap = new Uint8Array(256);
for (let i = 0; i < 256; i++) {
asciiMap[i] = defaultValue;
}
return asciiMap;
}
set(charCode, _value) {
let 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);
}
}
}
exports.CharacterClassifier = CharacterClassifier;
class CharacterSet {
constructor() {
this._actual = new CharacterClassifier(0 /* False */);
}
add(charCode) {
this._actual.set(charCode, 1 /* True */);
}
has(charCode) {
return (this._actual.get(charCode) === 1 /* True */);
}
}
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[109/*vs/editor/common/controller/wordCharacterClassifier*/], __M([0/*require*/,1/*exports*/,94/*vs/editor/common/core/characterClassifier*/]), function (require, exports, characterClassifier_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMapForWordSeparators = exports.WordCharacterClassifier = void 0;
class WordCharacterClassifier extends characterClassifier_1.CharacterClassifier {
constructor(wordSeparators) {
super(0 /* Regular */);
for (let i = 0, len = wordSeparators.length; i < len; i++) {
this.set(wordSeparators.charCodeAt(i), 2 /* WordSeparator */);
}
this.set(32 /* Space */, 1 /* Whitespace */);
this.set(9 /* Tab */, 1 /* Whitespace */);
}
}
exports.WordCharacterClassifier = WordCharacterClassifier;
function once(computeFn) {
let cache = {}; // TODO@Alex unbounded cache
return (input) => {
if (!cache.hasOwnProperty(input)) {
cache[input] = computeFn(input);
}
return cache[input];
};
}
exports.getMapForWordSeparators = once((input) => new WordCharacterClassifier(input));
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[13/*vs/editor/common/core/position*/], __M([0/*require*/,1/*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) {
let aLineNumber = a.lineNumber | 0;
let bLineNumber = b.lineNumber | 0;
if (aLineNumber === bLineNumber) {
let aColumn = a.column | 0;
let 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'));
}
}
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[3/*vs/editor/common/core/range*/], __M([0/*require*/,1/*exports*/,13/*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 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 strinctly 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;
let otherStartLineNumber = b.startLineNumber;
let otherStartColumn = b.startColumn;
let otherEndLineNumber = b.endLineNumber;
let 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) {
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);
}
// ---
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;
}
}
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[216/*vs/editor/browser/controller/textAreaState*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings, position_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PagedScreenReaderStrategy = exports.TextAreaState = exports._debugComposition = void 0;
exports._debugComposition = false;
class TextAreaState {
constructor(value, selectionStart, selectionEnd, selectionStartPosition, selectionEndPosition) {
this.value = value;
this.selectionStart = selectionStart;
this.selectionEnd = selectionEnd;
this.selectionStartPosition = selectionStartPosition;
this.selectionEndPosition = selectionEndPosition;
}
toString() {
return '[ <' + this.value + '>, selectionStart: ' + this.selectionStart + ', selectionEnd: ' + this.selectionEnd + ']';
}
static readFromTextArea(textArea) {
return new TextAreaState(textArea.getValue(), textArea.getSelectionStart(), textArea.getSelectionEnd(), null, null);
}
collapseSelection() {
return new TextAreaState(this.value, this.value.length, this.value.length, null, null);
}
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.selectionStartPosition, str, -1);
}
if (offset >= this.selectionEnd) {
const str = this.value.substring(this.selectionEnd, offset);
return this._finishDeduceEditorPosition(this.selectionEndPosition, str, 1);
}
const str1 = this.value.substring(this.selectionStart, offset);
if (str1.indexOf(String.fromCharCode(8230)) === -1) {
return this._finishDeduceEditorPosition(this.selectionStartPosition, str1, 1);
}
const str2 = this.value.substring(offset, this.selectionEnd);
return this._finishDeduceEditorPosition(this.selectionEndPosition, 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 selectedText(text) {
return new TextAreaState(text, 0, text.length, null, null);
}
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());
}
let previousValue = previousState.value;
let previousSelectionStart = previousState.selectionStart;
let previousSelectionEnd = previousState.selectionEnd;
let currentValue = currentState.value;
let currentSelectionStart = currentState.selectionStart;
let currentSelectionEnd = currentState.selectionEnd;
// Strip the previous suffix from the value (without interfering with the current selection)
const previousSuffix = previousValue.substring(previousSelectionEnd);
const currentSuffix = currentValue.substring(currentSelectionEnd);
const suffixLength = strings.commonSuffixLength(previousSuffix, currentSuffix);
currentValue = currentValue.substring(0, currentValue.length - suffixLength);
previousValue = previousValue.substring(0, previousValue.length - suffixLength);
const previousPrefix = previousValue.substring(0, previousSelectionStart);
const currentPrefix = currentValue.substring(0, currentSelectionStart);
const prefixLength = strings.commonPrefixLength(previousPrefix, currentPrefix);
currentValue = currentValue.substring(prefixLength);
previousValue = previousValue.substring(prefixLength);
currentSelectionStart -= prefixLength;
previousSelectionStart -= prefixLength;
currentSelectionEnd -= prefixLength;
previousSelectionEnd -= 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 (couldBeEmojiInput && currentSelectionStart === currentSelectionEnd && previousValue.length > 0) {
// on OSX, emojis from the emoji picker are inserted at random locations
// the only hints we can use is that the selection is immediately after the inserted emoji
// and that none of the old text has been deleted
let potentialEmojiInput = null;
if (currentSelectionStart === currentValue.length) {
// emoji potentially inserted "somewhere" after the previous selection => it should appear at the end of `currentValue`
if (currentValue.startsWith(previousValue)) {
// only if all of the old text is accounted for
potentialEmojiInput = currentValue.substring(previousValue.length);
}
}
else {
// emoji potentially inserted "somewhere" before the previous selection => it should appear at the start of `currentValue`
if (currentValue.endsWith(previousValue)) {
// only if all of the old text is accounted for
potentialEmojiInput = currentValue.substring(0, currentValue.length - previousValue.length);
}
}
if (potentialEmojiInput !== null && potentialEmojiInput.length > 0) {
// now we check that this is indeed an emoji
// emojis can grow quite long, so a length check is of no help
// e.g. 1F3F4 E0067 E0062 E0065 E006E E0067 E007F ; fully-qualified # 🏴󠁧󠁢󠁥󠁮󠁧󠁿 England
// Oftentimes, emojis use Variation Selector-16 (U+FE0F), so that is a good hint
// http://emojipedia.org/variation-selector-16/
// > An invisible codepoint which specifies that the preceding character
// > should be displayed with emoji presentation. Only required if the
// > preceding character defaults to text presentation.
if (/\uFE0F/.test(potentialEmojiInput) || strings.containsEmoji(potentialEmojiInput)) {
return {
text: potentialEmojiInput,
replacePrevCharCnt: 0,
replaceNextCharCnt: 0,
positionDelta: 0
};
}
}
}
if (currentSelectionStart === currentSelectionEnd) {
// composition accept case (noticed in FF + Japanese)
// [blahblah] => blahblah|
if (previousValue === currentValue
&& previousSelectionStart === 0
&& previousSelectionEnd === previousValue.length
&& currentSelectionStart === currentValue.length
&& currentValue.indexOf('\n') === -1) {
if (strings.containsFullWidthCharacter(currentValue)) {
return {
text: '',
replacePrevCharCnt: 0,
replaceNextCharCnt: 0,
positionDelta: 0
};
}
}
// no current selection
const replacePreviousCharacters = (previousPrefix.length - prefixLength);
if (exports._debugComposition) {
console.log('REMOVE PREVIOUS: ' + (previousPrefix.length - prefixLength) + ' 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;
TextAreaState.EMPTY = new TextAreaState('', 0, 0, null, null);
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(previousState, model, selection, linesPerPage, trimLongText) {
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);
const pretextRange = selectionStartPageRange.intersectRanges(new range_1.Range(1, 1, selection.startLineNumber, selection.startColumn));
let pretext = model.getValueInRange(pretextRange, 1 /* LF */);
const lastLine = model.getLineCount();
const lastLineMaxColumn = model.getLineMaxColumn(lastLine);
const posttextRange = selectionEndPageRange.intersectRanges(new range_1.Range(selection.endLineNumber, selection.endColumn, lastLine, lastLineMaxColumn));
let posttext = model.getValueInRange(posttextRange, 1 /* LF */);
let text;
if (selectionStartPage === selectionEndPage || selectionStartPage + 1 === selectionEndPage) {
// take full selection
text = model.getValueInRange(selection, 1 /* LF */);
}
else {
const selectionRange1 = selectionStartPageRange.intersectRanges(selection);
const selectionRange2 = selectionEndPageRange.intersectRanges(selection);
text = (model.getValueInRange(selectionRange1, 1 /* LF */)
+ String.fromCharCode(8230)
+ model.getValueInRange(selectionRange2, 1 /* LF */));
}
// Chromium handles very poorly text even of a few thousand chars
// Cut text to avoid stalling the entire UI
if (trimLongText) {
const LIMIT_CHARS = 500;
if (pretext.length > LIMIT_CHARS) {
pretext = pretext.substring(pretext.length - LIMIT_CHARS, pretext.length);
}
if (posttext.length > LIMIT_CHARS) {
posttext = posttext.substring(0, LIMIT_CHARS);
}
if (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, new position_1.Position(selection.startLineNumber, selection.startColumn), new position_1.Position(selection.endLineNumber, selection.endColumn));
}
}
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[217/*vs/editor/browser/widget/diffNavigator*/], __M([0/*require*/,1/*exports*/,198/*vs/base/common/assert*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,42/*vs/base/common/objects*/,3/*vs/editor/common/core/range*/]), function (require, exports, assert, event_1, lifecycle_1, objects, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiffNavigator = void 0;
const defaultOptions = {
followsCaret: true,
ignoreCharChanges: true,
alwaysRevealFirst: true
};
/**
* Create a new diff navigator for the provided diff editor.
*/
class DiffNavigator extends lifecycle_1.Disposable {
constructor(editor, options = {}) {
super();
this._onDidUpdate = this._register(new event_1.Emitter());
this._editor = editor;
this._options = objects.mixin(options, defaultOptions, false);
this.disposed = false;
this.nextIdx = -1;
this.ranges = [];
this.ignoreSelectionChange = false;
this.revealFirst = Boolean(this._options.alwaysRevealFirst);
// hook up to diff editor for diff, disposal, and caret move
this._register(this._editor.onDidDispose(() => this.dispose()));
this._register(this._editor.onDidUpdateDiff(() => this._onDiffUpdated()));
if (this._options.followsCaret) {
this._register(this._editor.getModifiedEditor().onDidChangeCursorPosition((e) => {
if (this.ignoreSelectionChange) {
return;
}
this.nextIdx = -1;
}));
}
if (this._options.alwaysRevealFirst) {
this._register(this._editor.getModifiedEditor().onDidChangeModel((e) => {
this.revealFirst = true;
}));
}
// init things
this._init();
}
_init() {
let changes = this._editor.getLineChanges();
if (!changes) {
return;
}
}
_onDiffUpdated() {
this._init();
this._compute(this._editor.getLineChanges());
if (this.revealFirst) {
// Only reveal first on first non-null changes
if (this._editor.getLineChanges() !== null) {
this.revealFirst = false;
this.nextIdx = -1;
this.next(1 /* Immediate */);
}
}
}
_compute(lineChanges) {
// new ranges
this.ranges = [];
if (lineChanges) {
// create ranges from changes
lineChanges.forEach((lineChange) => {
if (!this._options.ignoreCharChanges && lineChange.charChanges) {
lineChange.charChanges.forEach((charChange) => {
this.ranges.push({
rhs: true,
range: new range_1.Range(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn)
});
});
}
else {
this.ranges.push({
rhs: true,
range: new range_1.Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedStartLineNumber, 1)
});
}
});
}
// sort
this.ranges.sort((left, right) => {
if (left.range.getStartPosition().isBeforeOrEqual(right.range.getStartPosition())) {
return -1;
}
else if (right.range.getStartPosition().isBeforeOrEqual(left.range.getStartPosition())) {
return 1;
}
else {
return 0;
}
});
this._onDidUpdate.fire(this);
}
_initIdx(fwd) {
let found = false;
let position = this._editor.getPosition();
if (!position) {
this.nextIdx = 0;
return;
}
for (let i = 0, len = this.ranges.length; i < len && !found; i++) {
let range = this.ranges[i].range;
if (position.isBeforeOrEqual(range.getStartPosition())) {
this.nextIdx = i + (fwd ? 0 : -1);
found = true;
}
}
if (!found) {
// after the last change
this.nextIdx = fwd ? 0 : this.ranges.length - 1;
}
if (this.nextIdx < 0) {
this.nextIdx = this.ranges.length - 1;
}
}
_move(fwd, scrollType) {
assert.ok(!this.disposed, 'Illegal State - diff navigator has been disposed');
if (!this.canNavigate()) {
return;
}
if (this.nextIdx === -1) {
this._initIdx(fwd);
}
else if (fwd) {
this.nextIdx += 1;
if (this.nextIdx >= this.ranges.length) {
this.nextIdx = 0;
}
}
else {
this.nextIdx -= 1;
if (this.nextIdx < 0) {
this.nextIdx = this.ranges.length - 1;
}
}
let info = this.ranges[this.nextIdx];
this.ignoreSelectionChange = true;
try {
let pos = info.range.getStartPosition();
this._editor.setPosition(pos);
this._editor.revealPositionInCenter(pos, scrollType);
}
finally {
this.ignoreSelectionChange = false;
}
}
canNavigate() {
return this.ranges && this.ranges.length > 0;
}
next(scrollType = 0 /* Smooth */) {
this._move(true, scrollType);
}
previous(scrollType = 0 /* Smooth */) {
this._move(false, scrollType);
}
dispose() {
super.dispose();
this.ranges = [];
this.disposed = true;
}
}
exports.DiffNavigator = DiffNavigator;
});
/*---------------------------------------------------------------------------------------------
* 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/common/core/editOperation*/], __M([0/*require*/,1/*exports*/,3/*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[375/*vs/editor/common/commands/trimTrailingWhitespaceCommand*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,56/*vs/editor/common/core/editOperation*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings, editOperation_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.trimTrailingWhitespace = exports.TrimTrailingWhitespaceCommand = void 0;
class TrimTrailingWhitespaceCommand {
constructor(selection, cursors) {
this._selection = selection;
this._cursors = cursors;
this._selectionId = null;
}
getEditOperations(model, builder) {
let ops = trimTrailingWhitespace(model, this._cursors);
for (let i = 0, len = ops.length; i < len; i++) {
let 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) {
// 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);
}
}
let r = [];
let rLen = 0;
let cursorIndex = 0;
let cursorLen = cursors.length;
for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) {
let lineContent = model.getLineContent(lineNumber);
let 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;
}
let 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;
}
fromColumn = Math.max(minEditColumn, fromColumn);
r[rLen++] = editOperation_1.EditOperation.delete(new range_1.Range(lineNumber, fromColumn, lineNumber, maxLineColumn));
}
return r;
}
exports.trimTrailingWhitespace = trimTrailingWhitespace;
});
/*---------------------------------------------------------------------------------------------
* 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/editor/common/core/rgba*/], __M([0/*require*/,1/*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 {
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;
RGBA8.Empty = new RGBA8(0, 0, 0, 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[21/*vs/editor/common/core/selection*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,3/*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 /* LTR */;
}
return 1 /* RTL */;
}
/**
* Create a new selection with a different `positionLineNumber` and `positionColumn`.
*/
setEndPosition(endLineNumber, endColumn) {
if (this.getDirection() === 0 /* 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);
}
/**
* Create a new selection with a different `selectionStartLineNumber` and `selectionStartColumn`.
*/
setStartPosition(startLineNumber, startColumn) {
if (this.getDirection() === 0 /* 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);
}
/**
* 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 /* 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[169/*vs/editor/browser/controller/textAreaInput*/], __M([0/*require*/,1/*exports*/,39/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,15/*vs/base/common/async*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,106/*vs/base/common/mime*/,17/*vs/base/common/platform*/,8/*vs/base/common/strings*/,216/*vs/editor/browser/controller/textAreaState*/,13/*vs/editor/common/core/position*/,21/*vs/editor/common/core/selection*/]), function (require, exports, browser, dom, async_1, event_1, lifecycle_1, mime_1, platform, strings, textAreaState_1, position_1, selection_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TextAreaInput = exports.InMemoryClipboardMetadataManager = exports.CopyOptions = exports.TextAreaSyntethicEvents = void 0;
var TextAreaSyntethicEvents;
(function (TextAreaSyntethicEvents) {
TextAreaSyntethicEvents.Tap = '-monaco-textarea-synthetic-tap';
})(TextAreaSyntethicEvents = exports.TextAreaSyntethicEvents || (exports.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 {
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;
InMemoryClipboardMetadataManager.INSTANCE = new InMemoryClipboardMetadataManager();
/**
* 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).
*/
class TextAreaInput extends lifecycle_1.Disposable {
constructor(host, textArea) {
super();
this.textArea = textArea;
this._onFocus = this._register(new event_1.Emitter());
this.onFocus = this._onFocus.event;
this._onBlur = this._register(new event_1.Emitter());
this.onBlur = this._onBlur.event;
this._onKeyDown = this._register(new event_1.Emitter());
this.onKeyDown = this._onKeyDown.event;
this._onKeyUp = this._register(new event_1.Emitter());
this.onKeyUp = this._onKeyUp.event;
this._onCut = this._register(new event_1.Emitter());
this.onCut = this._onCut.event;
this._onPaste = this._register(new event_1.Emitter());
this.onPaste = this._onPaste.event;
this._onType = this._register(new event_1.Emitter());
this.onType = this._onType.event;
this._onCompositionStart = this._register(new event_1.Emitter());
this.onCompositionStart = this._onCompositionStart.event;
this._onCompositionUpdate = this._register(new event_1.Emitter());
this.onCompositionUpdate = this._onCompositionUpdate.event;
this._onCompositionEnd = this._register(new event_1.Emitter());
this.onCompositionEnd = this._onCompositionEnd.event;
this._onSelectionChangeRequest = this._register(new event_1.Emitter());
this.onSelectionChangeRequest = this._onSelectionChangeRequest.event;
this._host = host;
this._textArea = this._register(new TextAreaWrapper(textArea));
this._asyncTriggerCut = this._register(new async_1.RunOnceScheduler(() => this._onCut.fire(), 0));
this._asyncFocusGainWriteScreenReaderContent = this._register(new async_1.RunOnceScheduler(() => this.writeScreenReaderContent('asyncFocusGain'), 0));
this._textAreaState = textAreaState_1.TextAreaState.EMPTY;
this._selectionChangeListener = null;
this.writeScreenReaderContent('ctor');
this._hasFocus = false;
this._isDoingComposition = false;
this._nextCommand = 0 /* Type */;
let lastKeyDown = null;
this._register(dom.addStandardDisposableListener(textArea.domNode, 'keydown', (e) => {
if (e.keyCode === 109 /* KEY_IN_COMPOSITION */
|| (this._isDoingComposition && e.keyCode === 1 /* Backspace */)) {
// Stop propagation for keyDown events if the IME is processing key input
e.stopPropagation();
}
if (e.equals(9 /* 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(dom.addStandardDisposableListener(textArea.domNode, 'keyup', (e) => {
this._onKeyUp.fire(e);
}));
this._register(dom.addDisposableListener(textArea.domNode, 'compositionstart', (e) => {
if (textAreaState_1._debugComposition) {
console.log(`[compositionstart]`, e);
}
if (this._isDoingComposition) {
return;
}
this._isDoingComposition = true;
if (platform.isMacintosh
&& this._textAreaState.selectionStart === this._textAreaState.selectionEnd
&& this._textAreaState.selectionStart > 0
&& this._textAreaState.value.substr(this._textAreaState.selectionStart - 1, 1) === e.data) {
const isArrowKey = (lastKeyDown && lastKeyDown.equals(109 /* KEY_IN_COMPOSITION */)
&& (lastKeyDown.code === 'ArrowRight' || lastKeyDown.code === 'ArrowLeft'));
if (isArrowKey || browser.isFirefox) {
// Handling long press case on Chromium/Safari macOS + arrow key => pretend the character was selected
// or long press case on Firefox on macOS
if (textAreaState_1._debugComposition) {
console.log(`[compositionstart] Handling long press case on macOS + arrow key or Firefox`, e);
}
this._textAreaState = new textAreaState_1.TextAreaState(this._textAreaState.value, this._textAreaState.selectionStart - 1, this._textAreaState.selectionEnd, this._textAreaState.selectionStartPosition ? new position_1.Position(this._textAreaState.selectionStartPosition.lineNumber, this._textAreaState.selectionStartPosition.column - 1) : null, this._textAreaState.selectionEndPosition);
this._onCompositionStart.fire({ revealDeltaColumns: -1 });
return;
}
}
if (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({ revealDeltaColumns: -this._textAreaState.selectionStart });
return;
}
this._setAndWriteTextAreaState('compositionstart', textAreaState_1.TextAreaState.EMPTY);
this._onCompositionStart.fire({ revealDeltaColumns: 0 });
}));
/**
* Deduce the typed input from a text area's value and the last observed state.
*/
const deduceInputFromTextAreaValue = (couldBeEmojiInput) => {
const oldState = this._textAreaState;
const newState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea);
return [newState, textAreaState_1.TextAreaState.deduceInput(oldState, newState, couldBeEmojiInput)];
};
const deduceAndroidCompositionInput = () => {
const oldState = this._textAreaState;
const newState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea);
return [newState, textAreaState_1.TextAreaState.deduceAndroidCompositionInput(oldState, newState)];
};
/**
* Deduce the composition input from a string.
*/
const deduceComposition = (text) => {
const oldState = this._textAreaState;
const newState = textAreaState_1.TextAreaState.selectedText(text);
const typeInput = {
text: newState.value,
replacePrevCharCnt: oldState.selectionEnd - oldState.selectionStart,
replaceNextCharCnt: 0,
positionDelta: 0
};
return [newState, typeInput];
};
this._register(dom.addDisposableListener(textArea.domNode, 'compositionupdate', (e) => {
if (textAreaState_1._debugComposition) {
console.log(`[compositionupdate]`, e);
}
if (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, typeInput] = deduceAndroidCompositionInput();
this._textAreaState = newState;
this._onType.fire(typeInput);
this._onCompositionUpdate.fire(e);
return;
}
const [newState, typeInput] = deduceComposition(e.data || '');
this._textAreaState = newState;
this._onType.fire(typeInput);
this._onCompositionUpdate.fire(e);
}));
this._register(dom.addDisposableListener(textArea.domNode, 'compositionend', (e) => {
if (textAreaState_1._debugComposition) {
console.log(`[compositionend]`, e);
}
// https://github.com/microsoft/monaco-editor/issues/1663
// On iOS 13.2, Chinese system IME randomly trigger an additional compositionend event with empty data
if (!this._isDoingComposition) {
return;
}
this._isDoingComposition = false;
if (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, typeInput] = deduceAndroidCompositionInput();
this._textAreaState = newState;
this._onType.fire(typeInput);
this._onCompositionEnd.fire();
return;
}
const [newState, typeInput] = deduceComposition(e.data || '');
this._textAreaState = newState;
this._onType.fire(typeInput);
// isChrome: the textarea is not updated correctly when composition ends
// isFirefox: the textarea is not updated correctly after inserting emojis
// => we cannot assume the text at the end consists only of the composited text
if (browser.isChrome || browser.isFirefox) {
this._textAreaState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea);
}
this._onCompositionEnd.fire();
}));
this._register(dom.addDisposableListener(textArea.domNode, 'input', () => {
// 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._isDoingComposition) {
return;
}
const [newState, typeInput] = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/ platform.isMacintosh);
if (typeInput.replacePrevCharCnt === 0 && typeInput.text.length === 1 && strings.isHighSurrogate(typeInput.text.charCodeAt(0))) {
// Ignore invalid input but keep it around for next time
return;
}
this._textAreaState = newState;
if (this._nextCommand === 0 /* Type */) {
if (typeInput.text !== '' || typeInput.replacePrevCharCnt !== 0) {
this._onType.fire(typeInput);
}
}
else {
if (typeInput.text !== '' || typeInput.replacePrevCharCnt !== 0) {
this._firePaste(typeInput.text, null);
}
this._nextCommand = 0 /* Type */;
}
}));
// --- Clipboard operations
this._register(dom.addDisposableListener(textArea.domNode, 'cut', (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(dom.addDisposableListener(textArea.domNode, 'copy', (e) => {
this._ensureClipboardGetsEditorSelection(e);
}));
this._register(dom.addDisposableListener(textArea.domNode, 'paste', (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');
if (ClipboardEventUtils.canUseTextData(e)) {
const [pastePlainText, metadata] = ClipboardEventUtils.getTextData(e);
if (pastePlainText !== '') {
this._firePaste(pastePlainText, metadata);
}
}
else {
if (this._textArea.getSelectionStart() !== this._textArea.getSelectionEnd()) {
// Clean up the textarea, to get a clean paste
this._setAndWriteTextAreaState('paste', textAreaState_1.TextAreaState.EMPTY);
}
this._nextCommand = 1 /* Paste */;
}
}));
this._register(dom.addDisposableListener(textArea.domNode, 'focus', () => {
const hadFocus = this._hasFocus;
this._setHasFocus(true);
if (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
this._asyncFocusGainWriteScreenReaderContent.schedule();
}
}));
this._register(dom.addDisposableListener(textArea.domNode, 'blur', () => {
if (this._isDoingComposition) {
// 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._isDoingComposition = false;
// Clear the textarea to avoid an unwanted cursor type
this.writeScreenReaderContent('blurWithoutCompositionEnd');
// Fire artificial composition end
this._onCompositionEnd.fire();
}
this._setHasFocus(false);
}));
this._register(dom.addDisposableListener(textArea.domNode, TextAreaSyntethicEvents.Tap, () => {
if (browser.isAndroid && this._isDoingComposition) {
// 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._isDoingComposition = false;
// Clear the textarea to avoid an unwanted cursor type
this.writeScreenReaderContent('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(document, 'selectionchange', (e) => {
if (!this._hasFocus) {
return;
}
if (this._isDoingComposition) {
return;
}
if (!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.selectionStartPosition || !this._textAreaState.selectionEndPosition) {
// 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() {
const shadowRoot = dom.getShadowRoot(this.textArea.domNode);
if (shadowRoot) {
this._setHasFocus(shadowRoot.activeElement === this.textArea.domNode);
}
else if (dom.isInDOM(this.textArea.domNode)) {
this._setHasFocus(document.activeElement === this.textArea.domNode);
}
else {
this._setHasFocus(false);
}
}
_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.writeScreenReaderContent('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;
}
writeScreenReaderContent(reason) {
if (this._isDoingComposition) {
// Do not write to the text area when doing composition
return;
}
this._setAndWriteTextAreaState(reason, this._host.getScreenReaderContent(this._textAreaState));
}
_ensureClipboardGetsEditorSelection(e) {
const dataToCopy = this._host.getDataToCopy(ClipboardEventUtils.canUseTextData(e));
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
(browser.isFirefox ? dataToCopy.text.replace(/\r\n/g, '\n') : dataToCopy.text), storedMetadata);
if (!ClipboardEventUtils.canUseTextData(e)) {
// Looks like an old browser. The strategy is to place the text
// we'd like to be copied to the clipboard in the textarea and select it.
this._setAndWriteTextAreaState('copy or cut', textAreaState_1.TextAreaState.selectedText(dataToCopy.text));
return;
}
ClipboardEventUtils.setTextData(e, dataToCopy.text, dataToCopy.html, storedMetadata);
}
_firePaste(text, metadata) {
if (!metadata) {
// try the in-memory store
metadata = InMemoryClipboardMetadataManager.INSTANCE.get(text);
}
this._onPaste.fire({
text: text,
metadata: metadata
});
}
}
exports.TextAreaInput = TextAreaInput;
class ClipboardEventUtils {
static canUseTextData(e) {
if (e.clipboardData) {
return true;
}
if (window.clipboardData) {
return true;
}
return false;
}
static getTextData(e) {
if (e.clipboardData) {
e.preventDefault();
const text = e.clipboardData.getData(mime_1.Mimes.text);
let metadata = null;
const rawmetadata = e.clipboardData.getData('vscode-editor-data');
if (typeof rawmetadata === 'string') {
try {
metadata = JSON.parse(rawmetadata);
if (metadata.version !== 1) {
metadata = null;
}
}
catch (err) {
// no problem!
}
}
return [text, metadata];
}
if (window.clipboardData) {
e.preventDefault();
const text = window.clipboardData.getData('Text');
return [text, null];
}
throw new Error('ClipboardEventUtils.getTextData: Cannot use text data!');
}
static setTextData(e, text, html, metadata) {
if (e.clipboardData) {
e.clipboardData.setData(mime_1.Mimes.text, text);
if (typeof html === 'string') {
e.clipboardData.setData('text/html', html);
}
e.clipboardData.setData('vscode-editor-data', JSON.stringify(metadata));
e.preventDefault();
return;
}
if (window.clipboardData) {
window.clipboardData.setData('Text', text);
e.preventDefault();
return;
}
throw new Error('ClipboardEventUtils.setTextData: Cannot use text data!');
}
}
class TextAreaWrapper extends lifecycle_1.Disposable {
constructor(_textArea) {
super();
this._actual = _textArea;
this._ignoreSelectionChangeTime = 0;
}
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.domNode.value;
}
setValue(reason, value) {
const textArea = this._actual.domNode;
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.domNode.selectionDirection === 'backward' ? this._actual.domNode.selectionEnd : this._actual.domNode.selectionStart;
}
getSelectionEnd() {
return this._actual.domNode.selectionDirection === 'backward' ? this._actual.domNode.selectionStart : this._actual.domNode.selectionEnd;
}
setSelectionRange(reason, selectionStart, selectionEnd) {
const textArea = this._actual.domNode;
let activeElement = null;
const shadowRoot = dom.getShadowRoot(textArea);
if (shadowRoot) {
activeElement = shadowRoot.activeElement;
}
else {
activeElement = document.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 && window.parent !== window) {
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 && window.parent !== window) {
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)
}
}
}
});
/*---------------------------------------------------------------------------------------------
* 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/commands/replaceCommand*/], __M([0/*require*/,1/*exports*/,21/*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) {
let inverseEditOperations = helper.getInverseEditOperations();
let srcRange = inverseEditOperations[0].range;
return new selection_1.Selection(srcRange.endLineNumber, srcRange.endColumn, srcRange.endLineNumber, srcRange.endColumn);
}
}
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 new selection_1.Selection(srcRange.startLineNumber, srcRange.startColumn, srcRange.endLineNumber, srcRange.endColumn);
}
}
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) {
let inverseEditOperations = helper.getInverseEditOperations();
let srcRange = inverseEditOperations[0].range;
return new selection_1.Selection(srcRange.startLineNumber, srcRange.startColumn, srcRange.startLineNumber, srcRange.startColumn);
}
}
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) {
let inverseEditOperations = helper.getInverseEditOperations();
let srcRange = inverseEditOperations[0].range;
return new selection_1.Selection(srcRange.endLineNumber + this._lineNumberDeltaOffset, srcRange.endColumn + this._columnDeltaOffset, srcRange.endLineNumber + this._lineNumberDeltaOffset, srcRange.endColumn + 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[376/*vs/editor/common/commands/surroundSelectionCommand*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/]), function (require, exports, range_1, selection_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
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) {
let inverseEditOperations = helper.getInverseEditOperations();
let firstOperationRange = inverseEditOperations[0].range;
let secondOperationRange = inverseEditOperations[1].range;
return new selection_1.Selection(firstOperationRange.endLineNumber, firstOperationRange.endColumn, secondOperationRange.endLineNumber, secondOperationRange.endColumn - this._charAfterSelection.length);
}
}
exports.SurroundSelectionCommand = SurroundSelectionCommand;
});
/*---------------------------------------------------------------------------------------------
* 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/core/stringBuilder*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,17/*vs/base/common/platform*/,103/*vs/base/common/buffer*/]), function (require, exports, strings, platform, buffer) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decodeUTF16LE = exports.createStringBuilder = exports.hasTextDecoder = exports.getPlatformTextDecoder = void 0;
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;
}
exports.getPlatformTextDecoder = getPlatformTextDecoder;
exports.hasTextDecoder = (typeof TextDecoder !== 'undefined');
if (exports.hasTextDecoder) {
exports.createStringBuilder = (capacity) => new StringBuilder(capacity);
exports.decodeUTF16LE = standardDecodeUTF16LE;
}
else {
exports.createStringBuilder = (capacity) => new CompatStringBuilder();
exports.decodeUTF16LE = compatDecodeUTF16LE;
}
function standardDecodeUTF16LE(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) {
let 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;
}
}
write1(charCode) {
const remainingSpace = this._capacity - this._bufferLength;
if (remainingSpace <= 1) {
if (remainingSpace === 0 || strings.isHighSurrogate(charCode)) {
this._flushBuffer();
}
}
this._buffer[this._bufferLength++] = charCode;
}
appendASCII(charCode) {
if (this._bufferLength === this._capacity) {
// buffer is full
this._flushBuffer();
}
this._buffer[this._bufferLength++] = charCode;
}
appendASCIIString(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);
}
}
}
class CompatStringBuilder {
constructor() {
this._pieces = [];
this._piecesLen = 0;
}
reset() {
this._pieces = [];
this._piecesLen = 0;
}
build() {
return this._pieces.join('');
}
write1(charCode) {
this._pieces[this._piecesLen++] = String.fromCharCode(charCode);
}
appendASCII(charCode) {
this._pieces[this._piecesLen++] = String.fromCharCode(charCode);
}
appendASCIIString(str) {
this._pieces[this._piecesLen++] = 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[170/*vs/editor/browser/view/viewLayer*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,83/*vs/editor/common/core/stringBuilder*/]), function (require, exports, fastDomNode_1, stringBuilder_1) {
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.VisibleLinesCollection = exports.RenderedLinesCollection = void 0;
class RenderedLinesCollection {
constructor(createLine) {
this._createLine = createLine;
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 Error('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, changeToLineNumber) {
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._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(host) {
this._host = host;
this.domNode = this._createDomNode();
this._linesCollection = new RenderedLinesCollection(() => this._host.createVisibleLine());
}
_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(129 /* 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.toLineNumber);
}
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();
if (lineDomNode) {
this.domNode.domNode.removeChild(lineDomNode);
}
}
}
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();
if (lineDomNode) {
this.domNode.domNode.removeChild(lineDomNode);
}
}
}
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._host, 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 {
constructor(domNode, host, viewportData) {
this.domNode = domNode;
this.host = host;
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.host.createVisibleLine();
}
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]);
}
}
_insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {
const newLines = [];
let newLinesLen = 0;
for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
newLines[newLinesLen++] = this.host.createVisibleLine();
}
ctx.lines = newLines.concat(ctx.lines);
}
_removeLinesBefore(ctx, removeCount) {
for (let i = 0; i < removeCount; i++) {
const lineDomNode = ctx.lines[i].getDomNode();
if (lineDomNode) {
this.domNode.removeChild(lineDomNode);
}
}
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.host.createVisibleLine();
}
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();
if (lineDomNode) {
this.domNode.removeChild(lineDomNode);
}
}
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);
}
}
}
_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, 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, sb);
if (!renderResult) {
// line does not need rendering
continue;
}
wasInvalid[i] = true;
hadInvalidLine = true;
}
if (hadInvalidLine) {
this._finishRenderingInvalidLines(ctx, sb.build(), wasInvalid);
}
}
}
}
ViewLayerRenderer._ttPolicy = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('editorViewLayer', { createHTML: value => value });
ViewLayerRenderer._sb = (0, stringBuilder_1.createStringBuilder)(100000);
});
/*---------------------------------------------------------------------------------------------
* 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/common/core/token*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TokenizationResult2 = exports.TokenizationResult = exports.Token = void 0;
class Token {
constructor(offset, type, language) {
this._tokenBrand = undefined;
this.offset = offset | 0; // @perf
this.type = type;
this.language = language;
}
toString() {
return '(' + this.offset + ', ' + this.type + ')';
}
}
exports.Token = Token;
class TokenizationResult {
constructor(tokens, endState) {
this._tokenizationResultBrand = undefined;
this.tokens = tokens;
this.endState = endState;
}
}
exports.TokenizationResult = TokenizationResult;
class TokenizationResult2 {
constructor(tokens, endState) {
this._tokenizationResult2Brand = undefined;
this.tokens = tokens;
this.endState = endState;
}
}
exports.TokenizationResult2 = TokenizationResult2;
});
/*---------------------------------------------------------------------------------------------
* 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/common/diff/diffComputer*/], __M([0/*require*/,1/*exports*/,128/*vs/base/common/diff/diff*/,8/*vs/base/common/strings*/]), function (require, exports, diff_1, strings) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiffComputer = void 0;
const MINIMUM_MATCHING_CHARACTER_LENGTH = 3;
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++;
}
}
return new CharSequence(charCodes, lineNumbers, columns);
}
}
class CharSequence {
constructor(charCodes, lineNumbers, columns) {
this._charCodes = charCodes;
this._lineNumbers = lineNumbers;
this._columns = columns;
}
getElements() {
return this._charCodes;
}
getStartLineNumber(i) {
return this._lineNumbers[i];
}
getStartColumn(i) {
return this._columns[i];
}
getEndLineNumber(i) {
return this._lineNumbers[i];
}
getEndColumn(i) {
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) {
let originalStartLineNumber;
let originalStartColumn;
let originalEndLineNumber;
let originalEndColumn;
let modifiedStartLineNumber;
let modifiedStartColumn;
let modifiedEndLineNumber;
let modifiedEndColumn;
if (diffChange.originalLength === 0) {
originalStartLineNumber = 0;
originalStartColumn = 0;
originalEndLineNumber = 0;
originalEndColumn = 0;
}
else {
originalStartLineNumber = originalCharSequence.getStartLineNumber(diffChange.originalStart);
originalStartColumn = originalCharSequence.getStartColumn(diffChange.originalStart);
originalEndLineNumber = originalCharSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1);
originalEndColumn = originalCharSequence.getEndColumn(diffChange.originalStart + diffChange.originalLength - 1);
}
if (diffChange.modifiedLength === 0) {
modifiedStartLineNumber = 0;
modifiedStartColumn = 0;
modifiedEndLineNumber = 0;
modifiedEndColumn = 0;
}
else {
modifiedStartLineNumber = modifiedCharSequence.getStartLineNumber(diffChange.modifiedStart);
modifiedStartColumn = modifiedCharSequence.getStartColumn(diffChange.modifiedStart);
modifiedEndLineNumber = modifiedCharSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1);
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);
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: [{
modifiedEndColumn: 0,
modifiedEndLineNumber: 0,
modifiedStartColumn: 0,
modifiedStartLineNumber: 0,
originalEndColumn: 0,
originalEndLineNumber: 0,
originalStartColumn: 0,
originalStartLineNumber: 0
}]
}]
};
}
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: [{
modifiedEndColumn: 0,
modifiedEndLineNumber: 0,
modifiedStartColumn: 0,
modifiedStartLineNumber: 0,
originalEndColumn: 0,
originalEndLineNumber: 0,
originalStartColumn: 0,
originalStartLineNumber: 0
}]
}]
};
}
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 + 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[219/*vs/editor/common/editorAction*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InternalEditorAction = void 0;
class InternalEditorAction {
constructor(id, label, alias, precondition, run, contextKeyService) {
this.id = id;
this.label = label;
this.alias = alias;
this._precondition = precondition;
this._run = run;
this._contextKeyService = contextKeyService;
}
isSupported() {
return this._contextKeyService.contextMatchesRules(this._precondition);
}
run() {
if (!this.isSupported()) {
return Promise.resolve(undefined);
}
return this._run();
}
}
exports.InternalEditorAction = InternalEditorAction;
});
define(__m[110/*vs/editor/common/editorCommon*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EditorType = exports.isThemeColor = void 0;
/**
* @internal
*/
function isThemeColor(o) {
return o && typeof o.id === 'string';
}
exports.isThemeColor = isThemeColor;
/**
* 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[111/*vs/editor/browser/editorBrowser*/], __M([0/*require*/,1/*exports*/,110/*vs/editor/common/editorCommon*/]), function (require, exports, editorCommon) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCodeEditor = exports.isDiffEditor = exports.isCodeEditor = void 0;
/**
*@internal
*/
function isCodeEditor(thing) {
if (thing && typeof thing.getEditorType === 'function') {
return thing.getEditorType() === editorCommon.EditorType.ICodeEditor;
}
else {
return false;
}
}
exports.isCodeEditor = isCodeEditor;
/**
*@internal
*/
function isDiffEditor(thing) {
if (thing && typeof thing.getEditorType === 'function') {
return thing.getEditorType() === editorCommon.EditorType.IDiffEditor;
}
else {
return false;
}
}
exports.isDiffEditor = isDiffEditor;
/**
*@internal
*/
function getCodeEditor(thing) {
if (isCodeEditor(thing)) {
return thing;
}
if (isDiffEditor(thing)) {
return thing.getModifiedEditor();
}
return null;
}
exports.getCodeEditor = getCodeEditor;
});
define(__m[53/*vs/editor/common/model*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApplyEditsResult = exports.ValidAnnotatedEditOperation = exports.FindMatch = exports.TextModelResolvedOptions = exports.MinimapPosition = exports.OverviewRulerLane = void 0;
/**
* 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 || (exports.OverviewRulerLane = {}));
/**
* 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 || (exports.MinimapPosition = {}));
class TextModelResolvedOptions {
/**
* @internal
*/
constructor(src) {
this._textModelResolvedOptionsBrand = undefined;
this.tabSize = Math.max(1, src.tabSize | 0);
this.indentSize = src.tabSize | 0;
this.insertSpaces = Boolean(src.insertSpaces);
this.defaultEOL = src.defaultEOL | 0;
this.trimAutoWhitespace = Boolean(src.trimAutoWhitespace);
}
/**
* @internal
*/
equals(other) {
return (this.tabSize === other.tabSize
&& this.indentSize === other.indentSize
&& this.insertSpaces === other.insertSpaces
&& this.defaultEOL === other.defaultEOL
&& this.trimAutoWhitespace === other.trimAutoWhitespace);
}
/**
* @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
*/
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 ApplyEditsResult {
constructor(reverseEdits, changes, trimAutoWhitespaceLineNumbers) {
this.reverseEdits = reverseEdits;
this.changes = changes;
this.trimAutoWhitespaceLineNumbers = trimAutoWhitespaceLineNumbers;
}
}
exports.ApplyEditsResult = ApplyEditsResult;
});
/*---------------------------------------------------------------------------------------------
* 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/common/model/indentationGuesser*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.guessIndentation = void 0;
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++) {
let aCharCode = a.charCodeAt(i);
let bCharCode = b.charCodeAt(i);
if (aCharCode !== bCharCode) {
break;
}
}
let aSpacesCnt = 0, aTabsCount = 0;
for (let j = i; j < aLength; j++) {
let aCharCode = a.charCodeAt(j);
if (aCharCode === 32 /* Space */) {
aSpacesCnt++;
}
else {
aTabsCount++;
}
}
let bSpacesCnt = 0, bTabsCount = 0;
for (let j = i; j < bLength; j++) {
let bCharCode = b.charCodeAt(j);
if (bCharCode === 32 /* Space */) {
bSpacesCnt++;
}
else {
bTabsCount++;
}
}
if (aSpacesCnt > 0 && aTabsCount > 0) {
return;
}
if (bSpacesCnt > 0 && bTabsCount > 0) {
return;
}
let tabsDiff = Math.abs(aTabsCount - bTabsCount);
let 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 /* Space */ && a.charCodeAt(bSpacesCnt - 1) === 32 /* Space */) {
if (a.charCodeAt(a.length - 1) === 44 /* 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
let spacesDiffCount = [0, 0, 0, 0, 0, 0, 0, 0, 0]; // `tabSize` scores
let tmp = new SpacesDiffResult();
for (let lineNumber = 1; lineNumber <= linesCount; lineNumber++) {
let currentLineLength = source.getLineLength(lineNumber);
let 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++) {
let charCode = (useCurrentLineText ? currentLineText.charCodeAt(j) : source.getLineCharCode(lineNumber, j));
if (charCode === 9 /* Tab */) {
currentLineTabsCount++;
}
else if (charCode === 32 /* 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;
}
}
let 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) => {
let 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
};
}
exports.guessIndentation = guessIndentation;
});
/*---------------------------------------------------------------------------------------------
* 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/common/model/intervalTree*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.intervalCompare = exports.recomputeMaxEnd = exports.nodeAcceptEdit = exports.IntervalTree = exports.SENTINEL = exports.IntervalNode = exports.getNodeColor = void 0;
function getNodeColor(node) {
return ((node.metadata & 1 /* ColorMask */) >>> 0 /* ColorOffset */);
}
exports.getNodeColor = getNodeColor;
function setNodeColor(node, color) {
node.metadata = ((node.metadata & 254 /* ColorMaskInverse */) | (color << 0 /* ColorOffset */));
}
function getNodeIsVisited(node) {
return ((node.metadata & 2 /* IsVisitedMask */) >>> 1 /* IsVisitedOffset */) === 1;
}
function setNodeIsVisited(node, value) {
node.metadata = ((node.metadata & 253 /* IsVisitedMaskInverse */) | ((value ? 1 : 0) << 1 /* IsVisitedOffset */));
}
function getNodeIsForValidation(node) {
return ((node.metadata & 4 /* IsForValidationMask */) >>> 2 /* IsForValidationOffset */) === 1;
}
function setNodeIsForValidation(node, value) {
node.metadata = ((node.metadata & 251 /* IsForValidationMaskInverse */) | ((value ? 1 : 0) << 2 /* IsForValidationOffset */));
}
function getNodeStickiness(node) {
return ((node.metadata & 24 /* StickinessMask */) >>> 3 /* StickinessOffset */);
}
function _setNodeStickiness(node, stickiness) {
node.metadata = ((node.metadata & 231 /* StickinessMaskInverse */) | (stickiness << 3 /* StickinessOffset */));
}
function getCollapseOnReplaceEdit(node) {
return ((node.metadata & 32 /* CollapseOnReplaceEditMask */) >>> 5 /* CollapseOnReplaceEditOffset */) === 1;
}
function setCollapseOnReplaceEdit(node, value) {
node.metadata = ((node.metadata & 223 /* CollapseOnReplaceEditMaskInverse */) | ((value ? 1 : 0) << 5 /* CollapseOnReplaceEditOffset */));
}
class IntervalNode {
constructor(id, start, end) {
this.metadata = 0;
this.parent = this;
this.left = this;
this.right = this;
setNodeColor(this, 1 /* 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);
_setNodeStickiness(this, 1 /* 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;
let className = this.options.className;
setNodeIsForValidation(this, (className === "squiggly-error" /* EditorErrorDecoration */
|| className === "squiggly-warning" /* EditorWarningDecoration */
|| className === "squiggly-info" /* EditorInfoDecoration */));
_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 /* Black */);
class IntervalTree {
constructor() {
this.root = exports.SENTINEL;
this.requestNormalizeDelta = false;
}
intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId) {
if (this.root === exports.SENTINEL) {
return [];
}
return intervalSearch(this, start, end, filterOwnerId, filterOutValidation, cachedVersionId);
}
search(filterOwnerId, filterOutValidation, cachedVersionId) {
if (this.root === exports.SENTINEL) {
return [];
}
return search(this, filterOwnerId, filterOutValidation, cachedVersionId);
}
/**
* 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 /* ForceMove */) {
return false;
}
if (moveSemantics === 2 /* 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 /* AlwaysGrowsWhenTypingAtEdges */
|| nodeStickiness === 2 /* GrowsOnlyWhenTypingBefore */);
const endStickToPreviousCharacter = (nodeStickiness === 1 /* NeverGrowsWhenTypingAtEdges */
|| nodeStickiness === 2 /* 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 /* ForceMove */ : (deletingCnt > 0 ? 2 /* ForceStay */ : 0 /* 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 /* ForceStay */ : 0 /* 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 /* ForceMove */ : 0 /* 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;
}
}
exports.nodeAcceptEdit = nodeAcceptEdit;
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;
let 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 /* MIN_SAFE_DELTA */ || node.delta > 1073741824 /* 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;
let 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;
let 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) {
let node = T.root;
let delta = 0;
let nodeStart = 0;
let nodeEnd = 0;
let 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 (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) {
// 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;
let 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 (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 /* 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 /* Red */) {
if (x.parent === x.parent.parent.left) {
const y = x.parent.parent.right;
if (getNodeColor(y) === 1 /* Red */) {
setNodeColor(x.parent, 0 /* Black */);
setNodeColor(y, 0 /* Black */);
setNodeColor(x.parent.parent, 1 /* Red */);
x = x.parent.parent;
}
else {
if (x === x.parent.right) {
x = x.parent;
leftRotate(T, x);
}
setNodeColor(x.parent, 0 /* Black */);
setNodeColor(x.parent.parent, 1 /* Red */);
rightRotate(T, x.parent.parent);
}
}
else {
const y = x.parent.parent.left;
if (getNodeColor(y) === 1 /* Red */) {
setNodeColor(x.parent, 0 /* Black */);
setNodeColor(y, 0 /* Black */);
setNodeColor(x.parent.parent, 1 /* Red */);
x = x.parent.parent;
}
else {
if (x === x.parent.left) {
x = x.parent;
rightRotate(T, x);
}
setNodeColor(x.parent, 0 /* Black */);
setNodeColor(x.parent.parent, 1 /* Red */);
leftRotate(T, x.parent.parent);
}
}
}
setNodeColor(T.root, 0 /* 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 /* 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 /* MIN_SAFE_DELTA */ || x.delta > 1073741824 /* 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 /* MIN_SAFE_DELTA */ || x.delta > 1073741824 /* MAX_SAFE_DELTA */) {
T.requestNormalizeDelta = true;
}
y.start += z.delta;
y.end += z.delta;
y.delta = z.delta;
if (y.delta < -1073741824 /* MIN_SAFE_DELTA */ || y.delta > 1073741824 /* MAX_SAFE_DELTA */) {
T.requestNormalizeDelta = true;
}
}
if (y === T.root) {
T.root = x;
setNodeColor(x, 0 /* Black */);
z.detach();
resetSentinel();
recomputeMaxEnd(x);
T.root.parent = exports.SENTINEL;
return;
}
let yWasRed = (getNodeColor(y) === 1 /* 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 /* Black */) {
if (x === x.parent.left) {
w = x.parent.right;
if (getNodeColor(w) === 1 /* Red */) {
setNodeColor(w, 0 /* Black */);
setNodeColor(x.parent, 1 /* Red */);
leftRotate(T, x.parent);
w = x.parent.right;
}
if (getNodeColor(w.left) === 0 /* Black */ && getNodeColor(w.right) === 0 /* Black */) {
setNodeColor(w, 1 /* Red */);
x = x.parent;
}
else {
if (getNodeColor(w.right) === 0 /* Black */) {
setNodeColor(w.left, 0 /* Black */);
setNodeColor(w, 1 /* Red */);
rightRotate(T, w);
w = x.parent.right;
}
setNodeColor(w, getNodeColor(x.parent));
setNodeColor(x.parent, 0 /* Black */);
setNodeColor(w.right, 0 /* Black */);
leftRotate(T, x.parent);
x = T.root;
}
}
else {
w = x.parent.left;
if (getNodeColor(w) === 1 /* Red */) {
setNodeColor(w, 0 /* Black */);
setNodeColor(x.parent, 1 /* Red */);
rightRotate(T, x.parent);
w = x.parent.left;
}
if (getNodeColor(w.left) === 0 /* Black */ && getNodeColor(w.right) === 0 /* Black */) {
setNodeColor(w, 1 /* Red */);
x = x.parent;
}
else {
if (getNodeColor(w.left) === 0 /* Black */) {
setNodeColor(w.right, 0 /* Black */);
setNodeColor(w, 1 /* Red */);
leftRotate(T, w);
w = x.parent.left;
}
setNodeColor(w, getNodeColor(x.parent));
setNodeColor(x.parent, 0 /* Black */);
setNodeColor(w.left, 0 /* Black */);
rightRotate(T, x.parent);
x = T.root;
}
}
}
setNodeColor(x, 0 /* 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 /* MIN_SAFE_DELTA */ || y.delta > 1073741824 /* 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 /* MIN_SAFE_DELTA */ || y.delta > 1073741824 /* 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);
}
exports.recomputeMaxEnd = recomputeMaxEnd;
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;
}
exports.intervalCompare = intervalCompare;
});
//#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[380/*vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.recomputeTreeMetadata = exports.updateTreeMetadata = exports.fixInsert = exports.rbDelete = exports.rightRotate = exports.leftRotate = exports.resetSentinel = exports.calculateLF = exports.calculateSize = exports.righttest = exports.leftest = exports.SENTINEL = exports.TreeNode = void 0;
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 /* Black */);
exports.SENTINEL.parent = exports.SENTINEL;
exports.SENTINEL.left = exports.SENTINEL;
exports.SENTINEL.right = exports.SENTINEL;
exports.SENTINEL.color = 0 /* Black */;
function leftest(node) {
while (node.left !== exports.SENTINEL) {
node = node.left;
}
return node;
}
exports.leftest = leftest;
function righttest(node) {
while (node.right !== exports.SENTINEL) {
node = node.right;
}
return node;
}
exports.righttest = righttest;
function calculateSize(node) {
if (node === exports.SENTINEL) {
return 0;
}
return node.size_left + node.piece.length + calculateSize(node.right);
}
exports.calculateSize = calculateSize;
function calculateLF(node) {
if (node === exports.SENTINEL) {
return 0;
}
return node.lf_left + node.piece.lineFeedCnt + calculateLF(node.right);
}
exports.calculateLF = calculateLF;
function resetSentinel() {
exports.SENTINEL.parent = exports.SENTINEL;
}
exports.resetSentinel = resetSentinel;
function leftRotate(tree, x) {
let 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;
}
exports.leftRotate = leftRotate;
function rightRotate(tree, y) {
let 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;
}
exports.rightRotate = rightRotate;
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 /* Black */;
z.detach();
resetSentinel();
tree.root.parent = exports.SENTINEL;
return;
}
let yWasRed = (y.color === 1 /* 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) {
let newSizeLeft = calculateSize(x);
let newLFLeft = calculateLF(x);
if (newSizeLeft !== x.parent.size_left || newLFLeft !== x.parent.lf_left) {
let delta = newSizeLeft - x.parent.size_left;
let 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 /* Black */) {
if (x === x.parent.left) {
w = x.parent.right;
if (w.color === 1 /* Red */) {
w.color = 0 /* Black */;
x.parent.color = 1 /* Red */;
leftRotate(tree, x.parent);
w = x.parent.right;
}
if (w.left.color === 0 /* Black */ && w.right.color === 0 /* Black */) {
w.color = 1 /* Red */;
x = x.parent;
}
else {
if (w.right.color === 0 /* Black */) {
w.left.color = 0 /* Black */;
w.color = 1 /* Red */;
rightRotate(tree, w);
w = x.parent.right;
}
w.color = x.parent.color;
x.parent.color = 0 /* Black */;
w.right.color = 0 /* Black */;
leftRotate(tree, x.parent);
x = tree.root;
}
}
else {
w = x.parent.left;
if (w.color === 1 /* Red */) {
w.color = 0 /* Black */;
x.parent.color = 1 /* Red */;
rightRotate(tree, x.parent);
w = x.parent.left;
}
if (w.left.color === 0 /* Black */ && w.right.color === 0 /* Black */) {
w.color = 1 /* Red */;
x = x.parent;
}
else {
if (w.left.color === 0 /* Black */) {
w.right.color = 0 /* Black */;
w.color = 1 /* Red */;
leftRotate(tree, w);
w = x.parent.left;
}
w.color = x.parent.color;
x.parent.color = 0 /* Black */;
w.left.color = 0 /* Black */;
rightRotate(tree, x.parent);
x = tree.root;
}
}
}
x.color = 0 /* Black */;
resetSentinel();
}
exports.rbDelete = rbDelete;
function fixInsert(tree, x) {
recomputeTreeMetadata(tree, x);
while (x !== tree.root && x.parent.color === 1 /* Red */) {
if (x.parent === x.parent.parent.left) {
const y = x.parent.parent.right;
if (y.color === 1 /* Red */) {
x.parent.color = 0 /* Black */;
y.color = 0 /* Black */;
x.parent.parent.color = 1 /* Red */;
x = x.parent.parent;
}
else {
if (x === x.parent.right) {
x = x.parent;
leftRotate(tree, x);
}
x.parent.color = 0 /* Black */;
x.parent.parent.color = 1 /* Red */;
rightRotate(tree, x.parent.parent);
}
}
else {
const y = x.parent.parent.left;
if (y.color === 1 /* Red */) {
x.parent.color = 0 /* Black */;
y.color = 0 /* Black */;
x.parent.parent.color = 1 /* Red */;
x = x.parent.parent;
}
else {
if (x === x.parent.left) {
x = x.parent;
rightRotate(tree, x);
}
x.parent.color = 0 /* Black */;
x.parent.parent.color = 1 /* Red */;
leftRotate(tree, x.parent.parent);
}
}
}
tree.root.color = 0 /* Black */;
}
exports.fixInsert = fixInsert;
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;
}
}
exports.updateTreeMetadata = updateTreeMetadata;
function recomputeTreeMetadata(tree, x) {
let delta = 0;
let lf_delta = 0;
if (x === tree.root) {
return;
}
if (delta === 0) {
// 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;
}
}
exports.recomputeTreeMetadata = recomputeTreeMetadata;
});
/*---------------------------------------------------------------------------------------------
* 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/common/model/textChange*/], __M([0/*require*/,1/*exports*/,103/*vs/base/common/buffer*/,83/*vs/editor/common/core/stringBuilder*/]), function (require, exports, buffer, stringBuilder_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compressConsecutiveTextChanges = exports.TextChange = void 0;
function escapeNewLine(str) {
return (str
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r'));
}
class TextChange {
constructor(oldPosition, oldText, newPosition, newText) {
this.oldPosition = oldPosition;
this.oldText = oldText;
this.newPosition = newPosition;
this.newText = newText;
}
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;
}
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();
}
exports.compressConsecutiveTextChanges = compressConsecutiveTextChanges;
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;
}
let result = [], 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;
}
let result = [], 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[96/*vs/editor/common/model/textModelEvents*/], __M([0/*require*/,1/*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 /* Flush */;
}
}
exports.ModelRawFlush = ModelRawFlush;
/**
* Represents text injected on a line
* @internal
*/
class LineInjectedText {
constructor(ownerId, lineNumber, column, options, order) {
this.ownerId = ownerId;
this.lineNumber = lineNumber;
this.column = column;
this.options = options;
this.order = order;
}
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;
}
}
exports.LineInjectedText = LineInjectedText;
/**
* An event describing that a line has changed in a model.
* @internal
*/
class ModelRawLineChanged {
constructor(lineNumber, detail, injectedText) {
this.changeType = 2 /* 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 /* 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 /* 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 /* 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);
return {
changes: changes,
eol: eol,
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[171/*vs/editor/common/model/textModelSearch*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,109/*vs/editor/common/controller/wordCharacterClassifier*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,53/*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.isValidMatch = exports.TextModelSearch = exports.createFindMatch = exports.SearchData = exports.isMultilineRegexSource = exports.SearchParams = void 0;
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 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 === 92 /* Backslash */) {
// move to next char
i++;
if (i >= len) {
// string ends with a \
break;
}
const nextChCode = searchString.charCodeAt(i);
if (nextChCode === 110 /* n */ || nextChCode === 114 /* r */ || nextChCode === 87 /* W */ || nextChCode === 119 /* w */) {
return true;
}
}
}
return false;
}
exports.isMultilineRegexSource = isMultilineRegexSource;
class SearchData {
constructor(regex, wordSeparators, simpleSearch) {
this.regex = regex;
this.wordSeparators = wordSeparators;
this.simpleSearch = simpleSearch;
}
}
exports.SearchData = SearchData;
function createFindMatch(range, rawMatches, captureMatches) {
if (!captureMatches) {
return new model_1.FindMatch(range, null);
}
let matches = [];
for (let i = 0, len = rawMatches.length; i < len; i++) {
matches[i] = rawMatches[i];
}
return new model_1.FindMatch(range, matches);
}
exports.createFindMatch = createFindMatch;
class LineFeedCounter {
constructor(text) {
let lineFeedsOffsets = [];
let lineFeedsOffsetsLen = 0;
for (let i = 0, textLen = text.length; i < textLen; i++) {
if (text.charCodeAt(i) === 10 /* 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) {
let lineFeedCountBeforeEndOfMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex + match0.length);
let 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 /* 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 /* LF */);
const lfCounter = (model.getEOL() === '\r\n' ? new LineFeedCounter(text) : null);
searcher.reset(searchStart.column - 1);
let 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 /* Regular */) {
// The character before the match is a word separator
return true;
}
if (charBefore === 13 /* CarriageReturn */ || charBefore === 10 /* 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 /* 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 /* Regular */) {
// The character after the match is a word separator
return true;
}
if (charAfter === 13 /* CarriageReturn */ || charAfter === 10 /* 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 /* 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));
}
exports.isValidMatch = isValidMatch;
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[221/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,53/*vs/editor/common/model*/,380/*vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase*/,171/*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 = exports.createLineStarts = exports.createLineStartsFast = exports.LineStarts = exports.createUintArray = exports.AverageBufferSize = void 0;
// const lfRegex = new RegExp(/\r\n|\r|\n/g);
exports.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;
}
exports.createUintArray = createUintArray;
class LineStarts {
constructor(lineStarts, cr, lf, crlf, isBasicASCII) {
this.lineStarts = lineStarts;
this.cr = cr;
this.lf = lf;
this.crlf = crlf;
this.isBasicASCII = isBasicASCII;
}
}
exports.LineStarts = LineStarts;
function createLineStartsFast(str, readonly = true) {
let r = [0], rLength = 1;
for (let i = 0, len = str.length; i < len; i++) {
const chr = str.charCodeAt(i);
if (chr === 13 /* CarriageReturn */) {
if (i + 1 < len && str.charCodeAt(i + 1) === 10 /* LineFeed */) {
// \r\n... case
r[rLength++] = i + 2;
i++; // skip \n
}
else {
// \r... case
r[rLength++] = i + 1;
}
}
else if (chr === 10 /* LineFeed */) {
r[rLength++] = i + 1;
}
}
if (readonly) {
return createUintArray(r);
}
else {
return r;
}
}
exports.createLineStartsFast = createLineStartsFast;
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 /* CarriageReturn */) {
if (i + 1 < len && str.charCodeAt(i + 1) === 10 /* LineFeed */) {
// \r\n... case
crlf++;
r[rLength++] = i + 2;
i++; // skip \n
}
else {
cr++;
// \r... case
r[rLength++] = i + 1;
}
}
else if (chr === 10 /* LineFeed */) {
lf++;
r[rLength++] = i + 1;
}
else {
if (isBasicASCII) {
if (chr !== 9 /* Tab */ && (chr < 32 || chr > 126)) {
isBasicASCII = false;
}
}
}
}
const result = new LineStarts(createUintArray(r), cr, lf, crlf, isBasicASCII);
r.length = 0;
return result;
}
exports.createLineStarts = createLineStarts;
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--) {
let 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--) {
let 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;
let tmp = this._cache;
for (let i = 0; i < tmp.length; i++) {
let nodePos = tmp[i];
if (nodePos.node.parent === null || nodePos.nodeStartOffset >= offset) {
tmp[i] = null;
hasInvalidVal = true;
continue;
}
}
if (hasInvalidVal) {
let 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);
}
let 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) {
let averageBufferSize = exports.AverageBufferSize;
let min = averageBufferSize - Math.floor(averageBufferSize / 3);
let max = min * 2;
let tempChunk = '';
let tempChunkLen = 0;
let chunks = [];
this.iterate(this.root, node => {
let str = this.getNodeContent(node);
let len = str.length;
if (tempChunkLen <= min || tempChunkLen + len < max) {
tempChunk += str;
tempChunkLen += len;
return true;
}
// flush anyways
let 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) {
let 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
let 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;
let 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) {
let out = this.getIndexOf(x, offset - x.size_left);
lfCnt += x.lf_left + out.index;
if (out.index === 0) {
let lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
let 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
let lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
let 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 '';
}
let startPosition = this.nodeAt2(range.startLineNumber, range.startColumn);
let endPosition = this.nodeAt2(range.endLineNumber, range.endColumn);
let 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) {
let node = startPosition.node;
let buffer = this._buffers[node.piece.bufferIndex].buffer;
let startOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
return buffer.substring(startOffset + startPosition.remainder, startOffset + endPosition.remainder);
}
let x = startPosition.node;
let buffer = this._buffers[x.piece.bufferIndex].buffer;
let 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) {
let buffer = this._buffers[x.piece.bufferIndex].buffer;
let 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() {
let 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 /* 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 /* 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 /* 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.
let matchingNode = nodePos.node.next();
if (!matchingNode) {
return 0;
}
let buffer = this._buffers[matchingNode.piece.bufferIndex];
let startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start);
return buffer.buffer.charCodeAt(startOffset);
}
else {
let buffer = this._buffers[nodePos.node.piece.bufferIndex];
let startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
let targetOffset = startOffset + nodePos.remainder;
return buffer.buffer.charCodeAt(targetOffset);
}
}
getLineCharCode(lineNumber, index) {
let nodePos = this.nodeAt2(lineNumber, index + 1);
return this._getCharCode(nodePos);
}
getLineLength(lineNumber) {
if (lineNumber === this.getLineCount()) {
let 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) {
let buffer = this._buffers[node.piece.bufferIndex];
let startOffsetInBuffer = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
let start = this.offsetInBuffer(node.piece.bufferIndex, startCursor);
let end = this.offsetInBuffer(node.piece.bufferIndex, endCursor);
let m;
// Reset regex to search from the beginning
let 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);
let lineFeedCnt = this.getLineFeedCnt(node.piece.bufferIndex, startCursor, ret);
let retStartColumn = ret.line === startCursor.line ? ret.column - startCursor.column + startColumn : ret.column + 1;
let 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 [];
}
let endPosition = this.nodeAt2(searchRange.endLineNumber, searchRange.endColumn);
if (endPosition === null) {
return [];
}
let start = this.positionInBuffer(startPosition.node, startPosition.remainder);
let 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) {
let lineBreakCnt = this.getLineFeedCnt(currentNode.piece.bufferIndex, start, currentNode.piece.end);
if (lineBreakCnt >= 1) {
// last line break position
let lineStarts = this._buffers[currentNode.piece.bufferIndex].lineStarts;
let startOffsetInBuffer = this.offsetInBuffer(currentNode.piece.bufferIndex, currentNode.piece.start);
let nextLineStartOffset = lineStarts[start.line + lineBreakCnt];
let 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;
}
let 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) {
let 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;
}
let 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) {
let { node, remainder, nodeStartOffset } = this.nodeAt(offset);
let piece = node.piece;
let bufferIndex = piece.bufferIndex;
let 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 < exports.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.
let 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)) {
let headOfRight = this.nodeCharCodeAt(node, remainder);
if (headOfRight === 10 /** \n */) {
let 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)) {
let tailOfLeft = this.nodeCharCodeAt(node, remainder - 1);
if (tailOfLeft === 13 /** \r */) {
let 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);
}
let 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
let 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;
}
let startPosition = this.nodeAt(offset);
let endPosition = this.nodeAt(offset + cnt);
let startNode = startPosition.node;
let endNode = endPosition.node;
if (startNode === endNode) {
let startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);
let endSplitPosInBuffer = this.positionInBuffer(startNode, endPosition.remainder);
if (startPosition.nodeStartOffset === offset) {
if (cnt === startNode.piece.length) { // delete node
let 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;
}
let nodesToDel = [];
let 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
let endSplitPosInBuffer = this.positionInBuffer(endNode, endPosition.remainder);
this.deleteNodeHead(endNode, endSplitPosInBuffer);
if (endNode.piece.length === 0) {
nodesToDel.push(endNode);
}
// delete nodes in between
let secondNode = startNode.next();
for (let node = secondNode; node !== rbTreeBase_1.SENTINEL && node !== endNode; node = node.next()) {
nodesToDel.push(node);
}
let 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
let nodesToDel = [];
if (this.shouldCheckCRLF() && this.endWithCR(value) && this.startWithLF(node)) {
// move `\n` to new node.
let piece = node.piece;
let newStart = { line: piece.start.line + 1, column: 0 };
let 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);
}
}
let 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';
}
let newPieces = this.createNewPieces(value);
let 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) {
let piece = node.piece;
let bufferIndex = node.piece.bufferIndex;
let lineStarts = this._buffers[bufferIndex].lineStarts;
let startOffset = lineStarts[piece.start.line] + piece.start.column;
let 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;
}
let 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;
}
let nextLineStartOffset = lineStarts[end.line + 1];
let 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.
let previousCharOffset = endOffset - 1; // end.column > 0 so it's okay.
let 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) {
let 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 > exports.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
let newPieces = [];
while (text.length > exports.AverageBufferSize) {
const lastChar = text.charCodeAt(exports.AverageBufferSize - 1);
let splitText;
if (lastChar === 13 /* CarriageReturn */ || (lastChar >= 0xD800 && lastChar <= 0xDBFF)) {
// last character is \r or a high surrogate => keep it back
splitText = text.substring(0, exports.AverageBufferSize - 1);
text = text.substring(exports.AverageBufferSize - 1);
}
else {
splitText = text.substring(0, exports.AverageBufferSize);
text = text.substring(exports.AverageBufferSize);
}
let 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));
}
let 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;
let endIndex = this._buffers[0].lineStarts.length - 1;
let endColumn = endOffset - this._buffers[0].lineStarts[endIndex];
let endPos = { line: endIndex, column: endColumn };
let 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 = '';
let cache = this._searchCache.get2(lineNumber);
if (cache) {
x = cache.node;
let prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber - 1);
let buffer = this._buffers[x.piece.bufferIndex].buffer;
let 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 {
let 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) {
let prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
let accumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
let buffer = this._buffers[x.piece.bufferIndex].buffer;
let 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) {
let prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
let buffer = this._buffers[x.piece.bufferIndex].buffer;
let 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) {
let buffer = this._buffers[x.piece.bufferIndex].buffer;
if (x.piece.lineFeedCnt > 0) {
let accumulatedValue = this.getAccumulatedValue(x, 0);
let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
ret += buffer.substring(startOffset, startOffset + accumulatedValue - endOffset);
return ret;
}
else {
let 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) {
let piece = node.piece;
let pos = this.positionInBuffer(node, accumulatedValue);
let 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.
let 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;
}
let piece = node.piece;
let lineStarts = this._buffers[piece.bufferIndex].lineStarts;
let 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
let newPiece = new Piece(piece.bufferIndex, end, originalEndPos, this.getLineFeedCnt(piece.bufferIndex, end, originalEndPos), this.offsetInBuffer(piece.bufferIndex, originalEndPos) - this.offsetInBuffer(piece.bufferIndex, end));
let 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) {
let 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;
let 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;
let 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) {
let prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
let 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) {
let 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) {
let accumulatedValue = this.getAccumulatedValue(x, 0);
let nodeStartOffset = this.offsetOfNode(x);
return {
node: x,
remainder: Math.min(column - 1, accumulatedValue),
nodeStartOffset
};
}
else {
if (x.piece.length >= column - 1) {
let 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;
}
let buffer = this._buffers[node.piece.bufferIndex];
let 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;
}
let piece = val.piece;
let lineStarts = this._buffers[piece.bufferIndex].lineStarts;
let line = piece.start.line;
let 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;
}
let 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)) {
let node = nextNode.prev();
if (this.endWithCR(node)) {
this.fixCRLF(node, nextNode);
}
}
}
validateCRLFWithNextNode(node) {
if (this.shouldCheckCRLF() && this.endWithCR(node)) {
let nextNode = node.next();
if (this.startWithLF(nextNode)) {
this.fixCRLF(node, nextNode);
}
}
}
fixCRLF(prev, next) {
let nodesToDel = [];
// update node
let 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
let 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
let 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)) {
let 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);
}
let 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 '';
}
let buffer = this._buffers[node.piece.bufferIndex];
let currentContent;
let piece = node.piece;
let startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
let endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
currentContent = buffer.buffer.substring(startOffset, endOffset);
return currentContent;
}
getPieceContent(piece) {
let buffer = this._buffers[piece.bufferIndex];
let startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
let endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
let currentContent = buffer.buffer.substring(startOffset, endOffset);
return currentContent;
}
/**
* node node
* / \ / \
* a b <---- a b
* /
* z
*/
rbInsertRight(node, p) {
let z = new rbTreeBase_1.TreeNode(p, 1 /* Red */);
z.left = rbTreeBase_1.SENTINEL;
z.right = rbTreeBase_1.SENTINEL;
z.parent = rbTreeBase_1.SENTINEL;
z.size_left = 0;
z.lf_left = 0;
let x = this.root;
if (x === rbTreeBase_1.SENTINEL) {
this.root = z;
z.color = 0 /* Black */;
}
else if (node.right === rbTreeBase_1.SENTINEL) {
node.right = z;
z.parent = node;
}
else {
let 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) {
let z = new rbTreeBase_1.TreeNode(p, 1 /* 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 /* Black */;
}
else if (node.left === rbTreeBase_1.SENTINEL) {
node.left = z;
z.parent = node;
}
else {
let 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[135/*vs/editor/common/model/wordHelper*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getWordAtText = exports.ensureValidWordDefinition = exports.DEFAULT_WORD_REGEXP = exports.USUAL_WORD_SEPARATORS = void 0;
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;
}
exports.ensureValidWordDefinition = ensureValidWordDefinition;
const _defaultConfig = {
maxLen: 1000,
windowSize: 15,
timeBudget: 150
};
function getWordAtText(column, wordDefinition, text, textOffset, config = _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) {
let result = {
word: match[0],
startColumn: textOffset + 1 + match.index,
endColumn: textOffset + 1 + match.index + match[0].length
};
wordDefinition.lastIndex = 0;
return result;
}
return null;
}
exports.getWordAtText = getWordAtText;
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[381/*vs/editor/common/modes/abstractMode*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FrankensteinMode = void 0;
class FrankensteinMode {
constructor(languageIdentifier) {
this._languageIdentifier = languageIdentifier;
}
getId() {
return this._languageIdentifier.language;
}
}
exports.FrankensteinMode = FrankensteinMode;
});
/*---------------------------------------------------------------------------------------------
* 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/common/modes/languageConfiguration*/], __M([0/*require*/,1/*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 || (exports.IndentAction = {}));
/**
* @internal
*/
class StandardAutoClosingPairConditional {
constructor(source) {
this._standardAutoClosingPairConditionalBrand = undefined;
this.open = source.open;
this.close = source.close;
// initially allowed in all tokens
this._standardTokenMask = 0;
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._standardTokenMask |= 2 /* String */;
break;
case 'comment':
this._standardTokenMask |= 1 /* Comment */;
break;
case 'regex':
this._standardTokenMask |= 4 /* RegEx */;
break;
}
}
}
}
isOK(standardToken) {
return (this._standardTokenMask & standardToken) === 0;
}
}
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[382/*vs/editor/common/modes/languageSelector*/], __M([0/*require*/,1/*exports*/,201/*vs/base/common/glob*/,73/*vs/base/common/path*/]), function (require, exports, glob_1, path_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.score = void 0;
function score(selector, candidateUri, candidateLanguage, candidateIsSynchronized) {
if (Array.isArray(selector)) {
// array -> take max individual value
let ret = 0;
for (const filter of selector) {
const value = score(filter, candidateUri, candidateLanguage, candidateIsSynchronized);
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 } = selector; // TODO: microsoft/TypeScript#42768
if (!candidateIsSynchronized && !hasAccessToAllModels) {
return 0;
}
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 (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 = Object.assign(Object.assign({}, 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;
}
}
exports.score = score;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[383/*vs/editor/common/modes/linkComputer*/], __M([0/*require*/,1/*exports*/,94/*vs/editor/common/core/characterClassifier*/]), function (require, exports, characterClassifier_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.computeLinks = exports.LinkComputer = exports.StateMachine = exports.Uint8Matrix = void 0;
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;
}
}
exports.Uint8Matrix = Uint8Matrix;
class StateMachine {
constructor(edges) {
let maxCharCode = 0;
let maxState = 0 /* Invalid */;
for (let i = 0, len = edges.length; i < len; i++) {
let [from, chCode, to] = edges[i];
if (chCode > maxCharCode) {
maxCharCode = chCode;
}
if (from > maxState) {
maxState = from;
}
if (to > maxState) {
maxState = to;
}
}
maxCharCode++;
maxState++;
let states = new Uint8Matrix(maxState, maxCharCode, 0 /* Invalid */);
for (let i = 0, len = edges.length; i < len; i++) {
let [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 /* 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 /* Start */, 104 /* h */, 2 /* H */],
[1 /* Start */, 72 /* H */, 2 /* H */],
[1 /* Start */, 102 /* f */, 6 /* F */],
[1 /* Start */, 70 /* F */, 6 /* F */],
[2 /* H */, 116 /* t */, 3 /* HT */],
[2 /* H */, 84 /* T */, 3 /* HT */],
[3 /* HT */, 116 /* t */, 4 /* HTT */],
[3 /* HT */, 84 /* T */, 4 /* HTT */],
[4 /* HTT */, 112 /* p */, 5 /* HTTP */],
[4 /* HTT */, 80 /* P */, 5 /* HTTP */],
[5 /* HTTP */, 115 /* s */, 9 /* BeforeColon */],
[5 /* HTTP */, 83 /* S */, 9 /* BeforeColon */],
[5 /* HTTP */, 58 /* Colon */, 10 /* AfterColon */],
[6 /* F */, 105 /* i */, 7 /* FI */],
[6 /* F */, 73 /* I */, 7 /* FI */],
[7 /* FI */, 108 /* l */, 8 /* FIL */],
[7 /* FI */, 76 /* L */, 8 /* FIL */],
[8 /* FIL */, 101 /* e */, 9 /* BeforeColon */],
[8 /* FIL */, 69 /* E */, 9 /* BeforeColon */],
[9 /* BeforeColon */, 58 /* Colon */, 10 /* AfterColon */],
[10 /* AfterColon */, 47 /* Slash */, 11 /* AlmostThere */],
[11 /* AlmostThere */, 47 /* Slash */, 12 /* End */],
]);
}
return _stateMachine;
}
let _classifier = null;
function getClassifier() {
if (_classifier === null) {
_classifier = new characterClassifier_1.CharacterClassifier(0 /* None */);
const FORCE_TERMINATION_CHARACTERS = ' \t<>\'\"、。。、,.:;‘〈「『〔([{「」}])〕』」〉’`~…';
for (let i = 0; i < FORCE_TERMINATION_CHARACTERS.length; i++) {
_classifier.set(FORCE_TERMINATION_CHARACTERS.charCodeAt(i), 1 /* 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 /* 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 /* 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 /* OpenParen */ && lastCharCodeInLink === 41 /* CloseParen */)
|| (charCodeBeforeLink === 91 /* OpenSquareBracket */ && lastCharCodeInLink === 93 /* CloseSquareBracket */)
|| (charCodeBeforeLink === 123 /* OpenCurlyBrace */ && lastCharCodeInLink === 125 /* 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();
let 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 /* 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 /* Accept */) {
let chClass;
switch (chCode) {
case 40 /* OpenParen */:
hasOpenParens = true;
chClass = 0 /* None */;
break;
case 41 /* CloseParen */:
chClass = (hasOpenParens ? 0 /* None */ : 1 /* ForceTermination */);
break;
case 91 /* OpenSquareBracket */:
inSquareBrackets = true;
hasOpenSquareBracket = true;
chClass = 0 /* None */;
break;
case 93 /* CloseSquareBracket */:
inSquareBrackets = false;
chClass = (hasOpenSquareBracket ? 0 /* None */ : 1 /* ForceTermination */);
break;
case 123 /* OpenCurlyBrace */:
hasOpenCurlyBracket = true;
chClass = 0 /* None */;
break;
case 125 /* CloseCurlyBrace */:
chClass = (hasOpenCurlyBracket ? 0 /* None */ : 1 /* ForceTermination */);
break;
/* The following three rules make it that ' or " or ` are allowed inside links if the link began with a different one */
case 39 /* SingleQuote */:
chClass = (linkBeginChCode === 34 /* DoubleQuote */ || linkBeginChCode === 96 /* BackTick */) ? 0 /* None */ : 1 /* ForceTermination */;
break;
case 34 /* DoubleQuote */:
chClass = (linkBeginChCode === 39 /* SingleQuote */ || linkBeginChCode === 96 /* BackTick */) ? 0 /* None */ : 1 /* ForceTermination */;
break;
case 96 /* BackTick */:
chClass = (linkBeginChCode === 39 /* SingleQuote */ || linkBeginChCode === 34 /* DoubleQuote */) ? 0 /* None */ : 1 /* ForceTermination */;
break;
case 42 /* Asterisk */:
// `*` terminates a link if the link began with `*`
chClass = (linkBeginChCode === 42 /* Asterisk */) ? 1 /* ForceTermination */ : 0 /* None */;
break;
case 124 /* Pipe */:
// `|` terminates a link if the link began with `|`
chClass = (linkBeginChCode === 124 /* Pipe */) ? 1 /* ForceTermination */ : 0 /* None */;
break;
case 32 /* Space */:
// ` ` allow space in between [ and ]
chClass = (inSquareBrackets ? 0 /* None */ : 1 /* ForceTermination */);
break;
default:
chClass = classifier.get(chCode);
}
// Check if character terminates link
if (chClass === 1 /* ForceTermination */) {
result.push(LinkComputer._createLink(classifier, line, i, linkBeginIndex, j));
resetStateMachine = true;
}
}
else if (state === 12 /* End */) {
let chClass;
if (chCode === 91 /* OpenSquareBracket */) {
// Allow for the authority part to contain ipv6 addresses which contain [ and ]
hasOpenSquareBracket = true;
chClass = 0 /* None */;
}
else {
chClass = classifier.get(chCode);
}
// Check if character terminates link
if (chClass === 1 /* ForceTermination */) {
resetStateMachine = true;
}
else {
state = 13 /* Accept */;
}
}
else {
state = stateMachine.nextState(state, chCode);
if (state === 0 /* Invalid */) {
resetStateMachine = true;
}
}
if (resetStateMachine) {
state = 1 /* Start */;
hasOpenParens = false;
hasOpenSquareBracket = false;
hasOpenCurlyBracket = false;
// Record where the link started
linkBeginIndex = j + 1;
linkBeginChCode = chCode;
}
j++;
}
if (state === 13 /* 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);
}
exports.computeLinks = computeLinks;
});
/*---------------------------------------------------------------------------------------------
* 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/editor/common/modes/supports*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ignoreBracketsInToken = exports.ScopedLineTokens = exports.createScopedLineTokens = void 0;
function createScopedLineTokens(context, offset) {
let tokenCount = context.getCount();
let tokenIndex = context.findTokenIndexAtOffset(offset);
let 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));
}
exports.createScopedLineTokens = createScopedLineTokens;
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;
}
getLineContent() {
const actualLineContent = this._actual.getLineContent();
return actualLineContent.substring(this.firstCharOffset, this._lastCharOffset);
}
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);
}
}
exports.ScopedLineTokens = ScopedLineTokens;
function ignoreBracketsInToken(standardTokenType) {
return (standardTokenType & 7 /* value */) !== 0;
}
exports.ignoreBracketsInToken = ignoreBracketsInToken;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[384/*vs/editor/common/modes/supports/characterPair*/], __M([0/*require*/,1/*exports*/,112/*vs/editor/common/modes/languageConfiguration*/]), function (require, exports, languageConfiguration_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CharacterPairSupport = void 0;
class CharacterPairSupport {
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._autoCloseBefore = typeof config.autoCloseBefore === 'string' ? config.autoCloseBefore : CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED;
this._surroundingPairs = config.surroundingPairs || this._autoClosingPairs;
}
getAutoClosingPairs() {
return this._autoClosingPairs;
}
getAutoCloseBeforeSet() {
return this._autoCloseBefore;
}
static shouldAutoClosePair(autoClosingPair, 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 autoClosingPair.isOK(standardTokenType);
}
getSurroundingPairs() {
return this._surroundingPairs;
}
}
exports.CharacterPairSupport = CharacterPairSupport;
CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED = ';:.,=}])> \n\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[385/*vs/editor/common/modes/supports/indentRules*/], __M([0/*require*/,1/*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 /* INCREASE_MASK */;
}
if (this.shouldDecrease(text)) {
ret += 2 /* DECREASE_MASK */;
}
if (this.shouldIndentNextLine(text)) {
ret += 4 /* INDENT_NEXTLINE_MASK */;
}
if (this.shouldIgnore(text)) {
ret += 8 /* 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[386/*vs/editor/common/modes/supports/inplaceReplaceSupport*/], __M([0/*require*/,1/*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'],
];
}
navigateValueSet(range1, text1, range2, text2, up) {
if (range1 && text1) {
let result = this.doNavigateValueSet(text1, up);
if (result) {
return {
range: range1,
value: result
};
}
}
if (range2 && text2) {
let result = this.doNavigateValueSet(text2, up);
if (result) {
return {
range: range2,
value: result
};
}
}
return null;
}
doNavigateValueSet(text, up) {
let numberResult = this.numberReplace(text, up);
if (numberResult !== null) {
return numberResult;
}
return this.textReplace(text, up);
}
numberReplace(value, up) {
let precision = Math.pow(10, value.length - (value.lastIndexOf('.') + 1));
let n1 = Number(value);
let 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;
BasicInplaceReplace.INSTANCE = new 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[387/*vs/editor/common/modes/supports/onEnter*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,8/*vs/base/common/strings*/,112/*vs/editor/common/modes/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 /* Advanced */) {
for (let i = 0, len = this._regExpRules.length; i < len; i++) {
let 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 /* Brackets */) {
if (beforeEnterText.length > 0 && afterEnterText.length > 0) {
for (let i = 0, len = this._brackets.length; i < len; i++) {
let 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 /* Brackets */) {
if (beforeEnterText.length > 0) {
for (let i = 0, len = this._brackets.length; i < len; i++) {
let 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[173/*vs/editor/common/modes/supports/richEditBrackets*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,83/*vs/editor/common/core/stringBuilder*/,3/*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;
class RichEditBracket {
constructor(languageIdentifier, index, open, close, forwardRegex, reversedRegex) {
this._richEditBracketBrand = undefined;
this.languageIdentifier = languageIdentifier;
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);
}
isOpen(text) {
return this._openSet.has(text);
}
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;
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++) {
let currentOpen = [];
let 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(languageIdentifier, _brackets) {
this._richEditBracketsBrand = undefined;
const brackets = groupFuzzyBrackets(_brackets);
this.brackets = brackets.map((b, index) => {
return new RichEditBracket(languageIdentifier, 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;
}
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);
}
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));
}
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);
}
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) {
let regexStr = `(${pieces.map(prepareBracketForRegExp).join(')|(')})`;
return strings.createRegExp(regexStr, true);
}
const toReversedString = (function () {
function reverse(str) {
if (stringBuilder.hasTextDecoder) {
// 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);
}
else {
let result = [], resultLen = 0;
for (let i = str.length - 1; i >= 0; i--) {
result[resultLen++] = str.charAt(i);
}
return result.join('');
}
}
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) {
let m = reversedText.match(reversedBracketRegex);
if (!m) {
return null;
}
let matchOffset = reversedText.length - (m.index || 0);
let matchLength = m[0].length;
let 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) {
let m = text.match(bracketRegex);
if (!m) {
return null;
}
let matchOffset = m.index || 0;
let matchLength = m[0].length;
if (matchLength === 0) {
return null;
}
let 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[388/*vs/editor/common/modes/supports/electricCharacter*/], __M([0/*require*/,1/*exports*/,172/*vs/editor/common/modes/supports*/,173/*vs/editor/common/modes/supports/richEditBrackets*/]), function (require, exports, supports_1, richEditBrackets_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BracketElectricCharacterSupport = void 0;
class BracketElectricCharacterSupport {
constructor(richEditBrackets) {
this._richEditBrackets = richEditBrackets;
}
getElectricCharacters() {
let 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);
}
}
}
// Filter duplicate entries
result = result.filter((item, pos, array) => {
return array.indexOf(item) === pos;
});
return 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[45/*vs/editor/common/modes/languageConfigurationRegistry*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,135/*vs/editor/common/model/wordHelper*/,112/*vs/editor/common/modes/languageConfiguration*/,172/*vs/editor/common/modes/supports*/,384/*vs/editor/common/modes/supports/characterPair*/,388/*vs/editor/common/modes/supports/electricCharacter*/,385/*vs/editor/common/modes/supports/indentRules*/,387/*vs/editor/common/modes/supports/onEnter*/,173/*vs/editor/common/modes/supports/richEditBrackets*/]), function (require, exports, event_1, lifecycle_1, strings, wordHelper_1, languageConfiguration_1, supports_1, characterPair_1, electricCharacter_1, indentRules_1, onEnter_1, richEditBrackets_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LanguageConfigurationRegistry = exports.LanguageConfigurationRegistryImpl = exports.LanguageConfigurationChangeEvent = exports.RichEditSupport = void 0;
class RichEditSupport {
constructor(languageIdentifier, rawConf) {
this._languageIdentifier = languageIdentifier;
this._brackets = null;
this._electricCharacter = null;
this._conf = rawConf;
this._onEnterSupport = (this._conf.brackets || this._conf.indentationRules || this._conf.onEnterRules ? new onEnter_1.OnEnterSupport(this._conf) : null);
this.comments = RichEditSupport._handleComments(this._conf);
this.characterPair = new characterPair_1.CharacterPairSupport(this._conf);
this.wordDefinition = this._conf.wordPattern || wordHelper_1.DEFAULT_WORD_REGEXP;
this.indentationRules = this._conf.indentationRules;
if (this._conf.indentationRules) {
this.indentRulesSupport = new indentRules_1.IndentRulesSupport(this._conf.indentationRules);
}
else {
this.indentRulesSupport = null;
}
this.foldingRules = this._conf.folding || {};
}
get brackets() {
if (!this._brackets && this._conf.brackets) {
this._brackets = new richEditBrackets_1.RichEditBrackets(this._languageIdentifier, this._conf.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);
}
static _handleComments(conf) {
let commentRule = conf.comments;
if (!commentRule) {
return null;
}
// comment configuration
let comments = {};
if (commentRule.lineComment) {
comments.lineCommentToken = commentRule.lineComment;
}
if (commentRule.blockComment) {
let [blockStart, blockEnd] = commentRule.blockComment;
comments.blockCommentStartToken = blockStart;
comments.blockCommentEndToken = blockEnd;
}
return comments;
}
}
exports.RichEditSupport = RichEditSupport;
class LanguageConfigurationChangeEvent {
constructor(languageIdentifier) {
this.languageIdentifier = languageIdentifier;
}
}
exports.LanguageConfigurationChangeEvent = LanguageConfigurationChangeEvent;
class LanguageConfigurationEntry {
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 LanguageConfigurationEntries {
constructor(languageIdentifier) {
this.languageIdentifier = languageIdentifier;
this._resolved = null;
this._entries = [];
this._order = 0;
this._resolved = null;
}
register(configuration, priority) {
const entry = new LanguageConfigurationEntry(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;
}
}
});
}
getRichEditSupport() {
if (!this._resolved) {
const config = this._resolve();
if (config) {
this._resolved = new RichEditSupport(this.languageIdentifier, config);
}
}
return this._resolved;
}
_resolve() {
if (this._entries.length === 0) {
return null;
}
this._entries.sort(LanguageConfigurationEntry.cmp);
const result = {};
for (const entry of this._entries) {
const conf = entry.configuration;
result.comments = conf.comments || result.comments;
result.brackets = conf.brackets || result.brackets;
result.wordPattern = conf.wordPattern || result.wordPattern;
result.indentationRules = conf.indentationRules || result.indentationRules;
result.onEnterRules = conf.onEnterRules || result.onEnterRules;
result.autoClosingPairs = conf.autoClosingPairs || result.autoClosingPairs;
result.surroundingPairs = conf.surroundingPairs || result.surroundingPairs;
result.autoCloseBefore = conf.autoCloseBefore || result.autoCloseBefore;
result.folding = conf.folding || result.folding;
result.__electricCharacterSupport = conf.__electricCharacterSupport || result.__electricCharacterSupport;
}
return result;
}
}
class LanguageConfigurationRegistryImpl {
constructor() {
this._entries2 = new Map();
this._onDidChange = new event_1.Emitter();
this.onDidChange = this._onDidChange.event;
}
/**
* @param priority Use a higher number for higher priority
*/
register(languageIdentifier, configuration, priority = 0) {
let entries = this._entries2.get(languageIdentifier.id);
if (!entries) {
entries = new LanguageConfigurationEntries(languageIdentifier);
this._entries2.set(languageIdentifier.id, entries);
}
const disposable = entries.register(configuration, priority);
this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageIdentifier));
return (0, lifecycle_1.toDisposable)(() => {
disposable.dispose();
this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageIdentifier));
});
}
_getRichEditSupport(languageId) {
const entries = this._entries2.get(languageId);
return entries ? entries.getRichEditSupport() : null;
}
getIndentationRules(languageId) {
const value = this._getRichEditSupport(languageId);
return value ? value.indentationRules || null : null;
}
// begin electricCharacter
_getElectricCharacterSupport(languageId) {
let value = this._getRichEditSupport(languageId);
if (!value) {
return null;
}
return value.electricCharacter || null;
}
getElectricCharacters(languageId) {
let electricCharacterSupport = this._getElectricCharacterSupport(languageId);
if (!electricCharacterSupport) {
return [];
}
return electricCharacterSupport.getElectricCharacters();
}
/**
* Should return opening bracket type to match indentation with
*/
onElectricCharacter(character, context, column) {
let scopedLineTokens = (0, supports_1.createScopedLineTokens)(context, column - 1);
let electricCharacterSupport = this._getElectricCharacterSupport(scopedLineTokens.languageId);
if (!electricCharacterSupport) {
return null;
}
return electricCharacterSupport.onElectricCharacter(character, scopedLineTokens, column - scopedLineTokens.firstCharOffset);
}
// end electricCharacter
getComments(languageId) {
let value = this._getRichEditSupport(languageId);
if (!value) {
return null;
}
return value.comments || null;
}
// begin characterPair
_getCharacterPairSupport(languageId) {
let value = this._getRichEditSupport(languageId);
if (!value) {
return null;
}
return value.characterPair || null;
}
getAutoClosingPairs(languageId) {
const characterPairSupport = this._getCharacterPairSupport(languageId);
return new languageConfiguration_1.AutoClosingPairs(characterPairSupport ? characterPairSupport.getAutoClosingPairs() : []);
}
getAutoCloseBeforeSet(languageId) {
let characterPairSupport = this._getCharacterPairSupport(languageId);
if (!characterPairSupport) {
return characterPair_1.CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED;
}
return characterPairSupport.getAutoCloseBeforeSet();
}
getSurroundingPairs(languageId) {
let characterPairSupport = this._getCharacterPairSupport(languageId);
if (!characterPairSupport) {
return [];
}
return characterPairSupport.getSurroundingPairs();
}
shouldAutoClosePair(autoClosingPair, context, column) {
const scopedLineTokens = (0, supports_1.createScopedLineTokens)(context, column - 1);
return characterPair_1.CharacterPairSupport.shouldAutoClosePair(autoClosingPair, scopedLineTokens, column - scopedLineTokens.firstCharOffset);
}
// end characterPair
getWordDefinition(languageId) {
let value = this._getRichEditSupport(languageId);
if (!value) {
return (0, wordHelper_1.ensureValidWordDefinition)(null);
}
return (0, wordHelper_1.ensureValidWordDefinition)(value.wordDefinition || null);
}
getFoldingRules(languageId) {
let value = this._getRichEditSupport(languageId);
if (!value) {
return {};
}
return value.foldingRules;
}
// begin Indent Rules
getIndentRulesSupport(languageId) {
let value = this._getRichEditSupport(languageId);
if (!value) {
return null;
}
return value.indentRulesSupport || null;
}
/**
* Get nearest preceiding 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
*/
getPrecedingValidLine(model, lineNumber, indentRulesSupport) {
let languageID = model.getLanguageIdAtPosition(lineNumber, 0);
if (lineNumber > 1) {
let lastLineNumber;
let resultLineNumber = -1;
for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) {
if (model.getLanguageIdAtPosition(lastLineNumber, 0) !== languageID) {
return resultLineNumber;
}
let text = model.getLineContent(lastLineNumber);
if (indentRulesSupport.shouldIgnore(text) || /^\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.
*/
getInheritIndentForLine(autoIndent, model, lineNumber, honorIntentialIndent = true) {
if (autoIndent < 4 /* Full */) {
return null;
}
const indentRulesSupport = this.getIndentRulesSupport(model.getLanguageIdentifier().id);
if (!indentRulesSupport) {
return null;
}
if (lineNumber <= 1) {
return {
indentation: '',
action: null
};
}
const precedingUnIgnoredLine = this.getPrecedingValidLine(model, lineNumber, indentRulesSupport);
if (precedingUnIgnoredLine < 0) {
return null;
}
else if (precedingUnIgnoredLine < 1) {
return {
indentation: '',
action: null
};
}
const precedingUnIgnoredLineContent = model.getLineContent(precedingUnIgnoredLine);
if (indentRulesSupport.shouldIncrease(precedingUnIgnoredLineContent) || indentRulesSupport.shouldIndentNextLine(precedingUnIgnoredLineContent)) {
return {
indentation: strings.getLeadingWhitespace(precedingUnIgnoredLineContent),
action: languageConfiguration_1.IndentAction.Indent,
line: precedingUnIgnoredLine
};
}
else if (indentRulesSupport.shouldDecrease(precedingUnIgnoredLineContent)) {
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 /* INCREASE_MASK */ | 2 /* DECREASE_MASK */)) &&
(previousLineIndentMetadata & 4 /* INDENT_NEXTLINE_MASK */)) {
let stopLine = 0;
for (let i = previousLine - 1; i > 0; i--) {
if (indentRulesSupport.shouldIndentNextLine(model.getLineContent(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--) {
const lineContent = model.getLineContent(i);
if (indentRulesSupport.shouldIncrease(lineContent)) {
return {
indentation: strings.getLeadingWhitespace(lineContent),
action: languageConfiguration_1.IndentAction.Indent,
line: i
};
}
else if (indentRulesSupport.shouldIndentNextLine(lineContent)) {
let stopLine = 0;
for (let j = i - 1; j > 0; j--) {
if (indentRulesSupport.shouldIndentNextLine(model.getLineContent(i))) {
continue;
}
stopLine = j;
break;
}
return {
indentation: strings.getLeadingWhitespace(model.getLineContent(stopLine + 1)),
action: null,
line: stopLine + 1
};
}
else if (indentRulesSupport.shouldDecrease(lineContent)) {
return {
indentation: strings.getLeadingWhitespace(lineContent),
action: null,
line: i
};
}
}
return {
indentation: strings.getLeadingWhitespace(model.getLineContent(1)),
action: null,
line: 1
};
}
}
}
getGoodIndentForLine(autoIndent, virtualModel, languageId, lineNumber, indentConverter) {
if (autoIndent < 4 /* Full */) {
return null;
}
const richEditSupport = this._getRichEditSupport(languageId);
if (!richEditSupport) {
return null;
}
const indentRulesSupport = this.getIndentRulesSupport(languageId);
if (!indentRulesSupport) {
return null;
}
const indent = this.getInheritIndentForLine(autoIndent, virtualModel, lineNumber);
const lineContent = virtualModel.getLineContent(lineNumber);
if (indent) {
const inheritLine = indent.line;
if (inheritLine !== undefined) {
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 (indentRulesSupport.shouldDecrease(lineContent)) {
indentation = indentConverter.unshiftIndent(indentation);
}
if (enterResult.appendText) {
indentation += enterResult.appendText;
}
return strings.getLeadingWhitespace(indentation);
}
}
if (indentRulesSupport.shouldDecrease(lineContent)) {
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;
}
getIndentForEnter(autoIndent, model, range, indentConverter) {
if (autoIndent < 4 /* Full */) {
return null;
}
model.forceTokenization(range.startLineNumber);
const lineTokens = model.getLineTokens(range.startLineNumber);
const scopedLineTokens = (0, supports_1.createScopedLineTokens)(lineTokens, range.startColumn - 1);
const scopedLineText = scopedLineTokens.getLineContent();
let embeddedLanguage = false;
let beforeEnterText;
if (scopedLineTokens.firstCharOffset > 0 && lineTokens.getLanguageId(0) !== scopedLineTokens.languageId) {
// we are in the embeded language content
embeddedLanguage = true; // if embeddedLanguage is true, then we don't touch the indentation of current line
beforeEnterText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset);
}
else {
beforeEnterText = lineTokens.getLineContent().substring(0, range.startColumn - 1);
}
let afterEnterText;
if (range.isEmpty()) {
afterEnterText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset);
}
else {
const endScopedLineTokens = this.getScopedLineTokens(model, range.endLineNumber, range.endColumn);
afterEnterText = endScopedLineTokens.getLineContent().substr(range.endColumn - 1 - scopedLineTokens.firstCharOffset);
}
const indentRulesSupport = this.getIndentRulesSupport(scopedLineTokens.languageId);
if (!indentRulesSupport) {
return null;
}
const beforeEnterResult = beforeEnterText;
const beforeEnterIndent = strings.getLeadingWhitespace(beforeEnterText);
const virtualModel = {
getLineTokens: (lineNumber) => {
return model.getLineTokens(lineNumber);
},
getLanguageIdentifier: () => {
return model.getLanguageIdentifier();
},
getLanguageIdAtPosition: (lineNumber, column) => {
return model.getLanguageIdAtPosition(lineNumber, column);
},
getLineContent: (lineNumber) => {
if (lineNumber === range.startLineNumber) {
return beforeEnterResult;
}
else {
return model.getLineContent(lineNumber);
}
}
};
const currentLineIndent = strings.getLeadingWhitespace(lineTokens.getLineContent());
const afterEnterAction = this.getInheritIndentForLine(autoIndent, virtualModel, range.startLineNumber + 1);
if (!afterEnterAction) {
const beforeEnter = embeddedLanguage ? currentLineIndent : beforeEnterIndent;
return {
beforeEnter: beforeEnter,
afterEnter: beforeEnter
};
}
let afterEnterIndent = embeddedLanguage ? currentLineIndent : afterEnterAction.indentation;
if (afterEnterAction.action === languageConfiguration_1.IndentAction.Indent) {
afterEnterIndent = indentConverter.shiftIndent(afterEnterIndent);
}
if (indentRulesSupport.shouldDecrease(afterEnterText)) {
afterEnterIndent = indentConverter.unshiftIndent(afterEnterIndent);
}
return {
beforeEnter: embeddedLanguage ? 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.
*/
getIndentActionForType(autoIndent, model, range, ch, indentConverter) {
if (autoIndent < 4 /* Full */) {
return null;
}
const scopedLineTokens = this.getScopedLineTokens(model, range.startLineNumber, range.startColumn);
if (scopedLineTokens.firstCharOffset) {
// this line has mixed languages and indentation rules will not work
return null;
}
const indentRulesSupport = this.getIndentRulesSupport(scopedLineTokens.languageId);
if (!indentRulesSupport) {
return null;
}
const scopedLineText = scopedLineTokens.getLineContent();
const beforeTypeText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset);
// selection support
let afterTypeText;
if (range.isEmpty()) {
afterTypeText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset);
}
else {
const endScopedLineTokens = this.getScopedLineTokens(model, range.endLineNumber, range.endColumn);
afterTypeText = endScopedLineTokens.getLineContent().substr(range.endColumn - 1 - scopedLineTokens.firstCharOffset);
}
// 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(beforeTypeText + afterTypeText) && indentRulesSupport.shouldDecrease(beforeTypeText + ch + afterTypeText)) {
// after typing `ch`, the content matches decreaseIndentPattern, we should adjust the indent to a good manner.
// 1. Get inherited indent action
const r = this.getInheritIndentForLine(autoIndent, model, range.startLineNumber, false);
if (!r) {
return null;
}
let indentation = r.indentation;
if (r.action !== languageConfiguration_1.IndentAction.Indent) {
indentation = indentConverter.unshiftIndent(indentation);
}
return indentation;
}
return null;
}
getIndentMetadata(model, lineNumber) {
const indentRulesSupport = this.getIndentRulesSupport(model.getLanguageIdentifier().id);
if (!indentRulesSupport) {
return null;
}
if (lineNumber < 1 || lineNumber > model.getLineCount()) {
return null;
}
return indentRulesSupport.getIndentMetadata(model.getLineContent(lineNumber));
}
// end Indent Rules
// begin onEnter
getEnterAction(autoIndent, model, range) {
const scopedLineTokens = this.getScopedLineTokens(model, range.startLineNumber, range.startColumn);
const richEditSupport = this._getRichEditSupport(scopedLineTokens.languageId);
if (!richEditSupport) {
return null;
}
const scopedLineText = scopedLineTokens.getLineContent();
const beforeEnterText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset);
// selection support
let afterEnterText;
if (range.isEmpty()) {
afterEnterText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset);
}
else {
const endScopedLineTokens = this.getScopedLineTokens(model, range.endLineNumber, range.endColumn);
afterEnterText = endScopedLineTokens.getLineContent().substr(range.endColumn - 1 - scopedLineTokens.firstCharOffset);
}
let previousLineText = '';
if (range.startLineNumber > 1 && scopedLineTokens.firstCharOffset === 0) {
// This is not the first line and the entire line belongs to this mode
const oneLineAboveScopedLineTokens = this.getScopedLineTokens(model, range.startLineNumber - 1);
if (oneLineAboveScopedLineTokens.languageId === scopedLineTokens.languageId) {
// The line above ends with text belonging to the same mode
previousLineText = oneLineAboveScopedLineTokens.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 = this.getIndentationAtPosition(model, range.startLineNumber, range.startColumn);
if (removeText) {
indentation = indentation.substring(0, indentation.length - removeText);
}
return {
indentAction: indentAction,
appendText: appendText,
removeText: removeText,
indentation: indentation
};
}
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;
}
getScopedLineTokens(model, lineNumber, columnNumber) {
model.forceTokenization(lineNumber);
const lineTokens = model.getLineTokens(lineNumber);
const column = (typeof columnNumber === 'undefined' ? model.getLineMaxColumn(lineNumber) - 1 : columnNumber - 1);
return (0, supports_1.createScopedLineTokens)(lineTokens, column);
}
// end onEnter
getBracketsSupport(languageId) {
const value = this._getRichEditSupport(languageId);
if (!value) {
return null;
}
return value.brackets || null;
}
}
exports.LanguageConfigurationRegistryImpl = LanguageConfigurationRegistryImpl;
exports.LanguageConfigurationRegistry = new LanguageConfigurationRegistryImpl();
});
/*---------------------------------------------------------------------------------------------
* 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/common/modes/supports/tokenization*/], __M([0/*require*/,1/*exports*/,29/*vs/base/common/color*/]), function (require, exports, color_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateTokensCSSForColorMap = exports.ThemeTrieElement = exports.ThemeTrieElementRule = exports.strcmp = exports.toStandardTokenType = exports.TokenTheme = exports.ColorMap = exports.parseTokenTheme = exports.ParsedTokenThemeRule = void 0;
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 [];
}
let result = [], resultLen = 0;
for (let i = 0, len = source.length; i < len; i++) {
let entry = source[i];
let fontStyle = -1 /* NotSet */;
if (typeof entry.fontStyle === 'string') {
fontStyle = 0 /* None */;
let segments = entry.fontStyle.split(' ');
for (let j = 0, lenJ = segments.length; j < lenJ; j++) {
let segment = segments[j];
switch (segment) {
case 'italic':
fontStyle = fontStyle | 1 /* Italic */;
break;
case 'bold':
fontStyle = fontStyle | 2 /* Bold */;
break;
case 'underline':
fontStyle = fontStyle | 4 /* Underline */;
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;
}
exports.parseTokenTheme = parseTokenTheme;
/**
* Resolve rules (i.e. inheritance).
*/
function resolveParsedTokenThemeRules(parsedThemeRules, customTokenColors) {
// Sort rules lexicographically, and then by index if necessary
parsedThemeRules.sort((a, b) => {
let r = strcmp(a.token, b.token);
if (r !== 0) {
return r;
}
return a.index - b.index;
});
// Determine defaults
let defaultFontStyle = 0 /* None */;
let defaultForeground = '000000';
let defaultBackground = 'ffffff';
while (parsedThemeRules.length >= 1 && parsedThemeRules[0].token === '') {
let incomingDefaults = parsedThemeRules.shift();
if (incomingDefaults.fontStyle !== -1 /* NotSet */) {
defaultFontStyle = incomingDefaults.fontStyle;
}
if (incomingDefaults.foreground !== null) {
defaultForeground = incomingDefaults.foreground;
}
if (incomingDefaults.background !== null) {
defaultBackground = incomingDefaults.background;
}
}
let colorMap = new ColorMap();
// start with token colors from custom token themes
for (let color of customTokenColors) {
colorMap.getId(color);
}
let foregroundColorId = colorMap.getId(defaultForeground);
let backgroundColorId = colorMap.getId(defaultBackground);
let defaults = new ThemeTrieElementRule(defaultFontStyle, foregroundColorId, backgroundColorId);
let root = new ThemeTrieElement(defaults);
for (let i = 0, len = parsedThemeRules.length; i < len; i++) {
let 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 {
constructor(colorMap, root) {
this._colorMap = colorMap;
this._root = root;
this._cache = new Map();
}
static createFromRawTokenTheme(source, customTokenColors) {
return this.createFromParsedTokenTheme(parseTokenTheme(source), customTokenColors);
}
static createFromParsedTokenTheme(source, customTokenColors) {
return resolveParsedTokenThemeRules(source, customTokenColors);
}
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') {
let rule = this._match(token);
let standardToken = toStandardTokenType(token);
result = (rule.metadata
| (standardToken << 8 /* TOKEN_TYPE_OFFSET */)) >>> 0;
this._cache.set(token, result);
}
return (result
| (languageId << 0 /* LANGUAGEID_OFFSET */)) >>> 0;
}
}
exports.TokenTheme = TokenTheme;
const STANDARD_TOKEN_TYPE_REGEXP = /\b(comment|string|regex|regexp)\b/;
function toStandardTokenType(tokenType) {
let m = tokenType.match(STANDARD_TOKEN_TYPE_REGEXP);
if (!m) {
return 0 /* Other */;
}
switch (m[1]) {
case 'comment':
return 1 /* Comment */;
case 'string':
return 2 /* String */;
case 'regex':
return 4 /* RegEx */;
case 'regexp':
return 4 /* RegEx */;
}
throw new Error('Unexpected match for standard token type!');
}
exports.toStandardTokenType = toStandardTokenType;
function strcmp(a, b) {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
exports.strcmp = strcmp;
class ThemeTrieElementRule {
constructor(fontStyle, foreground, background) {
this._themeTrieElementRuleBrand = undefined;
this._fontStyle = fontStyle;
this._foreground = foreground;
this._background = background;
this.metadata = ((this._fontStyle << 11 /* FONT_STYLE_OFFSET */)
| (this._foreground << 14 /* FOREGROUND_OFFSET */)
| (this._background << 23 /* BACKGROUND_OFFSET */)) >>> 0;
}
clone() {
return new ThemeTrieElementRule(this._fontStyle, this._foreground, this._background);
}
acceptOverwrite(fontStyle, foreground, background) {
if (fontStyle !== -1 /* NotSet */) {
this._fontStyle = fontStyle;
}
if (foreground !== 0 /* None */) {
this._foreground = foreground;
}
if (background !== 0 /* None */) {
this._background = background;
}
this.metadata = ((this._fontStyle << 11 /* FONT_STYLE_OFFSET */)
| (this._foreground << 14 /* FOREGROUND_OFFSET */)
| (this._background << 23 /* 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;
}
let 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') {
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;
}
let 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) {
let rules = [];
for (let i = 1, len = colorMap.length; i < len; i++) {
let 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; }');
return rules.join('\n');
}
exports.generateTokensCSSForColorMap = generateTokensCSSForColorMap;
});
/*---------------------------------------------------------------------------------------------
* 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/common/modes/tokenizationRegistry*/], __M([0/*require*/,1/*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.TokenizationRegistryImpl = void 0;
class TokenizationRegistryImpl {
constructor() {
this._map = new Map();
this._promises = new Map();
this._onDidChange = new event_1.Emitter();
this.onDidChange = this._onDidChange.event;
this._colorMap = null;
}
fire(languages) {
this._onDidChange.fire({
changedLanguages: languages,
changedColorMap: false
});
}
register(language, support) {
this._map.set(language, support);
this.fire([language]);
return (0, lifecycle_1.toDisposable)(() => {
if (this._map.get(language) !== support) {
return;
}
this._map.delete(language);
this.fire([language]);
});
}
registerPromise(language, supportPromise) {
let registration = null;
let isDisposed = false;
this._promises.set(language, supportPromise.then(support => {
this._promises.delete(language);
if (isDisposed || !support) {
return;
}
registration = this.register(language, support);
}));
return (0, lifecycle_1.toDisposable)(() => {
isDisposed = true;
if (registration) {
registration.dispose();
}
});
}
getPromise(language) {
const support = this.get(language);
if (support) {
return Promise.resolve(support);
}
const promise = this._promises.get(language);
if (promise) {
return promise.then(_ => this.get(language));
}
return null;
}
get(language) {
return (this._map.get(language) || null);
}
setColorMap(colorMap) {
this._colorMap = colorMap;
this._onDidChange.fire({
changedLanguages: Array.from(this._map.keys()),
changedColorMap: true
});
}
getColorMap() {
return this._colorMap;
}
getDefaultBackground() {
if (this._colorMap && this._colorMap.length > 2 /* DefaultBackground */) {
return this._colorMap[2 /* DefaultBackground */];
}
return null;
}
}
exports.TokenizationRegistryImpl = TokenizationRegistryImpl;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[391/*vs/editor/common/services/semanticTokensDto*/], __M([0/*require*/,1/*exports*/,103/*vs/base/common/buffer*/,17/*vs/base/common/platform*/]), function (require, exports, buffer_1, platform) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodeSemanticTokensDto = void 0;
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 /* Full */;
dest[offset++] = semanticTokens.data.length;
dest.set(semanticTokens.data, offset);
offset += semanticTokens.data.length;
}
else {
dest[offset++] = 2 /* 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);
}
exports.encodeSemanticTokensDto = encodeSemanticTokensDto;
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[174/*vs/editor/common/standalone/standaloneEnums*/], __M([0/*require*/,1/*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.SelectionDirection = exports.ScrollbarVisibility = exports.ScrollType = exports.RenderMinimap = exports.RenderLineNumbersType = exports.OverviewRulerLane = exports.OverlayWidgetPositionPreference = exports.MouseTargetType = exports.MinimapPosition = exports.MarkerTag = exports.MarkerSeverity = exports.KeyCode = exports.InlineCompletionTriggerKind = exports.InlayHintKind = exports.IndentAction = 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.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 || (exports.AccessibilitySupport = {}));
var CompletionItemInsertTextRule;
(function (CompletionItemInsertTextRule) {
/**
* 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 || (exports.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 || (exports.CompletionItemKind = {}));
var CompletionItemTag;
(function (CompletionItemTag) {
CompletionItemTag[CompletionItemTag["Deprecated"] = 1] = "Deprecated";
})(CompletionItemTag = exports.CompletionItemTag || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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["autoClosingBrackets"] = 5] = "autoClosingBrackets";
EditorOption[EditorOption["autoClosingDelete"] = 6] = "autoClosingDelete";
EditorOption[EditorOption["autoClosingOvertype"] = 7] = "autoClosingOvertype";
EditorOption[EditorOption["autoClosingQuotes"] = 8] = "autoClosingQuotes";
EditorOption[EditorOption["autoIndent"] = 9] = "autoIndent";
EditorOption[EditorOption["automaticLayout"] = 10] = "automaticLayout";
EditorOption[EditorOption["autoSurround"] = 11] = "autoSurround";
EditorOption[EditorOption["codeLens"] = 12] = "codeLens";
EditorOption[EditorOption["codeLensFontFamily"] = 13] = "codeLensFontFamily";
EditorOption[EditorOption["codeLensFontSize"] = 14] = "codeLensFontSize";
EditorOption[EditorOption["colorDecorators"] = 15] = "colorDecorators";
EditorOption[EditorOption["columnSelection"] = 16] = "columnSelection";
EditorOption[EditorOption["comments"] = 17] = "comments";
EditorOption[EditorOption["contextmenu"] = 18] = "contextmenu";
EditorOption[EditorOption["copyWithSyntaxHighlighting"] = 19] = "copyWithSyntaxHighlighting";
EditorOption[EditorOption["cursorBlinking"] = 20] = "cursorBlinking";
EditorOption[EditorOption["cursorSmoothCaretAnimation"] = 21] = "cursorSmoothCaretAnimation";
EditorOption[EditorOption["cursorStyle"] = 22] = "cursorStyle";
EditorOption[EditorOption["cursorSurroundingLines"] = 23] = "cursorSurroundingLines";
EditorOption[EditorOption["cursorSurroundingLinesStyle"] = 24] = "cursorSurroundingLinesStyle";
EditorOption[EditorOption["cursorWidth"] = 25] = "cursorWidth";
EditorOption[EditorOption["disableLayerHinting"] = 26] = "disableLayerHinting";
EditorOption[EditorOption["disableMonospaceOptimizations"] = 27] = "disableMonospaceOptimizations";
EditorOption[EditorOption["domReadOnly"] = 28] = "domReadOnly";
EditorOption[EditorOption["dragAndDrop"] = 29] = "dragAndDrop";
EditorOption[EditorOption["emptySelectionClipboard"] = 30] = "emptySelectionClipboard";
EditorOption[EditorOption["extraEditorClassName"] = 31] = "extraEditorClassName";
EditorOption[EditorOption["fastScrollSensitivity"] = 32] = "fastScrollSensitivity";
EditorOption[EditorOption["find"] = 33] = "find";
EditorOption[EditorOption["fixedOverflowWidgets"] = 34] = "fixedOverflowWidgets";
EditorOption[EditorOption["folding"] = 35] = "folding";
EditorOption[EditorOption["foldingStrategy"] = 36] = "foldingStrategy";
EditorOption[EditorOption["foldingHighlight"] = 37] = "foldingHighlight";
EditorOption[EditorOption["foldingImportsByDefault"] = 38] = "foldingImportsByDefault";
EditorOption[EditorOption["unfoldOnClickAfterEndOfLine"] = 39] = "unfoldOnClickAfterEndOfLine";
EditorOption[EditorOption["fontFamily"] = 40] = "fontFamily";
EditorOption[EditorOption["fontInfo"] = 41] = "fontInfo";
EditorOption[EditorOption["fontLigatures"] = 42] = "fontLigatures";
EditorOption[EditorOption["fontSize"] = 43] = "fontSize";
EditorOption[EditorOption["fontWeight"] = 44] = "fontWeight";
EditorOption[EditorOption["formatOnPaste"] = 45] = "formatOnPaste";
EditorOption[EditorOption["formatOnType"] = 46] = "formatOnType";
EditorOption[EditorOption["glyphMargin"] = 47] = "glyphMargin";
EditorOption[EditorOption["gotoLocation"] = 48] = "gotoLocation";
EditorOption[EditorOption["hideCursorInOverviewRuler"] = 49] = "hideCursorInOverviewRuler";
EditorOption[EditorOption["highlightActiveIndentGuide"] = 50] = "highlightActiveIndentGuide";
EditorOption[EditorOption["hover"] = 51] = "hover";
EditorOption[EditorOption["inDiffEditor"] = 52] = "inDiffEditor";
EditorOption[EditorOption["inlineSuggest"] = 53] = "inlineSuggest";
EditorOption[EditorOption["letterSpacing"] = 54] = "letterSpacing";
EditorOption[EditorOption["lightbulb"] = 55] = "lightbulb";
EditorOption[EditorOption["lineDecorationsWidth"] = 56] = "lineDecorationsWidth";
EditorOption[EditorOption["lineHeight"] = 57] = "lineHeight";
EditorOption[EditorOption["lineNumbers"] = 58] = "lineNumbers";
EditorOption[EditorOption["lineNumbersMinChars"] = 59] = "lineNumbersMinChars";
EditorOption[EditorOption["linkedEditing"] = 60] = "linkedEditing";
EditorOption[EditorOption["links"] = 61] = "links";
EditorOption[EditorOption["matchBrackets"] = 62] = "matchBrackets";
EditorOption[EditorOption["minimap"] = 63] = "minimap";
EditorOption[EditorOption["mouseStyle"] = 64] = "mouseStyle";
EditorOption[EditorOption["mouseWheelScrollSensitivity"] = 65] = "mouseWheelScrollSensitivity";
EditorOption[EditorOption["mouseWheelZoom"] = 66] = "mouseWheelZoom";
EditorOption[EditorOption["multiCursorMergeOverlapping"] = 67] = "multiCursorMergeOverlapping";
EditorOption[EditorOption["multiCursorModifier"] = 68] = "multiCursorModifier";
EditorOption[EditorOption["multiCursorPaste"] = 69] = "multiCursorPaste";
EditorOption[EditorOption["occurrencesHighlight"] = 70] = "occurrencesHighlight";
EditorOption[EditorOption["overviewRulerBorder"] = 71] = "overviewRulerBorder";
EditorOption[EditorOption["overviewRulerLanes"] = 72] = "overviewRulerLanes";
EditorOption[EditorOption["padding"] = 73] = "padding";
EditorOption[EditorOption["parameterHints"] = 74] = "parameterHints";
EditorOption[EditorOption["peekWidgetDefaultFocus"] = 75] = "peekWidgetDefaultFocus";
EditorOption[EditorOption["definitionLinkOpensInPeek"] = 76] = "definitionLinkOpensInPeek";
EditorOption[EditorOption["quickSuggestions"] = 77] = "quickSuggestions";
EditorOption[EditorOption["quickSuggestionsDelay"] = 78] = "quickSuggestionsDelay";
EditorOption[EditorOption["readOnly"] = 79] = "readOnly";
EditorOption[EditorOption["renameOnType"] = 80] = "renameOnType";
EditorOption[EditorOption["renderControlCharacters"] = 81] = "renderControlCharacters";
EditorOption[EditorOption["renderIndentGuides"] = 82] = "renderIndentGuides";
EditorOption[EditorOption["renderFinalNewline"] = 83] = "renderFinalNewline";
EditorOption[EditorOption["renderLineHighlight"] = 84] = "renderLineHighlight";
EditorOption[EditorOption["renderLineHighlightOnlyWhenFocus"] = 85] = "renderLineHighlightOnlyWhenFocus";
EditorOption[EditorOption["renderValidationDecorations"] = 86] = "renderValidationDecorations";
EditorOption[EditorOption["renderWhitespace"] = 87] = "renderWhitespace";
EditorOption[EditorOption["revealHorizontalRightPadding"] = 88] = "revealHorizontalRightPadding";
EditorOption[EditorOption["roundedSelection"] = 89] = "roundedSelection";
EditorOption[EditorOption["rulers"] = 90] = "rulers";
EditorOption[EditorOption["scrollbar"] = 91] = "scrollbar";
EditorOption[EditorOption["scrollBeyondLastColumn"] = 92] = "scrollBeyondLastColumn";
EditorOption[EditorOption["scrollBeyondLastLine"] = 93] = "scrollBeyondLastLine";
EditorOption[EditorOption["scrollPredominantAxis"] = 94] = "scrollPredominantAxis";
EditorOption[EditorOption["selectionClipboard"] = 95] = "selectionClipboard";
EditorOption[EditorOption["selectionHighlight"] = 96] = "selectionHighlight";
EditorOption[EditorOption["selectOnLineNumbers"] = 97] = "selectOnLineNumbers";
EditorOption[EditorOption["showFoldingControls"] = 98] = "showFoldingControls";
EditorOption[EditorOption["showUnused"] = 99] = "showUnused";
EditorOption[EditorOption["snippetSuggestions"] = 100] = "snippetSuggestions";
EditorOption[EditorOption["smartSelect"] = 101] = "smartSelect";
EditorOption[EditorOption["smoothScrolling"] = 102] = "smoothScrolling";
EditorOption[EditorOption["stickyTabStops"] = 103] = "stickyTabStops";
EditorOption[EditorOption["stopRenderingLineAfter"] = 104] = "stopRenderingLineAfter";
EditorOption[EditorOption["suggest"] = 105] = "suggest";
EditorOption[EditorOption["suggestFontSize"] = 106] = "suggestFontSize";
EditorOption[EditorOption["suggestLineHeight"] = 107] = "suggestLineHeight";
EditorOption[EditorOption["suggestOnTriggerCharacters"] = 108] = "suggestOnTriggerCharacters";
EditorOption[EditorOption["suggestSelection"] = 109] = "suggestSelection";
EditorOption[EditorOption["tabCompletion"] = 110] = "tabCompletion";
EditorOption[EditorOption["tabIndex"] = 111] = "tabIndex";
EditorOption[EditorOption["unusualLineTerminators"] = 112] = "unusualLineTerminators";
EditorOption[EditorOption["useShadowDOM"] = 113] = "useShadowDOM";
EditorOption[EditorOption["useTabStops"] = 114] = "useTabStops";
EditorOption[EditorOption["wordSeparators"] = 115] = "wordSeparators";
EditorOption[EditorOption["wordWrap"] = 116] = "wordWrap";
EditorOption[EditorOption["wordWrapBreakAfterCharacters"] = 117] = "wordWrapBreakAfterCharacters";
EditorOption[EditorOption["wordWrapBreakBeforeCharacters"] = 118] = "wordWrapBreakBeforeCharacters";
EditorOption[EditorOption["wordWrapColumn"] = 119] = "wordWrapColumn";
EditorOption[EditorOption["wordWrapOverride1"] = 120] = "wordWrapOverride1";
EditorOption[EditorOption["wordWrapOverride2"] = 121] = "wordWrapOverride2";
EditorOption[EditorOption["wrappingIndent"] = 122] = "wrappingIndent";
EditorOption[EditorOption["wrappingStrategy"] = 123] = "wrappingStrategy";
EditorOption[EditorOption["showDeprecated"] = 124] = "showDeprecated";
EditorOption[EditorOption["inlayHints"] = 125] = "inlayHints";
EditorOption[EditorOption["editorClassName"] = 126] = "editorClassName";
EditorOption[EditorOption["pixelRatio"] = 127] = "pixelRatio";
EditorOption[EditorOption["tabFocusMode"] = 128] = "tabFocusMode";
EditorOption[EditorOption["layoutInfo"] = 129] = "layoutInfo";
EditorOption[EditorOption["wrappingInfo"] = 130] = "wrappingInfo";
})(EditorOption = exports.EditorOption || (exports.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 || (exports.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 || (exports.EndOfLineSequence = {}));
/**
* 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 || (exports.IndentAction = {}));
var InlayHintKind;
(function (InlayHintKind) {
InlayHintKind[InlayHintKind["Other"] = 0] = "Other";
InlayHintKind[InlayHintKind["Type"] = 1] = "Type";
InlayHintKind[InlayHintKind["Parameter"] = 2] = "Parameter";
})(InlayHintKind = exports.InlayHintKind || (exports.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 || (exports.InlineCompletionTriggerKind = {}));
/**
* 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["KEY_0"] = 21] = "KEY_0";
KeyCode[KeyCode["KEY_1"] = 22] = "KEY_1";
KeyCode[KeyCode["KEY_2"] = 23] = "KEY_2";
KeyCode[KeyCode["KEY_3"] = 24] = "KEY_3";
KeyCode[KeyCode["KEY_4"] = 25] = "KEY_4";
KeyCode[KeyCode["KEY_5"] = 26] = "KEY_5";
KeyCode[KeyCode["KEY_6"] = 27] = "KEY_6";
KeyCode[KeyCode["KEY_7"] = 28] = "KEY_7";
KeyCode[KeyCode["KEY_8"] = 29] = "KEY_8";
KeyCode[KeyCode["KEY_9"] = 30] = "KEY_9";
KeyCode[KeyCode["KEY_A"] = 31] = "KEY_A";
KeyCode[KeyCode["KEY_B"] = 32] = "KEY_B";
KeyCode[KeyCode["KEY_C"] = 33] = "KEY_C";
KeyCode[KeyCode["KEY_D"] = 34] = "KEY_D";
KeyCode[KeyCode["KEY_E"] = 35] = "KEY_E";
KeyCode[KeyCode["KEY_F"] = 36] = "KEY_F";
KeyCode[KeyCode["KEY_G"] = 37] = "KEY_G";
KeyCode[KeyCode["KEY_H"] = 38] = "KEY_H";
KeyCode[KeyCode["KEY_I"] = 39] = "KEY_I";
KeyCode[KeyCode["KEY_J"] = 40] = "KEY_J";
KeyCode[KeyCode["KEY_K"] = 41] = "KEY_K";
KeyCode[KeyCode["KEY_L"] = 42] = "KEY_L";
KeyCode[KeyCode["KEY_M"] = 43] = "KEY_M";
KeyCode[KeyCode["KEY_N"] = 44] = "KEY_N";
KeyCode[KeyCode["KEY_O"] = 45] = "KEY_O";
KeyCode[KeyCode["KEY_P"] = 46] = "KEY_P";
KeyCode[KeyCode["KEY_Q"] = 47] = "KEY_Q";
KeyCode[KeyCode["KEY_R"] = 48] = "KEY_R";
KeyCode[KeyCode["KEY_S"] = 49] = "KEY_S";
KeyCode[KeyCode["KEY_T"] = 50] = "KEY_T";
KeyCode[KeyCode["KEY_U"] = 51] = "KEY_U";
KeyCode[KeyCode["KEY_V"] = 52] = "KEY_V";
KeyCode[KeyCode["KEY_W"] = 53] = "KEY_W";
KeyCode[KeyCode["KEY_X"] = 54] = "KEY_X";
KeyCode[KeyCode["KEY_Y"] = 55] = "KEY_Y";
KeyCode[KeyCode["KEY_Z"] = 56] = "KEY_Z";
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["NumLock"] = 78] = "NumLock";
KeyCode[KeyCode["ScrollLock"] = 79] = "ScrollLock";
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ';:' key
*/
KeyCode[KeyCode["US_SEMICOLON"] = 80] = "US_SEMICOLON";
/**
* For any country/region, the '+' key
* For the US standard keyboard, the '=+' key
*/
KeyCode[KeyCode["US_EQUAL"] = 81] = "US_EQUAL";
/**
* For any country/region, the ',' key
* For the US standard keyboard, the ',<' key
*/
KeyCode[KeyCode["US_COMMA"] = 82] = "US_COMMA";
/**
* For any country/region, the '-' key
* For the US standard keyboard, the '-_' key
*/
KeyCode[KeyCode["US_MINUS"] = 83] = "US_MINUS";
/**
* For any country/region, the '.' key
* For the US standard keyboard, the '.>' key
*/
KeyCode[KeyCode["US_DOT"] = 84] = "US_DOT";
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '/?' key
*/
KeyCode[KeyCode["US_SLASH"] = 85] = "US_SLASH";
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '`~' key
*/
KeyCode[KeyCode["US_BACKTICK"] = 86] = "US_BACKTICK";
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '[{' key
*/
KeyCode[KeyCode["US_OPEN_SQUARE_BRACKET"] = 87] = "US_OPEN_SQUARE_BRACKET";
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '\|' key
*/
KeyCode[KeyCode["US_BACKSLASH"] = 88] = "US_BACKSLASH";
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ']}' key
*/
KeyCode[KeyCode["US_CLOSE_SQUARE_BRACKET"] = 89] = "US_CLOSE_SQUARE_BRACKET";
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ''"' key
*/
KeyCode[KeyCode["US_QUOTE"] = 90] = "US_QUOTE";
/**
* Used for miscellaneous characters; it can vary by keyboard.
*/
KeyCode[KeyCode["OEM_8"] = 91] = "OEM_8";
/**
* Either the angle bracket key or the backslash key on the RT 102-key keyboard.
*/
KeyCode[KeyCode["OEM_102"] = 92] = "OEM_102";
KeyCode[KeyCode["NUMPAD_0"] = 93] = "NUMPAD_0";
KeyCode[KeyCode["NUMPAD_1"] = 94] = "NUMPAD_1";
KeyCode[KeyCode["NUMPAD_2"] = 95] = "NUMPAD_2";
KeyCode[KeyCode["NUMPAD_3"] = 96] = "NUMPAD_3";
KeyCode[KeyCode["NUMPAD_4"] = 97] = "NUMPAD_4";
KeyCode[KeyCode["NUMPAD_5"] = 98] = "NUMPAD_5";
KeyCode[KeyCode["NUMPAD_6"] = 99] = "NUMPAD_6";
KeyCode[KeyCode["NUMPAD_7"] = 100] = "NUMPAD_7";
KeyCode[KeyCode["NUMPAD_8"] = 101] = "NUMPAD_8";
KeyCode[KeyCode["NUMPAD_9"] = 102] = "NUMPAD_9";
KeyCode[KeyCode["NUMPAD_MULTIPLY"] = 103] = "NUMPAD_MULTIPLY";
KeyCode[KeyCode["NUMPAD_ADD"] = 104] = "NUMPAD_ADD";
KeyCode[KeyCode["NUMPAD_SEPARATOR"] = 105] = "NUMPAD_SEPARATOR";
KeyCode[KeyCode["NUMPAD_SUBTRACT"] = 106] = "NUMPAD_SUBTRACT";
KeyCode[KeyCode["NUMPAD_DECIMAL"] = 107] = "NUMPAD_DECIMAL";
KeyCode[KeyCode["NUMPAD_DIVIDE"] = 108] = "NUMPAD_DIVIDE";
/**
* Cover all key codes when IME is processing input.
*/
KeyCode[KeyCode["KEY_IN_COMPOSITION"] = 109] = "KEY_IN_COMPOSITION";
KeyCode[KeyCode["ABNT_C1"] = 110] = "ABNT_C1";
KeyCode[KeyCode["ABNT_C2"] = 111] = "ABNT_C2";
/**
* Placed last to cover the length of the enum.
* Please do not depend on this value!
*/
KeyCode[KeyCode["MAX_VALUE"] = 112] = "MAX_VALUE";
})(KeyCode = exports.KeyCode || (exports.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 || (exports.MarkerSeverity = {}));
var MarkerTag;
(function (MarkerTag) {
MarkerTag[MarkerTag["Unnecessary"] = 1] = "Unnecessary";
MarkerTag[MarkerTag["Deprecated"] = 2] = "Deprecated";
})(MarkerTag = exports.MarkerTag || (exports.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 || (exports.MinimapPosition = {}));
/**
* 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 || (exports.MouseTargetType = {}));
/**
* 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 || (exports.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 || (exports.OverviewRulerLane = {}));
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 || (exports.RenderLineNumbersType = {}));
var RenderMinimap;
(function (RenderMinimap) {
RenderMinimap[RenderMinimap["None"] = 0] = "None";
RenderMinimap[RenderMinimap["Text"] = 1] = "Text";
RenderMinimap[RenderMinimap["Blocks"] = 2] = "Blocks";
})(RenderMinimap = exports.RenderMinimap || (exports.RenderMinimap = {}));
var ScrollType;
(function (ScrollType) {
ScrollType[ScrollType["Smooth"] = 0] = "Smooth";
ScrollType[ScrollType["Immediate"] = 1] = "Immediate";
})(ScrollType = exports.ScrollType || (exports.ScrollType = {}));
var ScrollbarVisibility;
(function (ScrollbarVisibility) {
ScrollbarVisibility[ScrollbarVisibility["Auto"] = 1] = "Auto";
ScrollbarVisibility[ScrollbarVisibility["Hidden"] = 2] = "Hidden";
ScrollbarVisibility[ScrollbarVisibility["Visible"] = 3] = "Visible";
})(ScrollbarVisibility = exports.ScrollbarVisibility || (exports.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 || (exports.SelectionDirection = {}));
var SignatureHelpTriggerKind;
(function (SignatureHelpTriggerKind) {
SignatureHelpTriggerKind[SignatureHelpTriggerKind["Invoke"] = 1] = "Invoke";
SignatureHelpTriggerKind[SignatureHelpTriggerKind["TriggerCharacter"] = 2] = "TriggerCharacter";
SignatureHelpTriggerKind[SignatureHelpTriggerKind["ContentChange"] = 3] = "ContentChange";
})(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.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 || (exports.SymbolKind = {}));
var SymbolTag;
(function (SymbolTag) {
SymbolTag[SymbolTag["Deprecated"] = 1] = "Deprecated";
})(SymbolTag = exports.SymbolTag || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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[222/*vs/editor/common/standalone/standaloneBase*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,6/*vs/base/common/event*/,41/*vs/base/common/keyCodes*/,24/*vs/base/common/uri*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,134/*vs/editor/common/core/token*/,174/*vs/editor/common/standalone/standaloneEnums*/]), function (require, exports, cancellation_1, event_1, keyCodes_1, uri_1, position_1, range_1, selection_1, token_1, standaloneEnums) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMonacoBaseAPI = exports.KeyMod = void 0;
class KeyMod {
static chord(firstPart, secondPart) {
return (0, keyCodes_1.KeyChord)(firstPart, secondPart);
}
}
exports.KeyMod = KeyMod;
KeyMod.CtrlCmd = 2048 /* CtrlCmd */;
KeyMod.Shift = 1024 /* Shift */;
KeyMod.Alt = 512 /* Alt */;
KeyMod.WinCtrl = 256 /* WinCtrl */;
function createMonacoBaseAPI() {
return {
editor: undefined,
languages: undefined,
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: token_1.Token
};
}
exports.createMonacoBaseAPI = 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[223/*vs/editor/common/view/overviewZoneManager*/], __M([0/*require*/,1/*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, color) {
this._overviewRulerZoneBrand = undefined;
this.startLineNumber = startLineNumber;
this.endLineNumber = endLineNumber;
this.color = color;
this._colorZone = null;
}
static compare(a, b) {
if (a.color === b.color) {
if (a.startLineNumber === b.startLineNumber) {
return a.endLineNumber - b.endLineNumber;
}
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); // @perf
const totalHeight = Math.floor(this.getCanvasHeight()); // @perf
const outerHeight = Math.floor(this._outerHeight); // @perf
const heightRatio = totalHeight / outerHeight;
const halfMinimumHeight = Math.floor(4 /* MINIMUM_HEIGHT */ * this._pixelRatio / 2);
let 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 y1 = Math.floor(heightRatio * (this._getVerticalOffsetForLine(zone.startLineNumber)));
const y2 = Math.floor(heightRatio * (this._getVerticalOffsetForLine(zone.endLineNumber) + lineHeight));
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[113/*vs/editor/common/view/renderingContext*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VisibleRanges = exports.HorizontalPosition = 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) {
return this._viewLayout.getVerticalOffsetForLineNumber(lineNumber);
}
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) {
this.outsideRenderedLine = outsideRenderedLine;
this.lineNumber = lineNumber;
this.ranges = ranges;
}
}
exports.LineVisibleRanges = LineVisibleRanges;
class HorizontalRange {
constructor(left, width) {
this.left = Math.round(left);
this.width = Math.round(width);
}
toString() {
return `[${this.left},${this.width}]`;
}
}
exports.HorizontalRange = HorizontalRange;
class HorizontalPosition {
constructor(outsideRenderedLine, left) {
this.outsideRenderedLine = outsideRenderedLine;
this.left = Math.round(left);
}
}
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[392/*vs/editor/browser/viewParts/lines/rangeUtil*/], __M([0/*require*/,1/*exports*/,113/*vs/editor/common/view/renderingContext*/]), function (require, exports, renderingContext_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RangeUtil = void 0;
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;
}
}
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 [new renderingContext_1.HorizontalRange(ranges[0].left, ranges[0].width)];
}
ranges.sort(FloatHorizontalRange.compare);
let result = [], resultLen = 0;
let prevLeft = ranges[0].left;
let prevWidth = ranges[0].width;
for (let i = 1, len = ranges.length; i < len; i++) {
const range = ranges[i];
const myLeft = range.left;
const myWidth = range.width;
if (prevLeft + prevWidth + 0.9 /* account for browser's rounding errors*/ >= myLeft) {
prevWidth = Math.max(prevWidth, myLeft + myWidth - prevLeft);
}
else {
result[resultLen++] = new renderingContext_1.HorizontalRange(prevLeft, prevWidth);
prevLeft = myLeft;
prevWidth = myWidth;
}
}
result[resultLen++] = new renderingContext_1.HorizontalRange(prevLeft, prevWidth);
return result;
}
static _createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft) {
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 FloatHorizontalRange(Math.max(0, clientRect.left - clientRectDeltaLeft), clientRect.width);
}
return this._mergeAdjacentRanges(result);
}
static readHorizontalRanges(domNode, startChildIndex, startOffset, endChildIndex, endOffset, clientRectDeltaLeft, endNode) {
// 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();
return this._createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft);
}
// 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 /* 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 /* MAX_SAFE_SMALL_INTEGER */;
}
if (!endElement && endOffset === 0 && endChildIndex > 0) {
endElement = domNode.children[endChildIndex - 1].firstChild;
endOffset = 1073741824 /* 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, endNode);
return this._createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft);
}
}
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[393/*vs/editor/common/view/viewContext*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ViewContext = exports.EditorTheme = void 0;
class EditorTheme {
constructor(theme) {
this._theme = theme;
}
get type() {
return this._theme.type;
}
update(theme) {
this._theme = theme;
}
getColor(color) {
return this._theme.getColor(color);
}
}
exports.EditorTheme = EditorTheme;
class ViewContext {
constructor(configuration, theme, model) {
this.configuration = configuration;
this.theme = new EditorTheme(theme);
this.model = model;
this.viewLayout = model.viewLayout;
}
addEventHandler(eventHandler) {
this.model.addViewEventHandler(eventHandler);
}
removeEventHandler(eventHandler) {
this.model.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[175/*vs/editor/common/view/viewEvents*/], __M([0/*require*/,1/*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 /* ViewCompositionStart */;
}
}
exports.ViewCompositionStartEvent = ViewCompositionStartEvent;
class ViewCompositionEndEvent {
constructor() {
this.type = 1 /* ViewCompositionEnd */;
}
}
exports.ViewCompositionEndEvent = ViewCompositionEndEvent;
class ViewConfigurationChangedEvent {
constructor(source) {
this.type = 2 /* ViewConfigurationChanged */;
this._source = source;
}
hasChanged(id) {
return this._source.hasChanged(id);
}
}
exports.ViewConfigurationChangedEvent = ViewConfigurationChangedEvent;
class ViewCursorStateChangedEvent {
constructor(selections, modelSelections) {
this.type = 3 /* ViewCursorStateChanged */;
this.selections = selections;
this.modelSelections = modelSelections;
}
}
exports.ViewCursorStateChangedEvent = ViewCursorStateChangedEvent;
class ViewDecorationsChangedEvent {
constructor(source) {
this.type = 4 /* ViewDecorationsChanged */;
if (source) {
this.affectsMinimap = source.affectsMinimap;
this.affectsOverviewRuler = source.affectsOverviewRuler;
}
else {
this.affectsMinimap = true;
this.affectsOverviewRuler = true;
}
}
}
exports.ViewDecorationsChangedEvent = ViewDecorationsChangedEvent;
class ViewFlushedEvent {
constructor() {
this.type = 5 /* ViewFlushed */;
// Nothing to do
}
}
exports.ViewFlushedEvent = ViewFlushedEvent;
class ViewFocusChangedEvent {
constructor(isFocused) {
this.type = 6 /* ViewFocusChanged */;
this.isFocused = isFocused;
}
}
exports.ViewFocusChangedEvent = ViewFocusChangedEvent;
class ViewLanguageConfigurationEvent {
constructor() {
this.type = 7 /* ViewLanguageConfigurationChanged */;
}
}
exports.ViewLanguageConfigurationEvent = ViewLanguageConfigurationEvent;
class ViewLineMappingChangedEvent {
constructor() {
this.type = 8 /* ViewLineMappingChanged */;
// Nothing to do
}
}
exports.ViewLineMappingChangedEvent = ViewLineMappingChangedEvent;
class ViewLinesChangedEvent {
constructor(fromLineNumber, toLineNumber) {
this.type = 9 /* ViewLinesChanged */;
this.fromLineNumber = fromLineNumber;
this.toLineNumber = toLineNumber;
}
}
exports.ViewLinesChangedEvent = ViewLinesChangedEvent;
class ViewLinesDeletedEvent {
constructor(fromLineNumber, toLineNumber) {
this.type = 10 /* ViewLinesDeleted */;
this.fromLineNumber = fromLineNumber;
this.toLineNumber = toLineNumber;
}
}
exports.ViewLinesDeletedEvent = ViewLinesDeletedEvent;
class ViewLinesInsertedEvent {
constructor(fromLineNumber, toLineNumber) {
this.type = 11 /* ViewLinesInserted */;
this.fromLineNumber = fromLineNumber;
this.toLineNumber = toLineNumber;
}
}
exports.ViewLinesInsertedEvent = ViewLinesInsertedEvent;
class ViewRevealRangeRequestEvent {
constructor(source, range, selections, verticalType, revealHorizontal, scrollType) {
this.type = 12 /* ViewRevealRangeRequest */;
this.source = source;
this.range = range;
this.selections = selections;
this.verticalType = verticalType;
this.revealHorizontal = revealHorizontal;
this.scrollType = scrollType;
}
}
exports.ViewRevealRangeRequestEvent = ViewRevealRangeRequestEvent;
class ViewScrollChangedEvent {
constructor(source) {
this.type = 13 /* 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() {
this.type = 14 /* ViewThemeChanged */;
}
}
exports.ViewThemeChangedEvent = ViewThemeChangedEvent;
class ViewTokensChangedEvent {
constructor(ranges) {
this.type = 15 /* ViewTokensChanged */;
this.ranges = ranges;
}
}
exports.ViewTokensChangedEvent = ViewTokensChangedEvent;
class ViewTokensColorsChangedEvent {
constructor() {
this.type = 16 /* ViewTokensColorsChanged */;
// Nothing to do
}
}
exports.ViewTokensColorsChangedEvent = ViewTokensColorsChangedEvent;
class ViewZonesChangedEvent {
constructor() {
this.type = 17 /* 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[136/*vs/editor/common/viewLayout/lineDecorations*/], __M([0/*require*/,1/*exports*/,8/*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 [];
}
let result = [], 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 /* Regular */ || d.type === 3 /* 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 [];
}
let 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 /* Before */
? 2 /* PSEUDO_BEFORE */
: d.type === 2 /* After */
? 4 /* 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 /* 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[394/*vs/editor/common/viewLayout/linesLayout*/], __M([0/*require*/,1/*exports*/,8/*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 {
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) => {
let 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) {
this._checkPendingChanges();
lineNumber = lineNumber | 0;
let previousLinesHeight;
if (lineNumber > 1) {
previousLinesHeight = this._lineHeight * (lineNumber - 1);
}
else {
previousLinesHeight = 0;
}
const previousWhitespacesHeight = this.getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber);
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
};
}
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 [];
}
let 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;
LinesLayout.INSTANCE_COUNT = 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[114/*vs/editor/common/viewLayout/viewLineRenderer*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,83/*vs/editor/common/core/stringBuilder*/,136/*vs/editor/common/viewLayout/lineDecorations*/]), function (require, exports, strings, stringBuilder_1, lineDecorations_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderViewLine2 = exports.RenderLineOutput2 = exports.renderViewLine = exports.RenderLineOutput = exports.CharacterMapping = exports.DomPosition = exports.RenderLineInput = exports.LineRange = void 0;
class LinePart {
constructor(endIndex, type, metadata) {
this._linePartBrand = undefined;
this.endIndex = endIndex;
this.type = type;
this.metadata = metadata;
}
isWhitespace() {
return (this.metadata & 1 /* IS_WHITESPACE_MASK */ ? true : false);
}
isPseudoAfter() {
return (this.metadata & 4 /* PSEUDO_AFTER_MASK */ ? true : false);
}
}
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 /* All */
: renderWhitespace === 'boundary'
? 1 /* Boundary */
: renderWhitespace === 'selection'
? 2 /* Selection */
: renderWhitespace === 'trailing'
? 3 /* Trailing */
: 0 /* 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 {
constructor(length, partCount) {
this.length = length;
this._data = new Uint32Array(this.length);
this._absoluteOffsets = new Uint32Array(this.length);
}
static getPartIndex(partData) {
return (partData & 4294901760 /* PART_INDEX_MASK */) >>> 16 /* PART_INDEX_OFFSET */;
}
static getCharIndex(partData) {
return (partData & 65535 /* CHAR_INDEX_MASK */) >>> 0 /* CHAR_INDEX_OFFSET */;
}
setColumnInfo(column, partIndex, charIndex, partAbsoluteOffset) {
const partData = ((partIndex << 16 /* PART_INDEX_OFFSET */)
| (charIndex << 0 /* CHAR_INDEX_OFFSET */)) >>> 0;
this._data[column - 1] = partData;
this._absoluteOffsets[column - 1] = partAbsoluteOffset + charIndex;
}
getAbsoluteOffset(column) {
if (this._absoluteOffsets.length === 0) {
// No characters on this line
return 0;
}
return this._absoluteOffsets[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;
}
let searchEntry = ((partIndex << 16 /* PART_INDEX_OFFSET */)
| (charIndex << 0 /* CHAR_INDEX_OFFSET */)) >>> 0;
let min = 0;
let max = this.length - 1;
while (min + 1 < max) {
let mid = ((min + max) >>> 1);
let midEntry = this._data[mid];
if (midEntry === searchEntry) {
return mid;
}
else if (midEntry > searchEntry) {
max = mid;
}
else {
min = mid;
}
}
if (min === max) {
return min;
}
let minEntry = this._data[min];
let maxEntry = this._data[max];
if (minEntry === searchEntry) {
return min;
}
if (maxEntry === searchEntry) {
return max;
}
let minPartIndex = CharacterMapping.getPartIndex(minEntry);
let minCharIndex = CharacterMapping.getCharIndex(minEntry);
let maxPartIndex = CharacterMapping.getPartIndex(maxEntry);
let maxCharIndex;
if (minPartIndex !== maxPartIndex) {
// sitting between parts
maxCharIndex = partLength;
}
else {
maxCharIndex = CharacterMapping.getCharIndex(maxEntry);
}
let minEntryDistance = charIndex - minCharIndex;
let 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.appendASCIIString(`<span>`);
let beforeCount = 0;
let afterCount = 0;
let containsForeignElements = 0 /* None */;
for (const lineDecoration of input.lineDecorations) {
if (lineDecoration.type === 1 /* Before */ || lineDecoration.type === 2 /* After */) {
sb.appendASCIIString(`<span class="`);
sb.appendASCIIString(lineDecoration.className);
sb.appendASCIIString(`"></span>`);
if (lineDecoration.type === 1 /* Before */) {
containsForeignElements |= 1 /* Before */;
beforeCount++;
}
if (lineDecoration.type === 2 /* After */) {
containsForeignElements |= 2 /* After */;
afterCount++;
}
}
}
sb.appendASCIIString(`</span>`);
const characterMapping = new CharacterMapping(1, beforeCount + afterCount);
characterMapping.setColumnInfo(1, beforeCount, 0, 0);
return new RenderLineOutput(characterMapping, false, containsForeignElements);
}
// completely empty line
sb.appendASCIIString('<span><span></span></span>');
return new RenderLineOutput(new CharacterMapping(0, 0), false, 0 /* None */);
}
return _renderLine(resolveRenderLineInput(input), sb);
}
exports.renderViewLine = renderViewLine;
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) {
let sb = (0, stringBuilder_1.createStringBuilder)(10000);
let out = renderViewLine(input, sb);
return new RenderLineOutput2(out.characterMapping, sb.build(), out.containsRTL, out.containsForeignElements);
}
exports.renderViewLine2 = renderViewLine2;
class ResolvedRenderLineInput {
constructor(fontIsMonospace, canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, 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.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 len;
if (input.stopRenderingLineAfter !== -1 && input.stopRenderingLineAfter < lineContent.length) {
isOverflowing = true;
len = input.stopRenderingLineAfter;
}
else {
isOverflowing = false;
len = lineContent.length;
}
let tokens = transformAndRemoveOverflowing(input.lineTokens, input.fauxIndentLength, len);
if (input.renderWhitespace === 4 /* All */ ||
input.renderWhitespace === 1 /* Boundary */ ||
(input.renderWhitespace === 2 /* Selection */ && !!input.selectionsOnLine) ||
input.renderWhitespace === 3 /* Trailing */) {
tokens = _applyRenderWhitespace(input, lineContent, len, tokens);
}
let containsForeignElements = 0 /* 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 /* RegularAffectingLetterSpacing */) {
// Pretend there are foreign elements... although not 100% accurate.
containsForeignElements |= 1 /* Before */;
}
else if (lineDecoration.type === 1 /* Before */) {
containsForeignElements |= 1 /* Before */;
}
else if (lineDecoration.type === 2 /* After */) {
containsForeignElements |= 2 /* 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, 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(tokens, fauxIndentLength, len) {
let result = [], resultLen = 0;
// The faux indent part of the line should have no token type
if (fauxIndentLength > 0) {
result[resultLen++] = new LinePart(fauxIndentLength, '', 0);
}
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) {
result[resultLen++] = new LinePart(len, type, 0);
break;
}
result[resultLen++] = new LinePart(endIndex, type, 0);
}
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;
let result = [], 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 /* LongToken */ < tokenEndIndex) {
const tokenType = token.type;
const tokenMetadata = token.metadata;
let lastSpaceOffset = -1;
let currTokenStart = lastTokenEndIndex;
for (let j = lastTokenEndIndex; j < tokenEndIndex; j++) {
if (lineContent.charCodeAt(j) === 32 /* Space */) {
lastSpaceOffset = j;
}
if (lastSpaceOffset !== -1 && j - currTokenStart >= 50 /* LongToken */) {
// Split at `lastSpaceOffset` + 1
result[resultLen++] = new LinePart(lastSpaceOffset + 1, tokenType, tokenMetadata);
currTokenStart = lastSpaceOffset + 1;
lastSpaceOffset = -1;
}
}
if (currTokenStart !== tokenEndIndex) {
result[resultLen++] = new LinePart(tokenEndIndex, tokenType, tokenMetadata);
}
}
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;
let diff = (tokenEndIndex - lastTokenEndIndex);
if (diff > 50 /* LongToken */) {
const tokenType = token.type;
const tokenMetadata = token.metadata;
const piecesCount = Math.ceil(diff / 50 /* LongToken */);
for (let j = 1; j < piecesCount; j++) {
let pieceEndIndex = lastTokenEndIndex + (j * 50 /* LongToken */);
result[resultLen++] = new LinePart(pieceEndIndex, tokenType, tokenMetadata);
}
result[resultLen++] = new LinePart(tokenEndIndex, tokenType, tokenMetadata);
}
else {
result[resultLen++] = token;
}
lastTokenEndIndex = tokenEndIndex;
}
}
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 /* Boundary */);
const onlyTrailing = (input.renderWhitespace === 3 /* Trailing */);
const generateLinePartForEachWhitespace = (input.renderSpaceWidth !== input.spaceWidth);
let result = [], resultLen = 0;
let tokenIndex = 0;
let tokenType = tokens[tokenIndex].type;
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 /* Tab */) {
// a tab character is rendered both in all and boundary cases
isInWhitespace = true;
}
else if (chCode === 32 /* 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 /* Null */);
isInWhitespace = (nextChCode === 32 /* Space */ || nextChCode === 9 /* 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 (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(i, 'mtkw', 1 /* IS_WHITESPACE */);
}
}
else {
result[resultLen++] = new LinePart(charIndex, 'mtkw', 1 /* IS_WHITESPACE */);
}
tmpIndent = tmpIndent % tabSize;
}
}
else {
// was in regular token
if (charIndex === tokenEndIndex || (isInWhitespace && charIndex > fauxIndentLength)) {
result[resultLen++] = new LinePart(charIndex, tokenType, 0);
tmpIndent = tmpIndent % tabSize;
}
}
if (chCode === 9 /* 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;
tokenEndIndex = tokens[tokenIndex].endIndex;
}
else {
break;
}
}
}
let generateWhitespace = false;
if (wasInWhitespace) {
// was in whitespace token
if (continuesWithWrappedLine && onlyBoundary) {
let lastCharCode = (len > 0 ? lineContent.charCodeAt(len - 1) : 0 /* Null */);
let prevCharCode = (len > 1 ? lineContent.charCodeAt(len - 2) : 0 /* Null */);
let isSingleTrailingSpace = (lastCharCode === 32 /* Space */ && (prevCharCode !== 32 /* Space */ && prevCharCode !== 9 /* 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(i, 'mtkw', 1 /* IS_WHITESPACE */);
}
}
else {
result[resultLen++] = new LinePart(len, 'mtkw', 1 /* IS_WHITESPACE */);
}
}
else {
result[resultLen++] = new LinePart(len, tokenType, 0);
}
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;
let result = [], resultLen = 0, 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;
while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset < tokenEndIndex) {
const lineDecoration = lineDecorations[lineDecorationIndex];
if (lineDecoration.startOffset > lastResultEndIndex) {
lastResultEndIndex = lineDecoration.startOffset;
result[resultLen++] = new LinePart(lastResultEndIndex, tokenType, tokenMetadata);
}
if (lineDecoration.endOffset + 1 <= tokenEndIndex) {
// This line decoration ends before this token ends
lastResultEndIndex = lineDecoration.endOffset + 1;
result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + ' ' + lineDecoration.className, tokenMetadata | lineDecoration.metadata);
lineDecorationIndex++;
}
else {
// This line decoration continues on to the next token
lastResultEndIndex = tokenEndIndex;
result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + ' ' + lineDecoration.className, tokenMetadata | lineDecoration.metadata);
break;
}
}
if (tokenEndIndex > lastResultEndIndex) {
lastResultEndIndex = tokenEndIndex;
result[resultLen++] = new LinePart(lastResultEndIndex, tokenType, tokenMetadata);
}
}
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(lastResultEndIndex, lineDecoration.className, lineDecoration.metadata);
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 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;
let partDisplacement = 0;
let prevPartContentCnt = 0;
let partAbsoluteOffset = 0;
if (containsRTL) {
sb.appendASCIIString('<span dir="ltr">');
}
else {
sb.appendASCIIString('<span>');
}
for (let partIndex = 0, tokensLen = parts.length; partIndex < tokensLen; partIndex++) {
partAbsoluteOffset += prevPartContentCnt;
const part = parts[partIndex];
const partEndIndex = part.endIndex;
const partType = part.type;
const partRendersWhitespace = (renderWhitespace !== 0 /* None */ && part.isWhitespace());
const partRendersWhitespaceWithWidth = partRendersWhitespace && !fontIsMonospace && (partType === 'mtkw' /*only whitespace*/ || !containsForeignElements);
const partIsEmptyAndHasPseudoAfter = (charIndex === partEndIndex && part.isPseudoAfter());
charOffsetInPart = 0;
sb.appendASCIIString('<span class="');
sb.appendASCIIString(partRendersWhitespaceWithWidth ? 'mtkz' : partType);
sb.appendASCII(34 /* DoubleQuote */);
if (partRendersWhitespace) {
let partContentCnt = 0;
{
let _charIndex = charIndex;
let _visibleColumn = visibleColumn;
for (; _charIndex < partEndIndex; _charIndex++) {
const charCode = lineContent.charCodeAt(_charIndex);
const charWidth = (charCode === 9 /* Tab */ ? (tabSize - (_visibleColumn % tabSize)) : 1) | 0;
partContentCnt += charWidth;
if (_charIndex >= fauxIndentLength) {
_visibleColumn += charWidth;
}
}
}
if (partRendersWhitespaceWithWidth) {
sb.appendASCIIString(' style="width:');
sb.appendASCIIString(String(spaceWidth * partContentCnt));
sb.appendASCIIString('px"');
}
sb.appendASCII(62 /* GreaterThan */);
for (; charIndex < partEndIndex; charIndex++) {
characterMapping.setColumnInfo(charIndex + 1, partIndex - partDisplacement, charOffsetInPart, partAbsoluteOffset);
partDisplacement = 0;
const charCode = lineContent.charCodeAt(charIndex);
let charWidth;
if (charCode === 9 /* Tab */) {
charWidth = (tabSize - (visibleColumn % tabSize)) | 0;
if (!canUseHalfwidthRightwardsArrow || charWidth > 1) {
sb.write1(0x2192); // RIGHTWARDS ARROW
}
else {
sb.write1(0xFFEB); // HALFWIDTH RIGHTWARDS ARROW
}
for (let space = 2; space <= charWidth; space++) {
sb.write1(0xA0); // &nbsp;
}
}
else { // must be CharCode.Space
charWidth = 1;
sb.write1(renderSpaceCharCode); // &middot; or word separator middle dot
}
charOffsetInPart += charWidth;
if (charIndex >= fauxIndentLength) {
visibleColumn += charWidth;
}
}
prevPartContentCnt = partContentCnt;
}
else {
let partContentCnt = 0;
sb.appendASCII(62 /* GreaterThan */);
for (; charIndex < partEndIndex; charIndex++) {
characterMapping.setColumnInfo(charIndex + 1, partIndex - partDisplacement, charOffsetInPart, partAbsoluteOffset);
partDisplacement = 0;
const charCode = lineContent.charCodeAt(charIndex);
let producedCharacters = 1;
let charWidth = 1;
switch (charCode) {
case 9 /* Tab */:
producedCharacters = (tabSize - (visibleColumn % tabSize));
charWidth = producedCharacters;
for (let space = 1; space <= producedCharacters; space++) {
sb.write1(0xA0); // &nbsp;
}
break;
case 32 /* Space */:
sb.write1(0xA0); // &nbsp;
break;
case 60 /* LessThan */:
sb.appendASCIIString('&lt;');
break;
case 62 /* GreaterThan */:
sb.appendASCIIString('&gt;');
break;
case 38 /* Ampersand */:
sb.appendASCIIString('&amp;');
break;
case 0 /* Null */:
if (renderControlCharacters) {
// See https://unicode-table.com/en/blocks/control-pictures/
sb.write1(9216);
}
else {
sb.appendASCIIString('&#00;');
}
break;
case 65279 /* UTF8_BOM */:
case 8232 /* LINE_SEPARATOR */:
case 8233 /* PARAGRAPH_SEPARATOR */:
case 133 /* NEXT_LINE */:
sb.write1(0xFFFD);
break;
default:
if (strings.isFullWidthCharacter(charCode)) {
charWidth++;
}
// See https://unicode-table.com/en/blocks/control-pictures/
if (renderControlCharacters && charCode < 32) {
sb.write1(9216 + charCode);
}
else if (renderControlCharacters && charCode === 127) {
// DEL
sb.write1(9249);
}
else {
sb.write1(charCode);
}
}
charOffsetInPart += producedCharacters;
partContentCnt += producedCharacters;
if (charIndex >= fauxIndentLength) {
visibleColumn += charWidth;
}
}
prevPartContentCnt = partContentCnt;
}
if (partIsEmptyAndHasPseudoAfter) {
partDisplacement++;
}
else {
partDisplacement = 0;
}
if (charIndex >= len && !lastCharacterMappingDefined && part.isPseudoAfter()) {
lastCharacterMappingDefined = true;
characterMapping.setColumnInfo(charIndex + 1, partIndex, charOffsetInPart, partAbsoluteOffset);
}
sb.appendASCIIString('</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, partAbsoluteOffset);
}
if (isOverflowing) {
sb.appendASCIIString('<span>&hellip;</span>');
}
sb.appendASCIIString('</span>');
return new RenderLineOutput(characterMapping, containsRTL, containsForeignElements);
}
});
/*---------------------------------------------------------------------------------------------
* 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/editor/common/viewLayout/viewLinesViewportData*/], __M([0/*require*/,1/*exports*/,3/*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.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.getViewLineRenderingData(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[224/*vs/editor/common/viewModel/prefixSumComputer*/], __M([0/*require*/,1/*exports*/,129/*vs/base/common/uint*/]), function (require, exports, uint_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PrefixSumComputer = exports.PrefixSumIndexOfResult = void 0;
class PrefixSumIndexOfResult {
constructor(index, remainder) {
this._prefixSumIndexOfResultBrand = undefined;
this.index = index;
this.remainder = remainder;
}
}
exports.PrefixSumIndexOfResult = PrefixSumIndexOfResult;
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;
}
changeValue(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;
}
let 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);
}
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); //@perf
// 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;
});
/*---------------------------------------------------------------------------------------------
* 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/common/model/mirrorTextModel*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,13/*vs/editor/common/core/position*/,224/*vs/editor/common/viewModel/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.changeValue(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;
}
let 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
let 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[397/*vs/editor/common/services/editorSimpleWorker*/], __M([0/*require*/,1/*exports*/,128/*vs/base/common/diff/diff*/,17/*vs/base/common/platform*/,24/*vs/base/common/uri*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,377/*vs/editor/common/diff/diffComputer*/,396/*vs/editor/common/model/mirrorTextModel*/,135/*vs/editor/common/model/wordHelper*/,383/*vs/editor/common/modes/linkComputer*/,386/*vs/editor/common/modes/supports/inplaceReplaceSupport*/,222/*vs/editor/common/standalone/standaloneBase*/,20/*vs/base/common/types*/,81/*vs/base/common/stopwatch*/]), function (require, exports, diff_1, platform_1, uri_1, position_1, range_1, diffComputer_1, mirrorTextModel_1, wordHelper_1, linkComputer_1, inplaceReplaceSupport_1, standaloneBase_1, types, stopwatch_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.create = exports.EditorSimpleWorker = void 0;
/**
* @internal
*/
class MirrorModel extends mirrorTextModel_1.MirrorTextModel {
get uri() {
return this._uri;
}
get eol() {
return this._eol;
}
getValue() {
return this.getText();
}
getLinesContent() {
return this._lines.slice(0);
}
getLineCount() {
return this._lines.length;
}
getLineContent(lineNumber) {
return this._lines[lineNumber - 1];
}
getWordAtPosition(position, wordDefinition) {
let 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) {
let content = this._lines[lineNumber - 1];
let ranges = this._wordenize(content, wordDefinition);
let 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);
}
let lineEnding = this._eol;
let startLineIndex = range.startLineNumber - 1;
let endLineIndex = range.endLineNumber - 1;
let 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();
let out = this._lineStarts.getIndexOf(offset);
let 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 {
let 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 };
}
}
}
/**
* @internal
*/
class EditorSimpleWorker {
constructor(host, foreignModuleFactory) {
this._host = host;
this._models = Object.create(null);
this._foreignModuleFactory = foreignModuleFactory;
this._foreignModule = null;
}
dispose() {
this._models = Object.create(null);
}
_getModel(uri) {
return this._models[uri];
}
_getModels() {
let 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(strURL, e) {
if (!this._models[strURL]) {
return;
}
let model = this._models[strURL];
model.onEvents(e);
}
acceptRemovedModel(strURL) {
if (!this._models[strURL]) {
return;
}
delete this._models[strURL];
}
// ---- BEGIN diff --------------------------------------------------------------------------
computeDiff(originalUrl, modifiedUrl, ignoreTrimWhitespace, maxComputationTime) {
return __awaiter(this, void 0, void 0, function* () {
const original = this._getModel(originalUrl);
const modified = this._getModel(modifiedUrl);
if (!original || !modified) {
return null;
}
const originalLines = original.getLinesContent();
const modifiedLines = modified.getLinesContent();
const diffComputer = new diffComputer_1.DiffComputer(originalLines, modifiedLines, {
shouldComputeCharChanges: true,
shouldPostProcessCharChanges: true,
shouldIgnoreTrimWhitespace: ignoreTrimWhitespace,
shouldMakePrettyDiff: true,
maxComputationTime: maxComputationTime
});
const diffResult = diffComputer.computeDiff();
const identical = (diffResult.changes.length > 0 ? false : this._modelsAreIdentical(original, modified));
return {
quitEarly: diffResult.quitEarly,
identical: identical,
changes: diffResult.changes
};
});
}
_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;
}
computeMoreMinimalEdits(modelUrl, edits) {
return __awaiter(this, void 0, void 0, function* () {
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
let aRng = a.range ? 0 : 1;
let bRng = b.range ? 0 : 1;
return aRng - bRng;
});
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, false);
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 ---------------------------------------------------------------
computeLinks(modelUrl) {
return __awaiter(this, void 0, void 0, function* () {
let model = this._getModel(modelUrl);
if (!model) {
return null;
}
return (0, linkComputer_1.computeLinks)(model);
});
}
textualSuggest(modelUrls, leadingWord, wordDef, wordDefFlags) {
return __awaiter(this, void 0, void 0, function* () {
const sw = new stopwatch_1.StopWatch(true);
const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
const seen = new Set();
outer: for (let url of modelUrls) {
const model = this._getModel(url);
if (!model) {
continue;
}
for (let 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 --
computeWordRanges(modelUrl, range, wordDef, wordDefFlags) {
return __awaiter(this, void 0, void 0, function* () {
let 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++) {
let 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
navigateValueSet(modelUrl, range, up, wordDef, wordDefFlags) {
return __awaiter(this, void 0, void 0, function* () {
let model = this._getModel(modelUrl);
if (!model) {
return null;
}
let wordDefRegExp = new RegExp(wordDef, wordDefFlags);
if (range.startColumn === range.endColumn) {
range = {
startLineNumber: range.startLineNumber,
startColumn: range.startColumn,
endLineNumber: range.endLineNumber,
endColumn: range.endColumn + 1
};
}
let selectionText = model.getValueInRange(range);
let wordRange = model.getWordAtPosition({ lineNumber: range.startLineNumber, column: range.startColumn }, wordDefRegExp);
if (!wordRange) {
return null;
}
let word = model.getValueInRange(wordRange);
let result = inplaceReplaceSupport_1.BasicInplaceReplace.INSTANCE.navigateValueSet(range, selectionText, wordRange, word, up);
return result;
});
}
// ---- BEGIN foreign module support --------------------------------------------------------------------------
loadForeignModule(moduleId, createData, foreignHostMethods) {
const proxyMethodRequest = (method, args) => {
return this._host.fhr(method, args);
};
const foreignHost = types.createProxyObject(foreignHostMethods, proxyMethodRequest);
let ctx = {
host: foreignHost,
getMirrorModels: () => {
return this._getModels();
}
};
if (this._foreignModuleFactory) {
this._foreignModule = this._foreignModuleFactory(ctx, createData);
// static foreing module
return Promise.resolve(types.getAllMethodNames(this._foreignModule));
}
// ESM-comment-begin
return new Promise((resolve, reject) => {
require([moduleId], (foreignModule) => {
this._foreignModule = foreignModule.create(ctx, createData);
resolve(types.getAllMethodNames(this._foreignModule));
}, reject);
});
// ESM-comment-end
// ESM-uncomment-begin
// return Promise.reject(new Error(`Unexpected usage`));
// ESM-uncomment-end
}
// 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;
// ---- END diff --------------------------------------------------------------------------
// ---- BEGIN minimal edits ---------------------------------------------------------------
EditorSimpleWorker._diffLimit = 100000;
// ---- BEGIN suggest --------------------------------------------------------------------------
EditorSimpleWorker._suggestionsLimit = 10000;
/**
* Called on the worker side
* @internal
*/
function create(host) {
return new EditorSimpleWorker(host, null);
}
exports.create = create;
if (typeof importScripts === 'function') {
// Running in a web worker
platform_1.globals.monaco = (0, standaloneBase_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[115/*vs/editor/common/viewModel/viewEventHandler*/], __M([0/*require*/,1/*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++) {
let e = events[i];
switch (e.type) {
case 0 /* ViewCompositionStart */:
if (this.onCompositionStart(e)) {
shouldRender = true;
}
break;
case 1 /* ViewCompositionEnd */:
if (this.onCompositionEnd(e)) {
shouldRender = true;
}
break;
case 2 /* ViewConfigurationChanged */:
if (this.onConfigurationChanged(e)) {
shouldRender = true;
}
break;
case 3 /* ViewCursorStateChanged */:
if (this.onCursorStateChanged(e)) {
shouldRender = true;
}
break;
case 4 /* ViewDecorationsChanged */:
if (this.onDecorationsChanged(e)) {
shouldRender = true;
}
break;
case 5 /* ViewFlushed */:
if (this.onFlushed(e)) {
shouldRender = true;
}
break;
case 6 /* ViewFocusChanged */:
if (this.onFocusChanged(e)) {
shouldRender = true;
}
break;
case 7 /* ViewLanguageConfigurationChanged */:
if (this.onLanguageConfigurationChanged(e)) {
shouldRender = true;
}
break;
case 8 /* ViewLineMappingChanged */:
if (this.onLineMappingChanged(e)) {
shouldRender = true;
}
break;
case 9 /* ViewLinesChanged */:
if (this.onLinesChanged(e)) {
shouldRender = true;
}
break;
case 10 /* ViewLinesDeleted */:
if (this.onLinesDeleted(e)) {
shouldRender = true;
}
break;
case 11 /* ViewLinesInserted */:
if (this.onLinesInserted(e)) {
shouldRender = true;
}
break;
case 12 /* ViewRevealRangeRequest */:
if (this.onRevealRangeRequest(e)) {
shouldRender = true;
}
break;
case 13 /* ViewScrollChanged */:
if (this.onScrollChanged(e)) {
shouldRender = true;
}
break;
case 15 /* ViewTokensChanged */:
if (this.onTokensChanged(e)) {
shouldRender = true;
}
break;
case 14 /* ViewThemeChanged */:
if (this.onThemeChanged(e)) {
shouldRender = true;
}
break;
case 16 /* ViewTokensColorsChanged */:
if (this.onTokensColorsChanged(e)) {
shouldRender = true;
}
break;
case 17 /* 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[97/*vs/editor/browser/view/dynamicViewOverlay*/], __M([0/*require*/,1/*exports*/,115/*vs/editor/common/viewModel/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[47/*vs/editor/browser/view/viewPart*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,115/*vs/editor/common/viewModel/viewEventHandler*/]), function (require, exports, fastDomNode_1, 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) {
if (target instanceof fastDomNode_1.FastDomNode) {
target.setAttribute('data-mprt', String(partId));
}
else {
target.setAttribute('data-mprt', String(partId));
}
}
static read(target) {
const r = target.getAttribute('data-mprt');
if (r === null) {
return 0 /* None */;
}
return parseInt(r, 10);
}
static collect(child, stopAt) {
let result = [], resultLen = 0;
while (child && child !== document.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[398/*vs/editor/browser/viewParts/contentWidgets/contentWidgets*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,47/*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 Coordinate {
constructor(top, left) {
this._coordinateBrand = undefined;
this.top = top;
this.left = left;
}
}
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 /* 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 /* 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) {
const keys = Object.keys(this._widgets);
for (const widgetId of keys) {
this._widgets[widgetId].onLineMappingChanged(e);
}
return true;
}
onLinesChanged(e) {
return true;
}
onLinesDeleted(e) {
return true;
}
onLinesInserted(e) {
return true;
}
onScrollChanged(e) {
return true;
}
onZonesChanged(e) {
return true;
}
// ---- end view event handlers
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, range, preference) {
const myWidget = this._widgets[widget.getId()];
myWidget.setPosition(range, preference);
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.parentNode.removeChild(domNode);
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._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(129 /* layoutInfo */);
this._fixedOverflowWidgets = options.get(34 /* fixedOverflowWidgets */);
this._contentWidth = layoutInfo.contentWidth;
this._contentLeft = layoutInfo.contentLeft;
this._lineHeight = options.get(57 /* lineHeight */);
this._range = null;
this._viewRange = null;
this._preference = [];
this._cachedDomNodeClientWidth = -1;
this._cachedDomNodeClientHeight = -1;
this._maxWidth = this._getMaxWidth();
this._isVisible = false;
this._renderData = null;
this.domNode.setPosition((this._fixedOverflowWidgets && this.allowEditorOverflow) ? 'fixed' : 'absolute');
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(57 /* lineHeight */);
if (e.hasChanged(129 /* layoutInfo */)) {
const layoutInfo = options.get(129 /* layoutInfo */);
this._contentLeft = layoutInfo.contentLeft;
this._contentWidth = layoutInfo.contentWidth;
this._maxWidth = this._getMaxWidth();
}
}
onLineMappingChanged(e) {
this._setPosition(this._range);
}
_setPosition(range) {
this._range = range;
this._viewRange = null;
if (this._range) {
// Do not trust that widgets give a valid position
const validModelRange = this._context.model.validateModelRange(this._range);
if (this._context.model.coordinatesConverter.modelPositionIsVisible(validModelRange.getStartPosition()) || this._context.model.coordinatesConverter.modelPositionIsVisible(validModelRange.getEndPosition())) {
this._viewRange = this._context.model.coordinatesConverter.convertModelRangeToViewRange(validModelRange);
}
}
}
_getMaxWidth() {
return (this.allowEditorOverflow
? window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
: this._contentWidth);
}
setPosition(range, preference) {
this._setPosition(range);
this._preference = preference;
this._cachedDomNodeClientWidth = -1;
this._cachedDomNodeClientHeight = -1;
}
_layoutBoxInViewport(topLeft, bottomLeft, width, height, ctx) {
// Our visible box is split horizontally by the current line => 2 boxes
// a) the box above the line
const aboveLineTop = topLeft.top;
const heightAboveLine = aboveLineTop;
// b) the box under the line
const underLineTop = bottomLeft.top + this._lineHeight;
const heightUnderLine = ctx.viewportHeight - underLineTop;
const aboveTop = aboveLineTop - height;
const fitsAbove = (heightAboveLine >= height);
const belowTop = underLineTop;
const fitsBelow = (heightUnderLine >= height);
// And its left
let actualAboveLeft = topLeft.left;
let actualBelowLeft = bottomLeft.left;
if (actualAboveLeft + width > ctx.scrollLeft + ctx.viewportWidth) {
actualAboveLeft = ctx.scrollLeft + ctx.viewportWidth - width;
}
if (actualBelowLeft + width > ctx.scrollLeft + ctx.viewportWidth) {
actualBelowLeft = ctx.scrollLeft + ctx.viewportWidth - width;
}
if (actualAboveLeft < ctx.scrollLeft) {
actualAboveLeft = ctx.scrollLeft;
}
if (actualBelowLeft < ctx.scrollLeft) {
actualBelowLeft = ctx.scrollLeft;
}
return {
fitsAbove: fitsAbove,
aboveTop: aboveTop,
aboveLeft: actualAboveLeft,
fitsBelow: fitsBelow,
belowTop: belowTop,
belowLeft: actualBelowLeft,
};
}
_layoutHorizontalSegmentInPage(windowSize, domNodePosition, left, width) {
// Initially, the limits are defined as the dom node limits
const MIN_LIMIT = Math.max(0, domNodePosition.left - width);
const MAX_LIMIT = Math.min(domNodePosition.left + domNodePosition.width + width, windowSize.width);
let absoluteLeft = domNodePosition.left + left - dom.StandardWindow.scrollX;
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(topLeft, bottomLeft, width, height, ctx) {
const aboveTop = topLeft.top - height;
const belowTop = bottomLeft.top + this._lineHeight;
const domNodePosition = dom.getDomNodePagePosition(this._viewDomNode.domNode);
const absoluteAboveTop = domNodePosition.top + aboveTop - dom.StandardWindow.scrollY;
const absoluteBelowTop = domNodePosition.top + belowTop - dom.StandardWindow.scrollY;
const windowSize = dom.getClientArea(document.body);
const [aboveLeft, absoluteAboveLeft] = this._layoutHorizontalSegmentInPage(windowSize, domNodePosition, topLeft.left - ctx.scrollLeft + this._contentLeft, width);
const [belowLeft, absoluteBelowLeft] = this._layoutHorizontalSegmentInPage(windowSize, domNodePosition, bottomLeft.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),
aboveLeft: absoluteAboveLeft,
fitsBelow,
belowTop: absoluteBelowTop,
belowLeft: absoluteBelowLeft
};
}
return {
fitsAbove,
aboveTop: aboveTop,
aboveLeft,
fitsBelow,
belowTop,
belowLeft
};
}
_prepareRenderWidgetAtExactPositionOverflowing(topLeft) {
return new Coordinate(topLeft.top, topLeft.left + this._contentLeft);
}
/**
* Compute `this._topLeft`
*/
_getTopAndBottomLeft(ctx) {
if (!this._viewRange) {
return [null, null];
}
const visibleRangesForRange = ctx.linesVisibleRangesForRange(this._viewRange, false);
if (!visibleRangesForRange || visibleRangesForRange.length === 0) {
return [null, null];
}
let firstLine = visibleRangesForRange[0];
let lastLine = visibleRangesForRange[0];
for (const visibleRangesForLine of visibleRangesForRange) {
if (visibleRangesForLine.lineNumber < firstLine.lineNumber) {
firstLine = visibleRangesForLine;
}
if (visibleRangesForLine.lineNumber > lastLine.lineNumber) {
lastLine = visibleRangesForLine;
}
}
let firstLineMinLeft = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; //firstLine.Constants.MAX_SAFE_SMALL_INTEGER;
for (const visibleRange of firstLine.ranges) {
if (visibleRange.left < firstLineMinLeft) {
firstLineMinLeft = visibleRange.left;
}
}
let lastLineMinLeft = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; //lastLine.Constants.MAX_SAFE_SMALL_INTEGER;
for (const visibleRange of lastLine.ranges) {
if (visibleRange.left < lastLineMinLeft) {
lastLineMinLeft = visibleRange.left;
}
}
const topForPosition = ctx.getVerticalOffsetForLineNumber(firstLine.lineNumber) - ctx.scrollTop;
const topLeft = new Coordinate(topForPosition, firstLineMinLeft);
const topForBottomLine = ctx.getVerticalOffsetForLineNumber(lastLine.lineNumber) - ctx.scrollTop;
const bottomLeft = new Coordinate(topForBottomLine, lastLineMinLeft);
return [topLeft, bottomLeft];
}
_prepareRenderWidget(ctx) {
const [topLeft, bottomLeft] = this._getTopAndBottomLeft(ctx);
if (!topLeft || !bottomLeft) {
return null;
}
if (this._cachedDomNodeClientWidth === -1 || this._cachedDomNodeClientHeight === -1) {
let preferredDimensions = null;
if (typeof this._actual.beforeRender === 'function') {
preferredDimensions = safeInvoke(this._actual.beforeRender, this._actual);
}
if (preferredDimensions) {
this._cachedDomNodeClientWidth = preferredDimensions.width;
this._cachedDomNodeClientHeight = preferredDimensions.height;
}
else {
const domNode = this.domNode.domNode;
this._cachedDomNodeClientWidth = domNode.clientWidth;
this._cachedDomNodeClientHeight = domNode.clientHeight;
}
}
let placement;
if (this.allowEditorOverflow) {
placement = this._layoutBoxInPage(topLeft, bottomLeft, this._cachedDomNodeClientWidth, this._cachedDomNodeClientHeight, ctx);
}
else {
placement = this._layoutBoxInViewport(topLeft, bottomLeft, this._cachedDomNodeClientWidth, this._cachedDomNodeClientHeight, ctx);
}
// Do two passes, first for perfect fit, second picks first option
if (this._preference) {
for (let pass = 1; pass <= 2; pass++) {
for (const pref of this._preference) {
// placement
if (pref === 1 /* ABOVE */) {
if (!placement) {
// Widget outside of viewport
return null;
}
if (pass === 2 || placement.fitsAbove) {
return { coordinate: new Coordinate(placement.aboveTop, placement.aboveLeft), position: 1 /* ABOVE */ };
}
}
else if (pref === 2 /* BELOW */) {
if (!placement) {
// Widget outside of viewport
return null;
}
if (pass === 2 || placement.fitsBelow) {
return { coordinate: new Coordinate(placement.belowTop, placement.belowLeft), position: 2 /* BELOW */ };
}
}
else {
if (this.allowEditorOverflow) {
return { coordinate: this._prepareRenderWidgetAtExactPositionOverflowing(topLeft), position: 0 /* EXACT */ };
}
else {
return { coordinate: topLeft, position: 0 /* 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._viewRange || !this._preference) {
return;
}
if (this._viewRange.endLineNumber < viewportData.startLineNumber || this._viewRange.startLineNumber > viewportData.endLineNumber) {
// Outside of viewport
return;
}
this.domNode.setMaxWidth(this._maxWidth);
}
prepareRender(ctx) {
this._renderData = this._prepareRenderWidget(ctx);
}
render(ctx) {
if (!this._renderData) {
// This widget should be invisible
if (this._isVisible) {
this.domNode.removeAttribute('monaco-visible-content-widget');
this._isVisible = false;
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);
}
}
}
function safeInvoke(fn, thisArg, ...args) {
try {
return fn.call(thisArg, ...args);
}
catch (_a) {
// 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[399/*vs/editor/browser/viewParts/decorations/decorations*/], __M([0/*require*/,1/*exports*/,97/*vs/editor/browser/view/dynamicViewOverlay*/,3/*vs/editor/common/core/range*/,113/*vs/editor/common/view/renderingContext*/,327/*vs/css!vs/editor/browser/viewParts/decorations/decorations*/]), function (require, exports, dynamicViewOverlay_1, range_1, renderingContext_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._lineHeight = options.get(57 /* lineHeight */);
this._typicalHalfwidthCharacterWidth = options.get(41 /* 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._lineHeight = options.get(57 /* lineHeight */);
this._typicalHalfwidthCharacterWidth = options.get(41 /* 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 = [], 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 lineHeight = String(this._lineHeight);
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%;height:'
+ lineHeight
+ 'px;"></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 lineHeight = String(this._lineHeight);
const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
let prevClassName = null;
let prevShowIfCollapsed = false;
let prevRange = null;
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.model.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, prevShowIfCollapsed, lineHeight, visibleStartLineNumber, output);
}
prevClassName = className;
prevShowIfCollapsed = showIfCollapsed;
prevRange = range;
}
if (prevClassName !== null) {
this._renderNormalDecoration(ctx, prevRange, prevClassName, prevShowIfCollapsed, lineHeight, visibleStartLineNumber, output);
}
}
_renderNormalDecoration(ctx, range, className, showIfCollapsed, lineHeight, 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 === 0) {
// collapsed range case => make the decoration visible by faking its width
lineVisibleRanges.ranges[0] = new renderingContext_1.HorizontalRange(singleVisibleRange.left, this._typicalHalfwidthCharacterWidth);
}
}
for (let k = 0, lenK = lineVisibleRanges.ranges.length; k < lenK; k++) {
const visibleRange = lineVisibleRanges.ranges[k];
const decorationOutput = ('<div class="cdr '
+ className
+ '" style="left:'
+ String(visibleRange.left)
+ 'px;width:'
+ String(visibleRange.width)
+ 'px;height:'
+ lineHeight
+ '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[176/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([0/*require*/,1/*exports*/,97/*vs/editor/browser/view/dynamicViewOverlay*/,328/*vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin*/]), function (require, exports, dynamicViewOverlay_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GlyphMarginOverlay = exports.DedupOverlay = exports.DecorationToRender = void 0;
class DecorationToRender {
constructor(startLineNumber, endLineNumber, className) {
this._decorationToRenderBrand = undefined;
this.startLineNumber = +startLineNumber;
this.endLineNumber = +endLineNumber;
this.className = String(className);
}
}
exports.DecorationToRender = DecorationToRender;
class DedupOverlay extends dynamicViewOverlay_1.DynamicViewOverlay {
_render(visibleStartLineNumber, visibleEndLineNumber, decorations) {
const output = [];
for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
const lineIndex = lineNumber - visibleStartLineNumber;
output[lineIndex] = [];
}
if (decorations.length === 0) {
return output;
}
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;
let startLineIndex = Math.max(d.startLineNumber, visibleStartLineNumber) - visibleStartLineNumber;
const endLineIndex = Math.min(d.endLineNumber, visibleEndLineNumber) - visibleStartLineNumber;
if (prevClassName === className) {
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].push(prevClassName);
}
}
return output;
}
}
exports.DedupOverlay = DedupOverlay;
class GlyphMarginOverlay extends DedupOverlay {
constructor(context) {
super();
this._context = context;
const options = this._context.configuration.options;
const layoutInfo = options.get(129 /* layoutInfo */);
this._lineHeight = options.get(57 /* lineHeight */);
this._glyphMargin = options.get(47 /* glyphMargin */);
this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
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(129 /* layoutInfo */);
this._lineHeight = options.get(57 /* lineHeight */);
this._glyphMargin = options.get(47 /* glyphMargin */);
this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
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();
let r = [], rLen = 0;
for (let i = 0, len = decorations.length; i < len; i++) {
const d = decorations[i];
const glyphMarginClassName = d.options.glyphMarginClassName;
if (glyphMarginClassName) {
r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, glyphMarginClassName);
}
}
return r;
}
prepareRender(ctx) {
if (!this._glyphMargin) {
this._renderResult = null;
return;
}
const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
const toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
const lineHeight = this._lineHeight.toString();
const left = this._glyphMarginLeft.toString();
const width = this._glyphMarginWidth.toString();
const common = '" style="left:' + left + 'px;width:' + width + 'px' + ';height:' + lineHeight + 'px;"></div>';
const output = [];
for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
const lineIndex = lineNumber - visibleStartLineNumber;
const classNames = toRender[lineIndex];
if (classNames.length === 0) {
output[lineIndex] = '';
}
else {
output[lineIndex] = ('<div class="cgmr codicon '
+ classNames.join(' ')
+ common);
}
}
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.GlyphMarginOverlay = GlyphMarginOverlay;
});
/*---------------------------------------------------------------------------------------------
* 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/viewParts/linesDecorations/linesDecorations*/], __M([0/*require*/,1/*exports*/,176/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/,332/*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(129 /* 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(129 /* 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();
let r = [], rLen = 0;
for (let i = 0, len = decorations.length; i < len; i++) {
const d = decorations[i];
const linesDecorationsClassName = d.options.linesDecorationsClassName;
if (linesDecorationsClassName) {
r[rLen++] = new glyphMargin_1.DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, linesDecorationsClassName);
}
const firstLineDecorationClassName = d.options.firstLineDecorationClassName;
if (firstLineDecorationClassName) {
r[rLen++] = new glyphMargin_1.DecorationToRender(d.range.startLineNumber, d.range.startLineNumber, firstLineDecorationClassName);
}
}
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 classNames = toRender[lineIndex];
let lineOutput = '';
for (let i = 0, len = classNames.length; i < len; i++) {
lineOutput += '<div class="cldr ' + classNames[i] + common;
}
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[225/*vs/editor/browser/viewParts/margin/margin*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,47/*vs/editor/browser/view/viewPart*/]), 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 {
constructor(context) {
super(context);
const options = this._context.configuration.options;
const layoutInfo = options.get(129 /* layoutInfo */);
this._canUseLayerHinting = !options.get(26 /* 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(129 /* layoutInfo */);
this._canUseLayerHinting = !options.get(26 /* 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;
Margin.CLASS_NAME = 'glyph-margin';
Margin.OUTER_CLASS_NAME = '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[401/*vs/editor/browser/viewParts/marginDecorations/marginDecorations*/], __M([0/*require*/,1/*exports*/,176/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/,333/*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();
let r = [], rLen = 0;
for (let i = 0, len = decorations.length; i < len; i++) {
const d = decorations[i];
const marginClassName = d.options.marginClassName;
if (marginClassName) {
r[rLen++] = new glyphMargin_1.DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, marginClassName);
}
}
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 classNames = toRender[lineIndex];
let lineOutput = '';
for (let i = 0, len = classNames.length; i < len; i++) {
lineOutput += '<div class="cmdr ' + classNames[i] + '" 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[402/*vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,47/*vs/editor/browser/view/viewPart*/,335/*vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/]), function (require, exports, fastDomNode_1, viewPart_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ViewOverlayWidgets = void 0;
class ViewOverlayWidgets extends viewPart_1.ViewPart {
constructor(context) {
super(context);
const options = this._context.configuration.options;
const layoutInfo = options.get(129 /* 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._domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
viewPart_1.PartFingerprints.write(this._domNode, 4 /* OverlayWidgets */);
this._domNode.setClassName('overlayWidgets');
}
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(129 /* 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());
this._domNode.appendChild(domNode);
this.setShouldRender();
}
setWidgetPosition(widget, preference) {
const widgetData = this._widgets[widget.getId()];
if (widgetData.preference === preference) {
return false;
}
widgetData.preference = preference;
this.setShouldRender();
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.parentNode.removeChild(domNode);
this.setShouldRender();
}
}
_renderWidget(widgetData) {
const domNode = widgetData.domNode;
if (widgetData.preference === null) {
domNode.unsetTop();
return;
}
if (widgetData.preference === 0 /* TOP_RIGHT_CORNER */) {
domNode.setTop(0);
domNode.setRight((2 * this._verticalScrollbarWidth) + this._minimapWidth);
}
else if (widgetData.preference === 1 /* BOTTOM_RIGHT_CORNER */) {
const widgetHeight = domNode.domNode.clientHeight;
domNode.setTop((this._editorHeight - widgetHeight - 2 * this._horizontalScrollbarHeight));
domNode.setRight((2 * this._verticalScrollbarWidth) + this._minimapWidth);
}
else if (widgetData.preference === 2 /* TOP_CENTER */) {
domNode.setTop(0);
domNode.domNode.style.right = '50%';
}
}
prepareRender(ctx) {
// Nothing to read
}
render(ctx) {
this._domNode.setWidth(this._editorWidth);
const keys = Object.keys(this._widgets);
for (let i = 0, len = keys.length; i < len; i++) {
const widgetId = keys[i];
this._renderWidget(this._widgets[widgetId]);
}
}
}
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[403/*vs/editor/browser/viewParts/overviewRuler/overviewRuler*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,223/*vs/editor/common/view/overviewZoneManager*/,115/*vs/editor/common/viewModel/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(57 /* lineHeight */));
this._zoneManager.setPixelRatio(options.get(127 /* 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(57 /* lineHeight */)) {
this._zoneManager.setLineHeight(options.get(57 /* lineHeight */));
this._render();
}
if (e.hasChanged(127 /* pixelRatio */)) {
this._zoneManager.setPixelRatio(options.get(127 /* 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[404/*vs/editor/browser/viewParts/viewZones/viewZones*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,12/*vs/base/common/errors*/,47/*vs/editor/browser/view/viewPart*/,13/*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(129 /* layoutInfo */);
this._lineHeight = options.get(57 /* 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.model.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);
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(129 /* layoutInfo */);
this._lineHeight = options.get(57 /* lineHeight */);
this._contentWidth = layoutInfo.contentWidth;
this._contentLeft = layoutInfo.contentLeft;
if (e.hasChanged(57 /* 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) {
if (typeof zone.afterColumn !== 'undefined') {
return zone.afterColumn;
}
return 10000;
}
_computeWhitespaceProps(zone) {
if (zone.afterLineNumber === 0) {
return {
afterViewLineNumber: 0,
heightInPx: this._heightInPixels(zone),
minWidthInPx: this._minWidthInPixels(zone)
};
}
let zoneAfterModelPosition;
if (typeof zone.afterColumn !== 'undefined') {
zoneAfterModelPosition = this._context.model.validateModelPosition({
lineNumber: zone.afterLineNumber,
column: zone.afterColumn
});
}
else {
const validAfterLineNumber = this._context.model.validateModelPosition({
lineNumber: zone.afterLineNumber,
column: 1
}).lineNumber;
zoneAfterModelPosition = new position_1.Position(validAfterLineNumber, this._context.model.getModelLineMaxColumn(validAfterLineNumber));
}
let zoneBeforeModelPosition;
if (zoneAfterModelPosition.column === this._context.model.getModelLineMaxColumn(zoneAfterModelPosition.lineNumber)) {
zoneBeforeModelPosition = this._context.model.validateModelPosition({
lineNumber: zoneAfterModelPosition.lineNumber + 1,
column: 1
});
}
else {
zoneBeforeModelPosition = this._context.model.validateModelPosition({
lineNumber: zoneAfterModelPosition.lineNumber,
column: zoneAfterModelPosition.column + 1
});
}
const viewPosition = this._context.model.coordinatesConverter.convertModelPositionToViewPosition(zoneAfterModelPosition);
const isVisible = this._context.model.coordinatesConverter.modelPositionIsVisible(zoneBeforeModelPosition);
return {
afterViewLineNumber: viewPosition.lineNumber,
heightInPx: (isVisible ? this._heightInPixels(zone) : 0),
minWidthInPx: this._minWidthInPixels(zone)
};
}
changeViewZones(callback) {
let zonesHaveChanged = false;
this._context.model.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,
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.parentNode.removeChild(zone.domNode.domNode);
if (zone.marginDomNode) {
zone.marginDomNode.removeAttribute('monaco-visible-view-zone');
zone.marginDomNode.removeAttribute('monaco-view-zone');
zone.marginDomNode.domNode.parentNode.removeChild(zone.marginDomNode.domNode);
}
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);
// 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 (let i = 0, len = visibleWhitespaces.length; i < len; i++) {
visibleZones[visibleWhitespaces[i].id] = visibleWhitespaces[i];
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[62/*vs/editor/common/viewModel/viewModel*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings, position_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ViewModelDecoration = exports.SingleLineInlineDecoration = exports.InlineDecoration = exports.ViewLineRenderingData = exports.ViewLineData = exports.MinimapLinesRenderingData = exports.InjectedText = exports.LineBreakData = exports.OutputPosition = 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 OutputPosition {
constructor(outputLineIndex, outputOffset) {
this.outputLineIndex = outputLineIndex;
this.outputOffset = outputOffset;
}
toString() {
return `${this.outputLineIndex}:${this.outputOffset}`;
}
toPosition(baseLineNumber, wrappedTextIndentLength) {
const delta = (this.outputLineIndex > 0 ? wrappedTextIndentLength : 0);
return new position_1.Position(baseLineNumber + this.outputLineIndex, delta + this.outputOffset + 1);
}
}
exports.OutputPosition = OutputPosition;
class LineBreakData {
constructor(breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength, injectionOffsets, injectionOptions) {
this.breakOffsets = breakOffsets;
this.breakOffsetsVisibleColumn = breakOffsetsVisibleColumn;
this.wrappedTextIndentLength = wrappedTextIndentLength;
this.injectionOffsets = injectionOffsets;
this.injectionOptions = injectionOptions;
}
getInputOffsetOfOutputPosition(outputLineIndex, outputOffset) {
let inputOffset = 0;
if (outputLineIndex === 0) {
inputOffset = outputOffset;
}
else {
inputOffset = this.breakOffsets[outputLineIndex - 1] + outputOffset;
}
if (this.injectionOffsets !== null) {
for (let i = 0; i < this.injectionOffsets.length; i++) {
if (inputOffset > this.injectionOffsets[i]) {
if (inputOffset < this.injectionOffsets[i] + this.injectionOptions[i].content.length) {
// `inputOffset` is within injected text
inputOffset = this.injectionOffsets[i];
}
else {
inputOffset -= this.injectionOptions[i].content.length;
}
}
else {
break;
}
}
}
return inputOffset;
}
getOutputPositionOfInputOffset(inputOffset, affinity = 2 /* None */) {
let delta = 0;
if (this.injectionOffsets !== null) {
for (let i = 0; i < this.injectionOffsets.length; i++) {
if (inputOffset < this.injectionOffsets[i]) {
break;
}
if (affinity !== 1 /* Right */ && inputOffset === this.injectionOffsets[i]) {
break;
}
delta += this.injectionOptions[i].content.length;
}
}
inputOffset += delta;
return this.getOutputPositionOfOffsetInUnwrappedLine(inputOffset, affinity);
}
getOutputPositionOfOffsetInUnwrappedLine(inputOffset, affinity = 2 /* 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 /* Left */) {
if (inputOffset <= midStart) {
high = mid - 1;
}
else if (inputOffset > midStop) {
low = mid + 1;
}
else {
break;
}
}
else {
if (inputOffset < midStart) {
high = mid - 1;
}
else if (inputOffset >= midStop) {
low = mid + 1;
}
else {
break;
}
}
}
return new OutputPosition(mid, inputOffset - midStart);
}
outputPositionToOffsetInUnwrappedLine(outputLineIndex, outputOffset) {
let result = (outputLineIndex > 0 ? this.breakOffsets[outputLineIndex - 1] : 0) + outputOffset;
if (outputLineIndex > 0) {
result -= this.wrappedTextIndentLength;
}
return result;
}
normalizeOffsetAroundInjections(offsetInUnwrappedLine, affinity) {
const injectedText = this.getInjectedTextAtOffset(offsetInUnwrappedLine);
if (!injectedText) {
return offsetInUnwrappedLine;
}
if (affinity === 2 /* None */) {
if (offsetInUnwrappedLine === injectedText.offsetInUnwrappedLine + injectedText.length) {
// go to the end of this injected text
return injectedText.offsetInUnwrappedLine + injectedText.length;
}
else {
// go to the start of this injected text
return injectedText.offsetInUnwrappedLine;
}
}
if (affinity === 1 /* Right */) {
let result = injectedText.offsetInUnwrappedLine + injectedText.length;
let index = injectedText.injectedTextIndex;
// traverse all injected text that touch eachother
while (index + 1 < this.injectionOffsets.length && this.injectionOffsets[index + 1] === this.injectionOffsets[index]) {
result += this.injectionOptions[index + 1].content.length;
index++;
}
return result;
}
// affinity is left
let result = injectedText.offsetInUnwrappedLine;
let index = injectedText.injectedTextIndex;
// traverse all injected text that touch eachother
while (index - 1 >= 0 && this.injectionOffsets[index - 1] === this.injectionOffsets[index]) {
result -= this.injectionOptions[index - 1].content.length;
index++;
}
return result;
}
getInjectedText(outputLineIndex, outputOffset) {
const offset = this.outputPositionToOffsetInUnwrappedLine(outputLineIndex, outputOffset);
const injectedText = this.getInjectedTextAtOffset(offset);
if (!injectedText) {
return null;
}
return {
options: this.injectionOptions[injectedText.injectedTextIndex]
};
}
getInjectedTextAtOffset(offsetInUnwrappedLine) {
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 injectedTextStartOffsetInUnwrappedLine = injectionOffsets[i] + totalInjectedTextLengthBefore;
const injectedTextEndOffsetInUnwrappedLine = injectionOffsets[i] + totalInjectedTextLengthBefore + length;
if (injectedTextStartOffsetInUnwrappedLine > offsetInUnwrappedLine) {
// Injected text starts later.
break; // All later injected texts have an even larger offset.
}
if (offsetInUnwrappedLine <= injectedTextEndOffsetInUnwrappedLine) {
// Injected text ends after or with the given position (but also starts with or before it).
return {
injectedTextIndex: i,
offsetInUnwrappedLine: injectedTextStartOffsetInUnwrappedLine,
length
};
}
totalInjectedTextLengthBefore += length;
}
}
return undefined;
}
}
exports.LineBreakData = LineBreakData;
class InjectedText {
constructor(options) {
this.options = options;
}
}
exports.InjectedText = InjectedText;
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 /* RegularAffectingLetterSpacing */ : 0 /* Regular */);
}
}
exports.SingleLineInlineDecoration = SingleLineInlineDecoration;
class ViewModelDecoration {
constructor(range, options) {
this._viewModelDecorationBrand = undefined;
this.range = range;
this.options = options;
}
}
exports.ViewModelDecoration = ViewModelDecoration;
});
/*---------------------------------------------------------------------------------------------
* 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/common/viewModel/monospaceLineBreaksComputer*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,94/*vs/editor/common/core/characterClassifier*/,62/*vs/editor/common/viewModel/viewModel*/,96/*vs/editor/common/model/textModelEvents*/]), function (require, exports, strings, characterClassifier_1, viewModel_1, textModelEvents_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MonospaceLineBreaksComputerFactory = void 0;
class WrappingCharacterClassifier extends characterClassifier_1.CharacterClassifier {
constructor(BREAK_BEFORE, BREAK_AFTER) {
super(0 /* NONE */);
for (let i = 0; i < BREAK_BEFORE.length; i++) {
this.set(BREAK_BEFORE.charCodeAt(i), 1 /* BREAK_BEFORE */);
}
for (let i = 0; i < BREAK_AFTER.length; i++) {
this.set(BREAK_AFTER.charCodeAt(i), 2 /* 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 /* BREAK_IDEOGRAPHIC */;
}
return (this._map.get(charCode) || this._defaultValue);
}
}
}
let arrPool1 = [];
let arrPool2 = [];
class MonospaceLineBreaksComputerFactory {
constructor(breakBeforeChars, breakAfterChars) {
this.classifier = new WrappingCharacterClassifier(breakBeforeChars, breakAfterChars);
}
static create(options) {
return new MonospaceLineBreaksComputerFactory(options.get(118 /* wordWrapBreakBeforeCharacters */), options.get(117 /* wordWrapBreakAfterCharacters */));
}
createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent) {
tabSize = tabSize | 0; //@perf
wrappingColumn = +wrappingColumn; //@perf
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; //@perf
let 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);
}
else {
result[i] = createLineBreaks(this.classifier, requests[i], injectedText, tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent);
}
}
arrPool1.length = 0;
arrPool2.length = 0;
return result;
}
};
}
}
exports.MonospaceLineBreaksComputerFactory = MonospaceLineBreaksComputerFactory;
function createLineBreaksFromPreviousLineBreaks(classifier, previousBreakingData, lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) {
if (firstLineBreakColumn === -1) {
return null;
}
const len = lineText.length;
if (len <= 1) {
return null;
}
const prevBreakingOffsets = previousBreakingData.breakOffsets;
const prevBreakingOffsetsVisibleColumn = previousBreakingData.breakOffsetsVisibleColumn;
const wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent);
const wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength;
let breakingOffsets = arrPool1;
let 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 /* Null */ : lineText.charCodeAt(prevBreakOffset - 1);
let prevCharCodeClass = prevBreakOffset === 0 ? 0 /* 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 /* NONE */;
charWidth = 2;
}
else {
charCodeClass = classifier.get(charCode);
charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
}
if (charStartOffset > lastBreakingOffset && canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass)) {
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 /* 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 /* 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)) {
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) {
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 viewModel_1.LineBreakData([lineText.length], [], 0, injectionOffsets, injectionOptions);
}
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 viewModel_1.LineBreakData([lineText.length], [], 0, injectionOffsets, injectionOptions);
}
const wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent);
const wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength;
let breakingOffsets = [];
let 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 /* NONE */;
charWidth = 2;
}
else {
charCodeClass = classifier.get(charCode);
charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
}
if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass)) {
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 viewModel_1.LineBreakData(breakingOffsets, breakingOffsetsVisibleColumn, wrappedTextIndentLength, injectionOffsets, injectionOptions);
}
function computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar) {
if (charCode === 9 /* 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) {
return (charCode !== 32 /* Space */
&& ((prevCharCodeClass === 2 /* BREAK_AFTER */)
|| (prevCharCodeClass === 3 /* BREAK_IDEOGRAPHIC */ && charCodeClass !== 2 /* BREAK_AFTER */)
|| (charCodeClass === 1 /* BREAK_BEFORE */)
|| (charCodeClass === 3 /* BREAK_IDEOGRAPHIC */ && prevCharCodeClass !== 1 /* BREAK_BEFORE */)));
}
function computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) {
let wrappedTextIndentLength = 0;
if (wrappingIndent !== 0 /* 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 /* Tab */ ? tabCharacterWidth(wrappedTextIndentLength, tabSize) : 1);
wrappedTextIndentLength += charWidth;
}
// Increase indent of continuation lines, if desired
const numberOfAdditionalTabs = (wrappingIndent === 3 /* DeepIndent */ ? 2 : wrappingIndent === 2 /* 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[177/*vs/editor/common/viewModel/viewModelEventDispatcher*/], __M([0/*require*/,1/*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.ReadOnlyEditAttemptEvent = exports.CursorStateChangedEvent = 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._emitOugoingEvents();
}
_addOutgoingEvent(e) {
for (let i = 0, len = this._outgoingEvents.length; i < len; i++) {
if (this._outgoingEvents[i].kind === e.kind) {
this._outgoingEvents[i] = this._outgoingEvents[i].merge(e);
return;
}
}
// not merged
this._outgoingEvents.push(e);
}
_emitOugoingEvents() {
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._emitOugoingEvents();
}
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 /* 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);
}
merge(other) {
if (other.kind !== 0 /* ContentSizeChanged */) {
return this;
}
return new ContentSizeChangedEvent(this._oldContentWidth, this._oldContentHeight, other.contentWidth, other.contentHeight);
}
}
exports.ContentSizeChangedEvent = ContentSizeChangedEvent;
class FocusChangedEvent {
constructor(oldHasFocus, hasFocus) {
this.kind = 1 /* FocusChanged */;
this.oldHasFocus = oldHasFocus;
this.hasFocus = hasFocus;
}
isNoOp() {
return (this.oldHasFocus === this.hasFocus);
}
merge(other) {
if (other.kind !== 1 /* FocusChanged */) {
return this;
}
return new FocusChangedEvent(this.oldHasFocus, other.hasFocus);
}
}
exports.FocusChangedEvent = FocusChangedEvent;
class ScrollChangedEvent {
constructor(oldScrollWidth, oldScrollLeft, oldScrollHeight, oldScrollTop, scrollWidth, scrollLeft, scrollHeight, scrollTop) {
this.kind = 2 /* 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);
}
merge(other) {
if (other.kind !== 2 /* ScrollChanged */) {
return this;
}
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 /* ViewZonesChanged */;
}
isNoOp() {
return false;
}
merge(other) {
return this;
}
}
exports.ViewZonesChangedEvent = ViewZonesChangedEvent;
class CursorStateChangedEvent {
constructor(oldSelections, selections, oldModelVersionId, modelVersionId, source, reason, reachedMaxCursorCount) {
this.kind = 5 /* 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);
}
merge(other) {
if (other.kind !== 5 /* CursorStateChanged */) {
return this;
}
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 = 4 /* ReadOnlyEditAttempt */;
}
isNoOp() {
return false;
}
merge(other) {
return this;
}
}
exports.ReadOnlyEditAttemptEvent = ReadOnlyEditAttemptEvent;
});
/*---------------------------------------------------------------------------------------------
* 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/editor/common/viewLayout/viewLayout*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,127/*vs/base/common/scrollable*/,394/*vs/editor/common/viewLayout/linesLayout*/,62/*vs/editor/common/viewModel/viewModel*/,177/*vs/editor/common/viewModel/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(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);
}
}
class ViewLayout extends lifecycle_1.Disposable {
constructor(configuration, lineCount, scheduleAtNextAnimationFrame) {
super();
this._configuration = configuration;
const options = this._configuration.options;
const layoutInfo = options.get(129 /* layoutInfo */);
const padding = options.get(73 /* padding */);
this._linesLayout = new linesLayout_1.LinesLayout(lineCount, options.get(57 /* lineHeight */), padding.top, padding.bottom);
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(102 /* smoothScrolling */) ? SMOOTH_SCROLLING_TIME : 0);
}
// ---- begin view event handlers
onConfigurationChanged(e) {
const options = this._configuration.options;
if (e.hasChanged(57 /* lineHeight */)) {
this._linesLayout.setLineHeight(options.get(57 /* lineHeight */));
}
if (e.hasChanged(73 /* padding */)) {
const padding = options.get(73 /* padding */);
this._linesLayout.setPadding(padding.top, padding.bottom);
}
if (e.hasChanged(129 /* layoutInfo */)) {
const layoutInfo = options.get(129 /* 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(102 /* 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(91 /* scrollbar */);
if (scrollbar.horizontal === 2 /* 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(93 /* scrollBeyondLastLine */)) {
result += Math.max(0, height - options.get(57 /* lineHeight */) - options.get(73 /* padding */).bottom);
}
else {
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(maxLineWidth) {
const options = this._configuration.options;
const wrappingInfo = options.get(130 /* wrappingInfo */);
const fontInfo = options.get(41 /* fontInfo */);
if (wrappingInfo.isViewportWrapping) {
const layoutInfo = options.get(129 /* layoutInfo */);
const minimap = options.get(63 /* 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(92 /* scrollBeyondLastColumn */) * fontInfo.typicalHalfwidthCharacterWidth;
const whitespaceMinWidth = this._linesLayout.getWhitespaceMinWidth();
return Math.max(maxLineWidth + extraHorizontalSpace, whitespaceMinWidth);
}
}
setMaxLineWidth(maxLineWidth) {
const scrollDimensions = this._scrollable.getScrollDimensions();
// const newScrollWidth = ;
this._scrollable.setScrollDimensions(new EditorScrollDimensions(scrollDimensions.width, this._computeContentWidth(maxLineWidth), 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();
let scrollTop = currentScrollPosition.scrollTop;
let firstLineNumberInViewport = this._linesLayout.getLineNumberAtOrAfterVerticalOffset(scrollTop);
let whitespaceAboveFirstLine = this._linesLayout.getWhitespaceAccumulatedHeightBeforeLineNumber(firstLineNumberInViewport);
return {
scrollTop: scrollTop,
scrollTopWithoutViewZones: scrollTop - whitespaceAboveFirstLine,
scrollLeft: currentScrollPosition.scrollLeft
};
}
// ---- IVerticalLayoutProvider
changeWhitespace(callback) {
const hadAChange = this._linesLayout.changeWhitespace(callback);
if (hadAChange) {
this.onHeightMaybeChanged();
}
return hadAChange;
}
getVerticalOffsetForLineNumber(lineNumber) {
return this._linesLayout.getVerticalOffsetForLineNumber(lineNumber);
}
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();
}
// ---- IScrollingProvider
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 /* Immediate */) {
this._scrollable.setScrollPositionNow(position);
}
else {
this._scrollable.setScrollPositionSmooth(position);
}
}
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[407/*vs/editor/contrib/caretOperations/moveCaretCommand*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,21/*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[137/*vs/editor/contrib/codeAction/types*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeActionCommandArgs = exports.filtersAction = exports.mayIncludeActionsOfKind = exports.CodeActionKind = void 0;
class CodeActionKind {
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 + CodeActionKind.sep);
}
intersects(other) {
return this.contains(other) || other.contains(this);
}
append(part) {
return new CodeActionKind(this.value + CodeActionKind.sep + part);
}
}
exports.CodeActionKind = CodeActionKind;
CodeActionKind.sep = '.';
CodeActionKind.None = new CodeActionKind('@@none@@'); // Special code action that contains nothing
CodeActionKind.Empty = new CodeActionKind('');
CodeActionKind.QuickFix = new CodeActionKind('quickfix');
CodeActionKind.Refactor = new CodeActionKind('refactor');
CodeActionKind.Source = new CodeActionKind('source');
CodeActionKind.SourceOrganizeImports = CodeActionKind.Source.append('organizeImports');
CodeActionKind.SourceFixAll = CodeActionKind.Source.append('fixAll');
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 && CodeActionKind.Source.contains(providedKind)) {
return false;
}
return true;
}
exports.mayIncludeActionsOfKind = mayIncludeActionsOfKind;
function filtersAction(filter, action) {
const actionKind = action.kind ? new CodeActionKind(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 && CodeActionKind.Source.contains(actionKind)) {
return false;
}
}
if (filter.onlyIncludePreferredActions) {
if (!action.isPreferred) {
return false;
}
}
return true;
}
exports.filtersAction = filtersAction;
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 {
constructor(kind, apply, preferred) {
this.kind = kind;
this.apply = apply;
this.preferred = preferred;
}
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" /* First */;
case 'never': return "never" /* Never */;
case 'ifsingle': return "ifSingle" /* IfSingle */;
default: return defaultAutoApply;
}
}
static getKindFromUser(arg, defaultKind) {
return typeof arg.kind === 'string'
? new CodeActionKind(arg.kind)
: defaultKind;
}
static getPreferredUser(arg) {
return typeof arg.preferred === 'boolean'
? arg.preferred
: false;
}
}
exports.CodeActionCommandArgs = CodeActionCommandArgs;
});
/*---------------------------------------------------------------------------------------------
* 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/colorPicker/colorPickerModel*/], __M([0/*require*/,1/*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 {
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;
}
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);
}
selectNextColorPresentation() {
this.presentationIndex = (this.presentationIndex + 1) % this.colorPresentations.length;
this.flushColor();
this._onDidChangePresentation.fire(this.presentation);
}
guessColorPresentation(color, originalText) {
for (let i = 0; i < this.colorPresentations.length; i++) {
if (originalText.toLowerCase() === this.colorPresentations[i].label) {
this.presentationIndex = i;
this._onDidChangePresentation.fire(this.presentation);
break;
}
}
}
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[226/*vs/editor/contrib/comment/blockCommentCommand*/], __M([0/*require*/,1/*exports*/,56/*vs/editor/common/core/editOperation*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, editOperation_1, position_1, range_1, selection_1, languageConfigurationRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BlockCommentCommand = void 0;
class BlockCommentCommand {
constructor(selection, insertSpace) {
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 /* A */ && codeA <= 90 /* Z */ && codeA + 32 === codeB) {
// codeA is upper-case variant of codeB
continue;
}
if (codeB >= 65 /* A */ && codeB <= 90 /* 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 /* Space */) {
// Pretend the start token contains a trailing space
startToken = startToken + ' ';
}
if (insertSpace && endTokenIndex > 0 && endLineText.charCodeAt(endTokenIndex - 1) === 32 /* 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) {
let 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) {
let 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.tokenizeIfCheap(startLineNumber);
const languageId = model.getLanguageIdAtPosition(startLineNumber, startColumn);
const config = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getComments(languageId);
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[409/*vs/editor/contrib/comment/lineCommentCommand*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,56/*vs/editor/common/core/editOperation*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/,226/*vs/editor/contrib/comment/blockCommentCommand*/]), function (require, exports, strings, editOperation_1, position_1, range_1, selection_1, languageConfigurationRegistry_1, blockCommentCommand_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LineCommentCommand = void 0;
class LineCommentCommand {
constructor(selection, tabSize, type, insertSpace, ignoreEmptyLines, ignoreFirstLine) {
this._selection = selection;
this._tabSize = tabSize;
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) {
model.tokenizeIfCheap(startLineNumber);
const languageId = model.getLanguageIdAtPosition(startLineNumber, 1);
const config = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getComments(languageId);
const commentStr = (config ? config.lineCommentToken : null);
if (!commentStr) {
// Mode does not support line comments
return null;
}
let 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) {
let onlyWhitespaceLines = true;
let shouldRemoveComments;
if (type === 0 /* Toggle */) {
shouldRemoveComments = true;
}
else if (type === 1 /* 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 /* Toggle */) {
// Every line so far has been a line comment, but this one is not
shouldRemoveComments = false;
}
else if (type === 1 /* 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 /* Space */) {
lineData.commentStrLength += 1;
}
}
}
if (type === 0 /* 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) {
const lines = LineCommentCommand._gatherPreflightCommentStrings(model, startLineNumber, endLineNumber);
if (lines === null) {
return {
supported: false
};
}
return LineCommentCommand._analyzeLines(type, insertSpace, model, lines, startLineNumber, ignoreEmptyLines, ignoreFirstLine);
}
/**
* 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._tabSize);
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;
let 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 /* 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 /* 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.tokenizeIfCheap(s.startLineNumber);
let languageId = model.getLanguageIdAtPosition(s.startLineNumber, 1);
let config = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getComments(languageId);
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);
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) {
let 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) {
let 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, tabSize, isTab, columnSize) {
if (isTab) {
return currentVisibleColumn + (tabSize - (currentVisibleColumn % tabSize));
}
return currentVisibleColumn + columnSize;
}
/**
* Adjust insertion points to have them vertically aligned in the add line comment case
*/
static _normalizeInsertionPoint(model, lines, startLineNumber, tabSize) {
let minVisibleColumn = 1073741824 /* 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, tabSize, lineContent.charCodeAt(j) === 9 /* Tab */, 1);
}
if (currentVisibleColumn < minVisibleColumn) {
minVisibleColumn = currentVisibleColumn;
}
}
minVisibleColumn = Math.floor(minVisibleColumn / tabSize) * tabSize;
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, tabSize, lineContent.charCodeAt(j) === 9 /* 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[410/*vs/editor/contrib/dnd/dragAndDropCommand*/], __M([0/*require*/,1/*exports*/,21/*vs/editor/common/core/selection*/,3/*vs/editor/common/core/range*/]), function (require, exports, selection_1, range_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) {
let 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[411/*vs/editor/contrib/find/replaceAllCommand*/], __M([0/*require*/,1/*exports*/,3/*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
let 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
let 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[412/*vs/editor/contrib/find/replacePattern*/], __M([0/*require*/,1/*exports*/,293/*vs/base/common/search*/]), function (require, exports, search_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseReplaceString = exports.ReplacePiece = exports.ReplacePattern = void 0;
/**
* Assigned when the replace pattern is entirely static.
*/
class StaticValueReplacePattern {
constructor(staticValue) {
this.staticValue = staticValue;
this.kind = 0 /* StaticValue */;
}
}
/**
* Assigned when the replace pattern has replacement patterns.
*/
class DynamicPiecesReplacePattern {
constructor(pieces) {
this.pieces = pieces;
this.kind = 1 /* DynamicPieces */;
}
}
class ReplacePattern {
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);
}
}
static fromStaticValue(value) {
return new ReplacePattern([ReplacePiece.staticValue(value)]);
}
get hasReplacementPatterns() {
return (this._state.kind === 1 /* DynamicPieces */);
}
buildReplaceString(matches, preserveCase) {
if (this._state.kind === 0 /* 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++) {
let 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) {
let repl = [];
let 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
let 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 {
constructor(staticValue, matchIndex, caseOps) {
this.staticValue = staticValue;
this.matchIndex = matchIndex;
if (!caseOps || caseOps.length === 0) {
this.caseOps = null;
}
else {
this.caseOps = caseOps.slice(0);
}
}
static staticValue(value) {
return new ReplacePiece(value, -1, null);
}
static caseOps(index, caseOps) {
return new ReplacePiece(null, index, caseOps);
}
}
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);
}
let caseOps = [];
let result = new ReplacePieceBuilder(replaceString);
for (let i = 0, len = replaceString.length; i < len; i++) {
let chCode = replaceString.charCodeAt(i);
if (chCode === 92 /* Backslash */) {
// move to next char
i++;
if (i >= len) {
// string ends with a \
break;
}
let nextChCode = replaceString.charCodeAt(i);
// let replaceWithCharacter: string | null = null;
switch (nextChCode) {
case 92 /* Backslash */:
// \\ => inserts a "\"
result.emitUnchanged(i - 1);
result.emitStatic('\\', i + 1);
break;
case 110 /* n */:
// \n => inserts a LF
result.emitUnchanged(i - 1);
result.emitStatic('\n', i + 1);
break;
case 116 /* 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 /* u */:
// \u => upper-cases one character.
case 85 /* U */:
// \U => upper-cases ALL following characters.
case 108 /* l */:
// \l => lower-cases one character.
case 76 /* 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 /* DollarSign */) {
// move to next char
i++;
if (i >= len) {
// string ends with a $
break;
}
let nextChCode = replaceString.charCodeAt(i);
if (nextChCode === 36 /* DollarSign */) {
// $$ => inserts a "$"
result.emitUnchanged(i - 1);
result.emitStatic('$', i + 1);
continue;
}
if (nextChCode === 48 /* Digit0 */ || nextChCode === 38 /* Ampersand */) {
// $& and $0 => inserts the matched substring.
result.emitUnchanged(i - 1);
result.emitMatchIndex(0, i + 1, caseOps);
caseOps.length = 0;
continue;
}
if (49 /* Digit1 */ <= nextChCode && nextChCode <= 57 /* Digit9 */) {
// $n
let matchIndex = nextChCode - 48 /* Digit0 */;
// peek next char to probe for $nn
if (i + 1 < len) {
let nextNextChCode = replaceString.charCodeAt(i + 1);
if (48 /* Digit0 */ <= nextNextChCode && nextNextChCode <= 57 /* Digit9 */) {
// $nn
// move to next char
i++;
matchIndex = matchIndex * 10 + (nextNextChCode - 48 /* 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();
}
exports.parseReplaceString = parseReplaceString;
});
/*---------------------------------------------------------------------------------------------
* 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/folding/foldingRanges*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FoldingRegion = exports.FoldingRegions = exports.MAX_LINE_NUMBER = exports.MAX_FOLDING_REGIONS = void 0;
exports.MAX_FOLDING_REGIONS = 0xFFFF;
exports.MAX_LINE_NUMBER = 0xFFFFFF;
const MASK_INDENT = 0xFF000000;
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 Uint32Array(Math.ceil(startIndexes.length / 32));
this._types = types;
this._parentsComputed = false;
}
ensureParentIndices() {
if (!this._parentsComputed) {
this._parentsComputed = true;
let parentIndexes = [];
let isInsideLast = (startLineNumber, endLineNumber) => {
let 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++) {
let startLineNumber = this._startIndexes[i];
let 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();
}
let 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) {
let arrayIndex = (index / 32) | 0;
let bit = index % 32;
return (this._collapseStates[arrayIndex] & (1 << bit)) !== 0;
}
setCollapsed(index, newState) {
let arrayIndex = (index / 32) | 0;
let bit = index % 32;
let value = this._collapseStates[arrayIndex];
if (newState) {
this._collapseStates[arrayIndex] = value | (1 << bit);
}
else {
this._collapseStates[arrayIndex] = value & ~(1 << bit);
}
}
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();
let 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) {
let 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) {
let 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() {
let res = [];
for (let i = 0; i < this.length; i++) {
res[i] = `[${this.isCollapsed(i) ? '+' : '-'}] ${this.getStartLineNumber(i)}/${this.getEndLineNumber(i)}`;
}
return res.join(', ');
}
}
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[413/*vs/editor/contrib/folding/foldingModel*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,178/*vs/editor/contrib/folding/foldingRanges*/]), function (require, exports, event_1, foldingRanges_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getNextFoldLine = exports.getPreviousFoldLine = exports.getParentFoldLine = exports.setCollapseStateForType = exports.setCollapseStateForMatchingLines = exports.setCollapseStateForRest = exports.setCollapseStateAtLevel = exports.setCollapseStateUp = exports.setCollapseStateLevelsUp = exports.setCollapseStateLevelsDown = exports.toggleCollapseState = exports.FoldingModel = void 0;
class FoldingModel {
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 = [];
this._isInitialized = false;
}
get regions() { return this._regions; }
get textModel() { return this._textModel; }
get isInitialized() { return this._isInitialized; }
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) {
accessor.changeDecorationOptions(this._editorDecorationIds[k], this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine));
}
if (isCollapsed && endLineNumber > lastHiddenLine) {
lastHiddenLine = endLineNumber;
}
k++;
}
};
for (let region of toggledRegions) {
let index = region.regionIndex;
let editorDecorationId = this._editorDecorationIds[index];
if (editorDecorationId && !processed[editorDecorationId]) {
processed[editorDecorationId] = true;
updateDecorationsUntil(index); // update all decorations up to current index using the old dirtyRegionEndLine
let 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 });
}
update(newRegions, blockedLineNumers = []) {
let newEditorDecorations = [];
let isBlocked = (startLineNumber, endLineNumber) => {
for (let blockedLineNumber of blockedLineNumers) {
if (startLineNumber < blockedLineNumber && blockedLineNumber <= endLineNumber) { // first line is visible
return true;
}
}
return false;
};
let lastHiddenLine = -1;
let initRange = (index, isCollapsed) => {
const startLineNumber = newRegions.getStartLineNumber(index);
const endLineNumber = newRegions.getEndLineNumber(index);
if (!isCollapsed) {
isCollapsed = newRegions.isCollapsed(index);
}
if (isCollapsed && isBlocked(startLineNumber, endLineNumber)) {
isCollapsed = false;
}
newRegions.setCollapsed(index, isCollapsed);
const maxColumn = this._textModel.getLineMaxColumn(startLineNumber);
const decorationRange = {
startLineNumber: startLineNumber,
startColumn: Math.max(maxColumn - 1, 1),
endLineNumber: startLineNumber,
endColumn: maxColumn
};
newEditorDecorations.push({ range: decorationRange, options: this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine) });
if (isCollapsed && endLineNumber > lastHiddenLine) {
lastHiddenLine = endLineNumber;
}
};
let i = 0;
let nextCollapsed = () => {
while (i < this._regions.length) {
let isCollapsed = this._regions.isCollapsed(i);
i++;
if (isCollapsed) {
return i - 1;
}
}
return -1;
};
let k = 0;
let collapsedIndex = nextCollapsed();
while (collapsedIndex !== -1 && k < newRegions.length) {
// get the latest range
let decRange = this._textModel.getDecorationRange(this._editorDecorationIds[collapsedIndex]);
if (decRange) {
let collapsedStartLineNumber = decRange.startLineNumber;
if (decRange.startColumn === Math.max(decRange.endColumn - 1, 1) && this._textModel.getLineMaxColumn(collapsedStartLineNumber) === decRange.endColumn) { // test that the decoration is still covering the full line else it got deleted
while (k < newRegions.length) {
let startLineNumber = newRegions.getStartLineNumber(k);
if (collapsedStartLineNumber >= startLineNumber) {
initRange(k, collapsedStartLineNumber === startLineNumber);
k++;
}
else {
break;
}
}
}
}
collapsedIndex = nextCollapsed();
}
while (k < newRegions.length) {
initRange(k, false);
k++;
}
this._editorDecorationIds = this._decorationProvider.deltaDecorations(this._editorDecorationIds, newEditorDecorations);
this._regions = newRegions;
this._isInitialized = true;
this._updateEventEmitter.fire({ model: this });
}
/**
* Collapse state memento, for persistence only
*/
getMemento() {
let collapsedRanges = [];
for (let i = 0; i < this._regions.length; i++) {
if (this._regions.isCollapsed(i)) {
let range = this._textModel.getDecorationRange(this._editorDecorationIds[i]);
if (range) {
let startLineNumber = range.startLineNumber;
let endLineNumber = range.endLineNumber + this._regions.getEndLineNumber(i) - this._regions.getStartLineNumber(i);
collapsedRanges.push({ startLineNumber, endLineNumber });
}
}
}
if (collapsedRanges.length > 0) {
return collapsedRanges;
}
return undefined;
}
/**
* Apply persisted state, for persistence only
*/
applyMemento(state) {
if (!Array.isArray(state)) {
return;
}
let toToogle = [];
for (let range of state) {
let region = this.getRegionAtLine(range.startLineNumber);
if (region && !region.isCollapsed) {
toToogle.push(region);
}
}
this.toggleCollapseState(toToogle);
}
dispose() {
this._decorationProvider.deltaDecorations(this._editorDecorationIds, []);
}
getAllRegionsAtLine(lineNumber, filter) {
let result = [];
if (this._regions) {
let index = this._regions.findRange(lineNumber);
let level = 1;
while (index >= 0) {
let current = this._regions.toRegion(index);
if (!filter || filter(current, level)) {
result.push(current);
}
level++;
index = current.parentIndex;
}
}
return result;
}
getRegionAtLine(lineNumber) {
if (this._regions) {
let index = this._regions.findRange(lineNumber);
if (index >= 0) {
return this._regions.toRegion(index);
}
}
return null;
}
getRegionsInside(region, filter) {
let result = [];
let index = region ? region.regionIndex + 1 : 0;
let 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++) {
let 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++) {
let 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) {
let toToggle = [];
for (let lineNumber of lineNumbers) {
let region = foldingModel.getRegionAtLine(lineNumber);
if (region) {
const doCollapse = !region.isCollapsed;
toToggle.push(region);
if (levels > 1) {
let regionsInside = foldingModel.getRegionsInside(region, (r, level) => r.isCollapsed !== doCollapse && level < levels);
toToggle.push(...regionsInside);
}
}
}
foldingModel.toggleCollapseState(toToggle);
}
exports.toggleCollapseState = toggleCollapseState;
/**
* 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) {
let toToggle = [];
if (lineNumbers && lineNumbers.length > 0) {
for (let lineNumber of lineNumbers) {
let region = foldingModel.getRegionAtLine(lineNumber);
if (region) {
if (region.isCollapsed !== doCollapse) {
toToggle.push(region);
}
if (levels > 1) {
let regionsInside = foldingModel.getRegionsInside(region, (r, level) => r.isCollapsed !== doCollapse && level < levels);
toToggle.push(...regionsInside);
}
}
}
}
else {
let regionsInside = foldingModel.getRegionsInside(null, (r, level) => r.isCollapsed !== doCollapse && level < levels);
toToggle.push(...regionsInside);
}
foldingModel.toggleCollapseState(toToggle);
}
exports.setCollapseStateLevelsDown = setCollapseStateLevelsDown;
/**
* 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) {
let toToggle = [];
for (let lineNumber of lineNumbers) {
let regions = foldingModel.getAllRegionsAtLine(lineNumber, (region, level) => region.isCollapsed !== doCollapse && level <= levels);
toToggle.push(...regions);
}
foldingModel.toggleCollapseState(toToggle);
}
exports.setCollapseStateLevelsUp = setCollapseStateLevelsUp;
/**
* 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) {
let toToggle = [];
for (let lineNumber of lineNumbers) {
let regions = foldingModel.getAllRegionsAtLine(lineNumber, (region) => region.isCollapsed !== doCollapse);
if (regions.length > 0) {
toToggle.push(regions[0]);
}
}
foldingModel.toggleCollapseState(toToggle);
}
exports.setCollapseStateUp = setCollapseStateUp;
/**
* 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) {
let filter = (region, level) => level === foldLevel && region.isCollapsed !== doCollapse && !blockedLineNumbers.some(line => region.containsLine(line));
let toToggle = foldingModel.getRegionsInside(null, filter);
foldingModel.toggleCollapseState(toToggle);
}
exports.setCollapseStateAtLevel = setCollapseStateAtLevel;
/**
* 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) {
let filteredRegions = [];
for (let lineNumber of blockedLineNumbers) {
filteredRegions.push(foldingModel.getAllRegionsAtLine(lineNumber, undefined)[0]);
}
let filter = (region) => filteredRegions.every((filteredRegion) => !filteredRegion.containedBy(region) && !region.containedBy(filteredRegion)) && region.isCollapsed !== doCollapse;
let toToggle = foldingModel.getRegionsInside(null, filter);
foldingModel.toggleCollapseState(toToggle);
}
exports.setCollapseStateForRest = setCollapseStateForRest;
/**
* Folds all regions for which the lines start with a given regex
* @param foldingModel the folding model
*/
function setCollapseStateForMatchingLines(foldingModel, regExp, doCollapse) {
let editorModel = foldingModel.textModel;
let regions = foldingModel.regions;
let toToggle = [];
for (let i = regions.length - 1; i >= 0; i--) {
if (doCollapse !== regions.isCollapsed(i)) {
let startLineNumber = regions.getStartLineNumber(i);
if (regExp.test(editorModel.getLineContent(startLineNumber))) {
toToggle.push(regions.toRegion(i));
}
}
}
foldingModel.toggleCollapseState(toToggle);
}
exports.setCollapseStateForMatchingLines = setCollapseStateForMatchingLines;
/**
* Folds all regions of the given type
* @param foldingModel the folding model
*/
function setCollapseStateForType(foldingModel, type, doCollapse) {
let regions = foldingModel.regions;
let 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);
}
exports.setCollapseStateForType = setCollapseStateForType;
/**
* 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;
let 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) {
let parentFoldingIdx = foldingRegion.parentIndex;
if (parentFoldingIdx !== -1) {
startLineNumber = foldingModel.regions.getStartLineNumber(parentFoldingIdx);
}
else {
startLineNumber = null;
}
}
}
return startLineNumber;
}
exports.getParentFoldLine = getParentFoldLine;
/**
* 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 (foldingRegion !== null) {
// 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.
let expectedParentIndex = foldingRegion.parentIndex;
if (expectedParentIndex === -1) {
return null;
}
let 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;
}
}
}
}
return null;
}
exports.getPreviousFoldLine = getPreviousFoldLine;
/**
* 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 (foldingRegion !== null) {
// Find max line number to stay within parent.
let expectedParentIndex = foldingRegion.parentIndex;
if (expectedParentIndex === -1) {
return null;
}
let maxLineNumber = foldingModel.regions.getEndLineNumber(foldingRegion.parentIndex);
// 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;
}
}
}
return null;
}
exports.getNextFoldLine = getNextFoldLine;
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/folding/hiddenRangeModel*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,3/*vs/editor/common/core/range*/,19/*vs/base/common/arrays*/]), function (require, exports, event_1, range_1, arrays_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HiddenRangeModel = void 0;
class HiddenRangeModel {
constructor(model) {
this._updateEventEmitter = new event_1.Emitter();
this._foldingModel = model;
this._foldingModelListener = model.onDidChange(_ => this.updateHiddenRanges());
this._hiddenRanges = [];
if (model.regions.length) {
this.updateHiddenRanges();
}
}
get onDidChange() { return this._updateEventEmitter.event; }
get hiddenRanges() { return this._hiddenRanges; }
updateHiddenRanges() {
let updateHiddenAreas = false;
let newHiddenAreas = [];
let i = 0; // index into hidden
let k = 0;
let lastCollapsedStart = Number.MAX_VALUE;
let lastCollapsedEnd = -1;
let ranges = this._foldingModel.regions;
for (; i < ranges.length; i++) {
if (!ranges.isCollapsed(i)) {
continue;
}
let startLineNumber = ranges.getStartLineNumber(i) + 1; // the first line is not hidden
let 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 (updateHiddenAreas || k < this._hiddenRanges.length) {
this.applyHiddenRanges(newHiddenAreas);
}
}
applyMemento(state) {
if (!Array.isArray(state) || state.length === 0) {
return false;
}
let hiddenRanges = [];
for (let r of state) {
if (!r.startLineNumber || !r.endLineNumber) {
return false;
}
hiddenRanges.push(new range_1.Range(r.startLineNumber + 1, 1, r.endLineNumber, 1));
}
this.applyHiddenRanges(hiddenRanges);
return true;
}
/**
* Collapse state memento, for persistence only, only used if folding model is not yet initialized
*/
getMemento() {
return this._hiddenRanges.map(r => ({ startLineNumber: r.startLineNumber - 1, endLineNumber: r.endLineNumber }));
}
applyHiddenRanges(newHiddenAreas) {
this._hiddenRanges = newHiddenAreas;
this._updateEventEmitter.fire(newHiddenAreas);
}
hasRanges() {
return this._hiddenRanges.length > 0;
}
isHidden(line) {
return findRange(this._hiddenRanges, line) !== null;
}
adjustSelections(selections) {
let hasChanges = false;
let editorModel = this._foldingModel.textModel;
let lastRange = null;
let 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];
let adjustedStartLine = adjustLine(selection.startLineNumber);
if (adjustedStartLine) {
selection = selection.setStartPosition(adjustedStartLine, editorModel.getLineMaxColumn(adjustedStartLine));
hasChanges = true;
}
let 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) {
let i = (0, arrays_1.findFirstInSorted)(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[227/*vs/editor/contrib/folding/syntaxRangeProvider*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,178/*vs/editor/contrib/folding/foldingRanges*/,2/*vs/base/common/lifecycle*/]), function (require, exports, errors_1, foldingRanges_1, lifecycle_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sanitizeRanges = exports.RangesCollector = exports.SyntaxRangeProvider = exports.ID_SYNTAX_PROVIDER = void 0;
const MAX_FOLDING_REGIONS = 5000;
const foldingContext = {};
exports.ID_SYNTAX_PROVIDER = 'syntax';
class SyntaxRangeProvider {
constructor(editorModel, providers, handleFoldingRangesChange, limit = MAX_FOLDING_REGIONS) {
this.editorModel = editorModel;
this.providers = providers;
this.limit = limit;
this.id = exports.ID_SYNTAX_PROVIDER;
for (const provider of providers) {
if (typeof provider.onDidChange === 'function') {
if (!this.disposables) {
this.disposables = new lifecycle_1.DisposableStore();
}
this.disposables.add(provider.onDidChange(handleFoldingRangesChange));
}
}
}
compute(cancellationToken) {
return collectSyntaxRanges(this.providers, this.editorModel, cancellationToken).then(ranges => {
if (ranges) {
let res = sanitizeRanges(ranges, this.limit);
return res;
}
return null;
});
}
dispose() {
var _a;
(_a = this.disposables) === null || _a === void 0 ? void 0 : _a.dispose();
}
}
exports.SyntaxRangeProvider = SyntaxRangeProvider;
function collectSyntaxRanges(providers, model, cancellationToken) {
let rangeData = null;
let 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 = [];
}
let nLines = model.getLineCount();
for (let 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;
}
let 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() {
if (this._length <= this._foldingRangesLimit) {
let startIndexes = new Uint32Array(this._length);
let 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 {
let entries = 0;
let maxLevel = this._nestingLevelCounts.length;
for (let i = 0; i < this._nestingLevelCounts.length; i++) {
let n = this._nestingLevelCounts[i];
if (n) {
if (n + entries > this._foldingRangesLimit) {
maxLevel = i;
break;
}
entries += n;
}
}
let startIndexes = new Uint32Array(this._foldingRangesLimit);
let endIndexes = new Uint32Array(this._foldingRangesLimit);
let types = [];
for (let i = 0, k = 0; i < this._length; i++) {
let level = this._nestingLevels[i];
if (level < maxLevel || (level === maxLevel && entries++ < this._foldingRangesLimit)) {
startIndexes[k] = this._startIndexes[i];
endIndexes[k] = this._endIndexes[i];
types[k] = this._types[i];
k++;
}
}
return new foldingRanges_1.FoldingRegions(startIndexes, endIndexes, types);
}
}
}
exports.RangesCollector = RangesCollector;
function sanitizeRanges(rangeData, limit) {
let sorted = rangeData.sort((d1, d2) => {
let diff = d1.start - d2.start;
if (diff === 0) {
diff = d1.rank - d2.rank;
}
return diff;
});
let collector = new RangesCollector(limit);
let top = undefined;
let previous = [];
for (let 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();
}
exports.sanitizeRanges = sanitizeRanges;
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/folding/intializingRangeProvider*/], __M([0/*require*/,1/*exports*/,227/*vs/editor/contrib/folding/syntaxRangeProvider*/]), function (require, exports, syntaxRangeProvider_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InitializingRangeProvider = exports.ID_INIT_PROVIDER = void 0;
exports.ID_INIT_PROVIDER = 'init';
class InitializingRangeProvider {
constructor(editorModel, initialRanges, onTimeout, timeoutTime) {
this.editorModel = editorModel;
this.id = exports.ID_INIT_PROVIDER;
if (initialRanges.length) {
let toDecorationRange = (range) => {
return {
range: {
startLineNumber: range.startLineNumber,
startColumn: 0,
endLineNumber: range.endLineNumber,
endColumn: editorModel.getLineLength(range.endLineNumber)
},
options: {
description: 'folding-initializing-range-provider',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */
}
};
};
this.decorationIds = editorModel.deltaDecorations([], initialRanges.map(toDecorationRange));
this.timeout = setTimeout(onTimeout, timeoutTime);
}
}
dispose() {
if (this.decorationIds) {
this.editorModel.deltaDecorations(this.decorationIds, []);
this.decorationIds = undefined;
}
if (typeof this.timeout === 'number') {
clearTimeout(this.timeout);
this.timeout = undefined;
}
}
compute(cancelationToken) {
let foldingRangeData = [];
if (this.decorationIds) {
for (let id of this.decorationIds) {
let range = this.editorModel.getDecorationRange(id);
if (range) {
foldingRangeData.push({ start: range.startLineNumber, end: range.endLineNumber, rank: 1 });
}
}
}
return Promise.resolve((0, syntaxRangeProvider_1.sanitizeRanges)(foldingRangeData, Number.MAX_VALUE));
}
}
exports.InitializingRangeProvider = InitializingRangeProvider;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[228/*vs/editor/contrib/format/formattingEdit*/], __M([0/*require*/,1/*exports*/,56/*vs/editor/common/core/editOperation*/,3/*vs/editor/common/core/range*/]), function (require, exports, editOperation_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FormattingEdit = void 0;
class FormattingEdit {
static _handleEolEdits(editor, edits) {
let newEol = undefined;
let singleEdits = [];
for (let 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 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();
}
}
}
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[229/*vs/editor/contrib/gotoSymbol/link/clickLinkGesture*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/,17/*vs/base/common/platform*/]), function (require, exports, lifecycle_1, event_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.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 /* Meta */, 'metaKey', 6 /* Alt */, 'altKey');
}
return new ClickLinkOptions(5 /* Ctrl */, 'ctrlKey', 6 /* Alt */, 'altKey');
}
if (platform.isMacintosh) {
return new ClickLinkOptions(6 /* Alt */, 'altKey', 57 /* Meta */, 'metaKey');
}
return new ClickLinkOptions(6 /* Alt */, 'altKey', 5 /* Ctrl */, 'ctrlKey');
}
class ClickLinkGesture extends lifecycle_1.Disposable {
constructor(editor) {
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._opts = createOptions(this._editor.getOption(68 /* multiCursorModifier */));
this._lastMouseMoveEvent = null;
this._hasTriggerKeyOnMouseDown = false;
this._lineNumberOnMouseDown = 0;
this._register(this._editor.onDidChangeConfiguration((e) => {
if (e.hasChanged(68 /* multiCursorModifier */)) {
const newOpts = createOptions(this._editor.getOption(68 /* 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 = mouseEvent.target.position ? mouseEvent.target.position.lineNumber : 0;
}
_onEditorMouseUp(mouseEvent) {
const currentLineNumber = mouseEvent.target.position ? mouseEvent.target.position.lineNumber : 0;
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[230/*vs/editor/contrib/hover/hoverOperation*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,12/*vs/base/common/errors*/]), function (require, exports, async_1, errors_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HoverOperation = void 0;
class HoverOperation {
constructor(computer, success, error, progress, hoverTime) {
this._computer = computer;
this._state = 0 /* IDLE */;
this._hoverTime = hoverTime;
this._firstWaitScheduler = new async_1.RunOnceScheduler(() => this._triggerAsyncComputation(), 0);
this._secondWaitScheduler = new async_1.RunOnceScheduler(() => this._triggerSyncComputation(), 0);
this._loadingMessageScheduler = new async_1.RunOnceScheduler(() => this._showLoadingMessage(), 0);
this._asyncComputationPromise = null;
this._asyncComputationPromiseDone = false;
this._completeCallback = success;
this._errorCallback = error;
this._progressCallback = progress;
}
setHoverTime(hoverTime) {
this._hoverTime = hoverTime;
}
_firstWaitTime() {
return this._hoverTime / 2;
}
_secondWaitTime() {
return this._hoverTime / 2;
}
_loadingMessageTime() {
return 3 * this._hoverTime;
}
_triggerAsyncComputation() {
this._state = 2 /* SECOND_WAIT */;
this._secondWaitScheduler.schedule(this._secondWaitTime());
if (this._computer.computeAsync) {
this._asyncComputationPromiseDone = false;
this._asyncComputationPromise = (0, async_1.createCancelablePromise)(token => this._computer.computeAsync(token));
this._asyncComputationPromise.then((asyncResult) => {
this._asyncComputationPromiseDone = true;
this._withAsyncResult(asyncResult);
}, (e) => this._onError(e));
}
else {
this._asyncComputationPromiseDone = true;
}
}
_triggerSyncComputation() {
if (this._computer.computeSync) {
this._computer.onResult(this._computer.computeSync(), true);
}
if (this._asyncComputationPromiseDone) {
this._state = 0 /* IDLE */;
this._onComplete(this._computer.getResult());
}
else {
this._state = 3 /* WAITING_FOR_ASYNC_COMPUTATION */;
this._onProgress(this._computer.getResult());
}
}
_showLoadingMessage() {
if (this._state === 3 /* WAITING_FOR_ASYNC_COMPUTATION */) {
this._onProgress(this._computer.getResultWithLoadingMessage());
}
}
_withAsyncResult(asyncResult) {
if (asyncResult) {
this._computer.onResult(asyncResult, false);
}
if (this._state === 3 /* WAITING_FOR_ASYNC_COMPUTATION */) {
this._state = 0 /* IDLE */;
this._onComplete(this._computer.getResult());
}
}
_onComplete(value) {
this._completeCallback(value);
}
_onError(error) {
if (this._errorCallback) {
this._errorCallback(error);
}
else {
(0, errors_1.onUnexpectedError)(error);
}
}
_onProgress(value) {
this._progressCallback(value);
}
start(mode) {
if (mode === 0 /* Delayed */) {
if (this._state === 0 /* IDLE */) {
this._state = 1 /* FIRST_WAIT */;
this._firstWaitScheduler.schedule(this._firstWaitTime());
this._loadingMessageScheduler.schedule(this._loadingMessageTime());
}
}
else {
switch (this._state) {
case 0 /* IDLE */:
this._triggerAsyncComputation();
this._secondWaitScheduler.cancel();
this._triggerSyncComputation();
break;
case 2 /* SECOND_WAIT */:
this._secondWaitScheduler.cancel();
this._triggerSyncComputation();
break;
}
}
}
cancel() {
this._loadingMessageScheduler.cancel();
if (this._state === 1 /* FIRST_WAIT */) {
this._firstWaitScheduler.cancel();
}
if (this._state === 2 /* SECOND_WAIT */) {
this._secondWaitScheduler.cancel();
if (this._asyncComputationPromise) {
this._asyncComputationPromise.cancel();
this._asyncComputationPromise = null;
}
}
if (this._state === 3 /* WAITING_FOR_ASYNC_COMPUTATION */) {
if (this._asyncComputationPromise) {
this._asyncComputationPromise.cancel();
this._asyncComputationPromise = null;
}
}
this._state = 0 /* IDLE */;
}
}
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[231/*vs/editor/contrib/hover/hoverTypes*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HoverForeignElementAnchor = exports.HoverRangeAnchor = void 0;
class HoverRangeAnchor {
constructor(priority, range) {
this.priority = priority;
this.range = range;
this.type = 1 /* Range */;
}
equals(other) {
return (other.type === 1 /* Range */ && this.range.equalsRange(other.range));
}
canAdoptVisibleHover(lastAnchor, showAtPosition) {
return (lastAnchor.type === 1 /* Range */ && showAtPosition.lineNumber === this.range.startLineNumber);
}
}
exports.HoverRangeAnchor = HoverRangeAnchor;
class HoverForeignElementAnchor {
constructor(priority, owner, range) {
this.priority = priority;
this.owner = owner;
this.range = range;
this.type = 2 /* ForeignElement */;
}
equals(other) {
return (other.type === 2 /* ForeignElement */ && this.owner === other.owner);
}
canAdoptVisibleHover(lastAnchor, showAtPosition) {
return (lastAnchor.type === 2 /* ForeignElement */ && this.owner === lastAnchor.owner);
}
}
exports.HoverForeignElementAnchor = HoverForeignElementAnchor;
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/hover/hoverWidgets*/], __M([0/*require*/,1/*exports*/,52/*vs/base/browser/ui/widget*/]), function (require, exports, widget_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GlyphHoverWidget = void 0;
class GlyphHoverWidget extends widget_1.Widget {
constructor(id, editor) {
super();
this._id = id;
this._editor = editor;
this._isVisible = false;
this._domNode = document.createElement('div');
this._domNode.className = 'monaco-hover hidden';
this._domNode.setAttribute('aria-hidden', 'true');
this._domNode.setAttribute('role', 'tooltip');
this._showAtLineNumber = -1;
this._register(this._editor.onDidChangeConfiguration((e) => {
if (e.hasChanged(41 /* fontInfo */)) {
this.updateFont();
}
}));
this._editor.addOverlayWidget(this);
}
get isVisible() {
return this._isVisible;
}
set isVisible(value) {
this._isVisible = value;
this._domNode.classList.toggle('hidden', !this._isVisible);
}
getId() {
return this._id;
}
getDomNode() {
return this._domNode;
}
showAt(lineNumber) {
this._showAtLineNumber = lineNumber;
if (!this.isVisible) {
this.isVisible = true;
}
const editorLayout = this._editor.getLayoutInfo();
const topForLineNumber = this._editor.getTopForLineNumber(this._showAtLineNumber);
const editorScrollTop = this._editor.getScrollTop();
const lineHeight = this._editor.getOption(57 /* lineHeight */);
const nodeHeight = this._domNode.clientHeight;
const top = topForLineNumber - editorScrollTop - ((nodeHeight - lineHeight) / 2);
this._domNode.style.left = `${editorLayout.glyphMarginLeft + editorLayout.glyphMarginWidth}px`;
this._domNode.style.top = `${Math.max(Math.round(top), 0)}px`;
}
hide() {
if (!this.isVisible) {
return;
}
this.isVisible = false;
}
getPosition() {
return null;
}
dispose() {
this._editor.removeOverlayWidget(this);
super.dispose();
}
updateFont() {
const codeTags = Array.prototype.slice.call(this._domNode.getElementsByTagName('code'));
const codeClasses = Array.prototype.slice.call(this._domNode.getElementsByClassName('code'));
[...codeTags, ...codeClasses].forEach(node => this._editor.applyFontInfo(node));
}
updateContents(node) {
this._domNode.textContent = '';
this._domNode.appendChild(node);
this.updateFont();
}
}
exports.GlyphHoverWidget = GlyphHoverWidget;
});
/*---------------------------------------------------------------------------------------------
* 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/inPlaceReplace/inPlaceReplaceCommand*/], __M([0/*require*/,1/*exports*/,21/*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[232/*vs/editor/contrib/indentation/indentUtils*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateIndent = exports.getSpaceCnt = void 0;
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;
}
exports.getSpaceCnt = getSpaceCnt;
function generateIndent(spacesCnt, tabSize, insertSpaces) {
spacesCnt = spacesCnt < 0 ? 0 : spacesCnt;
let result = '';
if (!insertSpaces) {
let 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;
}
exports.generateIndent = generateIndent;
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/inlineCompletions/ghostText*/], __M([0/*require*/,1/*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.BaseGhostTextWidgetModel = exports.GhostTextPart = exports.GhostText = void 0;
class GhostText {
constructor(lineNumber, parts, additionalReservedLineCount = 0) {
this.lineNumber = lineNumber;
this.parts = parts;
this.additionalReservedLineCount = additionalReservedLineCount;
}
static equals(a, b) {
return a === b || (!!a && !!b && a.equals(b));
}
equals(other) {
return this.lineNumber === other.lineNumber &&
this.parts.length === other.parts.length &&
this.parts.every((part, index) => part.equals(other.parts[index]));
}
}
exports.GhostText = GhostText;
class GhostTextPart {
constructor(column, lines) {
this.column = column;
this.lines = lines;
}
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 BaseGhostTextWidgetModel extends lifecycle_1.Disposable {
constructor(editor) {
super();
this.editor = editor;
this._expanded = undefined;
this.onDidChangeEmitter = new event_1.Emitter();
this.onDidChange = this.onDidChangeEmitter.event;
this._register(editor.onDidChangeConfiguration((e) => {
if (e.hasChanged(105 /* suggest */) && this._expanded === undefined) {
this.onDidChangeEmitter.fire();
}
}));
}
get expanded() {
if (this._expanded === undefined) {
// TODO this should use a global hidden setting.
// See https://github.com/microsoft/vscode/issues/125037.
return true;
}
return this._expanded;
}
setExpanded(expanded) {
this._expanded = true;
this.onDidChangeEmitter.fire();
}
}
exports.BaseGhostTextWidgetModel = BaseGhostTextWidgetModel;
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/inlineCompletions/utils*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDisposableRef = void 0;
function createDisposableRef(object, disposable) {
return {
object,
dispose: () => disposable === null || disposable === void 0 ? void 0 : disposable.dispose(),
};
}
exports.createDisposableRef = createDisposableRef;
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/linesOperations/copyLinesCommand*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,21/*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 /* 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));
}
let 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[420/*vs/editor/contrib/linesOperations/sortLinesCommand*/], __M([0/*require*/,1/*exports*/,56/*vs/editor/common/core/editOperation*/,3/*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 {
constructor(selection, descending) {
this.selection = selection;
this.descending = descending;
this.selectionId = null;
}
static getCollator() {
if (!SortLinesCommand._COLLATOR) {
SortLinesCommand._COLLATOR = new Intl.Collator();
}
return SortLinesCommand._COLLATOR;
}
getEditOperations(model, builder) {
let 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;
}
let 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;
SortLinesCommand._COLLATOR = null;
function getSortData(model, selection, descending) {
let 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;
}
let 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) {
let 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[234/*vs/editor/contrib/smartSelect/bracketSelections*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,72/*vs/base/common/linkedList*/]), function (require, exports, position_1, range_1, linkedList_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BracketSelectionRangeProvider = void 0;
class BracketSelectionRangeProvider {
provideSelectionRanges(model, positions) {
return __awaiter(this, void 0, void 0, function* () {
const result = [];
for (const position of positions) {
const bucket = [];
result.push(bucket);
const ranges = new Map();
yield new Promise(resolve => BracketSelectionRangeProvider._bracketsRightYield(resolve, 0, model, position, ranges));
yield new Promise(resolve => BracketSelectionRangeProvider._bracketsLeftYield(resolve, 0, model, position, ranges, bucket));
}
return result;
});
}
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;
}
let bracket = model.findNextBracket(pos);
if (!bracket) {
resolve();
break;
}
let d = Date.now() - t1;
if (d > BracketSelectionRangeProvider._maxDuration) {
setTimeout(() => BracketSelectionRangeProvider._bracketsRightYield(resolve, round + 1, model, pos, ranges));
break;
}
const key = bracket.close[0];
if (bracket.isOpen) {
// wait for closing
let val = counts.has(key) ? counts.get(key) : 0;
counts.set(key, val + 1);
}
else {
// 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;
}
let bracket = model.findPrevBracket(pos);
if (!bracket) {
resolve();
break;
}
let d = Date.now() - t1;
if (d > BracketSelectionRangeProvider._maxDuration) {
setTimeout(() => BracketSelectionRangeProvider._bracketsLeftYield(resolve, round + 1, model, pos, ranges, bucket));
break;
}
const key = bracket.close[0];
if (!bracket.isOpen) {
// wait for opening
let val = counts.has(key) ? counts.get(key) : 0;
counts.set(key, val + 1);
}
else {
// opening
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) {
let 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;
BracketSelectionRangeProvider._maxDuration = 30;
BracketSelectionRangeProvider._maxRounds = 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/smartSelect/wordSelections*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,8/*vs/base/common/strings*/]), function (require, exports, range_1, strings_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WordSelectionRangeProvider = void 0;
class WordSelectionRangeProvider {
provideSelectionRanges(model, positions) {
const result = [];
for (const position of positions) {
const bucket = [];
result.push(bucket);
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;
}
let { word, startColumn } = obj;
let offset = pos.column - startColumn;
let start = offset;
let end = offset;
let lastCh = 0;
// LEFT anchor (start)
for (; start >= 0; start--) {
let ch = word.charCodeAt(start);
if ((start !== offset) && (ch === 95 /* Underline */ || ch === 45 /* 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++) {
let ch = word.charCodeAt(end);
if ((0, strings_1.isUpperAsciiLetter)(ch) && (0, strings_1.isLowerAsciiLetter)(lastCh)) {
// fooBar
break;
}
else if (ch === 95 /* Underline */ || ch === 45 /* 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[116/*vs/editor/contrib/snippet/snippetParser*/], __M([0/*require*/,1/*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 isDigitCharacter(ch) {
return ch >= 48 /* Digit0 */ && ch <= 57 /* Digit9 */;
}
static isVariableCharacter(ch) {
return ch === 95 /* Underline */
|| (ch >= 97 /* a */ && ch <= 122 /* z */)
|| (ch >= 65 /* A */ && ch <= 90 /* 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 /* EOF */, pos: this.pos, len: 0 };
}
let 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 /* 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 /* 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 /* 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;
Scanner._table = {
[36 /* DollarSign */]: 0 /* Dollar */,
[58 /* Colon */]: 1 /* Colon */,
[44 /* Comma */]: 2 /* Comma */,
[123 /* OpenCurlyBrace */]: 3 /* CurlyOpen */,
[125 /* CloseCurlyBrace */]: 4 /* CurlyClose */,
[92 /* Backslash */]: 5 /* Backslash */,
[47 /* Slash */]: 6 /* Forwardslash */,
[124 /* Pipe */]: 7 /* Pipe */,
[43 /* Plus */]: 11 /* Plus */,
[45 /* Dash */]: 12 /* Dash */,
[63 /* QuestionMark */]: 13 /* QuestionMark */,
};
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 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 {
constructor(index) {
super();
this.index = index;
}
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;
}
}
get isFinalTabstop() {
return this.index === 0;
}
get choice() {
return this._children.length === 1 && this._children[0] instanceof Choice
? this._children[0]
: undefined;
}
clone() {
let 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() {
let 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() {
let 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).toLowerCase();
})
.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.toLowerCase();
}
else {
return word.charAt(0).toUpperCase()
+ word.substr(1).toLowerCase();
}
})
.join('');
}
clone() {
let 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
let 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) {
let 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() {
let 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 /* EOF */, pos: 0, len: 0 };
}
static escape(value) {
return value.replace(/\$|}|\\/g, '\\$&');
}
static guessNeedsClipboard(template) {
return /\${?CLIPBOARD/.test(template);
}
parse(value, insertFinalTabstop, enforceFinalTabstop) {
this._scanner.text(value);
this._token = this._scanner.next();
const snippet = new TextmateSnippet();
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 = [];
let placeholderCount = 0;
snippet.walk(marker => {
if (marker instanceof Placeholder) {
placeholderCount += 1;
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;
});
for (const placeholder of incompletePlaceholders) {
const defaultValues = placeholderDefaultValues.get(placeholder.index);
if (defaultValues) {
const clone = new Placeholder(placeholder.index);
clone.transform = placeholder.transform;
for (const child of defaultValues) {
clone.appendChild(child.clone());
}
snippet.replace(placeholder, [clone]);
}
}
if (!enforceFinalTabstop) {
enforceFinalTabstop = placeholderCount > 0 && insertFinalTabstop;
}
if (!placeholderDefaultValues.has(0) && enforceFinalTabstop) {
// the snippet uses placeholders but has no
// final tabstop defined -> insert at the end
snippet.appendChild(new Placeholder(0));
}
return snippet;
}
_accept(type, value) {
if (type === undefined || this._token.type === type) {
let 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 /* EOF */) {
return false;
}
else if (this._token.type === 5 /* Backslash */) {
const nextToken = this._scanner.next();
if (nextToken.type !== 0 /* Dollar */
&& nextToken.type !== 4 /* CurlyClose */
&& nextToken.type !== 5 /* 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 /* Backslash */, true)) {
// saw a backslash, append escaped token or that backslash
value = this._accept(0 /* Dollar */, true)
|| this._accept(4 /* CurlyClose */, true)
|| this._accept(5 /* 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 /* Dollar */)
&& (value = this._accept(9 /* VariableName */, true) || this._accept(8 /* 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 /* Dollar */)
&& this._accept(3 /* CurlyOpen */)
&& (index = this._accept(8 /* Int */, true));
if (!match) {
return this._backTo(token);
}
const placeholder = new Placeholder(Number(index));
if (this._accept(1 /* Colon */)) {
// ${1:<children>}
while (true) {
// ...} -> done
if (this._accept(4 /* 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 /* Pipe */)) {
// ${1|one,two,three|}
const choice = new Choice();
while (true) {
if (this._parseChoiceElement(choice)) {
if (this._accept(2 /* Comma */)) {
// opt, -> more
continue;
}
if (this._accept(7 /* Pipe */)) {
placeholder.appendChild(choice);
if (this._accept(4 /* CurlyClose */)) {
// ..|} -> done
parent.appendChild(placeholder);
return true;
}
}
}
this._backTo(token);
return false;
}
}
else if (this._accept(6 /* Forwardslash */)) {
// ${1/<regex>/<format>/<options>}
if (this._parseTransform(placeholder)) {
parent.appendChild(placeholder);
return true;
}
this._backTo(token);
return false;
}
else if (this._accept(4 /* 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 /* Comma */ || this._token.type === 7 /* Pipe */) {
break;
}
let value;
if (value = this._accept(5 /* Backslash */, true)) {
// \, \|, or \\
value = this._accept(2 /* Comma */, true)
|| this._accept(7 /* Pipe */, true)
|| this._accept(5 /* 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 /* Dollar */)
&& this._accept(3 /* CurlyOpen */)
&& (name = this._accept(9 /* VariableName */, true));
if (!match) {
return this._backTo(token);
}
const variable = new Variable(name);
if (this._accept(1 /* Colon */)) {
// ${foo:<children>}
while (true) {
// ...} -> done
if (this._accept(4 /* 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 /* Forwardslash */)) {
// ${foo/<regex>/<format>/<options>}
if (this._parseTransform(variable)) {
parent.appendChild(variable);
return true;
}
this._backTo(token);
return false;
}
else if (this._accept(4 /* CurlyClose */)) {
// ${foo}
parent.appendChild(variable);
return true;
}
else {
// ${foo <- missing curly or colon
return this._backTo(token);
}
}
_parseTransform(parent) {
// ...<regex>/<format>/<options>}
let transform = new Transform();
let regexValue = '';
let regexOptions = '';
// (1) /regex
while (true) {
if (this._accept(6 /* Forwardslash */)) {
break;
}
let escaped;
if (escaped = this._accept(5 /* Backslash */, true)) {
escaped = this._accept(6 /* Forwardslash */, true) || escaped;
regexValue += escaped;
continue;
}
if (this._token.type !== 14 /* EOF */) {
regexValue += this._accept(undefined, true);
continue;
}
return false;
}
// (2) /format
while (true) {
if (this._accept(6 /* Forwardslash */)) {
break;
}
let escaped;
if (escaped = this._accept(5 /* Backslash */, true)) {
escaped = this._accept(5 /* Backslash */, true) || this._accept(6 /* 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 /* CurlyClose */)) {
break;
}
if (this._token.type !== 14 /* 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 /* Dollar */)) {
return false;
}
let complex = false;
if (this._accept(3 /* CurlyOpen */)) {
complex = true;
}
let index = this._accept(8 /* 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 /* CurlyClose */)) {
// ${1}
parent.appendChild(new FormatString(Number(index)));
return true;
}
else if (!this._accept(1 /* Colon */)) {
this._backTo(token);
return false;
}
if (this._accept(6 /* Forwardslash */)) {
// ${1:/upcase}
let shorthand = this._accept(9 /* VariableName */, true);
if (!shorthand || !this._accept(4 /* CurlyClose */)) {
this._backTo(token);
return false;
}
else {
parent.appendChild(new FormatString(Number(index), shorthand));
return true;
}
}
else if (this._accept(11 /* Plus */)) {
// ${1:+<if>}
let ifValue = this._until(4 /* CurlyClose */);
if (ifValue) {
parent.appendChild(new FormatString(Number(index), undefined, ifValue, undefined));
return true;
}
}
else if (this._accept(12 /* Dash */)) {
// ${2:-<else>}
let elseValue = this._until(4 /* CurlyClose */);
if (elseValue) {
parent.appendChild(new FormatString(Number(index), undefined, undefined, elseValue));
return true;
}
}
else if (this._accept(13 /* QuestionMark */)) {
// ${2:?<if>:<else>}
let ifValue = this._until(1 /* Colon */);
if (ifValue) {
let elseValue = this._until(4 /* CurlyClose */);
if (elseValue) {
parent.appendChild(new FormatString(Number(index), undefined, ifValue, elseValue));
return true;
}
}
}
else {
// ${1:<else>}
let elseValue = this._until(4 /* 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 /* 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[422/*vs/editor/contrib/suggest/completionModel*/], __M([0/*require*/,1/*exports*/,67/*vs/base/common/filters*/,8/*vs/base/common/strings*/,19/*vs/base/common/arrays*/]), function (require, exports, filters_1, strings_1, arrays_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, clipboardText) {
this.clipboardText = clipboardText;
this._snippetCompareFn = CompletionModel._compareCompletionItems;
this._items = items;
this._column = column;
this._wordDistance = wordDistance;
this._options = options;
this._refilterKind = 1 /* All */;
this._lineContext = lineContext;
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 /* Incr */ : 1 /* All */;
this._lineContext = value;
}
}
get items() {
this._ensureCachedState();
return this._filteredItems;
}
get allProvider() {
this._ensureCachedState();
return this._providerInfo.keys();
}
get incomplete() {
this._ensureCachedState();
const result = new Set();
for (let [provider, incomplete] of this._providerInfo) {
if (incomplete) {
result.add(provider);
}
}
return result;
}
adopt(except) {
let res = [];
for (let i = 0; i < this._items.length;) {
if (!except.has(this._items[i].provider)) {
res.push(this._items[i]);
// unordered removed
this._items[i] = this._items[this._items.length - 1];
this._items.pop();
}
else {
// continue with next item
i++;
}
}
this._refilterKind = 1 /* All */;
return res;
}
get stats() {
this._ensureCachedState();
return this._stats;
}
_ensureCachedState() {
if (this._refilterKind !== 0 /* Nothing */) {
this._createCachedState();
}
}
_createCachedState() {
this._providerInfo = new Map();
const labelLengths = [];
const { leadingLineContent, characterCountDelta } = this._lineContext;
let word = '';
let wordLow = '';
// incrementally filter less
const source = this._refilterKind === 1 /* 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
}
// collect all support, know if their result is incomplete
this._providerInfo.set(item.provider, Boolean(item.container.incomplete));
// '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 /* Space */ || ch === 9 /* 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
let match = scoreFn(word, wordLow, wordPos, item.completion.filterText, item.filterTextLow, 0, false);
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`
let match = scoreFn(word, wordLow, wordPos, item.textLabel, item.labelLow, 0, false);
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 /* 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 /* Snippet */) {
return 1;
}
else if (b.completion.kind === 27 /* Snippet */) {
return -1;
}
}
return CompletionModel._compareCompletionItems(a, b);
}
static _compareCompletionItemsSnippetsUp(a, b) {
if (a.completion.kind !== b.completion.kind) {
if (a.completion.kind === 27 /* Snippet */) {
return -1;
}
else if (b.completion.kind === 27 /* 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[235/*vs/editor/contrib/suggest/resizable*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,7/*vs/base/browser/dom*/,107/*vs/base/browser/ui/sash/sash*/]), function (require, exports, event_1, lifecycle_1, dom_1, sash_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 /* VERTICAL */ });
this._westSash = new sash_1.Sash(this.domNode, { getVerticalSashLeft: () => 0 }, { orientation: 0 /* VERTICAL */ });
this._northSash = new sash_1.Sash(this.domNode, { getHorizontalSashTop: () => 0 }, { orientation: 1 /* HORIZONTAL */, orthogonalEdge: sash_1.OrthogonalEdge.North });
this._southSash = new sash_1.Sash(this.domNode, { getHorizontalSashTop: () => this._size.height }, { orientation: 1 /* 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 /* Enabled */ : 0 /* Disabled */;
this._eastSash.state = east ? 3 /* Enabled */ : 0 /* Disabled */;
this._southSash.state = south ? 3 /* Enabled */ : 0 /* Disabled */;
this._westSash.state = west ? 3 /* Enabled */ : 0 /* 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[423/*vs/editor/contrib/suggest/suggestCommitCharacters*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,94/*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, accept) {
this._disposables = new lifecycle_1.DisposableStore();
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()) {
const ch = text.charCodeAt(text.length - 1);
if (this._active.acceptCharacters.has(ch) && editor.getOption(0 /* 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[424/*vs/editor/contrib/suggest/suggestOvertypingCapturer*/], __M([0/*require*/,1/*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 {
constructor(editor, suggestModel) {
this._disposables = new lifecycle_1.DisposableStore();
this._lastOvertyped = [];
this._empty = true;
this._disposables.add(editor.onWillType(() => {
if (!this._empty) {
return;
}
if (!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) {
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._empty = false;
}));
this._disposables.add(suggestModel.onDidCancel(e => {
if (!this._empty && !e.retrigger) {
this._empty = true;
}
}));
}
getLastOvertypedInfo(idx) {
if (!this._empty && idx >= 0 && idx < this._lastOvertyped.length) {
return this._lastOvertyped[idx];
}
return undefined;
}
dispose() {
this._disposables.dispose();
}
}
exports.OvertypingCapturer = OvertypingCapturer;
OvertypingCapturer._maxSelectionLength = 51200;
});
/*---------------------------------------------------------------------------------------------
* 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/suggest/wordDistance*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,3/*vs/editor/common/core/range*/,234/*vs/editor/contrib/smartSelect/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 create(service, editor) {
return __awaiter(this, void 0, void 0, function* () {
if (!editor.getOption(105 /* 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] = yield new bracketSelections_1.BracketSelectionRangeProvider().provideSelectionRanges(model, [position]);
if (ranges.length === 0) {
return WordDistance.None;
}
const wordRanges = yield 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 /* Keyword */) {
return 2 << 20;
}
let word = typeof item.label === 'string' ? item.label : item.label.label;
let wordLines = wordRanges[word];
if ((0, arrays_1.isFalsyOrEmpty)(wordLines)) {
return 2 << 20;
}
let idx = (0, arrays_1.binarySearch)(wordLines, range_1.Range.fromPositions(anchor), range_1.Range.compareRangesUsingStarts);
let 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;
WordDistance.None = new class extends WordDistance {
distance() { 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[236/*vs/editor/standalone/common/monarch/monarchCommon*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.stateExists = exports.findRules = exports.substituteMatches = exports.createError = exports.log = exports.sanitize = exports.fixCase = exports.empty = exports.isIAction = exports.isString = exports.isFuzzyAction = exports.isFuzzyActionArr = void 0;
function isFuzzyActionArr(what) {
return (Array.isArray(what));
}
exports.isFuzzyActionArr = isFuzzyActionArr;
function isFuzzyAction(what) {
return !isFuzzyActionArr(what);
}
exports.isFuzzyAction = isFuzzyAction;
function isString(what) {
return (typeof what === 'string');
}
exports.isString = isString;
function isIAction(what) {
return !isString(what);
}
exports.isIAction = isIAction;
// Small helper functions
/**
* Is a string null, undefined, or empty?
*/
function empty(s) {
return (s ? false : true);
}
exports.empty = empty;
/**
* Puts a string to lower case if 'ignoreCase' is set.
*/
function fixCase(lexer, str) {
return (lexer.ignoreCase && str ? str.toLowerCase() : str);
}
exports.fixCase = fixCase;
/**
* 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
}
exports.sanitize = sanitize;
// Logging
/**
* Logs a message.
*/
function log(lexer, msg) {
console.log(`${lexer.languageId}: ${msg}`);
}
exports.log = log;
// Throwing errors
function createError(lexer, msg) {
return new Error(`${lexer.languageId}: ${msg}`);
}
exports.createError = createError;
// 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 '';
});
}
exports.substituteMatches = substituteMatches;
/**
* 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;
}
exports.findRules = findRules;
/**
* 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;
}
exports.stateExists = stateExists;
});
/*---------------------------------------------------------------------------------------------
* 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/standalone/common/monarch/monarchCompile*/], __M([0/*require*/,1/*exports*/,236/*vs/editor/standalone/common/monarch/monarchCommon*/]), function (require, exports, monarchCommon) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compile = void 0;
/*
* 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);
};
}
}
// Lexer helpers
/**
* Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set, and the 'u' flag if 'unicode' is set.
* Also replaces @\w+ or sequences with the content of the specified attribute
* @\w+ replacement can be avoided by escaping `@` signs with another `@` sign.
* @example /@attr/ will be replaced with the value of lexer[attr]
* @example /@@text/ will not be replaced and will become /@text/.
*/
function compileRegExp(lexer, str) {
// @@ 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, '@');
let flags = (lexer.ignoreCase ? 'i' : '') + (lexer.unicode ? 'u' : '');
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;
let 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)) {
let inWords = createKeywordMatcher(pat.split('|'), lexer.ignoreCase);
tester = function (s) { return (op === '~' ? inWords(s) : !inWords(s)); };
}
else if (op === '@' || op === '!@') {
let 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);
}
let 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
let re = compileRegExp(lexer, '^' + pat + '$');
tester = function (s) { return (op === '~' ? re.test(s) : !re.test(s)); };
}
else {
tester = function (s, id, matches, state) {
let re = compileRegExp(lexer, '^' + monarchCommon.substituteMatches(lexer, pat, id, matches, state) + '$');
return re.test(s);
};
}
}
else { // if (op==='==' || op==='!=') {
if (pat.indexOf('$') < 0) {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s) { return (op === '==' ? s === patx : s !== patx); };
}
else {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s, id, matches, state, eos) {
let 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) {
let 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)
let newAction = { token: action.token };
if (action.token.indexOf('$') >= 0) {
newAction.tokenSubst = true;
}
if (typeof (action.bracket) === 'string') {
if (action.bracket === '@open') {
newAction.bracket = 1 /* Open */;
}
else if (action.bracket === '@close') {
newAction.bracket = -1 /* 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)) {
let 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
let cases = [];
// for each case, push a test function and result value
for (let 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) + ')');
}
setAction(lexer, act) {
this.action = compileAction(lexer, this.name, act);
}
}
/**
* 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
let lexer = {};
lexer.languageId = languageId;
lexer.includeLF = bool(json.includeLF, false);
lexer.noThrow = false; // raise exceptions during compilation
lexer.maxStack = 100;
// Set standard fields: be defensive about types
lexer.start = (typeof json.start === 'string' ? json.start : null);
lexer.ignoreCase = bool(json.ignoreCase, false);
lexer.unicode = bool(json.unicode, false);
lexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId);
lexer.defaultToken = string(json.defaultToken, 'source');
lexer.usesEmbedded = false; // becomes true if we find a nextEmbedded action
// For calling compileAction later on
let 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 (let 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' }
];
}
let brackets = [];
for (let 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;
}
exports.compile = compile;
});
define(__m[427/*vs/nls!vs/base/browser/ui/actionbar/actionViewItems*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/actionbar/actionViewItems", data); });
define(__m[428/*vs/nls!vs/base/browser/ui/findinput/findInput*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/findinput/findInput", data); });
define(__m[429/*vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/findinput/findInputCheckboxes", 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[237/*vs/base/browser/ui/findinput/findInputCheckboxes*/], __M([0/*require*/,1/*exports*/,165/*vs/base/browser/ui/checkbox/checkbox*/,429/*vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes*/,27/*vs/base/common/codicons*/]), function (require, exports, checkbox_1, nls, codicons_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RegexCheckbox = exports.WholeWordsCheckbox = exports.CaseSensitiveCheckbox = void 0;
const NLS_CASE_SENSITIVE_CHECKBOX_LABEL = nls.localize(0, null);
const NLS_WHOLE_WORD_CHECKBOX_LABEL = nls.localize(1, null);
const NLS_REGEX_CHECKBOX_LABEL = nls.localize(2, null);
class CaseSensitiveCheckbox extends checkbox_1.Checkbox {
constructor(opts) {
super({
icon: codicons_1.Codicon.caseSensitive,
title: NLS_CASE_SENSITIVE_CHECKBOX_LABEL + opts.appendTitle,
isChecked: opts.isChecked,
inputActiveOptionBorder: opts.inputActiveOptionBorder,
inputActiveOptionForeground: opts.inputActiveOptionForeground,
inputActiveOptionBackground: opts.inputActiveOptionBackground
});
}
}
exports.CaseSensitiveCheckbox = CaseSensitiveCheckbox;
class WholeWordsCheckbox extends checkbox_1.Checkbox {
constructor(opts) {
super({
icon: codicons_1.Codicon.wholeWord,
title: NLS_WHOLE_WORD_CHECKBOX_LABEL + opts.appendTitle,
isChecked: opts.isChecked,
inputActiveOptionBorder: opts.inputActiveOptionBorder,
inputActiveOptionForeground: opts.inputActiveOptionForeground,
inputActiveOptionBackground: opts.inputActiveOptionBackground
});
}
}
exports.WholeWordsCheckbox = WholeWordsCheckbox;
class RegexCheckbox extends checkbox_1.Checkbox {
constructor(opts) {
super({
icon: codicons_1.Codicon.regex,
title: NLS_REGEX_CHECKBOX_LABEL + opts.appendTitle,
isChecked: opts.isChecked,
inputActiveOptionBorder: opts.inputActiveOptionBorder,
inputActiveOptionForeground: opts.inputActiveOptionForeground,
inputActiveOptionBackground: opts.inputActiveOptionBackground
});
}
}
exports.RegexCheckbox = RegexCheckbox;
});
define(__m[430/*vs/nls!vs/base/browser/ui/findinput/replaceInput*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/findinput/replaceInput", data); });
define(__m[431/*vs/nls!vs/base/browser/ui/iconLabel/iconLabelHover*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/iconLabel/iconLabelHover", 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[432/*vs/base/browser/ui/iconLabel/iconLabelHover*/], __M([0/*require*/,1/*exports*/,20/*vs/base/common/types*/,7/*vs/base/browser/dom*/,23/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,431/*vs/nls!vs/base/browser/ui/iconLabel/iconLabelHover*/,15/*vs/base/common/async*/]), function (require, exports, types_1, dom, cancellation_1, lifecycle_1, nls_1, async_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupCustomHover = exports.setupNativeHover = void 0;
function setupNativeHover(htmlElement, tooltip) {
if ((0, types_1.isString)(tooltip)) {
htmlElement.title = tooltip;
}
else if (tooltip === null || tooltip === void 0 ? void 0 : tooltip.markdownNotSupportedFallback) {
htmlElement.title = tooltip.markdownNotSupportedFallback;
}
else {
htmlElement.removeAttribute('title');
}
}
exports.setupNativeHover = setupNativeHover;
function setupCustomHover(hoverDelegate, htmlElement, markdownTooltip) {
if (!markdownTooltip) {
return undefined;
}
const tooltip = getTooltipForCustom(markdownTooltip);
let hoverPreparation;
let hoverWidget;
const mouseEnter = (e) => {
if (hoverPreparation) {
return;
}
const tokenSource = new cancellation_1.CancellationTokenSource();
const mouseLeaveOrDown = (e) => {
const isMouseDown = e.type === dom.EventType.MOUSE_DOWN;
if (isMouseDown) {
hoverWidget === null || hoverWidget === void 0 ? void 0 : hoverWidget.dispose();
hoverWidget = undefined;
}
if (isMouseDown || e.fromElement === htmlElement) {
hoverPreparation === null || hoverPreparation === void 0 ? void 0 : hoverPreparation.dispose();
hoverPreparation = undefined;
}
};
const mouseLeaveDomListener = dom.addDisposableListener(htmlElement, dom.EventType.MOUSE_LEAVE, mouseLeaveOrDown, true);
const mouseDownDownListener = dom.addDisposableListener(htmlElement, dom.EventType.MOUSE_DOWN, mouseLeaveOrDown, true);
const target = {
targetElements: [htmlElement],
dispose: () => { }
};
let mouseMoveDomListener;
if (hoverDelegate.placement === undefined || hoverDelegate.placement === 'mouse') {
const mouseMove = (e) => target.x = e.x + 10;
mouseMoveDomListener = dom.addDisposableListener(htmlElement, dom.EventType.MOUSE_MOVE, mouseMove, true);
}
const showHover = () => __awaiter(this, void 0, void 0, function* () {
var _a;
if (hoverPreparation) {
const hoverOptions = {
text: (0, nls_1.localize)(0, null),
target,
hoverPosition: 2 /* BELOW */
};
hoverWidget === null || hoverWidget === void 0 ? void 0 : hoverWidget.dispose();
hoverWidget = hoverDelegate.showHover(hoverOptions);
const resolvedTooltip = (_a = (yield tooltip(tokenSource.token))) !== null && _a !== void 0 ? _a : (!(0, types_1.isString)(markdownTooltip) ? markdownTooltip.markdownNotSupportedFallback : undefined);
hoverWidget === null || hoverWidget === void 0 ? void 0 : hoverWidget.dispose();
hoverWidget = undefined;
// awaiting the tooltip could take a while. Make sure we're still preparing to hover.
if (resolvedTooltip && hoverPreparation) {
const hoverOptions = {
text: resolvedTooltip,
target,
showPointer: hoverDelegate.placement === 'element',
hoverPosition: 2 /* BELOW */
};
hoverWidget = hoverDelegate.showHover(hoverOptions);
}
}
mouseMoveDomListener === null || mouseMoveDomListener === void 0 ? void 0 : mouseMoveDomListener.dispose();
});
const timeout = new async_1.RunOnceScheduler(showHover, hoverDelegate.delay);
timeout.schedule();
hoverPreparation = (0, lifecycle_1.toDisposable)(() => {
timeout.dispose();
mouseMoveDomListener === null || mouseMoveDomListener === void 0 ? void 0 : mouseMoveDomListener.dispose();
mouseDownDownListener.dispose();
mouseLeaveDomListener.dispose();
tokenSource.dispose(true);
});
};
const mouseOverDomEmitter = dom.addDisposableListener(htmlElement, dom.EventType.MOUSE_OVER, mouseEnter, true);
return (0, lifecycle_1.toDisposable)(() => {
mouseOverDomEmitter.dispose();
hoverPreparation === null || hoverPreparation === void 0 ? void 0 : hoverPreparation.dispose();
hoverWidget === null || hoverWidget === void 0 ? void 0 : hoverWidget.dispose();
});
}
exports.setupCustomHover = setupCustomHover;
function getTooltipForCustom(markdownTooltip) {
if ((0, types_1.isString)(markdownTooltip)) {
return () => __awaiter(this, void 0, void 0, function* () { return markdownTooltip; });
}
else if ((0, types_1.isFunction)(markdownTooltip.markdown)) {
return markdownTooltip.markdown;
}
else {
const markdown = markdownTooltip.markdown;
return () => __awaiter(this, void 0, void 0, function* () { return markdown; });
}
}
});
/*---------------------------------------------------------------------------------------------
* 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/base/browser/ui/iconLabel/iconLabel*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,161/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,2/*vs/base/common/lifecycle*/,126/*vs/base/common/range*/,42/*vs/base/common/objects*/,432/*vs/base/browser/ui/iconLabel/iconLabelHover*/,311/*vs/css!vs/base/browser/ui/iconLabel/iconlabel*/]), function (require, exports, dom, highlightedLabel_1, lifecycle_1, range_1, objects_1, iconLabelHover_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 className(className) {
if (this.disposed || className === this._className) {
return;
}
this._className = className;
this._element.className = className;
}
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.domNode = this._register(new FastLabelNode(dom.append(container, dom.$('.monaco-icon-label'))));
this.labelContainer = dom.append(this.domNode.element, dom.$('.monaco-icon-label-container'));
const nameContainer = dom.append(this.labelContainer, dom.$('span.monaco-icon-name-container'));
this.descriptionContainer = this._register(new FastLabelNode(dom.append(this.labelContainer, dom.$('span.monaco-icon-description-container'))));
if ((options === null || options === void 0 ? void 0 : options.supportHighlights) || (options === null || options === void 0 ? void 0 : options.supportIcons)) {
this.nameNode = new LabelWithHighlights(nameContainer, !!options.supportIcons);
}
else {
this.nameNode = new Label(nameContainer);
}
if (options === null || options === void 0 ? void 0 : options.supportDescriptionHighlights) {
this.descriptionNodeFactory = () => new highlightedLabel_1.HighlightedLabel(dom.append(this.descriptionContainer.element, dom.$('span.label-description')), !!options.supportIcons);
}
else {
this.descriptionNodeFactory = () => this._register(new FastLabelNode(dom.append(this.descriptionContainer.element, dom.$('span.label-description'))));
}
this.hoverDelegate = options === null || options === void 0 ? void 0 : options.hoverDelegate;
}
setLabel(label, description, options) {
const classes = ['monaco-icon-label'];
if (options) {
if (options.extraClasses) {
classes.push(...options.extraClasses);
}
if (options.italic) {
classes.push('italic');
}
if (options.strikethrough) {
classes.push('strikethrough');
}
}
this.domNode.className = classes.join(' ');
this.setupHover(this.labelContainer, options === null || options === void 0 ? void 0 : options.title);
this.nameNode.setLabel(label, options);
if (description || this.descriptionNode) {
if (!this.descriptionNode) {
this.descriptionNode = this.descriptionNodeFactory(); // description node is created lazily on demand
}
if (this.descriptionNode instanceof highlightedLabel_1.HighlightedLabel) {
this.descriptionNode.set(description || '', options ? options.descriptionMatches : undefined);
this.setupHover(this.descriptionNode.element, options === null || options === void 0 ? void 0 : options.descriptionTitle);
}
else {
this.descriptionNode.textContent = description || '';
this.setupHover(this.descriptionNode.element, (options === null || options === void 0 ? void 0 : options.descriptionTitle) || '');
this.descriptionNode.empty = !description;
}
}
}
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) {
(0, iconLabelHover_1.setupNativeHover)(htmlElement, tooltip);
}
else {
const hoverDisposable = (0, iconLabelHover_1.setupCustomHover)(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();
}
}
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 === null || options === void 0 ? void 0 : 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 === null || options === void 0 ? void 0 : options.domId) && `${options === null || options === void 0 ? void 0 : 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 === null || options === void 0 ? void 0 : 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 {
constructor(container, supportIcons) {
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 = new highlightedLabel_1.HighlightedLabel(dom.append(this.container, dom.$('a.label-name', { id: options === null || options === void 0 ? void 0 : options.domId })), this.supportIcons);
}
this.singleLabel.set(label, options === null || options === void 0 ? void 0 : options.matches, undefined, options === null || options === void 0 ? void 0 : options.labelEscapeNewLines);
}
else {
this.container.innerText = '';
this.container.classList.add('multiple');
this.singleLabel = undefined;
const separator = (options === null || options === void 0 ? void 0 : options.separator) || '/';
const matches = splitMatches(label, separator, options === null || options === void 0 ? void 0 : options.matches);
for (let i = 0; i < label.length; i++) {
const l = label[i];
const m = matches ? matches[i] : undefined;
const id = (options === null || options === void 0 ? void 0 : options.domId) && `${options === null || options === void 0 ? void 0 : 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 = new highlightedLabel_1.HighlightedLabel(dom.append(this.container, name), this.supportIcons);
highlightedLabel.set(l, m, undefined, options === null || options === void 0 ? void 0 : options.labelEscapeNewLines);
if (i < label.length - 1) {
dom.append(name, dom.$('span.label-separator', undefined, separator));
}
}
}
}
}
});
define(__m[433/*vs/nls!vs/base/browser/ui/inputbox/inputBox*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/inputbox/inputBox", data); });
define(__m[434/*vs/nls!vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/keybindingLabel/keybindingLabel", data); });
define(__m[435/*vs/nls!vs/base/browser/ui/menu/menu*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/menu/menu", data); });
define(__m[436/*vs/nls!vs/base/browser/ui/tree/abstractTree*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/tree/abstractTree", 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[180/*vs/base/browser/ui/tree/abstractTree*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,108/*vs/base/browser/ui/list/listWidget*/,7/*vs/base/browser/dom*/,6/*vs/base/common/event*/,51/*vs/base/browser/keyboardEvent*/,101/*vs/base/browser/ui/tree/tree*/,164/*vs/base/browser/dnd*/,19/*vs/base/common/arrays*/,166/*vs/base/browser/ui/list/listView*/,91/*vs/base/browser/event*/,67/*vs/base/common/filters*/,158/*vs/base/browser/ui/tree/indexTreeModel*/,436/*vs/nls!vs/base/browser/ui/tree/abstractTree*/,15/*vs/base/common/async*/,17/*vs/base/common/platform*/,102/*vs/base/common/numbers*/,199/*vs/base/common/collections*/,200/*vs/base/browser/ui/tree/treeIcons*/,324/*vs/css!vs/base/browser/ui/tree/media/tree*/]), function (require, exports, lifecycle_1, listWidget_1, dom_1, event_1, keyboardEvent_1, tree_1, dnd_1, arrays_1, listView_1, event_2, filters_1, indexTreeModel_1, nls_1, async_1, platform_1, numbers_1, collections_1, treeIcons_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AbstractTree = 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;
}
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) {
if (this.dnd.onDragStart) {
this.dnd.onDragStart(asTreeDragAndDropData(data), originalEvent);
}
}
onDragOver(data, targetNode, targetIndex, originalEvent, raw = true) {
const result = this.dnd.onDragOver(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, 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);
}
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 /* 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, originalEvent, false);
}
const model = this.modelProvider();
const ref = model.getNodeLocation(targetNode);
const start = model.getListIndex(ref);
const length = model.getListRenderCount(ref);
return Object.assign(Object.assign({}, result), { feedback: (0, arrays_1.range)(start, start + length) });
}
drop(data, targetNode, targetIndex, originalEvent) {
this.autoExpandDisposable.dispose();
this.autoExpandNode = undefined;
this.dnd.drop(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent);
}
onDragEnd(originalEvent) {
if (this.dnd.onDragEnd) {
this.dnd.onDragEnd(originalEvent);
}
}
}
function asListOptions(modelProvider, options) {
return options && Object.assign(Object.assign({}, 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(Object.assign(Object.assign({}, e), { element: e.element }));
},
isSelectionRangeChangeEvent(e) {
return options.multipleSelectionController.isSelectionRangeChangeEvent(Object.assign(Object.assign({}, e), { element: e.element }));
}
}, accessibilityProvider: options.accessibilityProvider && Object.assign(Object.assign({}, 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 && Object.assign(Object.assign({}, options.keyboardNavigationLabelProvider), { getKeyboardNavigationLabel(node) {
return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(node.element);
} }), enableKeyboardNavigation: options.simpleKeyboardNavigation });
}
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) {
if (this.delegate.setDynamicHeight) {
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 || (exports.RenderIndentGuides = {}));
class EventCollection {
constructor(onDidChange, _elements = []) {
this._elements = _elements;
this.onDidChange = event_1.Event.forEach(onDidChange, elements => this._elements = elements);
}
get elements() {
return this._elements;
}
}
class TreeRenderer {
constructor(renderer, modelProvider, onDidChangeCollapseState, activeNodes, options = {}) {
this.renderer = renderer;
this.modelProvider = modelProvider;
this.activeNodes = activeNodes;
this.renderedElements = new Map();
this.renderedNodes = new Map();
this.indent = TreeRenderer.DefaultIndent;
this.hideTwistiesOfChildlessElements = false;
this.shouldRenderIndentGuides = false;
this.renderedIndentGuides = new collections_1.SetMap();
this.activeIndentNodes = new Set();
this.indentGuidesDisposable = lifecycle_1.Disposable.None;
this.disposables = new lifecycle_1.DisposableStore();
this.templateId = renderer.templateId;
this.updateOptions(options);
event_1.Event.map(onDidChangeCollapseState, e => e.node)(this.onDidChangeNodeTwistieState, this, this.disposables);
if (renderer.onDidChangeTwistieState) {
renderer.onDidChangeTwistieState(this.onDidChangeTwistieState, this, this.disposables);
}
}
updateOptions(options = {}) {
if (typeof options.indent !== 'undefined') {
this.indent = (0, numbers_1.clamp)(options.indent, 0, 40);
}
if (typeof options.renderIndentGuides !== 'undefined') {
const shouldRenderIndentGuides = options.renderIndentGuides !== RenderIndentGuides.None;
if (shouldRenderIndentGuides !== this.shouldRenderIndentGuides) {
this.shouldRenderIndentGuides = shouldRenderIndentGuides;
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) {
if (typeof height === 'number') {
this.renderedNodes.set(node, { templateData, height });
this.renderedElements.set(node.element, node);
}
const indent = TreeRenderer.DefaultIndent + (node.depth - 1) * this.indent;
templateData.twistie.style.paddingLeft = `${indent}px`;
templateData.indent.style.width = `${indent + this.indent - 16}px`;
this.renderTwistie(node, templateData);
if (typeof height === 'number') {
this.renderIndentGuides(node, templateData);
}
this.renderer.renderElement(node, index, templateData.templateData, height);
}
disposeElement(node, index, templateData, height) {
templateData.indentGuidesDisposable.dispose();
if (this.renderer.disposeElement) {
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 data = this.renderedNodes.get(node);
if (!data) {
return;
}
this.renderTwistie(node, data.templateData);
this._onDidChangeActiveNodes(this.activeNodes.elements);
this.renderIndentGuides(node, data.templateData);
}
renderTwistie(node, templateData) {
templateData.twistie.classList.remove(...treeIcons_1.treeItemExpandedIcon.classNamesArray);
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(...treeIcons_1.treeItemExpandedIcon.classNamesArray);
}
templateData.twistie.classList.add('collapsible');
templateData.twistie.classList.toggle('collapsed', node.collapsed);
}
else {
templateData.twistie.classList.remove('collapsible', 'collapsed');
}
if (node.collapsible) {
templateData.container.setAttribute('aria-expanded', String(!node.collapsed));
}
else {
templateData.container.removeAttribute('aria-expanded');
}
}
renderIndentGuides(target, templateData) {
(0, dom_1.clearNode)(templateData.indent);
templateData.indentGuidesDisposable.dispose();
if (!this.shouldRenderIndentGuides) {
return;
}
const disposableStore = new lifecycle_1.DisposableStore();
const model = this.modelProvider();
let node = target;
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 (_a) {
// 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);
}
}
TreeRenderer.DefaultIndent = 8;
class TypeFilter {
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);
}
get totalCount() { return this._totalCount; }
get matchCount() { return this._matchCount; }
set pattern(pattern) {
this._pattern = pattern;
this._lowercasePattern = pattern.toLowerCase();
}
filter(element, parentVisibility) {
if (this._filter) {
const result = this._filter.filter(element, parentVisibility);
if (this.tree.options.simpleKeyboardNavigation) {
return result;
}
let visibility;
if (typeof result === 'boolean') {
visibility = result ? 1 /* Visible */ : 0 /* Hidden */;
}
else if ((0, indexTreeModel_1.isFilterResult)(result)) {
visibility = (0, indexTreeModel_1.getVisibleState)(result.visibility);
}
else {
visibility = result;
}
if (visibility === 0 /* Hidden */) {
return false;
}
}
this._totalCount++;
if (this.tree.options.simpleKeyboardNavigation || !this._pattern) {
this._matchCount++;
return { data: filters_1.FuzzyScore.Default, visibility: true };
}
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: true };
}
const score = (0, filters_1.fuzzyScore)(this._pattern, this._lowercasePattern, 0, labelStr, labelStr.toLowerCase(), 0, true);
if (score) {
this._matchCount++;
return labels.length === 1 ?
{ data: score, visibility: true } :
{ data: { label: labelStr, score: score }, visibility: true };
}
}
if (this.tree.options.filterOnType) {
return 2 /* Recurse */;
}
else {
return { data: filters_1.FuzzyScore.Default, visibility: true };
}
}
reset() {
this._totalCount = 0;
this._matchCount = 0;
}
dispose() {
(0, lifecycle_1.dispose)(this.disposables);
}
}
class TypeFilterController {
constructor(tree, model, view, filter, keyboardNavigationDelegate) {
this.tree = tree;
this.view = view;
this.filter = filter;
this.keyboardNavigationDelegate = keyboardNavigationDelegate;
this._enabled = false;
this._pattern = '';
this._empty = false;
this._onDidChangeEmptyState = new event_1.Emitter();
this.positionClassName = 'ne';
this.automaticKeyboardNavigation = true;
this.triggered = false;
this._onDidChangePattern = new event_1.Emitter();
this.enabledDisposables = new lifecycle_1.DisposableStore();
this.disposables = new lifecycle_1.DisposableStore();
this.domNode = (0, dom_1.$)(`.monaco-list-type-filter.${this.positionClassName}`);
this.domNode.draggable = true;
this.disposables.add((0, dom_1.addDisposableListener)(this.domNode, 'dragstart', () => this.onDragStart()));
this.messageDomNode = (0, dom_1.append)(view.getHTMLElement(), (0, dom_1.$)(`.monaco-list-type-filter-message`));
this.labelDomNode = (0, dom_1.append)(this.domNode, (0, dom_1.$)('span.label'));
const controls = (0, dom_1.append)(this.domNode, (0, dom_1.$)('.controls'));
this._filterOnType = !!tree.options.filterOnType;
this.filterOnTypeDomNode = (0, dom_1.append)(controls, (0, dom_1.$)('input.filter'));
this.filterOnTypeDomNode.type = 'checkbox';
this.filterOnTypeDomNode.checked = this._filterOnType;
this.filterOnTypeDomNode.tabIndex = -1;
this.updateFilterOnTypeTitleAndIcon();
this.disposables.add((0, dom_1.addDisposableListener)(this.filterOnTypeDomNode, 'input', () => this.onDidChangeFilterOnType()));
this.clearDomNode = (0, dom_1.append)(controls, (0, dom_1.$)('button.clear' + treeIcons_1.treeFilterClearIcon.cssSelector));
this.clearDomNode.tabIndex = -1;
this.clearDomNode.title = (0, nls_1.localize)(0, null);
this.keyboardNavigationEventFilter = tree.options.keyboardNavigationEventFilter;
model.onDidSplice(this.onDidSpliceModel, this, this.disposables);
this.updateOptions(tree.options);
}
get enabled() { return this._enabled; }
get pattern() { return this._pattern; }
get filterOnType() { return this._filterOnType; }
updateOptions(options) {
if (options.simpleKeyboardNavigation) {
this.disable();
}
else {
this.enable();
}
if (typeof options.filterOnType !== 'undefined') {
this._filterOnType = !!options.filterOnType;
this.filterOnTypeDomNode.checked = this._filterOnType;
this.updateFilterOnTypeTitleAndIcon();
}
if (typeof options.automaticKeyboardNavigation !== 'undefined') {
this.automaticKeyboardNavigation = options.automaticKeyboardNavigation;
}
this.tree.refilter();
this.render();
if (!this.automaticKeyboardNavigation) {
this.onEventOrInput('');
}
}
enable() {
if (this._enabled) {
return;
}
const onRawKeyDown = this.enabledDisposables.add(new event_2.DomEmitter(this.view.getHTMLElement(), 'keydown'));
const onKeyDown = event_1.Event.chain(onRawKeyDown.event)
.filter(e => !(0, listWidget_1.isInputElement)(e.target) || e.target === this.filterOnTypeDomNode)
.filter(e => e.key !== 'Dead' && !/^Media/.test(e.key))
.map(e => new keyboardEvent_1.StandardKeyboardEvent(e))
.filter(this.keyboardNavigationEventFilter || (() => true))
.filter(() => this.automaticKeyboardNavigation || this.triggered)
.filter(e => (this.keyboardNavigationDelegate.mightProducePrintableCharacter(e) && !(e.keyCode === 18 /* DownArrow */ || e.keyCode === 16 /* UpArrow */ || e.keyCode === 15 /* LeftArrow */ || e.keyCode === 17 /* RightArrow */)) || ((this.pattern.length > 0 || this.triggered) && ((e.keyCode === 9 /* Escape */ || e.keyCode === 1 /* Backspace */) && !e.altKey && !e.ctrlKey && !e.metaKey) || (e.keyCode === 1 /* Backspace */ && (platform_1.isMacintosh ? (e.altKey && !e.metaKey) : e.ctrlKey) && !e.shiftKey)))
.forEach(e => { e.stopPropagation(); e.preventDefault(); })
.event;
const onClearClick = this.enabledDisposables.add(new event_2.DomEmitter(this.clearDomNode, 'click'));
event_1.Event.chain(event_1.Event.any(onKeyDown, onClearClick.event))
.event(this.onEventOrInput, this, this.enabledDisposables);
this.filter.pattern = '';
this.tree.refilter();
this.render();
this._enabled = true;
this.triggered = false;
}
disable() {
if (!this._enabled) {
return;
}
this.domNode.remove();
this.enabledDisposables.clear();
this.tree.refilter();
this.render();
this._enabled = false;
this.triggered = false;
}
onEventOrInput(e) {
if (typeof e === 'string') {
this.onInput(e);
}
else if (e instanceof MouseEvent || e.keyCode === 9 /* Escape */ || (e.keyCode === 1 /* Backspace */ && (platform_1.isMacintosh ? e.altKey : e.ctrlKey))) {
this.onInput('');
}
else if (e.keyCode === 1 /* Backspace */) {
this.onInput(this.pattern.length === 0 ? '' : this.pattern.substr(0, this.pattern.length - 1));
}
else {
this.onInput(this.pattern + e.browserEvent.key);
}
}
onInput(pattern) {
const container = this.view.getHTMLElement();
if (pattern && !this.domNode.parentElement) {
container.append(this.domNode);
}
else if (!pattern && this.domNode.parentElement) {
this.domNode.remove();
this.tree.domFocus();
}
this._pattern = pattern;
this._onDidChangePattern.fire(pattern);
this.filter.pattern = pattern;
this.tree.refilter();
if (pattern) {
this.tree.focusNext(0, true, undefined, node => !filters_1.FuzzyScore.isDefault(node.filterData));
}
const focus = this.tree.getFocus();
if (focus.length > 0) {
const element = focus[0];
if (this.tree.getRelativeTop(element) === null) {
this.tree.reveal(element, 0.5);
}
}
this.render();
if (!pattern) {
this.triggered = false;
}
}
onDragStart() {
const container = this.view.getHTMLElement();
const { left } = (0, dom_1.getDomNodePagePosition)(container);
const containerWidth = container.clientWidth;
const midContainerWidth = containerWidth / 2;
const width = this.domNode.clientWidth;
const disposables = new lifecycle_1.DisposableStore();
let positionClassName = this.positionClassName;
const updatePosition = () => {
switch (positionClassName) {
case 'nw':
this.domNode.style.top = `4px`;
this.domNode.style.left = `4px`;
break;
case 'ne':
this.domNode.style.top = `4px`;
this.domNode.style.left = `${containerWidth - width - 6}px`;
break;
}
};
const onDragOver = (event) => {
event.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome)
const x = event.clientX - left;
if (event.dataTransfer) {
event.dataTransfer.dropEffect = 'none';
}
if (x < midContainerWidth) {
positionClassName = 'nw';
}
else {
positionClassName = 'ne';
}
updatePosition();
};
const onDragEnd = () => {
this.positionClassName = positionClassName;
this.domNode.className = `monaco-list-type-filter ${this.positionClassName}`;
this.domNode.style.top = '';
this.domNode.style.left = '';
(0, lifecycle_1.dispose)(disposables);
};
updatePosition();
this.domNode.classList.remove(positionClassName);
this.domNode.classList.add('dragging');
disposables.add((0, lifecycle_1.toDisposable)(() => this.domNode.classList.remove('dragging')));
disposables.add((0, dom_1.addDisposableListener)(document, 'dragover', e => onDragOver(e)));
disposables.add((0, dom_1.addDisposableListener)(this.domNode, 'dragend', () => onDragEnd()));
dnd_1.StaticDND.CurrentDragAndDropData = new dnd_1.DragAndDropData('vscode-ui');
disposables.add((0, lifecycle_1.toDisposable)(() => dnd_1.StaticDND.CurrentDragAndDropData = undefined));
}
onDidSpliceModel() {
if (!this._enabled || this.pattern.length === 0) {
return;
}
this.tree.refilter();
this.render();
}
onDidChangeFilterOnType() {
this.tree.updateOptions({ filterOnType: this.filterOnTypeDomNode.checked });
this.tree.refilter();
this.tree.domFocus();
this.render();
this.updateFilterOnTypeTitleAndIcon();
}
updateFilterOnTypeTitleAndIcon() {
if (this.filterOnType) {
this.filterOnTypeDomNode.classList.remove(...treeIcons_1.treeFilterOnTypeOffIcon.classNamesArray);
this.filterOnTypeDomNode.classList.add(...treeIcons_1.treeFilterOnTypeOnIcon.classNamesArray);
this.filterOnTypeDomNode.title = (0, nls_1.localize)(1, null);
}
else {
this.filterOnTypeDomNode.classList.remove(...treeIcons_1.treeFilterOnTypeOnIcon.classNamesArray);
this.filterOnTypeDomNode.classList.add(...treeIcons_1.treeFilterOnTypeOffIcon.classNamesArray);
this.filterOnTypeDomNode.title = (0, nls_1.localize)(2, null);
}
}
render() {
const noMatches = this.filter.totalCount > 0 && this.filter.matchCount === 0;
if (this.pattern && this.tree.options.filterOnType && noMatches) {
this.messageDomNode.textContent = (0, nls_1.localize)(3, null);
this._empty = true;
}
else {
this.messageDomNode.innerText = '';
this._empty = false;
}
this.domNode.classList.toggle('no-matches', noMatches);
this.domNode.title = (0, nls_1.localize)(4, null, this.filter.matchCount, this.filter.totalCount);
this.labelDomNode.textContent = this.pattern.length > 16 ? '…' + this.pattern.substr(this.pattern.length - 16) : this.pattern;
this._onDidChangeEmptyState.fire(this._empty);
}
shouldAllowFocus(node) {
if (!this.enabled || !this.pattern || this.filterOnType) {
return true;
}
if (this.filter.totalCount > 0 && this.filter.matchCount <= 1) {
return true;
}
return !filters_1.FuzzyScore.isDefault(node.filterData);
}
dispose() {
if (this._enabled) {
this.domNode.remove();
this.enabledDisposables.dispose();
this._enabled = false;
this.triggered = false;
}
this._onDidChangePattern.dispose();
(0, lifecycle_1.dispose)(this.disposables);
}
}
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;
}
return {
browserEvent: event.browserEvent,
element: event.element ? event.element.element : null,
target
};
}
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 {
constructor(getFirstViewElementWithTrait, identityProvider) {
this.getFirstViewElementWithTrait = getFirstViewElementWithTrait;
this.identityProvider = identityProvider;
this.nodes = [];
this._onDidChange = new event_1.Emitter();
this.onDidChange = this._onDidChange.event;
}
get nodeSet() {
if (!this._nodeSet) {
this._nodeSet = this.createNodeSet();
}
return this._nodeSet;
}
set(nodes, browserEvent) {
var _a;
if (!((_a = browserEvent) === null || _a === void 0 ? void 0 : _a.__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) {
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) {
super(list);
this.tree = tree;
}
onViewPointer(e) {
if ((0, listWidget_1.isInputElement)(e.browserEvent.target) || (0, listWidget_1.isMonacoEditor)(e.browserEvent.target)) {
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);
let expandOnlyOnTwistieClick = false;
if (typeof this.tree.expandOnlyOnTwistieClick === 'function') {
expandOnlyOnTwistieClick = this.tree.expandOnlyOnTwistieClick(node.element);
}
else {
expandOnlyOnTwistieClick = !!this.tree.expandOnlyOnTwistieClick;
}
if (expandOnlyOnTwistieClick && !onTwistie && e.browserEvent.detail !== 2) {
return super.onViewPointer(e);
}
if (!this.tree.expandOnDoubleClick && e.browserEvent.detail === 2) {
return super.onViewPointer(e);
}
if (node.collapsible) {
const model = this.tree.model; // internal
const location = model.getNodeLocation(node);
const recursive = e.browserEvent.altKey;
this.tree.setFocus([location]);
model.setCollapsed(location, undefined, recursive);
if (expandOnlyOnTwistieClick && onTwistie) {
return;
}
}
super.onViewPointer(e);
}
onDoubleClick(e) {
const onTwistie = e.browserEvent.target.classList.contains('monaco-tl-twistie');
if (onTwistie || !this.tree.expandOnDoubleClick) {
return;
}
super.onDoubleClick(e);
}
}
/**
* 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);
}
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.distinctES6)([...super.getFocus(), ...additionalFocus]));
}
if (additionalSelection.length > 0) {
super.setSelection((0, arrays_1.distinctES6)([...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 {
constructor(user, container, delegate, renderers, _options = {}) {
this._options = _options;
this.eventBufferer = new event_1.EventBufferer();
this.disposables = new lifecycle_1.DisposableStore();
this._onWillRefilter = new event_1.Emitter();
this.onWillRefilter = this._onWillRefilter.event;
this._onDidUpdateOptions = new event_1.Emitter();
const treeDelegate = new ComposedTreeDelegate(delegate);
const onDidChangeCollapseStateRelay = new event_1.Relay();
const onDidChangeActiveNodes = new event_1.Relay();
const activeNodes = new EventCollection(onDidChangeActiveNodes.event);
this.renderers = renderers.map(r => new TreeRenderer(r, () => this.model, onDidChangeCollapseStateRelay.event, activeNodes, _options));
for (let r of this.renderers) {
this.disposables.add(r);
}
let filter;
if (_options.keyboardNavigationLabelProvider) {
filter = new TypeFilter(this, _options.keyboardNavigationLabelProvider, _options.filter);
_options = Object.assign(Object.assign({}, _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, treeDelegate, this.renderers, this.focus, this.selection, this.anchor, Object.assign(Object.assign({}, asListOptions(() => this.model, _options)), { tree: this }));
this.model = this.createModel(user, this.view, _options);
onDidChangeCollapseStateRelay.input = this.model.onDidChangeCollapseState;
const onDidModelSplice = event_1.Event.forEach(this.model.onDidSplice, e => {
this.eventBufferer.bufferEvents(() => {
this.focus.onDidModelSplice(e);
this.selection.onDidModelSplice(e);
});
});
// 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.
onDidChangeActiveNodes.input = event_1.Event.chain(event_1.Event.any(onDidModelSplice, this.focus.onDidChange, this.selection.onDidChange))
.debounce(() => null, 0)
.map(() => {
const set = new Set();
for (const node of this.focus.getNodes()) {
set.add(node);
}
for (const node of this.selection.getNodes()) {
set.add(node);
}
return [...set.values()];
}).event;
if (_options.keyboardSupport !== false) {
const onKeyDown = event_1.Event.chain(this.view.onKeyDown)
.filter(e => !(0, listWidget_1.isInputElement)(e.target))
.map(e => new keyboardEvent_1.StandardKeyboardEvent(e));
onKeyDown.filter(e => e.keyCode === 15 /* LeftArrow */).on(this.onLeftArrow, this, this.disposables);
onKeyDown.filter(e => e.keyCode === 17 /* RightArrow */).on(this.onRightArrow, this, this.disposables);
onKeyDown.filter(e => e.keyCode === 10 /* Space */).on(this.onSpace, this, this.disposables);
}
if (_options.keyboardNavigationLabelProvider) {
const delegate = _options.keyboardNavigationDelegate || listWidget_1.DefaultKeyboardNavigationDelegate;
this.typeFilterController = new TypeFilterController(this, this.model, this.view, filter, delegate);
this.focusNavigationFilter = node => this.typeFilterController.shouldAllowFocus(node);
this.disposables.add(this.typeFilterController);
}
this.styleElement = (0, dom_1.createStyleSheet)(this.view.getHTMLElement());
this.getHTMLElement().classList.toggle('always', this._options.renderIndentGuides === RenderIndentGuides.Always);
}
get onDidChangeFocus() { return this.eventBufferer.wrapEvent(this.focus.onDidChange); }
get onDidChangeSelection() { return this.eventBufferer.wrapEvent(this.selection.onDidChange); }
get onMouseDblClick() { return event_1.Event.map(this.view.onMouseDblClick, asTreeMouseEvent); }
get onPointer() { return event_1.Event.map(this.view.onPointer, asTreeMouseEvent); }
get onDidFocus() { return this.view.onDidFocus; }
get onDidChangeCollapseState() { return this.model.onDidChangeCollapseState; }
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; }
updateOptions(optionsUpdate = {}) {
this._options = Object.assign(Object.assign({}, this._options), optionsUpdate);
for (const renderer of this.renderers) {
renderer.updateOptions(optionsUpdate);
}
this.view.updateOptions(Object.assign(Object.assign({}, this._options), { enableKeyboardNavigation: this._options.simpleKeyboardNavigation }));
if (this.typeFilterController) {
this.typeFilterController.updateOptions(this._options);
}
this._onDidUpdateOptions.fire(this._options);
this.getHTMLElement().classList.toggle('always', this._options.renderIndentGuides === RenderIndentGuides.Always);
}
get options() {
return this._options;
}
// Widget
getHTMLElement() {
return this.view.getHTMLElement();
}
get scrollTop() {
return this.view.scrollTop;
}
set scrollTop(scrollTop) {
this.view.scrollTop = scrollTop;
}
domFocus() {
this.view.domFocus();
}
layout(height, width) {
this.view.layout(height, 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.treeIndentGuidesStroke.transparent(0.4)}; }`);
content.push(`.monaco-list${suffix} .monaco-tl-indent > .indent-guide.active { border-color: ${styles.treeIndentGuidesStroke}; }`);
}
this.styleElement.textContent = content.join('\n');
this.view.style(styles);
}
collapse(location, recursive = false) {
return this.model.setCollapsed(location, true, recursive);
}
expand(location, recursive = false) {
return this.model.setCollapsed(location, false, 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) {
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) {
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 = this.focusNavigationFilter) {
this.view.focusNext(n, loop, browserEvent, filter);
}
getFocus() {
return this.focus.get();
}
reveal(location, relativeTop) {
this.model.expandTo(location);
const index = this.model.getListIndex(location);
if (index === -1) {
return;
}
this.view.reveal(index, relativeTop);
}
/**
* Returns the relative position of an element rendered in the list.
* Returns `null` if the element isn't *entirely* in the visible viewport.
*/
getRelativeTop(location) {
const index = this.model.getListIndex(location);
if (index === -1) {
return null;
}
return this.view.getRelativeTop(index);
}
// 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.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[437/*vs/base/browser/ui/tree/dataTree*/], __M([0/*require*/,1/*exports*/,180/*vs/base/browser/ui/tree/abstractTree*/,159/*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[238/*vs/base/browser/ui/tree/objectTree*/], __M([0/*require*/,1/*exports*/,54/*vs/base/common/iterator*/,180/*vs/base/browser/ui/tree/abstractTree*/,159/*vs/base/browser/ui/tree/objectTreeModel*/,292/*vs/base/browser/ui/tree/compressedObjectTreeModel*/,90/*vs/base/common/decorators*/]), function (require, exports, iterator_1, abstractTree_1, objectTreeModel_1, compressedObjectTreeModel_1, decorators_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CompressibleObjectTree = exports.ObjectTree = void 0;
class ObjectTree extends abstractTree_1.AbstractTree {
constructor(user, container, delegate, renderers, options = {}) {
super(user, container, delegate, renderers, options);
}
get onDidChangeCollapseState() { return this.model.onDidChangeCollapseState; }
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 {
constructor(_compressedTreeNodeProvider, renderer) {
this._compressedTreeNodeProvider = _compressedTreeNodeProvider;
this.renderer = renderer;
this.templateId = renderer.templateId;
if (renderer.onDidChangeTwistieState) {
this.onDidChangeTwistieState = renderer.onDidChangeTwistieState;
}
}
get compressedTreeNodeProvider() {
return this._compressedTreeNodeProvider();
}
renderTemplate(container) {
const data = this.renderer.renderTemplate(container);
return { compressedTreeNode: undefined, data };
}
renderElement(node, index, templateData, height) {
const 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) {
if (this.renderer.disposeCompressedElements) {
this.renderer.disposeCompressedElements(templateData.compressedTreeNode, index, templateData.data, height);
}
}
else {
if (this.renderer.disposeElement) {
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);
function asObjectTreeOptions(compressedTreeNodeProvider, options) {
return options && Object.assign(Object.assign({}, options), { keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && {
getKeyboardNavigationLabel(e) {
let compressedTreeNode;
try {
compressedTreeNode = compressedTreeNodeProvider().getCompressedTreeNode(e);
}
catch (_a) {
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 compressibleRenderers = renderers.map(r => new CompressibleRenderer(compressedTreeNodeProvider, r));
super(user, container, delegate, compressibleRenderers, asObjectTreeOptions(compressedTreeNodeProvider, options));
}
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[438/*vs/base/browser/ui/tree/asyncDataTree*/], __M([0/*require*/,1/*exports*/,180/*vs/base/browser/ui/tree/abstractTree*/,238/*vs/base/browser/ui/tree/objectTree*/,101/*vs/base/browser/ui/tree/tree*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/,15/*vs/base/common/async*/,54/*vs/base/common/iterator*/,166/*vs/base/browser/ui/list/listView*/,12/*vs/base/common/errors*/,158/*vs/base/browser/ui/tree/indexTreeModel*/,200/*vs/base/browser/ui/tree/treeIcons*/]), function (require, exports, abstractTree_1, objectTree_1, tree_1, lifecycle_1, event_1, async_1, iterator_1, listView_1, errors_1, indexTreeModel_1, treeIcons_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CompressibleAsyncDataTree = exports.AsyncDataTree = void 0;
function createAsyncDataTreeNode(props) {
return Object.assign(Object.assign({}, props), { children: [], refreshPromise: undefined, stale: true, slow: false, collapsedByDefault: undefined });
}
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 {
constructor(node) {
this.node = node;
}
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; }
}
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(...treeIcons_1.treeItemLoadingIcon.classNamesArray);
return true;
}
else {
twistieElement.classList.remove(...treeIcons_1.treeItemLoadingIcon.classNamesArray);
return false;
}
}
disposeElement(node, index, templateData, height) {
if (this.renderer.disposeElement) {
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) {
if (this.dnd.onDragStart) {
this.dnd.onDragStart(asAsyncDataTreeDragAndDropData(data), originalEvent);
}
}
onDragOver(data, targetNode, targetIndex, originalEvent, raw = true) {
return this.dnd.onDragOver(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent);
}
drop(data, targetNode, targetIndex, originalEvent) {
this.dnd.drop(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent);
}
onDragEnd(originalEvent) {
if (this.dnd.onDragEnd) {
this.dnd.onDragEnd(originalEvent);
}
}
}
function asObjectTreeOptions(options) {
return options && Object.assign(Object.assign({}, 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(Object.assign(Object.assign({}, e), { element: e.element }));
},
isSelectionRangeChangeEvent(e) {
return options.multipleSelectionController.isSelectionRangeChangeEvent(Object.assign(Object.assign({}, e), { element: e.element }));
}
}, accessibilityProvider: options.accessibilityProvider && Object.assign(Object.assign({}, options.accessibilityProvider), { getPosInSet: undefined, getSetSize: undefined, getRole: options.accessibilityProvider.getRole ? (el) => {
return options.accessibilityProvider.getRole(el.element);
} : () => 'treeitem', isChecked: options.accessibilityProvider.isChecked ? (e) => {
var _a;
return !!((_a = options.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.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 && Object.assign(Object.assign({}, 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))), additionalScrollHeight: options.additionalScrollHeight });
}
function dfs(node, fn) {
fn(node);
node.children.forEach(child => dfs(child, fn));
}
class AsyncDataTree {
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.collapseByDefault = options.collapseByDefault;
this.tree = this.createTree(user, container, delegate, renderers, options);
this.root = createAsyncDataTreeNode({
element: undefined,
parent: null,
hasChildren: true
});
if (this.identityProvider) {
this.root = Object.assign(Object.assign({}, this.root), { id: null });
}
this.nodes.set(null, this.root);
this.tree.onDidChangeCollapseState(this._onDidChangeCollapseState, this, this.disposables);
}
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; }
get onDidDispose() { return this.tree.onDidDispose; }
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;
}
domFocus() {
this.tree.domFocus();
}
layout(height, width) {
this.tree.layout(height, width);
}
style(styles) {
this.tree.style(styles);
}
// Model
getInput() {
return this.root.element;
}
setInput(input, viewState) {
return __awaiter(this, void 0, void 0, function* () {
this.refreshPromises.forEach(promise => promise.cancel());
this.refreshPromises.clear();
this.root.element = input;
const viewStateContext = viewState && { viewState, focus: [], selection: [] };
yield 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;
}
});
}
_updateChildren(element = this.root.element, recursive = true, rerender = false, viewStateContext, options) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof this.root.element === 'undefined') {
throw new tree_1.TreeError(this.user, 'Tree input not set');
}
if (this.root.refreshPromise) {
yield this.root.refreshPromise;
yield event_1.Event.toPromise(this._onDidRender.event);
}
const node = this.getDataNode(element);
yield this.refreshAndRenderNode(node, recursive, viewStateContext, options);
if (rerender) {
try {
this.tree.rerender(node);
}
catch (_a) {
// 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);
}
collapse(element, recursive = false) {
const node = this.getDataNode(element);
return this.tree.collapse(node === this.root ? null : node, recursive);
}
expand(element, recursive = false) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof this.root.element === 'undefined') {
throw new tree_1.TreeError(this.user, 'Tree input not set');
}
if (this.root.refreshPromise) {
yield this.root.refreshPromise;
yield 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) {
yield this.root.refreshPromise;
yield 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) {
yield this.root.refreshPromise;
yield 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);
}
// 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;
}
refreshAndRenderNode(node, recursive, viewStateContext, options) {
return __awaiter(this, void 0, void 0, function* () {
yield this.refreshNode(node, recursive, viewStateContext);
this.render(node, viewStateContext, options);
});
}
refreshNode(node, recursive, viewStateContext) {
return __awaiter(this, void 0, void 0, function* () {
let result;
this.subTreeRefreshPromises.forEach((refreshPromise, refreshNode) => {
if (!result && intersects(refreshNode, node)) {
result = refreshPromise.then(() => this.refreshNode(node, recursive, viewStateContext));
}
});
if (result) {
return result;
}
return this.doRefreshSubTree(node, recursive, viewStateContext);
});
}
doRefreshSubTree(node, recursive, viewStateContext) {
return __awaiter(this, void 0, void 0, function* () {
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 = yield this.doRefreshNode(node, recursive, viewStateContext);
node.stale = false;
yield async_1.Promises.settled(childrenToRefresh.map(child => this.doRefreshSubTree(child, recursive, viewStateContext)));
}
finally {
done();
}
});
}
doRefreshNode(node, recursive, viewStateContext) {
return __awaiter(this, void 0, void 0, function* () {
node.hasChildren = !!this.dataSource.hasChildren(node.element);
let childrenPromise;
if (!node.hasChildren) {
childrenPromise = Promise.resolve(iterator_1.Iterable.empty());
}
else {
const slowTimeout = (0, async_1.timeout)(800);
slowTimeout.then(() => {
node.slow = true;
this._onDidChangeNodeSlowState.fire(node);
}, _ => null);
childrenPromise = this.doGetChildren(node)
.finally(() => slowTimeout.cancel());
}
try {
const children = yield 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.isPromiseCanceledError)(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;
}
result = (0, async_1.createCancelablePromise)(() => __awaiter(this, void 0, void 0, function* () {
const children = yield this.dataSource.getChildren(node.element);
return this.processChildren(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) {
const collapsed = this.tree.isCollapsed(child);
childrenTreeNodesById.set(child.id, { node: child, collapsed });
}
}
const childrenToRefresh = [];
const children = childrenElements.map(element => {
const hasChildren = !!this.dataSource.hasChildren(element);
if (!this.identityProvider) {
const asyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, hasChildren });
if (hasChildren && this.collapseByDefault && !this.collapseByDefault(element)) {
asyncDataTreeNode.collapsedByDefault = false;
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 && this.collapseByDefault && !this.collapseByDefault(element)) {
asyncDataTreeNode.collapsedByDefault = false;
childrenToRefresh.push(asyncDataTreeNode);
}
return asyncDataTreeNode;
}
const childAsyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, id, hasChildren });
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 && this.collapseByDefault && !this.collapseByDefault(element)) {
childAsyncDataTreeNode.collapsedByDefault = false;
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].collapsedByDefault = false;
childrenToRefresh.push(children[0]);
}
return childrenToRefresh;
}
render(node, viewStateContext, options) {
const children = node.children.map(node => this.asTreeElement(node, viewStateContext));
const objectTreeOptions = options && Object.assign(Object.assign({}, 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 {
collapsed = node.collapsedByDefault;
}
node.collapsedByDefault = undefined;
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();
}
}
exports.AsyncDataTree = AsyncDataTree;
class CompressibleAsyncDataTreeNodeWrapper {
constructor(node) {
this.node = node;
}
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; }
}
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(...treeIcons_1.treeItemLoadingIcon.classNamesArray);
return true;
}
else {
twistieElement.classList.remove(...treeIcons_1.treeItemLoadingIcon.classNamesArray);
return false;
}
}
disposeElement(node, index, templateData, height) {
if (this.renderer.disposeElement) {
this.renderer.disposeElement(this.nodeMapper.map(node), index, templateData.templateData, height);
}
}
disposeCompressedElements(node, index, templateData, height) {
if (this.renderer.disposeCompressedElements) {
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 && Object.assign(Object.assign({}, objectTreeOptions), { keyboardNavigationLabelProvider: objectTreeOptions.keyboardNavigationLabelProvider && Object.assign(Object.assign({}, 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 Object.assign({ incompressible: this.compressionDelegate.isIncompressible(node.element) }, super.asTreeElement(node, viewStateContext));
}
updateOptions(options = {}) {
this.tree.updateOptions(options);
}
render(node, viewStateContext) {
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);
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 /* Visible */);
const visibility = getVisibility(result);
if (visibility === 2 /* Recurse */) {
throw new Error('Recursive tree visibility not supported in async data compressed trees');
}
return visibility === 1 /* Visible */;
});
}
return super.processChildren(children);
}
}
exports.CompressibleAsyncDataTree = CompressibleAsyncDataTree;
function getVisibility(filterResult) {
if (typeof filterResult === 'boolean') {
return filterResult ? 1 /* Visible */ : 0 /* Hidden */;
}
else if ((0, indexTreeModel_1.isFilterResult)(filterResult)) {
return (0, indexTreeModel_1.getVisibleState)(filterResult.visibility);
}
else {
return (0, indexTreeModel_1.getVisibleState)(filterResult);
}
}
});
define(__m[439/*vs/nls!vs/base/common/actions*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/common/actions", 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[50/*vs/base/common/actions*/], __M([0/*require*/,1/*exports*/,439/*vs/nls!vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/]), function (require, exports, nls, lifecycle_1, event_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EmptySubmenuAction = exports.SubmenuAction = exports.Separator = exports.ActionRunner = exports.Action = void 0;
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._checked = false;
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 });
}
}
run(event, data) {
return __awaiter(this, void 0, void 0, function* () {
if (this._actionCallback) {
yield this._actionCallback(event);
}
});
}
}
exports.Action = Action;
class ActionRunner extends lifecycle_1.Disposable {
constructor() {
super(...arguments);
this._onBeforeRun = this._register(new event_1.Emitter());
this.onBeforeRun = this._onBeforeRun.event;
this._onDidRun = this._register(new event_1.Emitter());
this.onDidRun = this._onDidRun.event;
}
run(action, context) {
return __awaiter(this, void 0, void 0, function* () {
if (!action.enabled) {
return;
}
this._onBeforeRun.fire({ action });
let error = undefined;
try {
yield this.runAction(action, context);
}
catch (e) {
error = e;
}
this._onDidRun.fire({ action, error });
});
}
runAction(action, context) {
return __awaiter(this, void 0, void 0, function* () {
yield action.run(context);
});
}
}
exports.ActionRunner = ActionRunner;
class Separator extends Action {
constructor(label) {
super(Separator.ID, label, label ? 'separator text' : 'separator');
this.checked = false;
this.enabled = false;
}
}
exports.Separator = Separator;
Separator.ID = 'vs.actions.separator';
class SubmenuAction {
constructor(id, label, actions, cssClass) {
this.tooltip = '';
this.enabled = true;
this.checked = false;
this.id = id;
this.label = label;
this.class = cssClass;
this._actions = actions;
}
get actions() { return this._actions; }
dispose() {
// there is NOTHING to dispose and the SubmenuAction should
// never have anything to dispose as it is a convenience type
// to bridge into the rendering world.
}
run() {
return __awaiter(this, void 0, void 0, function* () { });
}
}
exports.SubmenuAction = SubmenuAction;
class EmptySubmenuAction extends Action {
constructor() {
super(EmptySubmenuAction.ID, nls.localize(0, null), undefined, false);
}
}
exports.EmptySubmenuAction = EmptySubmenuAction;
EmptySubmenuAction.ID = 'vs.actions.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[117/*vs/base/browser/ui/actionbar/actionViewItems*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,427/*vs/nls!vs/base/browser/ui/actionbar/actionViewItems*/,2/*vs/base/common/lifecycle*/,50/*vs/base/common/actions*/,20/*vs/base/common/types*/,60/*vs/base/browser/touch*/,164/*vs/base/browser/dnd*/,39/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,206/*vs/css!vs/base/browser/ui/actionbar/actionbar*/]), function (require, exports, platform, nls, lifecycle_1, actions_1, types, touch_1, dnd_1, browser_1, dom_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ActionViewItem = exports.BaseActionViewItem = void 0;
class BaseActionViewItem extends lifecycle_1.Disposable {
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;
}
getAction() {
return this._action;
}
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 => { var _a; return (_a = e.dataTransfer) === null || _a === void 0 ? void 0 : _a.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)) {
platform.setImmediate(() => 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) {
var _a;
dom_1.EventHelper.stop(event, true);
const context = types.isUndefinedOrNull(this._context) ? ((_a = this.options) === null || _a === void 0 ? void 0 : _a.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
}
updateTooltip() {
// implement in subclass
}
updateClass() {
// implement in subclass
}
updateChecked() {
// implement in subclass
}
dispose() {
if (this.element) {
this.element.remove();
this.element = 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);
if (this.element) {
this.label = (0, dom_1.append)(this.element, (0, dom_1.$)('a.action-label'));
}
if (this.label) {
if (this._action.id === actions_1.Separator.ID) {
this.label.setAttribute('role', 'presentation'); // A separator is a presentation item
}
else {
if (this.options.isMenu) {
this.label.setAttribute('role', 'menuitem');
}
else {
this.label.setAttribute('role', 'button');
}
}
}
if (this.options.label && this.options.keybinding && this.element) {
(0, dom_1.append)(this.element, (0, dom_1.$)('span.keybinding')).textContent = this.options.keybinding;
}
this.updateClass();
this.updateLabel();
this.updateTooltip();
this.updateEnabled();
this.updateChecked();
}
// 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.getAction().label;
}
}
updateTooltip() {
let title = null;
if (this.getAction().tooltip) {
title = this.getAction().tooltip;
}
else if (!this.options.label && this.getAction().label && this.options.icon) {
title = this.getAction().label;
if (this.options.keybinding) {
title = nls.localize(0, null, title, this.options.keybinding);
}
}
if (title && this.label) {
this.label.title = title;
}
}
updateClass() {
if (this.cssClass && this.label) {
this.label.classList.remove(...this.cssClass.split(' '));
}
if (this.options.icon) {
this.cssClass = this.getAction().class;
if (this.label) {
this.label.classList.add('codicon');
if (this.cssClass) {
this.label.classList.add(...this.cssClass.split(' '));
}
}
this.updateEnabled();
}
else {
if (this.label) {
this.label.classList.remove('codicon');
}
}
}
updateEnabled() {
if (this.getAction().enabled) {
if (this.label) {
this.label.removeAttribute('aria-disabled');
this.label.classList.remove('disabled');
}
if (this.element) {
this.element.classList.remove('disabled');
}
}
else {
if (this.label) {
this.label.setAttribute('aria-disabled', 'true');
this.label.classList.add('disabled');
}
if (this.element) {
this.element.classList.add('disabled');
}
}
}
updateChecked() {
if (this.label) {
if (this.getAction().checked) {
this.label.classList.add('checked');
}
else {
this.label.classList.remove('checked');
}
}
}
}
exports.ActionViewItem = ActionViewItem;
});
/*---------------------------------------------------------------------------------------------
* 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/base/browser/ui/actionbar/actionbar*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,50/*vs/base/common/actions*/,7/*vs/base/browser/dom*/,20/*vs/base/common/types*/,51/*vs/base/browser/keyboardEvent*/,6/*vs/base/common/event*/,117/*vs/base/browser/ui/actionbar/actionViewItems*/,206/*vs/css!vs/base/browser/ui/actionbar/actionbar*/]), function (require, exports, lifecycle_1, actions_1, DOM, types, keyboardEvent_1, event_1, actionViewItems_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ActionBar = void 0;
class ActionBar extends lifecycle_1.Disposable {
constructor(container, options = {}) {
var _a, _b, _c, _d, _e, _f;
super();
// 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({ onFirstListenerAdd: () => 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._onBeforeRun = this._register(new event_1.Emitter());
this.onBeforeRun = this._onBeforeRun.event;
this.options = options;
this._context = (_a = options.context) !== null && _a !== void 0 ? _a : null;
this._orientation = (_b = this.options.orientation) !== null && _b !== void 0 ? _b : 0 /* HORIZONTAL */;
this._triggerKeys = {
keyDown: (_d = (_c = this.options.triggerKeys) === null || _c === void 0 ? void 0 : _c.keyDown) !== null && _d !== void 0 ? _d : false,
keys: (_f = (_e = this.options.triggerKeys) === null || _e === void 0 ? void 0 : _e.keys) !== null && _f !== void 0 ? _f : [3 /* Enter */, 10 /* Space */]
};
if (this.options.actionRunner) {
this._actionRunner = this.options.actionRunner;
}
else {
this._actionRunner = new actions_1.ActionRunner();
this._register(this._actionRunner);
}
this._register(this._actionRunner.onDidRun(e => this._onDidRun.fire(e)));
this._register(this._actionRunner.onBeforeRun(e => this._onBeforeRun.fire(e)));
this._actionIds = [];
this.viewItems = [];
this.focusedItem = undefined;
this.domNode = document.createElement('div');
this.domNode.className = 'monaco-action-bar';
if (options.animated !== false) {
this.domNode.classList.add('animated');
}
let previousKeys;
let nextKeys;
switch (this._orientation) {
case 0 /* HORIZONTAL */:
previousKeys = [15 /* LeftArrow */];
nextKeys = [17 /* RightArrow */];
break;
case 1 /* VERTICAL */:
previousKeys = [16 /* UpArrow */];
nextKeys = [18 /* 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 /* Escape */) && this.cancelHasListener) {
this._onDidCancel.fire();
}
else if (event.equals(14 /* Home */)) {
eventHandled = this.focusFirst();
}
else if (event.equals(13 /* End */)) {
eventHandled = this.focusLast();
}
else if (event.equals(2 /* Tab */) && focusedItem instanceof actionViewItems_1.BaseActionViewItem && focusedItem.trapsArrowNavigation) {
eventHandled = this.focusNext();
}
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 /* Tab */) || event.equals(1024 /* Shift */ | 2 /* Tab */)) {
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.focusedItem = undefined;
this.triggerKeyDown = false;
}
}));
this._register(this.focusTracker.onDidFocus(() => this.updateFocusedItem()));
this.actionsList = document.createElement('ul');
this.actionsList.className = 'actions-container';
this.actionsList.setAttribute('role', 'toolbar');
if (this.options.ariaLabel) {
this.actionsList.setAttribute('aria-label', this.options.ariaLabel);
}
this.domNode.appendChild(this.actionsList);
container.appendChild(this.domNode);
}
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;
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) {
if (actionRunner) {
this._actionRunner = actionRunner;
this.viewItems.forEach(item => item.actionRunner = actionRunner);
}
}
getContainer() {
return this.domNode;
}
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');
// Prevent native context menu on actions
if (!this.options.allowContextMenu) {
this._register(DOM.addDisposableListener(actionViewItemElement, DOM.EventType.CONTEXT_MENU, (e) => {
DOM.EventHelper.stop(e, true);
}));
}
let item;
if (this.options.actionViewItemProvider) {
item = this.options.actionViewItemProvider(action);
}
if (!item) {
item = new actionViewItems_1.ActionViewItem(this.context, action, options);
}
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);
this._actionIds.push(action.id);
}
else {
this.actionsList.insertBefore(actionViewItemElement, this.actionsList.children[index]);
this.viewItems.splice(index, 0, item);
this._actionIds.splice(index, 0, action.id);
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);
}
}
clear() {
(0, lifecycle_1.dispose)(this.viewItems);
this.viewItems = [];
this._actionIds = [];
DOM.clearNode(this.actionsList);
}
length() {
return this.viewItems.length;
}
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();
}
else {
if (index !== undefined) {
this.focusedItem = index;
}
this.updateFocus();
}
}
focusFirst() {
this.focusedItem = this.length() > 1 ? 1 : 0;
return this.focusPrevious();
}
focusLast() {
this.focusedItem = this.length() < 2 ? 0 : this.length() - 2;
return this.focusNext();
}
focusNext() {
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 (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());
this.updateFocus();
return true;
}
focusPrevious() {
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 (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());
this.updateFocus(true);
return true;
}
updateFocus(fromRight, preventScroll) {
if (typeof this.focusedItem === 'undefined') {
this.actionsList.focus({ preventScroll });
}
for (let i = 0; i < this.viewItems.length; i++) {
const item = this.viewItems[i];
const actionViewItem = item;
if (i === this.focusedItem) {
let focusItem = true;
if (!types.isFunction(actionViewItem.focus)) {
focusItem = false;
}
if (this.options.focusOnlyEnabledItems && types.isFunction(item.isEnabled) && !item.isEnabled()) {
focusItem = false;
}
if (focusItem) {
actionViewItem.focus(fromRight);
}
else {
this.actionsList.focus({ preventScroll });
}
}
else {
if (types.isFunction(actionViewItem.blur)) {
actionViewItem.blur();
}
}
}
}
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);
}
}
run(action, context) {
return __awaiter(this, void 0, void 0, function* () {
yield this._actionRunner.run(action, context);
});
}
dispose() {
(0, lifecycle_1.dispose)(this.viewItems);
this.viewItems = [];
this._actionIds = [];
this.getContainer().remove();
super.dispose();
}
}
exports.ActionBar = ActionBar;
});
/*---------------------------------------------------------------------------------------------
* 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/base/browser/ui/dropdown/dropdown*/], __M([0/*require*/,1/*exports*/,60/*vs/base/browser/touch*/,50/*vs/base/common/actions*/,7/*vs/base/browser/dom*/,51/*vs/base/browser/keyboardEvent*/,6/*vs/base/common/event*/,209/*vs/css!vs/base/browser/ui/dropdown/dropdown*/]), function (require, exports, touch_1, actions_1, dom_1, keyboardEvent_1, event_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DropdownMenu = exports.BaseDropdown = void 0;
class BaseDropdown extends actions_1.ActionRunner {
constructor(container, options) {
super();
this._onDidChangeVisibility = 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 (e instanceof MouseEvent && e.detail > 1) {
return; // prevent multiple clicks to open multiple context menus (https://github.com/microsoft/vscode/issues/41363)
}
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 /* Enter */) || event.equals(10 /* 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;
}
}
}
exports.BaseDropdown = BaseDropdown;
class DropdownMenu extends BaseDropdown {
constructor(container, options) {
super(container, options);
this._actions = [];
this._contextMenuProvider = options.contextMenuProvider;
this.actions = options.actions || [];
this.actionProvider = options.actionProvider;
this.menuClassName = options.menuClassName || '';
this.menuAsChild = !!options.menuAsChild;
}
set menuOptions(options) {
this._menuOptions = options;
}
get menuOptions() {
return this._menuOptions;
}
get actions() {
if (this.actionProvider) {
return this.actionProvider.getActions();
}
return this._actions;
}
set actions(actions) {
this._actions = actions;
}
show() {
super.show();
this.element.classList.add('active');
this._contextMenuProvider.showContextMenu({
getAnchor: () => this.element,
getActions: () => this.actions,
getActionsContext: () => this.menuOptions ? this.menuOptions.context : null,
getActionViewItem: action => this.menuOptions && this.menuOptions.actionViewItemProvider ? this.menuOptions.actionViewItemProvider(action) : undefined,
getKeyBinding: action => this.menuOptions && this.menuOptions.getKeyBinding ? this.menuOptions.getKeyBinding(action) : undefined,
getMenuClassName: () => this.menuClassName,
onHide: () => this.onHide(),
actionRunner: this.menuOptions ? this.menuOptions.actionRunner : undefined,
anchorAlignment: this.menuOptions ? this.menuOptions.anchorAlignment : 0 /* LEFT */,
domForShadowRoot: this.menuAsChild ? this.element : undefined
});
}
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[441/*vs/base/browser/ui/dropdown/dropdownActionViewItem*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,6/*vs/base/common/event*/,117/*vs/base/browser/ui/actionbar/actionViewItems*/,440/*vs/base/browser/ui/dropdown/dropdown*/,209/*vs/css!vs/base/browser/ui/dropdown/dropdown*/]), function (require, exports, dom_1, event_1, actionViewItems_1, dropdown_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.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');
this.element.title = 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
};
this.dropdownMenu = this._register(new dropdown_1.DropdownMenu(container, options));
this._register(this.dropdownMenu.onDidChangeVisibility(visible => {
var _a;
(_a = this.element) === null || _a === void 0 ? void 0 : _a.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 = Object.assign(Object.assign({}, this.dropdownMenu.menuOptions), { get anchorAlignment() {
return that.options.anchorAlignmentProvider();
} });
}
this.updateEnabled();
}
setActionContext(newContext) {
super.setActionContext(newContext);
if (this.dropdownMenu) {
if (this.dropdownMenu.menuOptions) {
this.dropdownMenu.menuOptions.context = newContext;
}
else {
this.dropdownMenu.menuOptions = { context: newContext };
}
}
}
updateEnabled() {
var _a, _b;
const disabled = !this.getAction().enabled;
(_a = this.actionItem) === null || _a === void 0 ? void 0 : _a.classList.toggle('disabled', disabled);
(_b = this.element) === null || _b === void 0 ? void 0 : _b.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[181/*vs/base/browser/ui/inputbox/inputBox*/], __M([0/*require*/,1/*exports*/,433/*vs/nls!vs/base/browser/ui/inputbox/inputBox*/,7/*vs/base/browser/dom*/,160/*vs/base/browser/formattedTextRenderer*/,44/*vs/base/browser/ui/aria/aria*/,84/*vs/base/browser/ui/actionbar/actionbar*/,6/*vs/base/common/event*/,52/*vs/base/browser/ui/widget*/,29/*vs/base/common/color*/,42/*vs/base/common/objects*/,287/*vs/base/common/history*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,91/*vs/base/browser/event*/,312/*vs/css!vs/base/browser/ui/inputbox/inputBox*/]), function (require, exports, nls, dom, formattedTextRenderer_1, aria, actionbar_1, event_1, widget_1, color_1, objects_1, history_1, scrollableElement_1, event_2) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HistoryInputBox = exports.InputBox = void 0;
const $ = dom.$;
const defaultOpts = {
inputBackground: color_1.Color.fromHex('#3C3C3C'),
inputForeground: color_1.Color.fromHex('#CCCCCC'),
inputValidationInfoBorder: color_1.Color.fromHex('#55AAFF'),
inputValidationInfoBackground: color_1.Color.fromHex('#063B49'),
inputValidationWarningBorder: color_1.Color.fromHex('#B89500'),
inputValidationWarningBackground: color_1.Color.fromHex('#352A05'),
inputValidationErrorBorder: color_1.Color.fromHex('#BE1100'),
inputValidationErrorBackground: color_1.Color.fromHex('#5A1D1D')
};
class InputBox extends widget_1.Widget {
constructor(container, contextViewProvider, options) {
var _a;
super();
this.state = 'idle';
this.maxHeight = Number.POSITIVE_INFINITY;
this._onDidChange = this._register(new event_1.Emitter());
this.onDidChange = this._onDidChange.event;
this._onDidHeightChange = this._register(new event_1.Emitter());
this.onDidHeightChange = this._onDidHeightChange.event;
this.contextViewProvider = contextViewProvider;
this.options = options || Object.create(null);
(0, objects_1.mixin)(this.options, defaultOpts, false);
this.message = null;
this.placeholder = this.options.placeholder || '';
this.tooltip = (_a = this.options.tooltip) !== null && _a !== void 0 ? _a : (this.placeholder || '');
this.ariaLabel = this.options.ariaLabel || '';
this.inputBackground = this.options.inputBackground;
this.inputForeground = this.options.inputForeground;
this.inputBorder = this.options.inputBorder;
this.inputValidationInfoBorder = this.options.inputValidationInfoBorder;
this.inputValidationInfoBackground = this.options.inputValidationInfoBackground;
this.inputValidationInfoForeground = this.options.inputValidationInfoForeground;
this.inputValidationWarningBorder = this.options.inputValidationWarningBorder;
this.inputValidationWarningBackground = this.options.inputValidationWarningBackground;
this.inputValidationWarningForeground = this.options.inputValidationWarningForeground;
this.inputValidationErrorBorder = this.options.inputValidationErrorBorder;
this.inputValidationErrorBackground = this.options.inputValidationErrorBackground;
this.inputValidationErrorForeground = this.options.inputValidationErrorForeground;
if (this.options.validationOptions) {
this.validation = this.options.validationOptions.validation;
}
this.element = dom.append(container, $('.monaco-inputbox.idle'));
let tagName = this.options.flexibleHeight ? 'textarea' : 'input';
let 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 /* 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_2.DomEmitter(document, 'selectionchange'));
const onAnchoredSelectionChange = event_1.Event.filter(onSelectionChange.event, () => {
const selection = document.getSelection();
return (selection === null || selection === void 0 ? void 0 : 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.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;
this.input.title = tooltip;
}
setAriaLabel(label) {
this.ariaLabel = label;
if (label) {
this.input.setAttribute('aria-label', this.ariaLabel);
}
else {
this.input.removeAttribute('aria-label');
}
}
getAriaLabel() {
return this.ariaLabel;
}
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 document.activeElement === 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;
}
enable() {
this.input.removeAttribute('disabled');
}
disable() {
this.blur();
this.input.disabled = true;
this._hideMessage();
}
get width() {
return dom.getTotalWidth(this.input);
}
set width(width) {
if (this.options.flexibleHeight && this.options.flexibleWidth) {
// textarea with horizontal scrolling
let horizontalPadding = 0;
if (this.mirror) {
const paddingLeft = parseFloat(this.mirror.style.paddingLeft || '') || 0;
const paddingRight = parseFloat(this.mirror.style.paddingRight || '') || 0;
horizontalPadding = paddingLeft + paddingRight;
}
this.input.style.width = (width - horizontalPadding) + 'px';
}
else {
this.input.style.width = width + 'px';
}
if (this.mirror) {
this.mirror.style.width = width + 'px';
}
}
set paddingRight(paddingRight) {
if (this.options.flexibleHeight && this.options.flexibleWidth) {
this.input.style.width = `calc(100% - ${paddingRight}px)`;
}
else {
this.input.style.paddingRight = 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) {
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 = styles.border ? `1px solid ${styles.border}` : '';
if (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 === null || errorMsg === void 0 ? void 0 : errorMsg.type;
}
stylesForType(type) {
switch (type) {
case 1 /* INFO */: return { border: this.inputValidationInfoBorder, background: this.inputValidationInfoBackground, foreground: this.inputValidationInfoForeground };
case 2 /* WARNING */: return { border: this.inputValidationWarningBorder, background: this.inputValidationWarningBackground, foreground: this.inputValidationWarningForeground };
default: return { border: this.inputValidationErrorBorder, background: this.inputValidationErrorBackground, foreground: this.inputValidationErrorForeground };
}
}
classForType(type) {
switch (type) {
case 1 /* INFO */: return 'info';
case 2 /* WARNING */: return 'warning';
default: return 'error';
}
}
_showMessage() {
if (!this.contextViewProvider || !this.message) {
return;
}
let div;
let layout = () => div.style.width = dom.getTotalWidth(this.element) + 'px';
this.contextViewProvider.showContextView({
getAnchor: () => this.element,
anchorAlignment: 1 /* 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 ? styles.background.toString() : '';
spanElement.style.color = styles.foreground ? styles.foreground.toString() : '';
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 /* ERROR */) {
alertText = nls.localize(0, null, this.message.content);
}
else if (this.message.type === 2 /* WARNING */) {
alertText = nls.localize(1, null, this.message.content);
}
else {
alertText = nls.localize(2, null, 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();
}
style(styles) {
this.inputBackground = styles.inputBackground;
this.inputForeground = styles.inputForeground;
this.inputBorder = styles.inputBorder;
this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
this.applyStyles();
}
applyStyles() {
const background = this.inputBackground ? this.inputBackground.toString() : '';
const foreground = this.inputForeground ? this.inputForeground.toString() : '';
const border = this.inputBorder ? this.inputBorder.toString() : '';
this.element.style.backgroundColor = background;
this.element.style.color = foreground;
this.input.style.backgroundColor = 'inherit';
this.input.style.color = foreground;
this.element.style.borderWidth = border ? '1px' : '';
this.element.style.borderStyle = border ? 'solid' : '';
this.element.style.borderColor = border;
}
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;
if (this.actionbar) {
this.actionbar.dispose();
}
super.dispose();
}
}
exports.InputBox = InputBox;
class HistoryInputBox extends InputBox {
constructor(container, contextViewProvider, options) {
super(container, contextViewProvider, options);
this.history = new history_1.HistoryNavigator(options.history, 100);
}
addToHistory() {
if (this.value && this.value !== this.getCurrentValue()) {
this.history.add(this.value);
}
}
showNextValue() {
if (!this.history.has(this.value)) {
this.addToHistory();
}
let next = this.getNextValue();
if (next) {
next = next === this.value ? this.getNextValue() : next;
}
if (next) {
this.value = next;
aria.status(this.value);
}
}
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);
}
}
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() || this.history.last();
}
}
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[442/*vs/base/browser/ui/findinput/findInput*/], __M([0/*require*/,1/*exports*/,428/*vs/nls!vs/base/browser/ui/findinput/findInput*/,7/*vs/base/browser/dom*/,181/*vs/base/browser/ui/inputbox/inputBox*/,52/*vs/base/browser/ui/widget*/,6/*vs/base/common/event*/,237/*vs/base/browser/ui/findinput/findInputCheckboxes*/,210/*vs/css!vs/base/browser/ui/findinput/findInput*/]), function (require, exports, nls, dom, inputBox_1, widget_1, event_1, findInputCheckboxes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FindInput = void 0;
const NLS_DEFAULT_LABEL = nls.localize(0, null);
class FindInput extends widget_1.Widget {
constructor(parent, contextViewProvider, _showOptionButtons, options) {
super();
this._showOptionButtons = _showOptionButtons;
this.fixFocusOnOptionClickEnabled = true;
this.imeSessionInProgress = false;
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.contextViewProvider = contextViewProvider;
this.placeholder = options.placeholder || '';
this.validation = options.validation;
this.label = options.label || NLS_DEFAULT_LABEL;
this.inputActiveOptionBorder = options.inputActiveOptionBorder;
this.inputActiveOptionForeground = options.inputActiveOptionForeground;
this.inputActiveOptionBackground = options.inputActiveOptionBackground;
this.inputBackground = options.inputBackground;
this.inputForeground = options.inputForeground;
this.inputBorder = options.inputBorder;
this.inputValidationInfoBorder = options.inputValidationInfoBorder;
this.inputValidationInfoBackground = options.inputValidationInfoBackground;
this.inputValidationInfoForeground = options.inputValidationInfoForeground;
this.inputValidationWarningBorder = options.inputValidationWarningBorder;
this.inputValidationWarningBackground = options.inputValidationWarningBackground;
this.inputValidationWarningForeground = options.inputValidationWarningForeground;
this.inputValidationErrorBorder = options.inputValidationErrorBorder;
this.inputValidationErrorBackground = options.inputValidationErrorBackground;
this.inputValidationErrorForeground = options.inputValidationErrorForeground;
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, this.contextViewProvider, {
placeholder: this.placeholder || '',
ariaLabel: this.label || '',
validationOptions: {
validation: this.validation
},
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder,
history,
flexibleHeight,
flexibleWidth,
flexibleMaxHeight
}));
this.regex = this._register(new findInputCheckboxes_1.RegexCheckbox({
appendTitle: appendRegexLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder,
inputActiveOptionForeground: this.inputActiveOptionForeground,
inputActiveOptionBackground: this.inputActiveOptionBackground
}));
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 findInputCheckboxes_1.WholeWordsCheckbox({
appendTitle: appendWholeWordsLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder,
inputActiveOptionForeground: this.inputActiveOptionForeground,
inputActiveOptionBackground: this.inputActiveOptionBackground
}));
this._register(this.wholeWords.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.validate();
}));
this.caseSensitive = this._register(new findInputCheckboxes_1.CaseSensitiveCheckbox({
appendTitle: appendCaseSensitiveLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder,
inputActiveOptionForeground: this.inputActiveOptionForeground,
inputActiveOptionBackground: this.inputActiveOptionBackground
}));
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);
}));
if (this._showOptionButtons) {
this.inputBox.paddingRight = this.caseSensitive.width() + this.wholeWords.width() + this.regex.width();
}
// Arrow-Key support to navigate between options
let indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode];
this.onkeydown(this.domNode, (event) => {
if (event.equals(15 /* LeftArrow */) || event.equals(17 /* RightArrow */) || event.equals(9 /* Escape */)) {
let index = indexes.indexOf(document.activeElement);
if (index >= 0) {
let newIndex = -1;
if (event.equals(17 /* RightArrow */)) {
newIndex = (index + 1) % indexes.length;
}
else if (event.equals(15 /* LeftArrow */)) {
if (index === 0) {
newIndex = indexes.length - 1;
}
else {
newIndex = index - 1;
}
}
if (event.equals(9 /* Escape */)) {
indexes[index].blur();
this.inputBox.focus();
}
else if (newIndex >= 0) {
indexes[newIndex].focus();
}
dom.EventHelper.stop(event, true);
}
}
});
let controls = document.createElement('div');
controls.className = 'controls';
controls.style.display = this._showOptionButtons ? 'block' : 'none';
controls.appendChild(this.caseSensitive.domNode);
controls.appendChild(this.wholeWords.domNode);
controls.appendChild(this.regex.domNode);
this.domNode.appendChild(controls);
if (parent) {
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));
}
enable() {
this.domNode.classList.remove('disabled');
this.inputBox.enable();
this.regex.enable();
this.wholeWords.enable();
this.caseSensitive.enable();
}
disable() {
this.domNode.classList.add('disabled');
this.inputBox.disable();
this.regex.disable();
this.wholeWords.disable();
this.caseSensitive.disable();
}
setFocusInputOnOptionClick(value) {
this.fixFocusOnOptionClickEnabled = value;
}
setEnabled(enabled) {
if (enabled) {
this.enable();
}
else {
this.disable();
}
}
getValue() {
return this.inputBox.value;
}
setValue(value) {
if (this.inputBox.value !== value) {
this.inputBox.value = value;
}
}
style(styles) {
this.inputActiveOptionBorder = styles.inputActiveOptionBorder;
this.inputActiveOptionForeground = styles.inputActiveOptionForeground;
this.inputActiveOptionBackground = styles.inputActiveOptionBackground;
this.inputBackground = styles.inputBackground;
this.inputForeground = styles.inputForeground;
this.inputBorder = styles.inputBorder;
this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
this.applyStyles();
}
applyStyles() {
if (this.domNode) {
const checkBoxStyles = {
inputActiveOptionBorder: this.inputActiveOptionBorder,
inputActiveOptionForeground: this.inputActiveOptionForeground,
inputActiveOptionBackground: this.inputActiveOptionBackground,
};
this.regex.style(checkBoxStyles);
this.wholeWords.style(checkBoxStyles);
this.caseSensitive.style(checkBoxStyles);
const inputBoxStyles = {
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder
};
this.inputBox.style(inputBoxStyles);
}
}
select() {
this.inputBox.select();
}
focus() {
this.inputBox.focus();
}
getCaseSensitive() {
return this.caseSensitive.checked;
}
setCaseSensitive(value) {
this.caseSensitive.checked = value;
}
getWholeWords() {
return this.wholeWords.checked;
}
setWholeWords(value) {
this.wholeWords.checked = value;
}
getRegex() {
return this.regex.checked;
}
setRegex(value) {
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();
}
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[443/*vs/base/browser/ui/findinput/replaceInput*/], __M([0/*require*/,1/*exports*/,430/*vs/nls!vs/base/browser/ui/findinput/replaceInput*/,7/*vs/base/browser/dom*/,181/*vs/base/browser/ui/inputbox/inputBox*/,52/*vs/base/browser/ui/widget*/,6/*vs/base/common/event*/,165/*vs/base/browser/ui/checkbox/checkbox*/,27/*vs/base/common/codicons*/,210/*vs/css!vs/base/browser/ui/findinput/findInput*/]), function (require, exports, nls, dom, inputBox_1, widget_1, event_1, checkbox_1, codicons_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReplaceInput = exports.PreserveCaseCheckbox = void 0;
const NLS_DEFAULT_LABEL = nls.localize(0, null);
const NLS_PRESERVE_CASE_LABEL = nls.localize(1, null);
class PreserveCaseCheckbox extends checkbox_1.Checkbox {
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,
inputActiveOptionBorder: opts.inputActiveOptionBorder,
inputActiveOptionForeground: opts.inputActiveOptionForeground,
inputActiveOptionBackground: opts.inputActiveOptionBackground
});
}
}
exports.PreserveCaseCheckbox = PreserveCaseCheckbox;
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;
this.inputActiveOptionBorder = options.inputActiveOptionBorder;
this.inputActiveOptionForeground = options.inputActiveOptionForeground;
this.inputActiveOptionBackground = options.inputActiveOptionBackground;
this.inputBackground = options.inputBackground;
this.inputForeground = options.inputForeground;
this.inputBorder = options.inputBorder;
this.inputValidationInfoBorder = options.inputValidationInfoBorder;
this.inputValidationInfoBackground = options.inputValidationInfoBackground;
this.inputValidationInfoForeground = options.inputValidationInfoForeground;
this.inputValidationWarningBorder = options.inputValidationWarningBorder;
this.inputValidationWarningBackground = options.inputValidationWarningBackground;
this.inputValidationWarningForeground = options.inputValidationWarningForeground;
this.inputValidationErrorBorder = options.inputValidationErrorBorder;
this.inputValidationErrorBackground = options.inputValidationErrorBackground;
this.inputValidationErrorForeground = options.inputValidationErrorForeground;
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
},
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder,
history,
flexibleHeight,
flexibleWidth,
flexibleMaxHeight
}));
this.preserveCase = this._register(new PreserveCaseCheckbox({
appendTitle: appendPreserveCaseLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder,
inputActiveOptionForeground: this.inputActiveOptionForeground,
inputActiveOptionBackground: this.inputActiveOptionBackground,
}));
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
let indexes = [this.preserveCase.domNode];
this.onkeydown(this.domNode, (event) => {
if (event.equals(15 /* LeftArrow */) || event.equals(17 /* RightArrow */) || event.equals(9 /* Escape */)) {
let index = indexes.indexOf(document.activeElement);
if (index >= 0) {
let newIndex = -1;
if (event.equals(17 /* RightArrow */)) {
newIndex = (index + 1) % indexes.length;
}
else if (event.equals(15 /* LeftArrow */)) {
if (index === 0) {
newIndex = indexes.length - 1;
}
else {
newIndex = index - 1;
}
}
if (event.equals(9 /* Escape */)) {
indexes[index].blur();
this.inputBox.focus();
}
else if (newIndex >= 0) {
indexes[newIndex].focus();
}
dom.EventHelper.stop(event, true);
}
}
});
let controls = document.createElement('div');
controls.className = 'controls';
controls.style.display = this._showOptionButtons ? 'block' : 'none';
controls.appendChild(this.preserveCase.domNode);
this.domNode.appendChild(controls);
if (parent) {
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();
}
}
style(styles) {
this.inputActiveOptionBorder = styles.inputActiveOptionBorder;
this.inputActiveOptionForeground = styles.inputActiveOptionForeground;
this.inputActiveOptionBackground = styles.inputActiveOptionBackground;
this.inputBackground = styles.inputBackground;
this.inputForeground = styles.inputForeground;
this.inputBorder = styles.inputBorder;
this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
this.applyStyles();
}
applyStyles() {
if (this.domNode) {
const checkBoxStyles = {
inputActiveOptionBorder: this.inputActiveOptionBorder,
inputActiveOptionForeground: this.inputActiveOptionForeground,
inputActiveOptionBackground: this.inputActiveOptionBackground,
};
this.preserveCase.style(checkBoxStyles);
const inputBoxStyles = {
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder
};
this.inputBox.style(inputBoxStyles);
}
}
select() {
this.inputBox.select();
}
focus() {
this.inputBox.focus();
}
getPreserveCase() {
return this.preserveCase.checked;
}
setPreserveCase(value) {
this.preserveCase.checked = value;
}
focusOnPreserve() {
this.preserveCase.focus();
}
validate() {
if (this.inputBox) {
this.inputBox.validate();
}
}
set width(newWidth) {
this.inputBox.paddingRight = this.cachedOptionsWidth;
this.inputBox.width = newWidth;
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[444/*vs/base/browser/ui/menu/menu*/], __M([0/*require*/,1/*exports*/,435/*vs/nls!vs/base/browser/ui/menu/menu*/,8/*vs/base/common/strings*/,50/*vs/base/common/actions*/,84/*vs/base/browser/ui/actionbar/actionbar*/,7/*vs/base/browser/dom*/,51/*vs/base/browser/keyboardEvent*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,207/*vs/base/browser/ui/contextview/contextview*/,17/*vs/base/common/platform*/,27/*vs/base/common/codicons*/,117/*vs/base/browser/ui/actionbar/actionViewItems*/,130/*vs/base/browser/ui/codicons/codiconStyles*/,39/*vs/base/browser/browser*/,55/*vs/base/browser/mouseEvent*/,104/*vs/base/common/iconLabels*/]), function (require, exports, nls, strings, actions_1, actionbar_1, dom_1, keyboardEvent_1, async_1, lifecycle_1, scrollableElement_1, contextview_1, platform_1, codicons_1, actionViewItems_1, codiconStyles_1, browser_1, mouseEvent_1, iconLabels_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanMnemonic = exports.Menu = exports.Direction = exports.MENU_ESCAPED_MNEMONIC_REGEX = exports.MENU_MNEMONIC_REGEX = void 0;
exports.MENU_MNEMONIC_REGEX = /\(&([^\s&])\)|(^|[^&])&([^\s&])/;
exports.MENU_ESCAPED_MNEMONIC_REGEX = /(&amp;)?(&amp;)([^\s&])/g;
const menuSelectionIcon = (0, codicons_1.registerCodicon)('menu-selection', codicons_1.Codicon.check);
const menuSubmenuIcon = (0, codicons_1.registerCodicon)('menu-submenu', codicons_1.Codicon.chevronRight);
var Direction;
(function (Direction) {
Direction[Direction["Right"] = 0] = "Right";
Direction[Direction["Left"] = 1] = "Left";
})(Direction = exports.Direction || (exports.Direction = {}));
class Menu extends actionbar_1.ActionBar {
constructor(container, actions, options = {}) {
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 /* VERTICAL */,
actionViewItemProvider: action => this.doGetActionViewItem(action, options, parentData),
context: options.context,
actionRunner: options.actionRunner,
ariaLabel: options.ariaLabel,
focusOnlyEnabledItems: true,
triggerKeys: { keys: [3 /* Enter */, ...(platform_1.isMacintosh || platform_1.isLinux ? [10 /* Space */] : [])], keyDown: true }
});
this.menuElement = menuElement;
this.actionsList.setAttribute('role', 'menu');
this.actionsList.tabIndex = 0;
this.menuDisposables = this._register(new lifecycle_1.DisposableStore());
this.initializeStyleSheet(container);
(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 /* Tab */)) {
e.preventDefault();
}
});
if (options.enableMnemonics) {
this.menuDisposables.add((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 /* Home */) || event.equals(11 /* PageUp */)) {
this.focusedItem = this.viewItems.length - 1;
this.focusNext();
dom_1.EventHelper.stop(e, true);
}
else if (event.equals(13 /* End */) || event.equals(12 /* 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 => {
let 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();
}
}
}));
let parentData = {
parent: this
};
this.mnemonics = new Map();
// Scroll Logic
this.scrollableElement = this._register(new scrollableElement_1.DomScrollableElement(menuElement, {
alwaysConsumeMouseWheel: true,
horizontal: 2 /* Hidden */,
vertical: 3 /* Visible */,
verticalScrollbarSize: 7,
handleMouseWheel: true,
useShadows: true
}));
const scrollElement = this.scrollableElement.getDomNode();
scrollElement.style.position = '';
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();
}));
menuElement.style.maxHeight = `${Math.max(10, window.innerHeight - container.getBoundingClientRect().top - 35)}px`;
actions = actions.filter(a => {
var _a;
if ((_a = options.submenuIds) === null || _a === void 0 ? void 0 : _a.has(a.id)) {
console.warn(`Found submenu cycle: ${a.id}`);
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);
});
}
initializeStyleSheet(container) {
if ((0, dom_1.isInShadowDOM)(container)) {
this.styleSheet = (0, dom_1.createStyleSheet)(container);
this.styleSheet.textContent = MENU_WIDGET_CSS;
}
else {
if (!Menu.globalStyleSheet) {
Menu.globalStyleSheet = (0, dom_1.createStyleSheet)();
Menu.globalStyleSheet.textContent = MENU_WIDGET_CSS;
}
this.styleSheet = Menu.globalStyleSheet;
}
}
style(style) {
const container = this.getContainer();
const fgColor = style.foregroundColor ? `${style.foregroundColor}` : '';
const bgColor = style.backgroundColor ? `${style.backgroundColor}` : '';
const border = style.borderColor ? `1px solid ${style.borderColor}` : '';
const shadow = style.shadowColor ? `0 2px 4px ${style.shadowColor}` : '';
container.style.border = border;
this.domNode.style.color = fgColor;
this.domNode.style.backgroundColor = bgColor;
container.style.boxShadow = shadow;
if (this.viewItems) {
this.viewItems.forEach(item => {
if (item instanceof BaseMenuActionViewItem || item instanceof MenuSeparatorActionViewItem) {
item.style(style);
}
});
}
}
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++) {
let elem = this.actionsList.children[i];
if (element === elem) {
this.focusedItem = i;
break;
}
}
}
updateFocus(fromRight) {
super.updateFocus(fromRight, 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 });
}
else if (action instanceof actions_1.SubmenuAction) {
const menuActionViewItem = new SubmenuMenuActionViewItem(action, action.actions, parentData, Object.assign(Object.assign({}, options), { submenuIds: new Set([...(options.submenuIds || []), action.id]) }));
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);
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 = {}) {
options.isMenu = true;
super(action, 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 = '';
// Set mnemonic
if (this.options.label && options.enableMnemonics) {
let label = this.getAction().label;
if (label) {
let 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(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 timout 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' + menuSelectionIcon.cssSelector));
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();
}
blur() {
super.blur();
this.applyStyle();
}
focus() {
super.focus();
if (this.item) {
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.getAction().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();
}
if (this.item) {
this.item.setAttribute('aria-keyshortcuts', (!!matches[1] ? matches[1] : matches[3]).toLocaleLowerCase());
}
}
else {
this.label.innerText = label.replace(/&&/g, '&').trim();
}
}
}
}
updateTooltip() {
let title = null;
if (this.getAction().tooltip) {
title = this.getAction().tooltip;
}
else if (!this.options.label && this.getAction().label && this.options.icon) {
title = this.getAction().label;
if (this.options.keybinding) {
title = nls.localize(0, null, title, this.options.keybinding);
}
}
if (title && this.item) {
this.item.title = title;
}
}
updateClass() {
if (this.cssClass && this.item) {
this.item.classList.remove(...this.cssClass.split(' '));
}
if (this.options.icon && this.label) {
this.cssClass = this.getAction().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.getAction().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;
}
if (this.getAction().checked) {
this.item.classList.add('checked');
this.item.setAttribute('role', 'menuitemcheckbox');
this.item.setAttribute('aria-checked', 'true');
}
else {
this.item.classList.remove('checked');
this.item.setAttribute('role', 'menuitem');
this.item.setAttribute('aria-checked', 'false');
}
}
getMnemonic() {
return this.mnemonic;
}
applyStyle() {
if (!this.menuStyle) {
return;
}
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 border = isSelected && this.menuStyle.selectionBorderColor ? `thin solid ${this.menuStyle.selectionBorderColor}` : '';
if (this.item) {
this.item.style.color = fgColor ? fgColor.toString() : '';
this.item.style.backgroundColor = bgColor ? bgColor.toString() : '';
}
if (this.check) {
this.check.style.color = fgColor ? fgColor.toString() : '';
}
if (this.container) {
this.container.style.border = border;
}
}
style(style) {
this.menuStyle = style;
this.applyStyle();
}
}
class SubmenuMenuActionViewItem extends BaseMenuActionViewItem {
constructor(action, submenuActions, parentData, submenuOptions) {
super(action, action, submenuOptions);
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 : Direction.Right;
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' + menuSubmenuIcon.cssSelector));
this.submenuIndicator.setAttribute('aria-hidden', 'true');
}
this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.KEY_UP, e => {
let event = new keyboardEvent_1.StandardKeyboardEvent(e);
if (event.equals(17 /* RightArrow */) || event.equals(3 /* Enter */)) {
dom_1.EventHelper.stop(e, true);
this.createSubmenu(true);
}
}));
this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.KEY_DOWN, e => {
let event = new keyboardEvent_1.StandardKeyboardEvent(e);
if ((0, dom_1.getActiveElement)() === this.item) {
if (event.equals(17 /* RightArrow */) || event.equals(3 /* 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(() => {
this.parentData.parent.focus(false);
this.cleanupExistingSubmenu(false);
}));
}
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 (_a) { }
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 === Direction.Right ? 0 /* Before */ : 1 /* 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 /* 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 = 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);
if (this.menuStyle) {
this.parentData.submenu.style(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 { top, left } = this.calculateSubmenuMenuLayout(new dom_1.Dimension(window.innerWidth, window.innerHeight), dom_1.Dimension.lift(viewBox), entryBoxUpdated, this.expandDirection);
this.submenuContainer.style.left = `${left}px`;
this.submenuContainer.style.top = `${top}px`;
this.submenuDisposables.add((0, dom_1.addDisposableListener)(this.submenuContainer, dom_1.EventType.KEY_UP, e => {
let event = new keyboardEvent_1.StandardKeyboardEvent(e);
if (event.equals(15 /* 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 => {
let event = new keyboardEvent_1.StandardKeyboardEvent(e);
if (event.equals(15 /* 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) {
var _a;
if (this.item) {
(_a = this.item) === null || _a === void 0 ? void 0 : _a.setAttribute('aria-expanded', value);
}
}
applyStyle() {
super.applyStyle();
if (!this.menuStyle) {
return;
}
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 ? `${fgColor}` : '';
}
if (this.parentData.submenu) {
this.parentData.submenu.style(this.menuStyle);
}
}
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 {
style(style) {
if (this.label) {
this.label.style.borderBottomColor = style.separatorColor ? `${style.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();
}
exports.cleanMnemonic = cleanMnemonic;
let MENU_WIDGET_CSS = `
.monaco-menu {
font-size: 13px;
}
${(0, codiconStyles_1.formatRule)(menuSelectionIcon)}
${(0, codiconStyles_1.formatRule)(menuSubmenuIcon)}
.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.animated .action-item.active {
transform: scale(1.272019649, 1.272019649); /* 1.272019649 = √φ */
}
.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 {
opacity: 0.4;
}
/* 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 #bbb;
padding-top: 1px;
margin-left: .8em;
margin-right: .8em;
}
.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;
}
.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 {
padding: 0.5em 0 0 0;
margin-bottom: 0.5em;
width: 100%;
height: 0px !important;
margin-left: .8em !important;
margin-right: .8em !important;
}
.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;
}
.monaco-menu .monaco-action-bar.vertical .action-item {
border: thin solid transparent; /* prevents jumping behaviour on hover or focus */
}
/* High Contrast Theming */
:host-context(.hc-black) .context-view.monaco-menu-container {
box-shadow: none;
}
:host-context(.hc-black) .monaco-menu .monaco-action-bar.vertical .action-item.focused {
background: none;
}
/* Vertical Action Bar Styles */
.monaco-menu .monaco-action-bar.vertical {
padding: .5em 0;
}
.monaco-menu .monaco-action-bar.vertical .action-menu-item {
height: 1.8em;
}
.monaco-menu .monaco-action-bar.vertical .action-label:not(.separator),
.monaco-menu .monaco-action-bar.vertical .keybinding {
font-size: inherit;
padding: 0 2em;
}
.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;
padding: 0.2em 0 0 0;
margin-bottom: 0.2em;
}
: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;
}
: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;
}
/* 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%;
box-shadow: #DDD 0 6px 6px -6px inset;
}
.monaco-scrollable-element > .shadow.left {
display: block;
top: 3px;
left: 0;
height: 100%;
width: 3px;
box-shadow: #DDD 6px 0 6px -6px inset;
}
.monaco-scrollable-element > .shadow.top-left-corner {
display: block;
top: 0;
left: 0;
height: 3px;
width: 3px;
}
.monaco-scrollable-element > .shadow.top.left {
box-shadow: #DDD 6px 6px 6px -6px inset;
}
/* ---------- Default Style ---------- */
:host-context(.vs) .monaco-scrollable-element > .scrollbar > .slider {
background: rgba(100, 100, 100, .4);
}
:host-context(.vs-dark) .monaco-scrollable-element > .scrollbar > .slider {
background: rgba(121, 121, 121, .4);
}
:host-context(.hc-black) .monaco-scrollable-element > .scrollbar > .slider {
background: rgba(111, 195, 223, .6);
}
.monaco-scrollable-element > .scrollbar > .slider:hover {
background: rgba(100, 100, 100, .7);
}
:host-context(.hc-black) .monaco-scrollable-element > .scrollbar > .slider:hover {
background: rgba(111, 195, 223, .8);
}
.monaco-scrollable-element > .scrollbar > .slider.active {
background: rgba(0, 0, 0, .6);
}
:host-context(.vs-dark) .monaco-scrollable-element > .scrollbar > .slider.active {
background: rgba(191, 191, 191, .4);
}
:host-context(.hc-black) .monaco-scrollable-element > .scrollbar > .slider.active {
background: rgba(111, 195, 223, 1);
}
:host-context(.vs-dark) .monaco-scrollable-element .shadow.top {
box-shadow: none;
}
:host-context(.vs-dark) .monaco-scrollable-element .shadow.left {
box-shadow: #000 6px 0 6px -6px inset;
}
:host-context(.vs-dark) .monaco-scrollable-element .shadow.top.left {
box-shadow: #000 6px 6px 6px -6px inset;
}
:host-context(.hc-black) .monaco-scrollable-element .shadow.top {
box-shadow: none;
}
:host-context(.hc-black) .monaco-scrollable-element .shadow.left {
box-shadow: none;
}
:host-context(.hc-black) .monaco-scrollable-element .shadow.top.left {
box-shadow: none;
}
`;
});
/*---------------------------------------------------------------------------------------------
* 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/parts/quickinput/browser/quickInputBox*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,181/*vs/base/browser/ui/inputbox/inputBox*/,2/*vs/base/common/lifecycle*/,51/*vs/base/browser/keyboardEvent*/,74/*vs/base/common/severity*/,55/*vs/base/browser/mouseEvent*/,132/*vs/css!vs/base/parts/quickinput/browser/media/quickInput*/]), function (require, exports, dom, inputBox_1, lifecycle_1, keyboardEvent_1, severity_1, mouseEvent_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.QuickInputBox = void 0;
const $ = dom.$;
class QuickInputBox extends lifecycle_1.Disposable {
constructor(parent) {
super();
this.parent = parent;
this.onKeyDown = (handler) => {
return dom.addDisposableListener(this.inputBox.inputElement, dom.EventType.KEY_DOWN, (e) => {
handler(new keyboardEvent_1.StandardKeyboardEvent(e));
});
};
this.onMouseDown = (handler) => {
return dom.addDisposableListener(this.inputBox.inputElement, dom.EventType.MOUSE_DOWN, (e) => {
handler(new mouseEvent_1.StandardMouseEvent(e));
});
};
this.onDidChange = (handler) => {
return this.inputBox.onDidChange(handler);
};
this.container = dom.append(this.parent, $('.quick-input-box'));
this.inputBox = this._register(new inputBox_1.InputBox(this.container, undefined));
}
get value() {
return this.inputBox.value;
}
set value(value) {
this.inputBox.value = value;
}
select(range = null) {
this.inputBox.select(range);
}
isSelectionAtEnd() {
return this.inputBox.isSelectionAtEnd();
}
get placeholder() {
return this.inputBox.inputElement.getAttribute('placeholder') || '';
}
set placeholder(placeholder) {
this.inputBox.setPlaceHolder(placeholder);
}
get ariaLabel() {
return this.inputBox.getAriaLabel();
}
set ariaLabel(ariaLabel) {
this.inputBox.setAriaLabel(ariaLabel);
}
get password() {
return this.inputBox.inputElement.type === 'password';
}
set password(password) {
this.inputBox.inputElement.type = password ? 'password' : 'text';
}
setAttribute(name, value) {
this.inputBox.inputElement.setAttribute(name, value);
}
removeAttribute(name) {
this.inputBox.inputElement.removeAttribute(name);
}
showDecoration(decoration) {
if (decoration === severity_1.default.Ignore) {
this.inputBox.hideMessage();
}
else {
this.inputBox.showMessage({ type: decoration === severity_1.default.Info ? 1 /* INFO */ : decoration === severity_1.default.Warning ? 2 /* WARNING */ : 3 /* ERROR */, content: '' });
}
}
stylesForType(decoration) {
return this.inputBox.stylesForType(decoration === severity_1.default.Info ? 1 /* INFO */ : decoration === severity_1.default.Warning ? 2 /* WARNING */ : 3 /* ERROR */);
}
setFocus() {
this.inputBox.focus();
}
layout() {
this.inputBox.layout();
}
style(styles) {
this.inputBox.style(styles);
}
}
exports.QuickInputBox = QuickInputBox;
});
define(__m[446/*vs/nls!vs/base/common/errorMessage*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/common/errorMessage", 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[447/*vs/base/common/errorMessage*/], __M([0/*require*/,1/*exports*/,446/*vs/nls!vs/base/common/errorMessage*/,20/*vs/base/common/types*/,19/*vs/base/common/arrays*/]), function (require, exports, nls, types, arrays) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toErrorMessage = void 0;
function exceptionToErrorMessage(exception, verbose) {
if (verbose && (exception.stack || exception.stacktrace)) {
return nls.localize(0, null, 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) {
// 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(1, null, exception.message);
}
return exception.message || nls.localize(2, null);
}
/**
* 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(3, null);
}
if (Array.isArray(error)) {
const errors = arrays.coalesce(error);
const msg = toErrorMessage(errors[0], verbose);
if (errors.length > 1) {
return nls.localize(4, null, 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(5, null);
}
exports.toErrorMessage = toErrorMessage;
});
define(__m[448/*vs/nls!vs/base/common/keybindingLabels*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/common/keybindingLabels", 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[182/*vs/base/common/keybindingLabels*/], __M([0/*require*/,1/*exports*/,448/*vs/nls!vs/base/common/keybindingLabels*/]), function (require, exports, nls) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
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 /* Macintosh */] = mac;
this.modifierLabels[1 /* Windows */] = windows;
this.modifierLabels[3 /* Linux */] = linux;
}
toLabel(OS, parts, keyLabelProvider) {
if (parts.length === 0) {
return null;
}
const result = [];
for (let i = 0, len = parts.length; i < len; i++) {
const part = parts[i];
const keyLabel = keyLabelProvider(part);
if (keyLabel === null) {
// this keybinding cannot be expressed...
return null;
}
result[i] = _simpleAsString(part, 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: '⌃',
shiftKey: '⇧',
altKey: '⌥',
metaKey: '⌘',
separator: '',
}, {
ctrlKey: nls.localize(0, null),
shiftKey: nls.localize(1, null),
altKey: nls.localize(2, null),
metaKey: nls.localize(3, null),
separator: '+',
}, {
ctrlKey: nls.localize(4, null),
shiftKey: nls.localize(5, null),
altKey: nls.localize(6, null),
metaKey: nls.localize(7, null),
separator: '+',
});
/**
* A label provider that prints modifiers in a suitable format for ARIA.
*/
exports.AriaLabelProvider = new ModifierLabelProvider({
ctrlKey: nls.localize(8, null),
shiftKey: nls.localize(9, null),
altKey: nls.localize(10, null),
metaKey: nls.localize(11, null),
separator: '+',
}, {
ctrlKey: nls.localize(12, null),
shiftKey: nls.localize(13, null),
altKey: nls.localize(14, null),
metaKey: nls.localize(15, null),
separator: '+',
}, {
ctrlKey: nls.localize(16, null),
shiftKey: nls.localize(17, null),
altKey: nls.localize(18, null),
metaKey: nls.localize(19, null),
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[449/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([0/*require*/,1/*exports*/,42/*vs/base/common/objects*/,182/*vs/base/common/keybindingLabels*/,7/*vs/base/browser/dom*/,434/*vs/nls!vs/base/browser/ui/keybindingLabel/keybindingLabel*/,313/*vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel*/]), function (require, exports, objects_1, keybindingLabels_1, dom, nls_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeybindingLabel = void 0;
const $ = dom.$;
class KeybindingLabel {
constructor(container, os, options) {
this.os = os;
this.keyElements = new Set();
this.options = options || Object.create(null);
this.labelBackground = this.options.keybindingLabelBackground;
this.labelForeground = this.options.keybindingLabelForeground;
this.labelBorder = this.options.keybindingLabelBorder;
this.labelBottomBorder = this.options.keybindingLabelBottomBorder;
this.labelShadow = this.options.keybindingLabelShadow;
this.domNode = dom.append(container, $('.monaco-keybinding'));
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) {
let [firstPart, chordPart] = this.keybinding.getParts();
if (firstPart) {
this.renderPart(this.domNode, firstPart, this.matches ? this.matches.firstPart : null);
}
if (chordPart) {
dom.append(this.domNode, $('span.monaco-keybinding-key-chord-separator', undefined, ' '));
this.renderPart(this.domNode, chordPart, this.matches ? this.matches.chordPart : null);
}
this.domNode.title = this.keybinding.getAriaLabel() || '';
}
else if (this.options && this.options.renderUnboundKeybindings) {
this.renderUnbound(this.domNode);
}
this.applyStyles();
this.didEverRender = true;
}
clear() {
dom.clearNode(this.domNode);
this.keyElements.clear();
}
renderPart(parent, part, match) {
const modifierLabels = keybindingLabels_1.UILabelProvider.modifierLabels[this.os];
if (part.ctrlKey) {
this.renderKey(parent, modifierLabels.ctrlKey, Boolean(match === null || match === void 0 ? void 0 : match.ctrlKey), modifierLabels.separator);
}
if (part.shiftKey) {
this.renderKey(parent, modifierLabels.shiftKey, Boolean(match === null || match === void 0 ? void 0 : match.shiftKey), modifierLabels.separator);
}
if (part.altKey) {
this.renderKey(parent, modifierLabels.altKey, Boolean(match === null || match === void 0 ? void 0 : match.altKey), modifierLabels.separator);
}
if (part.metaKey) {
this.renderKey(parent, modifierLabels.metaKey, Boolean(match === null || match === void 0 ? void 0 : match.metaKey), modifierLabels.separator);
}
const keyLabel = part.keyLabel;
if (keyLabel) {
this.renderKey(parent, keyLabel, Boolean(match === null || match === void 0 ? void 0 : 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)(0, null)));
}
createKeyElement(label, extraClass = '') {
const keyElement = $('span.monaco-keybinding-key' + extraClass, undefined, label);
this.keyElements.add(keyElement);
return keyElement;
}
style(styles) {
this.labelBackground = styles.keybindingLabelBackground;
this.labelForeground = styles.keybindingLabelForeground;
this.labelBorder = styles.keybindingLabelBorder;
this.labelBottomBorder = styles.keybindingLabelBottomBorder;
this.labelShadow = styles.keybindingLabelShadow;
this.applyStyles();
}
applyStyles() {
var _a;
if (this.element) {
for (const keyElement of this.keyElements) {
if (this.labelBackground) {
keyElement.style.backgroundColor = (_a = this.labelBackground) === null || _a === void 0 ? void 0 : _a.toString();
}
if (this.labelBorder) {
keyElement.style.borderColor = this.labelBorder.toString();
}
if (this.labelBottomBorder) {
keyElement.style.borderBottomColor = this.labelBottomBorder.toString();
}
if (this.labelShadow) {
keyElement.style.boxShadow = `inset 0 -1px 0 ${this.labelShadow}`;
}
}
if (this.labelForeground) {
this.element.style.color = this.labelForeground.toString();
}
}
}
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;
});
define(__m[450/*vs/nls!vs/base/parts/quickinput/browser/quickInput*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/parts/quickinput/browser/quickInput", data); });
define(__m[451/*vs/nls!vs/base/parts/quickinput/browser/quickInputList*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/parts/quickinput/browser/quickInputList", 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[452/*vs/base/parts/quickinput/browser/quickInputList*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,104/*vs/base/common/iconLabels*/,291/*vs/base/common/comparers*/,6/*vs/base/common/event*/,51/*vs/base/browser/keyboardEvent*/,179/*vs/base/browser/ui/iconLabel/iconLabel*/,161/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,90/*vs/base/common/decorators*/,19/*vs/base/common/arrays*/,17/*vs/base/common/platform*/,84/*vs/base/browser/ui/actionbar/actionbar*/,50/*vs/base/common/actions*/,213/*vs/base/parts/quickinput/browser/quickInputUtils*/,20/*vs/base/common/types*/,449/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/,451/*vs/nls!vs/base/parts/quickinput/browser/quickInputList*/,27/*vs/base/common/codicons*/,132/*vs/css!vs/base/parts/quickinput/browser/media/quickInput*/]), function (require, exports, dom, lifecycle_1, iconLabels_1, comparers_1, event_1, keyboardEvent_1, iconLabel_1, highlightedLabel_1, decorators_1, arrays_1, platform, actionbar_1, actions_1, quickInputUtils_1, types_1, keybindingLabel_1, nls_1, codicons_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.QuickInputList = exports.QuickInputListFocus = void 0;
const $ = dom.$;
class ListElement {
constructor(init) {
this.hidden = false;
this._onChecked = new event_1.Emitter();
this.onChecked = this._onChecked.event;
Object.assign(this, init);
}
get checked() {
return !!this._checked;
}
set checked(value) {
if (value !== this._checked) {
this._checked = value;
this._onChecked.fire(value);
}
}
dispose() {
this._onChecked.dispose();
}
}
class ListElementRenderer {
get templateId() {
return ListElementRenderer.ID;
}
renderTemplate(container) {
const data = Object.create(null);
data.toDisposeElement = [];
data.toDisposeTemplate = [];
data.entry = dom.append(container, $('.quick-input-list-entry'));
// Checkbox
const label = dom.append(data.entry, $('label.quick-input-list-label'));
data.toDisposeTemplate.push(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';
data.toDisposeTemplate.push(dom.addStandardDisposableListener(data.checkbox, dom.EventType.CHANGE, e => {
data.element.checked = data.checkbox.checked;
}));
// 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 });
// Keybinding
const keybindingContainer = dom.append(row1, $('.quick-input-list-entry-keybinding'));
data.keybinding = new keybindingLabel_1.KeybindingLabel(keybindingContainer, platform.OS);
// Detail
const detailContainer = dom.append(row2, $('.quick-input-list-label-meta'));
data.detail = new highlightedLabel_1.HighlightedLabel(detailContainer, true);
// Separator
data.separator = dom.append(data.entry, $('.quick-input-list-separator'));
// Actions
data.actionBar = new actionbar_1.ActionBar(data.entry);
data.actionBar.domNode.classList.add('quick-input-list-entry-action-bar');
data.toDisposeTemplate.push(data.actionBar);
return data;
}
renderElement(element, index, data) {
data.toDisposeElement = (0, lifecycle_1.dispose)(data.toDisposeElement);
data.element = element;
data.checkbox.checked = element.checked;
data.toDisposeElement.push(element.onChecked(checked => data.checkbox.checked = checked));
const { labelHighlights, descriptionHighlights, detailHighlights } = element;
// Label
const options = Object.create(null);
options.matches = labelHighlights || [];
options.descriptionTitle = element.saneDescription;
options.descriptionMatches = descriptionHighlights || [];
options.extraClasses = element.item.iconClasses;
options.italic = element.item.italic;
options.strikethrough = element.item.strikethrough;
data.label.setLabel(element.saneLabel, element.saneDescription, options);
// Keybinding
data.keybinding.set(element.item.keybinding);
// Meta
data.detail.set(element.saneDetail, detailHighlights);
// Separator
if (element.separator && element.separator.label) {
data.separator.textContent = element.separator.label;
data.separator.style.display = '';
}
else {
data.separator.style.display = 'none';
}
data.entry.classList.toggle('quick-input-list-separator-border', !!element.separator);
// Actions
data.actionBar.clear();
const buttons = element.item.buttons;
if (buttons && buttons.length) {
data.actionBar.push(buttons.map((button, index) => {
let cssClasses = button.iconClass || (button.iconPath ? (0, quickInputUtils_1.getIconClass)(button.iconPath) : undefined);
if (button.alwaysVisible) {
cssClasses = cssClasses ? `${cssClasses} always-visible` : 'always-visible';
}
const action = new actions_1.Action(`id-${index}`, '', cssClasses, true, () => __awaiter(this, void 0, void 0, function* () {
element.fireButtonTriggered({
button,
item: element.item
});
}));
action.tooltip = button.tooltip || '';
return action;
}), { icon: true, label: false });
data.entry.classList.add('has-actions');
}
else {
data.entry.classList.remove('has-actions');
}
}
disposeElement(element, index, data) {
data.toDisposeElement = (0, lifecycle_1.dispose)(data.toDisposeElement);
}
disposeTemplate(data) {
data.toDisposeElement = (0, lifecycle_1.dispose)(data.toDisposeElement);
data.toDisposeTemplate = (0, lifecycle_1.dispose)(data.toDisposeTemplate);
}
}
ListElementRenderer.ID = 'listelement';
class ListElementDelegate {
getHeight(element) {
return element.saneDetail ? 44 : 22;
}
getTemplateId(element) {
return ListElementRenderer.ID;
}
}
var QuickInputListFocus;
(function (QuickInputListFocus) {
QuickInputListFocus[QuickInputListFocus["First"] = 1] = "First";
QuickInputListFocus[QuickInputListFocus["Second"] = 2] = "Second";
QuickInputListFocus[QuickInputListFocus["Last"] = 3] = "Last";
QuickInputListFocus[QuickInputListFocus["Next"] = 4] = "Next";
QuickInputListFocus[QuickInputListFocus["Previous"] = 5] = "Previous";
QuickInputListFocus[QuickInputListFocus["NextPage"] = 6] = "NextPage";
QuickInputListFocus[QuickInputListFocus["PreviousPage"] = 7] = "PreviousPage";
})(QuickInputListFocus = exports.QuickInputListFocus || (exports.QuickInputListFocus = {}));
class QuickInputList {
constructor(parent, id, options) {
this.parent = parent;
this.inputElements = [];
this.elements = [];
this.elementsToIndexes = new Map();
this.matchOnDescription = false;
this.matchOnDetail = false;
this.matchOnLabel = true;
this.matchOnMeta = true;
this.sortByLabel = true;
this._onChangedAllVisibleChecked = new event_1.Emitter();
this.onChangedAllVisibleChecked = this._onChangedAllVisibleChecked.event;
this._onChangedCheckedCount = new event_1.Emitter();
this.onChangedCheckedCount = this._onChangedCheckedCount.event;
this._onChangedVisibleCount = new event_1.Emitter();
this.onChangedVisibleCount = this._onChangedVisibleCount.event;
this._onChangedCheckedElements = new event_1.Emitter();
this.onChangedCheckedElements = this._onChangedCheckedElements.event;
this._onButtonTriggered = new event_1.Emitter();
this.onButtonTriggered = this._onButtonTriggered.event;
this._onKeyDown = new event_1.Emitter();
this.onKeyDown = this._onKeyDown.event;
this._onLeave = new event_1.Emitter();
this.onLeave = this._onLeave.event;
this._fireCheckedEvents = true;
this.elementDisposables = [];
this.disposables = [];
this.id = id;
this.container = dom.append(this.parent, $('.quick-input-list'));
const delegate = new ListElementDelegate();
const accessibilityProvider = new QuickInputAccessibilityProvider();
this.list = options.createList('QuickInput', this.container, delegate, [new ListElementRenderer()], {
identityProvider: { getId: element => element.saneLabel },
setRowLineHeight: false,
multipleSelectionSupport: false,
horizontalScrolling: false,
accessibilityProvider
});
this.list.getHTMLElement().id = id;
this.disposables.push(this.list);
this.disposables.push(this.list.onKeyDown(e => {
const event = new keyboardEvent_1.StandardKeyboardEvent(e);
switch (event.keyCode) {
case 10 /* Space */:
this.toggleCheckbox();
break;
case 31 /* KEY_A */:
if (platform.isMacintosh ? e.metaKey : e.ctrlKey) {
this.list.setFocus((0, arrays_1.range)(this.list.length));
}
break;
case 16 /* UpArrow */:
const focus1 = this.list.getFocus();
if (focus1.length === 1 && focus1[0] === 0) {
this._onLeave.fire();
}
break;
case 18 /* DownArrow */:
const focus2 = this.list.getFocus();
if (focus2.length === 1 && focus2[0] === this.list.length - 1) {
this._onLeave.fire();
}
break;
}
this._onKeyDown.fire(event);
}));
this.disposables.push(this.list.onMouseDown(e => {
if (e.browserEvent.button !== 2) {
// Works around / fixes #64350.
e.browserEvent.preventDefault();
}
}));
this.disposables.push(dom.addDisposableListener(this.container, dom.EventType.CLICK, e => {
if (e.x || e.y) { // Avoid 'click' triggered by 'space' on checkbox.
this._onLeave.fire();
}
}));
this.disposables.push(this.list.onMouseMiddleClick(e => {
this._onLeave.fire();
}));
this.disposables.push(this.list.onContextMenu(e => {
if (typeof e.index === 'number') {
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.list.setSelection([e.index]);
}
}));
this.disposables.push(this._onChangedAllVisibleChecked, this._onChangedCheckedCount, this._onChangedVisibleCount, this._onChangedCheckedElements, this._onButtonTriggered, this._onLeave, this._onKeyDown);
}
get onDidChangeFocus() {
return event_1.Event.map(this.list.onDidChangeFocus, e => e.elements.map(e => e.item));
}
get onDidChangeSelection() {
return event_1.Event.map(this.list.onDidChangeSelection, e => ({ items: e.elements.map(e => e.item), event: e.browserEvent }));
}
getAllVisibleChecked() {
return this.allVisibleChecked(this.elements, false);
}
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;
}
getCheckedCount() {
let count = 0;
const elements = this.elements;
for (let i = 0, n = elements.length; i < n; i++) {
if (elements[i].checked) {
count++;
}
}
return count;
}
getVisibleCount() {
let count = 0;
const elements = this.elements;
for (let i = 0, n = elements.length; i < n; i++) {
if (!elements[i].hidden) {
count++;
}
}
return count;
}
setAllVisibleChecked(checked) {
try {
this._fireCheckedEvents = false;
this.elements.forEach(element => {
if (!element.hidden) {
element.checked = checked;
}
});
}
finally {
this._fireCheckedEvents = true;
this.fireCheckedEvents();
}
}
setElements(inputElements) {
this.elementDisposables = (0, lifecycle_1.dispose)(this.elementDisposables);
const fireButtonTriggered = (event) => this.fireButtonTriggered(event);
this.inputElements = inputElements;
this.elements = inputElements.reduce((result, item, index) => {
var _a, _b, _c;
if (item.type !== 'separator') {
const previous = index && inputElements[index - 1];
const saneLabel = item.label && item.label.replace(/\r?\n/g, ' ');
const saneMeta = item.meta && item.meta.replace(/\r?\n/g, ' ');
const saneDescription = item.description && item.description.replace(/\r?\n/g, ' ');
const saneDetail = item.detail && item.detail.replace(/\r?\n/g, ' ');
const saneAriaLabel = item.ariaLabel || [saneLabel, saneDescription, saneDetail]
.map(s => (0, codicons_1.getCodiconAriaLabel)(s))
.filter(s => !!s)
.join(', ');
result.push(new ListElement({
index,
item,
saneLabel,
saneMeta,
saneAriaLabel,
saneDescription,
saneDetail,
labelHighlights: (_a = item.highlights) === null || _a === void 0 ? void 0 : _a.label,
descriptionHighlights: (_b = item.highlights) === null || _b === void 0 ? void 0 : _b.description,
detailHighlights: (_c = item.highlights) === null || _c === void 0 ? void 0 : _c.detail,
checked: false,
separator: previous && previous.type === 'separator' ? previous : undefined,
fireButtonTriggered
}));
}
return result;
}, []);
this.elementDisposables.push(...this.elements);
this.elementDisposables.push(...this.elements.map(element => element.onChecked(() => this.fireCheckedEvents())));
this.elementsToIndexes = this.elements.reduce((map, element, index) => {
map.set(element.item, index);
return map;
}, new Map());
this.list.splice(0, this.list.length); // Clear focus and selection first, sending the events when the list is empty.
this.list.splice(0, this.list.length, this.elements);
this._onChangedVisibleCount.fire(this.elements.length);
}
getFocusedElements() {
return this.list.getFocusedElements()
.map(e => e.item);
}
setFocusedElements(items) {
this.list.setFocus(items
.filter(item => this.elementsToIndexes.has(item))
.map(item => this.elementsToIndexes.get(item)));
if (items.length > 0) {
const focused = this.list.getFocus()[0];
if (typeof focused === 'number') {
this.list.reveal(focused);
}
}
}
getActiveDescendant() {
return this.list.getHTMLElement().getAttribute('aria-activedescendant');
}
setSelectedElements(items) {
this.list.setSelection(items
.filter(item => this.elementsToIndexes.has(item))
.map(item => this.elementsToIndexes.get(item)));
}
getCheckedElements() {
return this.elements.filter(e => e.checked)
.map(e => e.item);
}
setCheckedElements(items) {
try {
this._fireCheckedEvents = false;
const checked = new Set();
for (const item of items) {
checked.add(item);
}
for (const element of this.elements) {
element.checked = checked.has(element.item);
}
}
finally {
this._fireCheckedEvents = true;
this.fireCheckedEvents();
}
}
set enabled(value) {
this.list.getHTMLElement().style.pointerEvents = value ? '' : 'none';
}
focus(what) {
if (!this.list.length) {
return;
}
if (what === QuickInputListFocus.Next && this.list.getFocus()[0] === this.list.length - 1) {
what = QuickInputListFocus.First;
}
if (what === QuickInputListFocus.Previous && this.list.getFocus()[0] === 0) {
what = QuickInputListFocus.Last;
}
if (what === QuickInputListFocus.Second && this.list.length < 2) {
what = QuickInputListFocus.First;
}
switch (what) {
case QuickInputListFocus.First:
this.list.focusFirst();
break;
case QuickInputListFocus.Second:
this.list.focusNth(1);
break;
case QuickInputListFocus.Last:
this.list.focusLast();
break;
case QuickInputListFocus.Next:
this.list.focusNext();
break;
case QuickInputListFocus.Previous:
this.list.focusPrevious();
break;
case QuickInputListFocus.NextPage:
this.list.focusNextPage();
break;
case QuickInputListFocus.PreviousPage:
this.list.focusPreviousPage();
break;
}
const focused = this.list.getFocus()[0];
if (typeof focused === 'number') {
this.list.reveal(focused);
}
}
clearFocus() {
this.list.setFocus([]);
}
domFocus() {
this.list.domFocus();
}
layout(maxHeight) {
this.list.getHTMLElement().style.maxHeight = maxHeight ? `calc(${Math.floor(maxHeight / 44) * 44}px)` : '';
this.list.layout();
}
filter(query) {
if (!(this.sortByLabel || this.matchOnLabel || this.matchOnDescription || this.matchOnDetail)) {
this.list.layout();
return false;
}
query = query.trim();
// Reset filtering
if (!query || !(this.matchOnLabel || this.matchOnDescription || this.matchOnDetail)) {
this.elements.forEach(element => {
element.labelHighlights = undefined;
element.descriptionHighlights = undefined;
element.detailHighlights = undefined;
element.hidden = false;
const previous = element.index && this.inputElements[element.index - 1];
element.separator = previous && previous.type === 'separator' ? previous : undefined;
});
}
// Filter by value (since we support icons in labels, use $(..) aware fuzzy matching)
else {
let currentSeparator;
this.elements.forEach(element => {
const labelHighlights = this.matchOnLabel ? (0, types_1.withNullAsUndefined)((0, iconLabels_1.matchesFuzzyIconAware)(query, (0, iconLabels_1.parseLabelWithIcons)(element.saneLabel))) : undefined;
const descriptionHighlights = this.matchOnDescription ? (0, types_1.withNullAsUndefined)((0, iconLabels_1.matchesFuzzyIconAware)(query, (0, iconLabels_1.parseLabelWithIcons)(element.saneDescription || ''))) : undefined;
const detailHighlights = this.matchOnDetail ? (0, types_1.withNullAsUndefined)((0, iconLabels_1.matchesFuzzyIconAware)(query, (0, iconLabels_1.parseLabelWithIcons)(element.saneDetail || ''))) : undefined;
const metaHighlights = this.matchOnMeta ? (0, types_1.withNullAsUndefined)((0, iconLabels_1.matchesFuzzyIconAware)(query, (0, iconLabels_1.parseLabelWithIcons)(element.saneMeta || ''))) : undefined;
if (labelHighlights || descriptionHighlights || detailHighlights || metaHighlights) {
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.alwaysShow;
}
element.separator = undefined;
// we can show the separator unless the list gets sorted by match
if (!this.sortByLabel) {
const previous = element.index && this.inputElements[element.index - 1];
currentSeparator = previous && previous.type === 'separator' ? previous : currentSeparator;
if (currentSeparator && !element.hidden) {
element.separator = currentSeparator;
currentSeparator = undefined;
}
}
});
}
const shownElements = this.elements.filter(element => !element.hidden);
// Sort by value
if (this.sortByLabel && query) {
const normalizedSearchValue = query.toLowerCase();
shownElements.sort((a, b) => {
return compareEntries(a, b, normalizedSearchValue);
});
}
this.elementsToIndexes = shownElements.reduce((map, element, index) => {
map.set(element.item, index);
return map;
}, new Map());
this.list.splice(0, this.list.length, shownElements);
this.list.setFocus([]);
this.list.layout();
this._onChangedAllVisibleChecked.fire(this.getAllVisibleChecked());
this._onChangedVisibleCount.fire(shownElements.length);
return true;
}
toggleCheckbox() {
try {
this._fireCheckedEvents = false;
const elements = this.list.getFocusedElements();
const allChecked = this.allVisibleChecked(elements);
for (const element of elements) {
element.checked = !allChecked;
}
}
finally {
this._fireCheckedEvents = true;
this.fireCheckedEvents();
}
}
display(display) {
this.container.style.display = display ? '' : 'none';
}
isDisplayed() {
return this.container.style.display !== 'none';
}
dispose() {
this.elementDisposables = (0, lifecycle_1.dispose)(this.elementDisposables);
this.disposables = (0, lifecycle_1.dispose)(this.disposables);
}
fireCheckedEvents() {
if (this._fireCheckedEvents) {
this._onChangedAllVisibleChecked.fire(this.getAllVisibleChecked());
this._onChangedCheckedCount.fire(this.getCheckedCount());
this._onChangedCheckedElements.fire(this.getCheckedElements());
}
}
fireButtonTriggered(event) {
this._onButtonTriggered.fire(event);
}
style(styles) {
this.list.style(styles);
}
}
__decorate([
decorators_1.memoize
], QuickInputList.prototype, "onDidChangeFocus", null);
__decorate([
decorators_1.memoize
], QuickInputList.prototype, "onDidChangeSelection", null);
exports.QuickInputList = QuickInputList;
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.saneLabel, elementB.saneLabel, lookFor);
}
class QuickInputAccessibilityProvider {
getWidgetAriaLabel() {
return (0, nls_1.localize)(0, null);
}
getAriaLabel(element) {
return element.saneAriaLabel;
}
getWidgetRole() {
return 'listbox';
}
getRole() {
return 'option';
}
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[453/*vs/base/parts/quickinput/browser/quickInput*/], __M([0/*require*/,1/*exports*/,205/*vs/base/parts/quickinput/common/quickInput*/,7/*vs/base/browser/dom*/,23/*vs/base/common/cancellation*/,452/*vs/base/parts/quickinput/browser/quickInputList*/,445/*vs/base/parts/quickinput/browser/quickInputBox*/,51/*vs/base/browser/keyboardEvent*/,450/*vs/nls!vs/base/parts/quickinput/browser/quickInput*/,208/*vs/base/browser/ui/countBadge/countBadge*/,316/*vs/base/browser/ui/progressbar/progressbar*/,6/*vs/base/common/event*/,304/*vs/base/browser/ui/button/button*/,2/*vs/base/common/lifecycle*/,74/*vs/base/common/severity*/,84/*vs/base/browser/ui/actionbar/actionbar*/,50/*vs/base/common/actions*/,19/*vs/base/common/arrays*/,15/*vs/base/common/async*/,213/*vs/base/parts/quickinput/browser/quickInputUtils*/,27/*vs/base/common/codicons*/,105/*vs/base/browser/ui/iconLabel/iconLabels*/,17/*vs/base/common/platform*/,132/*vs/css!vs/base/parts/quickinput/browser/media/quickInput*/]), function (require, exports, quickInput_1, dom, cancellation_1, quickInputList_1, quickInputBox_1, keyboardEvent_1, nls_1, countBadge_1, progressbar_1, event_1, button_1, lifecycle_1, severity_1, actionbar_1, actions_1, arrays_1, async_1, quickInputUtils_1, codicons_1, iconLabels_1, platform_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.QuickInputController = void 0;
const $ = dom.$;
const backButtonIcon = (0, codicons_1.registerCodicon)('quick-input-back', codicons_1.Codicon.arrowLeft);
const backButton = {
iconClass: backButtonIcon.classNames,
tooltip: (0, nls_1.localize)(0, null),
handle: -1 // TODO
};
class QuickInput extends lifecycle_1.Disposable {
constructor(ui) {
super();
this.ui = ui;
this.visible = false;
this._enabled = true;
this._busy = false;
this._ignoreFocusOut = false;
this._buttons = [];
this.noValidationMessage = QuickInput.noPromptMessage;
this._severity = severity_1.default.Ignore;
this.buttonsUpdated = false;
this.onDidTriggerButtonEmitter = this._register(new event_1.Emitter());
this.onDidHideEmitter = 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 buttons() {
return this._buttons;
}
set buttons(buttons) {
this._buttons = buttons;
this.buttonsUpdated = 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);
this.visible = 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 });
}
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.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.buttons.filter(button => button === backButton);
this.ui.leftActionBar.push(leftButtons.map((button, index) => {
const action = new actions_1.Action(`id-${index}`, '', button.iconClass || (0, quickInputUtils_1.getIconClass)(button.iconPath), true, () => __awaiter(this, void 0, void 0, function* () {
this.onDidTriggerButtonEmitter.fire(button);
}));
action.tooltip = button.tooltip || '';
return action;
}), { icon: true, label: false });
this.ui.rightActionBar.clear();
const rightButtons = this.buttons.filter(button => button !== backButton);
this.ui.rightActionBar.push(rightButtons.map((button, index) => {
const action = new actions_1.Action(`id-${index}`, '', button.iconClass || (0, quickInputUtils_1.getIconClass)(button.iconPath), true, () => __awaiter(this, void 0, void 0, function* () {
this.onDidTriggerButtonEmitter.fire(button);
}));
action.tooltip = button.tooltip || '';
return action;
}), { icon: true, label: false });
}
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, iconLabels_1.renderLabelWithIcons)(validationMessage));
}
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)(2, null, 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.paddingBottom = '4px';
}
else {
this.ui.message.style.color = '';
this.ui.message.style.backgroundColor = '';
this.ui.message.style.border = '';
this.ui.message.style.paddingBottom = '';
}
}
dispose() {
this.hide();
this.onDisposeEmitter.fire();
super.dispose();
}
}
QuickInput.noPromptMessage = (0, nls_1.localize)(1, null);
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._sortByLabel = true;
this._autoFocusOnList = true;
this._itemActivation = this.ui.isScreenReaderOptimized() ? quickInput_1.ItemActivation.NONE /* https://github.com/microsoft/vscode/issues/57501 */ : 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.valueSelectionUpdated = true;
this._ok = 'default';
this._customButton = false;
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;
}
get quickNavigate() {
return this._quickNavigate;
}
set quickNavigate(quickNavigate) {
this._quickNavigate = quickNavigate;
this.update();
}
get value() {
return this._value;
}
set value(value) {
if (this._value !== value) {
this._value = value || '';
this.update();
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;
}
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 sortByLabel() {
return this._sortByLabel;
}
set sortByLabel(sortByLabel) {
this._sortByLabel = sortByLabel;
this.update();
}
get autoFocusOnList() {
return this._autoFocusOnList;
}
set autoFocusOnList(autoFocusOnList) {
this._autoFocusOnList = autoFocusOnList;
this.update();
}
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;
}
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.autoFocusOnList) {
if (!this.canSelectMany) {
this.ui.list.focus(quickInputList_1.QuickInputListFocus.First);
}
}
}
show() {
if (!this.visible) {
this.visibleDisposables.add(this.ui.inputBox.onDidChange(value => {
if (value === this.value) {
return;
}
this._value = value;
const didFilter = this.ui.list.filter(this.filterValue(this.ui.inputBox.value));
if (didFilter) {
this.trySelectFirst();
}
this.onDidChangeValueEmitter.fire(value);
}));
this.visibleDisposables.add(this.ui.inputBox.onMouseDown(event => {
if (!this.autoFocusOnList) {
this.ui.list.clearFocus();
}
}));
this.visibleDisposables.add((this._hideInput ? this.ui.list : this.ui.inputBox).onKeyDown((event) => {
switch (event.keyCode) {
case 18 /* DownArrow */:
this.ui.list.focus(quickInputList_1.QuickInputListFocus.Next);
if (this.canSelectMany) {
this.ui.list.domFocus();
}
dom.EventHelper.stop(event, true);
break;
case 16 /* UpArrow */:
if (this.ui.list.getFocusedElements().length) {
this.ui.list.focus(quickInputList_1.QuickInputListFocus.Previous);
}
else {
this.ui.list.focus(quickInputList_1.QuickInputListFocus.Last);
}
if (this.canSelectMany) {
this.ui.list.domFocus();
}
dom.EventHelper.stop(event, true);
break;
case 12 /* PageDown */:
this.ui.list.focus(quickInputList_1.QuickInputListFocus.NextPage);
if (this.canSelectMany) {
this.ui.list.domFocus();
}
dom.EventHelper.stop(event, true);
break;
case 11 /* PageUp */:
this.ui.list.focus(quickInputList_1.QuickInputListFocus.PreviousPage);
if (this.canSelectMany) {
this.ui.list.domFocus();
}
dom.EventHelper.stop(event, true);
break;
case 17 /* RightArrow */:
if (!this._canAcceptInBackground) {
return; // needs to be enabled
}
if (!this.ui.inputBox.isSelectionAtEnd()) {
return; // ensure input box selection at end
}
if (this.activeItems[0]) {
this._selectedItems = [this.activeItems[0]];
this.onDidChangeSelectionEmitter.fire(this.selectedItems);
this.handleAccept(true);
}
break;
case 14 /* Home */:
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey) {
this.ui.list.focus(quickInputList_1.QuickInputListFocus.First);
dom.EventHelper.stop(event, true);
}
break;
case 13 /* End */:
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey) {
this.ui.list.focus(quickInputList_1.QuickInputListFocus.Last);
dom.EventHelper.stop(event, true);
}
break;
}
}));
this.visibleDisposables.add(this.ui.onDidAccept(() => {
if (!this.canSelectMany && this.activeItems[0]) {
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.ui.list.onDidChangeFocus(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(event instanceof MouseEvent && event.button === 1 /* mouse middle click */);
}
}));
this.visibleDisposables.add(this.ui.list.onChangedCheckedElements(checkedItems => {
if (!this.canSelectMany) {
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.registerQuickNavigation());
this.valueSelectionUpdated = true;
}
super.show(); // TODO: Why have show() bubble up while update() trickles down? (Could move setComboboxAccessibility() here.)
}
handleAccept(inBackground) {
// Figure out veto via `onWillAccept` event
let veto = false;
this.onWillAcceptEmitter.fire({ veto: () => veto = true });
// Continue with `onDidAccpet` 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 [firstPart, chordPart] = k.getParts();
if (chordPart) {
return false;
}
if (firstPart.shiftKey && keyCode === 4 /* 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 (firstPart.altKey && keyCode === 6 /* Alt */) {
return true;
}
if (firstPart.ctrlKey && keyCode === 5 /* Ctrl */) {
return true;
}
if (firstPart.metaKey && keyCode === 57 /* 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;
}
const hideInput = !!this._hideInput && this._items.length > 0;
this.ui.container.classList.toggle('hidden-input', hideInput && !this.description);
const visibilities = {
title: !!this.title || !!this.step || !!this.buttons.length,
description: !!this.description,
checkAll: this.canSelectMany && !this._hideCheckAll,
checkBox: this.canSelectMany,
inputBox: !hideInput,
progressBar: !hideInput,
visibleCount: true,
count: this.canSelectMany,
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 || '');
}
const ariaLabel = this.ariaLabel || this.placeholder || QuickPick.DEFAULT_ARIA_LABEL;
if (this.ui.inputBox.ariaLabel !== ariaLabel) {
this.ui.inputBox.ariaLabel = ariaLabel;
}
this.ui.list.matchOnDescription = this.matchOnDescription;
this.ui.list.matchOnDetail = this.matchOnDetail;
this.ui.list.matchOnLabel = this.matchOnLabel;
this.ui.list.sortByLabel = this.sortByLabel;
if (this.itemsUpdated) {
this.itemsUpdated = false;
this.ui.list.setElements(this.items);
this.ui.list.filter(this.filterValue(this.ui.inputBox.value));
this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked();
this.ui.visibleCount.setCount(this.ui.list.getVisibleCount());
this.ui.count.setCount(this.ui.list.getCheckedCount());
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(quickInputList_1.QuickInputListFocus.Second);
this._itemActivation = quickInput_1.ItemActivation.FIRST; // only valid once, then unset
break;
case quickInput_1.ItemActivation.LAST:
this.ui.list.focus(quickInputList_1.QuickInputListFocus.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 || '';
this.ui.setComboboxAccessibility(true);
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(quickInputList_1.QuickInputListFocus.First);
}
}
}
}
QuickPick.DEFAULT_ARIA_LABEL = (0, nls_1.localize)(3, null);
class QuickInputController extends lifecycle_1.Disposable {
constructor(options) {
super();
this.options = options;
this.comboboxAccessibility = false;
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.idPrefix = options.idPrefix;
this.parentElement = options.container;
this.styles = options.styles;
this.registerKeyModsListeners();
}
registerKeyModsListeners() {
const listener = (e) => {
this.keyMods.ctrlCmd = e.ctrlKey || e.metaKey;
this.keyMods.alt = e.altKey;
};
this._register(dom.addDisposableListener(window, dom.EventType.KEY_DOWN, listener, true));
this._register(dom.addDisposableListener(window, dom.EventType.KEY_UP, listener, true));
this._register(dom.addDisposableListener(window, dom.EventType.MOUSE_DOWN, listener, true));
}
getUI() {
if (this.ui) {
return this.ui;
}
const container = dom.append(this.parentElement, $('.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));
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));
rightActionBar.domNode.classList.add('quick-input-right-action-bar');
const description1 = dom.append(container, $('.quick-input-description'));
const headerContainer = dom.append(container, $('.quick-input-header'));
const checkAll = dom.append(headerContainer, $('input.quick-input-check-all'));
checkAll.type = 'checkbox';
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 extraContainer = dom.append(headerContainer, $('.quick-input-and-message'));
const filterContainer = dom.append(extraContainer, $('.quick-input-filter'));
const inputBox = this._register(new quickInputBox_1.QuickInputBox(filterContainer));
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)(4, null) });
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)(5, null) });
const okContainer = dom.append(headerContainer, $('.quick-input-action'));
const ok = new button_1.Button(okContainer);
ok.label = (0, nls_1.localize)(6, null);
this._register(ok.onDidClick(e => {
this.onDidAcceptEmitter.fire();
}));
const customButtonContainer = dom.append(headerContainer, $('.quick-input-action'));
const customButton = new button_1.Button(customButtonContainer);
customButton.label = (0, nls_1.localize)(7, null);
this._register(customButton.onDidClick(e => {
this.onDidCustomEmitter.fire();
}));
const message = dom.append(extraContainer, $(`#${this.idPrefix}message.quick-input-message`));
const list = this._register(new quickInputList_1.QuickInputList(container, this.idPrefix + 'list', this.options));
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.
setTimeout(() => {
inputBox.setFocus();
if (this.controller instanceof QuickPick && this.controller.canSelectMany) {
list.clearFocus();
}
}, 0);
}));
this._register(list.onDidChangeFocus(() => {
if (this.comboboxAccessibility) {
this.getUI().inputBox.setAttribute('aria-activedescendant', this.getUI().list.getActiveDescendant() || '');
}
}));
const progressBar = new progressbar_1.ProgressBar(container);
progressBar.getContainer().classList.add('quick-input-progress');
const focusTracker = dom.trackFocus(container);
this._register(focusTracker);
this._register(dom.addDisposableListener(container, dom.EventType.FOCUS, e => {
this.previousFocusElement = e.relatedTarget instanceof HTMLElement ? e.relatedTarget : undefined;
}, true));
this._register(focusTracker.onDidBlur(() => {
if (!this.getUI().ignoreFocusOut && !this.options.ignoreFocusOut()) {
this.hide(quickInput_1.QuickInputHideReason.Blur);
}
this.previousFocusElement = undefined;
}));
this._register(dom.addDisposableListener(container, dom.EventType.FOCUS, (e) => {
inputBox.setFocus();
}));
this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e) => {
const event = new keyboardEvent_1.StandardKeyboardEvent(e);
switch (event.keyCode) {
case 3 /* Enter */:
dom.EventHelper.stop(e, true);
this.onDidAcceptEmitter.fire();
break;
case 9 /* Escape */:
dom.EventHelper.stop(e, true);
this.hide(quickInput_1.QuickInputHideReason.Gesture);
break;
case 2 /* Tab */:
if (!event.altKey && !event.ctrlKey && !event.metaKey) {
const selectors = ['.action-label.codicon'];
if (container.classList.contains('show-checkboxes')) {
selectors.push('input');
}
else {
selectors.push('input[type=text]');
}
if (this.getUI().list.isDisplayed()) {
selectors.push('.monaco-list');
}
const stops = container.querySelectorAll(selectors.join(', '));
if (event.shiftKey && event.target === stops[0]) {
dom.EventHelper.stop(e, true);
stops[stops.length - 1].focus();
}
else if (!event.shiftKey && event.target === stops[stops.length - 1]) {
dom.EventHelper.stop(e, true);
stops[0].focus();
}
}
break;
}
}));
this.ui = {
container,
styleSheet,
leftActionBar,
titleBar,
title,
description1,
description2,
rightActionBar,
checkAll,
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,
isScreenReaderOptimized: () => this.options.isScreenReaderOptimized(),
show: controller => this.show(controller),
hide: () => this.hide(),
setVisibilities: visibilities => this.setVisibilities(visibilities),
setComboboxAccessibility: enabled => this.setComboboxAccessibility(enabled),
setEnabled: enabled => this.setEnabled(enabled),
setContextKey: contextKey => this.options.setContextKey(contextKey),
};
this.updateStyles();
return this.ui;
}
pick(picks, options = {}, token = cancellation_1.CancellationToken.None) {
return new Promise((doResolve, reject) => {
let resolve = (result) => {
resolve = doResolve;
if (options.onKeyMods) {
options.onKeyMods(input.keyMods);
}
doResolve(result);
};
if (token.isCancellationRequested) {
resolve(undefined);
return;
}
const input = this.createQuickPick();
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(Object.assign(Object.assign({}, 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((ai) => ai !== removed[0]);
input.items = items;
if (activeItems) {
input.activeItems = activeItems;
}
}
} }))),
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;
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.autoFocusOnList = (options.autoFocusOnList === undefined) || options.autoFocusOnList; // default to true
input.quickNavigate = options.quickNavigate;
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() {
const ui = this.getUI();
return new QuickPick(ui);
}
show(controller) {
const ui = this.getUI();
this.onShowEmitter.fire();
const oldController = this.controller;
this.controller = controller;
if (oldController) {
oldController.didHide();
}
this.setEnabled(true);
ui.leftActionBar.clear();
ui.title.textContent = '';
ui.description1.textContent = '';
ui.description2.textContent = '';
ui.rightActionBar.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;
this.setComboboxAccessibility(false);
ui.inputBox.ariaLabel = '';
const backKeybindingLabel = this.options.backKeybindingLabel();
backButton.tooltip = backKeybindingLabel ? (0, nls_1.localize)(8, null, backKeybindingLabel) : (0, nls_1.localize)(9, null);
ui.container.style.display = '';
this.updateLayout();
ui.inputBox.setFocus();
}
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.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.display(!!visibilities.list);
ui.container.classList[visibilities.checkBox ? 'add' : 'remove']('show-checkboxes');
this.updateLayout(); // TODO
}
setComboboxAccessibility(enabled) {
if (enabled !== this.comboboxAccessibility) {
const ui = this.getUI();
this.comboboxAccessibility = enabled;
if (this.comboboxAccessibility) {
ui.inputBox.setAttribute('role', 'combobox');
ui.inputBox.setAttribute('aria-haspopup', 'true');
ui.inputBox.setAttribute('aria-autocomplete', 'list');
ui.inputBox.setAttribute('aria-activedescendant', ui.list.getActiveDescendant() || '');
}
else {
ui.inputBox.removeAttribute('role');
ui.inputBox.removeAttribute('aria-haspopup');
ui.inputBox.removeAttribute('aria-autocomplete');
ui.inputBox.removeAttribute('aria-activedescendant');
}
}
}
setEnabled(enabled) {
if (enabled !== this.enabled) {
this.enabled = enabled;
for (const item of this.getUI().leftActionBar.viewItems) {
item.getAction().enabled = enabled;
}
for (const item of this.getUI().rightActionBar.viewItems) {
item.getAction().enabled = enabled;
}
this.getUI().checkAll.disabled = !enabled;
// this.getUI().inputBox.enabled = enabled; Avoid loosing focus.
this.getUI().ok.enabled = enabled;
this.getUI().list.enabled = enabled;
}
}
hide(reason) {
var _a;
const controller = this.controller;
if (controller) {
const focusChanged = !((_a = this.ui) === null || _a === void 0 ? void 0 : _a.container.contains(document.activeElement));
this.controller = null;
this.onHideEmitter.fire();
this.getUI().container.style.display = 'none';
if (!focusChanged) {
if (this.previousFocusElement && this.previousFocusElement.offsetParent) {
this.previousFocusElement.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.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.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, contrastBorder, widgetShadow, } = this.styles.widget;
this.ui.titleBar.style.backgroundColor = quickInputTitleBackground ? quickInputTitleBackground.toString() : '';
this.ui.container.style.backgroundColor = quickInputBackground ? quickInputBackground.toString() : '';
this.ui.container.style.color = quickInputForeground ? quickInputForeground.toString() : '';
this.ui.container.style.border = contrastBorder ? `1px solid ${contrastBorder}` : '';
this.ui.container.style.boxShadow = widgetShadow ? `0 0 8px 2px ${widgetShadow}` : '';
this.ui.inputBox.style(this.styles.inputBox);
this.ui.count.style(this.styles.countBadge);
this.ui.ok.style(this.styles.button);
this.ui.customButton.style(this.styles.button);
this.ui.progressBar.style(this.styles.progressBar);
this.ui.list.style(this.styles.list);
const content = [];
if (this.styles.list.pickerGroupBorder) {
content.push(`.quick-input-list .quick-input-list-entry { border-top-color: ${this.styles.list.pickerGroupBorder}; }`);
}
if (this.styles.list.pickerGroupForeground) {
content.push(`.quick-input-list .quick-input-list-separator { color: ${this.styles.list.pickerGroupForeground}; }`);
}
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;
QuickInputController.MAX_WIDTH = 600; // Max total width of quick input widget
});
define(__m[454/*vs/nls!vs/editor/browser/controller/coreCommands*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/controller/coreCommands", data); });
define(__m[455/*vs/nls!vs/editor/browser/controller/textAreaHandler*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/controller/textAreaHandler", data); });
define(__m[456/*vs/nls!vs/editor/browser/core/keybindingCancellation*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/core/keybindingCancellation", data); });
define(__m[457/*vs/nls!vs/editor/browser/editorExtensions*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/editorExtensions", data); });
define(__m[458/*vs/nls!vs/editor/browser/widget/codeEditorWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/codeEditorWidget", data); });
define(__m[459/*vs/nls!vs/editor/browser/widget/diffEditorWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/diffEditorWidget", data); });
define(__m[460/*vs/nls!vs/editor/browser/widget/diffReview*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/diffReview", data); });
define(__m[461/*vs/nls!vs/editor/browser/widget/inlineDiffMargin*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/inlineDiffMargin", 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[462/*vs/editor/browser/widget/inlineDiffMargin*/], __M([0/*require*/,1/*exports*/,461/*vs/nls!vs/editor/browser/widget/inlineDiffMargin*/,7/*vs/base/browser/dom*/,50/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/,27/*vs/base/common/codicons*/]), function (require, exports, nls, dom, actions_1, lifecycle_1, range_1, codicons_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InlineDiffMargin = void 0;
class InlineDiffMargin extends lifecycle_1.Disposable {
constructor(_viewZoneId, _marginDomNode, editor, diff, _contextMenuService, _clipboardService) {
super();
this._viewZoneId = _viewZoneId;
this._marginDomNode = _marginDomNode;
this.editor = editor;
this.diff = diff;
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 = codicons_1.Codicon.lightBulb.classNames + ' lightbulb-glyph';
this._diffActions.style.position = 'absolute';
const lineHeight = editor.getOption(57 /* lineHeight */);
const lineFeed = editor.getModel().getEOL();
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);
const actions = [];
// default action
actions.push(new actions_1.Action('diff.clipboard.copyDeletedContent', diff.originalEndLineNumber > diff.modifiedStartLineNumber
? nls.localize(0, null)
: nls.localize(1, null), undefined, true, () => __awaiter(this, void 0, void 0, function* () {
const range = new range_1.Range(diff.originalStartLineNumber, 1, diff.originalEndLineNumber + 1, 1);
const deletedText = diff.originalModel.getValueInRange(range);
yield this._clipboardService.writeText(deletedText);
})));
let currentLineNumberOffset = 0;
let copyLineAction = undefined;
if (diff.originalEndLineNumber > diff.modifiedStartLineNumber) {
copyLineAction = new actions_1.Action('diff.clipboard.copyDeletedLineContent', nls.localize(2, null, diff.originalStartLineNumber), undefined, true, () => __awaiter(this, void 0, void 0, function* () {
const lineContent = diff.originalModel.getLineContent(diff.originalStartLineNumber + currentLineNumberOffset);
yield this._clipboardService.writeText(lineContent);
}));
actions.push(copyLineAction);
}
const readOnly = editor.getOption(79 /* readOnly */);
if (!readOnly) {
actions.push(new actions_1.Action('diff.inline.revertChange', nls.localize(3, null), undefined, true, () => __awaiter(this, void 0, void 0, function* () {
const range = new range_1.Range(diff.originalStartLineNumber, 1, diff.originalEndLineNumber, diff.originalModel.getLineMaxColumn(diff.originalEndLineNumber));
const deletedText = diff.originalModel.getValueInRange(range);
if (diff.modifiedEndLineNumber === 0) {
// deletion only
const column = editor.getModel().getLineMaxColumn(diff.modifiedStartLineNumber);
editor.executeEdits('diffEditor', [
{
range: new range_1.Range(diff.modifiedStartLineNumber, column, diff.modifiedStartLineNumber, column),
text: lineFeed + deletedText
}
]);
}
else {
const column = editor.getModel().getLineMaxColumn(diff.modifiedEndLineNumber);
editor.executeEdits('diffEditor', [
{
range: new range_1.Range(diff.modifiedStartLineNumber, 1, diff.modifiedEndLineNumber, column),
text: deletedText
}
]);
}
})));
}
const showContextMenu = (x, y) => {
this._contextMenuService.showContextMenu({
getAnchor: () => {
return {
x,
y
};
},
getActions: () => {
if (copyLineAction) {
copyLineAction.label = nls.localize(4, null, diff.originalStartLineNumber + currentLineNumberOffset);
}
return actions;
},
autoSelectFirstItem: true
});
};
this._register(dom.addStandardDisposableListener(this._diffActions, 'mousedown', e => {
const { top, height } = dom.getDomNodePagePosition(this._diffActions);
let pad = Math.floor(lineHeight / 3);
e.preventDefault();
showContextMenu(e.posx, top + height + pad);
}));
this._register(editor.onMouseMove((e) => {
if (e.target.type === 8 /* CONTENT_VIEW_ZONE */ || e.target.type === 5 /* GUTTER_VIEW_ZONE */) {
const viewZoneId = e.target.detail.viewZoneId;
if (viewZoneId === this._viewZoneId) {
this.visibility = true;
currentLineNumberOffset = this._updateLightBulbPosition(this._marginDomNode, e.event.browserEvent.y, lineHeight);
}
else {
this.visibility = false;
}
}
else {
this.visibility = false;
}
}));
this._register(editor.onMouseDown((e) => {
if (!e.event.rightButton) {
return;
}
if (e.target.type === 8 /* CONTENT_VIEW_ZONE */ || e.target.type === 5 /* GUTTER_VIEW_ZONE */) {
const viewZoneId = e.target.detail.viewZoneId;
if (viewZoneId === this._viewZoneId) {
e.event.preventDefault();
currentLineNumberOffset = this._updateLightBulbPosition(this._marginDomNode, e.event.browserEvent.y, lineHeight);
showContextMenu(e.event.posx, e.event.posy + lineHeight);
}
}
}));
}
get visibility() {
return this._visibility;
}
set visibility(_visibility) {
if (this._visibility !== _visibility) {
this._visibility = _visibility;
if (_visibility) {
this._diffActions.style.visibility = 'visible';
}
else {
this._diffActions.style.visibility = 'hidden';
}
}
}
_updateLightBulbPosition(marginDomNode, y, lineHeight) {
const { top } = dom.getDomNodePagePosition(marginDomNode);
const offset = y - top;
const lineNumberOffset = Math.floor(offset / lineHeight);
const newTop = lineNumberOffset * lineHeight;
this._diffActions.style.top = `${newTop}px`;
if (this.diff.viewLineCounts) {
let acc = 0;
for (let i = 0; i < this.diff.viewLineCounts.length; i++) {
acc += this.diff.viewLineCounts[i];
if (lineNumberOffset < acc) {
return i;
}
}
}
return lineNumberOffset;
}
}
exports.InlineDiffMargin = InlineDiffMargin;
});
define(__m[463/*vs/nls!vs/editor/common/config/commonEditorConfig*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/config/commonEditorConfig", data); });
define(__m[464/*vs/nls!vs/editor/common/config/editorOptions*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/config/editorOptions", 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[35/*vs/editor/common/config/editorOptions*/], __M([0/*require*/,1/*exports*/,464/*vs/nls!vs/editor/common/config/editorOptions*/,17/*vs/base/common/platform*/,135/*vs/editor/common/model/wordHelper*/]), function (require, exports, nls, platform, wordHelper_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EditorOptions = exports.editorOptionsRegistry = exports.EDITOR_MODEL_DEFAULTS = exports.EDITOR_FONT_DEFAULTS = exports.filterValidationDecorations = exports.EditorLayoutInfoComputer = exports.EditorFontLigatures = exports.TextEditorCursorStyle = exports.stringSet = exports.boolean = exports.ComputeOptionsMemory = exports.ValidatedEditorOptions = exports.ConfigurationChangedEvent = exports.MINIMAP_GUTTER_WIDTH = void 0;
/**
* @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 ValidatedEditorOptions {
constructor() {
this._values = [];
}
_read(option) {
return this._values[option];
}
get(id) {
return this._values[id];
}
_write(option, value) {
this._values[option] = value;
}
}
exports.ValidatedEditorOptions = ValidatedEditorOptions;
/**
* @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;
}
compute(env, options, value) {
return value;
}
}
/**
* @internal
*/
class ComputedEditorOption {
constructor(id, deps = null) {
this.schema = undefined;
this.id = id;
this.name = '_never_';
this.defaultValue = undefined;
this.deps = deps;
}
validate(input) {
return this.defaultValue;
}
}
class SimpleEditorOption {
constructor(id, name, defaultValue, schema) {
this.id = id;
this.name = name;
this.defaultValue = defaultValue;
this.schema = schema;
}
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);
}
exports.boolean = boolean;
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);
}
}
class EditorIntOption extends SimpleEditorOption {
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;
}
static 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;
}
validate(input) {
return EditorIntOption.clampedInt(input, this.defaultValue, this.minimum, this.maximum);
}
}
class EditorFloatOption extends SimpleEditorOption {
constructor(id, name, defaultValue, validationFn, schema) {
if (typeof schema !== 'undefined') {
schema.type = 'number';
schema.default = defaultValue;
}
super(id, name, defaultValue, schema);
this.validationFn = validationFn;
}
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);
}
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) {
if (typeof value !== 'string') {
return defaultValue;
}
if (allowedValues.indexOf(value) === -1) {
return defaultValue;
}
return value;
}
exports.stringSet = stringSet;
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 /* None */;
case 'keep': return 1 /* Keep */;
case 'brackets': return 2 /* Brackets */;
case 'advanced': return 3 /* Advanced */;
case 'full': return 4 /* Full */;
}
}
//#endregion
//#region accessibilitySupport
class EditorAccessibilitySupport extends BaseEditorOption {
constructor() {
super(2 /* accessibilitySupport */, 'accessibilitySupport', 0 /* Unknown */, {
type: 'string',
enum: ['auto', 'on', 'off'],
enumDescriptions: [
nls.localize(0, null),
nls.localize(1, null),
nls.localize(2, null),
],
default: 'auto',
description: nls.localize(3, null)
});
}
validate(input) {
switch (input) {
case 'auto': return 0 /* Unknown */;
case 'off': return 1 /* Disabled */;
case 'on': return 2 /* Enabled */;
}
return this.defaultValue;
}
compute(env, options, value) {
if (value === 0 /* 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(17 /* comments */, 'comments', defaults, {
'editor.comments.insertSpace': {
type: 'boolean',
default: defaults.insertSpace,
description: nls.localize(4, null)
},
'editor.comments.ignoreEmptyLines': {
type: 'boolean',
default: defaults.ignoreEmptyLines,
description: nls.localize(5, null)
},
});
}
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 /* Blink */;
case 'smooth': return 2 /* Smooth */;
case 'phase': return 3 /* Phase */;
case 'expand': return 4 /* Expand */;
case 'solid': return 5 /* 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 || (exports.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(126 /* editorClassName */, [64 /* mouseStyle */, 31 /* extraEditorClassName */]);
}
compute(env, options, _) {
const classNames = ['monaco-editor'];
if (options.get(31 /* extraEditorClassName */)) {
classNames.push(options.get(31 /* extraEditorClassName */));
}
if (env.extraEditorClassName) {
classNames.push(env.extraEditorClassName);
}
if (options.get(64 /* mouseStyle */) === 'default') {
classNames.push('mouse-default');
}
else if (options.get(64 /* mouseStyle */) === 'copy') {
classNames.push('mouse-copy');
}
if (options.get(99 /* showUnused */)) {
classNames.push('showUnused');
}
if (options.get(124 /* showDeprecated */)) {
classNames.push('showDeprecated');
}
return classNames.join(' ');
}
}
//#endregion
//#region emptySelectionClipboard
class EditorEmptySelectionClipboard extends EditorBooleanOption {
constructor() {
super(30 /* emptySelectionClipboard */, 'emptySelectionClipboard', true, { description: nls.localize(6, null) });
}
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(33 /* find */, 'find', defaults, {
'editor.find.cursorMoveOnType': {
type: 'boolean',
default: defaults.cursorMoveOnType,
description: nls.localize(7, null)
},
'editor.find.seedSearchStringFromSelection': {
type: 'string',
enum: ['never', 'always', 'selection'],
default: defaults.seedSearchStringFromSelection,
enumDescriptions: [
nls.localize(8, null),
nls.localize(9, null),
nls.localize(10, null)
],
description: nls.localize(11, null)
},
'editor.find.autoFindInSelection': {
type: 'string',
enum: ['never', 'always', 'multiline'],
default: defaults.autoFindInSelection,
enumDescriptions: [
nls.localize(12, null),
nls.localize(13, null),
nls.localize(14, null)
],
description: nls.localize(15, null)
},
'editor.find.globalFindClipboard': {
type: 'boolean',
default: defaults.globalFindClipboard,
description: nls.localize(16, null),
included: platform.isMacintosh
},
'editor.find.addExtraSpaceOnTop': {
type: 'boolean',
default: defaults.addExtraSpaceOnTop,
description: nls.localize(17, null)
},
'editor.find.loop': {
type: 'boolean',
default: defaults.loop,
description: nls.localize(18, null)
},
});
}
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 {
constructor() {
super(42 /* fontLigatures */, 'fontLigatures', EditorFontLigatures.OFF, {
anyOf: [
{
type: 'boolean',
description: nls.localize(19, null),
},
{
type: 'string',
description: nls.localize(20, null)
}
],
description: nls.localize(21, null),
default: false
});
}
validate(input) {
if (typeof input === 'undefined') {
return this.defaultValue;
}
if (typeof input === 'string') {
if (input === 'false') {
return EditorFontLigatures.OFF;
}
if (input === 'true') {
return EditorFontLigatures.ON;
}
return input;
}
if (Boolean(input)) {
return EditorFontLigatures.ON;
}
return EditorFontLigatures.OFF;
}
}
exports.EditorFontLigatures = EditorFontLigatures;
EditorFontLigatures.OFF = '"liga" off, "calt" off';
EditorFontLigatures.ON = '"liga" on, "calt" on';
//#endregion
//#region fontInfo
class EditorFontInfo extends ComputedEditorOption {
constructor() {
super(41 /* fontInfo */);
}
compute(env, options, _) {
return env.fontInfo;
}
}
//#endregion
//#region fontSize
class EditorFontSize extends SimpleEditorOption {
constructor() {
super(43 /* fontSize */, 'fontSize', exports.EDITOR_FONT_DEFAULTS.fontSize, {
type: 'number',
minimum: 6,
maximum: 100,
default: exports.EDITOR_FONT_DEFAULTS.fontSize,
description: nls.localize(22, null)
});
}
validate(input) {
let 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 {
constructor() {
super(44 /* fontWeight */, 'fontWeight', exports.EDITOR_FONT_DEFAULTS.fontWeight, {
anyOf: [
{
type: 'number',
minimum: EditorFontWeight.MINIMUM_VALUE,
maximum: EditorFontWeight.MAXIMUM_VALUE,
errorMessage: nls.localize(23, null)
},
{
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(24, null)
});
}
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));
}
}
EditorFontWeight.SUGGESTION_VALUES = ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'];
EditorFontWeight.MINIMUM_VALUE = 1;
EditorFontWeight.MAXIMUM_VALUE = 1000;
class EditorGoToLocation extends BaseEditorOption {
constructor() {
const defaults = {
multiple: 'peek',
multipleDefinitions: 'peek',
multipleTypeDefinitions: 'peek',
multipleDeclarations: 'peek',
multipleImplementations: 'peek',
multipleReferences: 'peek',
alternativeDefinitionCommand: 'editor.action.goToReferences',
alternativeTypeDefinitionCommand: 'editor.action.goToReferences',
alternativeDeclarationCommand: 'editor.action.goToReferences',
alternativeImplementationCommand: '',
alternativeReferenceCommand: '',
};
const jsonSubset = {
type: 'string',
enum: ['peek', 'gotoAndPeek', 'goto'],
default: defaults.multiple,
enumDescriptions: [
nls.localize(25, null),
nls.localize(26, null),
nls.localize(27, null)
]
};
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(48 /* gotoLocation */, 'gotoLocation', defaults, {
'editor.gotoLocation.multiple': {
deprecationMessage: nls.localize(28, null),
},
'editor.gotoLocation.multipleDefinitions': Object.assign({ description: nls.localize(29, null) }, jsonSubset),
'editor.gotoLocation.multipleTypeDefinitions': Object.assign({ description: nls.localize(30, null) }, jsonSubset),
'editor.gotoLocation.multipleDeclarations': Object.assign({ description: nls.localize(31, null) }, jsonSubset),
'editor.gotoLocation.multipleImplementations': Object.assign({ description: nls.localize(32, null) }, jsonSubset),
'editor.gotoLocation.multipleReferences': Object.assign({ description: nls.localize(33, null) }, jsonSubset),
'editor.gotoLocation.alternativeDefinitionCommand': {
type: 'string',
default: defaults.alternativeDefinitionCommand,
enum: alternativeCommandOptions,
description: nls.localize(34, null)
},
'editor.gotoLocation.alternativeTypeDefinitionCommand': {
type: 'string',
default: defaults.alternativeTypeDefinitionCommand,
enum: alternativeCommandOptions,
description: nls.localize(35, null)
},
'editor.gotoLocation.alternativeDeclarationCommand': {
type: 'string',
default: defaults.alternativeDeclarationCommand,
enum: alternativeCommandOptions,
description: nls.localize(36, null)
},
'editor.gotoLocation.alternativeImplementationCommand': {
type: 'string',
default: defaults.alternativeImplementationCommand,
enum: alternativeCommandOptions,
description: nls.localize(37, null)
},
'editor.gotoLocation.alternativeReferenceCommand': {
type: 'string',
default: defaults.alternativeReferenceCommand,
enum: alternativeCommandOptions,
description: nls.localize(38, null)
},
});
}
validate(_input) {
var _a, _b, _c, _d, _e;
if (!_input || typeof _input !== 'object') {
return this.defaultValue;
}
const input = _input;
return {
multiple: stringSet(input.multiple, this.defaultValue.multiple, ['peek', 'gotoAndPeek', 'goto']),
multipleDefinitions: (_a = input.multipleDefinitions) !== null && _a !== void 0 ? _a : stringSet(input.multipleDefinitions, 'peek', ['peek', 'gotoAndPeek', 'goto']),
multipleTypeDefinitions: (_b = input.multipleTypeDefinitions) !== null && _b !== void 0 ? _b : stringSet(input.multipleTypeDefinitions, 'peek', ['peek', 'gotoAndPeek', 'goto']),
multipleDeclarations: (_c = input.multipleDeclarations) !== null && _c !== void 0 ? _c : stringSet(input.multipleDeclarations, 'peek', ['peek', 'gotoAndPeek', 'goto']),
multipleImplementations: (_d = input.multipleImplementations) !== null && _d !== void 0 ? _d : stringSet(input.multipleImplementations, 'peek', ['peek', 'gotoAndPeek', 'goto']),
multipleReferences: (_e = input.multipleReferences) !== null && _e !== void 0 ? _e : stringSet(input.multipleReferences, '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),
};
}
}
class EditorHover extends BaseEditorOption {
constructor() {
const defaults = {
enabled: true,
delay: 300,
sticky: true
};
super(51 /* hover */, 'hover', defaults, {
'editor.hover.enabled': {
type: 'boolean',
default: defaults.enabled,
description: nls.localize(39, null)
},
'editor.hover.delay': {
type: 'number',
default: defaults.delay,
description: nls.localize(40, null)
},
'editor.hover.sticky': {
type: 'boolean',
default: defaults.sticky,
description: nls.localize(41, null)
},
});
}
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)
};
}
}
/**
* @internal
*/
class EditorLayoutInfoComputer extends ComputedEditorOption {
constructor() {
super(129 /* layoutInfo */, [
47 /* glyphMargin */, 56 /* lineDecorationsWidth */, 35 /* folding */,
63 /* minimap */, 91 /* scrollbar */, 58 /* lineNumbers */,
59 /* lineNumbersMinChars */, 93 /* scrollBeyondLastLine */,
116 /* wordWrap */, 119 /* wordWrapColumn */, 120 /* wordWrapOverride1 */, 121 /* wordWrapOverride2 */,
2 /* accessibilitySupport */
]);
}
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
});
}
static computeContainedMinimapLineCount(input) {
const typicalViewportLineCount = input.height / input.lineHeight;
const extraLinesBeyondLastLine = input.scrollBeyondLastLine ? (typicalViewportLineCount - 1) : 0;
const desiredRatio = (input.viewLineCount + extraLinesBeyondLastLine) / (input.pixelRatio * input.height);
const minimapLineCount = Math.floor(input.viewLineCount / desiredRatio);
return { typicalViewportLineCount, 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 /* 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.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, extraLinesBeyondLastLine, desiredRatio, minimapLineCount } = EditorLayoutInfoComputer.computeContainedMinimapLineCount({
viewLineCount: viewLineCount,
scrollBeyondLastLine: scrollBeyondLastLine,
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((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, 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 /* Text */ : 2 /* 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(121 /* wordWrapOverride2 */);
const wordWrapOverride1 = (wordWrapOverride2 === 'inherit' ? options.get(120 /* wordWrapOverride1 */) : wordWrapOverride2);
const wordWrap = (wordWrapOverride1 === 'inherit' ? options.get(116 /* wordWrap */) : wordWrapOverride1);
const wordWrapColumn = options.get(119 /* wordWrapColumn */);
const accessibilitySupport = options.get(2 /* accessibilitySupport */);
const isDominatedByLongLines = env.isDominatedByLongLines;
const showGlyphMargin = options.get(47 /* glyphMargin */);
const showLineNumbers = (options.get(58 /* lineNumbers */).renderType !== 0 /* Off */);
const lineNumbersMinChars = options.get(59 /* lineNumbersMinChars */);
const scrollBeyondLastLine = options.get(93 /* scrollBeyondLastLine */);
const minimap = options.get(63 /* minimap */);
const scrollbar = options.get(91 /* scrollbar */);
const verticalScrollbarWidth = scrollbar.verticalScrollbarSize;
const verticalScrollbarHasArrows = scrollbar.verticalHasArrows;
const scrollbarArrowSize = scrollbar.arrowSize;
const horizontalScrollbarHeight = scrollbar.horizontalScrollbarSize;
const rawLineDecorationsWidth = options.get(56 /* lineDecorationsWidth */);
const folding = options.get(35 /* folding */);
let lineDecorationsWidth;
if (typeof rawLineDecorationsWidth === 'string' && /^\d+(\.\d+)?ch$/.test(rawLineDecorationsWidth)) {
const multiple = parseFloat(rawLineDecorationsWidth.substr(0, rawLineDecorationsWidth.length - 2));
lineDecorationsWidth = EditorIntOption.clampedInt(multiple * typicalHalfwidthCharacterWidth, 0, 0, 1000);
}
else {
lineDecorationsWidth = EditorIntOption.clampedInt(rawLineDecorationsWidth, 0, 0, 1000);
}
if (folding) {
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;
}
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 (accessibilitySupport !== 2 /* Enabled */) {
// See https://github.com/microsoft/vscode/issues/27766
// Never enable wrapping when a screen reader is attached
// because arrow down etc. will not move the cursor in the way
// a screen reader expects.
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,
minimap: minimap,
verticalScrollbarWidth: verticalScrollbarWidth,
viewLineCount: viewLineCount,
remainingWidth: remainingWidth,
isViewportWrapping: isViewportWrapping,
}, env.memory || new ComputeOptionsMemory());
if (minimapLayout.renderMinimap !== 0 /* 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,
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;
class EditorLightbulb extends BaseEditorOption {
constructor() {
const defaults = { enabled: true };
super(55 /* lightbulb */, 'lightbulb', defaults, {
'editor.lightbulb.enabled': {
type: 'boolean',
default: defaults.enabled,
description: nls.localize(42, null)
},
});
}
validate(_input) {
if (!_input || typeof _input !== 'object') {
return this.defaultValue;
}
const input = _input;
return {
enabled: boolean(input.enabled, this.defaultValue.enabled)
};
}
}
class EditorInlayHints extends BaseEditorOption {
constructor() {
const defaults = { enabled: true, fontSize: 0, fontFamily: '' };
super(125 /* inlayHints */, 'inlayHints', defaults, {
'editor.inlayHints.enabled': {
type: 'boolean',
default: defaults.enabled,
description: nls.localize(43, null)
},
'editor.inlayHints.fontSize': {
type: 'number',
default: defaults.fontSize,
markdownDescription: nls.localize(44, null)
},
'editor.inlayHints.fontFamily': {
type: 'string',
default: defaults.fontFamily,
description: nls.localize(45, null)
},
});
}
validate(_input) {
if (!_input || typeof _input !== 'object') {
return this.defaultValue;
}
const input = _input;
return {
enabled: boolean(input.enabled, this.defaultValue.enabled),
fontSize: EditorIntOption.clampedInt(input.fontSize, this.defaultValue.fontSize, 0, 100),
fontFamily: EditorStringOption.string(input.fontFamily, this.defaultValue.fontFamily)
};
}
}
//#endregion
//#region lineHeight
class EditorLineHeight extends EditorFloatOption {
constructor() {
super(57 /* lineHeight */, 'lineHeight', exports.EDITOR_FONT_DEFAULTS.lineHeight, x => EditorFloatOption.clamp(x, 0, 150), { markdownDescription: nls.localize(46, null) });
}
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',
renderCharacters: true,
maxColumn: 120,
scale: 1,
};
super(63 /* minimap */, 'minimap', defaults, {
'editor.minimap.enabled': {
type: 'boolean',
default: defaults.enabled,
description: nls.localize(47, null)
},
'editor.minimap.size': {
type: 'string',
enum: ['proportional', 'fill', 'fit'],
enumDescriptions: [
nls.localize(48, null),
nls.localize(49, null),
nls.localize(50, null),
],
default: defaults.size,
description: nls.localize(51, null)
},
'editor.minimap.side': {
type: 'string',
enum: ['left', 'right'],
default: defaults.side,
description: nls.localize(52, null)
},
'editor.minimap.showSlider': {
type: 'string',
enum: ['always', 'mouseover'],
default: defaults.showSlider,
description: nls.localize(53, null)
},
'editor.minimap.scale': {
type: 'number',
default: defaults.scale,
minimum: 1,
maximum: 3,
enum: [1, 2, 3],
description: nls.localize(54, null)
},
'editor.minimap.renderCharacters': {
type: 'boolean',
default: defaults.renderCharacters,
description: nls.localize(55, null)
},
'editor.minimap.maxColumn': {
type: 'number',
default: defaults.maxColumn,
description: nls.localize(56, null)
}
});
}
validate(_input) {
if (!_input || typeof _input !== 'object') {
return this.defaultValue;
}
const input = _input;
return {
enabled: boolean(input.enabled, this.defaultValue.enabled),
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),
};
}
}
//#endregion
//#region multiCursorModifier
function _multiCursorModifierFromString(multiCursorModifier) {
if (multiCursorModifier === 'ctrlCmd') {
return (platform.isMacintosh ? 'metaKey' : 'ctrlKey');
}
return 'altKey';
}
class EditorPadding extends BaseEditorOption {
constructor() {
super(73 /* padding */, 'padding', { top: 0, bottom: 0 }, {
'editor.padding.top': {
type: 'number',
default: 0,
minimum: 0,
maximum: 1000,
description: nls.localize(57, null)
},
'editor.padding.bottom': {
type: 'number',
default: 0,
minimum: 0,
maximum: 1000,
description: nls.localize(58, null)
}
});
}
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: false
};
super(74 /* parameterHints */, 'parameterHints', defaults, {
'editor.parameterHints.enabled': {
type: 'boolean',
default: defaults.enabled,
description: nls.localize(59, null)
},
'editor.parameterHints.cycle': {
type: 'boolean',
default: defaults.cycle,
description: nls.localize(60, null)
},
});
}
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(127 /* pixelRatio */);
}
compute(env, options, _) {
return env.pixelRatio;
}
}
class EditorQuickSuggestions extends BaseEditorOption {
constructor() {
const defaults = {
other: true,
comments: false,
strings: false
};
super(77 /* quickSuggestions */, 'quickSuggestions', defaults, {
anyOf: [
{
type: 'boolean',
},
{
type: 'object',
properties: {
strings: {
type: 'boolean',
default: defaults.strings,
description: nls.localize(61, null)
},
comments: {
type: 'boolean',
default: defaults.comments,
description: nls.localize(62, null)
},
other: {
type: 'boolean',
default: defaults.other,
description: nls.localize(63, null)
},
}
}
],
default: defaults,
description: nls.localize(64, null)
});
this.defaultValue = defaults;
}
validate(_input) {
if (typeof _input === 'boolean') {
return _input;
}
if (_input && typeof _input === 'object') {
const input = _input;
const opts = {
other: boolean(input.other, this.defaultValue.other),
comments: boolean(input.comments, this.defaultValue.comments),
strings: boolean(input.strings, this.defaultValue.strings),
};
if (opts.other && opts.comments && opts.strings) {
return true; // all on
}
else if (!opts.other && !opts.comments && !opts.strings) {
return false; // all off
}
else {
return opts;
}
}
return this.defaultValue;
}
}
class EditorRenderLineNumbersOption extends BaseEditorOption {
constructor() {
super(58 /* lineNumbers */, 'lineNumbers', { renderType: 1 /* On */, renderFn: null }, {
type: 'string',
enum: ['off', 'on', 'relative', 'interval'],
enumDescriptions: [
nls.localize(65, null),
nls.localize(66, null),
nls.localize(67, null),
nls.localize(68, null)
],
default: 'on',
description: nls.localize(69, null)
});
}
validate(lineNumbers) {
let renderType = this.defaultValue.renderType;
let renderFn = this.defaultValue.renderFn;
if (typeof lineNumbers !== 'undefined') {
if (typeof lineNumbers === 'function') {
renderType = 4 /* Custom */;
renderFn = lineNumbers;
}
else if (lineNumbers === 'interval') {
renderType = 3 /* Interval */;
}
else if (lineNumbers === 'relative') {
renderType = 2 /* Relative */;
}
else if (lineNumbers === 'on') {
renderType = 1 /* On */;
}
else {
renderType = 0 /* Off */;
}
}
return {
renderType,
renderFn
};
}
}
//#endregion
//#region renderValidationDecorations
/**
* @internal
*/
function filterValidationDecorations(options) {
const renderValidationDecorations = options.get(86 /* renderValidationDecorations */);
if (renderValidationDecorations === 'editable') {
return options.get(79 /* readOnly */);
}
return renderValidationDecorations === 'on' ? false : true;
}
exports.filterValidationDecorations = filterValidationDecorations;
class EditorRulers extends BaseEditorOption {
constructor() {
const defaults = [];
const columnSchema = { type: 'number', description: nls.localize(70, null) };
super(90 /* rulers */, 'rulers', defaults, {
type: 'array',
items: {
anyOf: [
columnSchema,
{
type: [
'object'
],
properties: {
column: columnSchema,
color: {
type: 'string',
description: nls.localize(71, null),
format: 'color-hex'
}
}
}
]
},
default: defaults,
description: nls.localize(72, null)
});
}
validate(input) {
if (Array.isArray(input)) {
let rulers = [];
for (let _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;
}
}
function _scrollbarVisibilityFromString(visibility, defaultValue) {
if (typeof visibility !== 'string') {
return defaultValue;
}
switch (visibility) {
case 'hidden': return 2 /* Hidden */;
case 'visible': return 3 /* Visible */;
default: return 1 /* Auto */;
}
}
class EditorScrollbar extends BaseEditorOption {
constructor() {
const defaults = {
vertical: 1 /* Auto */,
horizontal: 1 /* Auto */,
arrowSize: 11,
useShadows: true,
verticalHasArrows: false,
horizontalHasArrows: false,
horizontalScrollbarSize: 12,
horizontalSliderSize: 12,
verticalScrollbarSize: 14,
verticalSliderSize: 14,
handleMouseWheel: true,
alwaysConsumeMouseWheel: true,
scrollByPage: false
};
super(91 /* scrollbar */, 'scrollbar', defaults, {
'editor.scrollbar.vertical': {
type: 'string',
enum: ['auto', 'visible', 'hidden'],
enumDescriptions: [
nls.localize(73, null),
nls.localize(74, null),
nls.localize(75, null),
],
default: 'auto',
description: nls.localize(76, null)
},
'editor.scrollbar.horizontal': {
type: 'string',
enum: ['auto', 'visible', 'hidden'],
enumDescriptions: [
nls.localize(77, null),
nls.localize(78, null),
nls.localize(79, null),
],
default: 'auto',
description: nls.localize(80, null)
},
'editor.scrollbar.verticalScrollbarSize': {
type: 'number',
default: defaults.verticalScrollbarSize,
description: nls.localize(81, null)
},
'editor.scrollbar.horizontalScrollbarSize': {
type: 'number',
default: defaults.horizontalScrollbarSize,
description: nls.localize(82, null)
},
'editor.scrollbar.scrollByPage': {
type: 'boolean',
default: defaults.scrollByPage,
description: nls.localize(83, null)
}
});
}
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),
};
}
}
/**
* Configuration options for inline suggestions
*/
class InlineEditorSuggest extends BaseEditorOption {
constructor() {
const defaults = {
enabled: false,
mode: 'subwordSmart'
};
super(53 /* inlineSuggest */, 'inlineSuggest', defaults, {
'editor.inlineSuggest.enabled': {
type: 'boolean',
default: defaults.enabled,
description: nls.localize(84, null)
},
'editor.inlineSuggest.mode': {
type: 'string',
enum: ['prefix', 'subword', 'subwordSmart'],
enumDescriptions: [
nls.localize(85, null),
nls.localize(86, null),
nls.localize(87, null),
],
default: defaults.mode,
description: nls.localize(88, null)
},
});
}
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']),
};
}
}
class EditorSuggest extends BaseEditorOption {
constructor() {
const defaults = {
insertMode: 'insert',
filterGraceful: true,
snippetsPreventQuickSuggestions: true,
localityBonus: false,
shareSuggestSelections: false,
showIcons: true,
showStatusBar: false,
preview: false,
previewMode: 'subwordSmart',
showInlineDetails: true,
showMethods: true,
showFunctions: true,
showConstructors: true,
showDeprecated: 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(105 /* suggest */, 'suggest', defaults, {
'editor.suggest.insertMode': {
type: 'string',
enum: ['insert', 'replace'],
enumDescriptions: [
nls.localize(89, null),
nls.localize(90, null),
],
default: defaults.insertMode,
description: nls.localize(91, null)
},
'editor.suggest.filterGraceful': {
type: 'boolean',
default: defaults.filterGraceful,
description: nls.localize(92, null)
},
'editor.suggest.localityBonus': {
type: 'boolean',
default: defaults.localityBonus,
description: nls.localize(93, null)
},
'editor.suggest.shareSuggestSelections': {
type: 'boolean',
default: defaults.shareSuggestSelections,
markdownDescription: nls.localize(94, null)
},
'editor.suggest.snippetsPreventQuickSuggestions': {
type: 'boolean',
default: defaults.snippetsPreventQuickSuggestions,
description: nls.localize(95, null)
},
'editor.suggest.showIcons': {
type: 'boolean',
default: defaults.showIcons,
description: nls.localize(96, null)
},
'editor.suggest.showStatusBar': {
type: 'boolean',
default: defaults.showStatusBar,
description: nls.localize(97, null)
},
'editor.suggest.preview': {
type: 'boolean',
default: defaults.preview,
description: nls.localize(98, null)
},
'editor.suggest.previewMode': {
type: 'string',
enum: ['prefix', 'subword', 'subwordSmart'],
enumDescriptions: [
nls.localize(99, null),
nls.localize(100, null),
nls.localize(101, null),
],
default: defaults.previewMode,
description: nls.localize(102, null)
},
'editor.suggest.showInlineDetails': {
type: 'boolean',
default: defaults.showInlineDetails,
description: nls.localize(103, null)
},
'editor.suggest.maxVisibleSuggestions': {
type: 'number',
deprecationMessage: nls.localize(104, null),
},
'editor.suggest.filteredTypes': {
type: 'object',
deprecationMessage: nls.localize(105, null)
},
'editor.suggest.showMethods': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(106, null)
},
'editor.suggest.showFunctions': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(107, null)
},
'editor.suggest.showConstructors': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(108, null)
},
'editor.suggest.showDeprecated': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(109, null)
},
'editor.suggest.showFields': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(110, null)
},
'editor.suggest.showVariables': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(111, null)
},
'editor.suggest.showClasses': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(112, null)
},
'editor.suggest.showStructs': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(113, null)
},
'editor.suggest.showInterfaces': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(114, null)
},
'editor.suggest.showModules': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(115, null)
},
'editor.suggest.showProperties': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(116, null)
},
'editor.suggest.showEvents': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(117, null)
},
'editor.suggest.showOperators': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(118, null)
},
'editor.suggest.showUnits': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(119, null)
},
'editor.suggest.showValues': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(120, null)
},
'editor.suggest.showConstants': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(121, null)
},
'editor.suggest.showEnums': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(122, null)
},
'editor.suggest.showEnumMembers': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(123, null)
},
'editor.suggest.showKeywords': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(124, null)
},
'editor.suggest.showWords': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(125, null)
},
'editor.suggest.showColors': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(126, null)
},
'editor.suggest.showFiles': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(127, null)
},
'editor.suggest.showReferences': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(128, null)
},
'editor.suggest.showCustomcolors': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(129, null)
},
'editor.suggest.showFolders': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(130, null)
},
'editor.suggest.showTypeParameters': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(131, null)
},
'editor.suggest.showSnippets': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(132, null)
},
'editor.suggest.showUsers': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(133, null)
},
'editor.suggest.showIssues': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(134, null)
}
});
}
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),
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),
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(101 /* smartSelect */, 'smartSelect', {
selectLeadingAndTrailingWhitespace: true
}, {
'editor.smartSelect.selectLeadingAndTrailingWhitespace': {
description: nls.localize(135, null),
default: true,
type: 'boolean'
}
});
}
validate(input) {
if (!input || typeof input !== 'object') {
return this.defaultValue;
}
return {
selectLeadingAndTrailingWhitespace: boolean(input.selectLeadingAndTrailingWhitespace, this.defaultValue.selectLeadingAndTrailingWhitespace)
};
}
}
//#endregion
//#region tabFocusMode
class EditorTabFocusMode extends ComputedEditorOption {
constructor() {
super(128 /* tabFocusMode */, [79 /* readOnly */]);
}
compute(env, options, _) {
const readOnly = options.get(79 /* readOnly */);
return (readOnly ? true : env.tabFocusMode);
}
}
function _wrappingIndentFromString(wrappingIndent) {
switch (wrappingIndent) {
case 'none': return 0 /* None */;
case 'same': return 1 /* Same */;
case 'indent': return 2 /* Indent */;
case 'deepIndent': return 3 /* DeepIndent */;
}
}
class EditorWrappingInfoComputer extends ComputedEditorOption {
constructor() {
super(130 /* wrappingInfo */, [129 /* layoutInfo */]);
}
compute(env, options, _) {
const layoutInfo = options.get(129 /* layoutInfo */);
return {
isDominatedByLongLines: env.isDominatedByLongLines,
isWordWrapMinified: layoutInfo.isWordWrapMinified,
isViewportWrapping: layoutInfo.isViewportWrapping,
wrappingColumn: layoutInfo.wrappingColumn,
};
}
}
//#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, \'Droid Sans Fallback\'';
/**
* @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.EDITOR_MODEL_DEFAULTS = {
tabSize: 4,
indentSize: 4,
insertSpaces: true,
detectIndentation: true,
trimAutoWhitespace: true,
largeFileOptimizations: true
};
/**
* @internal
*/
exports.editorOptionsRegistry = [];
function register(option) {
exports.editorOptionsRegistry[option.id] = option;
return option;
}
/**
* WORKAROUND: TS emits "any" for complex editor options values (anything except string, bool, enum, etc. ends up being "any")
* @monacodtsreplace
* /accessibilitySupport, any/accessibilitySupport, AccessibilitySupport/
* /comments, any/comments, EditorCommentsOptions/
* /find, any/find, EditorFindOptions/
* /fontInfo, any/fontInfo, FontInfo/
* /gotoLocation, any/gotoLocation, GoToLocationOptions/
* /hover, any/hover, EditorHoverOptions/
* /lightbulb, any/lightbulb, EditorLightbulbOptions/
* /minimap, any/minimap, EditorMinimapOptions/
* /parameterHints, any/parameterHints, InternalParameterHintOptions/
* /quickSuggestions, any/quickSuggestions, ValidQuickSuggestionsOptions/
* /suggest, any/suggest, InternalSuggestOptions/
*/
exports.EditorOptions = {
acceptSuggestionOnCommitCharacter: register(new EditorBooleanOption(0 /* acceptSuggestionOnCommitCharacter */, 'acceptSuggestionOnCommitCharacter', true, { markdownDescription: nls.localize(136, null) })),
acceptSuggestionOnEnter: register(new EditorStringEnumOption(1 /* acceptSuggestionOnEnter */, 'acceptSuggestionOnEnter', 'on', ['on', 'smart', 'off'], {
markdownEnumDescriptions: [
'',
nls.localize(137, null),
''
],
markdownDescription: nls.localize(138, null)
})),
accessibilitySupport: register(new EditorAccessibilitySupport()),
accessibilityPageSize: register(new EditorIntOption(3 /* accessibilityPageSize */, 'accessibilityPageSize', 10, 1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, {
description: nls.localize(139, null)
})),
ariaLabel: register(new EditorStringOption(4 /* ariaLabel */, 'ariaLabel', nls.localize(140, null))),
autoClosingBrackets: register(new EditorStringEnumOption(5 /* autoClosingBrackets */, 'autoClosingBrackets', 'languageDefined', ['always', 'languageDefined', 'beforeWhitespace', 'never'], {
enumDescriptions: [
'',
nls.localize(141, null),
nls.localize(142, null),
'',
],
description: nls.localize(143, null)
})),
autoClosingDelete: register(new EditorStringEnumOption(6 /* autoClosingDelete */, 'autoClosingDelete', 'auto', ['always', 'auto', 'never'], {
enumDescriptions: [
'',
nls.localize(144, null),
'',
],
description: nls.localize(145, null)
})),
autoClosingOvertype: register(new EditorStringEnumOption(7 /* autoClosingOvertype */, 'autoClosingOvertype', 'auto', ['always', 'auto', 'never'], {
enumDescriptions: [
'',
nls.localize(146, null),
'',
],
description: nls.localize(147, null)
})),
autoClosingQuotes: register(new EditorStringEnumOption(8 /* autoClosingQuotes */, 'autoClosingQuotes', 'languageDefined', ['always', 'languageDefined', 'beforeWhitespace', 'never'], {
enumDescriptions: [
'',
nls.localize(148, null),
nls.localize(149, null),
'',
],
description: nls.localize(150, null)
})),
autoIndent: register(new EditorEnumOption(9 /* autoIndent */, 'autoIndent', 4 /* Full */, 'full', ['none', 'keep', 'brackets', 'advanced', 'full'], _autoIndentFromString, {
enumDescriptions: [
nls.localize(151, null),
nls.localize(152, null),
nls.localize(153, null),
nls.localize(154, null),
nls.localize(155, null),
],
description: nls.localize(156, null)
})),
automaticLayout: register(new EditorBooleanOption(10 /* automaticLayout */, 'automaticLayout', false)),
autoSurround: register(new EditorStringEnumOption(11 /* autoSurround */, 'autoSurround', 'languageDefined', ['languageDefined', 'quotes', 'brackets', 'never'], {
enumDescriptions: [
nls.localize(157, null),
nls.localize(158, null),
nls.localize(159, null),
''
],
description: nls.localize(160, null)
})),
stickyTabStops: register(new EditorBooleanOption(103 /* stickyTabStops */, 'stickyTabStops', false, { description: nls.localize(161, null) })),
codeLens: register(new EditorBooleanOption(12 /* codeLens */, 'codeLens', true, { description: nls.localize(162, null) })),
codeLensFontFamily: register(new EditorStringOption(13 /* codeLensFontFamily */, 'codeLensFontFamily', '', { description: nls.localize(163, null) })),
codeLensFontSize: register(new EditorIntOption(14 /* codeLensFontSize */, 'codeLensFontSize', 0, 0, 100, {
type: 'number',
default: 0,
minimum: 0,
maximum: 100,
markdownDescription: nls.localize(164, null)
})),
colorDecorators: register(new EditorBooleanOption(15 /* colorDecorators */, 'colorDecorators', true, { description: nls.localize(165, null) })),
columnSelection: register(new EditorBooleanOption(16 /* columnSelection */, 'columnSelection', false, { description: nls.localize(166, null) })),
comments: register(new EditorComments()),
contextmenu: register(new EditorBooleanOption(18 /* contextmenu */, 'contextmenu', true)),
copyWithSyntaxHighlighting: register(new EditorBooleanOption(19 /* copyWithSyntaxHighlighting */, 'copyWithSyntaxHighlighting', true, { description: nls.localize(167, null) })),
cursorBlinking: register(new EditorEnumOption(20 /* cursorBlinking */, 'cursorBlinking', 1 /* Blink */, 'blink', ['blink', 'smooth', 'phase', 'expand', 'solid'], _cursorBlinkingStyleFromString, { description: nls.localize(168, null) })),
cursorSmoothCaretAnimation: register(new EditorBooleanOption(21 /* cursorSmoothCaretAnimation */, 'cursorSmoothCaretAnimation', false, { description: nls.localize(169, null) })),
cursorStyle: register(new EditorEnumOption(22 /* cursorStyle */, 'cursorStyle', TextEditorCursorStyle.Line, 'line', ['line', 'block', 'underline', 'line-thin', 'block-outline', 'underline-thin'], _cursorStyleFromString, { description: nls.localize(170, null) })),
cursorSurroundingLines: register(new EditorIntOption(23 /* cursorSurroundingLines */, 'cursorSurroundingLines', 0, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(171, null) })),
cursorSurroundingLinesStyle: register(new EditorStringEnumOption(24 /* cursorSurroundingLinesStyle */, 'cursorSurroundingLinesStyle', 'default', ['default', 'all'], {
enumDescriptions: [
nls.localize(172, null),
nls.localize(173, null)
],
description: nls.localize(174, null)
})),
cursorWidth: register(new EditorIntOption(25 /* cursorWidth */, 'cursorWidth', 0, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { markdownDescription: nls.localize(175, null) })),
disableLayerHinting: register(new EditorBooleanOption(26 /* disableLayerHinting */, 'disableLayerHinting', false)),
disableMonospaceOptimizations: register(new EditorBooleanOption(27 /* disableMonospaceOptimizations */, 'disableMonospaceOptimizations', false)),
domReadOnly: register(new EditorBooleanOption(28 /* domReadOnly */, 'domReadOnly', false)),
dragAndDrop: register(new EditorBooleanOption(29 /* dragAndDrop */, 'dragAndDrop', true, { description: nls.localize(176, null) })),
emptySelectionClipboard: register(new EditorEmptySelectionClipboard()),
extraEditorClassName: register(new EditorStringOption(31 /* extraEditorClassName */, 'extraEditorClassName', '')),
fastScrollSensitivity: register(new EditorFloatOption(32 /* fastScrollSensitivity */, 'fastScrollSensitivity', 5, x => (x <= 0 ? 5 : x), { markdownDescription: nls.localize(177, null) })),
find: register(new EditorFind()),
fixedOverflowWidgets: register(new EditorBooleanOption(34 /* fixedOverflowWidgets */, 'fixedOverflowWidgets', false)),
folding: register(new EditorBooleanOption(35 /* folding */, 'folding', true, { description: nls.localize(178, null) })),
foldingStrategy: register(new EditorStringEnumOption(36 /* foldingStrategy */, 'foldingStrategy', 'auto', ['auto', 'indentation'], {
enumDescriptions: [
nls.localize(179, null),
nls.localize(180, null),
],
description: nls.localize(181, null)
})),
foldingHighlight: register(new EditorBooleanOption(37 /* foldingHighlight */, 'foldingHighlight', true, { description: nls.localize(182, null) })),
foldingImportsByDefault: register(new EditorBooleanOption(38 /* foldingImportsByDefault */, 'foldingImportsByDefault', false, { description: nls.localize(183, null) })),
unfoldOnClickAfterEndOfLine: register(new EditorBooleanOption(39 /* unfoldOnClickAfterEndOfLine */, 'unfoldOnClickAfterEndOfLine', false, { description: nls.localize(184, null) })),
fontFamily: register(new EditorStringOption(40 /* fontFamily */, 'fontFamily', exports.EDITOR_FONT_DEFAULTS.fontFamily, { description: nls.localize(185, null) })),
fontInfo: register(new EditorFontInfo()),
fontLigatures2: register(new EditorFontLigatures()),
fontSize: register(new EditorFontSize()),
fontWeight: register(new EditorFontWeight()),
formatOnPaste: register(new EditorBooleanOption(45 /* formatOnPaste */, 'formatOnPaste', false, { description: nls.localize(186, null) })),
formatOnType: register(new EditorBooleanOption(46 /* formatOnType */, 'formatOnType', false, { description: nls.localize(187, null) })),
glyphMargin: register(new EditorBooleanOption(47 /* glyphMargin */, 'glyphMargin', true, { description: nls.localize(188, null) })),
gotoLocation: register(new EditorGoToLocation()),
hideCursorInOverviewRuler: register(new EditorBooleanOption(49 /* hideCursorInOverviewRuler */, 'hideCursorInOverviewRuler', false, { description: nls.localize(189, null) })),
highlightActiveIndentGuide: register(new EditorBooleanOption(50 /* highlightActiveIndentGuide */, 'highlightActiveIndentGuide', true, { description: nls.localize(190, null) })),
hover: register(new EditorHover()),
inDiffEditor: register(new EditorBooleanOption(52 /* inDiffEditor */, 'inDiffEditor', false)),
letterSpacing: register(new EditorFloatOption(54 /* letterSpacing */, 'letterSpacing', exports.EDITOR_FONT_DEFAULTS.letterSpacing, x => EditorFloatOption.clamp(x, -5, 20), { description: nls.localize(191, null) })),
lightbulb: register(new EditorLightbulb()),
lineDecorationsWidth: register(new SimpleEditorOption(56 /* lineDecorationsWidth */, 'lineDecorationsWidth', 10)),
lineHeight: register(new EditorLineHeight()),
lineNumbers: register(new EditorRenderLineNumbersOption()),
lineNumbersMinChars: register(new EditorIntOption(59 /* lineNumbersMinChars */, 'lineNumbersMinChars', 5, 1, 300)),
linkedEditing: register(new EditorBooleanOption(60 /* linkedEditing */, 'linkedEditing', false, { description: nls.localize(192, null) })),
links: register(new EditorBooleanOption(61 /* links */, 'links', true, { description: nls.localize(193, null) })),
matchBrackets: register(new EditorStringEnumOption(62 /* matchBrackets */, 'matchBrackets', 'always', ['always', 'near', 'never'], { description: nls.localize(194, null) })),
minimap: register(new EditorMinimap()),
mouseStyle: register(new EditorStringEnumOption(64 /* mouseStyle */, 'mouseStyle', 'text', ['text', 'default', 'copy'])),
mouseWheelScrollSensitivity: register(new EditorFloatOption(65 /* mouseWheelScrollSensitivity */, 'mouseWheelScrollSensitivity', 1, x => (x === 0 ? 1 : x), { markdownDescription: nls.localize(195, null) })),
mouseWheelZoom: register(new EditorBooleanOption(66 /* mouseWheelZoom */, 'mouseWheelZoom', false, { markdownDescription: nls.localize(196, null) })),
multiCursorMergeOverlapping: register(new EditorBooleanOption(67 /* multiCursorMergeOverlapping */, 'multiCursorMergeOverlapping', true, { description: nls.localize(197, null) })),
multiCursorModifier: register(new EditorEnumOption(68 /* multiCursorModifier */, 'multiCursorModifier', 'altKey', 'alt', ['ctrlCmd', 'alt'], _multiCursorModifierFromString, {
markdownEnumDescriptions: [
nls.localize(198, null),
nls.localize(199, null)
],
markdownDescription: nls.localize(200, null)
})),
multiCursorPaste: register(new EditorStringEnumOption(69 /* multiCursorPaste */, 'multiCursorPaste', 'spread', ['spread', 'full'], {
markdownEnumDescriptions: [
nls.localize(201, null),
nls.localize(202, null)
],
markdownDescription: nls.localize(203, null)
})),
occurrencesHighlight: register(new EditorBooleanOption(70 /* occurrencesHighlight */, 'occurrencesHighlight', true, { description: nls.localize(204, null) })),
overviewRulerBorder: register(new EditorBooleanOption(71 /* overviewRulerBorder */, 'overviewRulerBorder', true, { description: nls.localize(205, null) })),
overviewRulerLanes: register(new EditorIntOption(72 /* overviewRulerLanes */, 'overviewRulerLanes', 3, 0, 3)),
padding: register(new EditorPadding()),
parameterHints: register(new EditorParameterHints()),
peekWidgetDefaultFocus: register(new EditorStringEnumOption(75 /* peekWidgetDefaultFocus */, 'peekWidgetDefaultFocus', 'tree', ['tree', 'editor'], {
enumDescriptions: [
nls.localize(206, null),
nls.localize(207, null)
],
description: nls.localize(208, null)
})),
definitionLinkOpensInPeek: register(new EditorBooleanOption(76 /* definitionLinkOpensInPeek */, 'definitionLinkOpensInPeek', false, { description: nls.localize(209, null) })),
quickSuggestions: register(new EditorQuickSuggestions()),
quickSuggestionsDelay: register(new EditorIntOption(78 /* quickSuggestionsDelay */, 'quickSuggestionsDelay', 10, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(210, null) })),
readOnly: register(new EditorBooleanOption(79 /* readOnly */, 'readOnly', false)),
renameOnType: register(new EditorBooleanOption(80 /* renameOnType */, 'renameOnType', false, { description: nls.localize(211, null), markdownDeprecationMessage: nls.localize(212, null) })),
renderControlCharacters: register(new EditorBooleanOption(81 /* renderControlCharacters */, 'renderControlCharacters', false, { description: nls.localize(213, null) })),
renderIndentGuides: register(new EditorBooleanOption(82 /* renderIndentGuides */, 'renderIndentGuides', true, { description: nls.localize(214, null) })),
renderFinalNewline: register(new EditorBooleanOption(83 /* renderFinalNewline */, 'renderFinalNewline', true, { description: nls.localize(215, null) })),
renderLineHighlight: register(new EditorStringEnumOption(84 /* renderLineHighlight */, 'renderLineHighlight', 'line', ['none', 'gutter', 'line', 'all'], {
enumDescriptions: [
'',
'',
'',
nls.localize(216, null),
],
description: nls.localize(217, null)
})),
renderLineHighlightOnlyWhenFocus: register(new EditorBooleanOption(85 /* renderLineHighlightOnlyWhenFocus */, 'renderLineHighlightOnlyWhenFocus', false, { description: nls.localize(218, null) })),
renderValidationDecorations: register(new EditorStringEnumOption(86 /* renderValidationDecorations */, 'renderValidationDecorations', 'editable', ['editable', 'on', 'off'])),
renderWhitespace: register(new EditorStringEnumOption(87 /* renderWhitespace */, 'renderWhitespace', 'selection', ['none', 'boundary', 'selection', 'trailing', 'all'], {
enumDescriptions: [
'',
nls.localize(219, null),
nls.localize(220, null),
nls.localize(221, null),
''
],
description: nls.localize(222, null)
})),
revealHorizontalRightPadding: register(new EditorIntOption(88 /* revealHorizontalRightPadding */, 'revealHorizontalRightPadding', 30, 0, 1000)),
roundedSelection: register(new EditorBooleanOption(89 /* roundedSelection */, 'roundedSelection', true, { description: nls.localize(223, null) })),
rulers: register(new EditorRulers()),
scrollbar: register(new EditorScrollbar()),
scrollBeyondLastColumn: register(new EditorIntOption(92 /* scrollBeyondLastColumn */, 'scrollBeyondLastColumn', 5, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(224, null) })),
scrollBeyondLastLine: register(new EditorBooleanOption(93 /* scrollBeyondLastLine */, 'scrollBeyondLastLine', true, { description: nls.localize(225, null) })),
scrollPredominantAxis: register(new EditorBooleanOption(94 /* scrollPredominantAxis */, 'scrollPredominantAxis', true, { description: nls.localize(226, null) })),
selectionClipboard: register(new EditorBooleanOption(95 /* selectionClipboard */, 'selectionClipboard', true, {
description: nls.localize(227, null),
included: platform.isLinux
})),
selectionHighlight: register(new EditorBooleanOption(96 /* selectionHighlight */, 'selectionHighlight', true, { description: nls.localize(228, null) })),
selectOnLineNumbers: register(new EditorBooleanOption(97 /* selectOnLineNumbers */, 'selectOnLineNumbers', true)),
showFoldingControls: register(new EditorStringEnumOption(98 /* showFoldingControls */, 'showFoldingControls', 'mouseover', ['always', 'mouseover'], {
enumDescriptions: [
nls.localize(229, null),
nls.localize(230, null),
],
description: nls.localize(231, null)
})),
showUnused: register(new EditorBooleanOption(99 /* showUnused */, 'showUnused', true, { description: nls.localize(232, null) })),
showDeprecated: register(new EditorBooleanOption(124 /* showDeprecated */, 'showDeprecated', true, { description: nls.localize(233, null) })),
inlayHints: register(new EditorInlayHints()),
snippetSuggestions: register(new EditorStringEnumOption(100 /* snippetSuggestions */, 'snippetSuggestions', 'inline', ['top', 'bottom', 'inline', 'none'], {
enumDescriptions: [
nls.localize(234, null),
nls.localize(235, null),
nls.localize(236, null),
nls.localize(237, null),
],
description: nls.localize(238, null)
})),
smartSelect: register(new SmartSelect()),
smoothScrolling: register(new EditorBooleanOption(102 /* smoothScrolling */, 'smoothScrolling', false, { description: nls.localize(239, null) })),
stopRenderingLineAfter: register(new EditorIntOption(104 /* stopRenderingLineAfter */, 'stopRenderingLineAfter', 10000, -1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */)),
suggest: register(new EditorSuggest()),
inlineSuggest: register(new InlineEditorSuggest()),
suggestFontSize: register(new EditorIntOption(106 /* suggestFontSize */, 'suggestFontSize', 0, 0, 1000, { markdownDescription: nls.localize(240, null) })),
suggestLineHeight: register(new EditorIntOption(107 /* suggestLineHeight */, 'suggestLineHeight', 0, 0, 1000, { markdownDescription: nls.localize(241, null) })),
suggestOnTriggerCharacters: register(new EditorBooleanOption(108 /* suggestOnTriggerCharacters */, 'suggestOnTriggerCharacters', true, { description: nls.localize(242, null) })),
suggestSelection: register(new EditorStringEnumOption(109 /* suggestSelection */, 'suggestSelection', 'recentlyUsed', ['first', 'recentlyUsed', 'recentlyUsedByPrefix'], {
markdownEnumDescriptions: [
nls.localize(243, null),
nls.localize(244, null),
nls.localize(245, null),
],
description: nls.localize(246, null)
})),
tabCompletion: register(new EditorStringEnumOption(110 /* tabCompletion */, 'tabCompletion', 'off', ['on', 'off', 'onlySnippets'], {
enumDescriptions: [
nls.localize(247, null),
nls.localize(248, null),
nls.localize(249, null),
],
description: nls.localize(250, null)
})),
tabIndex: register(new EditorIntOption(111 /* tabIndex */, 'tabIndex', 0, -1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */)),
unusualLineTerminators: register(new EditorStringEnumOption(112 /* unusualLineTerminators */, 'unusualLineTerminators', 'prompt', ['auto', 'off', 'prompt'], {
enumDescriptions: [
nls.localize(251, null),
nls.localize(252, null),
nls.localize(253, null),
],
description: nls.localize(254, null)
})),
useShadowDOM: register(new EditorBooleanOption(113 /* useShadowDOM */, 'useShadowDOM', true)),
useTabStops: register(new EditorBooleanOption(114 /* useTabStops */, 'useTabStops', true, { description: nls.localize(255, null) })),
wordSeparators: register(new EditorStringOption(115 /* wordSeparators */, 'wordSeparators', wordHelper_1.USUAL_WORD_SEPARATORS, { description: nls.localize(256, null) })),
wordWrap: register(new EditorStringEnumOption(116 /* wordWrap */, 'wordWrap', 'off', ['off', 'on', 'wordWrapColumn', 'bounded'], {
markdownEnumDescriptions: [
nls.localize(257, null),
nls.localize(258, null),
nls.localize(259, null),
nls.localize(260, null),
],
description: nls.localize(261, null)
})),
wordWrapBreakAfterCharacters: register(new EditorStringOption(117 /* wordWrapBreakAfterCharacters */, 'wordWrapBreakAfterCharacters', ' \t})]?|/&.,;¢°′″‰℃、。。、¢,.:;?!%・・ゝゞヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻ァィゥェォャュョッー”〉》」』】〕)]}」')),
wordWrapBreakBeforeCharacters: register(new EditorStringOption(118 /* wordWrapBreakBeforeCharacters */, 'wordWrapBreakBeforeCharacters', '([{‘“〈《「『【〔([{「£¥$£¥+')),
wordWrapColumn: register(new EditorIntOption(119 /* wordWrapColumn */, 'wordWrapColumn', 80, 1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, {
markdownDescription: nls.localize(262, null)
})),
wordWrapOverride1: register(new EditorStringEnumOption(120 /* wordWrapOverride1 */, 'wordWrapOverride1', 'inherit', ['off', 'on', 'inherit'])),
wordWrapOverride2: register(new EditorStringEnumOption(121 /* wordWrapOverride2 */, 'wordWrapOverride2', 'inherit', ['off', 'on', 'inherit'])),
wrappingIndent: register(new EditorEnumOption(122 /* wrappingIndent */, 'wrappingIndent', 1 /* Same */, 'same', ['none', 'same', 'indent', 'deepIndent'], _wrappingIndentFromString, {
enumDescriptions: [
nls.localize(263, null),
nls.localize(264, null),
nls.localize(265, null),
nls.localize(266, null),
],
description: nls.localize(267, null),
})),
wrappingStrategy: register(new EditorStringEnumOption(123 /* wrappingStrategy */, 'wrappingStrategy', 'simple', ['simple', 'advanced'], {
enumDescriptions: [
nls.localize(268, null),
nls.localize(269, null)
],
description: nls.localize(270, null)
})),
// Leave these at the end (because they have dependencies!)
editorClassName: register(new EditorClassName()),
pixelRatio: register(new EditorPixelRatio()),
tabFocusMode: register(new EditorTabFocusMode()),
layoutInfo: register(new EditorLayoutInfoComputer()),
wrappingInfo: register(new EditorWrappingInfoComputer())
};
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[465/*vs/editor/common/viewModel/viewModelDecorations*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,62/*vs/editor/common/viewModel/viewModel*/,35/*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;
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 /* Left */);
const end = this._coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.endLineNumber, this.model.getLineMaxColumn(modelRange.endLineNumber)), 1 /* 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 /* Right */);
}
r = new viewModel_1.ViewModelDecoration(viewRange, options);
this._decorationsCache[id] = r;
}
return r;
}
getDecorationsViewportData(viewRange) {
let cacheIsValid = (this._cachedModelDecorationsResolver !== null);
cacheIsValid = cacheIsValid && (viewRange.equalsRange(this._cachedModelDecorationsResolverViewRange));
if (!cacheIsValid) {
this._cachedModelDecorationsResolver = this._getDecorationsViewportData(viewRange);
this._cachedModelDecorationsResolverViewRange = viewRange;
}
return this._cachedModelDecorationsResolver;
}
_getDecorationsViewportData(viewportRange) {
const modelDecorations = this._linesCollection.getDecorationsInRange(viewportRange, this.editorId, (0, editorOptions_1.filterValidationDecorations)(this.configuration.options));
const startLineNumber = viewportRange.startLineNumber;
const endLineNumber = viewportRange.endLineNumber;
let decorationsInViewport = [], decorationsInViewportLen = 0;
let inlineDecorations = [];
for (let j = startLineNumber; j <= endLineNumber; j++) {
inlineDecorations[j - startLineNumber] = [];
}
for (let i = 0, len = modelDecorations.length; i < len; i++) {
let modelDecoration = modelDecorations[i];
let decorationOptions = modelDecoration.options;
let viewModelDecoration = this._getOrCreateViewModelDecoration(modelDecoration);
let viewRange = viewModelDecoration.range;
decorationsInViewport[decorationsInViewportLen++] = viewModelDecoration;
if (decorationOptions.inlineClassName) {
let inlineDecoration = new viewModel_1.InlineDecoration(viewRange, decorationOptions.inlineClassName, decorationOptions.inlineClassNameAffectsLetterSpacing ? 3 /* RegularAffectingLetterSpacing */ : 0 /* Regular */);
let intersectedStartLineNumber = Math.max(startLineNumber, viewRange.startLineNumber);
let 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) {
let inlineDecoration = new viewModel_1.InlineDecoration(new range_1.Range(viewRange.startLineNumber, viewRange.startColumn, viewRange.startLineNumber, viewRange.startColumn), decorationOptions.beforeContentClassName, 1 /* Before */);
inlineDecorations[viewRange.startLineNumber - startLineNumber].push(inlineDecoration);
}
}
if (decorationOptions.afterContentClassName) {
if (startLineNumber <= viewRange.endLineNumber && viewRange.endLineNumber <= endLineNumber) {
let inlineDecoration = new viewModel_1.InlineDecoration(new range_1.Range(viewRange.endLineNumber, viewRange.endColumn, viewRange.endLineNumber, viewRange.endColumn), decorationOptions.afterContentClassName, 2 /* After */);
inlineDecorations[viewRange.endLineNumber - startLineNumber].push(inlineDecoration);
}
}
}
return {
decorations: decorationsInViewport,
inlineDecorations: inlineDecorations
};
}
}
exports.ViewModelDecorations = ViewModelDecorations;
});
define(__m[466/*vs/nls!vs/editor/common/editorContextKeys*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/editorContextKeys", data); });
define(__m[467/*vs/nls!vs/editor/common/model/editStack*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/model/editStack", 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[239/*vs/editor/common/model/editStack*/], __M([0/*require*/,1/*exports*/,467/*vs/nls!vs/editor/common/model/editStack*/,12/*vs/base/common/errors*/,21/*vs/editor/common/core/selection*/,24/*vs/base/common/uri*/,220/*vs/editor/common/model/textChange*/,103/*vs/base/common/buffer*/,43/*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.isEditStackElement = exports.MultiModelEditStackElement = exports.SingleModelEditStackElement = exports.SingleModelEditStackData = void 0;
function uriGetComparisonKey(resource) {
return resource.toString();
}
class SingleModelEditStackData {
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;
}
static create(model, beforeCursorState) {
const alternativeVersionId = model.getAlternativeVersionId();
const eol = getModelEOL(model);
return new SingleModelEditStackData(alternativeVersionId, alternativeVersionId, eol, eol, beforeCursorState, beforeCursorState, []);
}
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 {
constructor(model, beforeCursorState) {
this.model = model;
this._data = SingleModelEditStackData.create(model, beforeCursorState);
}
get type() {
return 0 /* Resource */;
}
get resource() {
if (uri_1.URI.isUri(this.model)) {
return this.model;
}
return this.model.uri;
}
get label() {
return nls.localize(0, null);
}
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 {
constructor(label, editStackElements) {
this.type = 1 /* Workspace */;
this.label = label;
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;
}
get resources() {
return this._editStackElementsArr.map(editStackElement => editStackElement.resource);
}
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() {
let 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 /* LF */;
}
else {
return 1 /* CRLF */;
}
}
function isEditStackElement(element) {
if (!element) {
return false;
}
return ((element instanceof SingleModelEditStackElement) || (element instanceof MultiModelEditStackElement));
}
exports.isEditStackElement = isEditStackElement;
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) {
const lastElement = this._undoRedoService.getLastElement(this._model.uri);
if (isEditStackElement(lastElement) && lastElement.canAppend(this._model)) {
return lastElement;
}
const newElement = new SingleModelEditStackElement(this._model, beforeCursorState);
this._undoRedoService.pushElement(newElement);
return newElement;
}
pushEOL(eol) {
const editStackElement = this._getOrCreateEditStackElement(null);
this._model.setEOL(eol);
editStackElement.append(this._model, [], getModelEOL(this._model), this._model.getAlternativeVersionId(), null);
}
pushEditOperation(beforeCursorState, editOperations, cursorStateComputer) {
const editStackElement = this._getOrCreateEditStackElement(beforeCursorState);
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;
});
define(__m[468/*vs/nls!vs/editor/common/modes/modesRegistry*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/modes/modesRegistry", data); });
define(__m[469/*vs/nls!vs/editor/common/standaloneStrings*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/standaloneStrings", 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[63/*vs/editor/common/standaloneStrings*/], __M([0/*require*/,1/*exports*/,469/*vs/nls!vs/editor/common/standaloneStrings*/]), function (require, exports, nls) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleServicesNLS = exports.ToggleHighContrastNLS = exports.StandaloneCodeEditorNLS = exports.QuickOutlineNLS = exports.QuickCommandNLS = exports.QuickHelpNLS = exports.GoToLineNLS = exports.InspectTokensNLS = exports.AccessibilityHelpNLS = void 0;
var AccessibilityHelpNLS;
(function (AccessibilityHelpNLS) {
AccessibilityHelpNLS.noSelection = nls.localize(0, null);
AccessibilityHelpNLS.singleSelectionRange = nls.localize(1, null);
AccessibilityHelpNLS.singleSelection = nls.localize(2, null);
AccessibilityHelpNLS.multiSelectionRange = nls.localize(3, null);
AccessibilityHelpNLS.multiSelection = nls.localize(4, null);
AccessibilityHelpNLS.emergencyConfOn = nls.localize(5, null);
AccessibilityHelpNLS.openingDocs = nls.localize(6, null);
AccessibilityHelpNLS.readonlyDiffEditor = nls.localize(7, null);
AccessibilityHelpNLS.editableDiffEditor = nls.localize(8, null);
AccessibilityHelpNLS.readonlyEditor = nls.localize(9, null);
AccessibilityHelpNLS.editableEditor = nls.localize(10, null);
AccessibilityHelpNLS.changeConfigToOnMac = nls.localize(11, null);
AccessibilityHelpNLS.changeConfigToOnWinLinux = nls.localize(12, null);
AccessibilityHelpNLS.auto_on = nls.localize(13, null);
AccessibilityHelpNLS.auto_off = nls.localize(14, null);
AccessibilityHelpNLS.tabFocusModeOnMsg = nls.localize(15, null);
AccessibilityHelpNLS.tabFocusModeOnMsgNoKb = nls.localize(16, null);
AccessibilityHelpNLS.tabFocusModeOffMsg = nls.localize(17, null);
AccessibilityHelpNLS.tabFocusModeOffMsgNoKb = nls.localize(18, null);
AccessibilityHelpNLS.openDocMac = nls.localize(19, null);
AccessibilityHelpNLS.openDocWinLinux = nls.localize(20, null);
AccessibilityHelpNLS.outroMsg = nls.localize(21, null);
AccessibilityHelpNLS.showAccessibilityHelpAction = nls.localize(22, null);
})(AccessibilityHelpNLS = exports.AccessibilityHelpNLS || (exports.AccessibilityHelpNLS = {}));
var InspectTokensNLS;
(function (InspectTokensNLS) {
InspectTokensNLS.inspectTokensAction = nls.localize(23, null);
})(InspectTokensNLS = exports.InspectTokensNLS || (exports.InspectTokensNLS = {}));
var GoToLineNLS;
(function (GoToLineNLS) {
GoToLineNLS.gotoLineActionLabel = nls.localize(24, null);
})(GoToLineNLS = exports.GoToLineNLS || (exports.GoToLineNLS = {}));
var QuickHelpNLS;
(function (QuickHelpNLS) {
QuickHelpNLS.helpQuickAccessActionLabel = nls.localize(25, null);
})(QuickHelpNLS = exports.QuickHelpNLS || (exports.QuickHelpNLS = {}));
var QuickCommandNLS;
(function (QuickCommandNLS) {
QuickCommandNLS.quickCommandActionLabel = nls.localize(26, null);
QuickCommandNLS.quickCommandHelp = nls.localize(27, null);
})(QuickCommandNLS = exports.QuickCommandNLS || (exports.QuickCommandNLS = {}));
var QuickOutlineNLS;
(function (QuickOutlineNLS) {
QuickOutlineNLS.quickOutlineActionLabel = nls.localize(28, null);
QuickOutlineNLS.quickOutlineByCategoryActionLabel = nls.localize(29, null);
})(QuickOutlineNLS = exports.QuickOutlineNLS || (exports.QuickOutlineNLS = {}));
var StandaloneCodeEditorNLS;
(function (StandaloneCodeEditorNLS) {
StandaloneCodeEditorNLS.editorViewAccessibleLabel = nls.localize(30, null);
StandaloneCodeEditorNLS.accessibilityHelpMessage = nls.localize(31, null);
})(StandaloneCodeEditorNLS = exports.StandaloneCodeEditorNLS || (exports.StandaloneCodeEditorNLS = {}));
var ToggleHighContrastNLS;
(function (ToggleHighContrastNLS) {
ToggleHighContrastNLS.toggleHighContrast = nls.localize(32, null);
})(ToggleHighContrastNLS = exports.ToggleHighContrastNLS || (exports.ToggleHighContrastNLS = {}));
var SimpleServicesNLS;
(function (SimpleServicesNLS) {
SimpleServicesNLS.bulkEditServiceSummary = nls.localize(33, null);
})(SimpleServicesNLS = exports.SimpleServicesNLS || (exports.SimpleServicesNLS = {}));
});
define(__m[470/*vs/nls!vs/editor/common/view/editorColorRegistry*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/view/editorColorRegistry", data); });
define(__m[471/*vs/nls!vs/editor/contrib/anchorSelect/anchorSelect*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/anchorSelect/anchorSelect", data); });
define(__m[472/*vs/nls!vs/editor/contrib/bracketMatching/bracketMatching*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/bracketMatching/bracketMatching", data); });
define(__m[473/*vs/nls!vs/editor/contrib/caretOperations/caretOperations*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/caretOperations/caretOperations", data); });
define(__m[474/*vs/nls!vs/editor/contrib/caretOperations/transpose*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/caretOperations/transpose", data); });
define(__m[475/*vs/nls!vs/editor/contrib/clipboard/clipboard*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/clipboard/clipboard", data); });
define(__m[476/*vs/nls!vs/editor/contrib/codeAction/codeActionCommands*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/codeAction/codeActionCommands", data); });
define(__m[477/*vs/nls!vs/editor/contrib/codeAction/lightBulbWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/codeAction/lightBulbWidget", data); });
define(__m[478/*vs/nls!vs/editor/contrib/codelens/codelensController*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/codelens/codelensController", data); });
define(__m[479/*vs/nls!vs/editor/contrib/comment/comment*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/comment/comment", data); });
define(__m[480/*vs/nls!vs/editor/contrib/contextmenu/contextmenu*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/contextmenu/contextmenu", data); });
define(__m[481/*vs/nls!vs/editor/contrib/cursorUndo/cursorUndo*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/cursorUndo/cursorUndo", data); });
define(__m[482/*vs/nls!vs/editor/contrib/find/findController*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/find/findController", data); });
define(__m[483/*vs/nls!vs/editor/contrib/find/findWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/find/findWidget", data); });
define(__m[484/*vs/nls!vs/editor/contrib/folding/folding*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/folding/folding", data); });
define(__m[485/*vs/nls!vs/editor/contrib/folding/foldingDecorations*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/folding/foldingDecorations", data); });
define(__m[486/*vs/nls!vs/editor/contrib/fontZoom/fontZoom*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/fontZoom/fontZoom", data); });
define(__m[487/*vs/nls!vs/editor/contrib/format/format*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/format/format", data); });
define(__m[488/*vs/nls!vs/editor/contrib/format/formatActions*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/format/formatActions", data); });
define(__m[489/*vs/nls!vs/editor/contrib/gotoError/gotoError*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoError/gotoError", data); });
define(__m[490/*vs/nls!vs/editor/contrib/gotoError/gotoErrorWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoError/gotoErrorWidget", data); });
define(__m[491/*vs/nls!vs/editor/contrib/gotoSymbol/goToCommands*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/goToCommands", data); });
define(__m[492/*vs/nls!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition", data); });
define(__m[493/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesController*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/peek/referencesController", data); });
define(__m[494/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesTree*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/peek/referencesTree", data); });
define(__m[495/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/peek/referencesWidget", data); });
define(__m[496/*vs/nls!vs/editor/contrib/gotoSymbol/referencesModel*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/referencesModel", 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[118/*vs/editor/contrib/gotoSymbol/referencesModel*/], __M([0/*require*/,1/*exports*/,496/*vs/nls!vs/editor/contrib/gotoSymbol/referencesModel*/,6/*vs/base/common/event*/,43/*vs/base/common/resources*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,125/*vs/base/common/idGenerator*/,3/*vs/editor/common/core/range*/,49/*vs/base/common/map*/,12/*vs/base/common/errors*/]), function (require, exports, nls_1, event_1, resources_1, lifecycle_1, strings, idGenerator_1, range_1, map_1, errors_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() {
var _a, _b;
return (_b = (_a = this._range) !== null && _a !== void 0 ? _a : this.link.targetSelectionRange) !== null && _b !== void 0 ? _b : this.link.range;
}
set range(value) {
this._range = value;
this._rangeCallback(this);
}
get ariaMessage() {
var _a;
const preview = (_a = this.parent.getPreview(this)) === null || _a === void 0 ? void 0 : _a.preview(this.range);
if (!preview) {
return (0, nls_1.localize)(0, null, (0, resources_1.basename)(this.uri), this.range.startLineNumber, this.range.startColumn);
}
else {
return (0, nls_1.localize)(1, null, (0, resources_1.basename)(this.uri), this.range.startLineNumber, this.range.startColumn, preview.value);
}
}
}
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 /* 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)(2, null, (0, resources_1.basename)(this.uri), this.uri.fsPath);
}
else {
return (0, nls_1.localize)(3, null, len, (0, resources_1.basename)(this.uri), this.uri.fsPath);
}
}
resolve(textModelResolverService) {
return __awaiter(this, void 0, void 0, function* () {
if (this._previews.size !== 0) {
return this;
}
for (let child of this.children) {
if (this._previews.has(child.uri)) {
continue;
}
try {
const ref = yield 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 (let 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)(4, null);
}
else if (this.references.length === 1) {
return (0, nls_1.localize)(5, null, this.references[0].uri.fsPath);
}
else if (this.groups.length === 1) {
return (0, nls_1.localize)(6, null, this.references.length, this.groups[0].uri.fsPath);
}
else {
return (0, nls_1.localize)(7, null, this.references.length, this.groups.length);
}
}
nextOrPreviousReference(reference, next) {
let { parent } = reference;
let idx = parent.children.indexOf(reference);
let childCount = parent.children.length;
let 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;
});
define(__m[497/*vs/nls!vs/editor/contrib/gotoSymbol/symbolNavigation*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/symbolNavigation", data); });
define(__m[498/*vs/nls!vs/editor/contrib/hover/hover*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/hover", data); });
define(__m[499/*vs/nls!vs/editor/contrib/hover/markdownHoverParticipant*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/markdownHoverParticipant", data); });
define(__m[500/*vs/nls!vs/editor/contrib/hover/markerHoverParticipant*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/markerHoverParticipant", data); });
define(__m[501/*vs/nls!vs/editor/contrib/inPlaceReplace/inPlaceReplace*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/inPlaceReplace/inPlaceReplace", data); });
define(__m[502/*vs/nls!vs/editor/contrib/indentation/indentation*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/indentation/indentation", data); });
define(__m[503/*vs/nls!vs/editor/contrib/inlineCompletions/ghostTextController*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/inlineCompletions/ghostTextController", data); });
define(__m[504/*vs/nls!vs/editor/contrib/inlineCompletions/inlineCompletionsHoverParticipant*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/inlineCompletions/inlineCompletionsHoverParticipant", data); });
define(__m[505/*vs/nls!vs/editor/contrib/linesOperations/linesOperations*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/linesOperations/linesOperations", data); });
define(__m[506/*vs/nls!vs/editor/contrib/linkedEditing/linkedEditing*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/linkedEditing/linkedEditing", data); });
define(__m[507/*vs/nls!vs/editor/contrib/links/links*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/links/links", data); });
define(__m[508/*vs/nls!vs/editor/contrib/message/messageController*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/message/messageController", data); });
define(__m[509/*vs/nls!vs/editor/contrib/multicursor/multicursor*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/multicursor/multicursor", data); });
define(__m[510/*vs/nls!vs/editor/contrib/parameterHints/parameterHints*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/parameterHints/parameterHints", data); });
define(__m[511/*vs/nls!vs/editor/contrib/parameterHints/parameterHintsWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/parameterHints/parameterHintsWidget", data); });
define(__m[512/*vs/nls!vs/editor/contrib/peekView/peekView*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/peekView/peekView", data); });
define(__m[513/*vs/nls!vs/editor/contrib/quickAccess/gotoLineQuickAccess*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/quickAccess/gotoLineQuickAccess", data); });
define(__m[514/*vs/nls!vs/editor/contrib/quickAccess/gotoSymbolQuickAccess*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/quickAccess/gotoSymbolQuickAccess", data); });
define(__m[515/*vs/nls!vs/editor/contrib/rename/rename*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/rename/rename", data); });
define(__m[516/*vs/nls!vs/editor/contrib/rename/renameInputField*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/rename/renameInputField", data); });
define(__m[517/*vs/nls!vs/editor/contrib/smartSelect/smartSelect*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/smartSelect/smartSelect", data); });
define(__m[518/*vs/nls!vs/editor/contrib/snippet/snippetController2*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/snippet/snippetController2", data); });
define(__m[519/*vs/nls!vs/editor/contrib/snippet/snippetVariables*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/snippet/snippetVariables", data); });
define(__m[520/*vs/nls!vs/editor/contrib/suggest/suggest*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggest", data); });
define(__m[521/*vs/nls!vs/editor/contrib/suggest/suggestController*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestController", data); });
define(__m[522/*vs/nls!vs/editor/contrib/suggest/suggestWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestWidget", data); });
define(__m[523/*vs/nls!vs/editor/contrib/suggest/suggestWidgetDetails*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestWidgetDetails", data); });
define(__m[524/*vs/nls!vs/editor/contrib/suggest/suggestWidgetRenderer*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestWidgetRenderer", data); });
define(__m[525/*vs/nls!vs/editor/contrib/suggest/suggestWidgetStatus*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestWidgetStatus", data); });
define(__m[526/*vs/nls!vs/editor/contrib/symbolIcons/symbolIcons*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/symbolIcons/symbolIcons", data); });
define(__m[527/*vs/nls!vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode", data); });
define(__m[528/*vs/nls!vs/editor/contrib/tokenization/tokenization*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/tokenization/tokenization", data); });
define(__m[529/*vs/nls!vs/editor/contrib/unusualLineTerminators/unusualLineTerminators*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/unusualLineTerminators/unusualLineTerminators", data); });
define(__m[530/*vs/nls!vs/editor/contrib/wordHighlighter/wordHighlighter*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/wordHighlighter/wordHighlighter", data); });
define(__m[531/*vs/nls!vs/editor/contrib/wordOperations/wordOperations*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/wordOperations/wordOperations", data); });
define(__m[532/*vs/nls!vs/platform/actions/browser/menuEntryActionViewItem*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/actions/browser/menuEntryActionViewItem", data); });
define(__m[533/*vs/nls!vs/platform/configuration/common/configurationRegistry*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/configuration/common/configurationRegistry", data); });
define(__m[534/*vs/nls!vs/platform/contextkey/browser/contextKeyService*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/contextkey/browser/contextKeyService", data); });
define(__m[535/*vs/nls!vs/platform/contextkey/common/contextkeys*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/contextkey/common/contextkeys", data); });
define(__m[536/*vs/nls!vs/platform/keybinding/common/abstractKeybindingService*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/keybinding/common/abstractKeybindingService", data); });
define(__m[537/*vs/nls!vs/platform/list/browser/listService*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/list/browser/listService", data); });
define(__m[538/*vs/nls!vs/platform/markers/common/markers*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/markers/common/markers", data); });
define(__m[539/*vs/nls!vs/platform/quickinput/browser/commandsQuickAccess*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/quickinput/browser/commandsQuickAccess", data); });
define(__m[540/*vs/nls!vs/platform/quickinput/browser/helpQuickAccess*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/quickinput/browser/helpQuickAccess", data); });
define(__m[541/*vs/nls!vs/platform/theme/common/colorRegistry*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/theme/common/colorRegistry", data); });
define(__m[542/*vs/nls!vs/platform/theme/common/iconRegistry*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/theme/common/iconRegistry", data); });
define(__m[543/*vs/nls!vs/platform/undoRedo/common/undoRedoService*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/undoRedo/common/undoRedoService", 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[544/*vs/platform/clipboard/browser/clipboardService*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/]), function (require, exports, dom_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrowserClipboardService = void 0;
class BrowserClipboardService {
constructor() {
this.mapTextToType = new Map(); // unsupported in web (only in-memory)
this.findText = ''; // unsupported in web (only in-memory)
}
writeText(text, type) {
return __awaiter(this, void 0, void 0, function* () {
// With type: only in-memory is supported
if (type) {
this.mapTextToType.set(type, text);
return;
}
// Guard access to navigator.clipboard with try/catch
// as we have seen DOMExceptions in certain browsers
// due to security policies.
try {
return yield navigator.clipboard.writeText(text);
}
catch (error) {
console.error(error);
}
// Fallback to textarea and execCommand solution
const activeElement = document.activeElement;
const textArea = document.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();
document.execCommand('copy');
if (activeElement instanceof HTMLElement) {
activeElement.focus();
}
document.body.removeChild(textArea);
return;
});
}
readText(type) {
return __awaiter(this, void 0, void 0, function* () {
// 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 yield navigator.clipboard.readText();
}
catch (error) {
console.error(error);
return '';
}
});
}
readFindText() {
return __awaiter(this, void 0, void 0, function* () {
return this.findText;
});
}
writeFindText(text) {
return __awaiter(this, void 0, void 0, function* () {
this.findText = text;
});
}
}
exports.BrowserClipboardService = 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[545/*vs/platform/editor/common/editor*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EditorOpenContext = void 0;
var EditorOpenContext;
(function (EditorOpenContext) {
/**
* Default: the editor is opening via a programmatic call
* to the editor service API.
*/
EditorOpenContext[EditorOpenContext["API"] = 0] = "API";
/**
* Indicates that a user action triggered the opening, e.g.
* via mouse or keyboard use.
*/
EditorOpenContext[EditorOpenContext["USER"] = 1] = "USER";
})(EditorOpenContext = exports.EditorOpenContext || (exports.EditorOpenContext = {}));
});
define(__m[546/*vs/platform/extensions/common/extensions*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
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;
});
//#endregion
define(__m[240/*vs/platform/files/common/files*/], __M([0/*require*/,1/*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 || (exports.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[241/*vs/platform/instantiation/common/descriptors*/], __M([0/*require*/,1/*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[75/*vs/platform/instantiation/common/extensions*/], __M([0/*require*/,1/*exports*/,241/*vs/platform/instantiation/common/descriptors*/]), function (require, exports, descriptors_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSingletonServiceDescriptors = exports.registerSingleton = void 0;
const _registry = [];
function registerSingleton(id, ctorOrDescriptor, supportsDelayedInstantiation) {
if (!(ctorOrDescriptor instanceof descriptors_1.SyncDescriptor)) {
ctorOrDescriptor = new descriptors_1.SyncDescriptor(ctorOrDescriptor, [], supportsDelayedInstantiation);
}
_registry.push([id, ctorOrDescriptor]);
}
exports.registerSingleton = registerSingleton;
function getSingletonServiceDescriptors() {
return _registry;
}
exports.getSingletonServiceDescriptors = getSingletonServiceDescriptors;
});
/*---------------------------------------------------------------------------------------------
* 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/platform/instantiation/common/graph*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Graph = exports.Node = void 0;
class Node {
constructor(data) {
this.incoming = new Map();
this.outgoing = new Map();
this.data = data;
}
}
exports.Node = Node;
class Graph {
constructor(_hashFn) {
this._hashFn = _hashFn;
this._nodes = new Map();
// empty
}
roots() {
const ret = [];
for (let 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(this._hashFn(to), toNode);
toNode.incoming.set(this._hashFn(from), fromNode);
}
removeNode(data) {
const key = this._hashFn(data);
this._nodes.delete(key);
for (let 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(data);
this._nodes.set(key, node);
}
return node;
}
isEmpty() {
return this._nodes.size === 0;
}
toString() {
let data = [];
for (let [key, value] of this._nodes) {
data.push(`${key}, (incoming)[${[...value.incoming.keys()].join(', ')}], (outgoing)[${[...value.outgoing.keys()].join(',')}]`);
}
return data.join('\n');
}
/**
* This is brute force and slow and **only** be used
* to trouble shoot.
*/
findCycleSlow() {
for (let [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 (let [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[9/*vs/platform/instantiation/common/instantiation*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.optional = exports.createDecorator = exports.IInstantiationService = exports._util = void 0;
// ------ 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 || (exports._util = {}));
exports.IInstantiationService = createDecorator('instantiationService');
function storeServiceDependency(id, target, index, optional) {
if (target[_util.DI_TARGET] === target) {
target[_util.DI_DEPENDENCIES].push({ id, index, optional });
}
else {
target[_util.DI_DEPENDENCIES] = [{ id, index, optional }];
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, false);
};
id.toString = () => serviceId;
_util.serviceIds.set(serviceId, id);
return id;
}
exports.createDecorator = createDecorator;
/**
* Mark a service dependency as optional.
*/
function optional(serviceIdentifier) {
return function (target, key, index) {
if (arguments.length !== 3) {
throw new Error('@optional-decorator can only be used to decorate a parameter');
}
storeServiceDependency(serviceIdentifier, target, index, true);
};
}
exports.optional = optional;
});
/*---------------------------------------------------------------------------------------------
* 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/editor/browser/services/bulkEditService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,24/*vs/base/common/uri*/,20/*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');
function isWorkspaceFileEdit(thing) {
return (0, types_1.isObject)(thing) && (Boolean(thing.newUri) || Boolean(thing.oldUri));
}
function isWorkspaceTextEdit(thing) {
return (0, types_1.isObject)(thing) && uri_1.URI.isUri(thing.resource) && (0, types_1.isObject)(thing.edit);
}
class ResourceEdit {
constructor(metadata) {
this.metadata = metadata;
}
static convert(edit) {
return edit.edits.map(edit => {
if (isWorkspaceTextEdit(edit)) {
return new ResourceTextEdit(edit.resource, edit.edit, edit.modelVersionId, edit.metadata);
}
if (isWorkspaceFileEdit(edit)) {
return new ResourceFileEdit(edit.oldUri, edit.newUri, edit.options, edit.metadata);
}
throw new Error('Unsupported edit');
});
}
}
exports.ResourceEdit = ResourceEdit;
class ResourceTextEdit extends ResourceEdit {
constructor(resource, textEdit, versionId, metadata) {
super(metadata);
this.resource = resource;
this.textEdit = textEdit;
this.versionId = versionId;
}
}
exports.ResourceTextEdit = ResourceTextEdit;
class ResourceFileEdit extends ResourceEdit {
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[28/*vs/editor/browser/services/codeEditorService*/], __M([0/*require*/,1/*exports*/,9/*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.
*--------------------------------------------------------------------------------------------*/
define(__m[76/*vs/editor/common/services/editorWorkerService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IEditorWorkerService = exports.ID_EDITOR_WORKER_SERVICE = void 0;
exports.ID_EDITOR_WORKER_SERVICE = 'editorWorkerService';
exports.IEditorWorkerService = (0, instantiation_1.createDecorator)(exports.ID_EDITOR_WORKER_SERVICE);
});
/*---------------------------------------------------------------------------------------------
* 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/services/markersDecorationService*/], __M([0/*require*/,1/*exports*/,9/*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[57/*vs/editor/common/services/modeService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IModeService = void 0;
exports.IModeService = (0, instantiation_1.createDecorator)('modeService');
});
/*---------------------------------------------------------------------------------------------
* 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/services/modelService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.shouldSynchronizeModel = exports.IModelService = void 0;
exports.IModelService = (0, instantiation_1.createDecorator)('modelService');
function shouldSynchronizeModel(model) {
return (!model.isTooLargeForSyncing() && !model.isForSimpleWidget);
}
exports.shouldSynchronizeModel = shouldSynchronizeModel;
});
/*---------------------------------------------------------------------------------------------
* 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/common/modes/languageFeatureRegistry*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,92/*vs/base/common/hash*/,2/*vs/base/common/lifecycle*/,49/*vs/base/common/map*/,102/*vs/base/common/numbers*/,382/*vs/editor/common/modes/languageSelector*/,36/*vs/editor/common/services/modelService*/]), function (require, exports, event_1, hash_1, lifecycle_1, map_1, numbers_1, languageSelector_1, modelService_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LanguageFeatureRequestDelays = 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 LanguageFeatureRegistry {
constructor() {
this._clock = 0;
this._entries = [];
this._onDidChange = new event_1.Emitter();
}
get onDidChange() {
return 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) {
let 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);
const result = [];
// from registry
for (let entry of this._entries) {
if (entry._score > 0) {
result.push(entry.provider);
}
}
return result;
}
ordered(model) {
const result = [];
this._orderedForEach(model, entry => result.push(entry.provider));
return result;
}
orderedGroups(model) {
const result = [];
let lastBucket;
let lastBucketScore;
this._orderedForEach(model, entry => {
if (lastBucket && lastBucketScore === entry._score) {
lastBucket.push(entry.provider);
}
else {
lastBucketScore = entry._score;
lastBucket = [entry.provider];
result.push(lastBucket);
}
});
return result;
}
_orderedForEach(model, callback) {
if (!model) {
return;
}
this._updateScores(model);
for (const entry of this._entries) {
if (entry._score > 0) {
callback(entry);
}
}
}
_updateScores(model) {
let candidate = {
uri: model.uri.toString(),
language: model.getLanguageIdentifier().language
};
if (this._lastCandidate
&& this._lastCandidate.language === candidate.language
&& this._lastCandidate.uri === candidate.uri) {
// nothing has changed
return;
}
this._lastCandidate = candidate;
for (let entry of this._entries) {
entry._score = (0, languageSelector_1.score)(entry.selector, model.uri, model.getLanguageIdentifier().language, (0, modelService_1.shouldSynchronizeModel)(model));
if (isExclusive(entry.selector) && entry._score > 0) {
// support for one exclusive selector that overwrites
// any other selector
for (let 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;
}
else if (a._time < b._time) {
return 1;
}
else if (a._time > b._time) {
return -1;
}
else {
return 0;
}
}
}
exports.LanguageFeatureRegistry = LanguageFeatureRegistry;
/**
* Keeps moving average per model and set of providers so that requests
* can be debounce according to the provider performance
*/
class LanguageFeatureRequestDelays {
constructor(_registry, min, max = Number.MAX_SAFE_INTEGER) {
this._registry = _registry;
this.min = min;
this.max = max;
this._cache = new map_1.LRUCache(50, 0.7);
}
_key(model) {
return model.id + (0, hash_1.hash)(this._registry.all(model));
}
_clamp(value) {
if (value === undefined) {
return this.min;
}
else {
return Math.min(this.max, Math.max(this.min, Math.floor(value * 1.3)));
}
}
get(model) {
const key = this._key(model);
const avg = this._cache.get(key);
return this._clamp(avg === null || avg === void 0 ? void 0 : avg.value);
}
update(model, value) {
const key = this._key(model);
let avg = this._cache.get(key);
if (!avg) {
avg = new numbers_1.MovingAverage();
this._cache.set(key, avg);
}
avg.update(value);
return this.get(model);
}
}
exports.LanguageFeatureRequestDelays = LanguageFeatureRequestDelays;
});
/*---------------------------------------------------------------------------------------------
* 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/editor/common/modes*/], __M([0/*require*/,1/*exports*/,24/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,139/*vs/editor/common/modes/languageFeatureRegistry*/,390/*vs/editor/common/modes/tokenizationRegistry*/,27/*vs/base/common/codicons*/]), function (require, exports, uri_1, range_1, languageFeatureRegistry_1, tokenizationRegistry_1, codicons_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TokenizationRegistry = exports.DocumentRangeSemanticTokensProviderRegistry = exports.DocumentSemanticTokensProviderRegistry = exports.FoldingRangeProviderRegistry = exports.SelectionRangeRegistry = exports.ColorProviderRegistry = exports.LinkProviderRegistry = exports.OnTypeFormattingEditProviderRegistry = exports.DocumentRangeFormattingEditProviderRegistry = exports.DocumentFormattingEditProviderRegistry = exports.CodeActionProviderRegistry = exports.InlayHintsProviderRegistry = exports.CodeLensProviderRegistry = exports.TypeDefinitionProviderRegistry = exports.ImplementationProviderRegistry = exports.DeclarationProviderRegistry = exports.DefinitionProviderRegistry = exports.LinkedEditingRangeProviderRegistry = exports.DocumentHighlightProviderRegistry = exports.DocumentSymbolProviderRegistry = exports.HoverProviderRegistry = exports.SignatureHelpProviderRegistry = exports.InlineCompletionsProviderRegistry = exports.CompletionProviderRegistry = exports.RenameProviderRegistry = exports.ReferenceProviderRegistry = exports.InlayHintKind = exports.FoldingRangeKind = exports.SymbolKinds = exports.isLocationLink = exports.DocumentHighlightKind = exports.SignatureHelpTriggerKind = exports.InlineCompletionTriggerKind = exports.completionKindFromString = exports.completionKindToCssClass = exports.TokenMetadata = exports.LanguageIdentifier = void 0;
/**
* @internal
*/
class LanguageIdentifier {
constructor(language, id) {
this.language = language;
this.id = id;
}
}
exports.LanguageIdentifier = LanguageIdentifier;
/**
* @internal
*/
class TokenMetadata {
static getLanguageId(metadata) {
return (metadata & 255 /* LANGUAGEID_MASK */) >>> 0 /* LANGUAGEID_OFFSET */;
}
static getTokenType(metadata) {
return (metadata & 1792 /* TOKEN_TYPE_MASK */) >>> 8 /* TOKEN_TYPE_OFFSET */;
}
static getFontStyle(metadata) {
return (metadata & 14336 /* FONT_STYLE_MASK */) >>> 11 /* FONT_STYLE_OFFSET */;
}
static getForeground(metadata) {
return (metadata & 8372224 /* FOREGROUND_MASK */) >>> 14 /* FOREGROUND_OFFSET */;
}
static getBackground(metadata) {
return (metadata & 4286578688 /* BACKGROUND_MASK */) >>> 23 /* BACKGROUND_OFFSET */;
}
static getClassNameFromMetadata(metadata) {
let foreground = this.getForeground(metadata);
let className = 'mtk' + foreground;
let fontStyle = this.getFontStyle(metadata);
if (fontStyle & 1 /* Italic */) {
className += ' mtki';
}
if (fontStyle & 2 /* Bold */) {
className += ' mtkb';
}
if (fontStyle & 4 /* Underline */) {
className += ' mtku';
}
return className;
}
static getInlineStyleFromMetadata(metadata, colorMap) {
const foreground = this.getForeground(metadata);
const fontStyle = this.getFontStyle(metadata);
let result = `color: ${colorMap[foreground]};`;
if (fontStyle & 1 /* Italic */) {
result += 'font-style: italic;';
}
if (fontStyle & 2 /* Bold */) {
result += 'font-weight: bold;';
}
if (fontStyle & 4 /* Underline */) {
result += 'text-decoration: underline;';
}
return result;
}
}
exports.TokenMetadata = TokenMetadata;
/**
* @internal
*/
exports.completionKindToCssClass = (function () {
let data = Object.create(null);
data[0 /* Method */] = 'symbol-method';
data[1 /* Function */] = 'symbol-function';
data[2 /* Constructor */] = 'symbol-constructor';
data[3 /* Field */] = 'symbol-field';
data[4 /* Variable */] = 'symbol-variable';
data[5 /* Class */] = 'symbol-class';
data[6 /* Struct */] = 'symbol-struct';
data[7 /* Interface */] = 'symbol-interface';
data[8 /* Module */] = 'symbol-module';
data[9 /* Property */] = 'symbol-property';
data[10 /* Event */] = 'symbol-event';
data[11 /* Operator */] = 'symbol-operator';
data[12 /* Unit */] = 'symbol-unit';
data[13 /* Value */] = 'symbol-value';
data[14 /* Constant */] = 'symbol-constant';
data[15 /* Enum */] = 'symbol-enum';
data[16 /* EnumMember */] = 'symbol-enum-member';
data[17 /* Keyword */] = 'symbol-keyword';
data[27 /* Snippet */] = 'symbol-snippet';
data[18 /* Text */] = 'symbol-text';
data[19 /* Color */] = 'symbol-color';
data[20 /* File */] = 'symbol-file';
data[21 /* Reference */] = 'symbol-reference';
data[22 /* Customcolor */] = 'symbol-customcolor';
data[23 /* Folder */] = 'symbol-folder';
data[24 /* TypeParameter */] = 'symbol-type-parameter';
data[25 /* User */] = 'account';
data[26 /* Issue */] = 'issues';
return function (kind) {
const name = data[kind];
let codicon = name && codicons_1.iconRegistry.get(name);
if (!codicon) {
console.info('No codicon found for CompletionItemKind ' + kind);
codicon = codicons_1.Codicon.symbolProperty;
}
return codicon.classNames;
};
})();
/**
* @internal
*/
exports.completionKindFromString = (function () {
let data = Object.create(null);
data['method'] = 0 /* Method */;
data['function'] = 1 /* Function */;
data['constructor'] = 2 /* Constructor */;
data['field'] = 3 /* Field */;
data['variable'] = 4 /* Variable */;
data['class'] = 5 /* Class */;
data['struct'] = 6 /* Struct */;
data['interface'] = 7 /* Interface */;
data['module'] = 8 /* Module */;
data['property'] = 9 /* Property */;
data['event'] = 10 /* Event */;
data['operator'] = 11 /* Operator */;
data['unit'] = 12 /* Unit */;
data['value'] = 13 /* Value */;
data['constant'] = 14 /* Constant */;
data['enum'] = 15 /* Enum */;
data['enum-member'] = 16 /* EnumMember */;
data['enumMember'] = 16 /* EnumMember */;
data['keyword'] = 17 /* Keyword */;
data['snippet'] = 27 /* Snippet */;
data['text'] = 18 /* Text */;
data['color'] = 19 /* Color */;
data['file'] = 20 /* File */;
data['reference'] = 21 /* Reference */;
data['customcolor'] = 22 /* Customcolor */;
data['folder'] = 23 /* Folder */;
data['type-parameter'] = 24 /* TypeParameter */;
data['typeParameter'] = 24 /* TypeParameter */;
data['account'] = 25 /* User */;
data['issue'] = 26 /* Issue */;
return function (value, strict) {
let res = data[value];
if (typeof res === 'undefined' && !strict) {
res = 9 /* Property */;
}
return res;
};
})();
/**
* 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 || (exports.InlineCompletionTriggerKind = {}));
var SignatureHelpTriggerKind;
(function (SignatureHelpTriggerKind) {
SignatureHelpTriggerKind[SignatureHelpTriggerKind["Invoke"] = 1] = "Invoke";
SignatureHelpTriggerKind[SignatureHelpTriggerKind["TriggerCharacter"] = 2] = "TriggerCharacter";
SignatureHelpTriggerKind[SignatureHelpTriggerKind["ContentChange"] = 3] = "ContentChange";
})(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.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 || (exports.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));
}
exports.isLocationLink = isLocationLink;
/**
* @internal
*/
var SymbolKinds;
(function (SymbolKinds) {
const byName = new Map();
byName.set('file', 0 /* File */);
byName.set('module', 1 /* Module */);
byName.set('namespace', 2 /* Namespace */);
byName.set('package', 3 /* Package */);
byName.set('class', 4 /* Class */);
byName.set('method', 5 /* Method */);
byName.set('property', 6 /* Property */);
byName.set('field', 7 /* Field */);
byName.set('constructor', 8 /* Constructor */);
byName.set('enum', 9 /* Enum */);
byName.set('interface', 10 /* Interface */);
byName.set('function', 11 /* Function */);
byName.set('variable', 12 /* Variable */);
byName.set('constant', 13 /* Constant */);
byName.set('string', 14 /* String */);
byName.set('number', 15 /* Number */);
byName.set('boolean', 16 /* Boolean */);
byName.set('array', 17 /* Array */);
byName.set('object', 18 /* Object */);
byName.set('key', 19 /* Key */);
byName.set('null', 20 /* Null */);
byName.set('enum-member', 21 /* EnumMember */);
byName.set('struct', 22 /* Struct */);
byName.set('event', 23 /* Event */);
byName.set('operator', 24 /* Operator */);
byName.set('type-parameter', 25 /* TypeParameter */);
const byKind = new Map();
byKind.set(0 /* File */, 'file');
byKind.set(1 /* Module */, 'module');
byKind.set(2 /* Namespace */, 'namespace');
byKind.set(3 /* Package */, 'package');
byKind.set(4 /* Class */, 'class');
byKind.set(5 /* Method */, 'method');
byKind.set(6 /* Property */, 'property');
byKind.set(7 /* Field */, 'field');
byKind.set(8 /* Constructor */, 'constructor');
byKind.set(9 /* Enum */, 'enum');
byKind.set(10 /* Interface */, 'interface');
byKind.set(11 /* Function */, 'function');
byKind.set(12 /* Variable */, 'variable');
byKind.set(13 /* Constant */, 'constant');
byKind.set(14 /* String */, 'string');
byKind.set(15 /* Number */, 'number');
byKind.set(16 /* Boolean */, 'boolean');
byKind.set(17 /* Array */, 'array');
byKind.set(18 /* Object */, 'object');
byKind.set(19 /* Key */, 'key');
byKind.set(20 /* Null */, 'null');
byKind.set(21 /* EnumMember */, 'enum-member');
byKind.set(22 /* Struct */, 'struct');
byKind.set(23 /* Event */, 'event');
byKind.set(24 /* Operator */, 'operator');
byKind.set(25 /* TypeParameter */, 'type-parameter');
/**
* @internal
*/
function fromString(value) {
return byName.get(value);
}
SymbolKinds.fromString = fromString;
/**
* @internal
*/
function toString(kind) {
return byKind.get(kind);
}
SymbolKinds.toString = toString;
/**
* @internal
*/
function toCssClassName(kind, inline) {
const symbolName = byKind.get(kind);
let codicon = symbolName && codicons_1.iconRegistry.get('symbol-' + symbolName);
if (!codicon) {
console.info('No codicon found for SymbolKind ' + kind);
codicon = codicons_1.Codicon.symbolProperty;
}
return `${inline ? 'inline' : 'block'} ${codicon.classNames}`;
}
SymbolKinds.toCssClassName = toCssClassName;
})(SymbolKinds = exports.SymbolKinds || (exports.SymbolKinds = {}));
class FoldingRangeKind {
/**
* Creates a new {@link FoldingRangeKind}.
*
* @param value of the kind.
*/
constructor(value) {
this.value = value;
}
}
exports.FoldingRangeKind = FoldingRangeKind;
/**
* Kind for folding range representing a comment. The value of the kind is 'comment'.
*/
FoldingRangeKind.Comment = new FoldingRangeKind('comment');
/**
* Kind for folding range representing a import. The value of the kind is 'imports'.
*/
FoldingRangeKind.Imports = new FoldingRangeKind('imports');
/**
* Kind for folding range representing regions (for example marked by `#region`, `#endregion`).
* The value of the kind is 'region'.
*/
FoldingRangeKind.Region = new FoldingRangeKind('region');
var InlayHintKind;
(function (InlayHintKind) {
InlayHintKind[InlayHintKind["Other"] = 0] = "Other";
InlayHintKind[InlayHintKind["Type"] = 1] = "Type";
InlayHintKind[InlayHintKind["Parameter"] = 2] = "Parameter";
})(InlayHintKind = exports.InlayHintKind || (exports.InlayHintKind = {}));
// --- feature registries ------
/**
* @internal
*/
exports.ReferenceProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.RenameProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.CompletionProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.InlineCompletionsProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.SignatureHelpProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.HoverProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DocumentSymbolProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DocumentHighlightProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.LinkedEditingRangeProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DefinitionProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DeclarationProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.ImplementationProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.TypeDefinitionProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.CodeLensProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.InlayHintsProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.CodeActionProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DocumentFormattingEditProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DocumentRangeFormattingEditProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.OnTypeFormattingEditProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.LinkProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.ColorProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.SelectionRangeRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.FoldingRangeProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DocumentSemanticTokensProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DocumentRangeSemanticTokensProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.TokenizationRegistry = new tokenizationRegistry_1.TokenizationRegistryImpl();
});
/*---------------------------------------------------------------------------------------------
* 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/editor/common/core/lineTokens*/], __M([0/*require*/,1/*exports*/,18/*vs/editor/common/modes*/]), function (require, exports, modes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SlicedLineTokens = exports.LineTokens = void 0;
class LineTokens {
constructor(tokens, text) {
this._lineTokensBrand = undefined;
this._tokens = tokens;
this._tokensCount = (this._tokens.length >>> 1);
this._text = text;
}
static createEmpty(lineContent) {
const defaultMetadata = LineTokens.defaultTokenMetadata;
const tokens = new Uint32Array(2);
tokens[0] = lineContent.length;
tokens[1] = defaultMetadata;
return new LineTokens(tokens, lineContent);
}
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];
return modes_1.TokenMetadata.getLanguageId(metadata);
}
getStandardTokenType(tokenIndex) {
const metadata = this._tokens[(tokenIndex << 1) + 1];
return modes_1.TokenMetadata.getTokenType(metadata);
}
getForeground(tokenIndex) {
const metadata = this._tokens[(tokenIndex << 1) + 1];
return modes_1.TokenMetadata.getForeground(metadata);
}
getClassName(tokenIndex) {
const metadata = this._tokens[(tokenIndex << 1) + 1];
return modes_1.TokenMetadata.getClassNameFromMetadata(metadata);
}
getInlineStyle(tokenIndex, colorMap) {
const metadata = this._tokens[(tokenIndex << 1) + 1];
return modes_1.TokenMetadata.getInlineStyleFromMetadata(metadata, colorMap);
}
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 SlicedLineTokens(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) {
let nextOriginalTokenEndOffset = nextOriginalTokenIdx < this._tokensCount ? this._tokens[nextOriginalTokenIdx << 1] : -1;
let 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);
}
}
exports.LineTokens = LineTokens;
LineTokens.defaultTokenMetadata = ((0 /* None */ << 11 /* FONT_STYLE_OFFSET */)
| (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */)
| (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0;
class SlicedLineTokens {
constructor(source, startOffset, endOffset, deltaOffset) {
this._source = source;
this._startOffset = startOffset;
this._endOffset = endOffset;
this._deltaOffset = deltaOffset;
this._firstTokenIndex = source.findTokenIndexAtOffset(startOffset);
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++;
}
}
equals(other) {
if (other instanceof SlicedLineTokens) {
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;
}
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);
}
findTokenIndexAtOffset(offset) {
return this._source.findTokenIndexAtOffset(offset + this._startOffset - this._deltaOffset) - this._firstTokenIndex;
}
}
exports.SlicedLineTokens = SlicedLineTokens;
});
/*---------------------------------------------------------------------------------------------
* 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/editor/common/model/tokensStore*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,85/*vs/editor/common/core/lineTokens*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/modes*/]), function (require, exports, arrays, lineTokens_1, position_1, range_1, modes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TokensStore = exports.TokensStore2 = exports.MultilineTokens = exports.MultilineTokens2 = exports.LineTokens2 = exports.SparseEncodedTokens = exports.MultilineTokensBuilder = exports.countEOL = void 0;
function countEOL(text) {
let eolCount = 0;
let firstLineLength = 0;
let lastLineStart = 0;
let eol = 0 /* Unknown */;
for (let i = 0, len = text.length; i < len; i++) {
const chr = text.charCodeAt(i);
if (chr === 13 /* CarriageReturn */) {
if (eolCount === 0) {
firstLineLength = i;
}
eolCount++;
if (i + 1 < len && text.charCodeAt(i + 1) === 10 /* LineFeed */) {
// \r\n... case
eol |= 2 /* CRLF */;
i++; // skip \n
}
else {
// \r... case
eol |= 3 /* Invalid */;
}
lastLineStart = i + 1;
}
else if (chr === 10 /* LineFeed */) {
// \n... case
eol |= 1 /* LF */;
if (eolCount === 0) {
firstLineLength = i;
}
eolCount++;
lastLineStart = i + 1;
}
}
if (eolCount === 0) {
firstLineLength = text.length;
}
return [eolCount, firstLineLength, text.length - lastLineStart, eol];
}
exports.countEOL = countEOL;
function getDefaultMetadata(topLevelLanguageId) {
return ((topLevelLanguageId << 0 /* LANGUAGEID_OFFSET */)
| (0 /* Other */ << 8 /* TOKEN_TYPE_OFFSET */)
| (0 /* None */ << 11 /* FONT_STYLE_OFFSET */)
| (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */)
| (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0;
}
const EMPTY_LINE_TOKENS = (new Uint32Array(0)).buffer;
class MultilineTokensBuilder {
constructor() {
this.tokens = [];
}
add(lineNumber, lineTokens) {
if (this.tokens.length > 0) {
const last = this.tokens[this.tokens.length - 1];
const lastLineNumber = last.startLineNumber + last.tokens.length - 1;
if (lastLineNumber + 1 === lineNumber) {
// append
last.tokens.push(lineTokens);
return;
}
}
this.tokens.push(new MultilineTokens(lineNumber, [lineTokens]));
}
}
exports.MultilineTokensBuilder = MultilineTokensBuilder;
class SparseEncodedTokens {
constructor(tokens) {
this._tokens = tokens;
this._tokenCount = tokens.length / 4;
}
toString(startLineNumber) {
let 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 LineTokens2(this._tokens.subarray(4 * min, 4 * max + 4));
}
}
if (this._getDeltaLine(low) === deltaLine) {
return new LineTokens2(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;
let aTokens = [];
let 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 SparseEncodedTokens(new Uint32Array(aTokens)), new SparseEncodedTokens(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 left and shrinks
if (tokenDeltaLine === startDeltaLine) {
// the deletion started on the same line as the token
// => the token moves left and shrinks
tokenStartCharacter = startCharacter;
tokenEndCharacter = tokenStartCharacter + (tokenEndCharacter - endCharacter);
}
else {
// the deletion started on a line above the token
// => the token moves to the beginning of the line
tokenStartCharacter = 0;
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 /* Digit0 */ && firstCharCode <= 57 /* Digit9 */)
|| (firstCharCode >= 65 /* A */ && firstCharCode <= 90 /* Z */)
|| (firstCharCode >= 97 /* a */ && firstCharCode <= 122 /* 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;
}
}
}
exports.SparseEncodedTokens = SparseEncodedTokens;
class LineTokens2 {
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.LineTokens2 = LineTokens2;
class MultilineTokens2 {
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 MultilineTokens2(this.startLineNumber, a), new MultilineTokens2(this.startLineNumber + bDeltaLine, b)];
}
applyEdit(range, text) {
const [eolCount, firstLineLength, lastLineLength] = countEOL(text);
this.acceptEdit(range, eolCount, firstLineLength, lastLineLength, text.length > 0 ? text.charCodeAt(0) : 0 /* 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.MultilineTokens2 = MultilineTokens2;
class MultilineTokens {
constructor(startLineNumber, tokens) {
this.startLineNumber = startLineNumber;
this.tokens = tokens;
}
}
exports.MultilineTokens = MultilineTokens;
function toUint32Array(arr) {
if (arr instanceof Uint32Array) {
return arr;
}
else {
return new Uint32Array(arr);
}
}
class TokensStore2 {
constructor() {
this._pieces = [];
this._isComplete = false;
}
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;
}
addSemanticTokens(lineNumber, aTokens) {
const pieces = this._pieces;
if (pieces.length === 0) {
return aTokens;
}
const pieceIndex = TokensStore2._findFirstPieceWithLine(pieces, lineNumber);
const bTokens = pieces[pieceIndex].getLineTokens(lineNumber);
if (!bTokens) {
return aTokens;
}
const aLen = aTokens.getCount();
const bLen = bTokens.getCount();
let aIndex = 0;
let result = [], 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 /* SEMANTIC_USE_ITALIC */) ? 2048 /* ITALIC_MASK */ : 0)
| ((bMetadata & 2 /* SEMANTIC_USE_BOLD */) ? 4096 /* BOLD_MASK */ : 0)
| ((bMetadata & 4 /* SEMANTIC_USE_UNDERLINE */) ? 8192 /* UNDERLINE_MASK */ : 0)
| ((bMetadata & 8 /* SEMANTIC_USE_FOREGROUND */) ? 8372224 /* FOREGROUND_MASK */ : 0)
| ((bMetadata & 16 /* SEMANTIC_USE_BACKGROUND */) ? 4286578688 /* 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());
}
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;
}
//#region Editing
acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode) {
for (const piece of this._pieces) {
piece.acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode);
}
}
}
exports.TokensStore2 = TokensStore2;
class TokensStore {
constructor() {
this._lineTokens = [];
this._len = 0;
}
flush() {
this._lineTokens = [];
this._len = 0;
}
getTokens(topLevelLanguageId, lineIndex, lineText) {
let rawLineTokens = null;
if (lineIndex < this._len) {
rawLineTokens = this._lineTokens[lineIndex];
}
if (rawLineTokens !== null && rawLineTokens !== EMPTY_LINE_TOKENS) {
return new lineTokens_1.LineTokens(toUint32Array(rawLineTokens), lineText);
}
let lineTokens = new Uint32Array(2);
lineTokens[0] = lineText.length;
lineTokens[1] = getDefaultMetadata(topLevelLanguageId);
return new lineTokens_1.LineTokens(lineTokens, lineText);
}
static _massageTokens(topLevelLanguageId, lineTextLength, _tokens) {
const tokens = _tokens ? toUint32Array(_tokens) : null;
if (lineTextLength === 0) {
let hasDifferentLanguageId = false;
if (tokens && tokens.length > 1) {
hasDifferentLanguageId = (modes_1.TokenMetadata.getLanguageId(tokens[1]) !== topLevelLanguageId);
}
if (!hasDifferentLanguageId) {
return 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;
}
let 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 = TokensStore._massageTokens(topLevelLanguageId, lineTextLength, _tokens);
this._ensureLine(lineIndex);
const oldTokens = this._lineTokens[lineIndex];
this._lineTokens[lineIndex] = tokens;
if (checkEquality) {
return !TokensStore._equals(oldTokens, tokens);
}
return false;
}
static _equals(_a, _b) {
if (!_a || !_b) {
return !_a && !_b;
}
const a = toUint32Array(_a);
const b = 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] = TokensStore._delete(this._lineTokens[firstLineIndex], range.startColumn - 1, range.endColumn - 1);
return;
}
this._lineTokens[firstLineIndex] = TokensStore._deleteEnding(this._lineTokens[firstLineIndex], range.startColumn - 1);
const lastLineIndex = range.endLineNumber - 1;
let lastLineTokens = null;
if (lastLineIndex < this._len) {
lastLineTokens = TokensStore._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] = TokensStore._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] = TokensStore._insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength);
return;
}
this._lineTokens[lineIndex] = TokensStore._deleteEnding(this._lineTokens[lineIndex], position.column - 1);
this._lineTokens[lineIndex] = TokensStore._insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength);
this._insertLines(position.lineNumber, eolCount);
}
static _deleteBeginning(lineTokens, toChIndex) {
if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
return lineTokens;
}
return TokensStore._delete(lineTokens, 0, toChIndex);
}
static _deleteEnding(lineTokens, fromChIndex) {
if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
return lineTokens;
}
const tokens = toUint32Array(lineTokens);
const lineTextLength = tokens[tokens.length - 2];
return TokensStore._delete(lineTokens, fromChIndex, lineTextLength);
}
static _delete(lineTokens, fromChIndex, toChIndex) {
if (lineTokens === null || lineTokens === 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 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;
}
let tmp = new Uint32Array(dest);
tmp.set(tokens.subarray(0, dest), 0);
return tmp.buffer;
}
static _append(lineTokens, _otherTokens) {
if (_otherTokens === EMPTY_LINE_TOKENS) {
return lineTokens;
}
if (lineTokens === 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);
let 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 === 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.TokensStore = TokensStore;
});
/*---------------------------------------------------------------------------------------------
* 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/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,8/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/,53/*vs/editor/common/model*/,221/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/,140/*vs/editor/common/model/tokensStore*/,220/*vs/editor/common/model/textChange*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, strings, range_1, model_1, pieceTreeBase_1, tokensStore_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) {
let 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 /* TextDefined */) {
if (range.isEmpty()) {
return '';
}
const lineEnding = this._getEndOfLine(eol);
return this._pieceTree.getValueInRange(range, lineEnding);
}
getValueLengthInRange(range, eol = 0 /* TextDefined */) {
if (range.isEmpty()) {
return 0;
}
if (range.startLineNumber === range.endLineNumber) {
return (range.endColumn - range.startColumn);
}
let startOffset = this.getOffsetAt(range.startLineNumber, range.startColumn);
let endOffset = this.getOffsetAt(range.endLineNumber, range.endColumn);
return endOffset - startOffset;
}
getCharacterCountInRange(range, eol = 0 /* 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 /* LF */:
return '\n';
case 2 /* CRLF */:
return '\r\n';
case 0 /* 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++) {
let op = rawOperations[i];
if (canReduceOperations && op._isTracked) {
canReduceOperations = false;
}
let 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, tokensStore_1.countEOL)(op.text);
const bufferEOL = this.getEOL();
const expectedStrEOL = (bufferEOL === '\r\n' ? 2 /* CRLF */ : 1 /* LF */);
if (strEOL === 0 /* 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++) {
let rangeEnd = operations[i].range.getEndPosition();
let 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
let reverseRanges = (computeUndoEdits || recordTrimAutoWhitespace ? PieceTreeTextBuffer._getInverseEditRanges(operations) : []);
let newTrimAutoWhitespaceCandidates = [];
if (recordTrimAutoWhitespace) {
for (let i = 0; i < operations.length; i++) {
let op = operations[i];
let 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++) {
let lineNumber = newTrimAutoWhitespaceCandidates[i].lineNumber;
if (i > 0 && newTrimAutoWhitespaceCandidates[i - 1].lineNumber === lineNumber) {
// Do not have the same line number twice
continue;
}
let prevContent = newTrimAutoWhitespaceCandidates[i].oldContent;
let 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, tokensStore_1.countEOL)(text);
return {
sortIndex: 0,
identifier: operations[0].identifier,
range: entireEditRange,
rangeOffset: this.getOffsetAt(entireEditRange.startLineNumber, entireEditRange.startColumn),
rangeLength: this.getValueLengthInRange(entireEditRange, 0 /* TextDefined */),
text: text,
eolCount: eolCount,
firstLineLength: firstLineLength,
lastLineLength: lastLineLength,
forceMoveMarkers: forceMoveMarkers,
isAutoWhitespaceEdit: false
};
}
_doApplyEdits(operations) {
operations.sort(PieceTreeTextBuffer._sortOpsDescending);
let contentChanges = [];
// operations are from bottom to top
for (let i = 0; i < operations.length; i++) {
let 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) {
let result = [];
let prevOpEndLineNumber = 0;
let prevOpEndColumn = 0;
let prevOp = null;
for (let i = 0, len = operations.length; i < len; i++) {
let 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) {
let r = range_1.Range.compareRangesUsingEnds(a.range, b.range);
if (r === 0) {
return a.sortIndex - b.sortIndex;
}
return r;
}
static _sortOpsDescending(a, b) {
let 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[548/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,221/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/,242/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer*/]), function (require, exports, strings, pieceTreeBase_1, pieceTreeTextBuffer_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PieceTreeTextBufferBuilder = exports.PieceTreeTextBufferFactory = 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 /* 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);
let 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++) {
let str = chunks[i].buffer.replace(/\r\n|\r|\n/g, eol);
let 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 };
}
}
exports.PieceTreeTextBufferFactory = PieceTreeTextBufferFactory;
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 /* 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 (this.isBasicASCII) {
this.isBasicASCII = lineStarts.isBasicASCII;
}
if (!this.isBasicASCII && !this.containsRTL) {
// No need to check if it is basic ASCII
this.containsRTL = strings.containsRTL(chunk);
}
if (!this.isBasicASCII && !this.containsUnusualLineTerminators) {
// No need to check if it is basic ASCII
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
let lastChunk = this.chunks[this.chunks.length - 1];
lastChunk.buffer += String.fromCharCode(this._previousChar);
let newLineStarts = (0, pieceTreeBase_1.createLineStartsFast)(lastChunk.buffer);
lastChunk.lineStarts = newLineStarts;
if (this._previousChar === 13 /* 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[77/*vs/editor/common/modes/nullMode*/], __M([0/*require*/,1/*exports*/,134/*vs/editor/common/core/token*/,18/*vs/editor/common/modes*/]), function (require, exports, token_1, modes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.nullTokenize2 = exports.nullTokenize = exports.NULL_LANGUAGE_IDENTIFIER = exports.NULL_MODE_ID = exports.NULL_STATE = void 0;
class NullStateImpl {
clone() {
return this;
}
equals(other) {
return (this === other);
}
}
exports.NULL_STATE = new NullStateImpl();
exports.NULL_MODE_ID = 'vs.editor.nullMode';
exports.NULL_LANGUAGE_IDENTIFIER = new modes_1.LanguageIdentifier(exports.NULL_MODE_ID, 0 /* Null */);
function nullTokenize(modeId, buffer, state, deltaOffset) {
return new token_1.TokenizationResult([new token_1.Token(deltaOffset, '', modeId)], state);
}
exports.nullTokenize = nullTokenize;
function nullTokenize2(languageId, buffer, state, deltaOffset) {
let tokens = new Uint32Array(2);
tokens[0] = deltaOffset;
tokens[1] = ((languageId << 0 /* LANGUAGEID_OFFSET */)
| (0 /* Other */ << 8 /* TOKEN_TYPE_OFFSET */)
| (0 /* None */ << 11 /* FONT_STYLE_OFFSET */)
| (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */)
| (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0;
return new token_1.TokenizationResult2(tokens, state === null ? exports.NULL_STATE : state);
}
exports.nullTokenize2 = nullTokenize2;
});
/*---------------------------------------------------------------------------------------------
* 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/common/model/textModelTokens*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,12/*vs/base/common/errors*/,85/*vs/editor/common/core/lineTokens*/,13/*vs/editor/common/core/position*/,18/*vs/editor/common/modes*/,77/*vs/editor/common/modes/nullMode*/,2/*vs/base/common/lifecycle*/,81/*vs/base/common/stopwatch*/,140/*vs/editor/common/model/tokensStore*/,17/*vs/base/common/platform*/]), function (require, exports, arrays, errors_1, lineTokens_1, position_1, modes_1, nullMode_1, lifecycle_1, stopwatch_1, tokensStore_1, platform) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TextModelTokenization = exports.TokenizationStateStore = void 0;
class TokenizationStateStore {
constructor() {
this._beginState = [];
this._valid = [];
this._len = 0;
this._invalidLineStartIndex = 0;
}
_reset(initialState) {
this._beginState = [];
this._valid = [];
this._len = 0;
this._invalidLineStartIndex = 0;
if (initialState) {
this._setBeginState(0, initialState);
}
}
flush(initialState) {
this._reset(initialState);
}
get invalidLineStartIndex() {
return this._invalidLineStartIndex;
}
_invalidateLine(lineIndex) {
if (lineIndex < this._len) {
this._valid[lineIndex] = false;
}
if (lineIndex < this._invalidLineStartIndex) {
this._invalidLineStartIndex = lineIndex;
}
}
_isValid(lineIndex) {
if (lineIndex < this._len) {
return this._valid[lineIndex];
}
return false;
}
getBeginState(lineIndex) {
if (lineIndex < this._len) {
return this._beginState[lineIndex];
}
return null;
}
_ensureLine(lineIndex) {
while (lineIndex >= this._len) {
this._beginState[this._len] = null;
this._valid[this._len] = false;
this._len++;
}
}
_deleteLines(start, deleteCount) {
if (deleteCount === 0) {
return;
}
if (start + deleteCount > this._len) {
deleteCount = this._len - start;
}
this._beginState.splice(start, deleteCount);
this._valid.splice(start, deleteCount);
this._len -= deleteCount;
}
_insertLines(insertIndex, insertCount) {
if (insertCount === 0) {
return;
}
let beginState = [];
let valid = [];
for (let i = 0; i < insertCount; i++) {
beginState[i] = null;
valid[i] = false;
}
this._beginState = arrays.arrayInsert(this._beginState, insertIndex, beginState);
this._valid = arrays.arrayInsert(this._valid, insertIndex, valid);
this._len += insertCount;
}
_setValid(lineIndex, valid) {
this._ensureLine(lineIndex);
this._valid[lineIndex] = valid;
}
_setBeginState(lineIndex, beginState) {
this._ensureLine(lineIndex);
this._beginState[lineIndex] = beginState;
}
setEndState(linesLength, lineIndex, endState) {
this._setValid(lineIndex, true);
this._invalidLineStartIndex = lineIndex + 1;
// Check if this was the last line
if (lineIndex === linesLength - 1) {
return;
}
// Check if the end state has changed
const previousEndState = this.getBeginState(lineIndex + 1);
if (previousEndState === null || !endState.equals(previousEndState)) {
this._setBeginState(lineIndex + 1, endState);
this._invalidateLine(lineIndex + 1);
return;
}
// Perhaps we can skip tokenizing some lines...
let i = lineIndex + 1;
while (i < linesLength) {
if (!this._isValid(i)) {
break;
}
i++;
}
this._invalidLineStartIndex = i;
}
setFakeTokens(lineIndex) {
this._setValid(lineIndex, false);
}
//#region Editing
applyEdits(range, eolCount) {
const deletingLinesCnt = range.endLineNumber - range.startLineNumber;
const insertingLinesCnt = eolCount;
const editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt);
for (let j = editingLinesCnt; j >= 0; j--) {
this._invalidateLine(range.startLineNumber + j - 1);
}
this._acceptDeleteRange(range);
this._acceptInsertText(new position_1.Position(range.startLineNumber, range.startColumn), eolCount);
}
_acceptDeleteRange(range) {
const firstLineIndex = range.startLineNumber - 1;
if (firstLineIndex >= this._len) {
return;
}
this._deleteLines(range.startLineNumber, range.endLineNumber - range.startLineNumber);
}
_acceptInsertText(position, eolCount) {
const lineIndex = position.lineNumber - 1;
if (lineIndex >= this._len) {
return;
}
this._insertLines(position.lineNumber, eolCount);
}
}
exports.TokenizationStateStore = TokenizationStateStore;
class TextModelTokenization extends lifecycle_1.Disposable {
constructor(textModel) {
super();
this._isDisposed = false;
this._textModel = textModel;
this._tokenizationStateStore = new TokenizationStateStore();
this._tokenizationSupport = null;
this._register(modes_1.TokenizationRegistry.onDidChange((e) => {
const languageIdentifier = this._textModel.getLanguageIdentifier();
if (e.changedLanguages.indexOf(languageIdentifier.language) === -1) {
return;
}
this._resetTokenizationState();
this._textModel.clearTokens();
}));
this._register(this._textModel.onDidChangeContentFast((e) => {
if (e.isFlush) {
this._resetTokenizationState();
return;
}
for (let i = 0, len = e.changes.length; i < len; i++) {
const change = e.changes[i];
const [eolCount] = (0, tokensStore_1.countEOL)(change.text);
this._tokenizationStateStore.applyEdits(change.range, eolCount);
}
this._beginBackgroundTokenization();
}));
this._register(this._textModel.onDidChangeAttached(() => {
this._beginBackgroundTokenization();
}));
this._register(this._textModel.onDidChangeLanguage(() => {
this._resetTokenizationState();
this._textModel.clearTokens();
}));
this._resetTokenizationState();
}
dispose() {
this._isDisposed = true;
super.dispose();
}
_resetTokenizationState() {
const [tokenizationSupport, initialState] = initializeTokenization(this._textModel);
this._tokenizationSupport = tokenizationSupport;
this._tokenizationStateStore.flush(initialState);
this._beginBackgroundTokenization();
}
_beginBackgroundTokenization() {
if (this._textModel.isAttachedToEditor() && this._hasLinesToTokenize()) {
platform.setImmediate(() => {
if (this._isDisposed) {
// disposed in the meantime
return;
}
this._revalidateTokensNow();
});
}
}
_revalidateTokensNow(toLineNumber = this._textModel.getLineCount()) {
const MAX_ALLOWED_TIME = 1;
const builder = new tokensStore_1.MultilineTokensBuilder();
const sw = stopwatch_1.StopWatch.create(false);
while (this._hasLinesToTokenize()) {
if (sw.elapsed() > MAX_ALLOWED_TIME) {
// Stop if MAX_ALLOWED_TIME is reached
break;
}
const tokenizedLineNumber = this._tokenizeOneInvalidLine(builder);
if (tokenizedLineNumber >= toLineNumber) {
break;
}
}
this._beginBackgroundTokenization();
this._textModel.setTokens(builder.tokens);
}
tokenizeViewport(startLineNumber, endLineNumber) {
const builder = new tokensStore_1.MultilineTokensBuilder();
this._tokenizeViewport(builder, startLineNumber, endLineNumber);
this._textModel.setTokens(builder.tokens);
}
reset() {
this._resetTokenizationState();
this._textModel.clearTokens();
}
forceTokenization(lineNumber) {
const builder = new tokensStore_1.MultilineTokensBuilder();
this._updateTokensUntilLine(builder, lineNumber);
this._textModel.setTokens(builder.tokens);
}
isCheapToTokenize(lineNumber) {
if (!this._tokenizationSupport) {
return true;
}
const firstInvalidLineNumber = this._tokenizationStateStore.invalidLineStartIndex + 1;
if (lineNumber > firstInvalidLineNumber) {
return false;
}
if (lineNumber < firstInvalidLineNumber) {
return true;
}
if (this._textModel.getLineLength(lineNumber) < 2048 /* CHEAP_TOKENIZATION_LENGTH_LIMIT */) {
return true;
}
return false;
}
_hasLinesToTokenize() {
if (!this._tokenizationSupport) {
return false;
}
return (this._tokenizationStateStore.invalidLineStartIndex < this._textModel.getLineCount());
}
_tokenizeOneInvalidLine(builder) {
if (!this._hasLinesToTokenize()) {
return this._textModel.getLineCount() + 1;
}
const lineNumber = this._tokenizationStateStore.invalidLineStartIndex + 1;
this._updateTokensUntilLine(builder, lineNumber);
return lineNumber;
}
_updateTokensUntilLine(builder, lineNumber) {
if (!this._tokenizationSupport) {
return;
}
const languageIdentifier = this._textModel.getLanguageIdentifier();
const linesLength = this._textModel.getLineCount();
const endLineIndex = lineNumber - 1;
// Validate all states up to and including endLineIndex
for (let lineIndex = this._tokenizationStateStore.invalidLineStartIndex; lineIndex <= endLineIndex; lineIndex++) {
const text = this._textModel.getLineContent(lineIndex + 1);
const lineStartState = this._tokenizationStateStore.getBeginState(lineIndex);
const r = safeTokenize(languageIdentifier, this._tokenizationSupport, text, true, lineStartState);
builder.add(lineIndex + 1, r.tokens);
this._tokenizationStateStore.setEndState(linesLength, lineIndex, r.endState);
lineIndex = this._tokenizationStateStore.invalidLineStartIndex - 1; // -1 because the outer loop increments it
}
}
_tokenizeViewport(builder, startLineNumber, endLineNumber) {
if (!this._tokenizationSupport) {
// nothing to do
return;
}
if (endLineNumber <= this._tokenizationStateStore.invalidLineStartIndex) {
// nothing to do
return;
}
if (startLineNumber <= this._tokenizationStateStore.invalidLineStartIndex) {
// tokenization has reached the viewport start...
this._updateTokensUntilLine(builder, endLineNumber);
return;
}
let nonWhitespaceColumn = this._textModel.getLineFirstNonWhitespaceColumn(startLineNumber);
let fakeLines = [];
let initialState = null;
for (let i = startLineNumber - 1; nonWhitespaceColumn > 0 && i >= 1; i--) {
let newNonWhitespaceIndex = this._textModel.getLineFirstNonWhitespaceColumn(i);
if (newNonWhitespaceIndex === 0) {
continue;
}
if (newNonWhitespaceIndex < nonWhitespaceColumn) {
initialState = this._tokenizationStateStore.getBeginState(i - 1);
if (initialState) {
break;
}
fakeLines.push(this._textModel.getLineContent(i));
nonWhitespaceColumn = newNonWhitespaceIndex;
}
}
if (!initialState) {
initialState = this._tokenizationSupport.getInitialState();
}
const languageIdentifier = this._textModel.getLanguageIdentifier();
let state = initialState;
for (let i = fakeLines.length - 1; i >= 0; i--) {
let r = safeTokenize(languageIdentifier, this._tokenizationSupport, fakeLines[i], false, state);
state = r.endState;
}
for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
let text = this._textModel.getLineContent(lineNumber);
let r = safeTokenize(languageIdentifier, this._tokenizationSupport, text, true, state);
builder.add(lineNumber, r.tokens);
this._tokenizationStateStore.setFakeTokens(lineNumber - 1);
state = r.endState;
}
}
}
exports.TextModelTokenization = TextModelTokenization;
function initializeTokenization(textModel) {
const languageIdentifier = textModel.getLanguageIdentifier();
let tokenizationSupport = (textModel.isTooLargeForTokenization()
? null
: modes_1.TokenizationRegistry.get(languageIdentifier.language));
let initialState = null;
if (tokenizationSupport) {
try {
initialState = tokenizationSupport.getInitialState();
}
catch (e) {
(0, errors_1.onUnexpectedError)(e);
tokenizationSupport = null;
}
}
return [tokenizationSupport, initialState];
}
function safeTokenize(languageIdentifier, tokenizationSupport, text, hasEOL, state) {
let r = null;
if (tokenizationSupport) {
try {
r = tokenizationSupport.tokenize2(text, hasEOL, state.clone(), 0);
}
catch (e) {
(0, errors_1.onUnexpectedError)(e);
}
}
if (!r) {
r = (0, nullMode_1.nullTokenize2)(languageIdentifier.id, text, state, 0);
}
lineTokens_1.LineTokens.convertToEndOffset(r.tokens, text.length);
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[31/*vs/editor/common/model/textModel*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,24/*vs/base/common/uri*/,35/*vs/editor/common/config/editorOptions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,53/*vs/editor/common/model*/,239/*vs/editor/common/model/editStack*/,378/*vs/editor/common/model/indentationGuesser*/,379/*vs/editor/common/model/intervalTree*/,548/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder*/,96/*vs/editor/common/model/textModelEvents*/,171/*vs/editor/common/model/textModelSearch*/,549/*vs/editor/common/model/textModelTokens*/,135/*vs/editor/common/model/wordHelper*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/,77/*vs/editor/common/modes/nullMode*/,172/*vs/editor/common/modes/supports*/,173/*vs/editor/common/modes/supports/richEditBrackets*/,140/*vs/editor/common/model/tokensStore*/,29/*vs/base/common/color*/,242/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer*/,19/*vs/base/common/arrays*/]), function (require, exports, errors_1, event_1, lifecycle_1, strings, uri_1, editorOptions_1, position_1, range_1, selection_1, model, editStack_1, indentationGuesser_1, intervalTree_1, pieceTreeTextBufferBuilder_1, textModelEvents_1, textModelSearch_1, textModelTokens_1, wordHelper_1, languageConfigurationRegistry_1, nullMode_1, supports_1, richEditBrackets_1, tokensStore_1, color_1, pieceTreeTextBuffer_1, arrays_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DidChangeContentEmitter = exports.DidChangeDecorationsEmitter = exports.ModelDecorationOptions = exports.ModelDecorationInjectedTextOptions = exports.ModelDecorationMinimapOptions = exports.ModelDecorationOverviewRulerOptions = exports.TextModel = exports.LONG_LINE_BOUNDARY = exports.createTextBuffer = exports.createTextBufferFactory = void 0;
function createTextBufferBuilder() {
return new pieceTreeTextBufferBuilder_1.PieceTreeTextBufferBuilder();
}
function createTextBufferFactory(text) {
const builder = createTextBufferBuilder();
builder.acceptChunk(text);
return builder.finish();
}
exports.createTextBufferFactory = createTextBufferFactory;
function createTextBuffer(value, defaultEOL) {
const factory = (typeof value === 'string' ? createTextBufferFactory(value) : value);
return factory.create(defaultEOL);
}
exports.createTextBuffer = createTextBuffer;
let MODEL_ID = 0;
const LIMIT_FIND_COUNT = 999;
exports.LONG_LINE_BOUNDARY = 10000;
class TextModelSnapshot {
constructor(source) {
this._source = source;
this._eos = false;
}
read() {
if (this._eos) {
return null;
}
let result = [], resultCnt = 0, resultLength = 0;
do {
let 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`); };
class BracketSearchCanceled {
constructor() {
this._searchCanceledBrand = undefined;
}
}
BracketSearchCanceled.INSTANCE = new BracketSearchCanceled();
function stripBracketSearchCanceled(result) {
if (result instanceof BracketSearchCanceled) {
return null;
}
return result;
}
class TextModel extends lifecycle_1.Disposable {
//#endregion
constructor(source, creationOptions, languageIdentifier, associatedResource = null, undoRedoService) {
super();
//#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._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._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._onDidChangeContentOrInjectedText = this._register(new event_1.Emitter());
this.onDidChangeContentOrInjectedText = this._onDidChangeContentOrInjectedText.event;
this._eventEmitter = this._register(new DidChangeContentEmitter());
this._register(this._eventEmitter.fastEvent((e) => {
this._onDidChangeContentOrInjectedText.fire(e.rawContentChangedEvent);
}));
// 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._undoRedoService = undoRedoService;
this._attachedEditorCount = 0;
const { textBuffer, disposable } = createTextBuffer(source, creationOptions.defaultEOL);
this._buffer = textBuffer;
this._bufferDisposable = disposable;
this._options = TextModel.resolveOptions(this._buffer, creationOptions);
const bufferLineCount = this._buffer.getLineCount();
const bufferTextLength = this._buffer.getValueLengthInRange(new range_1.Range(1, 1, bufferLineCount, this._buffer.getLineLength(bufferLineCount) + 1), 0 /* 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.LARGE_FILE_SIZE_THRESHOLD)
|| (bufferLineCount > TextModel.LARGE_FILE_LINE_COUNT_THRESHOLD));
}
else {
this._isTooLargeForTokenization = false;
}
this._isTooLargeForSyncing = (bufferTextLength > TextModel.MODEL_SYNC_LIMIT);
this._versionId = 1;
this._alternativeVersionId = 1;
this._initialUndoRedoSnapshot = null;
this._isDisposed = false;
this._isDisposing = false;
this._languageIdentifier = languageIdentifier || nullMode_1.NULL_LANGUAGE_IDENTIFIER;
this._languageRegistryListener = languageConfigurationRegistry_1.LanguageConfigurationRegistry.onDidChange((e) => {
if (e.languageIdentifier.id === this._languageIdentifier.id) {
this._onDidChangeLanguageConfiguration.fire({});
}
});
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, undoRedoService);
this._isUndoing = false;
this._isRedoing = false;
this._trimAutoWhitespaceLines = null;
this._tokens = new tokensStore_1.TokensStore();
this._tokens2 = new tokensStore_1.TokensStore2();
this._tokenization = new textModelTokens_1.TextModelTokenization(this);
}
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: guessedIndentation.tabSize,
insertSpaces: guessedIndentation.insertSpaces,
trimAutoWhitespace: options.trimAutoWhitespace,
defaultEOL: options.defaultEOL
});
}
return new model.TextModelResolvedOptions({
tabSize: options.tabSize,
indentSize: options.indentSize,
insertSpaces: options.insertSpaces,
trimAutoWhitespace: options.trimAutoWhitespace,
defaultEOL: options.defaultEOL
});
}
onDidChangeContentFast(listener) {
return this._eventEmitter.fastEvent((e) => listener(e.contentChangedEvent));
}
onDidChangeContent(listener) {
return this._eventEmitter.slowEvent((e) => listener(e.contentChangedEvent));
}
dispose() {
this._isDisposing = true;
this._onWillDispose.fire();
this._languageRegistryListener.dispose();
this._tokenization.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;
}
_assertNotDisposed() {
if (this._isDisposed) {
throw new Error('Model is disposed!');
}
}
_emitContentChangedEvent(rawChange, change) {
if (this._isDisposing) {
// Do not confuse listeners by emitting any event after disposing
return;
}
this._eventEmitter.fire(new textModelEvents_1.InternalModelContentChangeEvent(rawChange, change));
}
setValue(value) {
this._assertNotDisposed();
if (value === null) {
// There's nothing to do
return;
}
const { textBuffer, disposable } = createTextBuffer(value, this._options.defaultEOL);
this._setValueFromTextBuffer(textBuffer, disposable);
}
_createContentChanged2(range, rangeOffset, rangeLength, text, isUndoing, isRedoing, isFlush) {
return {
changes: [{
range: range,
rangeOffset: rangeOffset,
rangeLength: rangeLength,
text: text,
}],
eol: this._buffer.getEOL(),
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();
// Flush all tokens
this._tokens.flush();
this._tokens2.flush();
// 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));
}
setEOL(eol) {
this._assertNotDisposed();
const newEOL = (eol === 1 /* 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));
}
_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._onDidChangeAttached.fire(undefined);
}
}
onBeforeDetached() {
this._attachedEditorCount--;
if (this._attachedEditorCount === 0) {
this._onDidChangeAttached.fire(undefined);
}
}
isAttachedToEditor() {
return this._attachedEditorCount > 0;
}
getAttachedEditorCount() {
return this._attachedEditorCount;
}
isTooLargeForSyncing() {
return this._isTooLargeForSyncing;
}
isTooLargeForTokenization() {
return this._isTooLargeForTokenization;
}
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 >= exports.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();
let tabSize = (typeof _newOpts.tabSize !== 'undefined') ? _newOpts.tabSize : this._options.tabSize;
let indentSize = (typeof _newOpts.indentSize !== 'undefined') ? _newOpts.indentSize : this._options.indentSize;
let insertSpaces = (typeof _newOpts.insertSpaces !== 'undefined') ? _newOpts.insertSpaces : this._options.insertSpaces;
let trimAutoWhitespace = (typeof _newOpts.trimAutoWhitespace !== 'undefined') ? _newOpts.trimAutoWhitespace : this._options.trimAutoWhitespace;
let newOpts = new model.TextModelResolvedOptions({
tabSize: tabSize,
indentSize: indentSize,
insertSpaces: insertSpaces,
defaultEOL: this._options.defaultEOL,
trimAutoWhitespace: trimAutoWhitespace
});
if (this._options.equals(newOpts)) {
return;
}
let e = this._options.createChangeEvent(newOpts);
this._options = newOpts;
this._onDidChangeOptions.fire(e);
}
detectIndentation(defaultInsertSpaces, defaultTabSize) {
this._assertNotDisposed();
let 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
});
}
static _normalizeIndentationFromWhitespace(str, indentSize, insertSpaces) {
let spacesCnt = 0;
for (let i = 0; i < str.length; i++) {
if (str.charAt(i) === '\t') {
spacesCnt += indentSize;
}
else {
spacesCnt++;
}
}
let result = '';
if (!insertSpaces) {
let 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;
}
static normalizeIndentation(str, indentSize, insertSpaces) {
let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(str);
if (firstNonWhitespaceIndex === -1) {
firstNonWhitespaceIndex = str.length;
}
return TextModel._normalizeIndentationFromWhitespace(str.substring(0, firstNonWhitespaceIndex), indentSize, insertSpaces) + str.substring(firstNonWhitespaceIndex);
}
normalizeIndentation(str) {
this._assertNotDisposed();
return TextModel.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 /* 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();
let position = this._validatePosition(rawPosition.lineNumber, rawPosition.column, 0 /* Relaxed */);
return this._buffer.getOffsetAt(position.lineNumber, position.column);
}
getPositionAt(rawOffset) {
this._assertNotDisposed();
let 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();
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 /* TextDefined */) {
this._assertNotDisposed();
return this._buffer.getValueInRange(this.validateRange(rawRange), eol);
}
getValueLengthInRange(rawRange, eol = 0 /* TextDefined */) {
this._assertNotDisposed();
return this._buffer.getValueLengthInRange(this.validateRange(rawRange), eol);
}
getCharacterCountInRange(rawRange, eol = 0 /* 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 Error('Illegal value for lineNumber');
}
return this._buffer.getLineContent(lineNumber);
}
getLineLength(lineNumber) {
this._assertNotDisposed();
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
throw new Error('Illegal value for lineNumber');
}
return this._buffer.getLineLength(lineNumber);
}
getLinesContent() {
this._assertNotDisposed();
return this._buffer.getLinesContent();
}
getEOL() {
this._assertNotDisposed();
return this._buffer.getEOL();
}
getEndOfLineSequence() {
this._assertNotDisposed();
return (this._buffer.getEOL() === '\n'
? 0 /* LF */
: 1 /* CRLF */);
}
getLineMinColumn(lineNumber) {
this._assertNotDisposed();
return 1;
}
getLineMaxColumn(lineNumber) {
this._assertNotDisposed();
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
throw new Error('Illegal value for lineNumber');
}
return this._buffer.getLineLength(lineNumber) + 1;
}
getLineFirstNonWhitespaceColumn(lineNumber) {
this._assertNotDisposed();
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
throw new Error('Illegal value for lineNumber');
}
return this._buffer.getLineFirstNonWhitespaceColumn(lineNumber);
}
getLineLastNonWhitespaceColumn(lineNumber) {
this._assertNotDisposed();
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
throw new Error('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 /* 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 /* 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 /* 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 /* Relaxed */)) {
return false;
}
if (!this._isValidPosition(endLineNumber, endColumn, 0 /* Relaxed */)) {
return false;
}
if (validationType === 1 /* 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 /* 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 /* Relaxed */);
const end = this._validatePosition(_range.endLineNumber, _range.endColumn, 0 /* Relaxed */);
const startLineNumber = start.lineNumber;
const startColumn = start.column;
const endLineNumber = end.lineNumber;
const endColumn = end.column;
if (validationType === 1 /* 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();
let 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 /* LF */ : 1 /* 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) {
try {
this._onDidChangeDecorations.beginDeferredEmit();
this._eventEmitter.beginDeferredEmit();
return this._pushEditOperations(beforeCursorState, this._validateEditOperations(editOperations), cursorStateComputer);
}
finally {
this._eventEmitter.endDeferredEmit();
this._onDidChangeDecorations.endDeferredEmit();
}
}
_pushEditOperations(beforeCursorState, editOperations, cursorStateComputer) {
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).
let 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++) {
let sel = beforeCursorState[i];
let foundEditNearSel = false;
for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
let editRange = incomingEdits[j].range;
let selIsAbove = editRange.startLineNumber > sel.endLineNumber;
let 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++) {
let trimLineNumber = this._trimAutoWhitespaceLines[i];
let maxLineColumn = this.getLineMaxColumn(trimLineNumber);
let allowTrimLine = true;
for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
let editRange = incomingEdits[j].range;
let 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);
}
_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 tokens and 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];
const [eolCount, firstLineLength, lastLineLength] = (0, tokensStore_1.countEOL)(change.text);
this._tokens.acceptEdit(change.range, eolCount, firstLineLength);
this._tokens2.acceptEdit(change.range, eolCount, firstLineLength, lastLineLength, change.text.length > 0 ? change.text.charCodeAt(0) : 0 /* Null */);
this._decorationsTree.acceptReplace(change.rangeOffset, change.rangeLength, change.text.length, change.forceMoveMarkers);
}
let rawContentChanges = [];
this._increaseVersionId();
let lineCount = oldLineCount;
for (let i = 0, len = contentChanges.length; i < len; i++) {
const change = contentChanges[i];
const [eolCount] = (0, tokensStore_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;
let injectedTexts = [];
let newLines = [];
for (let i = 0; i < cnt; i++) {
let 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(),
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 = [...affectedInjectedTextLines];
const lineChangeEvents = affectedLines.map(lineNumber => new textModelEvents_1.ModelRawLineChanged(lineNumber, this.getLineContent(lineNumber), this._getInjectedTextInLine(lineNumber)));
this._onDidChangeContentOrInjectedText.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) {
let 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._onDidChangeDecorations.beginDeferredEmit();
return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);
}
finally {
this._onDidChangeDecorations.endDeferredEmit();
}
}
_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] }])[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) {
let lineCount = this.getLineCount();
let startLineNumber = Math.min(lineCount, Math.max(1, _startLineNumber));
let endLineNumber = Math.min(lineCount, Math.max(1, _endLineNumber));
let endColumn = this.getLineMaxColumn(endLineNumber);
return this._getDecorationsInRange(new range_1.Range(startLineNumber, 1, endLineNumber, endColumn), ownerId, filterOutValidation);
}
getDecorationsInRange(range, ownerId = 0, filterOutValidation = false) {
let validatedRange = this.validateRange(range);
return this._getDecorationsInRange(validatedRange, ownerId, filterOutValidation);
}
getOverviewRulerDecorations(ownerId = 0, filterOutValidation = false) {
return this._decorationsTree.getAll(this, ownerId, filterOutValidation, true);
}
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) {
return this._decorationsTree.getAll(this, ownerId, filterOutValidation, false);
}
_getDecorationsInRange(filterRange, filterOwnerId, filterOutValidation) {
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);
}
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);
}
if (nodeWasInOverviewRuler !== nodeIsInOverviewRuler) {
// Delete + Insert due to an overview ruler status change
this._decorationsTree.delete(node);
node.setOptions(options);
this._decorationsTree.insert(node);
}
else {
node.setOptions(options);
}
}
_deltaDecorationsImpl(ownerId, oldDecorationsIds, newDecorations) {
const versionId = this.getVersionId();
const oldDecorationsLen = oldDecorationsIds.length;
let oldDecorationIndex = 0;
const newDecorationsLen = newDecorations.length;
let newDecorationIndex = 0;
let 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);
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);
}
this._onDidChangeDecorations.checkAffectedAndFire(options);
this._decorationsTree.insert(node);
result[newDecorationIndex] = node.id;
newDecorationIndex++;
}
else {
if (node) {
delete this._decorations[node.id];
}
}
}
return result;
}
setTokens(tokens) {
if (tokens.length === 0) {
return;
}
let 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 j = 0, lenJ = element.tokens.length; j < lenJ; j++) {
const lineNumber = element.startLineNumber + j;
if (hasChange) {
this._tokens.setTokens(this._languageIdentifier.id, lineNumber - 1, this._buffer.getLineLength(lineNumber), element.tokens[j], false);
maxChangedLineNumber = lineNumber;
}
else {
const lineHasChange = this._tokens.setTokens(this._languageIdentifier.id, lineNumber - 1, this._buffer.getLineLength(lineNumber), element.tokens[j], true);
if (lineHasChange) {
hasChange = true;
minChangedLineNumber = lineNumber;
maxChangedLineNumber = lineNumber;
}
}
}
if (hasChange) {
ranges.push({ fromLineNumber: minChangedLineNumber, toLineNumber: maxChangedLineNumber });
}
}
if (ranges.length > 0) {
this._emitModelTokensChangedEvent({
tokenizationSupportChanged: false,
semanticTokensApplied: false,
ranges: ranges
});
}
}
setSemanticTokens(tokens, isComplete) {
this._tokens2.set(tokens, isComplete);
this._emitModelTokensChangedEvent({
tokenizationSupportChanged: false,
semanticTokensApplied: tokens !== null,
ranges: [{ fromLineNumber: 1, toLineNumber: this.getLineCount() }]
});
}
hasCompleteSemanticTokens() {
return this._tokens2.isComplete();
}
hasSomeSemanticTokens() {
return !this._tokens2.isEmpty();
}
setPartialSemanticTokens(range, tokens) {
if (this.hasCompleteSemanticTokens()) {
return;
}
const changedRange = this._tokens2.setPartial(range, tokens);
this._emitModelTokensChangedEvent({
tokenizationSupportChanged: false,
semanticTokensApplied: true,
ranges: [{ fromLineNumber: changedRange.startLineNumber, toLineNumber: changedRange.endLineNumber }]
});
}
tokenizeViewport(startLineNumber, endLineNumber) {
startLineNumber = Math.max(1, startLineNumber);
endLineNumber = Math.min(this._buffer.getLineCount(), endLineNumber);
this._tokenization.tokenizeViewport(startLineNumber, endLineNumber);
}
clearTokens() {
this._tokens.flush();
this._emitModelTokensChangedEvent({
tokenizationSupportChanged: true,
semanticTokensApplied: false,
ranges: [{
fromLineNumber: 1,
toLineNumber: this._buffer.getLineCount()
}]
});
}
_emitModelTokensChangedEvent(e) {
if (!this._isDisposing) {
this._onDidChangeTokens.fire(e);
}
}
resetTokenization() {
this._tokenization.reset();
}
forceTokenization(lineNumber) {
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
throw new Error('Illegal value for lineNumber');
}
this._tokenization.forceTokenization(lineNumber);
}
isCheapToTokenize(lineNumber) {
return this._tokenization.isCheapToTokenize(lineNumber);
}
tokenizeIfCheap(lineNumber) {
if (this.isCheapToTokenize(lineNumber)) {
this.forceTokenization(lineNumber);
}
}
getLineTokens(lineNumber) {
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
throw new Error('Illegal value for lineNumber');
}
return this._getLineTokens(lineNumber);
}
_getLineTokens(lineNumber) {
const lineText = this.getLineContent(lineNumber);
const syntacticTokens = this._tokens.getTokens(this._languageIdentifier.id, lineNumber - 1, lineText);
return this._tokens2.addSemanticTokens(lineNumber, syntacticTokens);
}
getLanguageIdentifier() {
return this._languageIdentifier;
}
getModeId() {
return this._languageIdentifier.language;
}
setMode(languageIdentifier) {
if (this._languageIdentifier.id === languageIdentifier.id) {
// There's nothing to do
return;
}
let e = {
oldLanguage: this._languageIdentifier.language,
newLanguage: languageIdentifier.language
};
this._languageIdentifier = languageIdentifier;
this._onDidChangeLanguage.fire(e);
this._onDidChangeLanguageConfiguration.fire({});
}
getLanguageIdAtPosition(lineNumber, column) {
const position = this.validatePosition(new position_1.Position(lineNumber, column));
const lineTokens = this.getLineTokens(position.lineNumber);
return lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1));
}
// Having tokens allows implementing additional helper methods
getWordAtPosition(_position) {
this._assertNotDisposed();
const position = this.validatePosition(_position);
const lineContent = this.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] = TextModel._findLanguageBoundaries(lineTokens, tokenIndex);
const rightBiasedWord = (0, wordHelper_1.getWordAtText)(position.column, languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(lineTokens.getLanguageId(tokenIndex)), 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] = TextModel._findLanguageBoundaries(lineTokens, tokenIndex - 1);
const leftBiasedWord = (0, wordHelper_1.getWordAtText)(position.column, languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(lineTokens.getLanguageId(tokenIndex - 1)), 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;
}
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
};
}
findMatchingBracketUp(_bracket, _position) {
let bracket = _bracket.toLowerCase();
let position = this.validatePosition(_position);
let lineTokens = this._getLineTokens(position.lineNumber);
let languageId = lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1));
let bracketsSupport = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
if (!bracketsSupport) {
return null;
}
let data = bracketsSupport.textIsBracket[bracket];
if (!data) {
return null;
}
return stripBracketSearchCanceled(this._findMatchingBracketUp(data, position, null));
}
matchBracket(position) {
return this._matchBracket(this.validatePosition(position));
}
_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) {
const lineNumber = position.lineNumber;
const lineTokens = this._getLineTokens(lineNumber);
const lineText = this._buffer.getLineContent(lineNumber);
const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
if (tokenIndex < 0) {
return null;
}
const currentModeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(tokenIndex));
// 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], null);
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 = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(prevTokenIndex));
// check that previous token is not to be ignored
if (prevModeBrackets && !(0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(prevTokenIndex))) {
let { 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], null);
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.languageIdentifier.id;
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._getLineTokens(lineNumber);
const tokenCount = lineTokens.getCount();
const lineText = this._buffer.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.languageIdentifier.id;
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.getLineCount();
for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
const lineTokens = this._getLineTokens(lineNumber);
const tokenCount = lineTokens.getCount();
const lineText = this._buffer.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.validatePosition(_position);
let languageId = -1;
let modeBrackets = null;
for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {
const lineTokens = this._getLineTokens(lineNumber);
const tokenCount = lineTokens.getCount();
const lineText = this._buffer.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 = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
}
}
let prevSearchInToken = true;
for (; tokenIndex >= 0; tokenIndex--) {
const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
if (languageId !== tokenLanguageId) {
// language id change!
if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
const r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return this._toFoundBracket(modeBrackets, r);
}
prevSearchInToken = false;
}
languageId = tokenLanguageId;
modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
}
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 (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
const r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return this._toFoundBracket(modeBrackets, r);
}
}
}
prevSearchInToken = searchInToken;
}
if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
const r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return this._toFoundBracket(modeBrackets, r);
}
}
}
return null;
}
findNextBracket(_position) {
const position = this.validatePosition(_position);
const lineCount = this.getLineCount();
let languageId = -1;
let modeBrackets = null;
for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
const lineTokens = this._getLineTokens(lineNumber);
const tokenCount = lineTokens.getCount();
const lineText = this._buffer.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 = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
}
}
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 = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return this._toFoundBracket(modeBrackets, r);
}
prevSearchInToken = false;
}
languageId = tokenLanguageId;
modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
}
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 = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return this._toFoundBracket(modeBrackets, r);
}
}
}
prevSearchInToken = searchInToken;
}
if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
const r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return this._toFoundBracket(modeBrackets, r);
}
}
}
return null;
}
findEnclosingBrackets(_position, maxDuration) {
let continueSearchPredicate;
if (typeof maxDuration === 'undefined') {
continueSearchPredicate = null;
}
else {
const startTime = Date.now();
continueSearchPredicate = () => {
return (Date.now() - startTime <= maxDuration);
};
}
const position = this.validatePosition(_position);
const lineCount = this.getLineCount();
const savedCounts = new Map();
let counts = [];
const resetCounts = (languageId, modeBrackets) => {
if (!savedCounts.has(languageId)) {
let 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 = -1;
let modeBrackets = null;
for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
const lineTokens = this._getLineTokens(lineNumber);
const tokenCount = lineTokens.getCount();
const lineText = this._buffer.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 = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
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 = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
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(modeBrackets, r) {
if (!r) {
return null;
}
let text = this.getValueInRange(r);
text = text.toLowerCase();
let data = modeBrackets.textIsBracket[text];
if (!data) {
return null;
}
return {
range: r,
open: data.open,
close: data.close,
isOpen: modeBrackets.textIsOpenBracket[text]
};
}
/**
* Returns:
* - -1 => the line consists of whitespace
* - otherwise => the indent level is returned value
*/
static computeIndentLevel(line, tabSize) {
let indent = 0;
let i = 0;
let len = line.length;
while (i < len) {
let chCode = line.charCodeAt(i);
if (chCode === 32 /* Space */) {
indent++;
}
else if (chCode === 9 /* Tab */) {
indent = indent - indent % tabSize + tabSize;
}
else {
break;
}
i++;
}
if (i === len) {
return -1; // line only consists of whitespace
}
return indent;
}
_computeIndentLevel(lineIndex) {
return TextModel.computeIndentLevel(this._buffer.getLineContent(lineIndex + 1), this._options.tabSize);
}
getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) {
this._assertNotDisposed();
const lineCount = this.getLineCount();
if (lineNumber < 1 || lineNumber > lineCount) {
throw new Error('Illegal value for lineNumber');
}
const foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(this._languageIdentifier.id);
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--) {
let 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++) {
let 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--) {
let 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++) {
let 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) {
// 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._options.indentSize);
}
else {
up_resolveIndents(upLineNumber);
upLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, up_aboveContentLineIndent, up_belowContentLineIndent);
}
}
let downLineIndentLevel = -1;
if (goDown) {
// 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._options.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 };
}
getLinesIndentGuides(startLineNumber, endLineNumber) {
this._assertNotDisposed();
const lineCount = this.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 foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(this._languageIdentifier.id);
const offSide = Boolean(foldingRules && foldingRules.offSide);
let 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++) {
let 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 / this._options.indentSize);
continue;
}
if (aboveContentLineIndex === -2) {
aboveContentLineIndex = -1;
aboveContentLineIndent = -1;
// must find previous line with content
for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
let 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++) {
let 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) {
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 / this._options.indentSize));
}
else if (aboveContentLineIndent === belowContentLineIndent) {
// we are in between two regions
return Math.ceil(belowContentLineIndent / this._options.indentSize);
}
else {
if (offSide) {
// same level as region below
return Math.ceil(belowContentLineIndent / this._options.indentSize);
}
else {
// we are inside the region that ends below
return (1 + Math.floor(belowContentLineIndent / this._options.indentSize));
}
}
}
//#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;
TextModel.MODEL_SYNC_LIMIT = 50 * 1024 * 1024; // 50 MB
TextModel.LARGE_FILE_SIZE_THRESHOLD = 20 * 1024 * 1024; // 20 MB;
TextModel.LARGE_FILE_LINE_COUNT_THRESHOLD = 300 * 1000; // 300K lines
TextModel.DEFAULT_CREATION_OPTIONS = {
isForSimpleWidget: false,
tabSize: editorOptions_1.EDITOR_MODEL_DEFAULTS.tabSize,
indentSize: editorOptions_1.EDITOR_MODEL_DEFAULTS.indentSize,
insertSpaces: editorOptions_1.EDITOR_MODEL_DEFAULTS.insertSpaces,
detectIndentation: false,
defaultEOL: 1 /* LF */,
trimAutoWhitespace: editorOptions_1.EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
largeFileOptimizations: editorOptions_1.EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
};
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 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);
}
_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) {
const versionId = host.getVersionId();
const result = this._intervalSearch(start, end, filterOwnerId, filterOutValidation, versionId);
return this._ensureNodesHaveRanges(host, result);
}
_intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId) {
const r0 = this._decorationsTree0.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId);
const r1 = this._decorationsTree1.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId);
const r2 = this._injectedTextDecorationsTree.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId);
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);
return this._ensureNodesHaveRanges(host, result);
}
getAllInjectedText(host, filterOwnerId) {
const versionId = host.getVersionId();
const result = this._injectedTextDecorationsTree.search(filterOwnerId, false, versionId);
return this._ensureNodesHaveRanges(host, result);
}
getAll(host, filterOwnerId, filterOutValidation, overviewRulerOnly) {
const versionId = host.getVersionId();
const result = this._search(filterOwnerId, filterOutValidation, overviewRulerOnly, versionId);
return this._ensureNodesHaveRanges(host, result);
}
_search(filterOwnerId, filterOutValidation, overviewRulerOnly, cachedVersionId) {
if (overviewRulerOnly) {
return this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId);
}
else {
const r0 = this._decorationsTree0.search(filterOwnerId, filterOutValidation, cachedVersionId);
const r1 = this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId);
const r2 = this._injectedTextDecorationsTree.search(filterOwnerId, filterOutValidation, cachedVersionId);
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;
}
let c = color ? theme.getColor(color.id) : null;
if (!c) {
return '';
}
return c.toString();
}
}
exports.ModelDecorationOverviewRulerOptions = ModelDecorationOverviewRulerOptions;
class ModelDecorationMinimapOptions extends DecorationOptions {
constructor(options) {
super(options);
this.position = options.position;
}
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 {
constructor(options) {
this.content = options.content || '';
this.inlineClassName = options.inlineClassName || null;
this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false;
}
static from(options) {
if (options instanceof ModelDecorationInjectedTextOptions) {
return options;
}
return new ModelDecorationInjectedTextOptions(options);
}
}
exports.ModelDecorationInjectedTextOptions = ModelDecorationInjectedTextOptions;
class ModelDecorationOptions {
constructor(options) {
this.description = options.description;
this.stickiness = options.stickiness || 0 /* AlwaysGrowsWhenTypingAtEdges */;
this.zIndex = options.zIndex || 0;
this.className = options.className ? cleanClassName(options.className) : null;
this.hoverMessage = options.hoverMessage || null;
this.glyphMarginHoverMessage = options.glyphMarginHoverMessage || 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.glyphMarginClassName = options.glyphMarginClassName ? cleanClassName(options.glyphMarginClassName) : null;
this.linesDecorationsClassName = options.linesDecorationsClassName ? cleanClassName(options.linesDecorationsClassName) : 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;
}
static register(options) {
return new ModelDecorationOptions(options);
}
static createDynamic(options) {
return new ModelDecorationOptions(options);
}
}
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 /* AlwaysGrowsWhenTypingAtEdges */ }),
ModelDecorationOptions.register({ description: 'tracked-range-never-grows-when-typing-at-edges', stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ }),
ModelDecorationOptions.register({ description: 'tracked-range-grows-only-when-typing-before', stickiness: 2 /* GrowsOnlyWhenTypingBefore */ }),
ModelDecorationOptions.register({ description: 'tracked-range-grows-only-when-typing-after', stickiness: 3 /* 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._shouldFire = false;
this._affectsMinimap = false;
this._affectsOverviewRuler = false;
}
beginDeferredEmit() {
this._deferredCnt++;
}
endDeferredEmit() {
var _a;
this._deferredCnt--;
if (this._deferredCnt === 0) {
if (this._shouldFire) {
this.handleBeforeFire(this._affectedInjectedTextLines);
const event = {
affectsMinimap: this._affectsMinimap,
affectsOverviewRuler: this._affectsOverviewRuler
};
this._shouldFire = false;
this._affectsMinimap = false;
this._affectsOverviewRuler = false;
this._actual.fire(event);
}
(_a = this._affectedInjectedTextLines) === null || _a === void 0 ? void 0 : _a.clear();
this._affectedInjectedTextLines = null;
}
}
recordLineAffectedByInjectedText(lineNumber) {
if (!this._affectedInjectedTextLines) {
this._affectedInjectedTextLines = new Set();
}
this._affectedInjectedTextLines.add(lineNumber);
}
checkAffectedAndFire(options) {
if (!this._affectsMinimap) {
this._affectsMinimap = options.minimap && options.minimap.position ? true : false;
}
if (!this._affectsOverviewRuler) {
this._affectsOverviewRuler = options.overviewRuler && options.overviewRuler.color ? true : false;
}
this._shouldFire = true;
}
fire() {
this._affectsMinimap = true;
this._affectsOverviewRuler = true;
this._shouldFire = true;
}
}
exports.DidChangeDecorationsEmitter = DidChangeDecorationsEmitter;
//#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);
}
}
exports.DidChangeContentEmitter = DidChangeContentEmitter;
});
/*---------------------------------------------------------------------------------------------
* 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/controller/cursorCommon*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,8/*vs/base/common/strings*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,31/*vs/editor/common/model/textModel*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, errors_1, strings, position_1, range_1, selection_1, textModel_1, languageConfigurationRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isQuote = exports.CursorColumns = exports.EditOperationResult = exports.CursorState = exports.PartialViewCursorState = exports.PartialModelCursorState = exports.CursorContext = exports.SingleCursorState = exports.CursorConfiguration = void 0;
const autoCloseAlways = () => true;
const autoCloseNever = () => false;
const autoCloseBeforeWhitespace = (chr) => (chr === ' ' || chr === '\t');
class CursorConfiguration {
constructor(languageIdentifier, modelOptions, configuration) {
this._cursorMoveConfigurationBrand = undefined;
this._languageIdentifier = languageIdentifier;
const options = configuration.options;
const layoutInfo = options.get(129 /* layoutInfo */);
this.readOnly = options.get(79 /* readOnly */);
this.tabSize = modelOptions.tabSize;
this.indentSize = modelOptions.indentSize;
this.insertSpaces = modelOptions.insertSpaces;
this.stickyTabStops = options.get(103 /* stickyTabStops */);
this.lineHeight = options.get(57 /* lineHeight */);
this.pageSize = Math.max(1, Math.floor(layoutInfo.height / this.lineHeight) - 2);
this.useTabStops = options.get(114 /* useTabStops */);
this.wordSeparators = options.get(115 /* wordSeparators */);
this.emptySelectionClipboard = options.get(30 /* emptySelectionClipboard */);
this.copyWithSyntaxHighlighting = options.get(19 /* copyWithSyntaxHighlighting */);
this.multiCursorMergeOverlapping = options.get(67 /* multiCursorMergeOverlapping */);
this.multiCursorPaste = options.get(69 /* multiCursorPaste */);
this.autoClosingBrackets = options.get(5 /* autoClosingBrackets */);
this.autoClosingQuotes = options.get(8 /* autoClosingQuotes */);
this.autoClosingDelete = options.get(6 /* autoClosingDelete */);
this.autoClosingOvertype = options.get(7 /* autoClosingOvertype */);
this.autoSurround = options.get(11 /* autoSurround */);
this.autoIndent = options.get(9 /* autoIndent */);
this.surroundingPairs = {};
this._electricChars = null;
this.shouldAutoCloseBefore = {
quote: CursorConfiguration._getShouldAutoClose(languageIdentifier, this.autoClosingQuotes),
bracket: CursorConfiguration._getShouldAutoClose(languageIdentifier, this.autoClosingBrackets)
};
this.autoClosingPairs = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getAutoClosingPairs(languageIdentifier.id);
let surroundingPairs = CursorConfiguration._getSurroundingPairs(languageIdentifier);
if (surroundingPairs) {
for (const pair of surroundingPairs) {
this.surroundingPairs[pair.open] = pair.close;
}
}
}
static shouldRecreate(e) {
return (e.hasChanged(129 /* layoutInfo */)
|| e.hasChanged(115 /* wordSeparators */)
|| e.hasChanged(30 /* emptySelectionClipboard */)
|| e.hasChanged(67 /* multiCursorMergeOverlapping */)
|| e.hasChanged(69 /* multiCursorPaste */)
|| e.hasChanged(5 /* autoClosingBrackets */)
|| e.hasChanged(8 /* autoClosingQuotes */)
|| e.hasChanged(6 /* autoClosingDelete */)
|| e.hasChanged(7 /* autoClosingOvertype */)
|| e.hasChanged(11 /* autoSurround */)
|| e.hasChanged(114 /* useTabStops */)
|| e.hasChanged(57 /* lineHeight */)
|| e.hasChanged(79 /* readOnly */));
}
get electricChars() {
if (!this._electricChars) {
this._electricChars = {};
let electricChars = CursorConfiguration._getElectricCharacters(this._languageIdentifier);
if (electricChars) {
for (const char of electricChars) {
this._electricChars[char] = true;
}
}
}
return this._electricChars;
}
normalizeIndentation(str) {
return textModel_1.TextModel.normalizeIndentation(str, this.indentSize, this.insertSpaces);
}
static _getElectricCharacters(languageIdentifier) {
try {
return languageConfigurationRegistry_1.LanguageConfigurationRegistry.getElectricCharacters(languageIdentifier.id);
}
catch (e) {
(0, errors_1.onUnexpectedError)(e);
return null;
}
}
static _getShouldAutoClose(languageIdentifier, autoCloseConfig) {
switch (autoCloseConfig) {
case 'beforeWhitespace':
return autoCloseBeforeWhitespace;
case 'languageDefined':
return CursorConfiguration._getLanguageDefinedShouldAutoClose(languageIdentifier);
case 'always':
return autoCloseAlways;
case 'never':
return autoCloseNever;
}
}
static _getLanguageDefinedShouldAutoClose(languageIdentifier) {
try {
const autoCloseBeforeSet = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getAutoCloseBeforeSet(languageIdentifier.id);
return c => autoCloseBeforeSet.indexOf(c) !== -1;
}
catch (e) {
(0, errors_1.onUnexpectedError)(e);
return autoCloseNever;
}
}
static _getSurroundingPairs(languageIdentifier) {
try {
return languageConfigurationRegistry_1.LanguageConfigurationRegistry.getSurroundingPairs(languageIdentifier.id);
}
catch (e) {
(0, errors_1.onUnexpectedError)(e);
return null;
}
}
}
exports.CursorConfiguration = CursorConfiguration;
/**
* Represents the cursor state on either the model or on the view model.
*/
class SingleCursorState {
constructor(selectionStart, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns) {
this._singleCursorStateBrand = undefined;
this.selectionStart = selectionStart;
this.selectionStartLeftoverVisibleColumns = selectionStartLeftoverVisibleColumns;
this.position = position;
this.leftoverVisibleColumns = leftoverVisibleColumns;
this.selection = SingleCursorState._computeSelection(this.selectionStart, this.position);
}
equals(other) {
return (this.selectionStartLeftoverVisibleColumns === other.selectionStartLeftoverVisibleColumns
&& this.leftoverVisibleColumns === other.leftoverVisibleColumns
&& 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.selectionStartLeftoverVisibleColumns, new position_1.Position(lineNumber, column), leftoverVisibleColumns);
}
else {
// move everything
return new SingleCursorState(new range_1.Range(lineNumber, column, lineNumber, column), leftoverVisibleColumns, new position_1.Position(lineNumber, column), leftoverVisibleColumns);
}
}
static _computeSelection(selectionStart, position) {
let startLineNumber, startColumn, endLineNumber, endColumn;
if (selectionStart.isEmpty()) {
startLineNumber = selectionStart.startLineNumber;
startColumn = selectionStart.startColumn;
endLineNumber = position.lineNumber;
endColumn = position.column;
}
else {
if (position.isBeforeOrEqual(selectionStart.getStartPosition())) {
startLineNumber = selectionStart.endLineNumber;
startColumn = selectionStart.endColumn;
endLineNumber = position.lineNumber;
endColumn = position.column;
}
else {
startLineNumber = selectionStart.startLineNumber;
startColumn = selectionStart.startColumn;
endLineNumber = position.lineNumber;
endColumn = position.column;
}
}
return new selection_1.Selection(startLineNumber, startColumn, endLineNumber, endColumn);
}
}
exports.SingleCursorState = SingleCursorState;
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;
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;
class CursorState {
constructor(modelState, viewState) {
this._cursorStateBrand = undefined;
this.modelState = modelState;
this.viewState = viewState;
}
static fromModelState(modelState) {
return new PartialModelCursorState(modelState);
}
static fromViewState(viewState) {
return new PartialViewCursorState(viewState);
}
static fromModelSelection(modelSelection) {
const selectionStartLineNumber = modelSelection.selectionStartLineNumber;
const selectionStartColumn = modelSelection.selectionStartColumn;
const positionLineNumber = modelSelection.positionLineNumber;
const positionColumn = modelSelection.positionColumn;
const modelState = new SingleCursorState(new range_1.Range(selectionStartLineNumber, selectionStartColumn, selectionStartLineNumber, selectionStartColumn), 0, new position_1.Position(positionLineNumber, positionColumn), 0);
return CursorState.fromModelState(modelState);
}
static fromModelSelections(modelSelections) {
let states = [];
for (let i = 0, len = modelSelections.length; i < len; i++) {
states[i] = this.fromModelSelection(modelSelections[i]);
}
return states;
}
equals(other) {
return (this.viewState.equals(other.viewState) && this.modelState.equals(other.modelState));
}
}
exports.CursorState = CursorState;
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;
/**
* Common operations that work and make sense both on the model and on the view model.
*/
class CursorColumns {
static visibleColumnFromColumn(lineContent, column, tabSize) {
const lineContentLength = lineContent.length;
const endOffset = column - 1 < lineContentLength ? column - 1 : lineContentLength;
let result = 0;
let i = 0;
while (i < endOffset) {
const codePoint = strings.getNextCodePoint(lineContent, endOffset, i);
i += (codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
if (codePoint === 9 /* Tab */) {
result = CursorColumns.nextRenderTabStop(result, tabSize);
}
else {
let graphemeBreakType = strings.getGraphemeBreakType(codePoint);
while (i < endOffset) {
const nextCodePoint = strings.getNextCodePoint(lineContent, endOffset, i);
const nextGraphemeBreakType = strings.getGraphemeBreakType(nextCodePoint);
if (strings.breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) {
break;
}
i += (nextCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
graphemeBreakType = nextGraphemeBreakType;
}
if (strings.isFullWidthCharacter(codePoint) || strings.isEmojiImprecise(codePoint)) {
result = result + 2;
}
else {
result = result + 1;
}
}
}
return result;
}
/**
* Returns an array that maps one based columns to one based visible columns. The entry at position 0 is -1.
*/
static visibleColumnsByColumns(lineContent, tabSize) {
const endOffset = lineContent.length;
let result = new Array();
result.push(-1);
let pos = 0;
let i = 0;
while (i < endOffset) {
const codePoint = strings.getNextCodePoint(lineContent, endOffset, i);
i += (codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
result.push(pos);
if (codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */) {
result.push(pos);
}
if (codePoint === 9 /* Tab */) {
pos = CursorColumns.nextRenderTabStop(pos, tabSize);
}
else {
let graphemeBreakType = strings.getGraphemeBreakType(codePoint);
while (i < endOffset) {
const nextCodePoint = strings.getNextCodePoint(lineContent, endOffset, i);
const nextGraphemeBreakType = strings.getGraphemeBreakType(nextCodePoint);
if (strings.breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) {
break;
}
i += (nextCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
result.push(pos);
if (codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */) {
result.push(pos);
}
graphemeBreakType = nextGraphemeBreakType;
}
if (strings.isFullWidthCharacter(codePoint) || strings.isEmojiImprecise(codePoint)) {
pos = pos + 2;
}
else {
pos = pos + 1;
}
}
}
result.push(pos);
return result;
}
static visibleColumnFromColumn2(config, model, position) {
return this.visibleColumnFromColumn(model.getLineContent(position.lineNumber), position.column, config.tabSize);
}
static columnFromVisibleColumn(lineContent, visibleColumn, tabSize) {
if (visibleColumn <= 0) {
return 1;
}
const lineLength = lineContent.length;
let beforeVisibleColumn = 0;
let beforeColumn = 1;
let i = 0;
while (i < lineLength) {
const codePoint = strings.getNextCodePoint(lineContent, lineLength, i);
i += (codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
let afterVisibleColumn;
if (codePoint === 9 /* Tab */) {
afterVisibleColumn = CursorColumns.nextRenderTabStop(beforeVisibleColumn, tabSize);
}
else {
let graphemeBreakType = strings.getGraphemeBreakType(codePoint);
while (i < lineLength) {
const nextCodePoint = strings.getNextCodePoint(lineContent, lineLength, i);
const nextGraphemeBreakType = strings.getGraphemeBreakType(nextCodePoint);
if (strings.breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) {
break;
}
i += (nextCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
graphemeBreakType = nextGraphemeBreakType;
}
if (strings.isFullWidthCharacter(codePoint) || strings.isEmojiImprecise(codePoint)) {
afterVisibleColumn = beforeVisibleColumn + 2;
}
else {
afterVisibleColumn = beforeVisibleColumn + 1;
}
}
const afterColumn = i + 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 lineLength + 1;
}
static columnFromVisibleColumn2(config, model, lineNumber, visibleColumn) {
let result = this.columnFromVisibleColumn(model.getLineContent(lineNumber), visibleColumn, config.tabSize);
let minColumn = model.getLineMinColumn(lineNumber);
if (result < minColumn) {
return minColumn;
}
let maxColumn = model.getLineMaxColumn(lineNumber);
if (result > maxColumn) {
return maxColumn;
}
return result;
}
/**
* ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns)
*/
static nextRenderTabStop(visibleColumn, tabSize) {
return visibleColumn + tabSize - visibleColumn % tabSize;
}
/**
* ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns)
*/
static nextIndentTabStop(visibleColumn, indentSize) {
return visibleColumn + indentSize - visibleColumn % indentSize;
}
/**
* ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns)
*/
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)
*/
static prevIndentTabStop(column, indentSize) {
return Math.max(0, column - 1 - (column - 1) % indentSize);
}
}
exports.CursorColumns = CursorColumns;
function isQuote(ch) {
return (ch === '\'' || ch === '"' || ch === '`');
}
exports.isQuote = isQuote;
});
/*---------------------------------------------------------------------------------------------
* 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/common/commands/shiftCommand*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,40/*vs/editor/common/controller/cursorCommon*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, strings, cursorCommon_1, range_1, selection_1, languageConfigurationRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ShiftCommand = exports.cachedStringRepeat = 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];
}
exports.cachedStringRepeat = cachedStringRepeat;
class ShiftCommand {
constructor(range, opts) {
this._opts = opts;
this._selection = range;
this._selectionId = null;
this._useLastEditRangeForCursorEndPosition = false;
this._selectionStartColumnStaysPut = false;
}
static unshiftIndent(line, column, tabSize, indentSize, insertSpaces) {
// Determine the visible column where the content starts
const contentStartVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(line, column, tabSize);
if (insertSpaces) {
const indent = cachedStringRepeat(' ', indentSize);
const desiredTabStop = cursorCommon_1.CursorColumns.prevIndentTabStop(contentStartVisibleColumn, indentSize);
const indentCount = desiredTabStop / indentSize; // will be an integer
return cachedStringRepeat(indent, indentCount);
}
else {
const indent = '\t';
const desiredTabStop = cursorCommon_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 = cursorCommon_1.CursorColumns.visibleColumnFromColumn(line, column, tabSize);
if (insertSpaces) {
const indent = cachedStringRepeat(' ', indentSize);
const desiredTabStop = cursorCommon_1.CursorColumns.nextIndentTabStop(contentStartVisibleColumn, indentSize);
const indentCount = desiredTabStop / indentSize; // will be an integer
return cachedStringRepeat(indent, indentCount);
}
else {
const indent = '\t';
const desiredTabStop = cursorCommon_1.CursorColumns.nextRenderTabStop(contentStartVisibleColumn, tabSize);
const indentCount = desiredTabStop / tabSize; // will be an integer
return cachedStringRepeat(indent, indentCount);
}
}
_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;
let 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) {
let contentStartVisibleColumn = cursorCommon_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.isCheapToTokenize(lineNumber - 1)) {
let enterAction = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(this._opts.autoIndent, model, new range_1.Range(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1), lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)));
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 /* 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 /* 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.unshiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces);
}
else {
desiredIndent = ShiftCommand.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 /* 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) {
let 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
let initialStartColumn = this._selection.startColumn;
let resultStartColumn = result.startColumn;
if (resultStartColumn <= initialStartColumn) {
return result;
}
if (result.getDirection() === 0 /* 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;
});
/*---------------------------------------------------------------------------------------------
* 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/controller/cursorAtomicMoveOperations*/], __M([0/*require*/,1/*exports*/,40/*vs/editor/common/controller/cursorCommon*/]), function (require, exports, cursorCommon_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 /* Space */:
visibleColumn += 1;
break;
case 9 /* Tab */:
// Skip to the next multiple of tabSize.
visibleColumn = cursorCommon_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 /* Left */:
left = true;
break;
case 1 /* Right */:
left = false;
break;
case 2 /* 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 /* Space */:
currentVisibleColumn += 1;
break;
case 9 /* Tab */:
currentVisibleColumn = cursorCommon_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 = cursorCommon_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 /* Space */:
currentVisibleColumn += 1;
break;
case 9 /* Tab */:
currentVisibleColumn = cursorCommon_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[550/*vs/editor/common/controller/cursorColumnSelection*/], __M([0/*require*/,1/*exports*/,40/*vs/editor/common/controller/cursorCommon*/,13/*vs/editor/common/core/position*/,3/*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) {
let lineCount = Math.abs(toLineNumber - fromLineNumber) + 1;
let reversed = (fromLineNumber > toLineNumber);
let isRTL = (fromVisibleColumn > toVisibleColumn);
let isLTR = (fromVisibleColumn < toVisibleColumn);
let result = [];
// console.log(`fromVisibleColumn: ${fromVisibleColumn}, toVisibleColumn: ${toVisibleColumn}`);
for (let i = 0; i < lineCount; i++) {
let lineNumber = fromLineNumber + (reversed ? -i : i);
let startColumn = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, fromVisibleColumn);
let endColumn = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, toVisibleColumn);
let visibleStartColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, new position_1.Position(lineNumber, startColumn));
let visibleEndColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, 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, 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, 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 = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, 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[185/*vs/editor/common/controller/cursorMoveOperations*/], __M([0/*require*/,1/*exports*/,40/*vs/editor/common/controller/cursorCommon*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,8/*vs/base/common/strings*/,243/*vs/editor/common/controller/cursorAtomicMoveOperations*/]), function (require, exports, cursorCommon_1, position_1, range_1, strings, cursorAtomicMoveOperations_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 /* 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 /* 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 /* 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 /* Right */);
const r = MoveOperations.right(config, model, normalizedPos);
lineNumber = r.lineNumber;
column = r.column;
}
return cursor.move(inSelectionMode, lineNumber, column, 0);
}
static down(config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnLastLine) {
const currentVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns;
const lineCount = model.getLineCount();
const wasOnLastPosition = (lineNumber === lineCount && column === model.getLineMaxColumn(lineNumber));
lineNumber = lineNumber + count;
if (lineNumber > lineCount) {
lineNumber = lineCount;
if (allowMoveOnLastLine) {
column = model.getLineMaxColumn(lineNumber);
}
else {
column = Math.min(model.getLineMaxColumn(lineNumber), column);
}
}
else {
column = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, currentVisibleColumn);
}
if (wasOnLastPosition) {
leftoverVisibleColumns = 0;
}
else {
leftoverVisibleColumns = currentVisibleColumn - cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize);
}
return new CursorPosition(lineNumber, column, leftoverVisibleColumns);
}
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 r = MoveOperations.down(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true);
return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns);
}
static translateDown(config, model, cursor) {
let selection = cursor.selection;
let selectionStart = MoveOperations.down(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);
let 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), selectionStart.leftoverVisibleColumns, new position_1.Position(position.lineNumber, position.column), position.leftoverVisibleColumns);
}
static up(config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnFirstLine) {
const currentVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns;
const wasOnFirstPosition = (lineNumber === 1 && column === 1);
lineNumber = lineNumber - count;
if (lineNumber < 1) {
lineNumber = 1;
if (allowMoveOnFirstLine) {
column = model.getLineMinColumn(lineNumber);
}
else {
column = Math.min(model.getLineMaxColumn(lineNumber), column);
}
}
else {
column = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, currentVisibleColumn);
}
if (wasOnFirstPosition) {
leftoverVisibleColumns = 0;
}
else {
leftoverVisibleColumns = currentVisibleColumn - cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize);
}
return new CursorPosition(lineNumber, column, leftoverVisibleColumns);
}
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;
}
let 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) {
let selection = cursor.selection;
let selectionStart = MoveOperations.up(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);
let 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), 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) {
let lineNumber = cursor.position.lineNumber;
let minColumn = model.getLineMinColumn(lineNumber);
let firstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(lineNumber) || minColumn;
let column;
let 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) {
let lineNumber = cursor.position.lineNumber;
let maxColumn = model.getLineMaxColumn(lineNumber);
return cursor.move(inSelectionMode, lineNumber, maxColumn, sticky ? 1073741824 /* 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) {
let lastLineNumber = model.getLineCount();
let 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[186/*vs/editor/common/controller/cursorDeleteOperations*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,95/*vs/editor/common/commands/replaceCommand*/,40/*vs/editor/common/controller/cursorCommon*/,185/*vs/editor/common/controller/cursorMoveOperations*/,3/*vs/editor/common/core/range*/,13/*vs/editor/common/core/position*/]), function (require, exports, strings, replaceCommand_1, cursorCommon_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) {
let commands = [];
let shouldPushStackElementBefore = (prevEditOperationType !== 3 /* DeletingRight */);
for (let i = 0, len = selections.length; i < len; i++) {
const selection = selections[i];
let deleteSelection = selection;
if (deleteSelection.isEmpty()) {
let position = selection.getPosition();
let 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) {
let 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 /* DeletingLeft */);
for (let i = 0, len = selections.length; i < len; i++) {
let 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 = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, position);
const toVisibleColumn = cursorCommon_1.CursorColumns.prevIndentTabStop(fromVisibleColumn, config.indentSize);
const toColumn = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, 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) {
let commands = [];
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
let 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) {
// Cutting the last line & there are more than 1 lines in the model
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);
}
let deleteSelection = new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn);
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 /* 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[187/*vs/editor/common/controller/cursorTypeOperations*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,8/*vs/base/common/strings*/,95/*vs/editor/common/commands/replaceCommand*/,184/*vs/editor/common/commands/shiftCommand*/,376/*vs/editor/common/commands/surroundSelectionCommand*/,40/*vs/editor/common/controller/cursorCommon*/,109/*vs/editor/common/controller/wordCharacterClassifier*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,112/*vs/editor/common/modes/languageConfiguration*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, errors_1, strings, replaceCommand_1, shiftCommand_1, surroundSelectionCommand_1, cursorCommon_1, wordCharacterClassifier_1, range_1, selection_1, languageConfiguration_1, languageConfigurationRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeWithAutoClosingCommand = exports.TypeOperations = void 0;
class TypeOperations {
static indent(config, model, selections) {
if (model === null || selections === null) {
return [];
}
let 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
});
}
return commands;
}
static outdent(config, model, selections) {
let 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
});
}
return commands;
}
static shiftIndent(config, indentation, count) {
count = count || 1;
return shiftCommand_1.ShiftCommand.shiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces);
}
static unshiftIndent(config, indentation, count) {
count = count || 1;
return shiftCommand_1.ShiftCommand.unshiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces);
}
static _distributedPaste(config, model, selections, text) {
let 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 /* Other */, commands, {
shouldPushStackElementBefore: true,
shouldPushStackElementAfter: true
});
}
static _simplePaste(config, model, selections, text, pasteOnNewLine) {
let commands = [];
for (let i = 0, len = selections.length; i < len; i++) {
const selection = selections[i];
let 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
let 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 /* Other */, commands, {
shouldPushStackElementBefore: true,
shouldPushStackElementAfter: true
});
}
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 /* LineFeed */) {
text = text.substr(0, text.length - 1);
}
// Remove trailing \r if present
if (text.charCodeAt(text.length - 1) === 13 /* CarriageReturn */) {
text = text.substr(0, text.length - 1);
}
let lines = strings.splitLines(text);
if (lines.length === selections.length) {
return lines;
}
}
return null;
}
static paste(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 _goodIndentForLine(config, model, lineNumber) {
let action = null;
let indentation = '';
const expectedIndentAction = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getInheritIndentForLine(config.autoIndent, model, lineNumber, false);
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 = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(config.autoIndent, model, new range_1.Range(lastLineNumber, maxColumn, lastLineNumber, maxColumn));
if (expectedEnterAction) {
indentation = expectedEnterAction.indentation + expectedEnterAction.appendText;
}
}
if (action) {
if (action === languageConfiguration_1.IndentAction.Indent) {
indentation = TypeOperations.shiftIndent(config, indentation);
}
if (action === languageConfiguration_1.IndentAction.Outdent) {
indentation = TypeOperations.unshiftIndent(config, indentation);
}
indentation = config.normalizeIndentation(indentation);
}
if (!indentation) {
return null;
}
return indentation;
}
static _replaceJumpToNextIndent(config, model, selection, insertsAutoWhitespace) {
let typeText = '';
let position = selection.getStartPosition();
if (config.insertSpaces) {
let visibleColumnFromColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, position);
let indentSize = config.indentSize;
let spacesCnt = indentSize - (visibleColumnFromColumn % indentSize);
for (let i = 0; i < spacesCnt; i++) {
typeText += ' ';
}
}
else {
typeText = '\t';
}
return new replaceCommand_1.ReplaceCommand(selection, typeText, insertsAutoWhitespace);
}
static tab(config, model, selections) {
let commands = [];
for (let i = 0, len = selections.length; i < len; i++) {
const selection = selections[i];
if (selection.isEmpty()) {
let lineText = model.getLineContent(selection.startLineNumber);
if (/^\s*$/.test(lineText) && model.isCheapToTokenize(selection.startLineNumber)) {
let goodIndent = this._goodIndentForLine(config, model, selection.startLineNumber);
goodIndent = goodIndent || '\t';
let 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) {
let 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
});
}
}
return commands;
}
static compositionType(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 /* TypingOther */, commands, {
shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, 4 /* 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);
}
static _typeCommand(range, text, keepPosition) {
if (keepPosition) {
return new replaceCommand_1.ReplaceCommandWithoutChangingPosition(range, text, true);
}
else {
return new replaceCommand_1.ReplaceCommand(range, text, true);
}
}
static _enter(config, model, keepPosition, range) {
if (config.autoIndent === 0 /* None */) {
return TypeOperations._typeCommand(range, '\n', keepPosition);
}
if (!model.isCheapToTokenize(range.getStartPosition().lineNumber) || config.autoIndent === 1 /* Keep */) {
let lineText = model.getLineContent(range.startLineNumber);
let indentation = strings.getLeadingWhitespace(lineText).substring(0, range.startColumn - 1);
return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation), keepPosition);
}
const r = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(config.autoIndent, model, range);
if (r) {
if (r.indentAction === languageConfiguration_1.IndentAction.None) {
// Nothing special
return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(r.indentation + r.appendText), keepPosition);
}
else if (r.indentAction === languageConfiguration_1.IndentAction.Indent) {
// Indent once
return TypeOperations._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 = TypeOperations.unshiftIndent(config, r.indentation);
return TypeOperations._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 /* Full */) {
const ir = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentForEnter(config.autoIndent, model, range, {
unshiftIndent: (indent) => {
return TypeOperations.unshiftIndent(config, indent);
},
shiftIndent: (indent) => {
return TypeOperations.shiftIndent(config, indent);
},
normalizeIndentation: (indent) => {
return config.normalizeIndentation(indent);
}
});
if (ir) {
let oldEndViewColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, 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 TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation), keepPosition);
}
static _isAutoIndentType(config, model, selections) {
if (config.autoIndent < 4 /* Full */) {
return false;
}
for (let i = 0, len = selections.length; i < len; i++) {
if (!model.isCheapToTokenize(selections[i].getEndPosition().lineNumber)) {
return false;
}
}
return true;
}
static _runAutoIndentType(config, model, range, ch) {
const currentIndentation = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentationAtPosition(model, range.startLineNumber, range.startColumn);
const actualIndentation = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentActionForType(config.autoIndent, model, range, ch, {
shiftIndent: (indentation) => {
return TypeOperations.shiftIndent(config, indentation);
},
unshiftIndent: (indentation) => {
return TypeOperations.unshiftIndent(config, indentation);
},
});
if (actualIndentation === null) {
return null;
}
if (actualIndentation !== config.normalizeIndentation(currentIndentation)) {
const firstNonWhitespace = model.getLineFirstNonWhitespaceColumn(range.startLineNumber);
if (firstNonWhitespace === 0) {
return TypeOperations._typeCommand(new range_1.Range(range.startLineNumber, 1, range.endLineNumber, range.endColumn), config.normalizeIndentation(actualIndentation) + ch, false);
}
else {
return TypeOperations._typeCommand(new range_1.Range(range.startLineNumber, 1, range.endLineNumber, range.endColumn), config.normalizeIndentation(actualIndentation) +
model.getLineContent(range.startLineNumber).substring(firstNonWhitespace - 1, range.startColumn - 1) + ch, false);
}
}
return null;
}
static _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 /* Null */;
if (beforeCharacter === 92 /* 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;
}
static _runAutoClosingOvertype(prevEditOperationType, config, model, selections, ch) {
let 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 /* TypingOther */, commands, {
shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, 4 /* TypingOther */),
shouldPushStackElementAfter: false
});
}
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;
}
static _findAutoClosingPairOpen(config, model, positions, ch) {
const autoClosingPairCandidates = config.autoClosingPairs.autoClosingPairsOpenByEnd.get(ch);
if (!autoClosingPairCandidates) {
return null;
}
// Determine which auto-closing pair it is
let autoClosingPair = null;
for (const autoClosingPairCandidate of autoClosingPairCandidates) {
if (autoClosingPair === null || autoClosingPairCandidate.open.length > autoClosingPair.open.length) {
let candidateIsMatch = true;
for (const position of positions) {
const relevantText = model.getValueInRange(new range_1.Range(position.lineNumber, position.column - autoClosingPairCandidate.open.length + 1, position.lineNumber, position.column));
if (relevantText + ch !== autoClosingPairCandidate.open) {
candidateIsMatch = false;
break;
}
}
if (candidateIsMatch) {
autoClosingPair = autoClosingPairCandidate;
}
}
}
return autoClosingPair;
}
static _findSubAutoClosingPairClose(config, autoClosingPair) {
if (autoClosingPair.open.length <= 1) {
return '';
}
const lastChar = autoClosingPair.close.charAt(autoClosingPair.close.length - 1);
// get candidates with the same last character as close
const subPairCandidates = config.autoClosingPairs.autoClosingPairsCloseByEnd.get(lastChar) || [];
let subPairMatch = null;
for (const x of subPairCandidates) {
if (x.open !== autoClosingPair.open && autoClosingPair.open.includes(x.open) && autoClosingPair.close.endsWith(x.close)) {
if (!subPairMatch || x.open.length > subPairMatch.open.length) {
subPairMatch = x;
}
}
}
if (subPairMatch) {
return subPairMatch.close;
}
else {
return '';
}
}
static _getAutoClosingPairClose(config, model, selections, ch, insertOpenCharacter) {
const chIsQuote = (0, cursorCommon_1.isQuote)(ch);
const autoCloseConfig = chIsQuote ? config.autoClosingQuotes : config.autoClosingBrackets;
if (autoCloseConfig === 'never') {
return null;
}
const autoClosingPair = this._findAutoClosingPairOpen(config, model, selections.map(s => s.getPosition()), ch);
if (!autoClosingPair) {
return null;
}
const subAutoClosingPairClose = this._findSubAutoClosingPairClose(config, autoClosingPair);
let isSubAutoClosingPairPresent = true;
const shouldAutoCloseBefore = chIsQuote ? config.shouldAutoCloseBefore.quote : config.shouldAutoCloseBefore.bracket;
for (let i = 0, len = selections.length; i < len; i++) {
const selection = selections[i];
if (!selection.isEmpty()) {
return null;
}
const position = selection.getPosition();
const lineText = model.getLineContent(position.lineNumber);
const lineAfter = lineText.substring(position.column - 1);
if (!lineAfter.startsWith(subAutoClosingPairClose)) {
isSubAutoClosingPairPresent = false;
}
// Only consider auto closing the pair if an allowed character follows or if another autoclosed pair closing brace follows
if (lineText.length > position.column - 1) {
const characterAfter = lineText.charAt(position.column - 1);
const isBeforeCloseBrace = TypeOperations._isBeforeClosingBrace(config, lineAfter);
if (!isBeforeCloseBrace && !shouldAutoCloseBefore(characterAfter)) {
return null;
}
}
if (!model.isCheapToTokenize(position.lineNumber)) {
// Do not force tokenization
return null;
}
// Do not auto-close ' or " after a word character
if (autoClosingPair.open.length === 1 && chIsQuote && autoCloseConfig !== 'always') {
const wordSeparators = (0, wordCharacterClassifier_1.getMapForWordSeparators)(config.wordSeparators);
if (insertOpenCharacter && position.column > 1 && wordSeparators.get(lineText.charCodeAt(position.column - 2)) === 0 /* Regular */) {
return null;
}
if (!insertOpenCharacter && position.column > 2 && wordSeparators.get(lineText.charCodeAt(position.column - 3)) === 0 /* Regular */) {
return null;
}
}
model.forceTokenization(position.lineNumber);
const lineTokens = model.getLineTokens(position.lineNumber);
let shouldAutoClosePair = false;
try {
shouldAutoClosePair = languageConfigurationRegistry_1.LanguageConfigurationRegistry.shouldAutoClosePair(autoClosingPair, lineTokens, insertOpenCharacter ? position.column : position.column - 1);
}
catch (e) {
(0, errors_1.onUnexpectedError)(e);
}
if (!shouldAutoClosePair) {
return null;
}
}
if (isSubAutoClosingPairPresent) {
return autoClosingPair.close.substring(0, autoClosingPair.close.length - subAutoClosingPairClose.length);
}
else {
return autoClosingPair.close;
}
}
static _runAutoClosingOpenCharType(prevEditOperationType, config, model, selections, ch, insertOpenCharacter, autoClosingPairClose) {
let commands = [];
for (let i = 0, len = selections.length; i < len; i++) {
const selection = selections[i];
commands[i] = new TypeWithAutoClosingCommand(selection, ch, insertOpenCharacter, autoClosingPairClose);
}
return new cursorCommon_1.EditOperationResult(4 /* TypingOther */, commands, {
shouldPushStackElementBefore: true,
shouldPushStackElementAfter: false
});
}
static _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');
}
}
static _isSurroundSelectionType(config, model, selections, ch) {
if (!TypeOperations._shouldSurroundChar(config, ch) || !config.surroundingPairs.hasOwnProperty(ch)) {
return false;
}
const isTypingAQuoteCharacter = (0, cursorCommon_1.isQuote)(ch);
for (let i = 0, len = selections.length; i < len; i++) {
const selection = selections[i];
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;
}
static _runSurroundSelectionType(prevEditOperationType, config, model, selections, ch) {
let 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 /* Other */, commands, {
shouldPushStackElementBefore: true,
shouldPushStackElementAfter: true
});
}
static _isTypeInterceptorElectricChar(config, model, selections) {
if (selections.length === 1 && model.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;
}
let position = selection.getPosition();
model.forceTokenization(position.lineNumber);
let lineTokens = model.getLineTokens(position.lineNumber);
let electricAction;
try {
electricAction = languageConfigurationRegistry_1.LanguageConfigurationRegistry.onElectricCharacter(ch, lineTokens, position.column);
}
catch (e) {
(0, errors_1.onUnexpectedError)(e);
return null;
}
if (!electricAction) {
return null;
}
if (electricAction.matchOpenBracket) {
let endColumn = (lineTokens.getLineContent() + ch).lastIndexOf(electricAction.matchOpenBracket) + 1;
let match = model.findMatchingBracketUp(electricAction.matchOpenBracket, {
lineNumber: position.lineNumber,
column: endColumn
});
if (match) {
if (match.startLineNumber === position.lineNumber) {
// matched something on the same line => no change in indentation
return null;
}
let matchLine = model.getLineContent(match.startLineNumber);
let matchLineIndentation = strings.getLeadingWhitespace(matchLine);
let newIndentation = config.normalizeIndentation(matchLineIndentation);
let lineText = model.getLineContent(position.lineNumber);
let lineFirstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(position.lineNumber) || position.column;
let prefix = lineText.substring(lineFirstNonBlankColumn - 1, position.column - 1);
let typeText = newIndentation + prefix + ch;
let 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;
}
/**
* This is very similar with typing, but the character is already in the text buffer!
*/
static compositionEndWithInterceptors(prevEditOperationType, config, model, selectionsWhenCompositionStarted, selections, autoClosedCharacters) {
if (!selectionsWhenCompositionStarted || selection_1.Selection.selectionsArrEqual(selectionsWhenCompositionStarted, selections)) {
// no content was typed
return null;
}
let ch = null;
// extract last typed character
for (const selection of selections) {
if (!selection.isEmpty()) {
return null;
}
const position = selection.getPosition();
const currentChar = model.getValueInRange(new range_1.Range(position.lineNumber, position.column - 1, position.lineNumber, position.column));
if (ch === null) {
ch = currentChar;
}
else if (ch !== currentChar) {
return null;
}
}
if (!ch) {
return null;
}
if (this._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 /* TypingOther */, commands, {
shouldPushStackElementBefore: true,
shouldPushStackElementAfter: false
});
}
const autoClosingPairClose = this._getAutoClosingPairClose(config, model, selections, ch, false);
if (autoClosingPairClose !== null) {
return this._runAutoClosingOpenCharType(prevEditOperationType, config, model, selections, ch, false, autoClosingPairClose);
}
return null;
}
static typeWithInterceptors(isDoingComposition, prevEditOperationType, config, model, selections, autoClosedCharacters, ch) {
if (!isDoingComposition && ch === '\n') {
let commands = [];
for (let i = 0, len = selections.length; i < len; i++) {
commands[i] = TypeOperations._enter(config, model, false, selections[i]);
}
return new cursorCommon_1.EditOperationResult(4 /* TypingOther */, commands, {
shouldPushStackElementBefore: true,
shouldPushStackElementAfter: false,
});
}
if (!isDoingComposition && this._isAutoIndentType(config, model, selections)) {
let commands = [];
let autoIndentFails = false;
for (let i = 0, len = selections.length; i < len; i++) {
commands[i] = this._runAutoIndentType(config, model, selections[i], ch);
if (!commands[i]) {
autoIndentFails = true;
break;
}
}
if (!autoIndentFails) {
return new cursorCommon_1.EditOperationResult(4 /* TypingOther */, commands, {
shouldPushStackElementBefore: true,
shouldPushStackElementAfter: false,
});
}
}
if (!isDoingComposition && this._isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch)) {
return this._runAutoClosingOvertype(prevEditOperationType, config, model, selections, ch);
}
if (!isDoingComposition) {
const autoClosingPairClose = this._getAutoClosingPairClose(config, model, selections, ch, true);
if (autoClosingPairClose) {
return this._runAutoClosingOpenCharType(prevEditOperationType, config, model, selections, ch, true, autoClosingPairClose);
}
}
if (this._isSurroundSelectionType(config, model, selections, ch)) {
return this._runSurroundSelectionType(prevEditOperationType, config, model, selections, ch);
}
// 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;
}
}
// A simple character type
let 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
});
}
static typeWithoutInterceptors(prevEditOperationType, config, model, selections, str) {
let 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
});
}
static lineInsertBefore(config, model, selections) {
if (model === null || selections === null) {
return [];
}
let 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--;
let 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 [];
}
let commands = [];
for (let i = 0, len = selections.length; i < len; i++) {
const lineNumber = selections[i].positionLineNumber;
let 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) {
let commands = [];
for (let i = 0, len = selections.length; i < len; i++) {
commands[i] = this._enter(config, model, true, selections[i]);
}
return commands;
}
}
exports.TypeOperations = TypeOperations;
class TypeWithAutoClosingCommand extends replaceCommand_1.ReplaceCommandWithOffsetCursorState {
constructor(selection, openCharacter, insertOpenCharacter, closeCharacter) {
super(selection, (insertOpenCharacter ? openCharacter : '') + closeCharacter, 0, -closeCharacter.length);
this._openCharacter = openCharacter;
this._closeCharacter = closeCharacter;
this.closeCharacterRange = null;
this.enclosingRange = null;
}
computeCursorState(model, helper) {
let inverseEditOperations = helper.getInverseEditOperations();
let range = inverseEditOperations[0].range;
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.TypeWithAutoClosingCommand = TypeWithAutoClosingCommand;
function getTypingOperation(typedText, previousTypingOperation) {
if (typedText === ' ') {
return previousTypingOperation === 5 /* TypingFirstSpace */
|| previousTypingOperation === 6 /* TypingConsecutiveSpace */
? 6 /* TypingConsecutiveSpace */
: 5 /* TypingFirstSpace */;
}
return 4 /* TypingOther */;
}
function shouldPushStackElementBetween(previousTypingOperation, typingOperation) {
if (isTypingOperation(previousTypingOperation) && !isTypingOperation(typingOperation)) {
// Always set an undo stop before non-type operations
return true;
}
if (previousTypingOperation === 5 /* 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 /* TypingConsecutiveSpace */ || type === 5 /* TypingFirstSpace */)
? 'space'
: type;
}
function isTypingOperation(type) {
return type === 4 /* TypingOther */
|| type === 5 /* TypingFirstSpace */
|| type === 6 /* TypingConsecutiveSpace */;
}
});
/*---------------------------------------------------------------------------------------------
* 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/editor/common/controller/cursorWordOperations*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,40/*vs/editor/common/controller/cursorCommon*/,186/*vs/editor/common/controller/cursorDeleteOperations*/,109/*vs/editor/common/controller/wordCharacterClassifier*/,13/*vs/editor/common/core/position*/,3/*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 _findPreviousWordOnLine(wordSeparators, model, position) {
let lineContent = model.getLineContent(position.lineNumber);
return this._doFindPreviousWordOnLine(lineContent, wordSeparators, position);
}
static _doFindPreviousWordOnLine(lineContent, wordSeparators, position) {
let wordType = 0 /* None */;
for (let chIndex = position.column - 2; chIndex >= 0; chIndex--) {
let chCode = lineContent.charCodeAt(chIndex);
let chClass = wordSeparators.get(chCode);
if (chClass === 0 /* Regular */) {
if (wordType === 2 /* Separator */) {
return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));
}
wordType = 1 /* Regular */;
}
else if (chClass === 2 /* WordSeparator */) {
if (wordType === 1 /* Regular */) {
return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));
}
wordType = 2 /* Separator */;
}
else if (chClass === 1 /* Whitespace */) {
if (wordType !== 0 /* None */) {
return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));
}
}
}
if (wordType !== 0 /* None */) {
return this._createWord(lineContent, wordType, 1 /* Whitespace */, 0, this._findEndOfWord(lineContent, wordSeparators, wordType, 0));
}
return null;
}
static _findEndOfWord(lineContent, wordSeparators, wordType, startIndex) {
let len = lineContent.length;
for (let chIndex = startIndex; chIndex < len; chIndex++) {
let chCode = lineContent.charCodeAt(chIndex);
let chClass = wordSeparators.get(chCode);
if (chClass === 1 /* Whitespace */) {
return chIndex;
}
if (wordType === 1 /* Regular */ && chClass === 2 /* WordSeparator */) {
return chIndex;
}
if (wordType === 2 /* Separator */ && chClass === 0 /* Regular */) {
return chIndex;
}
}
return len;
}
static _findNextWordOnLine(wordSeparators, model, position) {
let lineContent = model.getLineContent(position.lineNumber);
return this._doFindNextWordOnLine(lineContent, wordSeparators, position);
}
static _doFindNextWordOnLine(lineContent, wordSeparators, position) {
let wordType = 0 /* None */;
let len = lineContent.length;
for (let chIndex = position.column - 1; chIndex < len; chIndex++) {
let chCode = lineContent.charCodeAt(chIndex);
let chClass = wordSeparators.get(chCode);
if (chClass === 0 /* Regular */) {
if (wordType === 2 /* Separator */) {
return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);
}
wordType = 1 /* Regular */;
}
else if (chClass === 2 /* WordSeparator */) {
if (wordType === 1 /* Regular */) {
return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);
}
wordType = 2 /* Separator */;
}
else if (chClass === 1 /* Whitespace */) {
if (wordType !== 0 /* None */) {
return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);
}
}
}
if (wordType !== 0 /* None */) {
return this._createWord(lineContent, wordType, 1 /* Whitespace */, this._findStartOfWord(lineContent, wordSeparators, wordType, len - 1), len);
}
return null;
}
static _findStartOfWord(lineContent, wordSeparators, wordType, startIndex) {
for (let chIndex = startIndex; chIndex >= 0; chIndex--) {
let chCode = lineContent.charCodeAt(chIndex);
let chClass = wordSeparators.get(chCode);
if (chClass === 1 /* Whitespace */) {
return chIndex + 1;
}
if (wordType === 1 /* Regular */ && chClass === 2 /* WordSeparator */) {
return chIndex + 1;
}
if (wordType === 2 /* Separator */ && chClass === 0 /* Regular */) {
return chIndex + 1;
}
}
return 0;
}
static moveWordLeft(wordSeparators, model, position, wordNavigationType) {
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 /* WordStart */) {
return new position_1.Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
}
if (wordNavigationType === 1 /* WordStartFast */) {
if (prevWordOnLine
&& prevWordOnLine.wordType === 2 /* Separator */
&& prevWordOnLine.end - prevWordOnLine.start === 1
&& prevWordOnLine.nextCharClass === 0 /* 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 /* WordAccessibility */) {
while (prevWordOnLine
&& prevWordOnLine.wordType === 2 /* 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 /* Underline */ && right !== 95 /* Underline */) {
// snake_case_variables
return new position_1.Position(lineNumber, column);
}
if (strings.isLowerAsciiLetter(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)) {
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 /* WordEnd */) {
if (nextWordOnLine && nextWordOnLine.wordType === 2 /* Separator */) {
if (nextWordOnLine.end - nextWordOnLine.start === 1 && nextWordOnLine.nextCharClass === 0 /* 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 /* 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 /* 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 /* Underline */ && right === 95 /* Underline */) {
// snake_case_variables
return new position_1.Position(lineNumber, column);
}
if (strings.isLowerAsciiLetter(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)) {
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) {
let r = this._deleteWordLeftWhitespace(model, position);
if (r) {
return r;
}
}
let prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);
if (wordNavigationType === 0 /* 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);
let 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 /* Space */ || charCode === 9 /* 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) {
let len = str.length;
for (let chIndex = startIndex; chIndex < len; chIndex++) {
let 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) {
let r = this._deleteWordRightWhitespace(model, position);
if (r) {
return r;
}
}
let nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, position);
if (wordNavigationType === 2 /* 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, position) {
const wordSeparators = (0, wordCharacterClassifier_1.getMapForWordSeparators)(_wordSeparators);
const prevWord = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);
if (prevWord && prevWord.wordType === 1 /* 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 /* 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);
let prevWord = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);
let nextWord = WordOperations._findNextWordOnLine(wordSeparators, model, position);
if (!inSelectionMode) {
// Entering word selection for the first time
let startColumn;
let endColumn;
if (prevWord && prevWord.wordType === 1 /* 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 /* 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), 0, new position_1.Position(position.lineNumber, endColumn), 0);
}
let startColumn;
let endColumn;
if (prevWord && prevWord.wordType === 1 /* 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 /* 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;
}
let lineNumber = position.lineNumber;
let column;
if (cursor.selectionStart.containsPosition(position)) {
column = cursor.selectionStart.endColumn;
}
else if (position.isBeforeOrEqual(cursor.selectionStart.getStartPosition())) {
column = startColumn;
let possiblePosition = new position_1.Position(lineNumber, column);
if (cursor.selectionStart.containsPosition(possiblePosition)) {
column = cursor.selectionStart.endColumn;
}
}
else {
column = endColumn;
let 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 /* WordStart */),
WordOperations.deleteWordLeft(ctx, 2 /* 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 /* WordStart */),
WordOperations.deleteWordRight(ctx, 2 /* WordEnd */),
WordOperations._deleteWordPartRight(ctx.model, ctx.selection)
]);
candidates.sort(range_1.Range.compareRangesUsingStarts);
return candidates[0];
}
static moveWordPartLeft(wordSeparators, model, position) {
const candidates = enforceDefined([
WordOperations.moveWordLeft(wordSeparators, model, position, 0 /* WordStart */),
WordOperations.moveWordLeft(wordSeparators, model, position, 2 /* WordEnd */),
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 /* WordStart */),
WordOperations.moveWordRight(wordSeparators, model, position, 2 /* 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[244/*vs/editor/common/controller/cursorMoveCommands*/], __M([0/*require*/,1/*exports*/,20/*vs/base/common/types*/,40/*vs/editor/common/controller/cursorCommon*/,185/*vs/editor/common/controller/cursorMoveOperations*/,141/*vs/editor/common/controller/cursorWordOperations*/,13/*vs/editor/common/core/position*/,3/*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) {
let result = [], 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) {
let result = [], 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) {
let 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) {
let 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) {
let 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, new position_1.Position(endLineNumber, endColumn), 0));
}
return result;
}
static moveToBeginningOfBuffer(viewModel, cursors, inSelectionMode) {
let 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) {
let 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, 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 || !cursor.modelState.hasSelection()) {
// 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), 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(cursor.modelState.hasSelection(), 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(cursor.modelState.hasSelection(), selectToViewLineNumber, selectToViewColumn, 0));
}
else {
const endPositionOfSelectionStart = cursor.modelState.selectionStart.getEndPosition();
return cursorCommon_1.CursorState.fromModelState(cursor.modelState.move(cursor.modelState.hasSelection(), 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, new position_1.Position(lineNumber, column), 0));
}
static moveTo(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 /* Left */: {
if (unit === 4 /* 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 /* Right */: {
if (unit === 4 /* 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 /* Up */: {
if (unit === 2 /* 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 /* Down */: {
if (unit === 2 /* 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 /* PrevBlankLine */: {
if (unit === 2 /* 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 /* NextBlankLine */: {
if (unit === 2 /* 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 /* WrappedLineStart */: {
// Move to the beginning of the current view line
return this._moveToViewMinColumn(viewModel, cursors, inSelectionMode);
}
case 7 /* WrappedLineFirstNonWhitespaceCharacter */: {
// Move to the first non-whitespace column of the current view line
return this._moveToViewFirstNonWhitespaceColumn(viewModel, cursors, inSelectionMode);
}
case 8 /* WrappedLineColumnCenter */: {
// Move to the "center" of the current view line
return this._moveToViewCenterColumn(viewModel, cursors, inSelectionMode);
}
case 9 /* WrappedLineEnd */: {
// Move to the end of the current view line
return this._moveToViewMaxColumn(viewModel, cursors, inSelectionMode);
}
case 10 /* 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 /* 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 /* 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 /* 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 /* ViewPortIfOutside */: {
// Move to a position inside the viewport
let 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) {
let 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 {
if (viewLineNumber > visibleViewRange.endLineNumber - 1) {
viewLineNumber = visibleViewRange.endLineNumber - 1;
}
if (viewLineNumber < visibleViewRange.startLineNumber) {
viewLineNumber = visibleViewRange.startLineNumber;
}
const viewColumn = viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber);
return this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
}
}
/**
* 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) {
let 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.getLineContent(viewLineNumber).length / 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) {
let 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.getLineContent(viewLineNumber).length / 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) {
let 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) {
let 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) {
let 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) {
let 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) {
let 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) {
let 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) {
let 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) {
let 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) {
let 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;
}
let 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.description = {
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 /* Left */;
break;
case CursorMove.RawDirection.Right:
direction = 1 /* Right */;
break;
case CursorMove.RawDirection.Up:
direction = 2 /* Up */;
break;
case CursorMove.RawDirection.Down:
direction = 3 /* Down */;
break;
case CursorMove.RawDirection.PrevBlankLine:
direction = 4 /* PrevBlankLine */;
break;
case CursorMove.RawDirection.NextBlankLine:
direction = 5 /* NextBlankLine */;
break;
case CursorMove.RawDirection.WrappedLineStart:
direction = 6 /* WrappedLineStart */;
break;
case CursorMove.RawDirection.WrappedLineFirstNonWhitespaceCharacter:
direction = 7 /* WrappedLineFirstNonWhitespaceCharacter */;
break;
case CursorMove.RawDirection.WrappedLineColumnCenter:
direction = 8 /* WrappedLineColumnCenter */;
break;
case CursorMove.RawDirection.WrappedLineEnd:
direction = 9 /* WrappedLineEnd */;
break;
case CursorMove.RawDirection.WrappedLineLastNonWhitespaceCharacter:
direction = 10 /* WrappedLineLastNonWhitespaceCharacter */;
break;
case CursorMove.RawDirection.ViewPortTop:
direction = 11 /* ViewPortTop */;
break;
case CursorMove.RawDirection.ViewPortBottom:
direction = 13 /* ViewPortBottom */;
break;
case CursorMove.RawDirection.ViewPortCenter:
direction = 12 /* ViewPortCenter */;
break;
case CursorMove.RawDirection.ViewPortIfOutside:
direction = 14 /* ViewPortIfOutside */;
break;
default:
// illegal arguments
return null;
}
let unit = 0 /* None */;
switch (args.by) {
case CursorMove.RawUnit.Line:
unit = 1 /* Line */;
break;
case CursorMove.RawUnit.WrappedLine:
unit = 2 /* WrappedLine */;
break;
case CursorMove.RawUnit.Character:
unit = 3 /* Character */;
break;
case CursorMove.RawUnit.HalfLine:
unit = 4 /* HalfLine */;
break;
}
return {
direction: direction,
unit: unit,
select: (!!args.select),
value: (args.value || 1)
};
}
CursorMove.parse = parse;
})(CursorMove = exports.CursorMove || (exports.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[551/*vs/editor/common/controller/oneCursor*/], __M([0/*require*/,1/*exports*/,40/*vs/editor/common/controller/cursorCommon*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*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, new position_1.Position(1, 1), 0), new cursorCommon_1.SingleCursorState(new range_1.Range(1, 1, 1, 1), 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 /* AlwaysGrowsWhenTypingAtEdges */);
}
_removeTrackedRange(context) {
this._selTrackedRange = context.model._setTrackedRange(this._selTrackedRange, null, 0 /* AlwaysGrowsWhenTypingAtEdges */);
}
asCursorState() {
return new cursorCommon_1.CursorState(this.modelState, this.viewState);
}
readSelectionFromMarkers(context) {
const range = context.model._getTrackedRange(this._selTrackedRange);
if (this.modelState.selection.getDirection() === 0 /* 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);
}
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 /* 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 /* 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.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.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, 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.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.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[552/*vs/editor/common/controller/cursorCollection*/], __M([0/*require*/,1/*exports*/,40/*vs/editor/common/controller/cursorCommon*/,551/*vs/editor/common/controller/oneCursor*/,21/*vs/editor/common/core/selection*/]), function (require, exports, cursorCommon_1, oneCursor_1, selection_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CursorCollection = void 0;
class CursorCollection {
constructor(context) {
this.context = context;
this.primaryCursor = new oneCursor_1.Cursor(context);
this.secondaryCursors = [];
this.lastAddedCursorIndex = 0;
}
dispose() {
this.primaryCursor.dispose(this.context);
this.killSecondaryCursors();
}
startTrackingSelections() {
this.primaryCursor.startTrackingSelection(this.context);
for (let i = 0, len = this.secondaryCursors.length; i < len; i++) {
this.secondaryCursors[i].startTrackingSelection(this.context);
}
}
stopTrackingSelections() {
this.primaryCursor.stopTrackingSelection(this.context);
for (let i = 0, len = this.secondaryCursors.length; i < len; i++) {
this.secondaryCursors[i].stopTrackingSelection(this.context);
}
}
updateContext(context) {
this.context = context;
}
ensureValidState() {
this.primaryCursor.ensureValidState(this.context);
for (let i = 0, len = this.secondaryCursors.length; i < len; i++) {
this.secondaryCursors[i].ensureValidState(this.context);
}
}
readSelectionFromMarkers() {
let result = [];
result[0] = this.primaryCursor.readSelectionFromMarkers(this.context);
for (let i = 0, len = this.secondaryCursors.length; i < len; i++) {
result[i + 1] = this.secondaryCursors[i].readSelectionFromMarkers(this.context);
}
return result;
}
getAll() {
let result = [];
result[0] = this.primaryCursor.asCursorState();
for (let i = 0, len = this.secondaryCursors.length; i < len; i++) {
result[i + 1] = this.secondaryCursors[i].asCursorState();
}
return result;
}
getViewPositions() {
let result = [];
result[0] = this.primaryCursor.viewState.position;
for (let i = 0, len = this.secondaryCursors.length; i < len; i++) {
result[i + 1] = this.secondaryCursors[i].viewState.position;
}
return result;
}
getTopMostViewPosition() {
let result = this.primaryCursor.viewState.position;
for (let i = 0, len = this.secondaryCursors.length; i < len; i++) {
const viewPosition = this.secondaryCursors[i].viewState.position;
if (viewPosition.isBefore(result)) {
result = viewPosition;
}
}
return result;
}
getBottomMostViewPosition() {
let result = this.primaryCursor.viewState.position;
for (let i = 0, len = this.secondaryCursors.length; i < len; i++) {
const viewPosition = this.secondaryCursors[i].viewState.position;
if (result.isBeforeOrEqual(viewPosition)) {
result = viewPosition;
}
}
return result;
}
getSelections() {
let result = [];
result[0] = this.primaryCursor.modelState.selection;
for (let i = 0, len = this.secondaryCursors.length; i < len; i++) {
result[i + 1] = this.secondaryCursors[i].modelState.selection;
}
return result;
}
getViewSelections() {
let result = [];
result[0] = this.primaryCursor.viewState.selection;
for (let i = 0, len = this.secondaryCursors.length; i < len; i++) {
result[i + 1] = this.secondaryCursors[i].viewState.selection;
}
return result;
}
setSelections(selections) {
this.setStates(cursorCommon_1.CursorState.fromModelSelections(selections));
}
getPrimaryCursor() {
return this.primaryCursor.asCursorState();
}
setStates(states) {
if (states === null) {
return;
}
this.primaryCursor.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.secondaryCursors.length;
const secondaryStatesLength = secondaryStates.length;
if (secondaryCursorsLength < secondaryStatesLength) {
let createCnt = secondaryStatesLength - secondaryCursorsLength;
for (let i = 0; i < createCnt; i++) {
this._addSecondaryCursor();
}
}
else if (secondaryCursorsLength > secondaryStatesLength) {
let removeCnt = secondaryCursorsLength - secondaryStatesLength;
for (let i = 0; i < removeCnt; i++) {
this._removeSecondaryCursor(this.secondaryCursors.length - 1);
}
}
for (let i = 0; i < secondaryStatesLength; i++) {
this.secondaryCursors[i].setState(this.context, secondaryStates[i].modelState, secondaryStates[i].viewState);
}
}
killSecondaryCursors() {
this._setSecondaryStates([]);
}
_addSecondaryCursor() {
this.secondaryCursors.push(new oneCursor_1.Cursor(this.context));
this.lastAddedCursorIndex = this.secondaryCursors.length;
}
getLastAddedCursorIndex() {
if (this.secondaryCursors.length === 0 || this.lastAddedCursorIndex === 0) {
return 0;
}
return this.lastAddedCursorIndex;
}
_removeSecondaryCursor(removeIndex) {
if (this.lastAddedCursorIndex >= removeIndex + 1) {
this.lastAddedCursorIndex--;
}
this.secondaryCursors[removeIndex].dispose(this.context);
this.secondaryCursors.splice(removeIndex, 1);
}
_getAll() {
let result = [];
result[0] = this.primaryCursor;
for (let i = 0, len = this.secondaryCursors.length; i < len; i++) {
result[i + 1] = this.secondaryCursors[i];
}
return result;
}
normalize() {
if (this.secondaryCursors.length === 0) {
return;
}
let cursors = this._getAll();
let sortedCursors = [];
for (let i = 0, len = cursors.length; i < len; i++) {
sortedCursors.push({
index: i,
selection: cursors[i].modelState.selection,
});
}
sortedCursors.sort((a, b) => {
if (a.selection.startLineNumber === b.selection.startLineNumber) {
return a.selection.startColumn - b.selection.startColumn;
}
return a.selection.startLineNumber - b.selection.startLineNumber;
});
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[245/*vs/editor/common/controller/cursor*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,8/*vs/base/common/strings*/,552/*vs/editor/common/controller/cursorCollection*/,40/*vs/editor/common/controller/cursorCommon*/,186/*vs/editor/common/controller/cursorDeleteOperations*/,187/*vs/editor/common/controller/cursorTypeOperations*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,96/*vs/editor/common/model/textModelEvents*/,175/*vs/editor/common/view/viewEvents*/,2/*vs/base/common/lifecycle*/,177/*vs/editor/common/viewModel/viewModelEventDispatcher*/]), function (require, exports, errors_1, strings, cursorCollection_1, cursorCommon_1, cursorDeleteOperations_1, cursorTypeOperations_1, range_1, selection_1, textModelEvents_1, viewEvents_1, lifecycle_1, viewModelEventDispatcher_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CursorsController = exports.CursorModelState = void 0;
/**
* A snapshot of the cursor and the model state
*/
class CursorModelState {
constructor(model, cursor) {
this.modelVersionId = model.getVersionId();
this.cursorState = cursor.getCursorStates();
}
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;
}
}
exports.CursorModelState = CursorModelState;
class AutoClosedAction {
constructor(model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations) {
this._model = model;
this._autoClosedCharactersDecorations = autoClosedCharactersDecorations;
this._autoClosedEnclosingDecorations = autoClosedEnclosingDecorations;
}
static getAllAutoClosedCharacters(autoClosedActions) {
let autoClosedCharacters = [];
for (const autoClosedAction of autoClosedActions) {
autoClosedCharacters = autoClosedCharacters.concat(autoClosedAction.getAutoClosedCharactersRanges());
}
return autoClosedCharacters;
}
dispose() {
this._autoClosedCharactersDecorations = this._model.deltaDecorations(this._autoClosedCharactersDecorations, []);
this._autoClosedEnclosingDecorations = this._model.deltaDecorations(this._autoClosedEnclosingDecorations, []);
}
getAutoClosedCharactersRanges() {
let 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) {
let 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 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 cursorCommon_1.CursorContext(this._model, this._viewModel, this._coordinatesConverter, cursorConfig);
this._cursors = new cursorCollection_1.CursorCollection(this.context);
this._hasFocus = false;
this._isHandling = false;
this._isDoingComposition = false;
this._selectionsWhenCompositionStarted = null;
this._columnSelectData = null;
this._autoClosedActions = [];
this._prevEditOperationType = 0 /* Other */;
}
dispose() {
this._cursors.dispose();
this._autoClosedActions = (0, lifecycle_1.dispose)(this._autoClosedActions);
super.dispose();
}
updateConfiguration(cursorConfig) {
this.context = new cursorCommon_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 /* NotSet */, this.getCursorStates());
}
setHasFocus(hasFocus) {
this._hasFocus = hasFocus;
}
_validateAutoClosedActions() {
if (this._autoClosedActions.length > 0) {
let 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;
if (states !== null && states.length > CursorsController.MAX_CURSOR_COUNT) {
states = states.slice(0, CursorsController.MAX_CURSOR_COUNT);
reachedMaxCursorCount = true;
}
const oldState = new CursorModelState(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;
}
revealPrimary(eventsCollector, source, revealHorizontal, scrollType) {
const viewPositions = this._cursors.getViewPositions();
if (viewPositions.length > 1) {
this._emitCursorRevealRange(eventsCollector, source, null, this._cursors.getViewSelections(), 0 /* Simple */, revealHorizontal, scrollType);
return;
}
else {
const viewPosition = viewPositions[0];
const viewRange = new range_1.Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
this._emitCursorRevealRange(eventsCollector, source, viewRange, null, 0 /* Simple */, revealHorizontal, scrollType);
}
}
_revealPrimaryCursor(eventsCollector, source, verticalType, revealHorizontal, scrollType) {
const viewPositions = this._cursors.getViewPositions();
if (viewPositions.length > 1) {
this._emitCursorRevealRange(eventsCollector, source, null, this._cursors.getViewSelections(), verticalType, revealHorizontal, scrollType);
}
else {
const viewPosition = viewPositions[0];
const viewRange = new range_1.Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
this._emitCursorRevealRange(eventsCollector, source, viewRange, null, verticalType, revealHorizontal, scrollType);
}
}
_emitCursorRevealRange(eventsCollector, source, viewRange, viewSelections, verticalType, revealHorizontal, scrollType) {
eventsCollector.emitViewEvent(new viewEvents_1.ViewRevealRangeRequestEvent(source, viewRange, viewSelections, verticalType, revealHorizontal, scrollType));
}
saveState() {
let 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) {
let 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 /* NotSet */, cursorCommon_1.CursorState.fromModelSelections(desiredSelections));
this.revealPrimary(eventsCollector, 'restoreState', true, 1 /* Immediate */);
}
onModelContentChanged(eventsCollector, e) {
if (e instanceof textModelEvents_1.ModelInjectedTextChangedEvent) {
// If injected texts change, the view positions of all cursors need to be updated.
const selectionsFromMarkers = this._cursors.readSelectionFromMarkers();
this.setStates(eventsCollector, 'modelChange', 2 /* RecoverFromMarkers */, cursorCommon_1.CursorState.fromModelSelections(selectionsFromMarkers));
}
else {
this._knownModelVersionId = e.versionId;
if (this._isHandling) {
return;
}
const hadFlushEvent = e.containsEvent(1 /* Flush */);
this._prevEditOperationType = 0 /* 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 /* 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 /* Undo */ : e.isRedoing ? 6 /* Redo */ : 2 /* RecoverFromMarkers */, cursorState)) {
this._revealPrimaryCursor(eventsCollector, 'modelChange', 0 /* Simple */, true, 0 /* Smooth */);
}
}
else {
const selectionsFromMarkers = this._cursors.readSelectionFromMarkers();
this.setStates(eventsCollector, 'modelChange', 2 /* 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: cursorCommon_1.CursorColumns.visibleColumnFromColumn2(this.context.cursorConfig, this._viewModel, viewSelectionStart),
toViewLineNumber: viewPosition.lineNumber,
toViewVisualColumn: cursorCommon_1.CursorColumns.visibleColumnFromColumn2(this.context.cursorConfig, 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) {
let autoClosedCharactersDeltaDecorations = [];
let 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 /* NeverGrowsWhenTypingAtEdges */
}
});
autoClosedEnclosingDeltaDecorations.push({
range: autoClosedEnclosingRanges[i],
options: {
description: 'auto-closed-enclosing',
stickiness: 1 /* 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
let autoClosedCharactersRanges = [];
let autoClosedEnclosingRanges = [];
for (let i = 0; i < opResult.commands.length; i++) {
const command = opResult.commands[i];
if (command instanceof cursorTypeOperations_1.TypeWithAutoClosingCommand && 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 = new CursorModelState(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));
// 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;
}
let 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;
}
let autoClosedCharactersRanges = [];
let 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 /* NotSet */);
}
if (autoClosedCharactersRanges.length > 0) {
this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges);
}
}
_executeEdit(callback, eventsCollector, source, cursorChangeReason = 0 /* NotSet */) {
if (this.context.cursorConfig.readOnly) {
// we cannot edit when read only...
return;
}
const oldState = new CursorModelState(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._revealPrimaryCursor(eventsCollector, source, 0 /* Simple */, true, 0 /* Smooth */);
}
}
setIsDoingComposition(isDoingComposition) {
this._isDoingComposition = isDoingComposition;
}
getAutoClosedCharacters() {
return AutoClosedAction.getAllAutoClosedCharacters(this._autoClosedActions);
}
startComposition(eventsCollector) {
this._selectionsWhenCompositionStarted = this.getSelections().slice(0);
}
endComposition(eventsCollector, source) {
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, this._selectionsWhenCompositionStarted, this.getSelections(), this.getAutoClosedCharacters()));
this._selectionsWhenCompositionStarted = null;
}
}, 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._isDoingComposition, 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 /* 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 /* 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 /* Other */, [command], {
shouldPushStackElementBefore: false,
shouldPushStackElementAfter: false
}));
}, eventsCollector, source);
}
executeCommands(eventsCollector, commands, source) {
this._executeEdit(() => {
this._executeEditOperation(new cursorCommon_1.EditOperationResult(0 /* Other */, commands, {
shouldPushStackElementBefore: false,
shouldPushStackElementAfter: false
}));
}, eventsCollector, source);
}
}
exports.CursorsController = CursorsController;
CursorsController.MAX_CURSOR_COUNT = 10000;
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 /* 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
let 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) => {
let 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;
};
let 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 /* 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
let losingCursors = [];
for (let 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
let 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 /* GrowsOnlyWhenTypingBefore */;
}
else {
stickiness = 3 /* GrowsOnlyWhenTypingAfter */;
}
}
else {
// Try to lock it with surrounding text
const maxLineColumn = ctx.model.getLineMaxColumn(selection.startLineNumber);
if (selection.startColumn === maxLineColumn) {
stickiness = 2 /* GrowsOnlyWhenTypingBefore */;
}
else {
stickiness = 3 /* GrowsOnlyWhenTypingAfter */;
}
}
}
else {
stickiness = 1 /* 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!
let 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;
}
}
});
/*---------------------------------------------------------------------------------------------
* 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/common/modes/textToHtmlTokenizer*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,85/*vs/editor/common/core/lineTokens*/,77/*vs/editor/common/modes/nullMode*/]), function (require, exports, strings, lineTokens_1, nullMode_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.tokenizeLineToHTML = exports.tokenizeToString = void 0;
const fallback = {
getInitialState: () => nullMode_1.NULL_STATE,
tokenize2: (buffer, hasEOL, state, deltaOffset) => (0, nullMode_1.nullTokenize2)(0 /* Null */, buffer, state, deltaOffset)
};
function tokenizeToString(text, tokenizationSupport = fallback) {
return _tokenizeToString(text, tokenizationSupport || fallback);
}
exports.tokenizeToString = tokenizeToString;
function tokenizeLineToHTML(text, viewLineTokens, colorMap, startOffset, endOffset, tabSize, useNbsp) {
let result = `<div>`;
let charIndex = startOffset;
let tabsCharDelta = 0;
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 /* Tab */:
let insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
tabsCharDelta += insertSpacesCount - 1;
while (insertSpacesCount > 0) {
partContent += useNbsp ? '&#160;' : ' ';
insertSpacesCount--;
}
break;
case 60 /* LessThan */:
partContent += '&lt;';
break;
case 62 /* GreaterThan */:
partContent += '&gt;';
break;
case 38 /* Ampersand */:
partContent += '&amp;';
break;
case 0 /* Null */:
partContent += '&#00;';
break;
case 65279 /* UTF8_BOM */:
case 8232 /* LINE_SEPARATOR */:
case 8233 /* PARAGRAPH_SEPARATOR */:
case 133 /* NEXT_LINE */:
partContent += '\ufffd';
break;
case 13 /* CarriageReturn */:
// zero width space, because carriage return would introduce a line break
partContent += '&#8203';
break;
case 32 /* Space */:
partContent += useNbsp ? '&#160;' : ' ';
break;
default:
partContent += String.fromCharCode(charCode);
}
}
result += `<span style="${viewLineTokens.getInlineStyle(tokenIndex, colorMap)}">${partContent}</span>`;
if (tokenEndIndex > endOffset || charIndex >= endOffset) {
break;
}
}
result += `</div>`;
return result;
}
exports.tokenizeLineToHTML = tokenizeLineToHTML;
function _tokenizeToString(text, tokenizationSupport) {
let result = `<div class="monaco-tokenized-source">`;
let lines = strings.splitLines(text);
let currentState = tokenizationSupport.getInitialState();
for (let i = 0, len = lines.length; i < len; i++) {
let line = lines[i];
if (i > 0) {
result += `<br/>`;
}
let tokenizationResult = tokenizationSupport.tokenize2(line, true, currentState, 0);
lineTokens_1.LineTokens.convertToEndOffset(tokenizationResult.tokens, line.length);
let lineTokens = new lineTokens_1.LineTokens(tokenizationResult.tokens, line);
let 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[68/*vs/editor/common/services/resolverService*/], __M([0/*require*/,1/*exports*/,9/*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');
});
define(__m[142/*vs/editor/common/services/textResourceConfigurationService*/], __M([0/*require*/,1/*exports*/,9/*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');
});
/*---------------------------------------------------------------------------------------------
* 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/editor/common/viewModel/minimapTokensColorTracker*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,218/*vs/editor/common/core/rgba*/,18/*vs/editor/common/modes*/]), function (require, exports, event_1, lifecycle_1, rgba_1, modes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MinimapTokensColorTracker = void 0;
class MinimapTokensColorTracker extends lifecycle_1.Disposable {
constructor() {
super();
this._onDidChange = new event_1.Emitter();
this.onDidChange = this._onDidChange.event;
this._updateColorMap();
this._register(modes_1.TokenizationRegistry.onDidChange(e => {
if (e.changedColorMap) {
this._updateColorMap();
}
}));
}
static getInstance() {
if (!this._INSTANCE) {
this._INSTANCE = (0, lifecycle_1.markAsSingleton)(new MinimapTokensColorTracker());
}
return this._INSTANCE;
}
_updateColorMap() {
const colorMap = modes_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));
}
let backgroundLuminosity = colorMap[2 /* 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 /* DefaultBackground */;
}
return this._colors[colorId];
}
backgroundIsLight() {
return this._backgroundIsLight;
}
}
exports.MinimapTokensColorTracker = MinimapTokensColorTracker;
MinimapTokensColorTracker._INSTANCE = 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[553/*vs/editor/common/viewModel/splitLinesCollection*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,85/*vs/editor/common/core/lineTokens*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,31/*vs/editor/common/model/textModel*/,175/*vs/editor/common/view/viewEvents*/,224/*vs/editor/common/viewModel/prefixSumComputer*/,62/*vs/editor/common/viewModel/viewModel*/,96/*vs/editor/common/model/textModelEvents*/]), function (require, exports, arrays, lineTokens_1, position_1, range_1, textModel_1, viewEvents, prefixSumComputer_1, viewModel_1, textModelEvents_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IdentityLinesCollection = exports.IdentityCoordinatesConverter = exports.SplitLine = exports.SplitLinesCollection = exports.CoordinatesConverter = void 0;
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) {
return this._lines.convertModelPositionToViewPosition(modelPosition.lineNumber, modelPosition.column, affinity);
}
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);
}
}
exports.CoordinatesConverter = CoordinatesConverter;
class LineNumberMapper {
constructor(viewLineCounts) {
this._counts = viewLineCounts;
this._isValid = false;
this._validEndIndex = -1;
this._modelToView = [];
this._viewToModel = [];
}
_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._counts.length; i < len; i++) {
const viewLineCount = this._counts[i];
const viewLinesAbove = (i > 0 ? this._modelToView[i - 1] : 0);
this._modelToView[i] = viewLinesAbove + viewLineCount;
for (let j = 0; j < viewLineCount; j++) {
this._viewToModel[viewLinesAbove + j] = i;
}
}
// trim things
this._modelToView.length = this._counts.length;
this._viewToModel.length = this._modelToView[this._modelToView.length - 1];
// mark as valid
this._isValid = true;
this._validEndIndex = this._counts.length - 1;
}
changeValue(index, value) {
if (this._counts[index] === value) {
// no change
return;
}
this._counts[index] = value;
this._invalidate(index);
}
removeValues(start, deleteCount) {
this._counts.splice(start, deleteCount);
this._invalidate(start);
}
insertValues(insertIndex, insertArr) {
this._counts = arrays.arrayInsert(this._counts, insertIndex, insertArr);
this._invalidate(insertIndex);
}
getTotalValue() {
this._ensureValid();
return this._viewToModel.length;
}
getAccumulatedValue(index) {
this._ensureValid();
return this._modelToView[index];
}
getIndexOf(accumulatedValue) {
this._ensureValid();
const modelLineIndex = this._viewToModel[accumulatedValue];
const viewLinesAbove = (modelLineIndex > 0 ? this._modelToView[modelLineIndex - 1] : 0);
return new prefixSumComputer_1.PrefixSumIndexOfResult(modelLineIndex, accumulatedValue - viewLinesAbove);
}
}
class SplitLinesCollection {
constructor(editorId, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, tabSize, wrappingStrategy, wrappingColumn, wrappingIndent) {
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._constructLines(/*resetHiddenAreas*/ true, null);
}
dispose() {
this.hiddenAreasIds = this.model.deltaDecorations(this.hiddenAreasIds, []);
}
createCoordinatesConverter() {
return new CoordinatesConverter(this);
}
_constructLines(resetHiddenAreas, previousLineBreaks) {
this.lines = [];
if (resetHiddenAreas) {
this.hiddenAreasIds = [];
}
const linesContent = this.model.getLinesContent();
const injectedTextDecorations = this.model.getInjectedTextDecorations(this._editorId);
const injectedText = textModelEvents_1.LineInjectedText.fromDecorations(injectedTextDecorations);
const lineCount = linesContent.length;
const lineBreaksComputer = this.createLineBreaksComputer();
const injectedTextLength = injectedText.length;
let injectedTextIndex = 0;
let nextLineNumberWithInjectedText = (injectedTextIndex < injectedTextLength ? injectedText[injectedTextIndex].lineNumber : lineCount + 1);
for (let i = 0; i < lineCount; i++) {
let lineInjectedText = null;
if (i + 1 === nextLineNumberWithInjectedText) {
// There is some injected text on this line
lineInjectedText = [];
while (i + 1 === nextLineNumberWithInjectedText && injectedTextIndex < injectedTextLength) {
lineInjectedText.push(injectedText[injectedTextIndex]);
injectedTextIndex++;
nextLineNumberWithInjectedText = (injectedTextIndex < injectedTextLength ? injectedText[injectedTextIndex].lineNumber : lineCount + 1);
}
}
lineBreaksComputer.addRequest(linesContent[i], lineInjectedText, previousLineBreaks ? previousLineBreaks[i] : null);
}
const linesBreaks = lineBreaksComputer.finalize();
let values = [];
let hiddenAreas = this.hiddenAreasIds.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++) {
let lineNumber = i + 1;
if (lineNumber === nextLineNumberToUpdateHiddenArea) {
hiddenAreaIdx++;
hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;
hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;
nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : lineCount + 2;
}
let isInHiddenArea = (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd);
let line = createSplitLine(linesBreaks[i], !isInHiddenArea);
values[i] = line.getViewLineCount();
this.lines[i] = line;
}
this._validModelVersionId = this.model.getVersionId();
this.prefixSumComputer = new LineNumberMapper(values);
}
getHiddenAreas() {
return this.hiddenAreasIds.map((decId) => {
return this.model.getDecorationRange(decId);
});
}
_reduceRanges(_ranges) {
if (_ranges.length === 0) {
return [];
}
let ranges = _ranges.map(r => this.model.validateRange(r)).sort(range_1.Range.compareRangesUsingStarts);
let result = [];
let currentRangeStart = ranges[0].startLineNumber;
let currentRangeEnd = ranges[0].endLineNumber;
for (let i = 1, len = ranges.length; i < len; i++) {
let range = ranges[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;
}
setHiddenAreas(_ranges) {
let newRanges = this._reduceRanges(_ranges);
// BEGIN TODO@Martin: Please stop calling this method on each model change!
let oldRanges = this.hiddenAreasIds.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;
}
}
// END TODO@Martin: Please stop calling this method on each model change!
let newDecorations = [];
for (const newRange of newRanges) {
newDecorations.push({
range: newRange,
options: textModel_1.ModelDecorationOptions.EMPTY
});
}
this.hiddenAreasIds = this.model.deltaDecorations(this.hiddenAreasIds, newDecorations);
let hiddenAreas = newRanges;
let hiddenAreaStart = 1, hiddenAreaEnd = 0;
let hiddenAreaIdx = -1;
let nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : this.lines.length + 2;
let hasVisibleLine = false;
for (let i = 0; i < this.lines.length; i++) {
let lineNumber = i + 1;
if (lineNumber === nextLineNumberToUpdateHiddenArea) {
hiddenAreaIdx++;
hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;
hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;
nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : this.lines.length + 2;
}
let lineChanged = false;
if (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd) {
// Line should be hidden
if (this.lines[i].isVisible()) {
this.lines[i] = this.lines[i].setVisible(false);
lineChanged = true;
}
}
else {
hasVisibleLine = true;
// Line should be visible
if (!this.lines[i].isVisible()) {
this.lines[i] = this.lines[i].setVisible(true);
lineChanged = true;
}
}
if (lineChanged) {
let newOutputLineCount = this.lines[i].getViewLineCount();
this.prefixSumComputer.changeValue(i, newOutputLineCount);
}
}
if (!hasVisibleLine) {
// Cannot have everything be hidden => reveal everything!
this.setHiddenAreas([]);
}
return true;
}
modelPositionIsVisible(modelLineNumber, _modelColumn) {
if (modelLineNumber < 1 || modelLineNumber > this.lines.length) {
// invalid arguments
return false;
}
return this.lines[modelLineNumber - 1].isVisible();
}
getModelLineViewLineCount(modelLineNumber) {
if (modelLineNumber < 1 || modelLineNumber > this.lines.length) {
// invalid arguments
return 1;
}
return this.lines[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) {
const equalFontInfo = this.fontInfo.equals(fontInfo);
const equalWrappingStrategy = (this.wrappingStrategy === wrappingStrategy);
const equalWrappingColumn = (this.wrappingColumn === wrappingColumn);
const equalWrappingIndent = (this.wrappingIndent === wrappingIndent);
if (equalFontInfo && equalWrappingStrategy && equalWrappingColumn && equalWrappingIndent) {
return false;
}
const onlyWrappingColumnChanged = (equalFontInfo && equalWrappingStrategy && !equalWrappingColumn && equalWrappingIndent);
this.fontInfo = fontInfo;
this.wrappingStrategy = wrappingStrategy;
this.wrappingColumn = wrappingColumn;
this.wrappingIndent = wrappingIndent;
let previousLineBreaks = null;
if (onlyWrappingColumnChanged) {
previousLineBreaks = [];
for (let i = 0, len = this.lines.length; i < len; i++) {
previousLineBreaks[i] = this.lines[i].getLineBreakData();
}
}
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);
}
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;
}
let outputFromLineNumber = (fromLineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(fromLineNumber - 2) + 1);
let outputToLineNumber = this.prefixSumComputer.getAccumulatedValue(toLineNumber - 1);
this.lines.splice(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);
this.prefixSumComputer.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.lines[fromLineNumber - 2].isVisible());
let outputFromLineNumber = (fromLineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(fromLineNumber - 2) + 1);
let totalOutputLineCount = 0;
let insertLines = [];
let insertPrefixSumValues = [];
for (let i = 0, len = lineBreaks.length; i < len; i++) {
let line = createSplitLine(lineBreaks[i], !isInHiddenArea);
insertLines.push(line);
let outputLineCount = line.getViewLineCount();
totalOutputLineCount += outputLineCount;
insertPrefixSumValues[i] = outputLineCount;
}
// TODO@Alex: use arrays.arrayInsert
this.lines = this.lines.slice(0, fromLineNumber - 1).concat(insertLines).concat(this.lines.slice(fromLineNumber - 1));
this.prefixSumComputer.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];
}
let lineIndex = lineNumber - 1;
let oldOutputLineCount = this.lines[lineIndex].getViewLineCount();
let isVisible = this.lines[lineIndex].isVisible();
let line = createSplitLine(lineBreakData, isVisible);
this.lines[lineIndex] = line;
let newOutputLineCount = this.lines[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 = (lineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(lineNumber - 2) + 1);
changeTo = changeFrom + newOutputLineCount - 1;
deleteFrom = changeTo + 1;
deleteTo = deleteFrom + (oldOutputLineCount - newOutputLineCount) - 1;
lineMappingChanged = true;
}
else if (oldOutputLineCount < newOutputLineCount) {
changeFrom = (lineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(lineNumber - 2) + 1);
changeTo = changeFrom + oldOutputLineCount - 1;
insertFrom = changeTo + 1;
insertTo = insertFrom + (newOutputLineCount - oldOutputLineCount) - 1;
lineMappingChanged = true;
}
else {
changeFrom = (lineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(lineNumber - 2) + 1);
changeTo = changeFrom + newOutputLineCount - 1;
}
this.prefixSumComputer.changeValue(lineIndex, newOutputLineCount);
const viewLinesChangedEvent = (changeFrom <= changeTo ? new viewEvents.ViewLinesChangedEvent(changeFrom, changeTo) : 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.lines.length === 1 && !this.lines[0].isVisible()) {
// At least one line must be visible => reset hidden areas
this.setHiddenAreas([]);
}
}
getViewLineCount() {
return this.prefixSumComputer.getTotalValue();
}
_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.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
};
}
getViewLinesIndentGuides(viewStartLineNumber, viewEndLineNumber) {
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 = [];
let resultRepeatCount = [];
let resultRepeatOption = [];
const modelStartLineIndex = modelStart.lineNumber - 1;
const modelEndLineIndex = modelEnd.lineNumber - 1;
let reqStart = null;
for (let modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) {
const line = this.lines[modelLineIndex];
if (line.isVisible()) {
let viewLineStartIndex = line.getViewLineNumberOfModelPosition(0, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);
let viewLineEndIndex = line.getViewLineNumberOfModelPosition(0, this.model.getLineMaxColumn(modelLineIndex + 1));
let count = viewLineEndIndex - viewLineStartIndex + 1;
let option = 0 /* BlockNone */;
if (count > 1 && line.getViewLineMinColumn(this.model, modelLineIndex + 1, viewLineEndIndex) === 1) {
// wrapped lines should block indent guides
option = (viewLineStartIndex === 0 ? 1 /* BlockSubsequent */ : 2 /* 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.getLinesIndentGuides(reqStart.lineNumber, modelLineIndex));
reqStart = null;
}
}
}
if (reqStart !== null) {
result = result.concat(this.model.getLinesIndentGuides(reqStart.lineNumber, modelEnd.lineNumber));
reqStart = null;
}
const viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;
let viewIndents = new Array(viewLineCount);
let currIndex = 0;
for (let i = 0, len = result.length; i < len; i++) {
let value = result[i];
let count = Math.min(viewLineCount - currIndex, resultRepeatCount[i]);
let option = resultRepeatOption[i];
let blockAtIndex;
if (option === 2 /* BlockAll */) {
blockAtIndex = 0;
}
else if (option === 1 /* 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) {
viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
let r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
let lineIndex = r.index;
let remainder = r.remainder;
return this.lines[lineIndex].getViewLineContent(this.model, lineIndex + 1, remainder);
}
getViewLineLength(viewLineNumber) {
viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
let r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
let lineIndex = r.index;
let remainder = r.remainder;
return this.lines[lineIndex].getViewLineLength(this.model, lineIndex + 1, remainder);
}
getViewLineMinColumn(viewLineNumber) {
viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
let r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
let lineIndex = r.index;
let remainder = r.remainder;
return this.lines[lineIndex].getViewLineMinColumn(this.model, lineIndex + 1, remainder);
}
getViewLineMaxColumn(viewLineNumber) {
viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
let r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
let lineIndex = r.index;
let remainder = r.remainder;
return this.lines[lineIndex].getViewLineMaxColumn(this.model, lineIndex + 1, remainder);
}
getViewLineData(viewLineNumber) {
viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
let r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
let lineIndex = r.index;
let remainder = r.remainder;
return this.lines[lineIndex].getViewLineData(this.model, lineIndex + 1, remainder);
}
getViewLinesData(viewStartLineNumber, viewEndLineNumber, needed) {
viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber);
viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber);
let start = this.prefixSumComputer.getIndexOf(viewStartLineNumber - 1);
let viewLineNumber = viewStartLineNumber;
let startModelLineIndex = start.index;
let startRemainder = start.remainder;
let result = [];
for (let modelLineIndex = startModelLineIndex, len = this.model.getLineCount(); modelLineIndex < len; modelLineIndex++) {
let line = this.lines[modelLineIndex];
if (!line.isVisible()) {
continue;
}
let fromViewLineIndex = (modelLineIndex === startModelLineIndex ? startRemainder : 0);
let remainingViewLineCount = line.getViewLineCount() - fromViewLineIndex;
let lastLine = false;
if (viewLineNumber + remainingViewLineCount > viewEndLineNumber) {
lastLine = true;
remainingViewLineCount = viewEndLineNumber - viewLineNumber + 1;
}
let toViewLineIndex = fromViewLineIndex + remainingViewLineCount;
line.getViewLinesData(this.model, modelLineIndex + 1, fromViewLineIndex, toViewLineIndex, viewLineNumber - viewStartLineNumber, needed, result);
viewLineNumber += remainingViewLineCount;
if (lastLine) {
break;
}
}
return result;
}
validateViewPosition(viewLineNumber, viewColumn, expectedModelPosition) {
viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
let r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
let lineIndex = r.index;
let remainder = r.remainder;
let line = this.lines[lineIndex];
let minColumn = line.getViewLineMinColumn(this.model, lineIndex + 1, remainder);
let maxColumn = line.getViewLineMaxColumn(this.model, lineIndex + 1, remainder);
if (viewColumn < minColumn) {
viewColumn = minColumn;
}
if (viewColumn > maxColumn) {
viewColumn = maxColumn;
}
let computedModelColumn = line.getModelColumnOfViewPosition(remainder, viewColumn);
let 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) {
viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
let r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
let lineIndex = r.index;
let remainder = r.remainder;
let inputColumn = this.lines[lineIndex].getModelColumnOfViewPosition(remainder, viewColumn);
// console.log('out -> in ' + viewLineNumber + ',' + viewColumn + ' ===> ' + (lineIndex+1) + ',' + inputColumn);
return this.model.validatePosition(new position_1.Position(lineIndex + 1, 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 /* None */) {
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;
while (lineIndex > 0 && !this.lines[lineIndex].isVisible()) {
lineIndex--;
lineIndexChanged = true;
}
if (lineIndex === 0 && !this.lines[lineIndex].isVisible()) {
// Could not reach a real line
// console.log('in -> out ' + inputLineNumber + ',' + inputColumn + ' ===> ' + 1 + ',' + 1);
return new position_1.Position(1, 1);
}
const deltaLineNumber = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1));
let r;
if (lineIndexChanged) {
r = this.lines[lineIndex].getViewPositionOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1), affinity);
}
else {
r = this.lines[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 /* 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 /* Right */);
const end = this.convertModelPositionToViewPosition(modelRange.endLineNumber, modelRange.endColumn, 0 /* Left */);
return new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column);
}
}
_getViewLineNumberForModelPosition(inputLineNumber, inputColumn) {
let lineIndex = inputLineNumber - 1;
if (this.lines[lineIndex].isVisible()) {
// this model line is visible
const deltaLineNumber = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1));
return this.lines[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber, inputColumn);
}
// this model line is not visible
while (lineIndex > 0 && !this.lines[lineIndex].isVisible()) {
lineIndex--;
}
if (lineIndex === 0 && !this.lines[lineIndex].isVisible()) {
// Could not reach a real line
return 1;
}
const deltaLineNumber = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1));
return this.lines[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1));
}
getAllOverviewRulerDecorations(ownerId, filterOutValidation, theme) {
const decorations = this.model.getOverviewRulerDecorations(ownerId, filterOutValidation);
const result = new OverviewRulerDecorations();
for (const decoration of decorations) {
const opts = decoration.options.overviewRuler;
const lane = opts ? opts.position : 0;
if (lane === 0) {
continue;
}
const color = opts.getColor(theme);
const viewStartLineNumber = this._getViewLineNumberForModelPosition(decoration.range.startLineNumber, decoration.range.startColumn);
const viewEndLineNumber = this._getViewLineNumberForModelPosition(decoration.range.endLineNumber, decoration.range.endColumn);
result.accept(color, viewStartLineNumber, viewEndLineNumber, lane);
}
return result.result;
}
getDecorationsInRange(range, ownerId, filterOutValidation) {
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);
}
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.lines[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));
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));
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
let finalResult = [], 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 viewLineNumber = this._toValidViewLineNumber(position.lineNumber);
const r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
const lineIndex = r.index;
const remainder = r.remainder;
return this.lines[lineIndex].getInjectedTextAt(remainder, position.column);
}
normalizePosition(position, affinity) {
const viewLineNumber = this._toValidViewLineNumber(position.lineNumber);
const r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
const lineIndex = r.index;
const remainder = r.remainder;
return this.lines[lineIndex].normalizePosition(this.model, lineIndex + 1, remainder, position, affinity);
}
getLineIndentColumn(lineNumber) {
const viewLineNumber = this._toValidViewLineNumber(lineNumber);
const r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
const lineIndex = r.index;
const remainder = r.remainder;
if (remainder === 0) {
return this.model.getLineIndentColumn(lineIndex + 1);
}
// 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.SplitLinesCollection = SplitLinesCollection;
class VisibleIdentitySplitLine {
constructor() { }
isVisible() {
return true;
}
setVisible(isVisible) {
if (isVisible) {
return this;
}
return InvisibleIdentitySplitLine.INSTANCE;
}
getLineBreakData() {
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) {
let lineTokens = model.getLineTokens(modelLineNumber);
let 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(model, modelLineNumber, outputLineIndex, outputPosition, affinity) {
return outputPosition;
}
getInjectedTextAt(_outputLineIndex, _outputColumn) {
return null;
}
}
VisibleIdentitySplitLine.INSTANCE = new VisibleIdentitySplitLine();
class InvisibleIdentitySplitLine {
constructor() { }
isVisible() {
return false;
}
setVisible(isVisible) {
if (!isVisible) {
return this;
}
return VisibleIdentitySplitLine.INSTANCE;
}
getLineBreakData() {
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(model, modelLineNumber, outputLineIndex, outputPosition, affinity) {
throw new Error('Not supported');
}
getInjectedTextAt(_outputLineIndex, _outputColumn) {
throw new Error('Not supported');
}
}
InvisibleIdentitySplitLine.INSTANCE = new InvisibleIdentitySplitLine();
class SplitLine {
constructor(lineBreakData, isVisible) {
this._lineBreakData = lineBreakData;
this._isVisible = isVisible;
}
isVisible() {
return this._isVisible;
}
setVisible(isVisible) {
this._isVisible = isVisible;
return this;
}
getLineBreakData() {
return this._lineBreakData;
}
getViewLineCount() {
if (!this._isVisible) {
return 0;
}
return this._lineBreakData.breakOffsets.length;
}
getInputStartOffsetOfOutputLineIndex(outputLineIndex) {
return this._lineBreakData.getInputOffsetOfOutputPosition(outputLineIndex, 0);
}
getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex) {
if (outputLineIndex + 1 === this._lineBreakData.breakOffsets.length) {
return model.getLineMaxColumn(modelLineNumber) - 1;
}
return this._lineBreakData.getInputOffsetOfOutputPosition(outputLineIndex + 1, 0);
}
getViewLineContent(model, modelLineNumber, outputLineIndex) {
if (!this._isVisible) {
throw new Error('Not supported');
}
// These offsets refer to model text with injected text.
const startOffset = outputLineIndex > 0 ? this._lineBreakData.breakOffsets[outputLineIndex - 1] : 0;
const endOffset = outputLineIndex < this._lineBreakData.breakOffsets.length
? this._lineBreakData.breakOffsets[outputLineIndex]
// This case might not be possible anyway, but we clamp the value to be on the safe side.
: this._lineBreakData.breakOffsets[this._lineBreakData.breakOffsets.length - 1];
let r;
if (this._lineBreakData.injectionOffsets !== null) {
const injectedTexts = this._lineBreakData.injectionOffsets.map((offset, idx) => new textModelEvents_1.LineInjectedText(0, 0, offset + 1, this._lineBreakData.injectionOptions[idx], 0));
r = textModelEvents_1.LineInjectedText.applyInjectedText(model.getLineContent(modelLineNumber), injectedTexts).substring(startOffset, endOffset);
}
else {
r = model.getValueInRange({
startLineNumber: modelLineNumber,
startColumn: startOffset + 1,
endLineNumber: modelLineNumber,
endColumn: endOffset + 1
});
}
if (outputLineIndex > 0) {
r = spaces(this._lineBreakData.wrappedTextIndentLength) + r;
}
return r;
}
getViewLineLength(model, modelLineNumber, outputLineIndex) {
// TODO @hediet make this method a member of LineBreakData.
if (!this._isVisible) {
throw new Error('Not supported');
}
// These offsets refer to model text with injected text.
const startOffset = outputLineIndex > 0 ? this._lineBreakData.breakOffsets[outputLineIndex - 1] : 0;
const endOffset = outputLineIndex < this._lineBreakData.breakOffsets.length
? this._lineBreakData.breakOffsets[outputLineIndex]
// This case might not be possible anyway, but we clamp the value to be on the safe side.
: this._lineBreakData.breakOffsets[this._lineBreakData.breakOffsets.length - 1];
let r = endOffset - startOffset;
if (outputLineIndex > 0) {
r = this._lineBreakData.wrappedTextIndentLength + r;
}
return r;
}
getViewLineMinColumn(_model, _modelLineNumber, outputLineIndex) {
if (!this._isVisible) {
throw new Error('Not supported');
}
return this._getViewLineMinColumn(outputLineIndex);
}
_getViewLineMinColumn(outputLineIndex) {
if (outputLineIndex > 0) {
return this._lineBreakData.wrappedTextIndentLength + 1;
}
return 1;
}
getViewLineMaxColumn(model, modelLineNumber, outputLineIndex) {
if (!this._isVisible) {
throw new Error('Not supported');
}
return this.getViewLineLength(model, modelLineNumber, outputLineIndex) + 1;
}
getViewLineData(model, modelLineNumber, outputLineIndex) {
if (!this._isVisible) {
throw new Error('Not supported');
}
const lineBreakData = this._lineBreakData;
const deltaStartIndex = (outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength : 0);
const injectionOffsets = lineBreakData.injectionOffsets;
const injectionOptions = lineBreakData.injectionOptions;
let lineContent;
let tokens;
let inlineDecorations;
if (injectionOffsets) {
const lineTokens = model.getLineTokens(modelLineNumber).withInserted(injectionOffsets.map((offset, idx) => ({
offset,
text: injectionOptions[idx].content,
tokenMetadata: lineTokens_1.LineTokens.defaultTokenMetadata
})));
const lineStartOffsetInUnwrappedLine = outputLineIndex > 0 ? lineBreakData.breakOffsets[outputLineIndex - 1] : 0;
const lineEndOffsetInUnwrappedLine = lineBreakData.breakOffsets[outputLineIndex];
lineContent = lineTokens.getLineContent().substring(lineStartOffsetInUnwrappedLine, lineEndOffsetInUnwrappedLine);
tokens = lineTokens.sliceAndInflate(lineStartOffsetInUnwrappedLine, lineEndOffsetInUnwrappedLine, deltaStartIndex);
inlineDecorations = new Array();
let totalInjectedTextLengthBefore = 0;
for (let i = 0; i < injectionOffsets.length; i++) {
const length = injectionOptions[i].content.length;
const injectedTextStartOffsetInUnwrappedLine = injectionOffsets[i] + totalInjectedTextLengthBefore;
const injectedTextEndOffsetInUnwrappedLine = injectionOffsets[i] + totalInjectedTextLengthBefore + length;
if (injectedTextStartOffsetInUnwrappedLine > lineEndOffsetInUnwrappedLine) {
// Injected text only starts in later wrapped lines.
break;
}
if (lineStartOffsetInUnwrappedLine < injectedTextEndOffsetInUnwrappedLine) {
// Injected text ends after or in this line (but also starts in or before this line).
const options = injectionOptions[i];
if (options.inlineClassName) {
const offset = (outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength : 0);
const start = offset + Math.max(injectedTextStartOffsetInUnwrappedLine - lineStartOffsetInUnwrappedLine, 0);
const end = offset + Math.min(injectedTextEndOffsetInUnwrappedLine - lineStartOffsetInUnwrappedLine, lineEndOffsetInUnwrappedLine);
if (start !== end) {
inlineDecorations.push(new viewModel_1.SingleLineInlineDecoration(start, end, options.inlineClassName, options.inlineClassNameAffectsLetterSpacing));
}
}
}
totalInjectedTextLengthBefore += length;
}
}
else {
const startOffset = this.getInputStartOffsetOfOutputLineIndex(outputLineIndex);
const endOffset = this.getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex);
const lineTokens = model.getLineTokens(modelLineNumber);
lineContent = model.getValueInRange({
startLineNumber: modelLineNumber,
startColumn: startOffset + 1,
endLineNumber: modelLineNumber,
endColumn: endOffset + 1
});
tokens = lineTokens.sliceAndInflate(startOffset, endOffset, deltaStartIndex);
inlineDecorations = null;
}
if (outputLineIndex > 0) {
lineContent = spaces(lineBreakData.wrappedTextIndentLength) + lineContent;
}
const minColumn = (outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength + 1 : 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);
}
getViewLinesData(model, modelLineNumber, fromOuputLineIndex, toOutputLineIndex, globalStartIndex, needed, result) {
if (!this._isVisible) {
throw new Error('Not supported');
}
for (let outputLineIndex = fromOuputLineIndex; outputLineIndex < toOutputLineIndex; outputLineIndex++) {
let globalIndex = globalStartIndex + outputLineIndex - fromOuputLineIndex;
if (!needed[globalIndex]) {
result[globalIndex] = null;
continue;
}
result[globalIndex] = this.getViewLineData(model, modelLineNumber, outputLineIndex);
}
}
getModelColumnOfViewPosition(outputLineIndex, outputColumn) {
if (!this._isVisible) {
throw new Error('Not supported');
}
let adjustedColumn = outputColumn - 1;
if (outputLineIndex > 0) {
if (adjustedColumn < this._lineBreakData.wrappedTextIndentLength) {
adjustedColumn = 0;
}
else {
adjustedColumn -= this._lineBreakData.wrappedTextIndentLength;
}
}
return this._lineBreakData.getInputOffsetOfOutputPosition(outputLineIndex, adjustedColumn) + 1;
}
getViewPositionOfModelPosition(deltaLineNumber, inputColumn, affinity = 2 /* None */) {
if (!this._isVisible) {
throw new Error('Not supported');
}
let r = this._lineBreakData.getOutputPositionOfInputOffset(inputColumn - 1, affinity);
let outputLineIndex = r.outputLineIndex;
let outputColumn = r.outputOffset + 1;
if (outputLineIndex > 0) {
outputColumn += this._lineBreakData.wrappedTextIndentLength;
}
// console.log('in -> out ' + deltaLineNumber + ',' + inputColumn + ' ===> ' + (deltaLineNumber+outputLineIndex) + ',' + outputColumn);
return new position_1.Position(deltaLineNumber + outputLineIndex, outputColumn);
}
getViewLineNumberOfModelPosition(deltaLineNumber, inputColumn) {
if (!this._isVisible) {
throw new Error('Not supported');
}
const r = this._lineBreakData.getOutputPositionOfInputOffset(inputColumn - 1);
return (deltaLineNumber + r.outputLineIndex);
}
normalizePosition(model, modelLineNumber, outputLineIndex, outputPosition, affinity) {
if (this._lineBreakData.injectionOffsets !== null) {
const baseViewLineNumber = outputPosition.lineNumber - outputLineIndex;
const offsetInUnwrappedLine = this._lineBreakData.outputPositionToOffsetInUnwrappedLine(outputLineIndex, outputPosition.column - 1);
const normalizedOffsetInUnwrappedLine = this._lineBreakData.normalizeOffsetAroundInjections(offsetInUnwrappedLine, affinity);
if (normalizedOffsetInUnwrappedLine !== offsetInUnwrappedLine) {
// injected text caused a change
return this._lineBreakData.getOutputPositionOfOffsetInUnwrappedLine(normalizedOffsetInUnwrappedLine, affinity).toPosition(baseViewLineNumber, this._lineBreakData.wrappedTextIndentLength);
}
}
if (affinity === 0 /* Left */) {
if (outputLineIndex > 0 && outputPosition.column === this._getViewLineMinColumn(outputLineIndex)) {
return new position_1.Position(outputPosition.lineNumber - 1, this.getViewLineMaxColumn(model, modelLineNumber, outputLineIndex - 1));
}
}
else if (affinity === 1 /* Right */) {
const maxOutputLineIndex = this.getViewLineCount() - 1;
if (outputLineIndex < maxOutputLineIndex && outputPosition.column === this.getViewLineMaxColumn(model, modelLineNumber, outputLineIndex)) {
return new position_1.Position(outputPosition.lineNumber + 1, this._getViewLineMinColumn(outputLineIndex + 1));
}
}
return outputPosition;
}
getInjectedTextAt(outputLineIndex, outputColumn) {
return this._lineBreakData.getInjectedText(outputLineIndex, outputColumn - 1);
}
}
exports.SplitLine = SplitLine;
let _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(' ');
}
function createSplitLine(lineBreakData, isVisible) {
if (lineBreakData === null) {
// No mapping needed
if (isVisible) {
return VisibleIdentitySplitLine.INSTANCE;
}
return InvisibleIdentitySplitLine.INSTANCE;
}
else {
return new SplitLine(lineBreakData, isVisible);
}
}
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;
}
}
exports.IdentityCoordinatesConverter = IdentityCoordinatesConverter;
class IdentityLinesCollection {
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() {
let 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, lineNumber), null, null];
}
acceptVersionId(_versionId) {
}
getViewLineCount() {
return this.model.getLineCount();
}
getActiveIndentGuide(viewLineNumber, _minLineNumber, _maxLineNumber) {
return {
startLineNumber: viewLineNumber,
endLineNumber: viewLineNumber,
indent: 0
};
}
getViewLinesIndentGuides(viewStartLineNumber, viewEndLineNumber) {
const viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;
let 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) {
let lineTokens = this.model.getLineTokens(viewLineNumber);
let 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);
let result = [];
for (let lineNumber = viewStartLineNumber; lineNumber <= viewEndLineNumber; lineNumber++) {
let idx = lineNumber - viewStartLineNumber;
if (!needed[idx]) {
result[idx] = null;
}
result[idx] = this.getViewLineData(lineNumber);
}
return result;
}
getAllOverviewRulerDecorations(ownerId, filterOutValidation, theme) {
const decorations = this.model.getOverviewRulerDecorations(ownerId, filterOutValidation);
const result = new OverviewRulerDecorations();
for (const decoration of decorations) {
const opts = decoration.options.overviewRuler;
const lane = opts ? opts.position : 0;
if (lane === 0) {
continue;
}
const color = opts.getColor(theme);
const viewStartLineNumber = decoration.range.startLineNumber;
const viewEndLineNumber = decoration.range.endLineNumber;
result.accept(color, viewStartLineNumber, viewEndLineNumber, lane);
}
return result.result;
}
getDecorationsInRange(range, ownerId, filterOutValidation) {
return this.model.getDecorationsInRange(range, ownerId, filterOutValidation);
}
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.IdentityLinesCollection = IdentityLinesCollection;
class OverviewRulerDecorations {
constructor() {
this.result = Object.create(null);
}
accept(color, startLineNumber, endLineNumber, lane) {
let prev = this.result[color];
if (prev) {
const prevLane = prev[prev.length - 3];
const prevEndLineNumber = prev[prev.length - 1];
if (prevLane === lane && prevEndLineNumber + 1 >= startLineNumber) {
// merge into prev
if (endLineNumber > prevEndLineNumber) {
prev[prev.length - 1] = endLineNumber;
}
return;
}
// push
prev.push(lane, startLineNumber, endLineNumber);
}
else {
this.result[color] = [lane, startLineNumber, 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[554/*vs/editor/common/viewModel/viewModelImpl*/], __M([0/*require*/,1/*exports*/,29/*vs/base/common/color*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,35/*vs/editor/common/config/editorOptions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,96/*vs/editor/common/model/textModelEvents*/,18/*vs/editor/common/modes*/,246/*vs/editor/common/modes/textToHtmlTokenizer*/,247/*vs/editor/common/viewModel/minimapTokensColorTracker*/,175/*vs/editor/common/view/viewEvents*/,406/*vs/editor/common/viewLayout/viewLayout*/,553/*vs/editor/common/viewModel/splitLinesCollection*/,62/*vs/editor/common/viewModel/viewModel*/,465/*vs/editor/common/viewModel/viewModelDecorations*/,15/*vs/base/common/async*/,17/*vs/base/common/platform*/,245/*vs/editor/common/controller/cursor*/,40/*vs/editor/common/controller/cursorCommon*/,177/*vs/editor/common/viewModel/viewModelEventDispatcher*/]), function (require, exports, color_1, lifecycle_1, strings, editorOptions_1, position_1, range_1, textModelEvents, modes_1, textToHtmlTokenizer_1, minimapTokensColorTracker_1, viewEvents, viewLayout_1, splitLinesCollection_1, viewModel_1, viewModelDecorations_1, async_1, platform, cursor_1, cursorCommon_1, viewModelEventDispatcher_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) {
super();
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.getLanguageIdentifier(), this.model.getOptions(), this._configuration);
this._tokenizeViewportSoon = this._register(new async_1.RunOnceScheduler(() => this.tokenizeViewport(), 50));
this._updateConfigurationViewLineCount = this._register(new async_1.RunOnceScheduler(() => this._updateConfigurationViewLineCountNow(), 0));
this._hasFocus = false;
this._viewportStartLine = -1;
this._viewportStartLineTrackedRange = null;
this._viewportStartLineDelta = 0;
if (USE_IDENTITY_LINES_COLLECTION && this.model.isTooLargeForTokenization()) {
this._lines = new splitLinesCollection_1.IdentityLinesCollection(this.model);
}
else {
const options = this._configuration.options;
const fontInfo = options.get(41 /* fontInfo */);
const wrappingStrategy = options.get(123 /* wrappingStrategy */);
const wrappingInfo = options.get(130 /* wrappingInfo */);
const wrappingIndent = options.get(122 /* wrappingIndent */);
this._lines = new splitLinesCollection_1.SplitLinesCollection(this._editorId, this.model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, this.model.getOptions().tabSize, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent);
}
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._tokenizeViewportSoon.schedule();
}
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._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.invalidateMinimapColorCache();
this._viewportStartLineTrackedRange = this.model._setTrackedRange(this._viewportStartLineTrackedRange, null, 1 /* NeverGrowsWhenTypingAtEdges */);
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());
}
tokenizeViewport() {
const linesViewportData = this.viewLayout.getLinesViewportData();
const startPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(linesViewportData.startLineNumber, 1));
const endPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(linesViewportData.endLineNumber, 1));
this.model.tokenizeViewport(startPosition.lineNumber, endPosition.lineNumber);
}
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());
}
onDidColorThemeChange() {
this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewThemeChangedEvent());
}
_onConfigurationChanged(eventsCollector, e) {
// We might need to restore the current centered view range, so save it (if available)
let previousViewportStartModelPosition = null;
if (this._viewportStartLine !== -1) {
let previousViewportStartViewPosition = new position_1.Position(this._viewportStartLine, this.getLineMinColumn(this._viewportStartLine));
previousViewportStartModelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(previousViewportStartViewPosition);
}
let restorePreviousViewportStart = false;
const options = this._configuration.options;
const fontInfo = options.get(41 /* fontInfo */);
const wrappingStrategy = options.get(123 /* wrappingStrategy */);
const wrappingInfo = options.get(130 /* wrappingInfo */);
const wrappingIndent = options.get(122 /* wrappingIndent */);
if (this._lines.setWrappingSettings(fontInfo, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent)) {
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());
if (this.viewLayout.getCurrentScrollTop() !== 0) {
// Never change the scroll position from 0 to something else...
restorePreviousViewportStart = true;
}
this._updateConfigurationViewLineCount.schedule();
}
if (e.hasChanged(79 /* readOnly */)) {
// Must read again all decorations due to readOnly filtering
this._decorations.reset();
eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null));
}
eventsCollector.emitViewEvent(new viewEvents.ViewConfigurationChangedEvent(e));
this.viewLayout.onConfigurationChanged(e);
if (restorePreviousViewportStart && previousViewportStartModelPosition) {
const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(previousViewportStartModelPosition);
const viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
this.viewLayout.setScrollPosition({ scrollTop: viewPositionTop + this._viewportStartLineDelta }, 1 /* Immediate */);
}
if (cursorCommon_1.CursorConfiguration.shouldRecreate(e)) {
this.cursorConfig = new cursorCommon_1.CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration);
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.changes;
const versionId = (e instanceof textModelEvents.ModelRawContentChangedEvent ? e.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 /* 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 /* 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();
let lineBreaksOffset = 0;
for (const change of changes) {
switch (change.changeType) {
case 1 /* Flush */: {
this._lines.onModelFlushed();
eventsCollector.emitViewEvent(new viewEvents.ViewFlushedEvent());
this._decorations.reset();
this.viewLayout.onFlushed(this.getLineCount());
hadOtherModelChange = true;
break;
}
case 3 /* 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 /* LinesInserted */: {
const insertedLineBreaks = lineBreaks.slice(lineBreaksOffset, lineBreaksOffset + change.detail.length);
lineBreaksOffset += 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 /* LineChanged */: {
const changedLineBreakData = lineBreaks[lineBreaksOffset];
lineBreaksOffset++;
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 /* 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
this._viewportStartLine = -1;
this._configuration.setMaxLineNumber(this.model.getLineCount());
this._updateConfigurationViewLineCountNow();
// Recover viewport
if (!this._hasFocus && this.model.getAttachedEditorCount() >= 2 && this._viewportStartLineTrackedRange) {
const modelRange = this.model._getTrackedRange(this._viewportStartLineTrackedRange);
if (modelRange) {
const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelRange.getStartPosition());
const viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
this.viewLayout.setScrollPosition({ scrollTop: viewPositionTop + this._viewportStartLineDelta }, 1 /* Immediate */);
}
}
try {
const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
this._cursor.onModelContentChanged(eventsCollector, e);
}
finally {
this._eventDispatcher.endEmitViewEvents();
}
}));
this._register(this.model.onDidChangeTokens((e) => {
let 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));
if (e.tokenizationSupportChanged) {
this._tokenizeViewportSoon.schedule();
}
}));
this._register(this.model.onDidChangeLanguageConfiguration((e) => {
this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewLanguageConfigurationEvent());
this.cursorConfig = new cursorCommon_1.CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration);
this._cursor.updateConfiguration(this.cursorConfig);
}));
this._register(this.model.onDidChangeLanguage((e) => {
this.cursorConfig = new cursorCommon_1.CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration);
this._cursor.updateConfiguration(this.cursorConfig);
}));
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.getLanguageIdentifier(), this.model.getOptions(), this._configuration);
this._cursor.updateConfiguration(this.cursorConfig);
}));
this._register(this.model.onDidChangeDecorations((e) => {
this._decorations.onModelDecorationsChanged();
this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewDecorationsChangedEvent(e));
}));
}
setHiddenAreas(ranges) {
try {
const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
let lineMappingChanged = this._lines.setHiddenAreas(ranges);
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();
}
}
finally {
this._eventDispatcher.endEmitViewEvents();
}
this._updateConfigurationViewLineCount.schedule();
}
getVisibleRangesPlusViewportAboveBelow() {
const layoutInfo = this._configuration.options.get(129 /* layoutInfo */);
const lineHeight = this._configuration.options.get(57 /* 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);
}
_toModelVisibleRanges(visibleViewRange) {
const visibleRange = this.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
const hiddenAreas = this._lines.getHiddenAreas();
if (hiddenAreas.length === 0) {
return [visibleRange];
}
let result = [], resultLen = 0;
let startLineNumber = visibleRange.startLineNumber;
let startColumn = visibleRange.startColumn;
let endLineNumber = visibleRange.endLineNumber;
let 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;
}
getTextModelOptions() {
return this.model.getOptions();
}
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._viewportStartLine = startLineNumber;
let position = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(startLineNumber, this.getLineMinColumn(startLineNumber)));
this._viewportStartLineTrackedRange = this.model._setTrackedRange(this._viewportStartLineTrackedRange, new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column), 1 /* NeverGrowsWhenTypingAtEdges */);
const viewportStartLineTop = this.viewLayout.getVerticalOffsetForLineNumber(startLineNumber);
const scrollTop = this.viewLayout.getCurrentScrollTop();
this._viewportStartLineDelta = scrollTop - viewportStartLineTop;
}
getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) {
return this._lines.getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber);
}
getLinesIndentGuides(startLineNumber, endLineNumber) {
return this._lines.getViewLinesIndentGuides(startLineNumber, endLineNumber);
}
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;
}
getDecorationsInViewport(visibleRange) {
return this._decorations.getDecorationsViewportData(visibleRange).decorations;
}
getInjectedTextAt(viewPosition) {
return this._lines.getInjectedTextAt(viewPosition);
}
getViewLineRenderingData(visibleRange, lineNumber) {
let mightContainRTL = this.model.mightContainRTL();
let mightContainNonBasicASCII = this.model.mightContainNonBasicASCII();
let tabSize = this.getTabSize();
let lineData = this._lines.getViewLineData(lineNumber);
let allInlineDecorations = this._decorations.getDecorationsViewportData(visibleRange).inlineDecorations;
let inlineDecorations = allInlineDecorations[lineNumber - visibleRange.startLineNumber];
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) {
let result = this._lines.getViewLinesData(startLineNumber, endLineNumber, needed);
return new viewModel_1.MinimapLinesRenderingData(this.getTabSize(), result);
}
getAllOverviewRulerDecorations(theme) {
return this._lines.getAllOverviewRulerDecorations(this._editorId, (0, editorOptions_1.filterValidationDecorations)(this._configuration.options), theme);
}
invalidateOverviewRulerColorCache() {
const decorations = this.model.getOverviewRulerDecorations();
for (const decoration of decorations) {
const opts = decoration.options.overviewRuler;
if (opts) {
opts.invalidateCachedColor();
}
}
}
invalidateMinimapColorCache() {
const decorations = this.model.getAllDecorations();
for (const decoration of decorations) {
const opts = decoration.options.minimap;
if (opts) {
opts.invalidateCachedColor();
}
}
}
getValueInRange(range, eol) {
const modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range);
return this.model.getValueInRange(modelRange, eol);
}
getModelLineMaxColumn(modelLineNumber) {
return this.model.getLineMaxColumn(modelLineNumber);
}
validateModelPosition(position) {
return this.model.validatePosition(position);
}
validateModelRange(range) {
return this.model.validateRange(range);
}
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);
}
getEOL() {
return this.model.getEOL();
}
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
let 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 /* CRLF */ : 0 /* TextDefined */));
}
prevModelLineNumber = modelLineNumber;
}
return result.length === 1 ? result[0] : result;
}
let result = [];
for (const modelRange of modelRanges) {
if (!modelRange.isEmpty()) {
result.push(this.model.getValueInRange(modelRange, forceCRLF ? 2 /* CRLF */ : 0 /* TextDefined */));
}
}
return result.length === 1 ? result[0] : result;
}
getRichTextToCopy(modelRanges, emptySelectionClipboard) {
const languageId = this.model.getLanguageIdentifier();
if (languageId.id === 1 /* PlainText */) {
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(41 /* 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.language,
html: (`<div style="`
+ `color: ${colorMap[1 /* DefaultForeground */]};`
+ `background-color: ${colorMap[2 /* 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.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() {
let colorMap = modes_1.TokenizationRegistry.getColorMap();
let 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 model
pushStackElement() {
this.model.pushStackElement();
}
//#endregion
//#region cursor operations
getPrimaryCursorState() {
return this._cursor.getPrimaryCursorState();
}
getLastAddedCursorIndex() {
return this._cursor.getLastAddedCursorIndex();
}
getCursorStates() {
return this._cursor.getCursorStates();
}
setCursorStates(source, reason, states) {
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 /* 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._cursor.setIsDoingComposition(true);
this._executeCursorEdit(eventsCollector => this._cursor.startComposition(eventsCollector));
}
endComposition(source) {
this._cursor.setIsDoingComposition(false);
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));
}
revealPrimaryCursor(source, revealHorizontal) {
this._withViewEventsCollector(eventsCollector => this._cursor.revealPrimary(eventsCollector, source, revealHorizontal, 0 /* 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, viewRange, null, 0 /* Simple */, true, 0 /* 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, viewRange, null, 0 /* Simple */, true, 0 /* Smooth */)));
}
revealRange(source, revealHorizontal, viewRange, verticalType, scrollType) {
this._withViewEventsCollector(eventsCollector => eventsCollector.emitViewEvent(new viewEvents.ViewRevealRangeRequestEvent(source, viewRange, null, verticalType, revealHorizontal, scrollType)));
}
//#endregion
//#region viewLayout
getVerticalOffsetForLineNumber(viewLineNumber) {
return this.viewLayout.getVerticalOffsetForLineNumber(viewLineNumber);
}
getScrollTop() {
return this.viewLayout.getCurrentScrollTop();
}
setScrollTop(newScrollTop, scrollType) {
this.viewLayout.setScrollPosition({ scrollTop: newScrollTop }, scrollType);
}
setScrollPosition(position, type) {
this.viewLayout.setScrollPosition(position, type);
}
deltaScrollNow(deltaScrollLeft, deltaScrollTop) {
this.viewLayout.deltaScrollNow(deltaScrollLeft, deltaScrollTop);
}
changeWhitespace(callback) {
const hadAChange = this.viewLayout.changeWhitespace(callback);
if (hadAChange) {
this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewZonesChangedEvent());
this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_1.ViewZonesChangedEvent());
}
}
setMaxLineWidth(maxLineWidth) {
this.viewLayout.setMaxLineWidth(maxLineWidth);
}
//#endregion
_withViewEventsCollector(callback) {
try {
const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
callback(eventsCollector);
}
finally {
this._eventDispatcher.endEmitViewEvents();
}
}
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;
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/documentSymbols/outlineModel*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,49/*vs/base/common/map*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/modes*/,54/*vs/base/common/iterator*/,139/*vs/editor/common/modes/languageFeatureRegistry*/]), function (require, exports, arrays_1, cancellation_1, errors_1, map_1, range_1, modes_1, iterator_1, languageFeatureRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OutlineModel = exports.OutlineGroup = exports.OutlineElement = exports.TreeElement = void 0;
class TreeElement {
remove() {
if (this.parent) {
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 {
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;
}
static create(textModel, token) {
let key = this._keys.for(textModel, true);
let data = OutlineModel._requests.get(key);
if (!data) {
let source = new cancellation_1.CancellationTokenSource();
data = {
promiseCnt: 0,
source,
promise: OutlineModel._create(textModel, source.token),
model: undefined,
};
OutlineModel._requests.set(key, data);
// keep moving average of request durations
const now = Date.now();
data.promise.then(() => {
this._requestDurations.update(textModel, Date.now() - now);
});
}
if (data.model) {
// resolved -> return data
return Promise.resolve(data.model);
}
// increase usage counter
data.promiseCnt += 1;
token.onCancellationRequested(() => {
// last -> cancel provider request, remove cached promise
if (--data.promiseCnt === 0) {
data.source.cancel();
OutlineModel._requests.delete(key);
}
});
return new Promise((resolve, reject) => {
data.promise.then(model => {
data.model = model;
resolve(model);
}, err => {
OutlineModel._requests.delete(key);
reject(err);
});
});
}
static _create(textModel, token) {
const cts = new cancellation_1.CancellationTokenSource(token);
const result = new OutlineModel(textModel.uri);
const provider = modes_1.DocumentSymbolProviderRegistry.ordered(textModel);
const promises = provider.map((provider, index) => {
var _a;
let id = TreeElement.findId(`provider_${index}`, result);
let group = new OutlineGroup(id, result, (_a = provider.displayName) !== null && _a !== void 0 ? _a : '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 = modes_1.DocumentSymbolProviderRegistry.onDidChange(() => {
const newProvider = modes_1.DocumentSymbolProviderRegistry.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(textModel, token);
}
else {
return result._compact();
}
}).finally(() => {
listener.dispose();
});
}
static _makeOutlineElement(info, container) {
let id = TreeElement.findId(info, container);
let 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);
}
_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
let group = iterator_1.Iterable.first(this._groups.values());
for (let [, 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) => range_1.Range.compareRangesUsingStarts(a.range, b.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;
OutlineModel._requestDurations = new languageFeatureRegistry_1.LanguageFeatureRequestDelays(modes_1.DocumentSymbolProviderRegistry, 350);
OutlineModel._requests = new map_1.LRUCache(9, 0.75);
OutlineModel._keys = new class {
constructor() {
this._counter = 1;
this._data = new WeakMap();
}
for(textModel, version) {
return `${textModel.id}/${version ? textModel.getVersionId() : ''}/${this._hash(modes_1.DocumentSymbolProviderRegistry.all(textModel))}`;
}
_hash(providers) {
let result = '';
for (const provider of providers) {
let n = this._data.get(provider);
if (typeof n === 'undefined') {
n = this._counter++;
this._data.set(provider, n);
}
result += n;
}
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[555/*vs/editor/contrib/folding/indentRangeProvider*/], __M([0/*require*/,1/*exports*/,178/*vs/editor/contrib/folding/foldingRanges*/,31/*vs/editor/common/model/textModel*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, foldingRanges_1, textModel_1, languageConfigurationRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.computeRanges = exports.RangesCollector = exports.IndentRangeProvider = exports.ID_INDENT_PROVIDER = void 0;
const MAX_FOLDING_REGIONS_FOR_INDENT_LIMIT = 5000;
exports.ID_INDENT_PROVIDER = 'indent';
class IndentRangeProvider {
constructor(editorModel) {
this.editorModel = editorModel;
this.id = exports.ID_INDENT_PROVIDER;
}
dispose() {
}
compute(cancelationToken) {
let foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(this.editorModel.getLanguageIdentifier().id);
let offSide = foldingRules && !!foldingRules.offSide;
let markers = foldingRules && foldingRules.markers;
return Promise.resolve(computeRanges(this.editorModel, offSide, markers));
}
}
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;
}
let 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) {
if (this._length <= this._foldingRangesLimit) {
// reverse and create arrays of the exact length
let startIndexes = new Uint32Array(this._length);
let 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 {
let entries = 0;
let maxIndent = this._indentOccurrences.length;
for (let i = 0; i < this._indentOccurrences.length; i++) {
let n = this._indentOccurrences[i];
if (n) {
if (n + entries > this._foldingRangesLimit) {
maxIndent = i;
break;
}
entries += n;
}
}
const tabSize = model.getOptions().tabSize;
// reverse and create arrays of the exact length
let startIndexes = new Uint32Array(this._foldingRangesLimit);
let endIndexes = new Uint32Array(this._foldingRangesLimit);
for (let i = this._length - 1, k = 0; i >= 0; i--) {
let startIndex = this._startIndexes[i];
let lineContent = model.getLineContent(startIndex);
let indent = textModel_1.TextModel.computeIndentLevel(lineContent, tabSize);
if (indent < maxIndent || (indent === maxIndent && entries++ < this._foldingRangesLimit)) {
startIndexes[k] = startIndex;
endIndexes[k] = this._endIndexes[i];
k++;
}
}
return new foldingRanges_1.FoldingRegions(startIndexes, endIndexes);
}
}
}
exports.RangesCollector = RangesCollector;
function computeRanges(model, offSide, markers, foldingRangesLimit = MAX_FOLDING_REGIONS_FOR_INDENT_LIMIT) {
const tabSize = model.getOptions().tabSize;
let result = new RangesCollector(foldingRangesLimit);
let pattern = undefined;
if (markers) {
pattern = new RegExp(`(${markers.start.source})|(?:${markers.end.source})`);
}
let previousRegions = [];
let 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--) {
let lineContent = model.getLineContent(line);
let indent = textModel_1.TextModel.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
let 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);
}
exports.computeRanges = computeRanges;
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/linesOperations/moveLinesCommand*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,184/*vs/editor/common/commands/shiftCommand*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,112/*vs/editor/common/modes/languageConfiguration*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/,232/*vs/editor/contrib/indentation/indentUtils*/]), function (require, exports, strings, shiftCommand_1, range_1, selection_1, languageConfiguration_1, languageConfigurationRegistry_1, indentUtils) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MoveLinesCommand = void 0;
class MoveLinesCommand {
constructor(selection, isMovingDown, autoIndent) {
this._selection = selection;
this._isMovingDown = isMovingDown;
this._autoIndent = autoIndent;
this._selectionId = null;
this._moveEndLineSelectionShrink = false;
}
getEditOperations(model, builder) {
let 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();
let indentConverter = this.buildIndentConverter(tabSize, indentSize, insertSpaces);
let virtualModel = {
getLineTokens: (lineNumber) => {
return model.getLineTokens(lineNumber);
},
getLanguageIdentifier: () => {
return model.getLanguageIdentifier();
},
getLanguageIdAtPosition: (lineNumber, column) => {
return model.getLanguageIdAtPosition(lineNumber, column);
},
getLineContent: null,
};
if (s.startLineNumber === s.endLineNumber && model.getLineMaxColumn(s.startLineNumber) === 1) {
// Current line is empty
let lineNumber = s.startLineNumber;
let 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)) {
let movingLineMatchResult = this.matchEnterRule(model, indentConverter, tabSize, movingLineNumber, s.startLineNumber - 1);
// if s.startLineNumber - 1 matches onEnter rule, we still honor that.
if (movingLineMatchResult !== null) {
let oldIndentation = strings.getLeadingWhitespace(model.getLineContent(movingLineNumber));
let newSpaceCnt = movingLineMatchResult + indentUtils.getSpaceCnt(oldIndentation, tabSize);
let newIndentation = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces);
insertingText = newIndentation + this.trimLeft(movingLineText);
}
else {
// no enter rule matches, let's check indentatin rules then.
virtualModel.getLineContent = (lineNumber) => {
if (lineNumber === s.startLineNumber) {
return model.getLineContent(movingLineNumber);
}
else {
return model.getLineContent(lineNumber);
}
};
let indentOfMovingLine = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber, 1), s.startLineNumber, indentConverter);
if (indentOfMovingLine !== null) {
let oldIndentation = strings.getLeadingWhitespace(model.getLineContent(movingLineNumber));
let newSpaceCnt = indentUtils.getSpaceCnt(indentOfMovingLine, tabSize);
let oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize);
if (newSpaceCnt !== oldSpaceCnt) {
let newIndentation = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces);
insertingText = newIndentation + this.trimLeft(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');
let 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.
virtualModel.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);
}
};
let newIndentatOfMovingBlock = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber, 1), s.startLineNumber + 1, indentConverter);
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)) {
virtualModel.getLineContent = (lineNumber) => {
if (lineNumber === movingLineNumber) {
return model.getLineContent(s.startLineNumber);
}
else {
return model.getLineContent(lineNumber);
}
};
let 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.
let indentOfFirstLine = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(s.startLineNumber, 1), movingLineNumber, indentConverter);
if (indentOfFirstLine !== null) {
// adjust the indentation of the moving block
let oldIndent = strings.getLeadingWhitespace(model.getLineContent(s.startLineNumber));
let newSpaceCnt = indentUtils.getSpaceCnt(indentOfFirstLine, tabSize);
let oldSpaceCnt = indentUtils.getSpaceCnt(oldIndent, tabSize);
if (newSpaceCnt !== oldSpaceCnt) {
let 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;
}
let movingLineText = model.getLineContent(line);
if (this.trimLeft(movingLineText).indexOf(this.trimLeft(enterPrefix)) >= 0) {
let oldIndentation = strings.getLeadingWhitespace(model.getLineContent(line));
let newIndentation = strings.getLeadingWhitespace(enterPrefix);
let indentMetadataOfMovelingLine = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentMetadata(model, line);
if (indentMetadataOfMovelingLine !== null && indentMetadataOfMovelingLine & 2 /* DECREASE_MASK */) {
newIndentation = indentConverter.unshiftIndent(newIndentation);
}
let newSpaceCnt = indentUtils.getSpaceCnt(newIndentation, tabSize);
let 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
let maxColumn = model.getLineMaxColumn(futureAboveLineNumber);
let enter = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(this._autoIndent, model, new range_1.Range(futureAboveLineNumber, maxColumn, futureAboveLineNumber, maxColumn));
return this.parseEnterResult(model, indentConverter, tabSize, line, enter);
}
else {
// go upwards, starting from `line - 1`
let validPrecedingLine = line - 1;
while (validPrecedingLine >= 1) {
let lineContent = model.getLineContent(validPrecedingLine);
let nonWhitespaceIdx = strings.lastNonWhitespaceIndex(lineContent);
if (nonWhitespaceIdx >= 0) {
break;
}
validPrecedingLine--;
}
if (validPrecedingLine < 1 || line > model.getLineCount()) {
return null;
}
let maxColumn = model.getLineMaxColumn(validPrecedingLine);
let enter = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(this._autoIndent, model, new range_1.Range(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn));
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);
}
let nonWhitespaceIdx = strings.lastNonWhitespaceIndex(lineContent);
if (nonWhitespaceIdx >= 0) {
break;
}
validPrecedingLine--;
}
if (validPrecedingLine < 1 || line > model.getLineCount()) {
return null;
}
let maxColumn = model.getLineMaxColumn(validPrecedingLine);
let enter = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(this._autoIndent, model, new range_1.Range(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn));
return this.parseEnterResult(model, indentConverter, tabSize, line, enter);
}
trimLeft(str) {
return str.replace(/^\s+/, '');
}
shouldAutoIndent(model, selection) {
if (this._autoIndent < 4 /* Full */) {
return false;
}
// if it's not easy to tokenize, we stop auto indent.
if (!model.isCheapToTokenize(selection.startLineNumber)) {
return false;
}
let languageAtSelectionStart = model.getLanguageIdAtPosition(selection.startLineNumber, 1);
let languageAtSelectionEnd = model.getLanguageIdAtPosition(selection.endLineNumber, 1);
if (languageAtSelectionStart !== languageAtSelectionEnd) {
return false;
}
if (languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentRulesSupport(languageAtSelectionStart) === null) {
return false;
}
return true;
}
getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, offset) {
for (let i = s.startLineNumber; i <= s.endLineNumber; i++) {
let lineContent = model.getLineContent(i);
let originalIndent = strings.getLeadingWhitespace(lineContent);
let originalSpacesCnt = indentUtils.getSpaceCnt(originalIndent, tabSize);
let newSpacesCnt = originalSpacesCnt + offset;
let 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;
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/zoneWidget/zoneWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,107/*vs/base/browser/ui/sash/sash*/,29/*vs/base/common/color*/,125/*vs/base/common/idGenerator*/,2/*vs/base/common/lifecycle*/,42/*vs/base/common/objects*/,3/*vs/editor/common/core/range*/,31/*vs/editor/common/model/textModel*/,362/*vs/css!vs/editor/contrib/zoneWidget/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 = exports.ViewZoneDelegate = 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) {
this.id = ''; // A valid zone id should be greater than 0
this.domNode = domNode;
this.afterLineNumber = afterLineNumber;
this.afterColumn = afterColumn;
this.heightInLines = heightInLines;
this._onDomNodeTop = onDomNodeTop;
this._onComputedHeight = onComputedHeight;
}
onDomNodeTop(top) {
this._onDomNodeTop(top);
}
onComputedHeight(height) {
this._onComputedHeight(height);
}
}
exports.ViewZoneDelegate = ViewZoneDelegate;
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 {
constructor(_editor) {
this._editor = _editor;
this._ruleName = Arrow._IdGenerator.nextId();
this._decorations = [];
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; margin-left: -${this._height}px; `);
}
show(where) {
this._decorations = this._editor.deltaDecorations(this._decorations, [{ range: range_1.Range.fromPositions(where), options: { description: 'zone-widget-arrow', className: this._ruleName, stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ } }]);
}
hide() {
this._editor.deltaDecorations(this._decorations, []);
}
}
Arrow._IdGenerator = new idGenerator_1.IdGenerator('.arrow-decoration-');
class ZoneWidget {
constructor(editor, options = {}) {
this._arrow = null;
this._overlayWidget = null;
this._resizeSash = null;
this._positionMarkerId = [];
this._viewZone = null;
this._disposables = new lifecycle_1.DisposableStore();
this.container = null;
this._isShowing = false;
this.editor = editor;
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.editor.deltaDecorations(this._positionMarkerId, []);
this._positionMarkerId = [];
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) {
let frameColor = this.options.frameColor.toString();
this.container.style.borderTopColor = frameColor;
this.container.style.borderBottomColor = frameColor;
}
if (this._arrow && this.options.arrowColor) {
let 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) {
let containerHeight = height - this._decoratingElementsHeight();
this.container.style.height = `${containerHeight}px`;
const layoutInfo = this.editor.getLayoutInfo();
this._doLayout(containerHeight, this._getWidth(layoutInfo));
}
if (this._resizeSash) {
this._resizeSash.layout();
}
}
get position() {
const [id] = this._positionMarkerId;
if (!id) {
return undefined;
}
const model = this.editor.getModel();
if (!model) {
return undefined;
}
const range = model.getDecorationRange(id);
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 = this.editor.deltaDecorations(this._positionMarkerId, [{ 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;
}
if (this._arrow) {
this._arrow.hide();
}
}
_decoratingElementsHeight() {
let lineHeight = this.editor.getOption(57 /* lineHeight */);
let result = 0;
if (this.options.showArrow) {
let arrowHeight = Math.round(lineHeight / 3);
result += 2 * arrowHeight;
}
if (this.options.showFrame) {
let 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(57 /* lineHeight */);
// adjust heightInLines to viewport
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._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';
}
let 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 revealLine = where.endLineNumber + 1;
if (revealLine <= model.getLineCount()) {
// reveal line below the zone widget
this.revealLine(revealLine, false);
}
else {
// reveal last line atop
this.revealLine(model.getLineCount(), true);
}
}
}
revealLine(lineNumber, isLastLine) {
if (isLastLine) {
this.editor.revealLineInCenter(lineNumber, 0 /* Smooth */);
}
else {
this.editor.revealLine(lineNumber, 0 /* 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 /* HORIZONTAL */ }));
if (!this.options.isResizeable) {
this._resizeSash.hide();
this._resizeSash.state = 0 /* 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) {
let lineDelta = (evt.currentY - data.startY) / this.editor.getOption(57 /* lineHeight */);
let roundedLineDelta = lineDelta < 0 ? Math.ceil(lineDelta) : Math.floor(lineDelta);
let 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[249/*vs/editor/standalone/common/monarch/monarchLexer*/], __M([0/*require*/,1/*exports*/,134/*vs/editor/common/core/token*/,18/*vs/editor/common/modes*/,77/*vs/editor/common/modes/nullMode*/,236/*vs/editor/standalone/common/monarch/monarchCommon*/]), function (require, exports, token_1, modes, nullMode_1, monarchCommon) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTokenizationSupport = exports.MonarchTokenizer = void 0;
const CACHE_STACK_DEPTH = 5;
/**
* Reuse the same stack elements up to a certain depth.
*/
class MonarchStackElementFactory {
constructor(maxCacheDepth) {
this._maxCacheDepth = maxCacheDepth;
this._entries = Object.create(null);
}
static create(parent, state) {
return this._INSTANCE.create(parent, state);
}
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;
}
}
MonarchStackElementFactory._INSTANCE = new MonarchStackElementFactory(CACHE_STACK_DEPTH);
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 EmbeddedModeData {
constructor(modeId, state) {
this.modeId = modeId;
this.state = state;
}
equals(other) {
return (this.modeId === other.modeId
&& this.state.equals(other.state));
}
clone() {
let stateClone = this.state.clone();
// save an object
if (stateClone === this.state) {
return this;
}
return new EmbeddedModeData(this.modeId, this.state);
}
}
/**
* Reuse the same line states up to a certain depth.
*/
class MonarchLineStateFactory {
constructor(maxCacheDepth) {
this._maxCacheDepth = maxCacheDepth;
this._entries = Object.create(null);
}
static create(stack, embeddedModeData) {
return this._INSTANCE.create(stack, embeddedModeData);
}
create(stack, embeddedModeData) {
if (embeddedModeData !== null) {
// no caching when embedding
return new MonarchLineState(stack, embeddedModeData);
}
if (stack !== null && stack.depth >= this._maxCacheDepth) {
// no caching above a certain depth
return new MonarchLineState(stack, embeddedModeData);
}
let stackElementId = MonarchStackElement.getStackElementId(stack);
let result = this._entries[stackElementId];
if (result) {
return result;
}
result = new MonarchLineState(stack, null);
this._entries[stackElementId] = result;
return result;
}
}
MonarchLineStateFactory._INSTANCE = new MonarchLineStateFactory(CACHE_STACK_DEPTH);
class MonarchLineState {
constructor(stack, embeddedModeData) {
this.stack = stack;
this.embeddedModeData = embeddedModeData;
}
clone() {
let embeddedModeDataClone = this.embeddedModeData ? this.embeddedModeData.clone() : null;
// save an object
if (embeddedModeDataClone === this.embeddedModeData) {
return this;
}
return MonarchLineStateFactory.create(this.stack, this.embeddedModeData);
}
equals(other) {
if (!(other instanceof MonarchLineState)) {
return false;
}
if (!this.stack.equals(other.stack)) {
return false;
}
if (this.embeddedModeData === null && other.embeddedModeData === null) {
return true;
}
if (this.embeddedModeData === null || other.embeddedModeData === null) {
return false;
}
return this.embeddedModeData.equals(other.embeddedModeData);
}
}
class MonarchClassicTokensCollector {
constructor() {
this._tokens = [];
this._language = null;
this._lastTokenType = null;
this._lastTokenLanguage = null;
}
enterMode(startOffset, modeId) {
this._language = modeId;
}
emit(startOffset, type) {
if (this._lastTokenType === type && this._lastTokenLanguage === this._language) {
return;
}
this._lastTokenType = type;
this._lastTokenLanguage = this._language;
this._tokens.push(new token_1.Token(startOffset, type, this._language));
}
nestedModeTokenize(embeddedModeLine, hasEOL, embeddedModeData, offsetDelta) {
const nestedModeId = embeddedModeData.modeId;
const embeddedModeState = embeddedModeData.state;
const nestedModeTokenizationSupport = modes.TokenizationRegistry.get(nestedModeId);
if (!nestedModeTokenizationSupport) {
this.enterMode(offsetDelta, nestedModeId);
this.emit(offsetDelta, '');
return embeddedModeState;
}
let nestedResult = nestedModeTokenizationSupport.tokenize(embeddedModeLine, hasEOL, embeddedModeState, offsetDelta);
this._tokens = this._tokens.concat(nestedResult.tokens);
this._lastTokenType = null;
this._lastTokenLanguage = null;
this._language = null;
return nestedResult.endState;
}
finalize(endState) {
return new token_1.TokenizationResult(this._tokens, endState);
}
}
class MonarchModernTokensCollector {
constructor(modeService, theme) {
this._modeService = modeService;
this._theme = theme;
this._prependTokens = null;
this._tokens = [];
this._currentLanguageId = 0 /* Null */;
this._lastTokenMetadata = 0;
}
enterMode(startOffset, modeId) {
this._currentLanguageId = this._modeService.getLanguageIdentifier(modeId).id;
}
emit(startOffset, type) {
let metadata = this._theme.match(this._currentLanguageId, type);
if (this._lastTokenMetadata === metadata) {
return;
}
this._lastTokenMetadata = metadata;
this._tokens.push(startOffset);
this._tokens.push(metadata);
}
static _merge(a, b, c) {
let aLen = (a !== null ? a.length : 0);
let bLen = b.length;
let 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;
}
let 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;
}
nestedModeTokenize(embeddedModeLine, hasEOL, embeddedModeData, offsetDelta) {
const nestedModeId = embeddedModeData.modeId;
const embeddedModeState = embeddedModeData.state;
const nestedModeTokenizationSupport = modes.TokenizationRegistry.get(nestedModeId);
if (!nestedModeTokenizationSupport) {
this.enterMode(offsetDelta, nestedModeId);
this.emit(offsetDelta, '');
return embeddedModeState;
}
let nestedResult = nestedModeTokenizationSupport.tokenize2(embeddedModeLine, hasEOL, embeddedModeState, 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 token_1.TokenizationResult2(MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, null), endState);
}
}
class MonarchTokenizer {
constructor(modeService, standaloneThemeService, modeId, lexer) {
this._modeService = modeService;
this._standaloneThemeService = standaloneThemeService;
this._modeId = modeId;
this._lexer = lexer;
this._embeddedModes = Object.create(null);
this.embeddedLoaded = Promise.resolve(undefined);
// Set up listening for embedded modes
let emitting = false;
this._tokenizationRegistryListener = modes.TokenizationRegistry.onDidChange((e) => {
if (emitting) {
return;
}
let isOneOfMyEmbeddedModes = false;
for (let i = 0, len = e.changedLanguages.length; i < len; i++) {
let language = e.changedLanguages[i];
if (this._embeddedModes[language]) {
isOneOfMyEmbeddedModes = true;
break;
}
}
if (isOneOfMyEmbeddedModes) {
emitting = true;
modes.TokenizationRegistry.fire([this._modeId]);
emitting = false;
}
});
}
dispose() {
this._tokenizationRegistryListener.dispose();
}
getLoadStatus() {
let promises = [];
for (let nestedModeId in this._embeddedModes) {
const tokenizationSupport = modes.TokenizationRegistry.get(nestedModeId);
if (tokenizationSupport) {
// The nested mode is already loaded
if (tokenizationSupport instanceof MonarchTokenizer) {
const nestedModeStatus = tokenizationSupport.getLoadStatus();
if (nestedModeStatus.loaded === false) {
promises.push(nestedModeStatus.promise);
}
}
continue;
}
const tokenizationSupportPromise = modes.TokenizationRegistry.getPromise(nestedModeId);
if (tokenizationSupportPromise) {
// The nested mode is in the process of being loaded
promises.push(tokenizationSupportPromise);
}
}
if (promises.length === 0) {
return {
loaded: true
};
}
return {
loaded: false,
promise: Promise.all(promises).then(_ => undefined)
};
}
getInitialState() {
let rootState = MonarchStackElementFactory.create(null, this._lexer.start);
return MonarchLineStateFactory.create(rootState, null);
}
tokenize(line, hasEOL, lineState, offsetDelta) {
let tokensCollector = new MonarchClassicTokensCollector();
let endLineState = this._tokenize(line, hasEOL, lineState, offsetDelta, tokensCollector);
return tokensCollector.finalize(endLineState);
}
tokenize2(line, hasEOL, lineState, offsetDelta) {
let tokensCollector = new MonarchModernTokensCollector(this._modeService, this._standaloneThemeService.getColorTheme().tokenTheme);
let endLineState = this._tokenize(line, hasEOL, lineState, offsetDelta, tokensCollector);
return tokensCollector.finalize(endLineState);
}
_tokenize(line, hasEOL, lineState, offsetDelta, collector) {
if (lineState.embeddedModeData) {
return this._nestedTokenize(line, hasEOL, lineState, offsetDelta, collector);
}
else {
return this._myTokenize(line, hasEOL, lineState, offsetDelta, collector);
}
}
_findLeavingNestedModeOffset(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.regex;
let regexSource = rule.regex.source;
if (regexSource.substr(0, 4) === '^(?:' && regexSource.substr(regexSource.length - 1, 1) === ')') {
let flags = (regex.ignoreCase ? 'i' : '') + (regex.unicode ? 'u' : '');
regex = new RegExp(regexSource.substr(4, regexSource.length - 5), flags);
}
let 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) {
let popOffset = this._findLeavingNestedModeOffset(line, lineState);
if (popOffset === -1) {
// tokenization will not leave nested mode
let nestedEndState = tokensCollector.nestedModeTokenize(line, hasEOL, lineState.embeddedModeData, offsetDelta);
return MonarchLineStateFactory.create(lineState.stack, new EmbeddedModeData(lineState.embeddedModeData.modeId, nestedEndState));
}
let nestedModeLine = line.substring(0, popOffset);
if (nestedModeLine.length > 0) {
// tokenize with the nested mode
tokensCollector.nestedModeTokenize(nestedModeLine, false, lineState.embeddedModeData, offsetDelta);
}
let 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.enterMode(offsetDelta, this._modeId);
const lineWithoutLFLength = lineWithoutLF.length;
const line = (hasEOL && this._lexer.includeLF ? lineWithoutLF + '\n' : lineWithoutLF);
const lineLength = line.length;
let embeddedModeData = lineState.embeddedModeData;
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 enteringEmbeddedMode = 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
let restOfLine = line.substr(pos);
for (const rule of rules) {
if (pos === 0 || !rule.matchOnlyAtLineStart) {
matches = restOfLine.match(rule.regex);
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 mode?
if (action.nextEmbedded) {
if (action.nextEmbedded === '@pop') {
if (!embeddedModeData) {
throw monarchCommon.createError(this._lexer, 'cannot pop embedded mode if not inside one');
}
embeddedModeData = null;
}
else if (embeddedModeData) {
throw monarchCommon.createError(this._lexer, 'cannot enter embedded mode from within an embedded mode');
}
else {
enteringEmbeddedMode = 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 computeNewStateForEmbeddedMode = (enteringEmbeddedMode) => {
// substitute language alias to known modes to support syntax highlighting
let enteringEmbeddedModeId = this._modeService.getModeIdForLanguageName(enteringEmbeddedMode);
if (enteringEmbeddedModeId) {
enteringEmbeddedMode = enteringEmbeddedModeId;
}
const embeddedModeData = this._getNestedEmbeddedModeData(enteringEmbeddedMode);
if (pos < lineLength) {
// there is content from the embedded mode on this line
const restOfLine = lineWithoutLF.substr(pos);
return this._nestedTokenize(restOfLine, hasEOL, MonarchLineStateFactory.create(stack, embeddedModeData), offsetDelta + pos, tokensCollector);
}
else {
return MonarchLineStateFactory.create(stack, embeddedModeData);
}
};
// 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 (enteringEmbeddedMode !== null) {
return computeNewStateForEmbeddedMode(enteringEmbeddedMode);
}
}
// 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) {
let rest = result.substr('@brackets'.length);
let 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 {
let token = (result === '' ? '' : result + this._lexer.tokenPostfix);
tokenType = monarchCommon.sanitize(token);
}
if (pos0 < lineWithoutLFLength) {
tokensCollector.emit(pos0 + offsetDelta, tokenType);
}
}
if (enteringEmbeddedMode !== null) {
return computeNewStateForEmbeddedMode(enteringEmbeddedMode);
}
}
return MonarchLineStateFactory.create(stack, embeddedModeData);
}
_getNestedEmbeddedModeData(mimetypeOrModeId) {
let nestedModeId = this._locateMode(mimetypeOrModeId);
if (nestedModeId) {
let tokenizationSupport = modes.TokenizationRegistry.get(nestedModeId);
if (tokenizationSupport) {
return new EmbeddedModeData(nestedModeId, tokenizationSupport.getInitialState());
}
}
return new EmbeddedModeData(nestedModeId || nullMode_1.NULL_MODE_ID, nullMode_1.NULL_STATE);
}
_locateMode(mimetypeOrModeId) {
if (!mimetypeOrModeId || !this._modeService.isRegisteredMode(mimetypeOrModeId)) {
return null;
}
if (mimetypeOrModeId === this._modeId) {
// embedding myself...
return mimetypeOrModeId;
}
let modeId = this._modeService.getModeId(mimetypeOrModeId);
if (modeId) {
// Fire mode loading event
this._modeService.triggerMode(modeId);
this._embeddedModes[modeId] = true;
}
return modeId;
}
}
exports.MonarchTokenizer = 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);
let brackets = lexer.brackets;
for (const bracket of brackets) {
if (bracket.open === matched) {
return { token: bracket.token, bracketType: 1 /* Open */ };
}
else if (bracket.close === matched) {
return { token: bracket.token, bracketType: -1 /* Close */ };
}
}
return null;
}
function createTokenizationSupport(modeService, standaloneThemeService, modeId, lexer) {
return new MonarchTokenizer(modeService, standaloneThemeService, modeId, lexer);
}
exports.createTokenizationSupport = createTokenizationSupport;
});
/*---------------------------------------------------------------------------------------------
* 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/standalone/browser/colorizer*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,8/*vs/base/common/strings*/,85/*vs/editor/common/core/lineTokens*/,18/*vs/editor/common/modes*/,114/*vs/editor/common/viewLayout/viewLineRenderer*/,62/*vs/editor/common/viewModel/viewModel*/,249/*vs/editor/standalone/common/monarch/monarchLexer*/]), function (require, exports, async_1, strings, lineTokens_1, modes_1, viewLineRenderer_1, viewModel_1, monarchLexer_1) {
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Colorizer = void 0;
const ttPolicy = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('standaloneColorizer', { createHTML: value => value });
class Colorizer {
static colorizeElement(themeService, modeService, domNode, options) {
options = options || {};
let theme = options.theme || 'vs';
let mimeType = options.mimeType || domNode.getAttribute('lang') || domNode.getAttribute('data-lang');
if (!mimeType) {
console.error('Mode not detected');
return Promise.resolve();
}
themeService.setTheme(theme);
let text = domNode.firstChild ? domNode.firstChild.nodeValue : '';
domNode.className += ' ' + theme;
let render = (str) => {
var _a;
const trustedhtml = (_a = ttPolicy === null || ttPolicy === void 0 ? void 0 : ttPolicy.createHTML(str)) !== null && _a !== void 0 ? _a : str;
domNode.innerHTML = trustedhtml;
};
return this.colorize(modeService, text || '', mimeType, options).then(render, (err) => console.error(err));
}
static colorize(modeService, text, mimeType, options) {
let tabSize = 4;
if (options && typeof options.tabSize === 'number') {
tabSize = options.tabSize;
}
if (strings.startsWithUTF8BOM(text)) {
text = text.substr(1);
}
let lines = strings.splitLines(text);
let language = modeService.getModeId(mimeType);
if (!language) {
return Promise.resolve(_fakeColorize(lines, tabSize));
}
// Send out the event to create the mode
modeService.triggerMode(language);
const tokenizationSupport = modes_1.TokenizationRegistry.get(language);
if (tokenizationSupport) {
return _colorize(lines, tabSize, tokenizationSupport);
}
const tokenizationSupportPromise = modes_1.TokenizationRegistry.getPromise(language);
if (tokenizationSupportPromise) {
// A tokenizer will be registered soon
return new Promise((resolve, reject) => {
tokenizationSupportPromise.then(tokenizationSupport => {
_colorize(lines, tabSize, tokenizationSupport).then(resolve, reject);
}, reject);
});
}
return new Promise((resolve, reject) => {
let listener = null;
let timeout = null;
const execute = () => {
if (listener) {
listener.dispose();
listener = null;
}
if (timeout) {
timeout.dispose();
timeout = null;
}
const tokenizationSupport = modes_1.TokenizationRegistry.get(language);
if (tokenizationSupport) {
_colorize(lines, tabSize, tokenizationSupport).then(resolve, reject);
return;
}
resolve(_fakeColorize(lines, tabSize));
};
// wait 500ms for mode to load, then give up
timeout = new async_1.TimeoutTimer();
timeout.cancelAndSet(execute, 500);
listener = modes_1.TokenizationRegistry.onDidChange((e) => {
if (e.changedLanguages.indexOf(language) >= 0) {
execute();
}
});
});
}
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);
let 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) {
let content = model.getLineContent(lineNumber);
model.forceTokenization(lineNumber);
let tokens = model.getLineTokens(lineNumber);
let inflatedTokens = tokens.inflate();
return this.colorizeLine(content, model.mightContainNonBasicASCII(), model.mightContainRTL(), inflatedTokens, tabSize);
}
}
exports.Colorizer = Colorizer;
function _colorize(lines, tabSize, tokenizationSupport) {
return new Promise((c, e) => {
const execute = () => {
const result = _actualColorize(lines, tabSize, tokenizationSupport);
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) {
let html = [];
const defaultMetadata = ((0 /* None */ << 11 /* FONT_STYLE_OFFSET */)
| (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */)
| (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0;
const tokens = new Uint32Array(2);
tokens[0] = 0;
tokens[1] = defaultMetadata;
for (let i = 0, length = lines.length; i < length; i++) {
let line = lines[i];
tokens[0] = line.length;
const lineTokens = new lineTokens_1.LineTokens(tokens, line);
const isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true);
const containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true);
let 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) {
let html = [];
let state = tokenizationSupport.getInitialState();
for (let i = 0, length = lines.length; i < length; i++) {
let line = lines[i];
let tokenizeResult = tokenizationSupport.tokenize2(line, true, state, 0);
lineTokens_1.LineTokens.convertToEndOffset(tokenizeResult.tokens, line.length);
let lineTokens = new lineTokens_1.LineTokens(tokenizeResult.tokens, line);
const isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true);
const containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true);
let 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[119/*vs/editor/standalone/common/standaloneThemeService*/], __M([0/*require*/,1/*exports*/,9/*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');
});
/*---------------------------------------------------------------------------------------------
* 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/platform/clipboard/common/clipboardService*/], __M([0/*require*/,1/*exports*/,9/*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[26/*vs/platform/commands/common/commands*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/,9/*vs/platform/instantiation/common/instantiation*/,6/*vs/base/common/event*/,72/*vs/base/common/linkedList*/,54/*vs/base/common/iterator*/]), function (require, exports, lifecycle_1, types_1, instantiation_1, event_1, linkedList_1, iterator_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.description) {
const constraints = [];
for (let arg of idOrCommand.description.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);
}
let removeFn = commands.unshift(idOrCommand);
let ret = (0, lifecycle_1.toDisposable)(() => {
removeFn();
const command = this._commands.get(id);
if (command === null || command === void 0 ? void 0 : 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[250/*vs/editor/common/services/getSemanticTokens*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,24/*vs/base/common/uri*/,18/*vs/editor/common/modes*/,36/*vs/editor/common/services/modelService*/,26/*vs/platform/commands/common/commands*/,20/*vs/base/common/types*/,391/*vs/editor/common/services/semanticTokensDto*/,3/*vs/editor/common/core/range*/]), function (require, exports, cancellation_1, errors_1, uri_1, modes_1, modelService_1, commands_1, types_1, semanticTokensDto_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDocumentRangeSemanticTokensProvider = exports.getDocumentSemanticTokens = exports.isSemanticTokensEdits = exports.isSemanticTokens = void 0;
function isSemanticTokens(v) {
return v && !!(v.data);
}
exports.isSemanticTokens = isSemanticTokens;
function isSemanticTokensEdits(v) {
return v && Array.isArray(v.edits);
}
exports.isSemanticTokensEdits = isSemanticTokensEdits;
function getDocumentSemanticTokens(model, lastResultId, token) {
const provider = _getDocumentSemanticTokensProvider(model);
if (!provider) {
return null;
}
return {
provider: provider,
request: Promise.resolve(provider.provideDocumentSemanticTokens(model, lastResultId, token))
};
}
exports.getDocumentSemanticTokens = getDocumentSemanticTokens;
function _getDocumentSemanticTokensProvider(model) {
const result = modes_1.DocumentSemanticTokensProviderRegistry.ordered(model);
return (result.length > 0 ? result[0] : null);
}
function getDocumentRangeSemanticTokensProvider(model) {
const result = modes_1.DocumentRangeSemanticTokensProviderRegistry.ordered(model);
return (result.length > 0 ? result[0] : null);
}
exports.getDocumentRangeSemanticTokensProvider = getDocumentRangeSemanticTokensProvider;
commands_1.CommandsRegistry.registerCommand('_provideDocumentSemanticTokensLegend', (accessor, ...args) => __awaiter(void 0, void 0, void 0, function* () {
const [uri] = args;
(0, types_1.assertType)(uri instanceof uri_1.URI);
const model = accessor.get(modelService_1.IModelService).getModel(uri);
if (!model) {
return undefined;
}
const provider = _getDocumentSemanticTokensProvider(model);
if (!provider) {
// there is no provider => fall back to a document range semantic tokens provider
return accessor.get(commands_1.ICommandService).executeCommand('_provideDocumentRangeSemanticTokensLegend', uri);
}
return provider.getLegend();
}));
commands_1.CommandsRegistry.registerCommand('_provideDocumentSemanticTokens', (accessor, ...args) => __awaiter(void 0, void 0, void 0, function* () {
const [uri] = args;
(0, types_1.assertType)(uri instanceof uri_1.URI);
const model = accessor.get(modelService_1.IModelService).getModel(uri);
if (!model) {
return undefined;
}
const r = getDocumentSemanticTokens(model, null, cancellation_1.CancellationToken.None);
if (!r) {
// 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 { provider, request } = r;
let result;
try {
result = yield request;
}
catch (err) {
(0, errors_1.onUnexpectedExternalError)(err);
return undefined;
}
if (!result || !isSemanticTokens(result)) {
return undefined;
}
const buff = (0, semanticTokensDto_1.encodeSemanticTokensDto)({
id: 0,
type: 'full',
data: result.data
});
if (result.resultId) {
provider.releaseDocumentSemanticTokens(result.resultId);
}
return buff;
}));
commands_1.CommandsRegistry.registerCommand('_provideDocumentRangeSemanticTokensLegend', (accessor, ...args) => __awaiter(void 0, void 0, void 0, function* () {
const [uri] = args;
(0, types_1.assertType)(uri instanceof uri_1.URI);
const model = accessor.get(modelService_1.IModelService).getModel(uri);
if (!model) {
return undefined;
}
const provider = getDocumentRangeSemanticTokensProvider(model);
if (!provider) {
return undefined;
}
return provider.getLegend();
}));
commands_1.CommandsRegistry.registerCommand('_provideDocumentRangeSemanticTokens', (accessor, ...args) => __awaiter(void 0, void 0, void 0, function* () {
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(modelService_1.IModelService).getModel(uri);
if (!model) {
return undefined;
}
const provider = getDocumentRangeSemanticTokensProvider(model);
if (!provider) {
// there is no provider
return undefined;
}
let result;
try {
result = yield provider.provideDocumentRangeSemanticTokens(model, range_1.Range.lift(range), cancellation_1.CancellationToken.None);
}
catch (err) {
(0, errors_1.onUnexpectedExternalError)(err);
return undefined;
}
if (!result || !isSemanticTokens(result)) {
return undefined;
}
return (0, semanticTokensDto_1.encodeSemanticTokensDto)({
id: 0,
type: 'full',
data: result.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[251/*vs/editor/contrib/codelens/codelens*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,24/*vs/base/common/uri*/,18/*vs/editor/common/modes*/,36/*vs/editor/common/services/modelService*/,2/*vs/base/common/lifecycle*/,26/*vs/platform/commands/common/commands*/,20/*vs/base/common/types*/]), function (require, exports, cancellation_1, errors_1, uri_1, modes_1, modelService_1, lifecycle_1, commands_1, types_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCodeLensModel = exports.CodeLensModel = void 0;
class CodeLensModel {
constructor() {
this.lenses = [];
this._disposables = new lifecycle_1.DisposableStore();
}
dispose() {
this._disposables.dispose();
}
add(list, provider) {
this._disposables.add(list);
for (const symbol of list.lenses) {
this.lenses.push({ symbol, provider });
}
}
}
exports.CodeLensModel = CodeLensModel;
function getCodeLensModel(model, token) {
return __awaiter(this, void 0, void 0, function* () {
const provider = modes_1.CodeLensProviderRegistry.ordered(model);
const providerRanks = new Map();
const result = new CodeLensModel();
const promises = provider.map((provider, i) => __awaiter(this, void 0, void 0, function* () {
providerRanks.set(provider, i);
try {
const list = yield Promise.resolve(provider.provideCodeLenses(model, token));
if (list) {
result.add(list, provider);
}
}
catch (err) {
(0, errors_1.onUnexpectedExternalError)(err);
}
}));
yield 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;
});
}
exports.getCodeLensModel = getCodeLensModel;
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 model = accessor.get(modelService_1.IModelService).getModel(uri);
if (!model) {
throw (0, errors_1.illegalArgument)();
}
const result = [];
const disposables = new lifecycle_1.DisposableStore();
return getCodeLensModel(model, cancellation_1.CancellationToken.None).then(value => {
disposables.add(value);
let 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[252/*vs/editor/contrib/colorPicker/color*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,24/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/modes*/,36/*vs/editor/common/services/modelService*/,26/*vs/platform/commands/common/commands*/]), function (require, exports, cancellation_1, errors_1, uri_1, range_1, modes_1, modelService_1, commands_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getColorPresentations = exports.getColors = void 0;
function getColors(model, token) {
const colors = [];
const providers = modes_1.ColorProviderRegistry.ordered(model).reverse();
const promises = providers.map(provider => Promise.resolve(provider.provideDocumentColors(model, token)).then(result => {
if (Array.isArray(result)) {
for (let colorInfo of result) {
colors.push({ colorInfo, provider });
}
}
}));
return Promise.all(promises).then(() => colors);
}
exports.getColors = getColors;
function getColorPresentations(model, colorInfo, provider, token) {
return Promise.resolve(provider.provideColorPresentations(model, colorInfo, token));
}
exports.getColorPresentations = getColorPresentations;
commands_1.CommandsRegistry.registerCommand('_executeDocumentColorProvider', function (accessor, ...args) {
const [resource] = args;
if (!(resource instanceof uri_1.URI)) {
throw (0, errors_1.illegalArgument)();
}
const model = accessor.get(modelService_1.IModelService).getModel(resource);
if (!model) {
throw (0, errors_1.illegalArgument)();
}
const rawCIs = [];
const providers = modes_1.ColorProviderRegistry.ordered(model).reverse();
const promises = providers.map(provider => Promise.resolve(provider.provideDocumentColors(model, cancellation_1.CancellationToken.None)).then(result => {
if (Array.isArray(result)) {
for (let ci of result) {
rawCIs.push({ range: ci.range, color: [ci.color.red, ci.color.green, ci.color.blue, ci.color.alpha] });
}
}
}));
return Promise.all(promises).then(() => rawCIs);
});
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 [red, green, blue, alpha] = color;
const model = accessor.get(modelService_1.IModelService).getModel(uri);
if (!model) {
throw (0, errors_1.illegalArgument)();
}
const colorInfo = {
range,
color: { red, green, blue, alpha }
};
const presentations = [];
const providers = modes_1.ColorProviderRegistry.ordered(model).reverse();
const promises = providers.map(provider => Promise.resolve(provider.provideColorPresentations(model, colorInfo, cancellation_1.CancellationToken.None)).then(result => {
if (Array.isArray(result)) {
presentations.push(...result);
}
}));
return Promise.all(promises).then(() => presentations);
});
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/documentSymbols/documentSymbols*/], __M([0/*require*/,1/*exports*/,24/*vs/base/common/uri*/,36/*vs/editor/common/services/modelService*/,23/*vs/base/common/cancellation*/,68/*vs/editor/common/services/resolverService*/,248/*vs/editor/contrib/documentSymbols/outlineModel*/,26/*vs/platform/commands/common/commands*/,20/*vs/base/common/types*/]), function (require, exports, uri_1, modelService_1, cancellation_1, resolverService_1, outlineModel_1, commands_1, types_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDocumentSymbols = void 0;
function getDocumentSymbols(document, flat, token) {
return __awaiter(this, void 0, void 0, function* () {
const model = yield outlineModel_1.OutlineModel.create(document, token);
return flat
? model.asListOfDocumentSymbols()
: model.getTopLevelSymbols();
});
}
exports.getDocumentSymbols = getDocumentSymbols;
commands_1.CommandsRegistry.registerCommand('_executeDocumentSymbolProvider', function (accessor, ...args) {
return __awaiter(this, void 0, void 0, function* () {
const [resource] = args;
(0, types_1.assertType)(uri_1.URI.isUri(resource));
const model = accessor.get(modelService_1.IModelService).getModel(resource);
if (model) {
return getDocumentSymbols(model, false, cancellation_1.CancellationToken.None);
}
const reference = yield accessor.get(resolverService_1.ITextModelService).createModelReference(resource);
try {
return yield getDocumentSymbols(reference.object.textEditorModel, false, 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[560/*vs/editor/contrib/links/getLinks*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,24/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/modes*/,36/*vs/editor/common/services/modelService*/,26/*vs/platform/commands/common/commands*/,2/*vs/base/common/lifecycle*/,19/*vs/base/common/arrays*/,20/*vs/base/common/types*/]), function (require, exports, cancellation_1, errors_1, uri_1, range_1, modes_1, modelService_1, commands_1, lifecycle_1, arrays_1, types_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLinks = exports.LinksList = exports.Link = void 0;
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;
}
resolve(token) {
return __awaiter(this, void 0, void 0, function* () {
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
let 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(model, token) {
const lists = [];
// ask all providers for links in parallel
const promises = modes_1.LinkProviderRegistry.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([]);
});
}
exports.getLinks = getLinks;
commands_1.CommandsRegistry.registerCommand('_executeLinkProvider', (accessor, ...args) => __awaiter(void 0, void 0, void 0, function* () {
let [uri, resolveCount] = args;
(0, types_1.assertType)(uri instanceof uri_1.URI);
if (typeof resolveCount !== 'number') {
resolveCount = 0;
}
const model = accessor.get(modelService_1.IModelService).getModel(uri);
if (!model) {
return [];
}
const list = yield getLinks(model, cancellation_1.CancellationToken.None);
if (!list) {
return [];
}
// resolve links
for (let i = 0; i < Math.min(resolveCount, list.links.length); i++) {
yield 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[16/*vs/platform/contextkey/common/contextkey*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,9/*vs/platform/instantiation/common/instantiation*/,17/*vs/base/common/platform*/]), function (require, exports, strings_1, instantiation_1, platform_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SET_CONTEXT_COMMAND_ID = 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 = void 0;
let _userAgent = platform_1.userAgent || '';
const STATIC_VALUES = new Map();
STATIC_VALUES.set('false', false);
STATIC_VALUES.set('true', true);
STATIC_VALUES.set('isMac', platform_1.isMacintosh);
STATIC_VALUES.set('isLinux', platform_1.isLinux);
STATIC_VALUES.set('isWindows', platform_1.isWindows);
STATIC_VALUES.set('isWeb', platform_1.isWeb);
STATIC_VALUES.set('isMacNative', platform_1.isMacintosh && !platform_1.isWeb);
STATIC_VALUES.set('isEdge', _userAgent.indexOf('Edg/') >= 0);
STATIC_VALUES.set('isFirefox', _userAgent.indexOf('Firefox') >= 0);
STATIC_VALUES.set('isChrome', _userAgent.indexOf('Chrome') >= 0);
STATIC_VALUES.set('isSafari', _userAgent.indexOf('Safari') >= 0);
const hasOwnProperty = Object.prototype.hasOwnProperty;
class ContextKeyExpr {
static has(key) {
return ContextKeyDefinedExpr.create(key);
}
static equals(key, value) {
return ContextKeyEqualsExpr.create(key, value);
}
static regex(key, value) {
return ContextKeyRegexExpr.create(key, value);
}
static not(key) {
return ContextKeyNotExpr.create(key);
}
static and(...expr) {
return ContextKeyAndExpr.create(expr);
}
static or(...expr) {
return ContextKeyOrExpr.create(expr);
}
static deserialize(serialized, strict = false) {
if (!serialized) {
return undefined;
}
return this._deserializeOrExpression(serialized, strict);
}
static _deserializeOrExpression(serialized, strict) {
let pieces = serialized.split('||');
return ContextKeyOrExpr.create(pieces.map(p => this._deserializeAndExpression(p, strict)));
}
static _deserializeAndExpression(serialized, strict) {
let pieces = serialized.split('&&');
return ContextKeyAndExpr.create(pieces.map(p => this._deserializeOne(p, strict)));
}
static _deserializeOne(serializedOne, strict) {
serializedOne = serializedOne.trim();
if (serializedOne.indexOf('!=') >= 0) {
let pieces = serializedOne.split('!=');
return ContextKeyNotEqualsExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict));
}
if (serializedOne.indexOf('==') >= 0) {
let pieces = serializedOne.split('==');
return ContextKeyEqualsExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict));
}
if (serializedOne.indexOf('=~') >= 0) {
let pieces = serializedOne.split('=~');
return ContextKeyRegexExpr.create(pieces[0].trim(), this._deserializeRegexValue(pieces[1], strict));
}
if (serializedOne.indexOf(' in ') >= 0) {
let pieces = serializedOne.split(' in ');
return ContextKeyInExpr.create(pieces[0].trim(), pieces[1].trim());
}
if (/^[^<=>]+>=[^<=>]+$/.test(serializedOne)) {
const pieces = serializedOne.split('>=');
return ContextKeyGreaterEqualsExpr.create(pieces[0].trim(), pieces[1].trim());
}
if (/^[^<=>]+>[^<=>]+$/.test(serializedOne)) {
const pieces = serializedOne.split('>');
return ContextKeyGreaterExpr.create(pieces[0].trim(), pieces[1].trim());
}
if (/^[^<=>]+<=[^<=>]+$/.test(serializedOne)) {
const pieces = serializedOne.split('<=');
return ContextKeySmallerEqualsExpr.create(pieces[0].trim(), pieces[1].trim());
}
if (/^[^<=>]+<[^<=>]+$/.test(serializedOne)) {
const pieces = serializedOne.split('<');
return ContextKeySmallerExpr.create(pieces[0].trim(), pieces[1].trim());
}
if (/^\!\s*/.test(serializedOne)) {
return ContextKeyNotExpr.create(serializedOne.substr(1).trim());
}
return ContextKeyDefinedExpr.create(serializedOne);
}
static _deserializeValue(serializedValue, strict) {
serializedValue = serializedValue.trim();
if (serializedValue === 'true') {
return true;
}
if (serializedValue === 'false') {
return false;
}
let m = /^'([^']*)'$/.exec(serializedValue);
if (m) {
return m[1].trim();
}
return serializedValue;
}
static _deserializeRegexValue(serializedValue, strict) {
if ((0, strings_1.isFalsyOrWhitespace)(serializedValue)) {
if (strict) {
throw new Error('missing regexp-value for =~-expression');
}
else {
console.warn('missing regexp-value for =~-expression');
}
return null;
}
let start = serializedValue.indexOf('/');
let end = serializedValue.lastIndexOf('/');
if (start === end || start < 0 /* || to < 0 */) {
if (strict) {
throw new Error(`bad regexp-value '${serializedValue}', missing /-enclosure`);
}
else {
console.warn(`bad regexp-value '${serializedValue}', missing /-enclosure`);
}
return null;
}
let value = serializedValue.slice(start + 1, end);
let caseIgnoreFlag = serializedValue[end + 1] === 'i' ? 'i' : '';
try {
return new RegExp(value, caseIgnoreFlag);
}
catch (e) {
if (strict) {
throw new Error(`bad regexp-value '${serializedValue}', parse error: ${e}`);
}
else {
console.warn(`bad regexp-value '${serializedValue}', parse error: ${e}`);
}
return null;
}
}
}
exports.ContextKeyExpr = ContextKeyExpr;
function cmp(a, b) {
return a.cmp(b);
}
class ContextKeyFalseExpr {
constructor() {
this.type = 0 /* False */;
}
cmp(other) {
return this.type - other.type;
}
equals(other) {
return (other.type === this.type);
}
evaluate(context) {
return false;
}
serialize() {
return 'false';
}
keys() {
return [];
}
negate() {
return ContextKeyTrueExpr.INSTANCE;
}
}
exports.ContextKeyFalseExpr = ContextKeyFalseExpr;
ContextKeyFalseExpr.INSTANCE = new ContextKeyFalseExpr();
class ContextKeyTrueExpr {
constructor() {
this.type = 1 /* True */;
}
cmp(other) {
return this.type - other.type;
}
equals(other) {
return (other.type === this.type);
}
evaluate(context) {
return true;
}
serialize() {
return 'true';
}
keys() {
return [];
}
negate() {
return ContextKeyFalseExpr.INSTANCE;
}
}
exports.ContextKeyTrueExpr = ContextKeyTrueExpr;
ContextKeyTrueExpr.INSTANCE = new ContextKeyTrueExpr();
class ContextKeyDefinedExpr {
constructor(key) {
this.key = key;
this.type = 2 /* Defined */;
}
static create(key) {
const staticValue = STATIC_VALUES.get(key);
if (typeof staticValue === 'boolean') {
return staticValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE;
}
return new ContextKeyDefinedExpr(key);
}
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;
}
evaluate(context) {
return (!!context.getValue(this.key));
}
serialize() {
return this.key;
}
keys() {
return [this.key];
}
negate() {
return ContextKeyNotExpr.create(this.key);
}
}
exports.ContextKeyDefinedExpr = ContextKeyDefinedExpr;
class ContextKeyEqualsExpr {
constructor(key, value) {
this.key = key;
this.value = value;
this.type = 4 /* Equals */;
}
static create(key, value) {
if (typeof value === 'boolean') {
return (value ? ContextKeyDefinedExpr.create(key) : ContextKeyNotExpr.create(key));
}
const staticValue = STATIC_VALUES.get(key);
if (typeof staticValue === 'boolean') {
const trueValue = staticValue ? 'true' : 'false';
return (value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE);
}
return new ContextKeyEqualsExpr(key, value);
}
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;
}
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() {
return ContextKeyNotEqualsExpr.create(this.key, this.value);
}
}
exports.ContextKeyEqualsExpr = ContextKeyEqualsExpr;
class ContextKeyInExpr {
constructor(key, valueKey) {
this.key = key;
this.valueKey = valueKey;
this.type = 10 /* In */;
}
static create(key, valueKey) {
return new ContextKeyInExpr(key, valueKey);
}
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;
}
evaluate(context) {
const source = context.getValue(this.valueKey);
const item = context.getValue(this.key);
if (Array.isArray(source)) {
return (source.indexOf(item) >= 0);
}
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() {
return ContextKeyNotInExpr.create(this);
}
}
exports.ContextKeyInExpr = ContextKeyInExpr;
class ContextKeyNotInExpr {
constructor(_actual) {
this._actual = _actual;
this.type = 11 /* NotIn */;
//
}
static create(actual) {
return new ContextKeyNotInExpr(actual);
}
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;
}
evaluate(context) {
return !this._actual.evaluate(context);
}
serialize() {
throw new Error('Method not implemented.');
}
keys() {
return this._actual.keys();
}
negate() {
return this._actual;
}
}
exports.ContextKeyNotInExpr = ContextKeyNotInExpr;
class ContextKeyNotEqualsExpr {
constructor(key, value) {
this.key = key;
this.value = value;
this.type = 5 /* NotEquals */;
}
static create(key, value) {
if (typeof value === 'boolean') {
if (value) {
return ContextKeyNotExpr.create(key);
}
return ContextKeyDefinedExpr.create(key);
}
const staticValue = STATIC_VALUES.get(key);
if (typeof staticValue === 'boolean') {
const falseValue = staticValue ? 'true' : 'false';
return (value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE);
}
return new ContextKeyNotEqualsExpr(key, value);
}
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;
}
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() {
return ContextKeyEqualsExpr.create(this.key, this.value);
}
}
exports.ContextKeyNotEqualsExpr = ContextKeyNotEqualsExpr;
class ContextKeyNotExpr {
constructor(key) {
this.key = key;
this.type = 3 /* Not */;
}
static create(key) {
const staticValue = STATIC_VALUES.get(key);
if (typeof staticValue === 'boolean') {
return (staticValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE);
}
return new ContextKeyNotExpr(key);
}
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;
}
evaluate(context) {
return (!context.getValue(this.key));
}
serialize() {
return `!${this.key}`;
}
keys() {
return [this.key];
}
negate() {
return ContextKeyDefinedExpr.create(this.key);
}
}
exports.ContextKeyNotExpr = ContextKeyNotExpr;
class ContextKeyGreaterExpr {
constructor(key, value) {
this.key = key;
this.value = value;
this.type = 12 /* Greater */;
}
static create(key, value) {
return new ContextKeyGreaterExpr(key, value);
}
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;
}
evaluate(context) {
return (parseFloat(context.getValue(this.key)) > parseFloat(this.value));
}
serialize() {
return `${this.key} > ${this.value}`;
}
keys() {
return [this.key];
}
negate() {
return ContextKeySmallerEqualsExpr.create(this.key, this.value);
}
}
exports.ContextKeyGreaterExpr = ContextKeyGreaterExpr;
class ContextKeyGreaterEqualsExpr {
constructor(key, value) {
this.key = key;
this.value = value;
this.type = 13 /* GreaterEquals */;
}
static create(key, value) {
return new ContextKeyGreaterEqualsExpr(key, value);
}
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;
}
evaluate(context) {
return (parseFloat(context.getValue(this.key)) >= parseFloat(this.value));
}
serialize() {
return `${this.key} >= ${this.value}`;
}
keys() {
return [this.key];
}
negate() {
return ContextKeySmallerExpr.create(this.key, this.value);
}
}
exports.ContextKeyGreaterEqualsExpr = ContextKeyGreaterEqualsExpr;
class ContextKeySmallerExpr {
constructor(key, value) {
this.key = key;
this.value = value;
this.type = 14 /* Smaller */;
}
static create(key, value) {
return new ContextKeySmallerExpr(key, value);
}
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;
}
evaluate(context) {
return (parseFloat(context.getValue(this.key)) < parseFloat(this.value));
}
serialize() {
return `${this.key} < ${this.value}`;
}
keys() {
return [this.key];
}
negate() {
return ContextKeyGreaterEqualsExpr.create(this.key, this.value);
}
}
exports.ContextKeySmallerExpr = ContextKeySmallerExpr;
class ContextKeySmallerEqualsExpr {
constructor(key, value) {
this.key = key;
this.value = value;
this.type = 15 /* SmallerEquals */;
}
static create(key, value) {
return new ContextKeySmallerEqualsExpr(key, value);
}
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;
}
evaluate(context) {
return (parseFloat(context.getValue(this.key)) <= parseFloat(this.value));
}
serialize() {
return `${this.key} <= ${this.value}`;
}
keys() {
return [this.key];
}
negate() {
return ContextKeyGreaterExpr.create(this.key, this.value);
}
}
exports.ContextKeySmallerEqualsExpr = ContextKeySmallerEqualsExpr;
class ContextKeyRegexExpr {
constructor(key, regexp) {
this.key = key;
this.regexp = regexp;
this.type = 7 /* Regex */;
//
}
static create(key, regexp) {
return new ContextKeyRegexExpr(key, regexp);
}
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;
}
evaluate(context) {
let value = context.getValue(this.key);
return this.regexp ? this.regexp.test(value) : false;
}
serialize() {
const value = this.regexp
? `/${this.regexp.source}/${this.regexp.ignoreCase ? 'i' : ''}`
: '/invalid/';
return `${this.key} =~ ${value}`;
}
keys() {
return [this.key];
}
negate() {
return ContextKeyNotRegexExpr.create(this);
}
}
exports.ContextKeyRegexExpr = ContextKeyRegexExpr;
class ContextKeyNotRegexExpr {
constructor(_actual) {
this._actual = _actual;
this.type = 8 /* NotRegex */;
//
}
static create(actual) {
return new ContextKeyNotRegexExpr(actual);
}
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;
}
evaluate(context) {
return !this._actual.evaluate(context);
}
serialize() {
throw new Error('Method not implemented.');
}
keys() {
return this._actual.keys();
}
negate() {
return this._actual;
}
}
exports.ContextKeyNotRegexExpr = ContextKeyNotRegexExpr;
class ContextKeyAndExpr {
constructor(expr) {
this.expr = expr;
this.type = 6 /* And */;
}
static create(_expr) {
return ContextKeyAndExpr._normalizeArr(_expr);
}
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;
}
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) {
const expr = [];
let hasTrue = false;
for (const e of arr) {
if (!e) {
continue;
}
if (e.type === 1 /* True */) {
// anything && true ==> anything
hasTrue = true;
continue;
}
if (e.type === 0 /* False */) {
// anything && false ==> false
return ContextKeyFalseExpr.INSTANCE;
}
if (e.type === 6 /* 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);
// 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 /* Or */) {
break;
}
// pop the last element
expr.pop();
// pop the second to last element
const secondToLastElement = expr.pop();
// distribute `lastElement` over `secondToLastElement`
const resultElement = ContextKeyOrExpr.create(lastElement.expr.map(el => ContextKeyAndExpr.create([el, secondToLastElement])));
if (resultElement) {
expr.push(resultElement);
expr.sort(cmp);
}
}
if (expr.length === 1) {
return expr[0];
}
return new ContextKeyAndExpr(expr);
}
serialize() {
return this.expr.map(e => e.serialize()).join(' && ');
}
keys() {
const result = [];
for (let expr of this.expr) {
result.push(...expr.keys());
}
return result;
}
negate() {
let result = [];
for (let expr of this.expr) {
result.push(expr.negate());
}
return ContextKeyOrExpr.create(result);
}
}
exports.ContextKeyAndExpr = ContextKeyAndExpr;
class ContextKeyOrExpr {
constructor(expr) {
this.expr = expr;
this.type = 9 /* Or */;
}
static create(_expr) {
const expr = ContextKeyOrExpr._normalizeArr(_expr);
if (expr.length === 0) {
return undefined;
}
if (expr.length === 1) {
return expr[0];
}
return new ContextKeyOrExpr(expr);
}
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;
}
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) {
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 /* False */) {
// anything || false ==> anything
hasFalse = true;
continue;
}
if (e.type === 1 /* True */) {
// anything || true ==> true
return [ContextKeyTrueExpr.INSTANCE];
}
if (e.type === 9 /* Or */) {
expr = expr.concat(e.expr);
continue;
}
expr.push(e);
}
if (expr.length === 0 && hasFalse) {
return [ContextKeyFalseExpr.INSTANCE];
}
expr.sort(cmp);
}
return expr;
}
serialize() {
return this.expr.map(e => e.serialize()).join(' || ');
}
keys() {
const result = [];
for (let expr of this.expr) {
result.push(...expr.keys());
}
return result;
}
negate() {
let result = [];
for (let expr of this.expr) {
result.push(expr.negate());
}
const terminals = (node) => {
if (node.type === 9 /* Or */) {
return node.expr;
}
return [node];
};
// 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 terminals(LEFT)) {
for (const right of terminals(RIGHT)) {
all.push(ContextKeyExpr.and(left, right));
}
}
result.unshift(ContextKeyExpr.or(...all));
}
return result[0];
}
}
exports.ContextKeyOrExpr = ContextKeyOrExpr;
class RawContextKey extends ContextKeyDefinedExpr {
constructor(key, defaultValue, metaOrHide) {
super(key);
this._defaultValue = defaultValue;
// collect all context keys into a central place
if (typeof metaOrHide === 'object') {
RawContextKey._info.push(Object.assign(Object.assign({}, metaOrHide), { key }));
}
else if (metaOrHide !== true) {
RawContextKey._info.push({ key, description: metaOrHide, type: defaultValue !== null && defaultValue !== undefined ? typeof defaultValue : undefined });
}
}
static all() {
return RawContextKey._info.values();
}
bindTo(target) {
return target.createKey(this.key, this._defaultValue);
}
getValue(target) {
return target.getContextKeyValue(this.key);
}
toNegated() {
return ContextKeyExpr.not(this.key);
}
isEqualTo(value) {
return ContextKeyExpr.equals(this.key, value);
}
}
exports.RawContextKey = RawContextKey;
RawContextKey._info = [];
exports.IContextKeyService = (0, instantiation_1.createDecorator)('contextKeyService');
exports.SET_CONTEXT_COMMAND_ID = 'setContext';
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;
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[25/*vs/editor/common/editorContextKeys*/], __M([0/*require*/,1/*exports*/,466/*vs/nls!vs/editor/common/editorContextKeys*/,16/*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(0, null));
/**
* 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(1, null));
/**
* 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(2, null));
EditorContextKeys.readOnly = new contextkey_1.RawContextKey('editorReadonly', false, nls.localize(3, null));
EditorContextKeys.inDiffEditor = new contextkey_1.RawContextKey('inDiffEditor', false, nls.localize(4, null));
EditorContextKeys.columnSelection = new contextkey_1.RawContextKey('editorColumnSelection', false, nls.localize(5, null));
EditorContextKeys.writable = EditorContextKeys.readOnly.toNegated();
EditorContextKeys.hasNonEmptySelection = new contextkey_1.RawContextKey('editorHasSelection', false, nls.localize(6, null));
EditorContextKeys.hasOnlyEmptySelection = EditorContextKeys.hasNonEmptySelection.toNegated();
EditorContextKeys.hasMultipleSelections = new contextkey_1.RawContextKey('editorHasMultipleSelections', false, nls.localize(7, null));
EditorContextKeys.hasSingleSelection = EditorContextKeys.hasMultipleSelections.toNegated();
EditorContextKeys.tabMovesFocus = new contextkey_1.RawContextKey('editorTabMovesFocus', false, nls.localize(8, null));
EditorContextKeys.tabDoesNotMoveFocus = EditorContextKeys.tabMovesFocus.toNegated();
EditorContextKeys.isInWalkThroughSnippet = 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(9, null));
/**
* 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(10, null));
EditorContextKeys.notInCompositeEditor = EditorContextKeys.inCompositeEditor.toNegated();
// -- mode context keys
EditorContextKeys.languageId = new contextkey_1.RawContextKey('editorLangId', '', nls.localize(11, null));
EditorContextKeys.hasCompletionItemProvider = new contextkey_1.RawContextKey('editorHasCompletionItemProvider', false, nls.localize(12, null));
EditorContextKeys.hasCodeActionsProvider = new contextkey_1.RawContextKey('editorHasCodeActionsProvider', false, nls.localize(13, null));
EditorContextKeys.hasCodeLensProvider = new contextkey_1.RawContextKey('editorHasCodeLensProvider', false, nls.localize(14, null));
EditorContextKeys.hasDefinitionProvider = new contextkey_1.RawContextKey('editorHasDefinitionProvider', false, nls.localize(15, null));
EditorContextKeys.hasDeclarationProvider = new contextkey_1.RawContextKey('editorHasDeclarationProvider', false, nls.localize(16, null));
EditorContextKeys.hasImplementationProvider = new contextkey_1.RawContextKey('editorHasImplementationProvider', false, nls.localize(17, null));
EditorContextKeys.hasTypeDefinitionProvider = new contextkey_1.RawContextKey('editorHasTypeDefinitionProvider', false, nls.localize(18, null));
EditorContextKeys.hasHoverProvider = new contextkey_1.RawContextKey('editorHasHoverProvider', false, nls.localize(19, null));
EditorContextKeys.hasDocumentHighlightProvider = new contextkey_1.RawContextKey('editorHasDocumentHighlightProvider', false, nls.localize(20, null));
EditorContextKeys.hasDocumentSymbolProvider = new contextkey_1.RawContextKey('editorHasDocumentSymbolProvider', false, nls.localize(21, null));
EditorContextKeys.hasReferenceProvider = new contextkey_1.RawContextKey('editorHasReferenceProvider', false, nls.localize(22, null));
EditorContextKeys.hasRenameProvider = new contextkey_1.RawContextKey('editorHasRenameProvider', false, nls.localize(23, null));
EditorContextKeys.hasSignatureHelpProvider = new contextkey_1.RawContextKey('editorHasSignatureHelpProvider', false, nls.localize(24, null));
EditorContextKeys.hasInlayHintsProvider = new contextkey_1.RawContextKey('editorHasInlayHintsProvider', false, nls.localize(25, null));
// -- mode context keys: formatting
EditorContextKeys.hasDocumentFormattingProvider = new contextkey_1.RawContextKey('editorHasDocumentFormattingProvider', false, nls.localize(26, null));
EditorContextKeys.hasDocumentSelectionFormattingProvider = new contextkey_1.RawContextKey('editorHasDocumentSelectionFormattingProvider', false, nls.localize(27, null));
EditorContextKeys.hasMultipleDocumentFormattingProvider = new contextkey_1.RawContextKey('editorHasMultipleDocumentFormattingProvider', false, nls.localize(28, null));
EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider = new contextkey_1.RawContextKey('editorHasMultipleDocumentSelectionFormattingProvider', false, nls.localize(29, null));
})(EditorContextKeys = exports.EditorContextKeys || (exports.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[188/*vs/editor/contrib/parameterHints/provideSignatureHelp*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,13/*vs/editor/common/core/position*/,18/*vs/editor/common/modes*/,16/*vs/platform/contextkey/common/contextkey*/,23/*vs/base/common/cancellation*/,26/*vs/platform/commands/common/commands*/,24/*vs/base/common/uri*/,20/*vs/base/common/types*/,68/*vs/editor/common/services/resolverService*/]), function (require, exports, errors_1, position_1, modes, contextkey_1, cancellation_1, commands_1, uri_1, types_1, resolverService_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.provideSignatureHelp = exports.Context = void 0;
exports.Context = {
Visible: new contextkey_1.RawContextKey('parameterHintsVisible', false),
MultipleSignatures: new contextkey_1.RawContextKey('parameterHintsMultipleSignatures', false),
};
function provideSignatureHelp(model, position, context, token) {
return __awaiter(this, void 0, void 0, function* () {
const supports = modes.SignatureHelpProviderRegistry.ordered(model);
for (const support of supports) {
try {
const result = yield support.provideSignatureHelp(model, position, token, context);
if (result) {
return result;
}
}
catch (err) {
(0, errors_1.onUnexpectedExternalError)(err);
}
}
return undefined;
});
}
exports.provideSignatureHelp = provideSignatureHelp;
commands_1.CommandsRegistry.registerCommand('_executeSignatureHelpProvider', (accessor, ...args) => __awaiter(void 0, void 0, void 0, function* () {
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 ref = yield accessor.get(resolverService_1.ITextModelService).createModelReference(uri);
try {
const result = yield provideSignatureHelp(ref.object.textEditorModel, position_1.Position.lift(position), {
triggerKind: modes.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[561/*vs/editor/contrib/parameterHints/parameterHintsModel*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,12/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,94/*vs/editor/common/core/characterClassifier*/,18/*vs/editor/common/modes*/,188/*vs/editor/contrib/parameterHints/provideSignatureHelp*/]), function (require, exports, async_1, errors_1, event_1, lifecycle_1, characterClassifier_1, modes, provideSignatureHelp_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ParameterHintsModel = void 0;
var ParameterHintState;
(function (ParameterHintState) {
ParameterHintState.Default = { type: 0 /* Default */ };
class Pending {
constructor(request, previouslyActiveHints) {
this.request = request;
this.previouslyActiveHints = previouslyActiveHints;
this.type = 2 /* Pending */;
}
}
ParameterHintState.Pending = Pending;
class Active {
constructor(hints) {
this.hints = hints;
this.type = 1 /* Active */;
}
}
ParameterHintState.Active = Active;
})(ParameterHintState || (ParameterHintState = {}));
class ParameterHintsModel extends lifecycle_1.Disposable {
constructor(editor, 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.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(modes.SignatureHelpProviderRegistry.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 /* 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 || !modes.SignatureHelpProviderRegistry.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 /* 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(74 /* 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 /* Active */) {
return;
}
const length = this.state.hints.signatures.length;
const activeSignature = this.state.hints.activeSignature;
const first = activeSignature === 0;
const cycle = this.editor.getOption(74 /* 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 /* Active */) {
return;
}
this.state = new ParameterHintState.Active(Object.assign(Object.assign({}, this.state.hints), { activeSignature }));
this._onChangedHints.fire(this.state.hints);
}
doTrigger(triggerId) {
return __awaiter(this, void 0, void 0, function* () {
const isRetrigger = this.state.type === 1 /* Active */ || this.state.type === 2 /* 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)(model, position, triggerContext, token)), activeSignatureHelp);
try {
const result = yield this.state.request;
// Check that we are still resolving the correct signature help
if (triggerId !== this.triggerId) {
result === null || result === void 0 ? void 0 : result.dispose();
return false;
}
if (!result || !result.value.signatures || result.value.signatures.length === 0) {
result === null || result === void 0 ? void 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 /* Active */: return this.state.hints;
case 2 /* Pending */: return this.state.previouslyActiveHints;
default: return undefined;
}
}
get isTriggered() {
return this.state.type === 1 /* Active */
|| this.state.type === 2 /* Pending */
|| this.throttledDelayer.isTriggered();
}
onModelChanged() {
this.cancel();
// Update trigger characters
this.triggerChars = new characterClassifier_1.CharacterSet();
this.retriggerChars = new characterClassifier_1.CharacterSet();
const model = this.editor.getModel();
if (!model) {
return;
}
for (const support of modes.SignatureHelpProviderRegistry.ordered(model)) {
for (const ch of support.signatureHelpTriggerCharacters || []) {
this.triggerChars.add(ch.charCodeAt(0));
// All trigger characters are also considered retrigger characters
this.retriggerChars.add(ch.charCodeAt(0));
}
for (const ch of support.signatureHelpRetriggerCharacters || []) {
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: modes.SignatureHelpTriggerKind.TriggerCharacter,
triggerCharacter: text.charAt(lastCharIndex),
});
}
}
onCursorChange(e) {
if (e.source === 'mouse') {
this.cancel();
}
else if (this.isTriggered) {
this.trigger({ triggerKind: modes.SignatureHelpTriggerKind.ContentChange });
}
}
onModelContentChange() {
if (this.isTriggered) {
this.trigger({ triggerKind: modes.SignatureHelpTriggerKind.ContentChange });
}
}
onEditorConfigurationChange() {
this.triggerOnType = this.editor.getOption(74 /* parameterHints */).enabled;
if (!this.triggerOnType) {
this.cancel();
}
}
dispose() {
this.cancel(true);
super.dispose();
}
}
exports.ParameterHintsModel = ParameterHintsModel;
ParameterHintsModel.DEFAULT_DELAY = 120; // ms
function mergeTriggerContexts(previous, current) {
switch (current.triggerKind) {
case modes.SignatureHelpTriggerKind.Invoke:
// Invoke overrides previous triggers.
return current;
case modes.SignatureHelpTriggerKind.ContentChange:
// Ignore content changes triggers
return previous;
case modes.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.
*--------------------------------------------------------------------------------------------*/
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
define(__m[562/*vs/editor/contrib/suggest/suggestAlternatives*/], __M([0/*require*/,1/*exports*/,16/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, contextkey_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SuggestAlternatives = void 0;
let SuggestAlternatives = class SuggestAlternatives {
constructor(_editor, contextKeyService) {
this._editor = _editor;
this._index = 0;
this._ckOtherSuggestions = SuggestAlternatives.OtherSuggestions.bindTo(contextKeyService);
}
dispose() {
this.reset();
}
reset() {
var _a;
this._ckOtherSuggestions.reset();
(_a = this._listener) === null || _a === void 0 ? void 0 : _a.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
let nextIndex = SuggestAlternatives._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;
while (true) {
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._moveIndex(fwd, this._model, this._index);
this._acceptNext({ index: this._index, item: this._model.items[this._index], model: this._model });
}
finally {
this._ignore = false;
}
}
};
SuggestAlternatives.OtherSuggestions = new contextkey_1.RawContextKey('hasOtherSuggestions', false);
SuggestAlternatives = __decorate([
__param(1, contextkey_1.IContextKeyService)
], SuggestAlternatives);
exports.SuggestAlternatives = 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[563/*vs/editor/contrib/suggest/wordContextKey*/], __M([0/*require*/,1/*exports*/,16/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, contextkey_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WordContextKey = void 0;
let WordContextKey = class WordContextKey {
constructor(_editor, contextKeyService) {
this._editor = _editor;
this._enabled = false;
this._ckAtEnd = WordContextKey.AtEnd.bindTo(contextKeyService);
this._configListener = this._editor.onDidChangeConfiguration(e => e.hasChanged(110 /* tabCompletion */) && this._update());
this._update();
}
dispose() {
var _a;
this._configListener.dispose();
(_a = this._selectionListener) === null || _a === void 0 ? void 0 : _a.dispose();
this._ckAtEnd.reset();
}
_update() {
// only update this when tab completions are enabled
const enabled = this._editor.getOption(110 /* 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;
}
}
};
WordContextKey.AtEnd = new contextkey_1.RawContextKey('atEndOfWord', false);
WordContextKey = __decorate([
__param(1, contextkey_1.IContextKeyService)
], WordContextKey);
exports.WordContextKey = 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[64/*vs/platform/accessibility/common/accessibility*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,16/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, instantiation_1, contextkey_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[253/*vs/platform/contextkey/common/contextkeys*/], __M([0/*require*/,1/*exports*/,535/*vs/nls!vs/platform/contextkey/common/contextkeys*/,16/*vs/platform/contextkey/common/contextkey*/,17/*vs/base/common/platform*/]), function (require, exports, nls_1, contextkey_1, platform_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InputFocusedContextKey = exports.IsWindowsContext = void 0;
exports.IsWindowsContext = new contextkey_1.RawContextKey('isWindows', platform_1.isWindows, (0, nls_1.localize)(0, null));
exports.InputFocusedContextKey = 'inputFocus';
});
/*---------------------------------------------------------------------------------------------
* 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/platform/contextview/browser/contextView*/], __M([0/*require*/,1/*exports*/,9/*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');
});
/*---------------------------------------------------------------------------------------------
* 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/platform/dialogs/common/dialogs*/], __M([0/*require*/,1/*exports*/,9/*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');
});
/*---------------------------------------------------------------------------------------------
* 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/platform/instantiation/common/serviceCollection*/], __M([0/*require*/,1/*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 (let [id, service] of entries) {
this.set(id, service);
}
}
set(id, instanceOrDescriptor) {
const result = this._entries.get(id);
this._entries.set(id, instanceOrDescriptor);
return result;
}
has(id) {
return this._entries.has(id);
}
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[564/*vs/platform/instantiation/common/instantiationService*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,547/*vs/platform/instantiation/common/graph*/,241/*vs/platform/instantiation/common/descriptors*/,9/*vs/platform/instantiation/common/instantiation*/,143/*vs/platform/instantiation/common/serviceCollection*/,15/*vs/base/common/async*/]), function (require, exports, errors_1, graph_1, descriptors_1, instantiation_1, serviceCollection_1, async_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InstantiationService = void 0;
// TRACING
const _enableTracing = false;
class CyclicDependencyError extends Error {
constructor(graph) {
var _a;
super('cyclic dependency between services');
this.message = (_a = graph.findCycleSlow()) !== null && _a !== void 0 ? _a : `UNABLE to detect cycle, dumping graph: \n${graph.toString()}`;
}
}
class InstantiationService {
constructor(services = new serviceCollection_1.ServiceCollection(), strict = false, parent) {
this._activeInstantiations = new Set();
this._services = services;
this._strict = strict;
this._parent = parent;
this._services.set(instantiation_1.IInstantiationService, this);
}
createChild(services) {
return new InstantiationService(services, this._strict, this);
}
invokeFunction(fn, ...args) {
let _trace = Trace.traceInvocation(fn);
let _done = false;
try {
const accessor = {
get: (id, isOptional) => {
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 && isOptional !== instantiation_1.optional) {
throw new Error(`[invokeFunction] unknown service '${id}'`);
}
return result;
}
};
return fn(accessor, ...args);
}
finally {
_done = true;
_trace.stop();
}
}
createInstance(ctorOrDescriptor, ...rest) {
let _trace;
let result;
if (ctorOrDescriptor instanceof descriptors_1.SyncDescriptor) {
_trace = Trace.traceCreation(ctorOrDescriptor.ctor);
result = this._createInstance(ctorOrDescriptor.ctor, ctorOrDescriptor.staticArguments.concat(rest), _trace);
}
else {
_trace = Trace.traceCreation(ctorOrDescriptor);
result = this._createInstance(ctorOrDescriptor, rest, _trace);
}
_trace.stop();
return result;
}
_createInstance(ctor, args = [], _trace) {
// arguments defined by service decorators
let serviceDependencies = instantiation_1._util.getServiceDependencies(ctor).sort((a, b) => a.index - b.index);
let serviceArgs = [];
for (const dependency of serviceDependencies) {
let service = this._getOrCreateServiceInstance(dependency.id, _trace);
if (!service && this._strict && !dependency.optional) {
throw new Error(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id}.`);
}
serviceArgs.push(service);
}
let firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;
// check for argument mismatches, adjust static args if needed
if (args.length !== firstServiceArgPos) {
console.warn(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`);
let delta = firstServiceArgPos - args.length;
if (delta > 0) {
args = args.concat(new Array(delta));
}
else {
args = args.slice(0, firstServiceArgPos);
}
}
// now create the instance
return new ctor(...[...args, ...serviceArgs]);
}
_setServiceInstance(id, instance) {
if (this._services.get(id) instanceof descriptors_1.SyncDescriptor) {
this._services.set(id, instance);
}
else if (this._parent) {
this._parent._setServiceInstance(id, instance);
}
else {
throw new Error('illegalState - setting UNKNOWN service instance');
}
}
_getServiceInstanceOrDescriptor(id) {
let instanceOrDesc = this._services.get(id);
if (!instanceOrDesc && this._parent) {
return this._parent._getServiceInstanceOrDescriptor(id);
}
else {
return instanceOrDesc;
}
}
_getOrCreateServiceInstance(id, _trace) {
let 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 }];
while (stack.length) {
const item = stack.pop();
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 (let dependency of instantiation_1._util.getServiceDependencies(item.desc.ctor)) {
let instanceOrDesc = this._getServiceInstanceOrDescriptor(dependency.id);
if (!instanceOrDesc && !dependency.optional) {
console.warn(`[createInstance] ${id} depends on ${dependency.id} which is NOT registered.`);
}
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._setServiceInstance(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(ctor, args, supportsDelayedInstantiation, _trace);
}
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(ctor, args = [], _supportsDelayedInstantiation, _trace) {
if (!_supportsDelayedInstantiation) {
// eager instantiation
return this._createInstance(ctor, args, _trace);
}
else {
// 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
const idle = new async_1.IdleValue(() => this._createInstance(ctor, args, _trace));
return new Proxy(Object.create(null), {
get(target, key) {
if (key in target) {
return target[key];
}
let 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;
}
});
}
}
}
exports.InstantiationService = InstantiationService;
class Trace {
constructor(type, name) {
this.type = type;
this.name = name;
this._start = Date.now();
this._dep = [];
}
static traceInvocation(ctor) {
return !_enableTracing ? Trace._None : new Trace(1 /* Invocation */, ctor.name || ctor.toString().substring(0, 42).replace(/\n/g, ''));
}
static traceCreation(ctor) {
return !_enableTracing ? Trace._None : new Trace(0 /* Creation */, ctor.name);
}
branch(id, first) {
let child = new Trace(2 /* Branch */, id.toString());
this._dep.push([id, first, child]);
return child;
}
stop() {
let dur = Date.now() - this._start;
Trace._totals += dur;
let causedCreation = false;
function printChild(n, trace) {
let res = [];
let 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}`);
let nested = printChild(n + 1, child);
if (nested) {
res.push(nested);
}
}
else {
res.push(`${prefix}uses -> ${id}`);
}
}
return res.join('\n');
}
let lines = [
`${this.type === 0 /* 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) {
console.log(lines.join('\n'));
}
}
}
Trace._None = new class extends Trace {
constructor() { super(-1, null); }
stop() { }
branch() { return this; }
};
Trace._totals = 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[565/*vs/platform/keybinding/common/abstractKeybindingService*/], __M([0/*require*/,1/*exports*/,536/*vs/nls!vs/platform/keybinding/common/abstractKeybindingService*/,15/*vs/base/common/async*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, nls, async_1, event_1, lifecycle_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AbstractKeybindingService = void 0;
class AbstractKeybindingService extends lifecycle_1.Disposable {
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._currentChord = null;
this._currentChordChecker = new async_1.IntervalTimer();
this._currentChordStatusMessage = null;
this._currentSingleModifier = null;
this._currentSingleModifierClearTimeout = new async_1.TimeoutTimer();
this._logging = false;
}
get onDidUpdateKeybindings() {
return this._onDidUpdateKeybindings ? this._onDidUpdateKeybindings.event : event_1.Event.None; // Sinon stubbing walks properties on prototype
}
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);
}
softDispatch(e, target) {
const keybinding = this.resolveKeyboardEvent(e);
if (keybinding.isChord()) {
console.warn('Unexpected keyboard event mapped to a chord');
return null;
}
const [firstPart,] = keybinding.getDispatchParts();
if (firstPart === null) {
// cannot be dispatched, probably only modifier keys
return null;
}
const contextValue = this._contextKeyService.getContext(target);
const currentChord = this._currentChord ? this._currentChord.keypress : null;
return this._getResolver().resolve(contextValue, currentChord, firstPart);
}
_enterChordMode(firstPart, keypressLabel) {
this._currentChord = {
keypress: firstPart,
label: keypressLabel
};
this._currentChordStatusMessage = this._notificationService.status(nls.localize(0, null, keypressLabel));
const chordEnterTime = Date.now();
this._currentChordChecker.cancelAndSet(() => {
if (!this._documentHasFocus()) {
// Focus has been lost => leave chord mode
this._leaveChordMode();
return;
}
if (Date.now() - chordEnterTime > 5000) {
// 5 seconds elapsed => leave chord mode
this._leaveChordMode();
}
}, 500);
}
_leaveChordMode() {
if (this._currentChordStatusMessage) {
this._currentChordStatusMessage.dispose();
this._currentChordStatusMessage = null;
}
this._currentChordChecker.cancel();
this._currentChord = null;
}
_dispatch(e, target) {
return this._doDispatch(this.resolveKeyboardEvent(e), target, /*isSingleModiferChord*/ false);
}
_singleModifierDispatch(e, target) {
const keybinding = this.resolveKeyboardEvent(e);
const [singleModifier,] = keybinding.getSingleModifierDispatchParts();
if (singleModifier !== null && 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 !== null && 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._currentSingleModifierClearTimeout.cancel();
this._currentSingleModifier = null;
return false;
}
_doDispatch(keybinding, target, isSingleModiferChord = false) {
let shouldPreventDefault = false;
if (keybinding.isChord()) {
console.warn('Unexpected keyboard event mapped to a chord');
return false;
}
let firstPart = null; // the first keybinding i.e. Ctrl+K
let currentChord = null; // the "second" keybinding i.e. Ctrl+K "Ctrl+D"
if (isSingleModiferChord) {
const [dispatchKeyname,] = keybinding.getSingleModifierDispatchParts();
firstPart = dispatchKeyname;
currentChord = dispatchKeyname;
}
else {
[firstPart,] = keybinding.getDispatchParts();
currentChord = this._currentChord ? this._currentChord.keypress : null;
}
if (firstPart === 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 = keybinding.getLabel();
const resolveResult = this._getResolver().resolve(contextValue, currentChord, firstPart);
this._logService.trace('KeybindingService#dispatch', keypressLabel, resolveResult === null || resolveResult === void 0 ? void 0 : resolveResult.commandId);
if (resolveResult && resolveResult.enterChord) {
shouldPreventDefault = true;
this._enterChordMode(firstPart, keypressLabel);
return shouldPreventDefault;
}
if (this._currentChord) {
if (!resolveResult || !resolveResult.commandId) {
this._notificationService.status(nls.localize(1, null, this._currentChord.label, keypressLabel), { hideAfter: 10 * 1000 /* 10s */ });
shouldPreventDefault = true;
}
}
this._leaveChordMode();
if (resolveResult && resolveResult.commandId) {
if (!resolveResult.bubble) {
shouldPreventDefault = true;
}
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));
}
this._telemetryService.publicLog2('workbenchActionExecuted', { id: resolveResult.commandId, from: 'keybinding' });
}
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 /* KEY_A */ && event.keyCode <= 56 /* KEY_Z */)
|| (event.keyCode >= 21 /* KEY_0 */ && event.keyCode <= 30 /* KEY_9 */)) {
return true;
}
return false;
}
}
exports.AbstractKeybindingService = AbstractKeybindingService;
});
/*---------------------------------------------------------------------------------------------
* 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/platform/keybinding/common/baseResolvedKeybinding*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,182/*vs/base/common/keybindingLabels*/,41/*vs/base/common/keyCodes*/]), function (require, exports, errors_1, keybindingLabels_1, keyCodes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseResolvedKeybinding = void 0;
class BaseResolvedKeybinding extends keyCodes_1.ResolvedKeybinding {
constructor(os, parts) {
super();
if (parts.length === 0) {
throw (0, errors_1.illegalArgument)(`parts`);
}
this._os = os;
this._parts = parts;
}
getLabel() {
return keybindingLabels_1.UILabelProvider.toLabel(this._os, this._parts, (keybinding) => this._getLabel(keybinding));
}
getAriaLabel() {
return keybindingLabels_1.AriaLabelProvider.toLabel(this._os, this._parts, (keybinding) => this._getAriaLabel(keybinding));
}
isChord() {
return (this._parts.length > 1);
}
getParts() {
return this._parts.map((keybinding) => this._getPart(keybinding));
}
_getPart(keybinding) {
return new keyCodes_1.ResolvedKeybindingPart(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.metaKey, this._getLabel(keybinding), this._getAriaLabel(keybinding));
}
getDispatchParts() {
return this._parts.map((keybinding) => this._getDispatchPart(keybinding));
}
getSingleModifierDispatchParts() {
return this._parts.map((keybinding) => this._getSingleModifierDispatchPart(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[37/*vs/platform/keybinding/common/keybinding*/], __M([0/*require*/,1/*exports*/,9/*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');
});
/*---------------------------------------------------------------------------------------------
* 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/platform/keybinding/common/keybindingResolver*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeybindingResolver = void 0;
class KeybindingResolver {
constructor(defaultKeybindings, overrides, log) {
this._log = log;
this._defaultKeybindings = defaultKeybindings;
this._defaultBoundCommands = new Map();
for (let i = 0, len = defaultKeybindings.length; i < len; i++) {
const command = defaultKeybindings[i].command;
if (command) {
this._defaultBoundCommands.set(command, true);
}
}
this._map = new Map();
this._lookupMap = new Map();
this._keybindings = KeybindingResolver.combine(defaultKeybindings, overrides);
for (let i = 0, len = this._keybindings.length; i < len; i++) {
let k = this._keybindings[i];
if (k.keypressParts.length === 0) {
// unbound
continue;
}
if (k.when && k.when.type === 0 /* False */) {
// when condition is false
continue;
}
// TODO@chords
this._addKeyPress(k.keypressParts[0], k);
}
}
static _isTargetedForRemoval(defaultKb, keypressFirstPart, keypressChordPart, command, when) {
if (defaultKb.command !== command) {
return false;
}
// TODO@chords
if (keypressFirstPart && defaultKb.keypressParts[0] !== keypressFirstPart) {
return false;
}
// TODO@chords
if (keypressChordPart && defaultKb.keypressParts[1] !== keypressChordPart) {
return false;
}
if (when) {
if (!defaultKb.when) {
return false;
}
if (!when.equals(defaultKb.when)) {
return false;
}
}
return true;
}
/**
* Looks for rules containing -command in `overrides` and removes them directly from `defaults`.
*/
static combine(defaults, rawOverrides) {
defaults = defaults.slice(0);
let overrides = [];
for (const override of rawOverrides) {
if (!override.command || override.command.length === 0 || override.command.charAt(0) !== '-') {
overrides.push(override);
continue;
}
const command = override.command.substr(1);
// TODO@chords
const keypressFirstPart = override.keypressParts[0];
const keypressChordPart = override.keypressParts[1];
const when = override.when;
for (let j = defaults.length - 1; j >= 0; j--) {
if (this._isTargetedForRemoval(defaults[j], keypressFirstPart, keypressChordPart, command, when)) {
defaults.splice(j, 1);
}
}
}
return defaults.concat(overrides);
}
_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--) {
let conflict = conflicts[i];
if (conflict.command === item.command) {
continue;
}
const conflictIsChord = (conflict.keypressParts.length > 1);
const itemIsChord = (item.keypressParts.length > 1);
// TODO@chords
if (conflictIsChord && itemIsChord && conflict.keypressParts[1] !== item.keypressParts[1]) {
// The conflict only shares the chord start with this command
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;
}
let 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 /* True */) {
return true;
}
if (!a || a.type === 1 /* True */) {
return false;
}
return this._implies(a, b);
}
/**
* Returns true if it is provable `p` implies `q`.
*/
static _implies(p, q) {
const notP = p.negate();
const terminals = (node) => {
if (node.type === 9 /* Or */) {
return node.expr;
}
return [node];
};
let expr = terminals(notP).concat(terminals(q));
for (let i = 0; i < expr.length; i++) {
const a = expr[i];
const notA = a.negate();
for (let j = i + 1; j < expr.length; j++) {
const b = expr[j];
if (notA.equals(b)) {
return true;
}
}
}
return false;
}
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];
}
resolve(context, currentChord, keypress) {
this._log(`| Resolving ${keypress}${currentChord ? ` chorded from ${currentChord}` : ``}`);
let lookupMap = null;
if (currentChord !== null) {
// Fetch all chord bindings for `currentChord`
const candidates = this._map.get(currentChord);
if (typeof candidates === 'undefined') {
// No chords starting with `currentChord`
this._log(`\\ No keybinding entries.`);
return null;
}
lookupMap = [];
for (let i = 0, len = candidates.length; i < len; i++) {
let candidate = candidates[i];
// TODO@chords
if (candidate.keypressParts[1] === keypress) {
lookupMap.push(candidate);
}
}
}
else {
const candidates = this._map.get(keypress);
if (typeof candidates === 'undefined') {
// No bindings with `keypress`
this._log(`\\ No keybinding entries.`);
return null;
}
lookupMap = candidates;
}
let result = this._findCommand(context, lookupMap);
if (!result) {
this._log(`\\ From ${lookupMap.length} keybinding entries, no when clauses matched the context.`);
return null;
}
// TODO@chords
if (currentChord === null && result.keypressParts.length > 1 && result.keypressParts[1] !== null) {
this._log(`\\ From ${lookupMap.length} keybinding entries, matched chord, when: ${printWhenExplanation(result.when)}, source: ${printSourceExplanation(result)}.`);
return {
enterChord: true,
leaveChord: false,
commandId: null,
commandArgs: null,
bubble: false
};
}
this._log(`\\ From ${lookupMap.length} keybinding entries, matched ${result.command}, when: ${printWhenExplanation(result.when)}, source: ${printSourceExplanation(result)}.`);
return {
enterChord: false,
leaveChord: result.keypressParts.length > 1,
commandId: result.command,
commandArgs: result.commandArgs,
bubble: result.bubble
};
}
_findCommand(context, matches) {
for (let i = matches.length - 1; i >= 0; i--) {
let 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[567/*vs/platform/keybinding/common/resolvedKeybindingItem*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.removeElementsAfterNulls = exports.ResolvedKeybindingItem = void 0;
class ResolvedKeybindingItem {
constructor(resolvedKeybinding, command, commandArgs, when, isDefault, extensionId, isBuiltinExtension) {
this._resolvedKeybindingItemBrand = undefined;
this.resolvedKeybinding = resolvedKeybinding;
this.keypressParts = resolvedKeybinding ? removeElementsAfterNulls(resolvedKeybinding.getDispatchParts()) : [];
if (resolvedKeybinding && this.keypressParts.length === 0) {
// handle possible single modifier chord keybindings
this.keypressParts = removeElementsAfterNulls(resolvedKeybinding.getSingleModifierDispatchParts());
}
this.bubble = (command ? command.charCodeAt(0) === 94 /* 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 removeElementsAfterNulls(arr) {
let result = [];
for (let i = 0, len = arr.length; i < len; i++) {
const element = arr[i];
if (!element) {
// stop processing at first encountered null
return result;
}
result.push(element);
}
return result;
}
exports.removeElementsAfterNulls = removeElementsAfterNulls;
});
/*---------------------------------------------------------------------------------------------
* 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/platform/keybinding/common/usLayoutResolvedKeybinding*/], __M([0/*require*/,1/*exports*/,41/*vs/base/common/keyCodes*/,566/*vs/platform/keybinding/common/baseResolvedKeybinding*/]), function (require, exports, keyCodes_1, baseResolvedKeybinding_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(actual, os) {
super(os, actual.parts);
}
_keyCodeToUILabel(keyCode) {
if (this._os === 2 /* Macintosh */) {
switch (keyCode) {
case 15 /* LeftArrow */:
return '←';
case 16 /* UpArrow */:
return '↑';
case 17 /* RightArrow */:
return '→';
case 18 /* DownArrow */:
return '↓';
}
}
return keyCodes_1.KeyCodeUtils.toString(keyCode);
}
_getLabel(keybinding) {
if (keybinding.isDuplicateModifierCase()) {
return '';
}
return this._keyCodeToUILabel(keybinding.keyCode);
}
_getAriaLabel(keybinding) {
if (keybinding.isDuplicateModifierCase()) {
return '';
}
return keyCodes_1.KeyCodeUtils.toString(keybinding.keyCode);
}
_getDispatchPart(keybinding) {
return USLayoutResolvedKeybinding.getDispatchStr(keybinding);
}
static getDispatchStr(keybinding) {
if (keybinding.isModifierKey()) {
return null;
}
let result = '';
if (keybinding.ctrlKey) {
result += 'ctrl+';
}
if (keybinding.shiftKey) {
result += 'shift+';
}
if (keybinding.altKey) {
result += 'alt+';
}
if (keybinding.metaKey) {
result += 'meta+';
}
result += keyCodes_1.KeyCodeUtils.toString(keybinding.keyCode);
return result;
}
_getSingleModifierDispatchPart(keybinding) {
if (keybinding.keyCode === 5 /* Ctrl */ && !keybinding.shiftKey && !keybinding.altKey && !keybinding.metaKey) {
return 'ctrl';
}
if (keybinding.keyCode === 4 /* Shift */ && !keybinding.ctrlKey && !keybinding.altKey && !keybinding.metaKey) {
return 'shift';
}
if (keybinding.keyCode === 6 /* Alt */ && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.metaKey) {
return 'alt';
}
if (keybinding.keyCode === 57 /* Meta */ && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.altKey) {
return 'meta';
}
return null;
}
}
exports.USLayoutResolvedKeybinding = USLayoutResolvedKeybinding;
});
/*---------------------------------------------------------------------------------------------
* 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/label/common/label*/], __M([0/*require*/,1/*exports*/,9/*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[144/*vs/platform/layout/browser/layoutService*/], __M([0/*require*/,1/*exports*/,9/*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[569/*vs/platform/contextview/browser/contextViewService*/], __M([0/*require*/,1/*exports*/,207/*vs/base/browser/ui/contextview/contextview*/,2/*vs/base/common/lifecycle*/,144/*vs/platform/layout/browser/layoutService*/]), function (require, exports, contextview_1, lifecycle_1, layoutService_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextViewService = void 0;
let ContextViewService = class ContextViewService extends lifecycle_1.Disposable {
constructor(layoutService) {
super();
this.layoutService = layoutService;
this.currentViewDisposable = lifecycle_1.Disposable.None;
this.container = layoutService.container;
this.contextView = this._register(new contextview_1.ContextView(this.container, 1 /* ABSOLUTE */));
this.layout();
this._register(layoutService.onDidLayout(() => this.layout()));
}
// ContextView
setContainer(container, domPosition) {
this.contextView.setContainer(container, domPosition || 1 /* ABSOLUTE */);
}
showContextView(delegate, container, shadowRoot) {
if (container) {
if (container !== this.container) {
this.container = container;
this.setContainer(container, shadowRoot ? 3 /* FIXED_SHADOW */ : 2 /* FIXED */);
}
}
else {
if (this.container !== this.layoutService.container) {
this.container = this.layoutService.container;
this.setContainer(this.container, 1 /* ABSOLUTE */);
}
}
this.contextView.show(delegate);
const disposable = (0, lifecycle_1.toDisposable)(() => {
if (this.currentViewDisposable === disposable) {
this.hideContextView();
}
});
this.currentViewDisposable = disposable;
return disposable;
}
getContextViewElement() {
return this.contextView.getViewElement();
}
layout() {
this.contextView.layout();
}
hideContextView(data) {
this.contextView.hide(data);
}
};
ContextViewService = __decorate([
__param(0, layoutService_1.ILayoutService)
], ContextViewService);
exports.ContextViewService = ContextViewService;
});
/*---------------------------------------------------------------------------------------------
* 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/platform/log/common/log*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/]), function (require, exports, instantiation_1, lifecycle_1, event_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LogService = exports.ConsoleLogger = exports.AbstractLogger = exports.DEFAULT_LOG_LEVEL = exports.LogLevel = exports.ILogService = void 0;
exports.ILogService = (0, instantiation_1.createDecorator)('logService');
var LogLevel;
(function (LogLevel) {
LogLevel[LogLevel["Trace"] = 0] = "Trace";
LogLevel[LogLevel["Debug"] = 1] = "Debug";
LogLevel[LogLevel["Info"] = 2] = "Info";
LogLevel[LogLevel["Warning"] = 3] = "Warning";
LogLevel[LogLevel["Error"] = 4] = "Error";
LogLevel[LogLevel["Critical"] = 5] = "Critical";
LogLevel[LogLevel["Off"] = 6] = "Off";
})(LogLevel = exports.LogLevel || (exports.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());
}
setLevel(level) {
if (this.level !== level) {
this.level = level;
this._onDidChangeLogLevel.fire(this.level);
}
}
getLevel() {
return this.level;
}
}
exports.AbstractLogger = AbstractLogger;
class ConsoleLogger extends AbstractLogger {
constructor(logLevel = exports.DEFAULT_LOG_LEVEL) {
super();
this.setLevel(logLevel);
}
trace(message, ...args) {
if (this.getLevel() <= LogLevel.Trace) {
console.log('%cTRACE', 'color: #888', message, ...args);
}
}
debug(message, ...args) {
if (this.getLevel() <= LogLevel.Debug) {
console.log('%cDEBUG', 'background: #eee; color: #888', message, ...args);
}
}
info(message, ...args) {
if (this.getLevel() <= LogLevel.Info) {
console.log('%c INFO', 'color: #33f', message, ...args);
}
}
error(message, ...args) {
if (this.getLevel() <= LogLevel.Error) {
console.log('%c ERR', 'color: #f33', message, ...args);
}
}
dispose() {
// noop
}
}
exports.ConsoleLogger = ConsoleLogger;
class LogService extends lifecycle_1.Disposable {
constructor(logger) {
super();
this.logger = logger;
this._register(logger);
}
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);
}
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[255/*vs/editor/common/services/editorWorkerServiceImpl*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,204/*vs/base/common/worker/simpleWorker*/,301/*vs/base/worker/defaultWorkerFactory*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/modes*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/,397/*vs/editor/common/services/editorSimpleWorker*/,36/*vs/editor/common/services/modelService*/,142/*vs/editor/common/services/textResourceConfigurationService*/,8/*vs/base/common/strings*/,19/*vs/base/common/arrays*/,70/*vs/platform/log/common/log*/,81/*vs/base/common/stopwatch*/,12/*vs/base/common/errors*/]), function (require, exports, async_1, lifecycle_1, simpleWorker_1, defaultWorkerFactory_1, range_1, modes, languageConfigurationRegistry_1, editorSimpleWorker_1, modelService_1, textResourceConfigurationService_1, strings_1, arrays_1, log_1, stopwatch_1, errors_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EditorWorkerClient = exports.EditorWorkerHost = exports.EditorWorkerServiceImpl = void 0;
/**
* Stop syncing a model to the worker if it was not needed for 1 min.
*/
const STOP_SYNC_MODEL_DELTA_TIME_MS = 60 * 1000;
/**
* Stop the worker if it was not needed for 5 min.
*/
const STOP_WORKER_DELTA_TIME_MS = 5 * 60 * 1000;
function canSyncModel(modelService, resource) {
let model = modelService.getModel(resource);
if (!model) {
return false;
}
if (model.isTooLargeForSyncing()) {
return false;
}
return true;
}
let EditorWorkerServiceImpl = class EditorWorkerServiceImpl extends lifecycle_1.Disposable {
constructor(modelService, configurationService, logService) {
super();
this._modelService = modelService;
this._workerManager = this._register(new WorkerManager(this._modelService));
this._logService = logService;
// register default link-provider and default completions-provider
this._register(modes.LinkProviderRegistry.register('*', {
provideLinks: (model, token) => {
if (!canSyncModel(this._modelService, model.uri)) {
return Promise.resolve({ links: [] }); // File too large
}
return this._workerManager.withWorker().then(client => client.computeLinks(model.uri)).then(links => {
return links && { links };
});
}
}));
this._register(modes.CompletionProviderRegistry.register('*', new WordBasedCompletionItemProvider(this._workerManager, configurationService, this._modelService)));
}
dispose() {
super.dispose();
}
canComputeDiff(original, modified) {
return (canSyncModel(this._modelService, original) && canSyncModel(this._modelService, modified));
}
computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime) {
return this._workerManager.withWorker().then(client => client.computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime));
}
computeMoreMinimalEdits(resource, edits) {
if ((0, arrays_1.isNonEmptyArray)(edits)) {
if (!canSyncModel(this._modelService, resource)) {
return Promise.resolve(edits); // File too large
}
const sw = stopwatch_1.StopWatch.create(true);
const result = this._workerManager.withWorker().then(client => client.computeMoreMinimalEdits(resource, edits));
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));
}
navigateValueSet(resource, range, up) {
return this._workerManager.withWorker().then(client => client.navigateValueSet(resource, range, up));
}
canComputeWordRanges(resource) {
return canSyncModel(this._modelService, resource);
}
computeWordRanges(resource, range) {
return this._workerManager.withWorker().then(client => client.computeWordRanges(resource, range));
}
};
EditorWorkerServiceImpl = __decorate([
__param(0, modelService_1.IModelService),
__param(1, textResourceConfigurationService_1.ITextResourceConfigurationService),
__param(2, log_1.ILogService)
], EditorWorkerServiceImpl);
exports.EditorWorkerServiceImpl = EditorWorkerServiceImpl;
class WordBasedCompletionItemProvider {
constructor(workerManager, configurationService, modelService) {
this._debugDisplayName = 'wordbasedCompletions';
this._workerManager = workerManager;
this._configurationService = configurationService;
this._modelService = modelService;
}
provideCompletionItems(model, position) {
return __awaiter(this, void 0, void 0, function* () {
const config = this._configurationService.getValue(model.uri, position, 'editor');
if (!config.wordBasedSuggestions) {
return undefined;
}
const models = [];
if (config.wordBasedSuggestionsMode === '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.wordBasedSuggestionsMode === 'allDocuments' || candidate.getLanguageIdentifier().id === model.getLanguageIdentifier().id) {
models.push(candidate.uri);
}
}
}
if (models.length === 0) {
return undefined; // File too large, no other files
}
const wordDefRegExp = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id);
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 = yield this._workerManager.withWorker();
const data = yield client.textualSuggest(models, word === null || word === void 0 ? void 0 : word.word, wordDefRegExp);
if (!data) {
return undefined;
}
return {
duration: data.duration,
suggestions: data.words.map((word) => {
return {
kind: 18 /* Text */,
label: word,
insertText: word,
range: { insert, replace }
};
}),
};
});
}
}
class WorkerManager extends lifecycle_1.Disposable {
constructor(modelService) {
super();
this._modelService = modelService;
this._editorWorkerClient = null;
this._lastWorkerUsedTime = (new Date()).getTime();
let stopWorkerInterval = this._register(new async_1.IntervalTimer());
stopWorkerInterval.cancelAndSet(() => this._checkStopIdleWorker(), Math.round(STOP_WORKER_DELTA_TIME_MS / 2));
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;
}
let 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;
}
let 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._modelService, false, 'editorWorkerService');
}
return Promise.resolve(this._editorWorkerClient);
}
}
class EditorModelManager extends lifecycle_1.Disposable {
constructor(proxy, modelService, keepIdleModels) {
super();
this._syncedModels = Object.create(null);
this._syncedModelsLastUsedTime = Object.create(null);
this._proxy = proxy;
this._modelService = modelService;
if (!keepIdleModels) {
let timer = new async_1.IntervalTimer();
timer.cancelAndSet(() => this._checkStopModelSync(), Math.round(STOP_SYNC_MODEL_DELTA_TIME_MS / 2));
this._register(timer);
}
}
dispose() {
for (let 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) {
for (const resource of resources) {
let resourceStr = resource.toString();
if (!this._syncedModels[resourceStr]) {
this._beginModelSync(resource);
}
if (this._syncedModels[resourceStr]) {
this._syncedModelsLastUsedTime[resourceStr] = (new Date()).getTime();
}
}
}
_checkStopModelSync() {
let currentTime = (new Date()).getTime();
let toRemove = [];
for (let modelUrl in this._syncedModelsLastUsedTime) {
let elapsedTime = currentTime - this._syncedModelsLastUsedTime[modelUrl];
if (elapsedTime > STOP_SYNC_MODEL_DELTA_TIME_MS) {
toRemove.push(modelUrl);
}
}
for (const e of toRemove) {
this._stopModelSync(e);
}
}
_beginModelSync(resource) {
let model = this._modelService.getModel(resource);
if (!model) {
return;
}
if (model.isTooLargeForSyncing()) {
return;
}
let 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) {
let toDispose = this._syncedModels[modelUrl];
delete this._syncedModels[modelUrl];
delete this._syncedModelsLastUsedTime[modelUrl];
(0, lifecycle_1.dispose)(toDispose);
}
}
class SynchronousWorkerClient {
constructor(instance) {
this._instance = instance;
this._proxyObj = Promise.resolve(this._instance);
}
dispose() {
this._instance.dispose();
}
getProxyObject() {
return this._proxyObj;
}
}
class EditorWorkerHost {
constructor(workerClient) {
this._workerClient = workerClient;
}
// foreign host request
fhr(method, args) {
return this._workerClient.fhr(method, args);
}
}
exports.EditorWorkerHost = EditorWorkerHost;
class EditorWorkerClient extends lifecycle_1.Disposable {
constructor(modelService, keepIdleModels, label) {
super();
this._disposed = false;
this._modelService = modelService;
this._keepIdleModels = keepIdleModels;
this._workerFactory = new defaultWorkerFactory_1.DefaultWorkerFactory(label);
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(new simpleWorker_1.SimpleWorkerClient(this._workerFactory, 'vs/editor/common/services/editorSimpleWorker', new EditorWorkerHost(this)));
}
catch (err) {
(0, simpleWorker_1.logOnceWebWorkerWarning)(err);
this._worker = new SynchronousWorkerClient(new editorSimpleWorker_1.EditorSimpleWorker(new EditorWorkerHost(this), null));
}
}
return this._worker;
}
_getProxy() {
return this._getOrCreateWorker().getProxyObject().then(undefined, (err) => {
(0, simpleWorker_1.logOnceWebWorkerWarning)(err);
this._worker = new SynchronousWorkerClient(new editorSimpleWorker_1.EditorSimpleWorker(new EditorWorkerHost(this), null));
return this._getOrCreateWorker().getProxyObject();
});
}
_getOrCreateModelManager(proxy) {
if (!this._modelManager) {
this._modelManager = this._register(new EditorModelManager(proxy, this._modelService, this._keepIdleModels));
}
return this._modelManager;
}
_withSyncedResources(resources) {
if (this._disposed) {
return Promise.reject((0, errors_1.canceled)());
}
return this._getProxy().then((proxy) => {
this._getOrCreateModelManager(proxy).ensureSyncedResources(resources);
return proxy;
});
}
computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime) {
return this._withSyncedResources([original, modified]).then(proxy => {
return proxy.computeDiff(original.toString(), modified.toString(), ignoreTrimWhitespace, maxComputationTime);
});
}
computeMoreMinimalEdits(resource, edits) {
return this._withSyncedResources([resource]).then(proxy => {
return proxy.computeMoreMinimalEdits(resource.toString(), edits);
});
}
computeLinks(resource) {
return this._withSyncedResources([resource]).then(proxy => {
return proxy.computeLinks(resource.toString());
});
}
textualSuggest(resources, leadingWord, wordDefRegExp) {
return __awaiter(this, void 0, void 0, function* () {
const proxy = yield this._withSyncedResources(resources);
const wordDef = wordDefRegExp.source;
const wordDefFlags = (0, strings_1.regExpFlags)(wordDefRegExp);
return proxy.textualSuggest(resources.map(r => r.toString()), leadingWord, wordDef, wordDefFlags);
});
}
computeWordRanges(resource, range) {
return this._withSyncedResources([resource]).then(proxy => {
let model = this._modelService.getModel(resource);
if (!model) {
return Promise.resolve(null);
}
let wordDefRegExp = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id);
let wordDef = wordDefRegExp.source;
let wordDefFlags = (0, strings_1.regExpFlags)(wordDefRegExp);
return proxy.computeWordRanges(resource.toString(), range, wordDef, wordDefFlags);
});
}
navigateValueSet(resource, range, up) {
return this._withSyncedResources([resource]).then(proxy => {
let model = this._modelService.getModel(resource);
if (!model) {
return null;
}
let wordDefRegExp = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id);
let wordDef = wordDefRegExp.source;
let wordDefFlags = (0, strings_1.regExpFlags)(wordDefRegExp);
return proxy.navigateValueSet(resource.toString(), range, up, wordDef, wordDefFlags);
});
}
dispose() {
super.dispose();
this._disposed = true;
}
}
exports.EditorWorkerClient = 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[256/*vs/editor/common/services/semanticTokensProviderStyling*/], __M([0/*require*/,1/*exports*/,18/*vs/editor/common/modes*/,70/*vs/platform/log/common/log*/,140/*vs/editor/common/model/tokensStore*/]), function (require, exports, modes_1, log_1, tokensStore_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toMultilineTokens2 = exports.SemanticTokensProviderStyling = void 0;
class SemanticTokensProviderStyling {
constructor(_legend, _themeService, _logService) {
this._legend = _legend;
this._themeService = _themeService;
this._logService = _logService;
this._hashTable = new HashTable();
this._hasWarnedOverlappingTokens = false;
}
getMetadata(tokenTypeIndex, tokenModifierSet, languageId) {
const entry = this._hashTable.get(tokenTypeIndex, tokenModifierSet, languageId.id);
let metadata;
if (entry) {
metadata = entry.metadata;
if (this._logService.getLevel() === log_1.LogLevel.Trace) {
this._logService.trace(`SemanticTokensProviderStyling [CACHED] ${tokenTypeIndex} / ${tokenModifierSet}: foreground ${modes_1.TokenMetadata.getForeground(metadata)}, fontStyle ${modes_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 (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.language);
if (typeof tokenStyle === 'undefined') {
metadata = 2147483647 /* NO_STYLING */;
}
else {
metadata = 0;
if (typeof tokenStyle.italic !== 'undefined') {
const italicBit = (tokenStyle.italic ? 1 /* Italic */ : 0) << 11 /* FONT_STYLE_OFFSET */;
metadata |= italicBit | 1 /* SEMANTIC_USE_ITALIC */;
}
if (typeof tokenStyle.bold !== 'undefined') {
const boldBit = (tokenStyle.bold ? 2 /* Bold */ : 0) << 11 /* FONT_STYLE_OFFSET */;
metadata |= boldBit | 2 /* SEMANTIC_USE_BOLD */;
}
if (typeof tokenStyle.underline !== 'undefined') {
const underlineBit = (tokenStyle.underline ? 4 /* Underline */ : 0) << 11 /* FONT_STYLE_OFFSET */;
metadata |= underlineBit | 4 /* SEMANTIC_USE_UNDERLINE */;
}
if (tokenStyle.foreground) {
const foregroundBits = (tokenStyle.foreground) << 14 /* FOREGROUND_OFFSET */;
metadata |= foregroundBits | 8 /* SEMANTIC_USE_FOREGROUND */;
}
if (metadata === 0) {
// Nothing!
metadata = 2147483647 /* NO_STYLING */;
}
}
}
else {
if (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 /* NO_STYLING */;
tokenType = 'not-in-legend';
}
this._hashTable.add(tokenTypeIndex, tokenModifierSet, languageId.id, metadata);
if (this._logService.getLevel() === log_1.LogLevel.Trace) {
this._logService.trace(`SemanticTokensProviderStyling ${tokenTypeIndex} (${tokenType}) / ${tokenModifierSet} (${tokenModifiers.join(' ')}): foreground ${modes_1.TokenMetadata.getForeground(metadata)}, fontStyle ${modes_1.TokenMetadata.getFontStyle(metadata).toString(2)}`);
}
}
return metadata;
}
warnOverlappingSemanticTokens(lineNumber, startColumn) {
if (!this._hasWarnedOverlappingTokens) {
this._hasWarnedOverlappingTokens = true;
console.warn(`Overlapping semantic tokens detected at lineNumber ${lineNumber}, column ${startColumn}`);
}
}
}
exports.SemanticTokensProviderStyling = 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 /* DesiredMaxAreas */), 400 /* 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 prevStartCharacter = 0;
let prevEndCharacter = 0;
while (tokenIndex < tokenEndIndex) {
const srcOffset = 5 * tokenIndex;
const deltaLine = srcData[srcOffset];
const deltaCharacter = srcData[srcOffset + 1];
const lineNumber = lastLineNumber + deltaLine;
const startCharacter = (deltaLine === 0 ? lastStartCharacter + deltaCharacter : deltaCharacter);
const length = srcData[srcOffset + 2];
const tokenTypeIndex = srcData[srcOffset + 3];
const tokenModifierSet = srcData[srcOffset + 4];
const metadata = styling.getMetadata(tokenTypeIndex, tokenModifierSet, languageId);
if (metadata !== 2147483647 /* NO_STYLING */) {
if (areaLine === 0) {
areaLine = lineNumber;
}
if (prevLineNumber === lineNumber && prevEndCharacter > startCharacter) {
styling.warnOverlappingSemanticTokens(lineNumber, startCharacter + 1);
if (prevStartCharacter < startCharacter) {
// the previous token survives after the overlapping one
destData[destOffset - 4 + 2] = startCharacter;
}
else {
// the previous token is entirely covered by the overlapping one
destOffset -= 4;
}
}
destData[destOffset] = lineNumber - areaLine;
destData[destOffset + 1] = startCharacter;
destData[destOffset + 2] = startCharacter + length;
destData[destOffset + 3] = metadata;
destOffset += 4;
prevLineNumber = lineNumber;
prevStartCharacter = startCharacter;
prevEndCharacter = startCharacter + length;
}
lastLineNumber = lineNumber;
lastStartCharacter = startCharacter;
tokenIndex++;
}
if (destOffset !== destData.length) {
destData = destData.subarray(0, destOffset);
}
const tokens = new tokensStore_1.MultilineTokens2(areaLine, new tokensStore_1.SparseEncodedTokens(destData));
result.push(tokens);
}
return result;
}
exports.toMultilineTokens2 = toMultilineTokens2;
class HashTableEntry {
constructor(tokenTypeIndex, tokenModifierSet, languageId, metadata) {
this.tokenTypeIndex = tokenTypeIndex;
this.tokenModifierSet = tokenModifierSet;
this.languageId = languageId;
this.metadata = metadata;
this.next = null;
}
}
class HashTable {
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;
}
}
HashTable._SIZES = [3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143];
});
/*---------------------------------------------------------------------------------------------
* 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/services/webWorker*/], __M([0/*require*/,1/*exports*/,255/*vs/editor/common/services/editorWorkerServiceImpl*/,20/*vs/base/common/types*/]), function (require, exports, editorWorkerServiceImpl_1, types) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createWebWorker = void 0;
/**
* 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);
}
exports.createWebWorker = createWebWorker;
class MonacoWebWorkerImpl extends editorWorkerServiceImpl_1.EditorWorkerClient {
constructor(modelService, opts) {
super(modelService, opts.keepIdleModels || false, opts.label);
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 ? types.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);
};
};
let foreignProxy = {};
for (const foreignMethod of foreignMethods) {
foreignProxy[foreignMethod] = createProxyMethod(foreignMethod, proxyMethodRequest);
}
return foreignProxy;
});
});
}
return this._foreignProxy;
}
getProxy() {
return this._getForeignProxy();
}
withSyncedResources(resources) {
return this._withSyncedResources(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[87/*vs/platform/markers/common/markers*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,538/*vs/nls!vs/platform/markers/common/markers*/,74/*vs/base/common/severity*/]), function (require, exports, instantiation_1, nls_1, severity_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 || (exports.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)(0, null);
_displayStrings[MarkerSeverity.Warning] = (0, nls_1.localize)(1, null);
_displayStrings[MarkerSeverity.Info] = (0, nls_1.localize)(2, null);
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 || (exports.MarkerSeverity = {}));
var IMarkerData;
(function (IMarkerData) {
const emptyString = '';
function makeKey(markerData) {
return makeKeyOptionalMessage(markerData, true);
}
IMarkerData.makeKey = makeKey;
function makeKeyOptionalMessage(markerData, useMessage) {
let 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 || (exports.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[571/*vs/editor/contrib/gotoError/markerNavigationService*/], __M([0/*require*/,1/*exports*/,87/*vs/platform/markers/common/markers*/,24/*vs/base/common/uri*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/,8/*vs/base/common/strings*/,19/*vs/base/common/arrays*/,9/*vs/platform/instantiation/common/instantiation*/,75/*vs/platform/instantiation/common/extensions*/,72/*vs/base/common/linkedList*/]), function (require, exports, markers_1, uri_1, event_1, lifecycle_1, range_1, strings_1, arrays_1, instantiation_1, extensions_1, linkedList_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) {
this._markerService = _markerService;
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 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(MarkerList._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;
}
let 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;
}
static _compareMarker(a, b) {
let res = (0, strings_1.compare)(a.resource.toString(), b.resource.toString());
if (res === 0) {
res = markers_1.MarkerSeverity.compare(a.severity, b.severity);
}
if (res === 0) {
res = range_1.Range.compareRangesUsingStarts(a, b);
}
return res;
}
};
MarkerList = __decorate([
__param(1, markers_1.IMarkerService)
], MarkerList);
exports.MarkerList = MarkerList;
exports.IMarkerNavigationService = (0, instantiation_1.createDecorator)('IMarkerNavigationService');
let MarkerNavigationService = class MarkerNavigationService {
constructor(_markerService) {
this._markerService = _markerService;
this._provider = new linkedList_1.LinkedList();
}
getMarkerList(resource) {
for (let provider of this._provider) {
const result = provider.getMarkerList(resource);
if (result) {
return result;
}
}
// default
return new MarkerList(resource, this._markerService);
}
};
MarkerNavigationService = __decorate([
__param(0, markers_1.IMarkerService)
], MarkerNavigationService);
(0, extensions_1.registerSingleton)(exports.IMarkerNavigationService, MarkerNavigationService, 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[572/*vs/platform/markers/common/markerService*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,46/*vs/base/common/network*/,24/*vs/base/common/uri*/,6/*vs/base/common/event*/,87/*vs/platform/markers/common/markers*/,49/*vs/base/common/map*/,54/*vs/base/common/iterator*/]), function (require, exports, arrays_1, network_1, uri_1, event_1, markers_1, map_1, iterator_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MarkerService = void 0;
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) {
let ownerMap = this._byResource.get(resource);
return ownerMap === null || ownerMap === void 0 ? void 0 : ownerMap.get(owner);
}
delete(resource, owner) {
let removedA = false;
let removedB = false;
let ownerMap = this._byResource.get(resource);
if (ownerMap) {
removedA = ownerMap.delete(owner);
}
let resourceMap = this._byOwner.get(owner);
if (resourceMap) {
removedB = resourceMap.delete(resource);
}
if (removedA !== removedB) {
throw new Error('illegal state');
}
return removedA && removedB;
}
values(key) {
var _a, _b, _c, _d;
if (typeof key === 'string') {
return (_b = (_a = this._byOwner.get(key)) === null || _a === void 0 ? void 0 : _a.values()) !== null && _b !== void 0 ? _b : iterator_1.Iterable.empty();
}
if (uri_1.URI.isUri(key)) {
return (_d = (_c = this._byResource.get(key)) === null || _c === void 0 ? void 0 : _c.values()) !== null && _d !== void 0 ? _d : 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 (resource.scheme === network_1.Schemas.inMemory || resource.scheme === network_1.Schemas.walkThrough || resource.scheme === network_1.Schemas.walkThroughSnippet) {
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,
};
}
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 (let markers of this._data.values()) {
for (let 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 !== null && resource !== void 0 ? 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 (let array of all) {
for (let item of array) {
set.set(item, true);
}
}
return Array.from(set.keys());
}
}
exports.MarkerService = 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[34/*vs/platform/notification/common/notification*/], __M([0/*require*/,1/*exports*/,74/*vs/base/common/severity*/,9/*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[58/*vs/platform/opener/common/opener*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,24/*vs/base/common/uri*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, lifecycle_1, strings_1, uri_1, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.matchesScheme = exports.NullOpenerService = exports.IOpenerService = void 0;
exports.IOpenerService = (0, instantiation_1.createDecorator)('openerService');
exports.NullOpenerService = Object.freeze({
_serviceBrand: undefined,
registerOpener() { return lifecycle_1.Disposable.None; },
registerValidator() { return lifecycle_1.Disposable.None; },
registerExternalUriResolver() { return lifecycle_1.Disposable.None; },
setDefaultExternalOpener() { },
registerExternalOpener() { return lifecycle_1.Disposable.None; },
open() {
return __awaiter(this, void 0, void 0, function* () { return false; });
},
resolveExternalUri(uri) {
return __awaiter(this, void 0, void 0, function* () { return { resolved: uri, dispose() { } }; });
},
});
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 + ':');
}
}
exports.matchesScheme = matchesScheme;
});
/*---------------------------------------------------------------------------------------------
* 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/browser/core/markdownRenderer*/], __M([0/*require*/,1/*exports*/,298/*vs/base/browser/markdownRenderer*/,58/*vs/platform/opener/common/opener*/,57/*vs/editor/common/services/modeService*/,12/*vs/base/common/errors*/,246/*vs/editor/common/modes/textToHtmlTokenizer*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,18/*vs/editor/common/modes*/]), function (require, exports, markdownRenderer_1, opener_1, modeService_1, errors_1, textToHtmlTokenizer_1, event_1, lifecycle_1, modes_1) {
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MarkdownRenderer = void 0;
/**
* Markdown renderer that can render codeblocks with the editor mechanics. This
* renderer should always be preferred.
*/
let MarkdownRenderer = class MarkdownRenderer {
constructor(_options, _modeService, _openerService) {
this._options = _options;
this._modeService = _modeService;
this._openerService = _openerService;
this._onDidRenderAsync = new event_1.Emitter();
this.onDidRenderAsync = this._onDidRenderAsync.event;
}
dispose() {
this._onDidRenderAsync.dispose();
}
render(markdown, options, markedOptions) {
const disposables = new lifecycle_1.DisposableStore();
let element;
if (!markdown) {
element = document.createElement('span');
}
else {
element = (0, markdownRenderer_1.renderMarkdown)(markdown, Object.assign(Object.assign({}, this._getRenderOptions(markdown, disposables)), options), markedOptions);
}
return {
element,
dispose: () => disposables.dispose()
};
}
_getRenderOptions(markdown, disposeables) {
return {
baseUrl: this._options.baseUrl,
codeBlockRenderer: (languageAlias, value) => __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c, _d;
// 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 modeId;
if (languageAlias) {
modeId = this._modeService.getModeIdForLanguageName(languageAlias);
}
else if (this._options.editor) {
modeId = (_a = this._options.editor.getModel()) === null || _a === void 0 ? void 0 : _a.getLanguageIdentifier().language;
}
if (!modeId) {
modeId = 'plaintext';
}
this._modeService.triggerMode(modeId);
const tokenization = (_b = yield modes_1.TokenizationRegistry.getPromise(modeId)) !== null && _b !== void 0 ? _b : undefined;
const element = document.createElement('span');
element.innerHTML = ((_d = (_c = MarkdownRenderer._ttpTokenizer) === null || _c === void 0 ? void 0 : _c.createHTML(value, tokenization)) !== null && _d !== void 0 ? _d : (0, textToHtmlTokenizer_1.tokenizeToString)(value, tokenization));
// use "good" font
let fontFamily = this._options.codeBlockFontFamily;
if (this._options.editor) {
fontFamily = this._options.editor.getOption(41 /* fontInfo */).fontFamily;
}
if (fontFamily) {
element.style.fontFamily = fontFamily;
}
return element;
}),
asyncRenderCallback: () => this._onDidRenderAsync.fire(),
actionHandler: {
callback: (content) => this._openerService.open(content, { fromUserGesture: true, allowContributedOpeners: true, allowCommands: markdown.isTrusted }).catch(errors_1.onUnexpectedError),
disposeables
}
};
}
};
MarkdownRenderer._ttpTokenizer = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('tokenizeToString', {
createHTML(value, tokenizer) {
return (0, textToHtmlTokenizer_1.tokenizeToString)(value, tokenizer);
}
});
MarkdownRenderer = __decorate([
__param(1, modeService_1.IModeService),
__param(2, opener_1.IOpenerService)
], MarkdownRenderer);
exports.MarkdownRenderer = MarkdownRenderer;
});
/*---------------------------------------------------------------------------------------------
* 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/browser/services/openerService*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,23/*vs/base/common/cancellation*/,72/*vs/base/common/linkedList*/,49/*vs/base/common/map*/,202/*vs/base/common/marshalling*/,46/*vs/base/common/network*/,43/*vs/base/common/resources*/,24/*vs/base/common/uri*/,28/*vs/editor/browser/services/codeEditorService*/,26/*vs/platform/commands/common/commands*/,545/*vs/platform/editor/common/editor*/,58/*vs/platform/opener/common/opener*/]), function (require, exports, dom, 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;
}
open(target, options) {
return __awaiter(this, void 0, void 0, function* () {
if (!(0, opener_1.matchesScheme)(target, network_1.Schemas.command)) {
return false;
}
if (!(options === null || options === void 0 ? void 0 : options.allowCommands)) {
// silently ignore commands when command-links are disabled, also
// surpress other openers by returning TRUE
return true;
}
// run command or bail out if command isn't known
if (typeof target === 'string') {
target = uri_1.URI.parse(target);
}
// execute as command
let args = [];
try {
args = (0, marshalling_1.parse)(decodeURIComponent(target.query));
}
catch (_a) {
// ignore and retry
try {
args = (0, marshalling_1.parse)(target.query);
}
catch (_b) {
// ignore error
}
}
if (!Array.isArray(args)) {
args = [args];
}
yield 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;
}
open(target, options) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof target === 'string') {
target = uri_1.URI.parse(target);
}
let selection = undefined;
const match = /^L?(\d+)(?:,(\d+))?/.exec(target.fragment);
if (match) {
// support file:///some/file.js#73,84
// support file:///some/file.js#L73
selection = {
startLineNumber: parseInt(match[1]),
startColumn: match[2] ? parseInt(match[2]) : 1
};
// remove fragment
target = target.with({ fragment: '' });
}
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)
}
yield this._editorService.openCodeEditor({
resource: target,
options: Object.assign({ selection, context: (options === null || options === void 0 ? void 0 : options.fromUserGesture) ? editor_1.EditorOpenContext.USER : editor_1.EditorOpenContext.API }, options === null || options === void 0 ? void 0 : options.editorOptions)
}, this._editorService.getFocusedCodeEditor(), options === null || options === void 0 ? void 0 : 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: (href) => __awaiter(this, void 0, void 0, function* () {
// 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, opener_1.matchesScheme)(href, network_1.Schemas.http) || (0, opener_1.matchesScheme)(href, network_1.Schemas.https)) {
dom.windowOpenNoOpener(href);
}
else {
window.location.href = href;
}
return true;
})
};
// Default opener: any external, maito, http(s), command, and catch-all-editors
this._openers.push({
open: (target, options) => __awaiter(this, void 0, void 0, function* () {
if ((options === null || options === void 0 ? void 0 : options.openExternal) || (0, opener_1.matchesScheme)(target, network_1.Schemas.mailto) || (0, opener_1.matchesScheme)(target, network_1.Schemas.http) || (0, opener_1.matchesScheme)(target, network_1.Schemas.https)) {
// open externally
yield 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 };
}
registerValidator(validator) {
const remove = this._validators.push(validator);
return { dispose: remove };
}
registerExternalUriResolver(resolver) {
const remove = this._resolvers.push(resolver);
return { dispose: remove };
}
setDefaultExternalOpener(externalOpener) {
this._defaultExternalOpener = externalOpener;
}
registerExternalOpener(opener) {
const remove = this._externalOpeners.push(opener);
return { dispose: remove };
}
open(target, options) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
// 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 = (_a = this._resolvedUriTargets.get(targetURI)) !== null && _a !== void 0 ? _a : target;
for (const validator of this._validators) {
if (!(yield validator.shouldOpen(validationTarget))) {
return false;
}
}
// check with contributed openers
for (const opener of this._openers) {
const handled = yield opener.open(target, options);
if (handled) {
return true;
}
}
return false;
});
}
resolveExternalUri(resource, options) {
return __awaiter(this, void 0, void 0, function* () {
for (const resolver of this._resolvers) {
try {
const result = yield resolver.resolveExternalUri(resource, options);
if (result) {
if (!this._resolvedUriTargets.has(result.resolved)) {
this._resolvedUriTargets.set(result.resolved, resource);
}
return result;
}
}
catch (_a) {
// noop
}
}
throw new Error('Could not resolve external URI: ' + resource.toString());
});
}
_doOpenExternal(resource, options) {
return __awaiter(this, void 0, void 0, function* () {
//todo@jrieken IExternalUriResolver should support `uri: URI | string`
const uri = typeof resource === 'string' ? uri_1.URI.parse(resource) : resource;
let externalUri;
try {
externalUri = (yield this.resolveExternalUri(uri, options)).resolved;
}
catch (_a) {
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 === null || options === void 0 ? void 0 : options.allowContributedOpeners) {
const preferredOpenerId = typeof (options === null || options === void 0 ? void 0 : options.allowContributedOpeners) === 'string' ? options === null || options === void 0 ? void 0 : options.allowContributedOpeners : undefined;
for (const opener of this._externalOpeners) {
const didOpen = yield 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();
}
};
OpenerService = __decorate([
__param(0, codeEditorService_1.ICodeEditorService),
__param(1, commands_1.ICommandService)
], OpenerService);
exports.OpenerService = 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[574/*vs/editor/contrib/hover/modesGlyphHover*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,82/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,230/*vs/editor/contrib/hover/hoverOperation*/,416/*vs/editor/contrib/hover/hoverWidgets*/,145/*vs/editor/browser/core/markdownRenderer*/,58/*vs/platform/opener/common/opener*/,19/*vs/base/common/arrays*/]), function (require, exports, dom_1, htmlContent_1, lifecycle_1, hoverOperation_1, hoverWidgets_1, markdownRenderer_1, opener_1, arrays_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModesGlyphHoverWidget = void 0;
class MarginComputer {
constructor(editor) {
this._editor = editor;
this._lineNumber = -1;
this._result = [];
}
setLineNumber(lineNumber) {
this._lineNumber = lineNumber;
this._result = [];
}
clearResult() {
this._result = [];
}
computeSync() {
const toHoverMessage = (contents) => {
return {
value: contents
};
};
const lineDecorations = this._editor.getLineDecorations(this._lineNumber);
const result = [];
if (!lineDecorations) {
return result;
}
for (const d of lineDecorations) {
if (!d.options.glyphMarginClassName) {
continue;
}
const hoverMessage = d.options.glyphMarginHoverMessage;
if (!hoverMessage || (0, htmlContent_1.isEmptyMarkdownString)(hoverMessage)) {
continue;
}
result.push(...(0, arrays_1.asArray)(hoverMessage).map(toHoverMessage));
}
return result;
}
onResult(result, isFromSynchronousComputation) {
this._result = this._result.concat(result);
}
getResult() {
return this._result;
}
getResultWithLoadingMessage() {
return this.getResult();
}
}
class ModesGlyphHoverWidget extends hoverWidgets_1.GlyphHoverWidget {
constructor(editor, modeService, openerService = opener_1.NullOpenerService) {
super(ModesGlyphHoverWidget.ID, editor);
this._renderDisposeables = this._register(new lifecycle_1.DisposableStore());
this._messages = [];
this._lastLineNumber = -1;
this._markdownRenderer = this._register(new markdownRenderer_1.MarkdownRenderer({ editor: this._editor }, modeService, openerService));
this._computer = new MarginComputer(this._editor);
this._hoverOperation = new hoverOperation_1.HoverOperation(this._computer, (result) => this._withResult(result), undefined, (result) => this._withResult(result), 300);
}
dispose() {
this._hoverOperation.cancel();
super.dispose();
}
onModelDecorationsChanged() {
if (this.isVisible) {
// The decorations have changed and the hover is visible,
// we need to recompute the displayed text
this._hoverOperation.cancel();
this._computer.clearResult();
this._hoverOperation.start(0 /* Delayed */);
}
}
startShowingAt(lineNumber) {
if (this._lastLineNumber === lineNumber) {
// 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._lastLineNumber = lineNumber;
this._computer.setLineNumber(lineNumber);
this._hoverOperation.start(0 /* Delayed */);
}
hide() {
this._lastLineNumber = -1;
this._hoverOperation.cancel();
super.hide();
}
_withResult(result) {
this._messages = result;
if (this._messages.length > 0) {
this._renderMessages(this._lastLineNumber, this._messages);
}
else {
this.hide();
}
}
_renderMessages(lineNumber, messages) {
this._renderDisposeables.clear();
const fragment = document.createDocumentFragment();
for (const msg of messages) {
const renderedContents = this._markdownRenderer.render(msg.value);
this._renderDisposeables.add(renderedContents);
fragment.appendChild((0, dom_1.$)('div.hover-row', undefined, renderedContents.element));
}
this.updateContents(fragment);
this.showAt(lineNumber);
}
}
exports.ModesGlyphHoverWidget = ModesGlyphHoverWidget;
ModesGlyphHoverWidget.ID = 'editor.contrib.modesGlyphHoverWidget';
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/suggest/suggestWidgetDetails*/], __M([0/*require*/,1/*exports*/,523/*vs/nls!vs/editor/contrib/suggest/suggestWidgetDetails*/,2/*vs/base/common/lifecycle*/,7/*vs/base/browser/dom*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,145/*vs/editor/browser/core/markdownRenderer*/,82/*vs/base/common/htmlContent*/,27/*vs/base/common/codicons*/,6/*vs/base/common/event*/,235/*vs/editor/contrib/suggest/resizable*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, nls, lifecycle_1, dom, scrollableElement_1, markdownRenderer_1, htmlContent_1, codicons_1, event_1, resizable_1, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SuggestDetailsOverlay = exports.SuggestDetailsWidget = exports.canExpandCompletionItem = void 0;
function canExpandCompletionItem(item) {
return !!item && Boolean(item.completion.documentation || item.completion.detail && item.completion.detail !== item.completion.label);
}
exports.canExpandCompletionItem = canExpandCompletionItem;
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, {});
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' + codicons_1.Codicon.close.cssSelector));
this._close.title = nls.localize(0, null);
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(41 /* fontInfo */)) {
this._configureFont();
}
}));
}
dispose() {
this._disposables.dispose();
this._renderDisposeable.dispose();
}
_configureFont() {
const options = this._editor.getOptions();
const fontInfo = options.get(41 /* fontInfo */);
const fontFamily = fontInfo.fontFamily;
const fontSize = options.get(106 /* suggestFontSize */) || fontInfo.fontSize;
const lineHeight = options.get(107 /* suggestLineHeight */) || fontInfo.lineHeight;
const fontWeight = fontInfo.fontWeight;
const fontSizePx = `${fontSize}px`;
const lineHeightPx = `${lineHeight}px`;
this.domNode.style.fontSize = fontSizePx;
this.domNode.style.lineHeight = lineHeightPx;
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(107 /* suggestLineHeight */) || this._editor.getOption(41 /* fontInfo */).lineHeight;
const borderWidth = this._borderWidth;
const borderHeight = borderWidth * 2;
return {
lineHeight,
borderWidth,
borderHeight,
verticalPadding: 22,
horizontalPadding: 14
};
}
renderLoading() {
this._type.textContent = nls.localize(1, null);
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) {
var _a, _b;
this._renderDisposeable.clear();
let { detail, documentation } = item.completion;
if (explainMode) {
let md = '';
md += `score: ${item.score[0]}\n`;
md += `prefix: ${(_a = item.word) !== null && _a !== void 0 ? _a : '(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: ${(_b = item.completion.commitCharacters) === null || _b === void 0 ? void 0 : _b.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 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;
}
};
SuggestDetailsWidget = __decorate([
__param(1, instantiation_1.IInstantiationService)
], SuggestDetailsWidget);
exports.SuggestDetailsWidget = SuggestDetailsWidget;
class SuggestDetailsOverlay {
constructor(widget, _editor) {
this.widget = widget;
this._editor = _editor;
this._disposables = new lifecycle_1.DisposableStore();
this._added = false;
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(() => {
var _a;
if (this._anchorBox) {
this._placeAtAnchor(this._anchorBox, (_a = this._userSize) !== null && _a !== void 0 ? _a : this.widget.size);
}
}));
}
dispose() {
this._resizable.dispose();
this._disposables.dispose();
this.hide();
}
getId() {
return 'suggest.details';
}
getDomNode() {
return this._resizable.domNode;
}
getPosition() {
return null;
}
show() {
if (!this._added) {
this._editor.addOverlayWidget(this);
this.getDomNode().style.position = 'fixed';
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) {
var _a;
const anchorBox = dom.getDomNodePagePosition(anchor);
this._anchorBox = anchorBox;
this._placeAtAnchor(this._anchorBox, (_a = this._userSize) !== null && _a !== void 0 ? _a : this.widget.size);
}
_placeAtAnchor(anchorBox, size) {
const bodyBox = dom.getClientArea(document.body);
const info = this.widget.getLayoutInfo();
let maxSizeTop;
let maxSizeBottom;
let minSize = new dom.Dimension(220, 2 * info.lineHeight);
let left = 0;
let top = anchorBox.top;
let bottom = anchorBox.top + anchorBox.height - info.borderHeight;
let alignAtTop;
let alignEast;
// position: EAST, west, south
let width = bodyBox.width - (anchorBox.left + anchorBox.width + info.borderWidth + info.horizontalPadding);
left = -info.borderWidth + anchorBox.left + anchorBox.width;
alignEast = true;
maxSizeTop = new dom.Dimension(width, bodyBox.height - anchorBox.top - info.borderHeight - info.verticalPadding);
maxSizeBottom = maxSizeTop.with(undefined, anchorBox.top + anchorBox.height - info.borderHeight - info.verticalPadding);
// find a better place if the widget is wider than there is space available
if (size.width > width) {
// position: east, WEST, south
if (anchorBox.left > width) {
// pos = SuggestDetailsPosition.West;
width = anchorBox.left - info.borderWidth - info.horizontalPadding;
alignEast = false;
left = Math.max(info.horizontalPadding, anchorBox.left - size.width - info.borderWidth);
maxSizeTop = maxSizeTop.with(width);
maxSizeBottom = maxSizeTop.with(undefined, maxSizeBottom.height);
}
// position: east, west, SOUTH
if (anchorBox.width > width * 1.3 && bodyBox.height - (anchorBox.top + anchorBox.height) > anchorBox.height) {
width = anchorBox.width;
left = anchorBox.left;
top = -info.borderWidth + anchorBox.top + anchorBox.height;
maxSizeTop = new dom.Dimension(anchorBox.width - info.borderHeight, bodyBox.height - anchorBox.top - anchorBox.height - info.verticalPadding);
maxSizeBottom = maxSizeTop.with(undefined, anchorBox.top - info.verticalPadding);
minSize = minSize.with(maxSizeTop.width);
}
}
// top/bottom placement
let height = size.height;
let maxHeight = Math.max(maxSizeTop.height, maxSizeBottom.height);
if (height > maxHeight) {
height = maxHeight;
}
let maxSize;
if (height <= maxSizeTop.height) {
alignAtTop = true;
maxSize = maxSizeTop;
}
else {
alignAtTop = false;
maxSize = maxSizeBottom;
}
this._applyTopLeft({ left, top: alignAtTop ? top : bottom - height });
this.getDomNode().style.position = 'fixed';
this._resizable.enableSashes(!alignAtTop, alignEast, alignAtTop, !alignEast);
this._resizable.minSize = 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.getDomNode().style.left = `${this._topLeft.left}px`;
this.getDomNode().style.top = `${this._topLeft.top}px`;
}
}
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[59/*vs/platform/progress/common/progress*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IEditorProgressService = exports.Progress = void 0;
class Progress {
constructor(callback) {
this.callback = callback;
}
report(item) {
this._value = item;
this.callback(this._value);
}
}
exports.Progress = Progress;
Progress.None = Object.freeze({ report() { } });
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[575/*vs/platform/quickinput/browser/pickerQuickAccess*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,15/*vs/base/common/async*/]), function (require, exports, cancellation_1, lifecycle_1, async_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 || (exports.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) {
var _a;
const disposables = new lifecycle_1.DisposableStore();
// Apply options if any
picker.canAcceptInBackground = !!((_a = this.options) === null || _a === void 0 ? void 0 : _a.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 = () => __awaiter(this, void 0, void 0, function* () {
const picksDisposables = picksDisposable.value = new lifecycle_1.DisposableStore();
// Cancel any previous ask for picks and busy
picksCts === null || picksCts === void 0 ? void 0 : 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;
const picksFilter = picker.value.substr(this.prefix.length).trim();
const providedPicks = this._getPicks(picksFilter, picksDisposables, picksToken);
const applyPicks = (picks, skipEmpty) => {
var _a;
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;
}
if (picksFilter.length > 0 && ((_a = this.options) === null || _a === void 0 ? void 0 : _a.noResultsPick)) {
items = [this.options.noResultsPick];
}
}
picker.items = items;
if (activeItem) {
picker.activeItems = [activeItem];
}
return true;
};
// No Picks
if (providedPicks === null) {
// Ignore
}
// Fast and Slow Picks
else if (isFastAndSlowPicks(providedPicks)) {
let fastPicksApplied = false;
let slowPicksApplied = false;
yield Promise.all([
// Fast Picks: to reduce amount of flicker, we race against
// the slow picks over 500ms and then set the fast picks.
// If the slow picks are faster, we reduce the flicker by
// only setting the items once.
(() => __awaiter(this, void 0, void 0, function* () {
yield (0, async_1.timeout)(PickerQuickAccessProvider.FAST_PICKS_RACE_DELAY);
if (picksToken.isCancellationRequested) {
return;
}
if (!slowPicksApplied) {
fastPicksApplied = applyPicks(providedPicks.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.
(() => __awaiter(this, void 0, void 0, function* () {
picker.busy = true;
try {
const awaitedAdditionalPicks = yield providedPicks.additionalPicks;
if (picksToken.isCancellationRequested) {
return;
}
let picks;
let activePick = undefined;
if (isPicksWithActive(providedPicks.picks)) {
picks = providedPicks.picks.items;
activePick = providedPicks.picks.active;
}
else {
picks = providedPicks.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;
}
}))()
]);
}
// Fast Picks
else if (!(providedPicks instanceof Promise)) {
applyPicks(providedPicks);
}
// Slow Picks
else {
picker.busy = true;
try {
const awaitedPicks = yield providedPicks;
if (picksToken.isCancellationRequested) {
return;
}
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 => {
const [item] = picker.selectedItems;
if (typeof (item === null || item === void 0 ? void 0 : item.accept) === 'function') {
if (!event.inBackground) {
picker.hide(); // hide picker unless we accept in background
}
item.accept(picker.keyMods, event);
}
}));
// Trigger the pick with button index if button triggered
disposables.add(picker.onDidTriggerItemButton(({ button, item }) => __awaiter(this, void 0, void 0, function* () {
var _b, _c;
if (typeof item.trigger === 'function') {
const buttonIndex = (_c = (_b = item.buttons) === null || _b === void 0 ? void 0 : _b.indexOf(button)) !== null && _c !== void 0 ? _c : -1;
if (buttonIndex >= 0) {
const result = item.trigger(buttonIndex, picker.keyMods);
const action = (typeof result === 'number') ? result : yield 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();
items.splice(index, 1);
picker.items = items;
}
break;
}
}
}
})));
return disposables;
}
}
exports.PickerQuickAccessProvider = PickerQuickAccessProvider;
PickerQuickAccessProvider.FAST_PICKS_RACE_DELAY = 200; // timeout before we accept fast results before slow results are present
});
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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[78/*vs/platform/quickinput/common/quickInput*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,205/*vs/base/parts/quickinput/common/quickInput*/]), function (require, exports, instantiation_1, quickInput_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IQuickInputService = void 0;
__exportStar(quickInput_1, exports);
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[32/*vs/platform/registry/common/platform*/], __M([0/*require*/,1/*exports*/,20/*vs/base/common/types*/,198/*vs/base/common/assert*/]), function (require, exports, Types, Assert) {
"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();
});
/*---------------------------------------------------------------------------------------------
* 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/modes/modesRegistry*/], __M([0/*require*/,1/*exports*/,468/*vs/nls!vs/editor/common/modes/modesRegistry*/,6/*vs/base/common/event*/,18/*vs/editor/common/modes*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/,32/*vs/platform/registry/common/platform*/,106/*vs/base/common/mime*/]), function (require, exports, nls, event_1, modes_1, languageConfigurationRegistry_1, platform_1, mime_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PLAINTEXT_LANGUAGE_IDENTIFIER = exports.PLAINTEXT_EXTENSION = exports.PLAINTEXT_MODE_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 = [];
this._dynamicLanguages = [];
}
// --- 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 [].concat(this._languages).concat(this._dynamicLanguages);
}
}
exports.EditorModesRegistry = EditorModesRegistry;
exports.ModesRegistry = new EditorModesRegistry();
platform_1.Registry.add(exports.Extensions.ModesRegistry, exports.ModesRegistry);
exports.PLAINTEXT_MODE_ID = 'plaintext';
exports.PLAINTEXT_EXTENSION = '.txt';
exports.PLAINTEXT_LANGUAGE_IDENTIFIER = new modes_1.LanguageIdentifier(exports.PLAINTEXT_MODE_ID, 1 /* PlainText */);
exports.ModesRegistry.registerLanguage({
id: exports.PLAINTEXT_MODE_ID,
extensions: [exports.PLAINTEXT_EXTENSION],
aliases: [nls.localize(0, null), 'text'],
mimetypes: [mime_1.Mimes.text]
});
languageConfigurationRegistry_1.LanguageConfigurationRegistry.register(exports.PLAINTEXT_LANGUAGE_IDENTIFIER, {
brackets: [
['(', ')'],
['[', ']'],
['{', '}'],
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '<', close: '>' },
{ open: '\"', close: '\"' },
{ open: '\'', close: '\'' },
{ open: '`', close: '`' },
],
folding: {
offSide: true
}
}, 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[576/*vs/editor/common/services/getIconClasses*/], __M([0/*require*/,1/*exports*/,46/*vs/base/common/network*/,43/*vs/base/common/resources*/,146/*vs/editor/common/modes/modesRegistry*/,240/*vs/platform/files/common/files*/]), function (require, exports, network_1, resources_1, modesRegistry_1, files_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cssEscape = exports.detectModeId = exports.getIconClasses = void 0;
function getIconClasses(modelService, modeService, resource, fileKind) {
// 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 {
name = cssEscape((0, resources_1.basenameOrAuthority)(resource).toLowerCase());
}
// Folders
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`);
// 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 detectedModeId = detectModeId(modelService, modeService, resource);
if (detectedModeId) {
classes.push(`${cssEscape(detectedModeId)}-lang-file-icon`);
}
}
}
return classes;
}
exports.getIconClasses = getIconClasses;
function detectModeId(modelService, modeService, resource) {
if (!resource) {
return null; // we need a resource at least
}
let modeId = 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) {
modeId = modeService.getModeId(mime);
}
}
// Any other URI: check for model if existing
else {
const model = modelService.getModel(resource);
if (model) {
modeId = model.getModeId();
}
}
// only take if the mode is specific (aka no just plain text)
if (modeId && modeId !== modesRegistry_1.PLAINTEXT_MODE_ID) {
return modeId;
}
// otherwise fallback to path based detection
return modeService.getModeIdByFilepathOrFirstLine(resource);
}
exports.detectModeId = detectModeId;
function cssEscape(str) {
return str.replace(/[\11\12\14\15\40]/g, '/'); // HTML class names can not contain certain whitespace characters, use / instead, which doesn't exist in file names.
}
exports.cssEscape = cssEscape;
});
/*---------------------------------------------------------------------------------------------
* 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/platform/jsonschemas/common/jsonContributionRegistry*/], __M([0/*require*/,1/*exports*/,32/*vs/platform/registry/common/platform*/,6/*vs/base/common/event*/]), function (require, exports, platform, event_1) {
"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[98/*vs/platform/configuration/common/configurationRegistry*/], __M([0/*require*/,1/*exports*/,533/*vs/nls!vs/platform/configuration/common/configurationRegistry*/,6/*vs/base/common/event*/,32/*vs/platform/registry/common/platform*/,20/*vs/base/common/types*/,189/*vs/platform/jsonschemas/common/jsonContributionRegistry*/]), function (require, exports, nls, event_1, platform_1, types, jsonContributionRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateProperty = exports.getDefaultValue = exports.overrideIdentifierFromKey = exports.OVERRIDE_PROPERTY_PATTERN = exports.resourceLanguageSettingsSchemaId = exports.resourceSettings = exports.windowSettings = exports.machineOverridableSettings = exports.machineSettings = exports.applicationSettings = exports.allSettings = exports.Extensions = void 0;
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.overrideIdentifiers = new Set();
this._onDidSchemaChange = new event_1.Emitter();
this._onDidUpdateConfiguration = new event_1.Emitter();
this.defaultValues = {};
this.defaultLanguageConfigurationOverridesNode = {
id: 'defaultOverrides',
title: nls.localize(0, null),
properties: {}
};
this.configurationContributors = [this.defaultLanguageConfigurationOverridesNode];
this.resourceLanguageSettingsSchema = { properties: {}, patternProperties: {}, additionalProperties: false, errorMessage: 'Unknown editor configuration setting', allowTrailingCommas: true, allowComments: true };
this.configurationProperties = {};
this.excludedConfigurationProperties = {};
contributionRegistry.registerSchema(exports.resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
}
registerConfiguration(configuration, validate = true) {
this.registerConfigurations([configuration], validate);
}
registerConfigurations(configurations, validate = true) {
const properties = [];
configurations.forEach(configuration => {
properties.push(...this.validateAndRegisterProperties(configuration, validate, configuration.extensionInfo)); // fills in defaults
this.configurationContributors.push(configuration);
this.registerJSONConfiguration(configuration);
});
contributionRegistry.registerSchema(exports.resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
this._onDidSchemaChange.fire();
this._onDidUpdateConfiguration.fire(properties);
}
registerOverrideIdentifiers(overrideIdentifiers) {
for (const overrideIdentifier of overrideIdentifiers) {
this.overrideIdentifiers.add(overrideIdentifier);
}
this.updateOverridePropertyPatternKey();
}
validateAndRegisterProperties(configuration, validate = true, extensionInfo, scope = 3 /* WINDOW */) {
var _a;
scope = types.isUndefinedOrNull(configuration.scope) ? scope : configuration.scope;
let propertyKeys = [];
let properties = configuration.properties;
if (properties) {
for (let key in properties) {
if (validate && validateProperty(key)) {
delete properties[key];
continue;
}
const property = properties[key];
// update default value
this.updatePropertyDefaultValue(key, property);
// update scope
if (exports.OVERRIDE_PROPERTY_PATTERN.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) ? !!((_a = extensionInfo === null || extensionInfo === void 0 ? void 0 : extensionInfo.restrictedConfigurations) === null || _a === void 0 ? void 0 : _a.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].deprecationMessage && properties[key].markdownDeprecationMessage) {
// If not set, default deprecationMessage to the markdown source
properties[key].deprecationMessage = properties[key].markdownDeprecationMessage;
}
propertyKeys.push(key);
}
}
let subNodes = configuration.allOf;
if (subNodes) {
for (let node of subNodes) {
propertyKeys.push(...this.validateAndRegisterProperties(node, validate, extensionInfo, scope));
}
}
return propertyKeys;
}
getConfigurationProperties() {
return this.configurationProperties;
}
registerJSONConfiguration(configuration) {
const register = (configuration) => {
let properties = configuration.properties;
if (properties) {
for (const key in properties) {
this.updateSchema(key, properties[key]);
}
}
let subNodes = configuration.allOf;
if (subNodes) {
subNodes.forEach(register);
}
};
register(configuration);
}
updateSchema(key, property) {
exports.allSettings.properties[key] = property;
switch (property.scope) {
case 1 /* APPLICATION */:
exports.applicationSettings.properties[key] = property;
break;
case 2 /* MACHINE */:
exports.machineSettings.properties[key] = property;
break;
case 6 /* MACHINE_OVERRIDABLE */:
exports.machineOverridableSettings.properties[key] = property;
break;
case 3 /* WINDOW */:
exports.windowSettings.properties[key] = property;
break;
case 4 /* RESOURCE */:
exports.resourceSettings.properties[key] = property;
break;
case 5 /* 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(1, null),
errorMessage: nls.localize(2, null),
$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;
}
this._onDidSchemaChange.fire();
}
updatePropertyDefaultValue(key, property) {
let defaultValue = this.defaultValues[key];
if (types.isUndefined(defaultValue)) {
defaultValue = property.default;
}
if (types.isUndefined(defaultValue)) {
defaultValue = getDefaultValue(property.type);
}
property.default = defaultValue;
}
}
const OVERRIDE_PROPERTY = '\\[.*\\]$';
exports.OVERRIDE_PROPERTY_PATTERN = new RegExp(OVERRIDE_PROPERTY);
function overrideIdentifierFromKey(key) {
return key.substring(1, key.length - 1);
}
exports.overrideIdentifierFromKey = overrideIdentifierFromKey;
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;
}
}
exports.getDefaultValue = getDefaultValue;
const configurationRegistry = new ConfigurationRegistry();
platform_1.Registry.add(exports.Extensions.Configuration, configurationRegistry);
function validateProperty(property) {
if (!property.trim()) {
return nls.localize(3, null);
}
if (exports.OVERRIDE_PROPERTY_PATTERN.test(property)) {
return nls.localize(4, null, property);
}
if (configurationRegistry.getConfigurationProperties()[property] !== undefined) {
return nls.localize(5, null, property);
}
return null;
}
exports.validateProperty = validateProperty;
});
/*---------------------------------------------------------------------------------------------
* 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/editor/common/config/commonEditorConfig*/], __M([0/*require*/,1/*exports*/,463/*vs/nls!vs/editor/common/config/commonEditorConfig*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,42/*vs/base/common/objects*/,19/*vs/base/common/arrays*/,35/*vs/editor/common/config/editorOptions*/,133/*vs/editor/common/config/editorZoom*/,168/*vs/editor/common/config/fontInfo*/,98/*vs/platform/configuration/common/configurationRegistry*/,32/*vs/platform/registry/common/platform*/,199/*vs/base/common/collections*/]), function (require, exports, nls, event_1, lifecycle_1, objects, arrays, editorOptions_1, editorZoom_1, fontInfo_1, configurationRegistry_1, platform_1, collections_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isDiffEditorConfigurationKey = exports.isEditorConfigurationKey = exports.editorConfigurationBaseNode = exports.CommonEditorConfiguration = exports.ComputedEditorOptions = exports.TabFocus = void 0;
exports.TabFocus = new class {
constructor() {
this._tabFocus = false;
this._onDidChangeTabFocus = new event_1.Emitter();
this.onDidChangeTabFocus = this._onDidChangeTabFocus.event;
}
getTabFocusMode() {
return this._tabFocus;
}
setTabFocusMode(tabFocusMode) {
if (this._tabFocus === tabFocusMode) {
return;
}
this._tabFocus = tabFocusMode;
this._onDidChangeTabFocus.fire(this._tabFocus);
}
};
const hasOwnProperty = Object.hasOwnProperty;
class ComputedEditorOptions {
constructor() {
this._values = [];
}
_read(id) {
return this._values[id];
}
get(id) {
return this._values[id];
}
_write(id, value) {
this._values[id] = value;
}
}
exports.ComputedEditorOptions = ComputedEditorOptions;
class RawEditorOptions {
constructor() {
this._values = [];
}
_read(id) {
return this._values[id];
}
_write(id, value) {
this._values[id] = value;
}
}
class EditorConfiguration2 {
static readOptions(_options) {
const options = _options;
const result = new RawEditorOptions();
for (const editorOption of editorOptions_1.editorOptionsRegistry) {
const value = (editorOption.name === '_never_' ? undefined : options[editorOption.name]);
result._write(editorOption.id, value);
}
return result;
}
static validateOptions(options) {
const result = new editorOptions_1.ValidatedEditorOptions();
for (const editorOption of editorOptions_1.editorOptionsRegistry) {
result._write(editorOption.id, editorOption.validate(options._read(editorOption.id)));
}
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') {
return (a === b);
}
if (Array.isArray(a) || Array.isArray(b)) {
return (Array.isArray(a) && Array.isArray(b) ? arrays.equals(a, b) : false);
}
for (let key in a) {
if (!EditorConfiguration2._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 = !EditorConfiguration2._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);
}
}
/**
* Compatibility with old options
*/
function migrateOptions(options) {
const wordWrap = options.wordWrap;
if (wordWrap === true) {
options.wordWrap = 'on';
}
else if (wordWrap === false) {
options.wordWrap = 'off';
}
const lineNumbers = options.lineNumbers;
if (lineNumbers === true) {
options.lineNumbers = 'on';
}
else if (lineNumbers === false) {
options.lineNumbers = 'off';
}
const autoClosingBrackets = options.autoClosingBrackets;
if (autoClosingBrackets === false) {
options.autoClosingBrackets = 'never';
options.autoClosingQuotes = 'never';
options.autoSurround = 'never';
}
const cursorBlinking = options.cursorBlinking;
if (cursorBlinking === 'visible') {
options.cursorBlinking = 'solid';
}
const renderWhitespace = options.renderWhitespace;
if (renderWhitespace === true) {
options.renderWhitespace = 'boundary';
}
else if (renderWhitespace === false) {
options.renderWhitespace = 'none';
}
const renderLineHighlight = options.renderLineHighlight;
if (renderLineHighlight === true) {
options.renderLineHighlight = 'line';
}
else if (renderLineHighlight === false) {
options.renderLineHighlight = 'none';
}
const acceptSuggestionOnEnter = options.acceptSuggestionOnEnter;
if (acceptSuggestionOnEnter === true) {
options.acceptSuggestionOnEnter = 'on';
}
else if (acceptSuggestionOnEnter === false) {
options.acceptSuggestionOnEnter = 'off';
}
const tabCompletion = options.tabCompletion;
if (tabCompletion === false) {
options.tabCompletion = 'off';
}
else if (tabCompletion === true) {
options.tabCompletion = 'onlySnippets';
}
const suggest = options.suggest;
if (suggest && typeof suggest.filteredTypes === 'object' && suggest.filteredTypes) {
const mapping = {};
mapping['method'] = 'showMethods';
mapping['function'] = 'showFunctions';
mapping['constructor'] = 'showConstructors';
mapping['deprecated'] = 'showDeprecated';
mapping['field'] = 'showFields';
mapping['variable'] = 'showVariables';
mapping['class'] = 'showClasses';
mapping['struct'] = 'showStructs';
mapping['interface'] = 'showInterfaces';
mapping['module'] = 'showModules';
mapping['property'] = 'showProperties';
mapping['event'] = 'showEvents';
mapping['operator'] = 'showOperators';
mapping['unit'] = 'showUnits';
mapping['value'] = 'showValues';
mapping['constant'] = 'showConstants';
mapping['enum'] = 'showEnums';
mapping['enumMember'] = 'showEnumMembers';
mapping['keyword'] = 'showKeywords';
mapping['text'] = 'showWords';
mapping['color'] = 'showColors';
mapping['file'] = 'showFiles';
mapping['reference'] = 'showReferences';
mapping['folder'] = 'showFolders';
mapping['typeParameter'] = 'showTypeParameters';
mapping['snippet'] = 'showSnippets';
(0, collections_1.forEach)(mapping, entry => {
const value = suggest.filteredTypes[entry.key];
if (value === false) {
suggest[entry.value] = value;
}
});
// delete (<any>suggest).filteredTypes;
}
const hover = options.hover;
if (hover === true) {
options.hover = {
enabled: true
};
}
else if (hover === false) {
options.hover = {
enabled: false
};
}
const parameterHints = options.parameterHints;
if (parameterHints === true) {
options.parameterHints = {
enabled: true
};
}
else if (parameterHints === false) {
options.parameterHints = {
enabled: false
};
}
const autoIndent = options.autoIndent;
if (autoIndent === true) {
options.autoIndent = 'full';
}
else if (autoIndent === false) {
options.autoIndent = 'advanced';
}
const matchBrackets = options.matchBrackets;
if (matchBrackets === true) {
options.matchBrackets = 'always';
}
else if (matchBrackets === false) {
options.matchBrackets = 'never';
}
}
function deepCloneAndMigrateOptions(_options) {
const options = objects.deepClone(_options);
migrateOptions(options);
return options;
}
class CommonEditorConfiguration extends lifecycle_1.Disposable {
constructor(isSimpleWidget, _options) {
super();
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.isSimpleWidget = isSimpleWidget;
this._isDominatedByLongLines = false;
this._computeOptionsMemory = new editorOptions_1.ComputeOptionsMemory();
this._viewLineCount = 1;
this._lineNumbersDigitCount = 1;
this._rawOptions = deepCloneAndMigrateOptions(_options);
this._readOptions = EditorConfiguration2.readOptions(this._rawOptions);
this._validatedOptions = EditorConfiguration2.validateOptions(this._readOptions);
this._register(editorZoom_1.EditorZoom.onDidChangeZoomLevel(_ => this._recomputeOptions()));
this._register(exports.TabFocus.onDidChangeTabFocus(_ => this._recomputeOptions()));
}
observeReferenceElement(dimension) {
}
updatePixelRatio() {
}
_recomputeOptions() {
const oldOptions = this.options;
const newOptions = this._computeInternalOptions();
if (!oldOptions) {
this.options = newOptions;
}
else {
const changeEvent = EditorConfiguration2.checkEquals(oldOptions, newOptions);
if (changeEvent === null) {
// nothing changed!
return;
}
this.options = newOptions;
this._onDidChangeFast.fire(changeEvent);
this._onDidChange.fire(changeEvent);
}
}
getRawOptions() {
return this._rawOptions;
}
_computeInternalOptions() {
const partialEnv = this._getEnvConfiguration();
const bareFontInfo = fontInfo_1.BareFontInfo.createFromValidatedSettings(this._validatedOptions, partialEnv.zoomLevel, partialEnv.pixelRatio, this.isSimpleWidget);
const env = {
memory: this._computeOptionsMemory,
outerWidth: partialEnv.outerWidth,
outerHeight: partialEnv.outerHeight,
fontInfo: this.readConfiguration(bareFontInfo),
extraEditorClassName: partialEnv.extraEditorClassName,
isDominatedByLongLines: this._isDominatedByLongLines,
viewLineCount: this._viewLineCount,
lineNumbersDigitCount: this._lineNumbersDigitCount,
emptySelectionClipboard: partialEnv.emptySelectionClipboard,
pixelRatio: partialEnv.pixelRatio,
tabFocusMode: exports.TabFocus.getTabFocusMode(),
accessibilitySupport: partialEnv.accessibilitySupport
};
return EditorConfiguration2.computeOptions(this._validatedOptions, env);
}
static _subsetEquals(base, subset) {
for (const key in subset) {
if (hasOwnProperty.call(subset, key)) {
const subsetValue = subset[key];
const baseValue = base[key];
if (baseValue === subsetValue) {
continue;
}
if (Array.isArray(baseValue) && Array.isArray(subsetValue)) {
if (!arrays.equals(baseValue, subsetValue)) {
return false;
}
continue;
}
if (baseValue && typeof baseValue === 'object' && subsetValue && typeof subsetValue === 'object') {
if (!this._subsetEquals(baseValue, subsetValue)) {
return false;
}
continue;
}
return false;
}
}
return true;
}
updateOptions(_newOptions) {
if (typeof _newOptions === 'undefined') {
return;
}
const newOptions = deepCloneAndMigrateOptions(_newOptions);
if (CommonEditorConfiguration._subsetEquals(this._rawOptions, newOptions)) {
return;
}
this._rawOptions = objects.mixin(this._rawOptions, newOptions || {});
this._readOptions = EditorConfiguration2.readOptions(this._rawOptions);
this._validatedOptions = EditorConfiguration2.validateOptions(this._readOptions);
this._recomputeOptions();
}
setIsDominatedByLongLines(isDominatedByLongLines) {
this._isDominatedByLongLines = isDominatedByLongLines;
this._recomputeOptions();
}
setMaxLineNumber(maxLineNumber) {
const lineNumbersDigitCount = CommonEditorConfiguration._digitCount(maxLineNumber);
if (this._lineNumbersDigitCount === lineNumbersDigitCount) {
return;
}
this._lineNumbersDigitCount = lineNumbersDigitCount;
this._recomputeOptions();
}
setViewLineCount(viewLineCount) {
if (this._viewLineCount === viewLineCount) {
return;
}
this._viewLineCount = viewLineCount;
this._recomputeOptions();
}
static _digitCount(n) {
let r = 0;
while (n) {
n = Math.floor(n / 10);
r++;
}
return r ? r : 1;
}
}
exports.CommonEditorConfiguration = CommonEditorConfiguration;
exports.editorConfigurationBaseNode = Object.freeze({
id: 'editor',
order: 5,
type: 'object',
title: nls.localize(0, null),
scope: 5 /* LANGUAGE_OVERRIDABLE */,
});
const configurationRegistry = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration);
const editorConfiguration = Object.assign(Object.assign({}, exports.editorConfigurationBaseNode), { properties: {
'editor.tabSize': {
type: 'number',
default: editorOptions_1.EDITOR_MODEL_DEFAULTS.tabSize,
minimum: 1,
markdownDescription: nls.localize(1, null)
},
// 'editor.indentSize': {
// 'anyOf': [
// {
// type: 'string',
// enum: ['tabSize']
// },
// {
// type: 'number',
// minimum: 1
// }
// ],
// default: 'tabSize',
// markdownDescription: nls.localize('indentSize', "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: editorOptions_1.EDITOR_MODEL_DEFAULTS.insertSpaces,
markdownDescription: nls.localize(2, null)
},
'editor.detectIndentation': {
type: 'boolean',
default: editorOptions_1.EDITOR_MODEL_DEFAULTS.detectIndentation,
markdownDescription: nls.localize(3, null)
},
'editor.trimAutoWhitespace': {
type: 'boolean',
default: editorOptions_1.EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
description: nls.localize(4, null)
},
'editor.largeFileOptimizations': {
type: 'boolean',
default: editorOptions_1.EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
description: nls.localize(5, null)
},
'editor.wordBasedSuggestions': {
type: 'boolean',
default: true,
description: nls.localize(6, null)
},
'editor.wordBasedSuggestionsMode': {
enum: ['currentDocument', 'matchingDocuments', 'allDocuments'],
default: 'matchingDocuments',
enumDescriptions: [
nls.localize(7, null),
nls.localize(8, null),
nls.localize(9, null)
],
description: nls.localize(10, null)
},
'editor.semanticHighlighting.enabled': {
enum: [true, false, 'configuredByTheme'],
enumDescriptions: [
nls.localize(11, null),
nls.localize(12, null),
nls.localize(13, null)
],
default: 'configuredByTheme',
description: nls.localize(14, null)
},
'editor.stablePeek': {
type: 'boolean',
default: false,
markdownDescription: nls.localize(15, null)
},
'editor.maxTokenizationLineLength': {
type: 'integer',
default: 20000,
description: nls.localize(16, null)
},
'diffEditor.maxComputationTime': {
type: 'number',
default: 5000,
description: nls.localize(17, null)
},
'diffEditor.renderSideBySide': {
type: 'boolean',
default: true,
description: nls.localize(18, null)
},
'diffEditor.ignoreTrimWhitespace': {
type: 'boolean',
default: true,
description: nls.localize(19, null)
},
'diffEditor.renderIndicators': {
type: 'boolean',
default: true,
description: nls.localize(20, null)
},
'diffEditor.codeLens': {
type: 'boolean',
default: false,
description: nls.localize(21, null)
},
'diffEditor.wordWrap': {
type: 'string',
enum: ['off', 'on', 'inherit'],
default: 'inherit',
markdownEnumDescriptions: [
nls.localize(22, null),
nls.localize(23, null),
nls.localize(24, null),
]
}
} });
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 (let key in schema) {
if (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);
}
exports.isEditorConfigurationKey = isEditorConfigurationKey;
function isDiffEditorConfigurationKey(key) {
const editorConfigurationKeys = getEditorConfigurationKeys();
return (editorConfigurationKeys[`diffEditor.${key}`] || false);
}
exports.isDiffEditorConfigurationKey = isDiffEditorConfigurationKey;
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[65/*vs/editor/browser/config/configuration*/], __M([0/*require*/,1/*exports*/,39/*vs/base/browser/browser*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,370/*vs/editor/browser/config/charWidthReader*/,214/*vs/editor/browser/config/elementSizeObserver*/,190/*vs/editor/common/config/commonEditorConfig*/,35/*vs/editor/common/config/editorOptions*/,168/*vs/editor/common/config/fontInfo*/]), function (require, exports, browser, event_1, lifecycle_1, platform, charWidthReader_1, elementSizeObserver_1, commonEditorConfig_1, editorOptions_1, fontInfo_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Configuration = exports.clearAllFontInfos = void 0;
class CSSBasedConfigurationCache {
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]);
}
}
function clearAllFontInfos() {
CSSBasedConfiguration.INSTANCE.clearCache();
}
exports.clearAllFontInfos = clearAllFontInfos;
class CSSBasedConfiguration extends lifecycle_1.Disposable {
constructor() {
super();
this._onDidChange = this._register(new event_1.Emitter());
this.onDidChange = this._onDidChange.event;
this._cache = new CSSBasedConfigurationCache();
this._evictUntrustedReadingsTimeout = -1;
}
dispose() {
if (this._evictUntrustedReadingsTimeout !== -1) {
clearTimeout(this._evictUntrustedReadingsTimeout);
this._evictUntrustedReadingsTimeout = -1;
}
super.dispose();
}
clearCache() {
this._cache = new CSSBasedConfigurationCache();
this._onDidChange.fire();
}
_writeToCache(item, value) {
this._cache.put(item, value);
if (!value.isTrusted && this._evictUntrustedReadingsTimeout === -1) {
// Try reading again after some time
this._evictUntrustedReadingsTimeout = setTimeout(() => {
this._evictUntrustedReadingsTimeout = -1;
this._evictUntrustedReadings();
}, 5000);
}
}
_evictUntrustedReadings() {
const values = this._cache.getValues();
let somethingRemoved = false;
for (const item of values) {
if (!item.isTrusted) {
somethingRemoved = true;
this._cache.remove(item);
}
}
if (somethingRemoved) {
this._onDidChange.fire();
}
}
readConfiguration(bareFontInfo) {
if (!this._cache.has(bareFontInfo)) {
let readConfig = CSSBasedConfiguration._actualReadConfiguration(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({
zoomLevel: browser.getZoomLevel(),
pixelRatio: browser.getPixelRatio(),
fontFamily: readConfig.fontFamily,
fontWeight: readConfig.fontWeight,
fontSize: readConfig.fontSize,
fontFeatureSettings: readConfig.fontFeatureSettings,
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(bareFontInfo, readConfig);
}
return this._cache.get(bareFontInfo);
}
static createRequest(chr, type, all, monospace) {
const result = new charWidthReader_1.CharWidthRequest(chr, type);
all.push(result);
if (monospace) {
monospace.push(result);
}
return result;
}
static _actualReadConfiguration(bareFontInfo) {
const all = [];
const monospace = [];
const typicalHalfwidthCharacter = this.createRequest('n', 0 /* Regular */, all, monospace);
const typicalFullwidthCharacter = this.createRequest('\uff4d', 0 /* Regular */, all, null);
const space = this.createRequest(' ', 0 /* Regular */, all, monospace);
const digit0 = this.createRequest('0', 0 /* Regular */, all, monospace);
const digit1 = this.createRequest('1', 0 /* Regular */, all, monospace);
const digit2 = this.createRequest('2', 0 /* Regular */, all, monospace);
const digit3 = this.createRequest('3', 0 /* Regular */, all, monospace);
const digit4 = this.createRequest('4', 0 /* Regular */, all, monospace);
const digit5 = this.createRequest('5', 0 /* Regular */, all, monospace);
const digit6 = this.createRequest('6', 0 /* Regular */, all, monospace);
const digit7 = this.createRequest('7', 0 /* Regular */, all, monospace);
const digit8 = this.createRequest('8', 0 /* Regular */, all, monospace);
const digit9 = this.createRequest('9', 0 /* Regular */, all, monospace);
// monospace test: used for whitespace rendering
const rightwardsArrow = this.createRequest('→', 0 /* Regular */, all, monospace);
const halfwidthRightwardsArrow = this.createRequest('→', 0 /* Regular */, all, null);
// U+00B7 - MIDDLE DOT
const middot = this.createRequest('·', 0 /* Regular */, all, monospace);
// U+2E31 - WORD SEPARATOR MIDDLE DOT
const wsmiddotWidth = this.createRequest(String.fromCharCode(0x2E31), 0 /* Regular */, all, null);
// monospace test: some characters
this.createRequest('|', 0 /* Regular */, all, monospace);
this.createRequest('/', 0 /* Regular */, all, monospace);
this.createRequest('-', 0 /* Regular */, all, monospace);
this.createRequest('_', 0 /* Regular */, all, monospace);
this.createRequest('i', 0 /* Regular */, all, monospace);
this.createRequest('l', 0 /* Regular */, all, monospace);
this.createRequest('m', 0 /* Regular */, all, monospace);
// monospace italic test
this.createRequest('|', 1 /* Italic */, all, monospace);
this.createRequest('_', 1 /* Italic */, all, monospace);
this.createRequest('i', 1 /* Italic */, all, monospace);
this.createRequest('l', 1 /* Italic */, all, monospace);
this.createRequest('m', 1 /* Italic */, all, monospace);
this.createRequest('n', 1 /* Italic */, all, monospace);
// monospace bold test
this.createRequest('|', 2 /* Bold */, all, monospace);
this.createRequest('_', 2 /* Bold */, all, monospace);
this.createRequest('i', 2 /* Bold */, all, monospace);
this.createRequest('l', 2 /* Bold */, all, monospace);
this.createRequest('m', 2 /* Bold */, all, monospace);
this.createRequest('n', 2 /* Bold */, all, monospace);
(0, charWidthReader_1.readCharWidths)(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;
}
// let's trust the zoom level only 2s after it was changed.
const canTrustBrowserZoomLevel = (browser.getTimeSinceLastZoomLevelChanged() > 2000);
return new fontInfo_1.FontInfo({
zoomLevel: browser.getZoomLevel(),
pixelRatio: browser.getPixelRatio(),
fontFamily: bareFontInfo.fontFamily,
fontWeight: bareFontInfo.fontWeight,
fontSize: bareFontInfo.fontSize,
fontFeatureSettings: bareFontInfo.fontFeatureSettings,
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
}, canTrustBrowserZoomLevel);
}
}
CSSBasedConfiguration.INSTANCE = new CSSBasedConfiguration();
class Configuration extends commonEditorConfig_1.CommonEditorConfiguration {
constructor(isSimpleWidget, options, referenceDomElement = null, accessibilityService) {
super(isSimpleWidget, options);
this.accessibilityService = accessibilityService;
this._elementSizeObserver = this._register(new elementSizeObserver_1.ElementSizeObserver(referenceDomElement, options.dimension, () => this._recomputeOptions()));
this._register(CSSBasedConfiguration.INSTANCE.onDidChange(() => this._recomputeOptions()));
if (this._validatedOptions.get(10 /* automaticLayout */)) {
this._elementSizeObserver.startObserving();
}
this._register(browser.onDidChangeZoomLevel(_ => this._recomputeOptions()));
this._register(this.accessibilityService.onDidChangeScreenReaderOptimized(() => this._recomputeOptions()));
this._recomputeOptions();
}
static applyFontInfoSlow(domNode, fontInfo) {
domNode.style.fontFamily = fontInfo.getMassagedFontFamily();
domNode.style.fontWeight = fontInfo.fontWeight;
domNode.style.fontSize = fontInfo.fontSize + 'px';
domNode.style.fontFeatureSettings = fontInfo.fontFeatureSettings;
domNode.style.lineHeight = fontInfo.lineHeight + 'px';
domNode.style.letterSpacing = fontInfo.letterSpacing + 'px';
}
static applyFontInfo(domNode, fontInfo) {
domNode.setFontFamily(fontInfo.getMassagedFontFamily());
domNode.setFontWeight(fontInfo.fontWeight);
domNode.setFontSize(fontInfo.fontSize);
domNode.setFontFeatureSettings(fontInfo.fontFeatureSettings);
domNode.setLineHeight(fontInfo.lineHeight);
domNode.setLetterSpacing(fontInfo.letterSpacing);
}
observeReferenceElement(dimension) {
this._elementSizeObserver.observe(dimension);
}
updatePixelRatio() {
this._recomputeOptions();
}
static _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 ';
}
if (platform.isMacintosh) {
extra += 'mac ';
}
return extra;
}
_getEnvConfiguration() {
return {
extraEditorClassName: Configuration._getExtraEditorClassName(),
outerWidth: this._elementSizeObserver.getWidth(),
outerHeight: this._elementSizeObserver.getHeight(),
emptySelectionClipboard: browser.isWebKit || browser.isFirefox,
pixelRatio: browser.getPixelRatio(),
zoomLevel: browser.getZoomLevel(),
accessibilitySupport: (this.accessibilityService.isScreenReaderOptimized()
? 2 /* Enabled */
: this.accessibilityService.getAccessibilitySupport())
};
}
readConfiguration(bareFontInfo) {
return CSSBasedConfiguration.INSTANCE.readConfiguration(bareFontInfo);
}
}
exports.Configuration = Configuration;
});
/*---------------------------------------------------------------------------------------------
* 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/browser/view/domLineBreaksComputer*/], __M([0/*require*/,1/*exports*/,83/*vs/editor/common/core/stringBuilder*/,8/*vs/base/common/strings*/,65/*vs/editor/browser/config/configuration*/,62/*vs/editor/common/viewModel/viewModel*/,96/*vs/editor/common/model/textModelEvents*/]), function (require, exports, stringBuilder_1, strings, configuration_1, viewModel_1, textModelEvents_1) {
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DOMLineBreaksComputerFactory = void 0;
const ttPolicy = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('domLineBreaksComputer', { createHTML: value => value });
class DOMLineBreaksComputerFactory {
static create() {
return new DOMLineBreaksComputerFactory();
}
constructor() {
}
createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent) {
tabSize = tabSize | 0; //@perf
wrappingColumn = +wrappingColumn; //@perf
let requests = [];
let injectedTexts = [];
return {
addRequest: (lineText, injectedText, previousLineBreakData) => {
requests.push(lineText);
injectedTexts.push(injectedText);
},
finalize: () => {
return createLineBreaks(requests, fontInfo, tabSize, wrappingColumn, wrappingIndent, injectedTexts);
}
};
}
}
exports.DOMLineBreaksComputerFactory = DOMLineBreaksComputerFactory;
function createLineBreaks(requests, fontInfo, tabSize, firstLineBreakColumn, wrappingIndent, injectedTextsPerLine) {
var _a;
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 viewModel_1.LineBreakData([lineText.length], [], 0, injectionOffsets, injectionOptions);
}
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);
// Cannot respect WrappingIndent.Indent and WrappingIndent.DeepIndent because that would require
// two dom layouts, in order to first set the width of the first line, and then set the width of the wrapped lines
if (wrappingIndent === 2 /* Indent */ || wrappingIndent === 3 /* DeepIndent */) {
wrappingIndent = 1 /* Same */;
}
const containerDomNode = document.createElement('div');
configuration_1.Configuration.applyFontInfoSlow(containerDomNode, fontInfo);
const sb = (0, stringBuilder_1.createStringBuilder)(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 /* 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 /* 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);
firstNonWhitespaceIndices[i] = firstNonWhitespaceIndex;
wrappedTextIndentLengths[i] = wrappedTextIndentLength;
renderLineContents[i] = renderLineContent;
allCharOffsets[i] = tmp[0];
allVisibleColumns[i] = tmp[1];
}
const html = sb.build();
const trustedhtml = (_a = ttPolicy === null || ttPolicy === void 0 ? void 0 : ttPolicy.createHTML(html)) !== null && _a !== void 0 ? _a : html;
containerDomNode.innerHTML = trustedhtml;
containerDomNode.style.position = 'absolute';
containerDomNode.style.top = '10000';
containerDomNode.style.wordWrap = 'break-word';
document.body.appendChild(containerDomNode);
let range = document.createRange();
const lineDomNodes = Array.prototype.slice.call(containerDomNode.children, 0);
let 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];
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 viewModel_1.LineBreakData(breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength, injectionOffsets, injectionOptions);
}
document.body.removeChild(containerDomNode);
return result;
}
function renderLine(lineContent, initialVisibleColumn, tabSize, width, sb) {
sb.appendASCIIString('<div style="width:');
sb.appendASCIIString(String(width));
sb.appendASCIIString('px;">');
// if (containsRTL) {
// sb.appendASCIIString('" dir="ltr');
// }
const len = lineContent.length;
let visibleColumn = initialVisibleColumn;
let charOffset = 0;
let charOffsets = [];
let visibleColumns = [];
let nextCharCode = (0 < len ? lineContent.charCodeAt(0) : 0 /* Null */);
sb.appendASCIIString('<span>');
for (let charIndex = 0; charIndex < len; charIndex++) {
if (charIndex !== 0 && charIndex % 16384 /* SPAN_MODULO_LIMIT */ === 0) {
sb.appendASCIIString('</span><span>');
}
charOffsets[charIndex] = charOffset;
visibleColumns[charIndex] = visibleColumn;
const charCode = nextCharCode;
nextCharCode = (charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0 /* Null */);
let producedCharacters = 1;
let charWidth = 1;
switch (charCode) {
case 9 /* Tab */:
producedCharacters = (tabSize - (visibleColumn % tabSize));
charWidth = producedCharacters;
for (let space = 1; space <= producedCharacters; space++) {
if (space < producedCharacters) {
sb.write1(0xA0); // &nbsp;
}
else {
sb.appendASCII(32 /* Space */);
}
}
break;
case 32 /* Space */:
if (nextCharCode === 32 /* Space */) {
sb.write1(0xA0); // &nbsp;
}
else {
sb.appendASCII(32 /* Space */);
}
break;
case 60 /* LessThan */:
sb.appendASCIIString('&lt;');
break;
case 62 /* GreaterThan */:
sb.appendASCIIString('&gt;');
break;
case 38 /* Ampersand */:
sb.appendASCIIString('&amp;');
break;
case 0 /* Null */:
sb.appendASCIIString('&#00;');
break;
case 65279 /* UTF8_BOM */:
case 8232 /* LINE_SEPARATOR */:
case 8233 /* PARAGRAPH_SEPARATOR */:
case 133 /* NEXT_LINE */:
sb.write1(0xFFFD);
break;
default:
if (strings.isFullWidthCharacter(charCode)) {
charWidth++;
}
if (charCode < 32) {
sb.write1(9216 + charCode);
}
else {
sb.write1(charCode);
}
}
charOffset += producedCharacters;
visibleColumn += charWidth;
}
sb.appendASCIIString('</span>');
charOffsets[lineContent.length] = charOffset;
visibleColumns[lineContent.length] = visibleColumn;
sb.appendASCIIString('</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 /* SPAN_MODULO_LIMIT */) | 0].firstChild, startOffset % 16384 /* SPAN_MODULO_LIMIT */);
range.setEnd(spans[(endOffset / 16384 /* SPAN_MODULO_LIMIT */) | 0].firstChild, endOffset % 16384 /* 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[578/*vs/editor/browser/view/viewOverlays*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,65/*vs/editor/browser/config/configuration*/,170/*vs/editor/browser/view/viewLayer*/,47/*vs/editor/browser/view/viewPart*/]), function (require, exports, fastDomNode_1, configuration_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._visibleLines = new viewLayer_1.VisibleLinesCollection(this);
this.domNode = this._visibleLines.domNode;
this._dynamicOverlays = [];
this._isFocused = false;
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;
}
// ---- begin IVisibleLinesHost
createVisibleLine() {
return new ViewOverlayLine(this._context.configuration, this._dynamicOverlays);
}
// ---- end IVisibleLinesHost
addDynamicOverlay(overlay) {
this._dynamicOverlays.push(overlay);
}
// ----- event handlers
onConfigurationChanged(e) {
this._visibleLines.onConfigurationChanged(e);
const startLineNumber = this._visibleLines.getStartLineNumber();
const endLineNumber = this._visibleLines.getEndLineNumber();
for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
const line = this._visibleLines.getVisibleLine(lineNumber);
line.onConfigurationChanged(e);
}
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(configuration, dynamicOverlays) {
this._configuration = configuration;
this._lineHeight = this._configuration.options.get(57 /* lineHeight */);
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
}
onConfigurationChanged(e) {
this._lineHeight = this._configuration.options.get(57 /* lineHeight */);
}
renderLine(lineNumber, deltaTop, 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.appendASCIIString('<div style="position:absolute;top:');
sb.appendASCIIString(String(deltaTop));
sb.appendASCIIString('px;width:100%;height:');
sb.appendASCIIString(String(this._lineHeight));
sb.appendASCIIString('px;">');
sb.appendASCIIString(result);
sb.appendASCIIString('</div>');
return true;
}
layoutLine(lineNumber, deltaTop) {
if (this._domNode) {
this._domNode.setTop(deltaTop);
this._domNode.setHeight(this._lineHeight);
}
}
}
exports.ViewOverlayLine = ViewOverlayLine;
class ContentViewOverlays extends ViewOverlays {
constructor(context) {
super(context);
const options = this._context.configuration.options;
const layoutInfo = options.get(129 /* layoutInfo */);
this._contentWidth = layoutInfo.contentWidth;
this.domNode.setHeight(0);
}
// --- begin event handlers
onConfigurationChanged(e) {
const options = this._context.configuration.options;
const layoutInfo = options.get(129 /* 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(129 /* layoutInfo */);
this._contentLeft = layoutInfo.contentLeft;
this.domNode.setClassName('margin-view-overlays');
this.domNode.setWidth(1);
configuration_1.Configuration.applyFontInfo(this.domNode, options.get(41 /* fontInfo */));
}
onConfigurationChanged(e) {
const options = this._context.configuration.options;
configuration_1.Configuration.applyFontInfo(this.domNode, options.get(41 /* fontInfo */));
const layoutInfo = options.get(129 /* 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[579/*vs/editor/browser/viewParts/viewCursors/viewCursor*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,8/*vs/base/common/strings*/,65/*vs/editor/browser/config/configuration*/,35/*vs/editor/common/config/editorOptions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,131/*vs/base/browser/ui/mouseCursor/mouseCursor*/]), function (require, exports, dom, fastDomNode_1, strings, configuration_1, editorOptions_1, position_1, range_1, mouseCursor_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ViewCursor = void 0;
class ViewCursorRenderData {
constructor(top, left, width, height, textContent, textContentClassName) {
this.top = top;
this.left = left;
this.width = width;
this.height = height;
this.textContent = textContent;
this.textContentClassName = textContentClassName;
}
}
class ViewCursor {
constructor(context) {
this._context = context;
const options = this._context.configuration.options;
const fontInfo = options.get(41 /* fontInfo */);
this._cursorStyle = options.get(22 /* cursorStyle */);
this._lineHeight = options.get(57 /* lineHeight */);
this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
this._lineCursorWidth = Math.min(options.get(25 /* 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);
configuration_1.Configuration.applyFontInfo(this._domNode, fontInfo);
this._domNode.setDisplay('none');
this._position = new position_1.Position(1, 1);
this._lastRenderedContent = '';
this._renderData = null;
}
getDomNode() {
return this._domNode;
}
getPosition() {
return this._position;
}
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(41 /* fontInfo */);
this._cursorStyle = options.get(22 /* cursorStyle */);
this._lineHeight = options.get(57 /* lineHeight */);
this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
this._lineCursorWidth = Math.min(options.get(25 /* cursorWidth */), this._typicalHalfwidthCharacterWidth);
configuration_1.Configuration.applyFontInfo(this._domNode, fontInfo);
return true;
}
onCursorPositionChanged(position) {
this._position = position;
return true;
}
_prepareRender(ctx) {
let textContent = '';
if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Line || this._cursorStyle === editorOptions_1.TextEditorCursorStyle.LineThin) {
const visibleRange = ctx.visibleRangeForPosition(this._position);
if (!visibleRange || visibleRange.outsideRenderedLine) {
// Outside viewport
return null;
}
let width;
if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Line) {
width = dom.computeScreenAwareSize(this._lineCursorWidth > 0 ? this._lineCursorWidth : 2);
if (width > 2) {
const lineContent = this._context.model.getLineContent(this._position.lineNumber);
const nextCharLength = strings.nextCharLength(lineContent, this._position.column - 1);
textContent = lineContent.substr(this._position.column - 1, nextCharLength);
}
}
else {
width = dom.computeScreenAwareSize(1);
}
let left = visibleRange.left;
if (width >= 2 && left >= 1) {
// try to center cursor
left -= 1;
}
const top = ctx.getVerticalOffsetForLineNumber(this._position.lineNumber) - ctx.bigNumbersDelta;
return new ViewCursorRenderData(top, left, width, this._lineHeight, textContent, '');
}
const lineContent = this._context.model.getLineContent(this._position.lineNumber);
const nextCharLength = strings.nextCharLength(lineContent, this._position.column - 1);
const visibleRangeForCharacter = ctx.linesVisibleRangesForRange(new range_1.Range(this._position.lineNumber, this._position.column, this._position.lineNumber, this._position.column + nextCharLength), 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 = range.width < 1 ? this._typicalHalfwidthCharacterWidth : range.width;
let textContentClassName = '';
if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Block) {
const lineData = this._context.model.getViewLineData(this._position.lineNumber);
textContent = lineContent.substr(this._position.column - 1, nextCharLength);
const tokenIndex = lineData.tokens.findTokenIndexAtOffset(this._position.column - 1);
textContentClassName = lineData.tokens.getClassName(tokenIndex);
}
let top = ctx.getVerticalOffsetForLineNumber(this._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, width, height, textContent, textContentClassName);
}
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 ${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.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[580/*vs/editor/common/services/languagesRegistry*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,106/*vs/base/common/mime*/,8/*vs/base/common/strings*/,18/*vs/editor/common/modes*/,146/*vs/editor/common/modes/modesRegistry*/,77/*vs/editor/common/modes/nullMode*/,98/*vs/platform/configuration/common/configurationRegistry*/,32/*vs/platform/registry/common/platform*/]), function (require, exports, errors_1, event_1, lifecycle_1, mime, strings, modes_1, modesRegistry_1, nullMode_1, configurationRegistry_1, platform_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LanguagesRegistry = void 0;
const hasOwnProperty = Object.prototype.hasOwnProperty;
class LanguagesRegistry extends lifecycle_1.Disposable {
constructor(useModesRegistry = true, warnOnOverwrite = false) {
super();
this._onDidChange = this._register(new event_1.Emitter());
this.onDidChange = this._onDidChange.event;
this._warnOnOverwrite = warnOnOverwrite;
this._nextLanguageId2 = 1;
this._languageIdToLanguage = [];
this._languageToLanguageId = Object.create(null);
this._languages = {};
this._mimeTypesMap = {};
this._nameMap = {};
this._lowercaseNameMap = {};
if (useModesRegistry) {
this._initializeFromRegistry();
this._register(modesRegistry_1.ModesRegistry.onDidChangeLanguages((m) => this._initializeFromRegistry()));
}
}
_initializeFromRegistry() {
this._languages = {};
this._mimeTypesMap = {};
this._nameMap = {};
this._lowercaseNameMap = {};
const desc = modesRegistry_1.ModesRegistry.getLanguages();
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) => {
let 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(modesRegistry_1.ModesRegistry.getLanguages().map(language => language.id));
this._onDidChange.fire();
}
_getLanguageId(language) {
if (this._languageToLanguageId[language]) {
return this._languageToLanguageId[language];
}
const languageId = this._nextLanguageId2++;
this._languageIdToLanguage[languageId] = language;
this._languageToLanguageId[language] = languageId;
return languageId;
}
_registerLanguage(lang) {
const langId = lang.id;
let resolvedLanguage;
if (hasOwnProperty.call(this._languages, langId)) {
resolvedLanguage = this._languages[langId];
}
else {
const languageId = this._getLanguageId(langId);
resolvedLanguage = {
identifier: new modes_1.LanguageIdentifier(langId, languageId),
name: null,
mimetypes: [],
aliases: [],
extensions: [],
filenames: [],
configurationFiles: []
};
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 (let extension of lang.extensions) {
mime.registerTextMime({ id: langId, mime: primaryMime, extension: extension }, this._warnOnOverwrite);
}
}
if (Array.isArray(lang.filenames)) {
for (let filename of lang.filenames) {
mime.registerTextMime({ id: langId, mime: primaryMime, filename: filename }, this._warnOnOverwrite);
resolvedLanguage.filenames.push(filename);
}
}
if (Array.isArray(lang.filenamePatterns)) {
for (let filenamePattern of lang.filenamePatterns) {
mime.registerTextMime({ 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 {
let firstLineRegex = new RegExp(firstLineRegexStr);
if (!strings.regExpLeadsToEndlessLoop(firstLineRegex)) {
mime.registerTextMime({ id: langId, mime: primaryMime, firstline: firstLineRegex }, this._warnOnOverwrite);
}
}
catch (err) {
// Most likely, the regex was bad
(0, errors_1.onUnexpectedError)(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);
}
}
let containsAliases = (langAliases !== null && langAliases.length > 0);
if (containsAliases && langAliases[0] === null) {
// signal that this language should not get a name
}
else {
let bestName = (containsAliases ? langAliases[0] : null) || langId;
if (containsAliases || !resolvedLanguage.name) {
resolvedLanguage.name = bestName;
}
}
if (lang.configuration) {
resolvedLanguage.configurationFiles.push(lang.configuration);
}
}
isRegisteredMode(mimetypeOrModeId) {
// Is this a known mime type ?
if (hasOwnProperty.call(this._mimeTypesMap, mimetypeOrModeId)) {
return true;
}
// Is this a known mode id ?
return hasOwnProperty.call(this._languages, mimetypeOrModeId);
}
getModeIdForLanguageNameLowercase(languageNameLower) {
if (!hasOwnProperty.call(this._lowercaseNameMap, languageNameLower)) {
return null;
}
return this._lowercaseNameMap[languageNameLower].language;
}
extractModeIds(commaSeparatedMimetypesOrCommaSeparatedIds) {
if (!commaSeparatedMimetypesOrCommaSeparatedIds) {
return [];
}
return (commaSeparatedMimetypesOrCommaSeparatedIds.
split(',').
map((mimeTypeOrId) => mimeTypeOrId.trim()).
map((mimeTypeOrId) => {
if (hasOwnProperty.call(this._mimeTypesMap, mimeTypeOrId)) {
return this._mimeTypesMap[mimeTypeOrId].language;
}
return mimeTypeOrId;
}).
filter((modeId) => {
return hasOwnProperty.call(this._languages, modeId);
}));
}
getLanguageIdentifier(_modeId) {
if (_modeId === nullMode_1.NULL_MODE_ID || _modeId === 0 /* Null */) {
return nullMode_1.NULL_LANGUAGE_IDENTIFIER;
}
let modeId;
if (typeof _modeId === 'string') {
modeId = _modeId;
}
else {
modeId = this._languageIdToLanguage[_modeId];
if (!modeId) {
return null;
}
}
if (!hasOwnProperty.call(this._languages, modeId)) {
return null;
}
return this._languages[modeId].identifier;
}
getModeIdsFromFilepathOrFirstLine(resource, firstLine) {
if (!resource && !firstLine) {
return [];
}
let mimeTypes = mime.guessMimeTypes(resource, firstLine);
return this.extractModeIds(mimeTypes.join(','));
}
}
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[581/*vs/editor/common/services/modeServiceImpl*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,381/*vs/editor/common/modes/abstractMode*/,77/*vs/editor/common/modes/nullMode*/,580/*vs/editor/common/services/languagesRegistry*/,19/*vs/base/common/arrays*/]), function (require, exports, event_1, lifecycle_1, abstractMode_1, nullMode_1, languagesRegistry_1, arrays_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModeServiceImpl = void 0;
class LanguageSelection {
constructor(onLanguagesMaybeChanged, selector) {
this._selector = selector;
this.languageIdentifier = this._selector();
let listener;
this._onDidChange = new event_1.Emitter({
onFirstListenerAdd: () => {
listener = onLanguagesMaybeChanged(() => this._evaluate());
},
onLastListenerRemove: () => {
listener.dispose();
}
});
this.onDidChange = this._onDidChange.event;
}
_evaluate() {
let languageIdentifier = this._selector();
if (languageIdentifier.id === this.languageIdentifier.id) {
// no change
return;
}
this.languageIdentifier = languageIdentifier;
this._onDidChange.fire(this.languageIdentifier);
}
}
class ModeServiceImpl extends lifecycle_1.Disposable {
constructor(warnOnOverwrite = false) {
super();
this._onDidCreateMode = this._register(new event_1.Emitter());
this.onDidCreateMode = this._onDidCreateMode.event;
this._onLanguagesMaybeChanged = this._register(new event_1.Emitter({ leakWarningThreshold: 200 /* https://github.com/microsoft/vscode/issues/119968 */ }));
this.onLanguagesMaybeChanged = this._onLanguagesMaybeChanged.event;
this._instantiatedModes = {};
this._registry = this._register(new languagesRegistry_1.LanguagesRegistry(true, warnOnOverwrite));
this._register(this._registry.onDidChange(() => this._onLanguagesMaybeChanged.fire()));
}
isRegisteredMode(mimetypeOrModeId) {
return this._registry.isRegisteredMode(mimetypeOrModeId);
}
getModeIdForLanguageName(alias) {
return this._registry.getModeIdForLanguageNameLowercase(alias);
}
getModeIdByFilepathOrFirstLine(resource, firstLine) {
const modeIds = this._registry.getModeIdsFromFilepathOrFirstLine(resource, firstLine);
return (0, arrays_1.firstOrDefault)(modeIds, null);
}
getModeId(commaSeparatedMimetypesOrCommaSeparatedIds) {
const modeIds = this._registry.extractModeIds(commaSeparatedMimetypesOrCommaSeparatedIds);
return (0, arrays_1.firstOrDefault)(modeIds, null);
}
getLanguageIdentifier(modeId) {
return this._registry.getLanguageIdentifier(modeId);
}
// --- instantiation
create(commaSeparatedMimetypesOrCommaSeparatedIds) {
return new LanguageSelection(this.onLanguagesMaybeChanged, () => {
const modeId = this.getModeId(commaSeparatedMimetypesOrCommaSeparatedIds);
return this._createModeAndGetLanguageIdentifier(modeId);
});
}
createByFilepathOrFirstLine(resource, firstLine) {
return new LanguageSelection(this.onLanguagesMaybeChanged, () => {
const modeId = this.getModeIdByFilepathOrFirstLine(resource, firstLine);
return this._createModeAndGetLanguageIdentifier(modeId);
});
}
_createModeAndGetLanguageIdentifier(modeId) {
// Fall back to plain text if no mode was found
const languageIdentifier = this.getLanguageIdentifier(modeId || 'plaintext') || nullMode_1.NULL_LANGUAGE_IDENTIFIER;
this._getOrCreateMode(languageIdentifier.language);
return languageIdentifier;
}
triggerMode(commaSeparatedMimetypesOrCommaSeparatedIds) {
const modeId = this.getModeId(commaSeparatedMimetypesOrCommaSeparatedIds);
// Fall back to plain text if no mode was found
this._getOrCreateMode(modeId || 'plaintext');
}
_getOrCreateMode(modeId) {
if (!this._instantiatedModes.hasOwnProperty(modeId)) {
let languageIdentifier = this.getLanguageIdentifier(modeId) || nullMode_1.NULL_LANGUAGE_IDENTIFIER;
this._instantiatedModes[modeId] = new abstractMode_1.FrankensteinMode(languageIdentifier);
this._onDidCreateMode.fire(this._instantiatedModes[modeId]);
}
return this._instantiatedModes[modeId];
}
}
exports.ModeServiceImpl = ModeServiceImpl;
});
define(__m[38/*vs/platform/configuration/common/configuration*/], __M([0/*require*/,1/*exports*/,32/*vs/platform/registry/common/platform*/,9/*vs/platform/instantiation/common/instantiation*/,98/*vs/platform/configuration/common/configurationRegistry*/]), function (require, exports, platform_1, instantiation_1, configurationRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDefaultValues = exports.getConfigurationKeys = exports.getConfigurationValue = exports.removeFromValueTree = exports.addToValueTree = exports.toValuesTree = exports.IConfigurationService = void 0;
exports.IConfigurationService = (0, instantiation_1.createDecorator)('configurationService');
function toValuesTree(properties, conflictReporter) {
const root = Object.create(null);
for (let key in properties) {
addToValueTree(root, key, properties[key], conflictReporter);
}
return root;
}
exports.toValuesTree = toValuesTree;
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++) {
let s = segments[i];
let obj = curr[s];
switch (typeof obj) {
case 'undefined':
obj = curr[s] = Object.create(null);
break;
case 'object':
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)}`);
}
}
exports.addToValueTree = addToValueTree;
function removeFromValueTree(valueTree, key) {
const segments = key.split('.');
doRemoveFromValueTree(valueTree, segments);
}
exports.removeFromValueTree = removeFromValueTree;
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;
}
exports.getConfigurationValue = getConfigurationValue;
function getConfigurationKeys() {
const properties = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).getConfigurationProperties();
return Object.keys(properties);
}
exports.getConfigurationKeys = getConfigurationKeys;
function getDefaultValues() {
const valueTreeRoot = Object.create(null);
const properties = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).getConfigurationProperties();
for (let key in properties) {
let value = properties[key].default;
addToValueTree(valueTreeRoot, key, value, message => console.error(`Conflict in default settings: ${message}`));
}
return valueTreeRoot;
}
exports.getDefaultValues = getDefaultValues;
});
/*---------------------------------------------------------------------------------------------
* 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/platform/accessibility/common/accessibilityService*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,64/*vs/platform/accessibility/common/accessibility*/,6/*vs/base/common/event*/,16/*vs/platform/contextkey/common/contextkey*/,38/*vs/platform/configuration/common/configuration*/]), function (require, exports, lifecycle_1, accessibility_1, event_1, contextkey_1, configuration_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AccessibilityService = void 0;
let AccessibilityService = class AccessibilityService extends lifecycle_1.Disposable {
constructor(_contextKeyService, _configurationService) {
super();
this._contextKeyService = _contextKeyService;
this._configurationService = _configurationService;
this._accessibilitySupport = 0 /* Unknown */;
this._onDidChangeScreenReaderOptimized = 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();
}
}));
updateContextKey();
this.onDidChangeScreenReaderOptimized(() => updateContextKey());
}
get onDidChangeScreenReaderOptimized() {
return this._onDidChangeScreenReaderOptimized.event;
}
isScreenReaderOptimized() {
const config = this._configurationService.getValue('editor.accessibilitySupport');
return config === 'on' || (config === 'auto' && this._accessibilitySupport === 2 /* Enabled */);
}
getAccessibilitySupport() {
return this._accessibilitySupport;
}
};
AccessibilityService = __decorate([
__param(0, contextkey_1.IContextKeyService),
__param(1, configuration_1.IConfigurationService)
], AccessibilityService);
exports.AccessibilityService = AccessibilityService;
});
define(__m[583/*vs/platform/configuration/common/configurationModels*/], __M([0/*require*/,1/*exports*/,49/*vs/base/common/map*/,19/*vs/base/common/arrays*/,20/*vs/base/common/types*/,42/*vs/base/common/objects*/,24/*vs/base/common/uri*/,98/*vs/platform/configuration/common/configurationRegistry*/,38/*vs/platform/configuration/common/configuration*/]), function (require, exports, map_1, arrays, types, objects, uri_1, configurationRegistry_1, configuration_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConfigurationChangeEvent = exports.Configuration = exports.DefaultConfigurationModel = exports.ConfigurationModel = void 0;
class ConfigurationModel {
constructor(_contents = {}, _keys = [], _overrides = []) {
this._contents = _contents;
this._keys = _keys;
this._overrides = _overrides;
this.isFrozen = false;
}
get contents() {
return this.checkAndFreeze(this._contents);
}
get overrides() {
return this.checkAndFreeze(this._overrides);
}
get keys() {
return this.checkAndFreeze(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;
}
override(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;
}
let contents = {};
for (const key of arrays.distinct([...Object.keys(this.contents), ...Object.keys(overrideContents)])) {
let contentsForKey = this.contents[key];
let 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);
}
merge(...others) {
const contents = objects.deepClone(this.contents);
const overrides = objects.deepClone(this.overrides);
const keys = [...this.keys];
for (const other of others) {
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);
}
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);
}
freeze() {
this.isFrozen = true;
return this;
}
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]);
}
}
checkAndFreeze(data) {
if (this.isFrozen && !Object.isFrozen(data)) {
return objects.deepFreeze(data);
}
return data;
}
getContentsForOverrideIdentifer(identifier) {
for (const override of this.overrides) {
if (override.identifiers.indexOf(identifier) !== -1) {
return override.contents;
}
}
return null;
}
toJSON() {
return {
contents: this.contents,
overrides: this.overrides,
keys: this.keys
};
}
// Update methods
setValue(key, value) {
this.addKey(key);
(0, configuration_1.addToValueTree)(this.contents, key, value, e => { throw new Error(e); });
}
removeValue(key) {
if (this.removeKey(key)) {
(0, configuration_1.removeFromValueTree)(this.contents, key);
}
}
addKey(key) {
let index = this.keys.length;
for (let i = 0; i < index; i++) {
if (key.indexOf(this.keys[i]) === 0) {
index = i;
}
}
this.keys.splice(index, 1, key);
}
removeKey(key) {
let index = this.keys.indexOf(key);
if (index !== -1) {
this.keys.splice(index, 1);
return true;
}
return false;
}
}
exports.ConfigurationModel = ConfigurationModel;
class DefaultConfigurationModel extends ConfigurationModel {
constructor() {
const contents = (0, configuration_1.getDefaultValues)();
const keys = (0, configuration_1.getConfigurationKeys)();
const overrides = [];
for (const key of Object.keys(contents)) {
if (configurationRegistry_1.OVERRIDE_PROPERTY_PATTERN.test(key)) {
overrides.push({
identifiers: [(0, configurationRegistry_1.overrideIdentifierFromKey)(key).trim()],
keys: Object.keys(contents[key]),
contents: (0, configuration_1.toValuesTree)(contents[key], message => console.error(`Conflict in default settings file: ${message}`)),
});
}
}
super(contents, keys, overrides);
}
}
exports.DefaultConfigurationModel = DefaultConfigurationModel;
class Configuration {
constructor(_defaultConfiguration, _localUserConfiguration, _remoteUserConfiguration = new ConfigurationModel(), _workspaceConfiguration = new ConfigurationModel(), _folderConfigurations = new map_1.ResourceMap(), _memoryConfiguration = new ConfigurationModel(), _memoryConfigurationByResource = new map_1.ResourceMap(), _freeze = true) {
this._defaultConfiguration = _defaultConfiguration;
this._localUserConfiguration = _localUserConfiguration;
this._remoteUserConfiguration = _remoteUserConfiguration;
this._workspaceConfiguration = _workspaceConfiguration;
this._folderConfigurations = _folderConfigurations;
this._memoryConfiguration = _memoryConfiguration;
this._memoryConfigurationByResource = _memoryConfigurationByResource;
this._freeze = _freeze;
this._workspaceConsolidatedConfiguration = null;
this._foldersConsolidatedConfigurations = new map_1.ResourceMap();
this._userConfiguration = null;
}
getValue(section, overrides, workspace) {
const consolidateConfigurationModel = this.getConsolidateConfigurationModel(overrides, workspace);
return consolidateConfigurationModel.getValue(section);
}
updateValue(key, value, overrides = {}) {
let memoryConfiguration;
if (overrides.resource) {
memoryConfiguration = this._memoryConfigurationByResource.get(overrides.resource);
if (!memoryConfiguration) {
memoryConfiguration = new ConfigurationModel();
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;
}
}
get userConfiguration() {
if (!this._userConfiguration) {
this._userConfiguration = this._remoteUserConfiguration.isEmpty() ? this._localUserConfiguration : this._localUserConfiguration.merge(this._remoteUserConfiguration);
if (this._freeze) {
this._userConfiguration.freeze();
}
}
return this._userConfiguration;
}
getConsolidateConfigurationModel(overrides, workspace) {
let configurationModel = this.getConsolidatedConfigurationModelForResource(overrides, workspace);
return overrides.overrideIdentifier ? configurationModel.override(overrides.overrideIdentifier) : 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.userConfiguration, this._workspaceConfiguration, this._memoryConfiguration);
if (this._freeze) {
this._workspaceConfiguration = this._workspaceConfiguration.freeze();
}
}
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);
if (this._freeze) {
folderConsolidatedConfiguration = folderConsolidatedConfiguration.freeze();
}
this._foldersConsolidatedConfigurations.set(folder, folderConsolidatedConfiguration);
}
else {
folderConsolidatedConfiguration = workspaceConsolidateConfiguration;
}
}
return folderConsolidatedConfiguration;
}
toData() {
return {
defaults: {
contents: this._defaultConfiguration.contents,
overrides: this._defaultConfiguration.overrides,
keys: this._defaultConfiguration.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) {
const defaultConfiguration = this.parseConfigurationModel(data.defaults);
const userConfiguration = this.parseConfigurationModel(data.user);
const workspaceConfiguration = this.parseConfigurationModel(data.workspace);
const folders = data.folders.reduce((result, value) => {
result.set(uri_1.URI.revive(value[0]), this.parseConfigurationModel(value[1]));
return result;
}, new map_1.ResourceMap());
return new Configuration(defaultConfiguration, userConfiguration, new ConfigurationModel(), workspaceConfiguration, folders, new ConfigurationModel(), new map_1.ResourceMap(), false);
}
static parseConfigurationModel(model) {
return new ConfigurationModel(model.contents, model.keys, model.overrides).freeze();
}
}
exports.Configuration = Configuration;
class ConfigurationChangeEvent {
constructor(change, previous, currentConfiguraiton, currentWorkspace) {
this.change = change;
this.previous = previous;
this.currentConfiguraiton = currentConfiguraiton;
this.currentWorkspace = currentWorkspace;
this._previousConfiguration = undefined;
const keysSet = new Set();
change.keys.forEach(key => keysSet.add(key));
change.overrides.forEach(([, keys]) => keys.forEach(key => keysSet.add(key)));
this.affectedKeys = [...keysSet.values()];
const configurationModel = new ConfigurationModel();
this.affectedKeys.forEach(key => configurationModel.setValue(key, {}));
this.affectedKeysTree = configurationModel.contents;
}
get previousConfiguration() {
if (!this._previousConfiguration && this.previous) {
this._previousConfiguration = Configuration.parse(this.previous.data);
}
return this._previousConfiguration;
}
affectsConfiguration(section, overrides) {
var _a;
if (this.doesAffectedKeysTreeContains(this.affectedKeysTree, section)) {
if (overrides) {
const value1 = this.previousConfiguration ? this.previousConfiguration.getValue(section, overrides, (_a = this.previous) === null || _a === void 0 ? void 0 : _a.workspace) : undefined;
const value2 = this.currentConfiguraiton.getValue(section, overrides, this.currentWorkspace);
return !objects.equals(value1, value2);
}
return true;
}
return false;
}
doesAffectedKeysTreeContains(affectedKeysTree, section) {
let requestedTree = (0, configuration_1.toValuesTree)({ [section]: true }, () => { });
let key;
while (typeof requestedTree === 'object' && (key = Object.keys(requestedTree)[0])) { // Only one key should present, since we added only one property
affectedKeysTree = affectedKeysTree[key];
if (!affectedKeysTree) {
return false; // Requested tree is not found
}
requestedTree = requestedTree[key];
}
return true;
}
}
exports.ConfigurationChangeEvent = ConfigurationChangeEvent;
});
/*---------------------------------------------------------------------------------------------
* 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/platform/contextkey/browser/contextKeyService*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,54/*vs/base/common/iterator*/,2/*vs/base/common/lifecycle*/,49/*vs/base/common/map*/,534/*vs/nls!vs/platform/contextkey/browser/contextKeyService*/,26/*vs/platform/commands/common/commands*/,38/*vs/platform/configuration/common/configuration*/,16/*vs/platform/contextkey/common/contextkey*/,254/*vs/platform/keybinding/common/keybindingResolver*/]), function (require, exports, event_1, iterator_1, lifecycle_1, map_1, nls_1, commands_1, configuration_1, contextkey_1, keybindingResolver_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextKeyService = exports.AbstractContextKeyService = exports.Context = void 0;
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;
}
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 {
constructor() {
super(-1, null);
}
setValue(key, value) {
return false;
}
removeValue(key) {
return false;
}
getValue(key) {
return undefined;
}
}
NullContext.INSTANCE = new NullContext();
class ConfigAwareContextValuesContainer extends Context {
constructor(id, _configurationService, emitter) {
super(id, null);
this._configurationService = _configurationService;
this._values = map_1.TernarySearchTree.forConfigKeys();
this._listener = this._configurationService.onDidChangeConfiguration(event => {
if (event.source === 6 /* DEFAULT */) {
// new setting, reset everything
const allKeys = Array.from(iterator_1.Iterable.map(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);
}
}
ConfigAwareContextValuesContainer._keyPrefix = 'config.';
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);
}
}
class ArrayContextKeyChangeEvent {
constructor(keys) {
this.keys = keys;
}
affectsSome(keys) {
for (const key of this.keys) {
if (keys.has(key)) {
return true;
}
}
return false;
}
}
class CompositeContextKeyChangeEvent {
constructor(events) {
this.events = events;
}
affectsSome(keys) {
for (const e of this.events) {
if (e.affectsSome(keys)) {
return true;
}
}
return false;
}
}
class AbstractContextKeyService {
constructor(myContextId) {
this._onDidChangeContext = 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 = keybindingResolver_1.KeybindingResolver.contextMatchesRules(context, rules);
// 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));
}
}
exports.AbstractContextKeyService = AbstractContextKeyService;
let ContextKeyService = class ContextKeyService extends AbstractContextKeyService {
constructor(configurationService) {
super(0);
this._contexts = new Map();
this._toDispose = new lifecycle_1.DisposableStore();
this._lastContextId = 0;
const myContext = new ConfigAwareContextValuesContainer(this._myContextId, configurationService, this._onDidChangeContext);
this._contexts.set(this._myContextId, myContext);
this._toDispose.add(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);
}
dispose() {
this._onDidChangeContext.dispose();
this._isDisposed = true;
this._toDispose.dispose();
}
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`);
}
let id = (++this._lastContextId);
this._contexts.set(id, new Context(id, this.getContextValuesContainer(parentContextId)));
return id;
}
disposeContext(contextId) {
if (!this._isDisposed) {
this._contexts.delete(contextId);
}
}
};
ContextKeyService = __decorate([
__param(0, configuration_1.IConfigurationService)
], ContextKeyService);
exports.ContextKeyService = ContextKeyService;
class ScopedContextKeyService extends AbstractContextKeyService {
constructor(parent, domNode) {
super(parent.createChildContext());
this._parentChangeListener = 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(this._onDidChangeContext.fire, this._onDidChangeContext);
}
dispose() {
if (this._isDisposed) {
return;
}
this._onDidChangeContext.dispose();
this._parent.disposeContext(this._myContextId);
this._parentChangeListener.dispose();
this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR);
this._isDisposed = true;
}
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;
}
commands_1.CommandsRegistry.registerCommand(contextkey_1.SET_CONTEXT_COMMAND_ID, function (accessor, contextKey, contextValue) {
accessor.get(contextkey_1.IContextKeyService).createKey(String(contextKey), contextValue);
});
commands_1.CommandsRegistry.registerCommand({
id: 'getContextKeyInfo',
handler() {
return [...contextkey_1.RawContextKey.all()].sort((a, b) => a.key.localeCompare(b.key));
},
description: {
description: (0, nls_1.localize)(0, null),
args: []
}
});
commands_1.CommandsRegistry.registerCommand('_generateContextKeyInfo', function () {
const result = [];
const seen = new Set();
for (let 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[88/*vs/platform/keybinding/common/keybindingsRegistry*/], __M([0/*require*/,1/*exports*/,41/*vs/base/common/keyCodes*/,17/*vs/base/common/platform*/,26/*vs/platform/commands/common/commands*/,32/*vs/platform/registry/common/platform*/]), function (require, exports, keyCodes_1, platform_1, commands_1, platform_2) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Extensions = exports.KeybindingsRegistry = void 0;
class KeybindingsRegistryImpl {
constructor() {
this._coreKeybindings = [];
this._extensionKeybindings = [];
this._cachedMergedKeybindings = null;
}
/**
* Take current platform into account and reduce to primary & secondary.
*/
static bindToCurrentPlatform(kb) {
if (platform_1.OS === 1 /* Windows */) {
if (kb && kb.win) {
return kb.win;
}
}
else if (platform_1.OS === 2 /* 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);
if (actualKb && actualKb.primary) {
const kk = (0, keyCodes_1.createKeybinding)(actualKb.primary, platform_1.OS);
if (kk) {
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, keyCodes_1.createKeybinding)(k, platform_1.OS);
if (kk) {
this._registerDefaultKeybinding(kk, rule.id, rule.args, rule.weight, -i - 1, rule.when);
}
}
}
}
registerCommandAndKeybindingRule(desc) {
this.registerKeybindingRule(desc);
commands_1.CommandsRegistry.registerCommand(desc);
}
static _mightProduceChar(keyCode) {
if (keyCode >= 21 /* KEY_0 */ && keyCode <= 30 /* KEY_9 */) {
return true;
}
if (keyCode >= 31 /* KEY_A */ && keyCode <= 56 /* KEY_Z */) {
return true;
}
return (keyCode === 80 /* US_SEMICOLON */
|| keyCode === 81 /* US_EQUAL */
|| keyCode === 82 /* US_COMMA */
|| keyCode === 83 /* US_MINUS */
|| keyCode === 84 /* US_DOT */
|| keyCode === 85 /* US_SLASH */
|| keyCode === 86 /* US_BACKTICK */
|| keyCode === 110 /* ABNT_C1 */
|| keyCode === 111 /* ABNT_C2 */
|| keyCode === 87 /* US_OPEN_SQUARE_BRACKET */
|| keyCode === 88 /* US_BACKSLASH */
|| keyCode === 89 /* US_CLOSE_SQUARE_BRACKET */
|| keyCode === 90 /* US_QUOTE */
|| keyCode === 91 /* OEM_8 */
|| keyCode === 92 /* OEM_102 */);
}
_assertNoCtrlAlt(keybinding, commandId) {
if (keybinding.ctrlKey && keybinding.altKey && !keybinding.metaKey) {
if (KeybindingsRegistryImpl._mightProduceChar(keybinding.keyCode)) {
console.warn('Ctrl+Alt+ keybindings should not be used by default under Windows. Offender: ', keybinding, ' for ', commandId);
}
}
}
_registerDefaultKeybinding(keybinding, commandId, commandArgs, weight1, weight2, when) {
if (platform_1.OS === 1 /* Windows */) {
this._assertNoCtrlAlt(keybinding.parts[0], commandId);
}
this._coreKeybindings.push({
keybinding: keybinding,
command: commandId,
commandArgs: commandArgs,
when: when,
weight1: weight1,
weight2: weight2,
extensionId: null,
isBuiltinExtension: false
});
this._cachedMergedKeybindings = null;
}
getDefaultKeybindings() {
if (!this._cachedMergedKeybindings) {
this._cachedMergedKeybindings = [].concat(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) {
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[585/*vs/platform/browser/contextScopedHistoryWidget*/], __M([0/*require*/,1/*exports*/,16/*vs/platform/contextkey/common/contextkey*/,442/*vs/base/browser/ui/findinput/findInput*/,88/*vs/platform/keybinding/common/keybindingsRegistry*/,443/*vs/base/browser/ui/findinput/replaceInput*/]), function (require, exports, contextkey_1, findInput_1, keybindingsRegistry_1, replaceInput_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextScopedReplaceInput = exports.ContextScopedFindInput = exports.createAndBindHistoryNavigationWidgetScopedContextKeyService = exports.HistoryNavigationEnablementContext = exports.HistoryNavigationWidgetContext = void 0;
exports.HistoryNavigationWidgetContext = 'historyNavigationWidget';
exports.HistoryNavigationEnablementContext = 'historyNavigationEnabled';
function bindContextScopedWidget(contextKeyService, widget, contextKey) {
new contextkey_1.RawContextKey(contextKey, widget).bindTo(contextKeyService);
}
function createWidgetScopedContextKeyService(contextKeyService, widget) {
return contextKeyService.createScoped(widget.target);
}
function getContextScopedWidget(contextKeyService, contextKey) {
return contextKeyService.getContext(document.activeElement).getValue(contextKey);
}
function createAndBindHistoryNavigationWidgetScopedContextKeyService(contextKeyService, widget) {
const scopedContextKeyService = createWidgetScopedContextKeyService(contextKeyService, widget);
bindContextScopedWidget(scopedContextKeyService, widget, exports.HistoryNavigationWidgetContext);
const historyNavigationEnablement = new contextkey_1.RawContextKey(exports.HistoryNavigationEnablementContext, true).bindTo(scopedContextKeyService);
return { scopedContextKeyService, historyNavigationEnablement };
}
exports.createAndBindHistoryNavigationWidgetScopedContextKeyService = createAndBindHistoryNavigationWidgetScopedContextKeyService;
let ContextScopedFindInput = class ContextScopedFindInput extends findInput_1.FindInput {
constructor(container, contextViewProvider, options, contextKeyService, showFindOptions = false) {
super(container, contextViewProvider, showFindOptions, options);
this._register(createAndBindHistoryNavigationWidgetScopedContextKeyService(contextKeyService, { target: this.inputBox.element, historyNavigator: this.inputBox }).scopedContextKeyService);
}
};
ContextScopedFindInput = __decorate([
__param(3, contextkey_1.IContextKeyService)
], ContextScopedFindInput);
exports.ContextScopedFindInput = ContextScopedFindInput;
let ContextScopedReplaceInput = class ContextScopedReplaceInput extends replaceInput_1.ReplaceInput {
constructor(container, contextViewProvider, options, contextKeyService, showReplaceOptions = false) {
super(container, contextViewProvider, showReplaceOptions, options);
this._register(createAndBindHistoryNavigationWidgetScopedContextKeyService(contextKeyService, { target: this.inputBox.element, historyNavigator: this.inputBox }).scopedContextKeyService);
}
};
ContextScopedReplaceInput = __decorate([
__param(3, contextkey_1.IContextKeyService)
], ContextScopedReplaceInput);
exports.ContextScopedReplaceInput = ContextScopedReplaceInput;
keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'history.showPrevious',
weight: 200 /* WorkbenchContrib */,
when: contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.has(exports.HistoryNavigationWidgetContext), contextkey_1.ContextKeyExpr.equals(exports.HistoryNavigationEnablementContext, true)),
primary: 16 /* UpArrow */,
secondary: [512 /* Alt */ | 16 /* UpArrow */],
handler: (accessor, arg2) => {
const widget = getContextScopedWidget(accessor.get(contextkey_1.IContextKeyService), exports.HistoryNavigationWidgetContext);
if (widget) {
const historyInputBox = widget.historyNavigator;
historyInputBox.showPreviousValue();
}
}
});
keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'history.showNext',
weight: 200 /* WorkbenchContrib */,
when: contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.has(exports.HistoryNavigationWidgetContext), contextkey_1.ContextKeyExpr.equals(exports.HistoryNavigationEnablementContext, true)),
primary: 18 /* DownArrow */,
secondary: [512 /* Alt */ | 18 /* DownArrow */],
handler: (accessor, arg2) => {
const widget = getContextScopedWidget(accessor.get(contextkey_1.IContextKeyService), exports.HistoryNavigationWidgetContext);
if (widget) {
const historyInputBox = widget.historyNavigator;
historyInputBox.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[99/*vs/platform/quickinput/common/quickAccess*/], __M([0/*require*/,1/*exports*/,32/*vs/platform/registry/common/platform*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/]), function (require, exports, platform_1, arrays_1, lifecycle_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 || (exports.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[586/*vs/platform/quickinput/browser/helpQuickAccess*/], __M([0/*require*/,1/*exports*/,78/*vs/platform/quickinput/common/quickInput*/,99/*vs/platform/quickinput/common/quickAccess*/,32/*vs/platform/registry/common/platform*/,540/*vs/nls!vs/platform/quickinput/browser/helpQuickAccess*/,2/*vs/base/common/lifecycle*/]), function (require, exports, quickInput_1, quickAccess_1, platform_1, nls_1, lifecycle_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HelpQuickAccessProvider = void 0;
let HelpQuickAccessProvider = class HelpQuickAccessProvider {
constructor(quickInputService) {
this.quickInputService = quickInputService;
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.PREFIX.length));
if (providerDescriptor && providerDescriptor.prefix && providerDescriptor.prefix !== HelpQuickAccessProvider.PREFIX) {
this.quickInputService.quickAccess.show(providerDescriptor.prefix, { preserveValue: true });
}
}));
// Fill in all providers separated by editor/global scope
const { editorProviders, globalProviders } = this.getQuickAccessProviders();
picker.items = editorProviders.length === 0 || globalProviders.length === 0 ?
// Without groups
[
...(editorProviders.length === 0 ? globalProviders : editorProviders)
] :
// With groups
[
{ label: (0, nls_1.localize)(0, null), type: 'separator' },
...globalProviders,
{ label: (0, nls_1.localize)(1, null), type: 'separator' },
...editorProviders
];
return disposables;
}
getQuickAccessProviders() {
const globalProviders = [];
const editorProviders = [];
for (const provider of this.registry.getQuickAccessProviders().sort((providerA, providerB) => providerA.prefix.localeCompare(providerB.prefix))) {
if (provider.prefix === HelpQuickAccessProvider.PREFIX) {
continue; // exclude help which is already active
}
for (const helpEntry of provider.helpEntries) {
const prefix = helpEntry.prefix || provider.prefix;
const label = prefix || '\u2026' /* ... */;
(helpEntry.needsEditor ? editorProviders : globalProviders).push({
prefix,
label,
ariaLabel: (0, nls_1.localize)(2, null, label, helpEntry.description),
description: helpEntry.description
});
}
}
return { editorProviders, globalProviders };
}
};
HelpQuickAccessProvider.PREFIX = '?';
HelpQuickAccessProvider = __decorate([
__param(0, quickInput_1.IQuickInputService)
], HelpQuickAccessProvider);
exports.HelpQuickAccessProvider = 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[587/*vs/editor/standalone/browser/quickAccess/standaloneHelpQuickAccess*/], __M([0/*require*/,1/*exports*/,32/*vs/platform/registry/common/platform*/,99/*vs/platform/quickinput/common/quickAccess*/,63/*vs/editor/common/standaloneStrings*/,586/*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, needsEditor: 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[588/*vs/platform/quickinput/browser/quickAccess*/], __M([0/*require*/,1/*exports*/,78/*vs/platform/quickinput/common/quickInput*/,2/*vs/base/common/lifecycle*/,99/*vs/platform/quickinput/common/quickAccess*/,32/*vs/platform/registry/common/platform*/,23/*vs/base/common/cancellation*/,9/*vs/platform/instantiation/common/instantiation*/,80/*vs/base/common/functional*/]), function (require, exports, quickInput_1, lifecycle_1, quickAccess_1, platform_1, cancellation_1, instantiation_1, functional_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) {
var _a;
// Find provider for the value to show
const [provider, descriptor] = this.getOrInstantiateProvider(value);
// Return early if quick access is already showing on that same prefix
const visibleQuickAccess = this.visibleQuickAccess;
const visibleDescriptor = visibleQuickAccess === null || visibleQuickAccess === void 0 ? void 0 : 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 === null || options === void 0 ? void 0 : 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 === null || options === void 0 ? void 0 : 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 === null || provider === void 0 ? void 0 : 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;
}
}
// 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());
picker.value = value;
this.adjustValueSelection(picker, descriptor, options);
picker.placeholder = descriptor === null || descriptor === void 0 ? void 0 : descriptor.placeholder;
picker.quickNavigate = options === null || options === void 0 ? void 0 : options.quickNavigateConfiguration;
picker.hideInput = !!picker.quickNavigate && !visibleQuickAccess; // only hide input if there was no picker opened already
if (typeof (options === null || options === void 0 ? void 0 : options.itemActivation) === 'number' || (options === null || options === void 0 ? void 0 : options.quickNavigateConfiguration)) {
picker.itemActivation = (_a = options === null || options === void 0 ? void 0 : options.itemActivation) !== null && _a !== void 0 ? _a : quickInput_1.ItemActivation.SECOND /* quick nav is always second */;
}
picker.contextKey = descriptor === null || descriptor === void 0 ? void 0 : descriptor.contextKey;
picker.filterValue = (value) => value.substring(descriptor ? descriptor.prefix.length : 0);
if (descriptor === null || descriptor === void 0 ? void 0 : descriptor.placeholder) {
picker.ariaLabel = descriptor === null || descriptor === void 0 ? void 0 : descriptor.placeholder;
}
// Pick mode: setup a promise that can be resolved
// with the selected items and prevent execution
let pickPromise = undefined;
let pickResolve = undefined;
if (pick) {
pickPromise = new Promise(resolve => pickResolve = resolve);
disposables.add((0, functional_1.once)(picker.onWillAccept)(e => {
e.veto();
picker.hide();
}));
}
// Register listeners
disposables.add(this.registerPickerListeners(picker, provider, descriptor, value));
// 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));
}
// Finally, trigger disposal and cancellation when the picker
// hides depending on items selected or not.
(0, functional_1.once)(picker.onDidHide)(() => {
if (picker.selectedItems.length === 0) {
cts.cancel();
}
// Start to dispose once picker hides
disposables.dispose();
// Resolve pick promise with selected items
pickResolve === null || pickResolve === void 0 ? void 0 : pickResolve(picker.selectedItems);
});
// 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();
// Pick mode: return with promise
if (pick) {
return pickPromise;
}
}
adjustValueSelection(picker, descriptor, options) {
var _a;
let valueSelection;
// Preserve: just always put the cursor at the end
if (options === null || options === void 0 ? void 0 : options.preserveValue) {
valueSelection = [picker.value.length, picker.value.length];
}
// Otherwise: select the value up until the prefix
else {
valueSelection = [(_a = descriptor === null || descriptor === void 0 ? void 0 : descriptor.prefix.length) !== null && _a !== void 0 ? _a : 0, picker.value.length];
}
picker.valueSelection = valueSelection;
}
registerPickerListeners(picker, provider, descriptor, value) {
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);
if (providerForValue !== provider) {
this.show(value, { preserveValue: true } /* do not rewrite value from user typing! */);
}
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) {
const providerDescriptor = this.registry.getQuickAccessProvider(value);
if (!providerDescriptor) {
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];
}
};
QuickAccessController = __decorate([
__param(0, quickInput_1.IQuickInputService),
__param(1, instantiation_1.IInstantiationService)
], QuickAccessController);
exports.QuickAccessController = 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[71/*vs/platform/storage/common/storage*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/,300/*vs/base/parts/storage/common/storage*/]), function (require, exports, instantiation_1, event_1, lifecycle_1, types_1, storage_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InMemoryStorageService = exports.AbstractStorageService = exports.WillSaveStateReason = exports.IStorageService = void 0;
const 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 || (exports.WillSaveStateReason = {}));
class AbstractStorageService extends lifecycle_1.Disposable {
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._globalKeyTargets = undefined;
}
emitDidChangeValue(scope, key) {
// Specially handle `TARGET_KEY`
if (key === TARGET_KEY) {
// Clear our cached version which is now out of date
if (scope === 0 /* GLOBAL */) {
this._globalKeyTargets = undefined;
}
else if (scope === 1 /* WORKSPACE */) {
this._workspaceKeyTargets = undefined;
}
// 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] });
}
}
get(key, scope, fallbackValue) {
var _a;
return (_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.get(key, fallbackValue);
}
getBoolean(key, scope, fallbackValue) {
var _a;
return (_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.getBoolean(key, fallbackValue);
}
getNumber(key, scope, fallbackValue) {
var _a;
return (_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.getNumber(key, fallbackValue);
}
store(key, value, scope, target) {
// We remove the key for undefined/null values
if ((0, types_1.isUndefinedOrNull)(value)) {
this.remove(key, scope);
return;
}
// Update our datastructures but send events only after
this.withPausedEmitters(() => {
var _a;
// Update key-target map
this.updateKeyTarget(key, scope, target);
// Store actual value
(_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.set(key, value);
});
}
remove(key, scope) {
// Update our datastructures but send events only after
this.withPausedEmitters(() => {
var _a;
// Update key-target map
this.updateKeyTarget(key, scope, undefined);
// Remove actual key
(_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.delete(key);
});
}
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) {
var _a, _b;
// Add
const keyTargets = this.getKeyTargets(scope);
if (typeof target === 'number') {
if (keyTargets[key] !== target) {
keyTargets[key] = target;
(_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.set(TARGET_KEY, JSON.stringify(keyTargets));
}
}
// Remove
else {
if (typeof keyTargets[key] === 'number') {
delete keyTargets[key];
(_b = this.getStorage(scope)) === null || _b === void 0 ? void 0 : _b.set(TARGET_KEY, JSON.stringify(keyTargets));
}
}
}
get workspaceKeyTargets() {
if (!this._workspaceKeyTargets) {
this._workspaceKeyTargets = this.loadKeyTargets(1 /* WORKSPACE */);
}
return this._workspaceKeyTargets;
}
get globalKeyTargets() {
if (!this._globalKeyTargets) {
this._globalKeyTargets = this.loadKeyTargets(0 /* GLOBAL */);
}
return this._globalKeyTargets;
}
getKeyTargets(scope) {
return scope === 0 /* GLOBAL */ ? this.globalKeyTargets : this.workspaceKeyTargets;
}
loadKeyTargets(scope) {
const keysRaw = this.get(TARGET_KEY, scope);
if (keysRaw) {
try {
return JSON.parse(keysRaw);
}
catch (error) {
// Fail gracefully
}
}
return Object.create(null);
}
}
exports.AbstractStorageService = AbstractStorageService;
AbstractStorageService.DEFAULT_FLUSH_INTERVAL = 60 * 1000; // every minute
class InMemoryStorageService extends AbstractStorageService {
constructor() {
super();
this.globalStorage = this._register(new storage_1.Storage(new storage_1.InMemoryStorageDatabase()));
this.workspaceStorage = this._register(new storage_1.Storage(new storage_1.InMemoryStorageDatabase()));
this._register(this.workspaceStorage.onDidChangeStorage(key => this.emitDidChangeValue(1 /* WORKSPACE */, key)));
this._register(this.globalStorage.onDidChangeStorage(key => this.emitDidChangeValue(0 /* GLOBAL */, key)));
}
getStorage(scope) {
return scope === 0 /* GLOBAL */ ? this.globalStorage : 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[589/*vs/editor/contrib/codelens/codeLensCache*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,75/*vs/platform/instantiation/common/extensions*/,251/*vs/editor/contrib/codelens/codelens*/,49/*vs/base/common/map*/,71/*vs/platform/storage/common/storage*/,3/*vs/editor/common/core/range*/,15/*vs/base/common/async*/,80/*vs/base/common/functional*/]), function (require, exports, instantiation_1, extensions_1, codelens_1, map_1, storage_1, range_1, async_1, functional_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, async_1.runWhenIdle)(() => storageService.remove(oldkey, 1 /* WORKSPACE */));
// restore lens data on start
const key = 'codelens/cache2';
const raw = storageService.get(key, 1 /* WORKSPACE */, '{}');
this._deserialize(raw);
// store lens data on shutdown
(0, functional_1.once)(storageService.onWillSaveState)(e => {
if (e.reason === storage_1.WillSaveStateReason.SHUTDOWN) {
storageService.store(key, this._serialize(), 1 /* WORKSPACE */, 1 /* 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 => {
var _a;
return {
range: item.symbol.range,
command: item.symbol.command && { id: '', title: (_a = item.symbol.command) === null || _a === void 0 ? void 0 : _a.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 (_a) {
// ignore...
}
}
};
CodeLensCache = __decorate([
__param(0, storage_1.IStorageService)
], CodeLensCache);
exports.CodeLensCache = CodeLensCache;
(0, extensions_1.registerSingleton)(exports.ICodeLensCache, CodeLensCache);
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/suggest/suggestMemory*/], __M([0/*require*/,1/*exports*/,49/*vs/base/common/map*/,71/*vs/platform/storage/common/storage*/,18/*vs/editor/common/modes*/,2/*vs/base/common/lifecycle*/,15/*vs/base/common/async*/,9/*vs/platform/instantiation/common/instantiation*/,38/*vs/platform/configuration/common/configuration*/,75/*vs/platform/instantiation/common/extensions*/,57/*vs/editor/common/services/modeService*/]), function (require, exports, map_1, storage_1, modes_1, lifecycle_1, async_1, instantiation_1, configuration_1, extensions_1, modeService_1) {
"use strict";
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;
}
let 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.getLanguageIdentifier().language}/${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);
}
let 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.getLanguageIdentifier().language}/${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();
let seq = 0;
for (const [key, value] of data) {
value.touch = seq;
value.type = typeof value.type === 'number' ? value.type : (0, modes_1.completionKindFromString)(value.type);
this._cache.set(key, value);
}
this._seq = this._cache.size;
}
}
exports.LRUMemory = LRUMemory;
class PrefixMemory extends Memory {
constructor() {
super('recentlyUsedByPrefix');
this._trie = map_1.TernarySearchTree.forStrings();
this._seq = 0;
}
memorize(model, pos, item) {
const { word } = model.getWordUntilPosition(pos);
const key = `${model.getLanguageIdentifier().language}/${word}`;
this._trie.set(key, {
type: item.completion.kind,
insertText: item.completion.insertText,
touch: this._seq++
});
}
select(model, pos, items) {
let { word } = model.getWordUntilPosition(pos);
if (!word) {
return super.select(model, pos, items);
}
let key = `${model.getLanguageIdentifier().language}/${word}`;
let item = this._trie.get(key);
if (!item) {
item = this._trie.findSubstr(key);
}
if (item) {
for (let i = 0; i < items.length; i++) {
let { kind, insertText } = items[i].completion;
if (kind === item.type && insertText === item.insertText) {
return i;
}
}
}
return super.select(model, pos, items);
}
toJSON() {
let 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 : (0, modes_1.completionKindFromString)(value.type);
this._trie.set(key, value);
}
}
}
}
exports.PrefixMemory = PrefixMemory;
let SuggestMemoryService = class SuggestMemoryService {
constructor(_storageService, _modeService, _configService) {
this._storageService = _storageService;
this._modeService = _modeService;
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) {
var _a, _b;
const mode = this._configService.getValue('editor.suggestSelection', {
overrideIdentifier: (_a = this._modeService.getLanguageIdentifier(model.getLanguageIdAtPosition(pos.lineNumber, pos.column))) === null || _a === void 0 ? void 0 : _a.language,
resource: model.uri
});
if (((_b = this._strategy) === null || _b === void 0 ? void 0 : _b.name) !== mode) {
this._saveState();
const ctor = SuggestMemoryService._strategyCtors.get(mode) || NoMemory;
this._strategy = new ctor();
try {
const share = this._configService.getValue('editor.suggest.shareSuggestSelections');
const scope = share ? 0 /* GLOBAL */ : 1 /* WORKSPACE */;
const raw = this._storageService.get(`${SuggestMemoryService._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 /* GLOBAL */ : 1 /* WORKSPACE */;
const raw = JSON.stringify(this._strategy);
this._storageService.store(`${SuggestMemoryService._storagePrefix}/${this._strategy.name}`, raw, scope, 1 /* MACHINE */);
}
}
};
SuggestMemoryService._strategyCtors = new Map([
['recentlyUsedByPrefix', PrefixMemory],
['recentlyUsed', LRUMemory],
['first', NoMemory]
]);
SuggestMemoryService._storagePrefix = 'suggest/memories';
SuggestMemoryService = __decorate([
__param(0, storage_1.IStorageService),
__param(1, modeService_1.IModeService),
__param(2, configuration_1.IConfigurationService)
], SuggestMemoryService);
exports.SuggestMemoryService = SuggestMemoryService;
exports.ISuggestMemoryService = (0, instantiation_1.createDecorator)('ISuggestMemories');
(0, extensions_1.registerSingleton)(exports.ISuggestMemoryService, SuggestMemoryService, 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[89/*vs/platform/telemetry/common/telemetry*/], __M([0/*require*/,1/*exports*/,9/*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[591/*vs/platform/quickinput/browser/commandsQuickAccess*/], __M([0/*require*/,1/*exports*/,539/*vs/nls!vs/platform/quickinput/browser/commandsQuickAccess*/,575/*vs/platform/quickinput/browser/pickerQuickAccess*/,2/*vs/base/common/lifecycle*/,67/*vs/base/common/filters*/,20/*vs/base/common/types*/,49/*vs/base/common/map*/,71/*vs/platform/storage/common/storage*/,38/*vs/platform/configuration/common/configuration*/,9/*vs/platform/instantiation/common/instantiation*/,37/*vs/platform/keybinding/common/keybinding*/,26/*vs/platform/commands/common/commands*/,89/*vs/platform/telemetry/common/telemetry*/,12/*vs/base/common/errors*/,120/*vs/platform/dialogs/common/dialogs*/,74/*vs/base/common/severity*/,447/*vs/base/common/errorMessage*/]), function (require, exports, nls_1, pickerQuickAccess_1, lifecycle_1, filters_1, types_1, map_1, storage_1, configuration_1, instantiation_1, keybinding_1, commands_1, telemetry_1, errors_1, dialogs_1, severity_1, errorMessage_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandsHistory = exports.AbstractCommandsQuickAccessProvider = void 0;
let AbstractCommandsQuickAccessProvider = class AbstractCommandsQuickAccessProvider extends pickerQuickAccess_1.PickerQuickAccessProvider {
constructor(options, instantiationService, keybindingService, commandService, telemetryService, dialogService) {
super(AbstractCommandsQuickAccessProvider.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;
}
_getPicks(filter, disposables, token) {
return __awaiter(this, void 0, void 0, function* () {
// Ask subclass for all command picks
const allCommandPicks = yield this.getCommandPicks(disposables, token);
if (token.isCancellationRequested) {
return [];
}
// Filter
const filteredCommandPicks = [];
for (const commandPick of allCommandPicks) {
const labelHighlights = (0, types_1.withNullAsUndefined)(AbstractCommandsQuickAccessProvider.WORD_FILTER(filter, commandPick.label));
const aliasHighlights = commandPick.commandAlias ? (0, types_1.withNullAsUndefined)(AbstractCommandsQuickAccessProvider.WORD_FILTER(filter, commandPick.commandAlias)) : 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);
}
}
// 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) => {
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
}
// both commands were never used, so we sort by name
return commandPickA.label.localeCompare(commandPickB.label);
});
const commandPicks = [];
let addSeparator = false;
for (let i = 0; i < filteredCommandPicks.length; i++) {
const commandPick = filteredCommandPicks[i];
const keybinding = this.keybindingService.lookupKeybinding(commandPick.commandId);
const ariaLabel = keybinding ?
(0, nls_1.localize)(0, null, commandPick.label, keybinding.getAriaLabel()) :
commandPick.label;
// Separator: recently used
if (i === 0 && this.commandsHistory.peek(commandPick.commandId)) {
commandPicks.push({ type: 'separator', label: (0, nls_1.localize)(1, null) });
addSeparator = true;
}
// Separator: other commands
if (i !== 0 && addSeparator && !this.commandsHistory.peek(commandPick.commandId)) {
commandPicks.push({ type: 'separator', label: (0, nls_1.localize)(2, null) });
addSeparator = false; // only once
}
// Command
commandPicks.push(Object.assign(Object.assign({}, commandPick), { ariaLabel, detail: this.options.showAlias && commandPick.commandAlias !== commandPick.label ? commandPick.commandAlias : undefined, keybinding, accept: () => __awaiter(this, void 0, void 0, function* () {
// Add to history
this.commandsHistory.push(commandPick.commandId);
// Telementry
this.telemetryService.publicLog2('workbenchActionExecuted', {
id: commandPick.commandId,
from: 'quick open'
});
// Run
try {
yield this.commandService.executeCommand(commandPick.commandId);
}
catch (error) {
if (!(0, errors_1.isPromiseCanceledError)(error)) {
this.dialogService.show(severity_1.default.Error, (0, nls_1.localize)(3, null, commandPick.label, (0, errorMessage_1.toErrorMessage)(error)));
}
}
}) }));
}
return commandPicks;
});
}
};
AbstractCommandsQuickAccessProvider.PREFIX = '>';
AbstractCommandsQuickAccessProvider.WORD_FILTER = (0, filters_1.or)(filters_1.matchesPrefix, filters_1.matchesWords, filters_1.matchesContiguousSubString);
AbstractCommandsQuickAccessProvider = __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);
exports.AbstractCommandsQuickAccessProvider = AbstractCommandsQuickAccessProvider;
let CommandsHistory = class CommandsHistory extends lifecycle_1.Disposable {
constructor(storageService, configurationService) {
super();
this.storageService = storageService;
this.configurationService = configurationService;
this.configuredCommandsHistoryLength = 0;
this.updateConfiguration();
this.load();
this.registerListeners();
}
registerListeners() {
this._register(this.configurationService.onDidChangeConfiguration(() => this.updateConfiguration()));
}
updateConfiguration() {
this.configuredCommandsHistoryLength = CommandsHistory.getConfiguredCommandHistoryLength(this.configurationService);
if (CommandsHistory.cache && CommandsHistory.cache.limit !== this.configuredCommandsHistoryLength) {
CommandsHistory.cache.limit = this.configuredCommandsHistoryLength;
CommandsHistory.saveState(this.storageService);
}
}
load() {
const raw = this.storageService.get(CommandsHistory.PREF_KEY_CACHE, 0 /* GLOBAL */);
let serializedCache;
if (raw) {
try {
serializedCache = JSON.parse(raw);
}
catch (error) {
// invalid data
}
}
const cache = CommandsHistory.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.counter = this.storageService.getNumber(CommandsHistory.PREF_KEY_COUNTER, 0 /* GLOBAL */, CommandsHistory.counter);
}
push(commandId) {
if (!CommandsHistory.cache) {
return;
}
CommandsHistory.cache.set(commandId, CommandsHistory.counter++); // set counter to command
CommandsHistory.saveState(this.storageService);
}
peek(commandId) {
var _a;
return (_a = CommandsHistory.cache) === null || _a === void 0 ? void 0 : _a.peek(commandId);
}
static saveState(storageService) {
if (!CommandsHistory.cache) {
return;
}
const serializedCache = { usesLRU: true, entries: [] };
CommandsHistory.cache.forEach((value, key) => serializedCache.entries.push({ key, value }));
storageService.store(CommandsHistory.PREF_KEY_CACHE, JSON.stringify(serializedCache), 0 /* GLOBAL */, 0 /* USER */);
storageService.store(CommandsHistory.PREF_KEY_COUNTER, CommandsHistory.counter, 0 /* GLOBAL */, 0 /* USER */);
}
static getConfiguredCommandHistoryLength(configurationService) {
var _a, _b;
const config = configurationService.getValue();
const configuredCommandHistoryLength = (_b = (_a = config.workbench) === null || _a === void 0 ? void 0 : _a.commandPalette) === null || _b === void 0 ? void 0 : _b.history;
if (typeof configuredCommandHistoryLength === 'number') {
return configuredCommandHistoryLength;
}
return CommandsHistory.DEFAULT_COMMANDS_HISTORY_LENGTH;
}
};
CommandsHistory.DEFAULT_COMMANDS_HISTORY_LENGTH = 50;
CommandsHistory.PREF_KEY_CACHE = 'commandPalette.mru.cache';
CommandsHistory.PREF_KEY_COUNTER = 'commandPalette.mru.counter';
CommandsHistory.counter = 1;
CommandsHistory = __decorate([
__param(0, storage_1.IStorageService),
__param(1, configuration_1.IConfigurationService)
], CommandsHistory);
exports.CommandsHistory = 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[592/*vs/editor/contrib/quickAccess/commandsQuickAccess*/], __M([0/*require*/,1/*exports*/,591/*vs/platform/quickinput/browser/commandsQuickAccess*/,104/*vs/base/common/iconLabels*/]), function (require, exports, commandsQuickAccess_1, iconLabels_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()) {
editorCommandPicks.push({
commandId: editorAction.id,
commandAlias: editorAction.alias,
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[22/*vs/platform/theme/common/colorRegistry*/], __M([0/*require*/,1/*exports*/,32/*vs/platform/registry/common/platform*/,29/*vs/base/common/color*/,6/*vs/base/common/event*/,541/*vs/nls!vs/platform/theme/common/colorRegistry*/,189/*vs/platform/jsonschemas/common/jsonContributionRegistry*/,15/*vs/base/common/async*/,20/*vs/base/common/types*/]), function (require, exports, platform, color_1, event_1, nls, jsonContributionRegistry_1, async_1, types_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.workbenchColorsSchemaId = exports.resolveColorValue = exports.ifDefinedThenElse = exports.oneOf = exports.transparent = exports.lighten = exports.darken = exports.executeTransform = exports.problemsInfoIconForeground = exports.problemsWarningIconForeground = exports.problemsErrorIconForeground = exports.minimapSliderActiveBackground = exports.minimapSliderHoverBackground = exports.minimapSliderBackground = exports.minimapBackground = exports.minimapWarning = exports.minimapError = exports.minimapSelection = exports.minimapFindMatch = exports.overviewRulerSelectionHighlightForeground = exports.overviewRulerFindMatchForeground = exports.snippetFinalTabstopHighlightBorder = exports.snippetFinalTabstopHighlightBackground = exports.snippetTabstopHighlightBorder = exports.snippetTabstopHighlightBackground = exports.menuSeparatorBackground = exports.menuSelectionBorder = exports.menuSelectionBackground = exports.menuSelectionForeground = exports.menuBackground = exports.menuForeground = exports.menuBorder = exports.quickInputListFocusBackground = exports.quickInputListFocusIconForeground = exports.quickInputListFocusForeground = exports._deprecatedQuickInputListFocusBackground = exports.tableColumnsBorder = exports.treeIndentGuidesStroke = exports.listFilterWidgetNoMatchesOutline = exports.listFilterWidgetOutline = exports.listFilterWidgetBackground = exports.listFocusHighlightForeground = exports.listHighlightForeground = exports.listDropBackground = exports.listHoverForeground = exports.listHoverBackground = exports.listInactiveFocusOutline = exports.listInactiveFocusBackground = exports.listInactiveSelectionIconForeground = exports.listInactiveSelectionForeground = exports.listInactiveSelectionBackground = exports.listActiveSelectionIconForeground = exports.listActiveSelectionForeground = exports.listActiveSelectionBackground = exports.listFocusOutline = exports.listFocusForeground = exports.listFocusBackground = exports.diffDiagonalFill = exports.diffBorder = exports.diffRemovedOutline = exports.diffInsertedOutline = exports.diffRemoved = exports.diffInserted = exports.defaultRemoveColor = exports.defaultInsertColor = exports.editorLightBulbAutoFixForeground = exports.editorLightBulbForeground = exports.editorInlayHintBackground = exports.editorInlayHintForeground = exports.editorActiveLinkForeground = exports.editorHoverStatusBarBackground = exports.editorHoverBorder = exports.editorHoverForeground = exports.editorHoverBackground = exports.editorHoverHighlight = exports.editorFindRangeHighlightBorder = exports.editorFindMatchHighlightBorder = exports.editorFindMatchBorder = exports.editorFindRangeHighlight = exports.editorFindMatchHighlight = exports.editorFindMatch = exports.editorSelectionHighlightBorder = exports.editorSelectionHighlight = exports.editorInactiveSelection = exports.editorSelectionForeground = exports.editorSelectionBackground = exports.keybindingLabelBottomBorder = exports.keybindingLabelBorder = exports.keybindingLabelForeground = exports.keybindingLabelBackground = exports.pickerGroupBorder = exports.pickerGroupForeground = exports.quickInputTitleBackground = exports.quickInputForeground = exports.quickInputBackground = exports.editorWidgetResizeBorder = exports.editorWidgetBorder = exports.editorWidgetForeground = exports.editorWidgetBackground = exports.editorForeground = exports.editorBackground = exports.editorHintBorder = exports.editorHintForeground = exports.editorInfoBorder = exports.editorInfoForeground = exports.editorInfoBackground = exports.editorWarningBorder = exports.editorWarningForeground = exports.editorWarningBackground = exports.editorErrorBorder = exports.editorErrorForeground = exports.editorErrorBackground = exports.progressBarBackground = exports.scrollbarSliderActiveBackground = exports.scrollbarSliderHoverBackground = exports.scrollbarSliderBackground = exports.scrollbarShadow = exports.badgeForeground = exports.badgeBackground = exports.buttonHoverBackground = exports.buttonBackground = exports.buttonForeground = exports.selectForeground = exports.selectBackground = exports.inputValidationErrorBorder = exports.inputValidationErrorForeground = exports.inputValidationErrorBackground = exports.inputValidationWarningBorder = exports.inputValidationWarningForeground = exports.inputValidationWarningBackground = exports.inputValidationInfoBorder = exports.inputValidationInfoForeground = exports.inputValidationInfoBackground = exports.inputActiveOptionForeground = exports.inputActiveOptionBackground = exports.inputActiveOptionBorder = exports.inputBorder = exports.inputForeground = exports.inputBackground = exports.widgetShadow = exports.textCodeBlockBackground = exports.textLinkActiveForeground = exports.textLinkForeground = exports.activeContrastBorder = exports.contrastBorder = exports.focusBorder = exports.iconForeground = exports.errorForeground = exports.foreground = exports.registerColor = exports.Extensions = void 0;
// color registry
exports.Extensions = {
ColorContribution: 'base.contributions.colors'
};
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) {
let colorContribution = { id, description, defaults, needsTransparency, deprecationMessage };
this.colorsById[id] = colorContribution;
let propertySchema = { type: 'string', description, format: 'color-hex', defaultSnippets: [{ body: '${1:#ff0000}' }] };
if (deprecationMessage) {
propertySchema.deprecationMessage = deprecationMessage;
}
this.colorSchema.properties[id] = propertySchema;
this.colorReferenceSchema.enum.push(id);
this.colorReferenceSchema.enumDescriptions.push(description);
this._onDidChangeSchema.fire();
return id;
}
resolveDefaultColor(id, theme) {
const colorDesc = this.colorsById[id];
if (colorDesc && colorDesc.defaults) {
const colorValue = colorDesc.defaults[theme.type];
return resolveColorValue(colorValue, theme);
}
return undefined;
}
getColorSchema() {
return this.colorSchema;
}
toString() {
let sorter = (a, b) => {
let cat1 = a.indexOf('.') === -1 ? 0 : 1;
let 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);
}
exports.registerColor = registerColor;
// ----- base colors
exports.foreground = registerColor('foreground', { dark: '#CCCCCC', light: '#616161', hc: '#FFFFFF' }, nls.localize(0, null));
exports.errorForeground = registerColor('errorForeground', { dark: '#F48771', light: '#A1260D', hc: '#F48771' }, nls.localize(1, null));
exports.iconForeground = registerColor('icon.foreground', { dark: '#C5C5C5', light: '#424242', hc: '#FFFFFF' }, nls.localize(2, null));
exports.focusBorder = registerColor('focusBorder', { dark: '#007FD4', light: '#0090F1', hc: '#F38518' }, nls.localize(3, null));
exports.contrastBorder = registerColor('contrastBorder', { light: null, dark: null, hc: '#6FC3DF' }, nls.localize(4, null));
exports.activeContrastBorder = registerColor('contrastActiveBorder', { light: null, dark: null, hc: exports.focusBorder }, nls.localize(5, null));
exports.textLinkForeground = registerColor('textLink.foreground', { light: '#006AB1', dark: '#3794FF', hc: '#3794FF' }, nls.localize(6, null));
exports.textLinkActiveForeground = registerColor('textLink.activeForeground', { light: '#006AB1', dark: '#3794FF', hc: '#3794FF' }, nls.localize(7, null));
exports.textCodeBlockBackground = registerColor('textCodeBlock.background', { light: '#dcdcdc66', dark: '#0a0a0a66', hc: color_1.Color.black }, nls.localize(8, null));
// ----- widgets
exports.widgetShadow = registerColor('widget.shadow', { dark: transparent(color_1.Color.black, .36), light: transparent(color_1.Color.black, .16), hc: null }, nls.localize(9, null));
exports.inputBackground = registerColor('input.background', { dark: '#3C3C3C', light: color_1.Color.white, hc: color_1.Color.black }, nls.localize(10, null));
exports.inputForeground = registerColor('input.foreground', { dark: exports.foreground, light: exports.foreground, hc: exports.foreground }, nls.localize(11, null));
exports.inputBorder = registerColor('input.border', { dark: null, light: null, hc: exports.contrastBorder }, nls.localize(12, null));
exports.inputActiveOptionBorder = registerColor('inputOption.activeBorder', { dark: '#007ACC00', light: '#007ACC00', hc: exports.contrastBorder }, nls.localize(13, null));
exports.inputActiveOptionBackground = registerColor('inputOption.activeBackground', { dark: transparent(exports.focusBorder, 0.4), light: transparent(exports.focusBorder, 0.2), hc: color_1.Color.transparent }, nls.localize(14, null));
exports.inputActiveOptionForeground = registerColor('inputOption.activeForeground', { dark: color_1.Color.white, light: color_1.Color.black, hc: null }, nls.localize(15, null));
exports.inputValidationInfoBackground = registerColor('inputValidation.infoBackground', { dark: '#063B49', light: '#D6ECF2', hc: color_1.Color.black }, nls.localize(16, null));
exports.inputValidationInfoForeground = registerColor('inputValidation.infoForeground', { dark: null, light: null, hc: null }, nls.localize(17, null));
exports.inputValidationInfoBorder = registerColor('inputValidation.infoBorder', { dark: '#007acc', light: '#007acc', hc: exports.contrastBorder }, nls.localize(18, null));
exports.inputValidationWarningBackground = registerColor('inputValidation.warningBackground', { dark: '#352A05', light: '#F6F5D2', hc: color_1.Color.black }, nls.localize(19, null));
exports.inputValidationWarningForeground = registerColor('inputValidation.warningForeground', { dark: null, light: null, hc: null }, nls.localize(20, null));
exports.inputValidationWarningBorder = registerColor('inputValidation.warningBorder', { dark: '#B89500', light: '#B89500', hc: exports.contrastBorder }, nls.localize(21, null));
exports.inputValidationErrorBackground = registerColor('inputValidation.errorBackground', { dark: '#5A1D1D', light: '#F2DEDE', hc: color_1.Color.black }, nls.localize(22, null));
exports.inputValidationErrorForeground = registerColor('inputValidation.errorForeground', { dark: null, light: null, hc: null }, nls.localize(23, null));
exports.inputValidationErrorBorder = registerColor('inputValidation.errorBorder', { dark: '#BE1100', light: '#BE1100', hc: exports.contrastBorder }, nls.localize(24, null));
exports.selectBackground = registerColor('dropdown.background', { dark: '#3C3C3C', light: color_1.Color.white, hc: color_1.Color.black }, nls.localize(25, null));
exports.selectForeground = registerColor('dropdown.foreground', { dark: '#F0F0F0', light: null, hc: color_1.Color.white }, nls.localize(26, null));
exports.buttonForeground = registerColor('button.foreground', { dark: color_1.Color.white, light: color_1.Color.white, hc: color_1.Color.white }, nls.localize(27, null));
exports.buttonBackground = registerColor('button.background', { dark: '#0E639C', light: '#007ACC', hc: null }, nls.localize(28, null));
exports.buttonHoverBackground = registerColor('button.hoverBackground', { dark: lighten(exports.buttonBackground, 0.2), light: darken(exports.buttonBackground, 0.2), hc: null }, nls.localize(29, null));
exports.badgeBackground = registerColor('badge.background', { dark: '#4D4D4D', light: '#C4C4C4', hc: color_1.Color.black }, nls.localize(30, null));
exports.badgeForeground = registerColor('badge.foreground', { dark: color_1.Color.white, light: '#333', hc: color_1.Color.white }, nls.localize(31, null));
exports.scrollbarShadow = registerColor('scrollbar.shadow', { dark: '#000000', light: '#DDDDDD', hc: null }, nls.localize(32, null));
exports.scrollbarSliderBackground = registerColor('scrollbarSlider.background', { dark: color_1.Color.fromHex('#797979').transparent(0.4), light: color_1.Color.fromHex('#646464').transparent(0.4), hc: transparent(exports.contrastBorder, 0.6) }, nls.localize(33, null));
exports.scrollbarSliderHoverBackground = registerColor('scrollbarSlider.hoverBackground', { dark: color_1.Color.fromHex('#646464').transparent(0.7), light: color_1.Color.fromHex('#646464').transparent(0.7), hc: transparent(exports.contrastBorder, 0.8) }, nls.localize(34, null));
exports.scrollbarSliderActiveBackground = registerColor('scrollbarSlider.activeBackground', { dark: color_1.Color.fromHex('#BFBFBF').transparent(0.4), light: color_1.Color.fromHex('#000000').transparent(0.6), hc: exports.contrastBorder }, nls.localize(35, null));
exports.progressBarBackground = registerColor('progressBar.background', { dark: color_1.Color.fromHex('#0E70C0'), light: color_1.Color.fromHex('#0E70C0'), hc: exports.contrastBorder }, nls.localize(36, null));
exports.editorErrorBackground = registerColor('editorError.background', { dark: null, light: null, hc: null }, nls.localize(37, null), true);
exports.editorErrorForeground = registerColor('editorError.foreground', { dark: '#F48771', light: '#E51400', hc: null }, nls.localize(38, null));
exports.editorErrorBorder = registerColor('editorError.border', { dark: null, light: null, hc: color_1.Color.fromHex('#E47777').transparent(0.8) }, nls.localize(39, null));
exports.editorWarningBackground = registerColor('editorWarning.background', { dark: null, light: null, hc: null }, nls.localize(40, null), true);
exports.editorWarningForeground = registerColor('editorWarning.foreground', { dark: '#CCA700', light: '#BF8803', hc: null }, nls.localize(41, null));
exports.editorWarningBorder = registerColor('editorWarning.border', { dark: null, light: null, hc: color_1.Color.fromHex('#FFCC00').transparent(0.8) }, nls.localize(42, null));
exports.editorInfoBackground = registerColor('editorInfo.background', { dark: null, light: null, hc: null }, nls.localize(43, null), true);
exports.editorInfoForeground = registerColor('editorInfo.foreground', { dark: '#75BEFF', light: '#75BEFF', hc: null }, nls.localize(44, null));
exports.editorInfoBorder = registerColor('editorInfo.border', { dark: null, light: null, hc: color_1.Color.fromHex('#75BEFF').transparent(0.8) }, nls.localize(45, null));
exports.editorHintForeground = registerColor('editorHint.foreground', { dark: color_1.Color.fromHex('#eeeeee').transparent(0.7), light: '#6c6c6c', hc: null }, nls.localize(46, null));
exports.editorHintBorder = registerColor('editorHint.border', { dark: null, light: null, hc: color_1.Color.fromHex('#eeeeee').transparent(0.8) }, nls.localize(47, null));
/**
* Editor background color.
* Because of bug https://monacotools.visualstudio.com/DefaultCollection/Monaco/_workitems/edit/13254
* we are *not* using the color white (or #ffffff, rgba(255,255,255)) but something very close to white.
*/
exports.editorBackground = registerColor('editor.background', { light: '#fffffe', dark: '#1E1E1E', hc: color_1.Color.black }, nls.localize(48, null));
/**
* Editor foreground color.
*/
exports.editorForeground = registerColor('editor.foreground', { light: '#333333', dark: '#BBBBBB', hc: color_1.Color.white }, nls.localize(49, null));
/**
* Editor widgets
*/
exports.editorWidgetBackground = registerColor('editorWidget.background', { dark: '#252526', light: '#F3F3F3', hc: '#0C141F' }, nls.localize(50, null));
exports.editorWidgetForeground = registerColor('editorWidget.foreground', { dark: exports.foreground, light: exports.foreground, hc: exports.foreground }, nls.localize(51, null));
exports.editorWidgetBorder = registerColor('editorWidget.border', { dark: '#454545', light: '#C8C8C8', hc: exports.contrastBorder }, nls.localize(52, null));
exports.editorWidgetResizeBorder = registerColor('editorWidget.resizeBorder', { light: null, dark: null, hc: null }, nls.localize(53, null));
/**
* Quick pick widget
*/
exports.quickInputBackground = registerColor('quickInput.background', { dark: exports.editorWidgetBackground, light: exports.editorWidgetBackground, hc: exports.editorWidgetBackground }, nls.localize(54, null));
exports.quickInputForeground = registerColor('quickInput.foreground', { dark: exports.editorWidgetForeground, light: exports.editorWidgetForeground, hc: exports.editorWidgetForeground }, nls.localize(55, null));
exports.quickInputTitleBackground = 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)), hc: '#000000' }, nls.localize(56, null));
exports.pickerGroupForeground = registerColor('pickerGroup.foreground', { dark: '#3794FF', light: '#0066BF', hc: color_1.Color.white }, nls.localize(57, null));
exports.pickerGroupBorder = registerColor('pickerGroup.border', { dark: '#3F3F46', light: '#CCCEDB', hc: color_1.Color.white }, nls.localize(58, null));
/**
* Keybinding label
*/
exports.keybindingLabelBackground = 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)), hc: color_1.Color.transparent }, nls.localize(59, null));
exports.keybindingLabelForeground = registerColor('keybindingLabel.foreground', { dark: color_1.Color.fromHex('#CCCCCC'), light: color_1.Color.fromHex('#555555'), hc: color_1.Color.white }, nls.localize(60, null));
exports.keybindingLabelBorder = 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)), hc: new color_1.Color(new color_1.RGBA(111, 195, 223)) }, nls.localize(61, null));
exports.keybindingLabelBottomBorder = 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)), hc: new color_1.Color(new color_1.RGBA(111, 195, 223)) }, nls.localize(62, null));
/**
* Editor selection colors.
*/
exports.editorSelectionBackground = registerColor('editor.selectionBackground', { light: '#ADD6FF', dark: '#264F78', hc: '#f3f518' }, nls.localize(63, null));
exports.editorSelectionForeground = registerColor('editor.selectionForeground', { light: null, dark: null, hc: '#000000' }, nls.localize(64, null));
exports.editorInactiveSelection = registerColor('editor.inactiveSelectionBackground', { light: transparent(exports.editorSelectionBackground, 0.5), dark: transparent(exports.editorSelectionBackground, 0.5), hc: transparent(exports.editorSelectionBackground, 0.5) }, nls.localize(65, null), true);
exports.editorSelectionHighlight = registerColor('editor.selectionHighlightBackground', { light: lessProminent(exports.editorSelectionBackground, exports.editorBackground, 0.3, 0.6), dark: lessProminent(exports.editorSelectionBackground, exports.editorBackground, 0.3, 0.6), hc: null }, nls.localize(66, null), true);
exports.editorSelectionHighlightBorder = registerColor('editor.selectionHighlightBorder', { light: null, dark: null, hc: exports.activeContrastBorder }, nls.localize(67, null));
/**
* Editor find match colors.
*/
exports.editorFindMatch = registerColor('editor.findMatchBackground', { light: '#A8AC94', dark: '#515C6A', hc: null }, nls.localize(68, null));
exports.editorFindMatchHighlight = registerColor('editor.findMatchHighlightBackground', { light: '#EA5C0055', dark: '#EA5C0055', hc: null }, nls.localize(69, null), true);
exports.editorFindRangeHighlight = registerColor('editor.findRangeHighlightBackground', { dark: '#3a3d4166', light: '#b4b4b44d', hc: null }, nls.localize(70, null), true);
exports.editorFindMatchBorder = registerColor('editor.findMatchBorder', { light: null, dark: null, hc: exports.activeContrastBorder }, nls.localize(71, null));
exports.editorFindMatchHighlightBorder = registerColor('editor.findMatchHighlightBorder', { light: null, dark: null, hc: exports.activeContrastBorder }, nls.localize(72, null));
exports.editorFindRangeHighlightBorder = registerColor('editor.findRangeHighlightBorder', { dark: null, light: null, hc: transparent(exports.activeContrastBorder, 0.4) }, nls.localize(73, null), true);
/**
* Editor hover
*/
exports.editorHoverHighlight = registerColor('editor.hoverHighlightBackground', { light: '#ADD6FF26', dark: '#264f7840', hc: '#ADD6FF26' }, nls.localize(74, null), true);
exports.editorHoverBackground = registerColor('editorHoverWidget.background', { light: exports.editorWidgetBackground, dark: exports.editorWidgetBackground, hc: exports.editorWidgetBackground }, nls.localize(75, null));
exports.editorHoverForeground = registerColor('editorHoverWidget.foreground', { light: exports.editorWidgetForeground, dark: exports.editorWidgetForeground, hc: exports.editorWidgetForeground }, nls.localize(76, null));
exports.editorHoverBorder = registerColor('editorHoverWidget.border', { light: exports.editorWidgetBorder, dark: exports.editorWidgetBorder, hc: exports.editorWidgetBorder }, nls.localize(77, null));
exports.editorHoverStatusBarBackground = registerColor('editorHoverWidget.statusBarBackground', { dark: lighten(exports.editorHoverBackground, 0.2), light: darken(exports.editorHoverBackground, 0.05), hc: exports.editorWidgetBackground }, nls.localize(78, null));
/**
* Editor link colors
*/
exports.editorActiveLinkForeground = registerColor('editorLink.activeForeground', { dark: '#4E94CE', light: color_1.Color.blue, hc: color_1.Color.cyan }, nls.localize(79, null));
/**
* Inline hints
*/
exports.editorInlayHintForeground = registerColor('editorInlayHint.foreground', { dark: transparent(exports.badgeForeground, .8), light: transparent(exports.badgeForeground, .8), hc: exports.badgeForeground }, nls.localize(80, null));
exports.editorInlayHintBackground = registerColor('editorInlayHint.background', { dark: transparent(exports.badgeBackground, .6), light: transparent(exports.badgeBackground, .3), hc: exports.badgeBackground }, nls.localize(81, null));
/**
* Editor lighbulb icon colors
*/
exports.editorLightBulbForeground = registerColor('editorLightBulb.foreground', { dark: '#FFCC00', light: '#DDB100', hc: '#FFCC00' }, nls.localize(82, null));
exports.editorLightBulbAutoFixForeground = registerColor('editorLightBulbAutoFix.foreground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, nls.localize(83, null));
/**
* Diff Editor Colors
*/
exports.defaultInsertColor = new color_1.Color(new color_1.RGBA(155, 185, 85, 0.2));
exports.defaultRemoveColor = new color_1.Color(new color_1.RGBA(255, 0, 0, 0.2));
exports.diffInserted = registerColor('diffEditor.insertedTextBackground', { dark: exports.defaultInsertColor, light: exports.defaultInsertColor, hc: null }, nls.localize(84, null), true);
exports.diffRemoved = registerColor('diffEditor.removedTextBackground', { dark: exports.defaultRemoveColor, light: exports.defaultRemoveColor, hc: null }, nls.localize(85, null), true);
exports.diffInsertedOutline = registerColor('diffEditor.insertedTextBorder', { dark: null, light: null, hc: '#33ff2eff' }, nls.localize(86, null));
exports.diffRemovedOutline = registerColor('diffEditor.removedTextBorder', { dark: null, light: null, hc: '#FF008F' }, nls.localize(87, null));
exports.diffBorder = registerColor('diffEditor.border', { dark: null, light: null, hc: exports.contrastBorder }, nls.localize(88, null));
exports.diffDiagonalFill = registerColor('diffEditor.diagonalFill', { dark: '#cccccc33', light: '#22222233', hc: null }, nls.localize(89, null));
/**
* List and tree colors
*/
exports.listFocusBackground = registerColor('list.focusBackground', { dark: null, light: null, hc: null }, nls.localize(90, null));
exports.listFocusForeground = registerColor('list.focusForeground', { dark: null, light: null, hc: null }, nls.localize(91, null));
exports.listFocusOutline = registerColor('list.focusOutline', { dark: exports.focusBorder, light: exports.focusBorder, hc: exports.activeContrastBorder }, nls.localize(92, null));
exports.listActiveSelectionBackground = registerColor('list.activeSelectionBackground', { dark: '#094771', light: '#0060C0', hc: null }, nls.localize(93, null));
exports.listActiveSelectionForeground = registerColor('list.activeSelectionForeground', { dark: color_1.Color.white, light: color_1.Color.white, hc: null }, nls.localize(94, null));
exports.listActiveSelectionIconForeground = registerColor('list.activeSelectionIconForeground', { dark: null, light: null, hc: null }, nls.localize(95, null));
exports.listInactiveSelectionBackground = registerColor('list.inactiveSelectionBackground', { dark: '#37373D', light: '#E4E6F1', hc: null }, nls.localize(96, null));
exports.listInactiveSelectionForeground = registerColor('list.inactiveSelectionForeground', { dark: null, light: null, hc: null }, nls.localize(97, null));
exports.listInactiveSelectionIconForeground = registerColor('list.inactiveSelectionIconForeground', { dark: null, light: null, hc: null }, nls.localize(98, null));
exports.listInactiveFocusBackground = registerColor('list.inactiveFocusBackground', { dark: null, light: null, hc: null }, nls.localize(99, null));
exports.listInactiveFocusOutline = registerColor('list.inactiveFocusOutline', { dark: null, light: null, hc: null }, nls.localize(100, null));
exports.listHoverBackground = registerColor('list.hoverBackground', { dark: '#2A2D2E', light: '#F0F0F0', hc: null }, nls.localize(101, null));
exports.listHoverForeground = registerColor('list.hoverForeground', { dark: null, light: null, hc: null }, nls.localize(102, null));
exports.listDropBackground = registerColor('list.dropBackground', { dark: '#062F4A', light: '#D6EBFF', hc: null }, nls.localize(103, null));
exports.listHighlightForeground = registerColor('list.highlightForeground', { dark: '#18A3FF', light: '#0066BF', hc: exports.focusBorder }, nls.localize(104, null));
exports.listFocusHighlightForeground = registerColor('list.focusHighlightForeground', { dark: exports.listHighlightForeground, light: ifDefinedThenElse(exports.listActiveSelectionBackground, exports.listHighlightForeground, '#9DDDFF'), hc: exports.listHighlightForeground }, nls.localize(105, null));
exports.listFilterWidgetBackground = registerColor('listFilterWidget.background', { light: '#efc1ad', dark: '#653723', hc: color_1.Color.black }, nls.localize(106, null));
exports.listFilterWidgetOutline = registerColor('listFilterWidget.outline', { dark: color_1.Color.transparent, light: color_1.Color.transparent, hc: '#f38518' }, nls.localize(107, null));
exports.listFilterWidgetNoMatchesOutline = registerColor('listFilterWidget.noMatchesOutline', { dark: '#BE1100', light: '#BE1100', hc: exports.contrastBorder }, nls.localize(108, null));
exports.treeIndentGuidesStroke = registerColor('tree.indentGuidesStroke', { dark: '#585858', light: '#a9a9a9', hc: '#a9a9a9' }, nls.localize(109, null));
exports.tableColumnsBorder = registerColor('tree.tableColumnsBorder', { dark: '#CCCCCC20', light: '#61616120', hc: null }, nls.localize(110, null));
/**
* Quick pick widget (dependent on List and tree colors)
*/
exports._deprecatedQuickInputListFocusBackground = registerColor('quickInput.list.focusBackground', { dark: null, light: null, hc: null }, '', undefined, nls.localize(111, null));
exports.quickInputListFocusForeground = registerColor('quickInputList.focusForeground', { dark: exports.listActiveSelectionForeground, light: exports.listActiveSelectionForeground, hc: exports.listActiveSelectionForeground }, nls.localize(112, null));
exports.quickInputListFocusIconForeground = registerColor('quickInputList.focusIconForeground', { dark: exports.listActiveSelectionIconForeground, light: exports.listActiveSelectionIconForeground, hc: exports.listActiveSelectionIconForeground }, nls.localize(113, null));
exports.quickInputListFocusBackground = registerColor('quickInputList.focusBackground', { dark: oneOf(exports._deprecatedQuickInputListFocusBackground, exports.listActiveSelectionBackground), light: oneOf(exports._deprecatedQuickInputListFocusBackground, exports.listActiveSelectionBackground), hc: null }, nls.localize(114, null));
/**
* Menu colors
*/
exports.menuBorder = registerColor('menu.border', { dark: null, light: null, hc: exports.contrastBorder }, nls.localize(115, null));
exports.menuForeground = registerColor('menu.foreground', { dark: exports.selectForeground, light: exports.foreground, hc: exports.selectForeground }, nls.localize(116, null));
exports.menuBackground = registerColor('menu.background', { dark: exports.selectBackground, light: exports.selectBackground, hc: exports.selectBackground }, nls.localize(117, null));
exports.menuSelectionForeground = registerColor('menu.selectionForeground', { dark: exports.listActiveSelectionForeground, light: exports.listActiveSelectionForeground, hc: exports.listActiveSelectionForeground }, nls.localize(118, null));
exports.menuSelectionBackground = registerColor('menu.selectionBackground', { dark: exports.listActiveSelectionBackground, light: exports.listActiveSelectionBackground, hc: exports.listActiveSelectionBackground }, nls.localize(119, null));
exports.menuSelectionBorder = registerColor('menu.selectionBorder', { dark: null, light: null, hc: exports.activeContrastBorder }, nls.localize(120, null));
exports.menuSeparatorBackground = registerColor('menu.separatorBackground', { dark: '#BBBBBB', light: '#888888', hc: exports.contrastBorder }, nls.localize(121, null));
/**
* Snippet placeholder colors
*/
exports.snippetTabstopHighlightBackground = 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)), hc: new color_1.Color(new color_1.RGBA(124, 124, 124, 0.3)) }, nls.localize(122, null));
exports.snippetTabstopHighlightBorder = registerColor('editor.snippetTabstopHighlightBorder', { dark: null, light: null, hc: null }, nls.localize(123, null));
exports.snippetFinalTabstopHighlightBackground = registerColor('editor.snippetFinalTabstopHighlightBackground', { dark: null, light: null, hc: null }, nls.localize(124, null));
exports.snippetFinalTabstopHighlightBorder = registerColor('editor.snippetFinalTabstopHighlightBorder', { dark: '#525252', light: new color_1.Color(new color_1.RGBA(10, 50, 100, 0.5)), hc: '#525252' }, nls.localize(125, null));
exports.overviewRulerFindMatchForeground = registerColor('editorOverviewRuler.findMatchForeground', { dark: '#d186167e', light: '#d186167e', hc: '#AB5A00' }, nls.localize(126, null), true);
exports.overviewRulerSelectionHighlightForeground = registerColor('editorOverviewRuler.selectionHighlightForeground', { dark: '#A0A0A0CC', light: '#A0A0A0CC', hc: '#A0A0A0CC' }, nls.localize(127, null), true);
exports.minimapFindMatch = registerColor('minimap.findMatchHighlight', { light: '#d18616', dark: '#d18616', hc: '#AB5A00' }, nls.localize(128, null), true);
exports.minimapSelection = registerColor('minimap.selectionHighlight', { light: '#ADD6FF', dark: '#264F78', hc: '#ffffff' }, nls.localize(129, null), true);
exports.minimapError = 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)), hc: new color_1.Color(new color_1.RGBA(255, 50, 50, 1)) }, nls.localize(130, null));
exports.minimapWarning = registerColor('minimap.warningHighlight', { dark: exports.editorWarningForeground, light: exports.editorWarningForeground, hc: exports.editorWarningBorder }, nls.localize(131, null));
exports.minimapBackground = registerColor('minimap.background', { dark: null, light: null, hc: null }, nls.localize(132, null));
exports.minimapSliderBackground = registerColor('minimapSlider.background', { light: transparent(exports.scrollbarSliderBackground, 0.5), dark: transparent(exports.scrollbarSliderBackground, 0.5), hc: transparent(exports.scrollbarSliderBackground, 0.5) }, nls.localize(133, null));
exports.minimapSliderHoverBackground = registerColor('minimapSlider.hoverBackground', { light: transparent(exports.scrollbarSliderHoverBackground, 0.5), dark: transparent(exports.scrollbarSliderHoverBackground, 0.5), hc: transparent(exports.scrollbarSliderHoverBackground, 0.5) }, nls.localize(134, null));
exports.minimapSliderActiveBackground = registerColor('minimapSlider.activeBackground', { light: transparent(exports.scrollbarSliderActiveBackground, 0.5), dark: transparent(exports.scrollbarSliderActiveBackground, 0.5), hc: transparent(exports.scrollbarSliderActiveBackground, 0.5) }, nls.localize(135, null));
exports.problemsErrorIconForeground = registerColor('problemsErrorIcon.foreground', { dark: exports.editorErrorForeground, light: exports.editorErrorForeground, hc: exports.editorErrorForeground }, nls.localize(136, null));
exports.problemsWarningIconForeground = registerColor('problemsWarningIcon.foreground', { dark: exports.editorWarningForeground, light: exports.editorWarningForeground, hc: exports.editorWarningForeground }, nls.localize(137, null));
exports.problemsInfoIconForeground = registerColor('problemsInfoIcon.foreground', { dark: exports.editorInfoForeground, light: exports.editorInfoForeground, hc: exports.editorInfoForeground }, nls.localize(138, null));
// ----- color functions
function executeTransform(transform, theme) {
var _a, _b, _c;
switch (transform.op) {
case 0 /* Darken */:
return (_a = resolveColorValue(transform.value, theme)) === null || _a === void 0 ? void 0 : _a.darken(transform.factor);
case 1 /* Lighten */:
return (_b = resolveColorValue(transform.value, theme)) === null || _b === void 0 ? void 0 : _b.lighten(transform.factor);
case 2 /* Transparent */:
return (_c = resolveColorValue(transform.value, theme)) === null || _c === void 0 ? void 0 : _c.transparent(transform.factor);
case 3 /* OneOf */:
for (const candidate of transform.values) {
const color = resolveColorValue(candidate, theme);
if (color) {
return color;
}
}
return undefined;
case 5 /* IfDefinedThenElse */:
return resolveColorValue(theme.defines(transform.if) ? transform.then : transform.else, theme);
case 4 /* 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, types_1.assertNever)(transform);
}
}
exports.executeTransform = executeTransform;
function darken(colorValue, factor) {
return { op: 0 /* Darken */, value: colorValue, factor };
}
exports.darken = darken;
function lighten(colorValue, factor) {
return { op: 1 /* Lighten */, value: colorValue, factor };
}
exports.lighten = lighten;
function transparent(colorValue, factor) {
return { op: 2 /* Transparent */, value: colorValue, factor };
}
exports.transparent = transparent;
function oneOf(...colorValues) {
return { op: 3 /* OneOf */, values: colorValues };
}
exports.oneOf = oneOf;
function ifDefinedThenElse(ifArg, thenArg, elseArg) {
return { op: 5 /* IfDefinedThenElse */, if: ifArg, then: thenArg, else: elseArg };
}
exports.ifDefinedThenElse = ifDefinedThenElse;
function lessProminent(colorValue, backgroundColorValue, factor, transparency) {
return { op: 4 /* 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.resolveColorValue = resolveColorValue;
exports.workbenchColorsSchemaId = 'vscode://schemas/workbench-colors';
let 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[122/*vs/platform/theme/common/styler*/], __M([0/*require*/,1/*exports*/,22/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, colorRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.attachMenuStyler = exports.defaultMenuStyles = exports.defaultListStyles = exports.attachListStyler = exports.attachBadgeStyler = exports.attachStyler = exports.computeStyles = void 0;
function computeStyles(theme, styleMap) {
const styles = Object.create(null);
for (let key in styleMap) {
const value = styleMap[key];
if (value) {
styles[key] = (0, colorRegistry_1.resolveColorValue)(value, theme);
}
}
return styles;
}
exports.computeStyles = computeStyles;
function attachStyler(themeService, styleMap, widgetOrCallback) {
function applyStyles() {
const styles = computeStyles(themeService.getColorTheme(), styleMap);
if (typeof widgetOrCallback === 'function') {
widgetOrCallback(styles);
}
else {
widgetOrCallback.style(styles);
}
}
applyStyles();
return themeService.onDidColorThemeChange(applyStyles);
}
exports.attachStyler = attachStyler;
function attachBadgeStyler(widget, themeService, style) {
return attachStyler(themeService, {
badgeBackground: (style === null || style === void 0 ? void 0 : style.badgeBackground) || colorRegistry_1.badgeBackground,
badgeForeground: (style === null || style === void 0 ? void 0 : style.badgeForeground) || colorRegistry_1.badgeForeground,
badgeBorder: colorRegistry_1.contrastBorder
}, widget);
}
exports.attachBadgeStyler = attachBadgeStyler;
function attachListStyler(widget, themeService, overrides) {
return attachStyler(themeService, Object.assign(Object.assign({}, exports.defaultListStyles), (overrides || {})), widget);
}
exports.attachListStyler = attachListStyler;
exports.defaultListStyles = {
listFocusBackground: colorRegistry_1.listFocusBackground,
listFocusForeground: colorRegistry_1.listFocusForeground,
listFocusOutline: colorRegistry_1.listFocusOutline,
listActiveSelectionBackground: colorRegistry_1.listActiveSelectionBackground,
listActiveSelectionForeground: colorRegistry_1.listActiveSelectionForeground,
listActiveSelectionIconForeground: colorRegistry_1.listActiveSelectionIconForeground,
listFocusAndSelectionBackground: colorRegistry_1.listActiveSelectionBackground,
listFocusAndSelectionForeground: colorRegistry_1.listActiveSelectionForeground,
listInactiveSelectionBackground: colorRegistry_1.listInactiveSelectionBackground,
listInactiveSelectionIconForeground: colorRegistry_1.listInactiveSelectionIconForeground,
listInactiveSelectionForeground: colorRegistry_1.listInactiveSelectionForeground,
listInactiveFocusBackground: colorRegistry_1.listInactiveFocusBackground,
listInactiveFocusOutline: colorRegistry_1.listInactiveFocusOutline,
listHoverBackground: colorRegistry_1.listHoverBackground,
listHoverForeground: colorRegistry_1.listHoverForeground,
listDropBackground: colorRegistry_1.listDropBackground,
listSelectionOutline: colorRegistry_1.activeContrastBorder,
listHoverOutline: colorRegistry_1.activeContrastBorder,
listFilterWidgetBackground: colorRegistry_1.listFilterWidgetBackground,
listFilterWidgetOutline: colorRegistry_1.listFilterWidgetOutline,
listFilterWidgetNoMatchesOutline: colorRegistry_1.listFilterWidgetNoMatchesOutline,
listMatchesShadow: colorRegistry_1.widgetShadow,
treeIndentGuidesStroke: colorRegistry_1.treeIndentGuidesStroke,
tableColumnsBorder: colorRegistry_1.tableColumnsBorder
};
exports.defaultMenuStyles = {
shadowColor: colorRegistry_1.widgetShadow,
borderColor: colorRegistry_1.menuBorder,
foregroundColor: colorRegistry_1.menuForeground,
backgroundColor: colorRegistry_1.menuBackground,
selectionForegroundColor: colorRegistry_1.menuSelectionForeground,
selectionBackgroundColor: colorRegistry_1.menuSelectionBackground,
selectionBorderColor: colorRegistry_1.menuSelectionBorder,
separatorColor: colorRegistry_1.menuSeparatorBackground
};
function attachMenuStyler(widget, themeService, style) {
return attachStyler(themeService, Object.assign(Object.assign({}, exports.defaultMenuStyles), style), widget);
}
exports.attachMenuStyler = attachMenuStyler;
});
/*---------------------------------------------------------------------------------------------
* 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/platform/contextview/browser/contextMenuHandler*/], __M([0/*require*/,1/*exports*/,50/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,444/*vs/base/browser/ui/menu/menu*/,7/*vs/base/browser/dom*/,122/*vs/platform/theme/common/styler*/,55/*vs/base/browser/mouseEvent*/,12/*vs/base/common/errors*/,369/*vs/css!vs/platform/contextview/browser/contextMenuHandler*/]), function (require, exports, actions_1, lifecycle_1, menu_1, dom_1, styler_1, mouseEvent_1, errors_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextMenuHandler = void 0;
class ContextMenuHandler {
constructor(contextViewService, telemetryService, notificationService, keybindingService, themeService) {
this.contextViewService = contextViewService;
this.telemetryService = telemetryService;
this.notificationService = notificationService;
this.keybindingService = keybindingService;
this.themeService = themeService;
this.focusToReturn = null;
this.block = 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 = document.activeElement;
let menu;
let 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) => {
let 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';
// TODO@Steven: this is never getting disposed
(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.onBeforeRun(this.onActionRun, 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)
});
menuDisposables.add((0, styler_1.attachMenuStyler)(menu, this.themeService));
menu.onDidCancel(() => this.contextViewService.hideContextView(true), null, menuDisposables);
menu.onDidBlur(() => this.contextViewService.hideContextView(true), null, menuDisposables);
menuDisposables.add((0, dom_1.addDisposableListener)(window, dom_1.EventType.BLUR, () => this.contextViewService.hideContextView(true)));
menuDisposables.add((0, dom_1.addDisposableListener)(window, dom_1.EventType.MOUSE_DOWN, (e) => {
if (e.defaultPrevented) {
return;
}
let event = new mouseEvent_1.StandardMouseEvent(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: () => {
if (menu) {
menu.focus(!!delegate.autoSelectFirstItem);
}
},
onHide: (didCancel) => {
if (delegate.onHide) {
delegate.onHide(!!didCancel);
}
if (this.block) {
this.block.remove();
this.block = null;
}
if (this.focusToReturn) {
this.focusToReturn.focus();
}
}
}, shadowRootElement, !!shadowRootElement);
}
onActionRun(e) {
this.telemetryService.publicLog2('workbenchActionExecuted', { id: e.action.id, from: 'contextMenu' });
this.contextViewService.hideContextView(false);
// Restore focus here
if (this.focusToReturn) {
this.focusToReturn.focus();
}
}
onDidActionRun(e) {
if (e.error && !(0, errors_1.isPromiseCanceledError)(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[100/*vs/platform/theme/common/theme*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ColorScheme = void 0;
/**
* Color scheme used by the OS and by color themes.
*/
var ColorScheme;
(function (ColorScheme) {
ColorScheme["DARK"] = "dark";
ColorScheme["LIGHT"] = "light";
ColorScheme["HIGH_CONTRAST"] = "hc";
})(ColorScheme = exports.ColorScheme || (exports.ColorScheme = {}));
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[258/*vs/editor/browser/viewParts/lines/viewLine*/], __M([0/*require*/,1/*exports*/,39/*vs/base/browser/browser*/,30/*vs/base/browser/fastDomNode*/,17/*vs/base/common/platform*/,392/*vs/editor/browser/viewParts/lines/rangeUtil*/,113/*vs/editor/common/view/renderingContext*/,136/*vs/editor/common/viewLayout/lineDecorations*/,114/*vs/editor/common/viewLayout/viewLineRenderer*/,100/*vs/platform/theme/common/theme*/,35/*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 = exports.DomReadingContext = void 0;
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 DomReadingContext {
constructor(domNode, endNode) {
this._domNode = domNode;
this._clientRectDeltaLeft = 0;
this._clientRectDeltaLeftRead = false;
this.endNode = endNode;
}
get clientRectDeltaLeft() {
if (!this._clientRectDeltaLeftRead) {
this._clientRectDeltaLeftRead = true;
this._clientRectDeltaLeft = this._domNode.getBoundingClientRect().left;
}
return this._clientRectDeltaLeft;
}
}
exports.DomReadingContext = DomReadingContext;
class ViewLineOptions {
constructor(config, themeType) {
this.themeType = themeType;
const options = config.options;
const fontInfo = options.get(41 /* fontInfo */);
this.renderWhitespace = options.get(87 /* renderWhitespace */);
this.renderControlCharacters = options.get(81 /* renderControlCharacters */);
this.spaceWidth = fontInfo.spaceWidth;
this.middotWidth = fontInfo.middotWidth;
this.wsmiddotWidth = fontInfo.wsmiddotWidth;
this.useMonospaceOptimizations = (fontInfo.isMonospace
&& !options.get(27 /* disableMonospaceOptimizations */));
this.canUseHalfwidthRightwardsArrow = fontInfo.canUseHalfwidthRightwardsArrow;
this.lineHeight = options.get(57 /* lineHeight */);
this.stopRenderingLineAfter = options.get(104 /* stopRenderingLineAfter */);
this.fontLigatures = options.get(42 /* 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 {
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 (this._options.themeType === theme_1.ColorScheme.HIGH_CONTRAST || this._options.renderWhitespace === 'selection') {
this._isMaybeInvalid = true;
return true;
}
return false;
}
renderLine(lineNumber, deltaTop, 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 (options.themeType === theme_1.ColorScheme.HIGH_CONTRAST || 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 (options.themeType === theme_1.ColorScheme.HIGH_CONTRAST || this._options.renderWhitespace !== 'selection') {
actualInlineDecorations.push(new lineDecorations_1.LineDecoration(startColumn, endColumn, 'inline-selected-text', 0 /* Regular */));
}
else {
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.appendASCIIString('<div style="top:');
sb.appendASCIIString(String(deltaTop));
sb.appendASCIIString('px;height:');
sb.appendASCIIString(String(this._options.lineHeight));
sb.appendASCIIString('px;" class="');
sb.appendASCIIString(ViewLine.CLASS_NAME);
sb.appendASCIIString('">');
const output = (0, viewLineRenderer_1.renderViewLine)(renderLineInput, sb);
sb.appendASCIIString('</div>');
let renderedViewLine = null;
if (monospaceAssumptionsAreValid && canUseFastRenderedViewLine && lineData.isBasicASCII && options.useMonospaceOptimizations && output.containsForeignElements === 0 /* None */) {
if (lineData.content.length < 300 && renderLineInput.lineTokens.getCount() < 100) {
// Browser rounding errors have been observed in Chrome and IE, so using the fast
// view line only for short lines. Please test before removing the length check...
// ---
// Another rounding error has been observed on Linux in VSCode, where <span> width
// rounding errors add up to an observable large number...
// ---
// Also see another example of rounding errors on Windows in
// https://github.com/microsoft/vscode/issues/33178
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) {
if (this._renderedViewLine && this._renderedViewLine.domNode) {
this._renderedViewLine.domNode.setTop(deltaTop);
this._renderedViewLine.domNode.setHeight(this._options.lineHeight);
}
}
// --- end IVisibleLineData
getWidth() {
if (!this._renderedViewLine) {
return 0;
}
return this._renderedViewLine.getWidth();
}
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(startColumn, endColumn, context) {
if (!this._renderedViewLine) {
return null;
}
startColumn = startColumn | 0; // @perf
endColumn = endColumn | 0; // @perf
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 | 0; // @perf
let outsideRenderedLine = false;
if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1 && endColumn > stopRenderingLineAfter + 1) {
// This range is obviously not visible
outsideRenderedLine = true;
}
if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1) {
startColumn = stopRenderingLineAfter + 1;
}
if (stopRenderingLineAfter !== -1 && endColumn > stopRenderingLineAfter + 1) {
endColumn = stopRenderingLineAfter + 1;
}
const horizontalRanges = this._renderedViewLine.getVisibleRangesForRange(startColumn, endColumn, context);
if (horizontalRanges && horizontalRanges.length > 0) {
return new renderingContext_1.VisibleRanges(outsideRenderedLine, horizontalRanges);
}
return null;
}
getColumnOfNodeOffset(lineNumber, spanNode, offset) {
if (!this._renderedViewLine) {
return 1;
}
return this._renderedViewLine.getColumnOfNodeOffset(lineNumber, spanNode, offset);
}
}
exports.ViewLine = ViewLine;
ViewLine.CLASS_NAME = 'view-line';
/**
* 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.domNode = domNode;
this.input = renderLineInput;
this._characterMapping = characterMapping;
this._charWidth = renderLineInput.spaceWidth;
}
getWidth() {
return this._getCharPosition(this._characterMapping.length);
}
getWidthIsFast() {
return true;
}
monospaceAssumptionsAreValid() {
if (!this.domNode) {
return monospaceAssumptionsAreValid;
}
const expectedWidth = this.getWidth();
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 /* None */);
}
getVisibleRangesForRange(startColumn, endColumn, context) {
const startPosition = this._getCharPosition(startColumn);
const endPosition = this._getCharPosition(endColumn);
return [new renderingContext_1.HorizontalRange(startPosition, endPosition - startPosition)];
}
_getCharPosition(column) {
const charOffset = this._characterMapping.getAbsoluteOffset(column);
return Math.round(this._charWidth * charOffset);
}
getColumnOfNodeOffset(lineNumber, spanNode, offset) {
const spanNodeTextContentLength = spanNode.textContent.length;
let spanIndex = -1;
while (spanNode) {
spanNode = spanNode.previousSibling;
spanIndex++;
}
return this._characterMapping.getColumn(new viewLineRenderer_1.DomPosition(spanIndex, offset), spanNodeTextContentLength);
}
}
/**
* 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 Int32Array(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() {
if (!this.domNode) {
return 0;
}
if (this._cachedWidth === -1) {
this._cachedWidth = this._getReadingTarget(this.domNode).offsetWidth;
}
return this._cachedWidth;
}
getWidthIsFast() {
if (this._cachedWidth === -1) {
return false;
}
return true;
}
/**
* Visible ranges for a model range
*/
getVisibleRangesForRange(startColumn, endColumn, context) {
if (!this.domNode) {
return null;
}
if (this._pixelOffsetCache !== null) {
// the text is LTR
const startOffset = this._readPixelOffset(this.domNode, startColumn, context);
if (startOffset === -1) {
return null;
}
const endOffset = this._readPixelOffset(this.domNode, endColumn, context);
if (endOffset === -1) {
return null;
}
return [new renderingContext_1.HorizontalRange(startOffset, endOffset - startOffset)];
}
return this._readVisibleRangesForRange(this.domNode, startColumn, endColumn, context);
}
_readVisibleRangesForRange(domNode, startColumn, endColumn, context) {
if (startColumn === endColumn) {
const pixelOffset = this._readPixelOffset(domNode, startColumn, context);
if (pixelOffset === -1) {
return null;
}
else {
return [new renderingContext_1.HorizontalRange(pixelOffset, 0)];
}
}
else {
return this._readRawVisibleRangesForRange(domNode, startColumn, endColumn, context);
}
}
_readPixelOffset(domNode, column, context) {
if (this._characterMapping.length === 0) {
// This line has no content
if (this._containsForeignElements === 0 /* None */) {
// We can assume the line is really empty
return 0;
}
if (this._containsForeignElements === 2 /* After */) {
// We have foreign elements after the (empty) line
return 0;
}
if (this._containsForeignElements === 1 /* Before */) {
// We have foreign elements before the (empty) line
return this.getWidth();
}
// We have foreign elements before & after the (empty) line
const readingTarget = this._getReadingTarget(domNode);
if (readingTarget.firstChild) {
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, column, context);
this._pixelOffsetCache[column] = result;
return result;
}
return this._actualReadPixelOffset(domNode, column, context);
}
_actualReadPixelOffset(domNode, 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.clientRectDeltaLeft, context.endNode);
if (!r || r.length === 0) {
return -1;
}
return r[0].left;
}
if (column === this._characterMapping.length && this._isWhitespaceOnly && this._containsForeignElements === 0 /* None */) {
// This branch helps in the case of whitespace only lines which have a width set
return this.getWidth();
}
const domPosition = this._characterMapping.getDomPosition(column);
const r = rangeUtil_1.RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), domPosition.partIndex, domPosition.charIndex, domPosition.partIndex, domPosition.charIndex, context.clientRectDeltaLeft, context.endNode);
if (!r || r.length === 0) {
return -1;
}
const result = r[0].left;
if (this.input.isBasicASCII) {
const charOffset = this._characterMapping.getAbsoluteOffset(column);
const expectedResult = Math.round(this.input.spaceWidth * charOffset);
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.HorizontalRange(0, this.getWidth())];
}
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.clientRectDeltaLeft, context.endNode);
}
/**
* Returns the column for the text found at a specific offset inside a rendered dom node
*/
getColumnOfNodeOffset(lineNumber, spanNode, offset) {
const spanNodeTextContentLength = spanNode.textContent.length;
let spanIndex = -1;
while (spanNode) {
spanNode = spanNode.previousSibling;
spanIndex++;
}
return this._characterMapping.getColumn(new viewLineRenderer_1.DomPosition(spanIndex, offset), spanNodeTextContentLength);
}
}
class WebKitRenderedViewLine extends RenderedViewLine {
_readVisibleRangesForRange(domNode, startColumn, endColumn, context) {
const output = super._readVisibleRangesForRange(domNode, 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, 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);
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[191/*vs/editor/browser/controller/mouseTarget*/], __M([0/*require*/,1/*exports*/,167/*vs/editor/browser/editorDom*/,47/*vs/editor/browser/view/viewPart*/,258/*vs/editor/browser/viewParts/lines/viewLine*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,40/*vs/editor/common/controller/cursorCommon*/,7/*vs/base/browser/dom*/,243/*vs/editor/common/controller/cursorAtomicMoveOperations*/]), function (require, exports, editorDom_1, viewPart_1, viewLine_1, position_1, range_1, cursorCommon_1, dom, cursorAtomicMoveOperations_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.shadowCaretRangeFromPoint = exports.MouseTargetFactory = exports.HitTestContext = exports.MouseTarget = exports.PointerHandlerLastRenderData = void 0;
class UnknownHitTestResult {
constructor(hitTarget = null) {
this.hitTarget = hitTarget;
this.type = 0 /* Unknown */;
}
}
class ContentHitTestResult {
constructor(position, spanNode, injectedText) {
this.position = position;
this.spanNode = spanNode;
this.injectedText = injectedText;
this.type = 1 /* 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 {
constructor(element, type, mouseColumn = 0, position = null, range = null, detail = null) {
this.element = element;
this.type = type;
this.mouseColumn = mouseColumn;
this.position = position;
if (!range && position) {
range = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column);
}
this.range = range;
this.detail = detail;
}
static _typeToString(type) {
if (type === 1 /* TEXTAREA */) {
return 'TEXTAREA';
}
if (type === 2 /* GUTTER_GLYPH_MARGIN */) {
return 'GUTTER_GLYPH_MARGIN';
}
if (type === 3 /* GUTTER_LINE_NUMBERS */) {
return 'GUTTER_LINE_NUMBERS';
}
if (type === 4 /* GUTTER_LINE_DECORATIONS */) {
return 'GUTTER_LINE_DECORATIONS';
}
if (type === 5 /* GUTTER_VIEW_ZONE */) {
return 'GUTTER_VIEW_ZONE';
}
if (type === 6 /* CONTENT_TEXT */) {
return 'CONTENT_TEXT';
}
if (type === 7 /* CONTENT_EMPTY */) {
return 'CONTENT_EMPTY';
}
if (type === 8 /* CONTENT_VIEW_ZONE */) {
return 'CONTENT_VIEW_ZONE';
}
if (type === 9 /* CONTENT_WIDGET */) {
return 'CONTENT_WIDGET';
}
if (type === 10 /* OVERVIEW_RULER */) {
return 'OVERVIEW_RULER';
}
if (type === 11 /* SCROLLBAR */) {
return 'SCROLLBAR';
}
if (type === 12 /* OVERLAY_WIDGET */) {
return 'OVERLAY_WIDGET';
}
return 'UNKNOWN';
}
static toString(target) {
return this._typeToString(target.type) + ': ' + target.position + ' - ' + target.range + ' - ' + target.detail;
}
toString() {
return MouseTarget.toString(this);
}
}
exports.MouseTarget = MouseTarget;
class ElementPath {
static isTextArea(path) {
return (path.length === 2
&& path[0] === 3 /* OverflowGuard */
&& path[1] === 6 /* TextArea */);
}
static isChildOfViewLines(path) {
return (path.length >= 4
&& path[0] === 3 /* OverflowGuard */
&& path[3] === 7 /* ViewLines */);
}
static isStrictChildOfViewLines(path) {
return (path.length > 4
&& path[0] === 3 /* OverflowGuard */
&& path[3] === 7 /* ViewLines */);
}
static isChildOfScrollableElement(path) {
return (path.length >= 2
&& path[0] === 3 /* OverflowGuard */
&& path[1] === 5 /* ScrollableElement */);
}
static isChildOfMinimap(path) {
return (path.length >= 2
&& path[0] === 3 /* OverflowGuard */
&& path[1] === 8 /* Minimap */);
}
static isChildOfContentWidgets(path) {
return (path.length >= 4
&& path[0] === 3 /* OverflowGuard */
&& path[3] === 1 /* ContentWidgets */);
}
static isChildOfOverflowingContentWidgets(path) {
return (path.length >= 1
&& path[0] === 2 /* OverflowingContentWidgets */);
}
static isChildOfOverlayWidgets(path) {
return (path.length >= 2
&& path[0] === 3 /* OverflowGuard */
&& path[1] === 4 /* OverlayWidgets */);
}
}
class HitTestContext {
constructor(context, viewHelper, lastRenderData) {
this.model = context.model;
const options = context.configuration.options;
this.layoutInfo = options.get(129 /* layoutInfo */);
this.viewDomNode = viewHelper.viewDomNode;
this.lineHeight = options.get(57 /* lineHeight */);
this.stickyTabStops = options.get(103 /* stickyTabStops */);
this.typicalHalfwidthCharacterWidth = options.get(41 /* 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.model.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.model.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.model.getLineCount();
const maxLineColumn = this._context.model.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.model.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 !== document.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) {
this.editorPos = editorPos;
this.pos = pos;
this.mouseVerticalOffset = Math.max(0, ctx.getCurrentScrollTop() + pos.y - editorPos.y);
this.mouseContentHorizontalOffset = ctx.getCurrentScrollLeft() + pos.x - editorPos.x - ctx.layoutInfo.contentLeft;
this.isInMarginArea = (pos.x - editorPos.x < ctx.layoutInfo.contentLeft && pos.x - editorPos.x >= ctx.layoutInfo.glyphMarginLeft);
this.isInContentArea = !this.isInMarginArea;
this.mouseColumn = Math.max(0, MouseTargetFactory._getMouseColumn(this.mouseContentHorizontalOffset, ctx.typicalHalfwidthCharacterWidth));
}
}
class HitTestRequest extends BareHitTestRequest {
constructor(ctx, editorPos, pos, target) {
super(ctx, editorPos, pos);
this._ctx = ctx;
if (target) {
this.target = target;
this.targetPath = viewPart_1.PartFingerprints.collect(target, ctx.viewDomNode);
}
else {
this.target = null;
this.targetPath = new Uint8Array(0);
}
}
toString() {
return `pos(${this.pos.x},${this.pos.y}), editorPos(${this.editorPos.x},${this.editorPos.y}), mouseVerticalOffset: ${this.mouseVerticalOffset}, mouseContentHorizontalOffset: ${this.mouseContentHorizontalOffset}\n\ttarget: ${this.target ? this.target.outerHTML : null}`;
}
// public fulfill(type: MouseTargetType.OVERVIEW_RULER, position?: Position | null, range?: EditorRange | null, detail?: any): MouseTarget;
// public fulfill(type: MouseTargetType.OUTSIDE_EDITOR, position?: Position | null, range?: EditorRange | null, detail?: any): MouseTarget;
fulfill(type, position = null, range = null, detail = null) {
let mouseColumn = this.mouseColumn;
if (position && position.column < this._ctx.model.getLineMaxColumn(position.lineNumber)) {
// Most likely, the line contains foreign decorations...
mouseColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(this._ctx.model.getLineContent(position.lineNumber), position.column, this._ctx.model.getTextModelOptions().tabSize) + 1;
}
return new MouseTarget(this.target, type, mouseColumn, position, range, detail);
}
withTarget(target) {
return new HitTestRequest(this._ctx, this.editorPos, this.pos, target);
}
}
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)) {
return true;
}
return false;
}
createMouseTarget(lastRenderData, editorPos, pos, target) {
const ctx = new HitTestContext(this._context, this._viewHelper, lastRenderData);
const request = new HitTestRequest(ctx, editorPos, pos, target);
try {
const r = MouseTargetFactory._createMouseTarget(ctx, request, false);
// console.log(r.toString());
return r;
}
catch (err) {
// console.log(err);
return request.fulfill(0 /* UNKNOWN */);
}
}
static _createMouseTarget(ctx, request, domHitTestExecuted) {
// console.log(`${domHitTestExecuted ? '=>' : ''}CAME IN REQUEST: ${request}`);
// First ensure the request has a target
if (request.target === null) {
if (domHitTestExecuted) {
// Still no target... and we have already executed hit test...
return request.fulfill(0 /* UNKNOWN */);
}
const hitTestResult = MouseTargetFactory._doHitTest(ctx, request);
if (hitTestResult.type === 1 /* Content */) {
return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request, hitTestResult.spanNode, hitTestResult.position, hitTestResult.injectedText);
}
return this._createMouseTarget(ctx, request.withTarget(hitTestResult.hitTarget), true);
}
// we know for a fact that request.target is not null
const resolvedRequest = request;
let result = null;
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, domHitTestExecuted);
result = result || MouseTargetFactory._hitTestScrollbar(ctx, resolvedRequest);
return (result || request.fulfill(0 /* UNKNOWN */));
}
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.fulfill(9 /* CONTENT_WIDGET */, null, null, widgetId);
}
else {
return request.fulfill(0 /* UNKNOWN */);
}
}
return null;
}
static _hitTestOverlayWidget(ctx, request) {
// Is it an overlay widget?
if (ElementPath.isChildOfOverlayWidgets(request.targetPath)) {
const widgetId = ctx.findAttribute(request.target, 'widgetId');
if (widgetId) {
return request.fulfill(12 /* OVERLAY_WIDGET */, null, null, widgetId);
}
else {
return request.fulfill(0 /* UNKNOWN */);
}
}
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.fulfill(6 /* CONTENT_TEXT */, d.position, null, { mightBeForeignElement: false });
}
}
}
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.fulfill(6 /* CONTENT_TEXT */, d.position, null, { mightBeForeignElement: false });
}
}
}
return null;
}
static _hitTestViewZone(ctx, request) {
const viewZoneData = ctx.getZoneAtCoord(request.mouseVerticalOffset);
if (viewZoneData) {
const mouseTargetType = (request.isInContentArea ? 8 /* CONTENT_VIEW_ZONE */ : 5 /* GUTTER_VIEW_ZONE */);
return request.fulfill(mouseTargetType, viewZoneData.position, null, viewZoneData);
}
return null;
}
static _hitTestTextArea(ctx, request) {
// Is it the textarea?
if (ElementPath.isTextArea(request.targetPath)) {
if (ctx.lastRenderData.lastTextareaPosition) {
return request.fulfill(6 /* CONTENT_TEXT */, ctx.lastRenderData.lastTextareaPosition, null, { mightBeForeignElement: false });
}
return request.fulfill(1 /* TEXTAREA */, ctx.lastRenderData.lastTextareaPosition);
}
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.pos.x - request.editorPos.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
return request.fulfill(2 /* GUTTER_GLYPH_MARGIN */, pos, res.range, detail);
}
offset -= ctx.layoutInfo.glyphMarginWidth;
if (offset <= ctx.layoutInfo.lineNumbersWidth) {
// On the line numbers
return request.fulfill(3 /* GUTTER_LINE_NUMBERS */, pos, res.range, detail);
}
offset -= ctx.layoutInfo.lineNumbersWidth;
// On the line decorations
return request.fulfill(4 /* GUTTER_LINE_DECORATIONS */, pos, res.range, detail);
}
return null;
}
static _hitTestViewLines(ctx, request, domHitTestExecuted) {
if (!ElementPath.isChildOfViewLines(request.targetPath)) {
return null;
}
if (ctx.isInTopPadding(request.mouseVerticalOffset)) {
return request.fulfill(7 /* CONTENT_EMPTY */, new position_1.Position(1, 1), null, 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.model.getLineCount();
const maxLineColumn = ctx.model.getLineMaxColumn(lineCount);
return request.fulfill(7 /* CONTENT_EMPTY */, new position_1.Position(lineCount, maxLineColumn), null, EMPTY_CONTENT_AFTER_LINES);
}
if (domHitTestExecuted) {
// 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.model.getLineLength(lineNumber) === 0) {
const lineWidth = ctx.getLineWidth(lineNumber);
const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
return request.fulfill(7 /* CONTENT_EMPTY */, new position_1.Position(lineNumber, 1), null, detail);
}
const lineWidth = ctx.getLineWidth(lineNumber);
if (request.mouseContentHorizontalOffset >= lineWidth) {
const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
const pos = new position_1.Position(lineNumber, ctx.model.getLineMaxColumn(lineNumber));
return request.fulfill(7 /* CONTENT_EMPTY */, pos, null, detail);
}
}
// We have already executed hit test...
return request.fulfill(0 /* UNKNOWN */);
}
const hitTestResult = MouseTargetFactory._doHitTest(ctx, request);
if (hitTestResult.type === 1 /* Content */) {
return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request, hitTestResult.spanNode, hitTestResult.position, hitTestResult.injectedText);
}
return this._createMouseTarget(ctx, request.withTarget(hitTestResult.hitTarget), true);
}
static _hitTestMinimap(ctx, request) {
if (ElementPath.isChildOfMinimap(request.targetPath)) {
const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
const maxColumn = ctx.model.getLineMaxColumn(possibleLineNumber);
return request.fulfill(11 /* SCROLLBAR */, 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.model.getLineMaxColumn(possibleLineNumber);
return request.fulfill(11 /* SCROLLBAR */, 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.model.getLineMaxColumn(possibleLineNumber);
return request.fulfill(11 /* SCROLLBAR */, new position_1.Position(possibleLineNumber, maxColumn));
}
return null;
}
getMouseColumn(editorPos, pos) {
const options = this._context.configuration.options;
const layoutInfo = options.get(129 /* layoutInfo */);
const mouseContentHorizontalOffset = this._context.viewLayout.getCurrentScrollLeft() + pos.x - editorPos.x - layoutInfo.contentLeft;
return MouseTargetFactory._getMouseColumn(mouseContentHorizontalOffset, options.get(41 /* 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.fulfill(7 /* CONTENT_EMPTY */, pos, null, detail);
}
const visibleRange = ctx.visibleRangeForPosition(lineNumber, column);
if (!visibleRange) {
return request.fulfill(0 /* UNKNOWN */, pos);
}
const columnHorizontalOffset = visibleRange.left;
if (request.mouseContentHorizontalOffset === columnHorizontalOffset) {
return request.fulfill(6 /* CONTENT_TEXT */, pos, null, { mightBeForeignElement: !!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.model.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();
const spanNodeClientRect = spanNode.getBoundingClientRect();
const mouseIsOverSpanNode = (spanNodeClientRect.left <= mouseCoordinates.clientX && mouseCoordinates.clientX <= spanNodeClientRect.right);
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) {
const rng = new range_1.Range(lineNumber, prev.column, lineNumber, curr.column);
return request.fulfill(6 /* CONTENT_TEXT */, pos, rng, { mightBeForeignElement: !mouseIsOverSpanNode || !!injectedText });
}
}
return request.fulfill(6 /* CONTENT_TEXT */, pos, null, { mightBeForeignElement: !mouseIsOverSpanNode || !!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 lineVerticalOffset = ctx.getVerticalOffsetForLineNumber(lineNumber);
const lineCenteredVerticalOffset = lineVerticalOffset + Math.floor(ctx.lineHeight / 2);
let adjustedPageY = request.pos.y + (lineCenteredVerticalOffset - request.mouseVerticalOffset);
if (adjustedPageY <= request.editorPos.y) {
adjustedPageY = request.editorPos.y + 1;
}
if (adjustedPageY >= request.editorPos.y + ctx.layoutInfo.height) {
adjustedPageY = request.editorPos.y + ctx.layoutInfo.height - 1;
}
const adjustedPage = new editorDom_1.PageCoordinates(request.pos.x, adjustedPageY);
const r = this._actualDoHitTestWithCaretRangeFromPoint(ctx, adjustedPage.toClientCoordinates());
if (r.type === 1 /* 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());
}
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 = document.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 = document.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.getTextModelOptions();
const newPosition = cursorAtomicMoveOperations_1.AtomicTabMoveOperations.atomicPosition(lineContent, position.column - 1, tabSize, 2 /* 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 document.caretRangeFromPoint === 'function') {
result = this._doHitTestWithCaretRangeFromPoint(ctx, request);
}
else if (document.caretPositionFromPoint) {
result = this._doHitTestWithCaretPositionFromPoint(ctx, request.pos.toClientCoordinates());
}
if (result.type === 1 /* Content */) {
const injectedText = ctx.model.getInjectedTextAt(result.position);
const normalizedPosition = ctx.model.normalizePosition(result.position, 2 /* None */);
if (injectedText || !normalizedPosition.equals(result.position)) {
result = new ContentHitTestResult(normalizedPosition, result.spanNode, injectedText);
}
}
// Snap to the nearest soft tab boundary if atomic soft tabs are enabled.
if (result.type === 1 /* Content */ && ctx.stickyTabStops) {
result = new ContentHitTestResult(this._snapToSoftTabBoundary(result.position, ctx.model), result.spanNode, result.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
const font = window.getComputedStyle(el, null).getPropertyValue('font');
// 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;
}
exports.shadowCaretRangeFromPoint = shadowCaretRangeFromPoint;
class CharWidthReader {
constructor() {
this._cache = {};
this._canvas = document.createElement('canvas');
}
static getInstance() {
if (!CharWidthReader._INSTANCE) {
CharWidthReader._INSTANCE = new CharWidthReader();
}
return CharWidthReader._INSTANCE;
}
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;
}
}
CharWidthReader._INSTANCE = 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[594/*vs/editor/browser/controller/mouseHandler*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,55/*vs/base/browser/mouseEvent*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,191/*vs/editor/browser/controller/mouseTarget*/,167/*vs/editor/browser/editorDom*/,133/*vs/editor/common/config/editorZoom*/,13/*vs/editor/common/core/position*/,21/*vs/editor/common/core/selection*/,115/*vs/editor/common/viewModel/viewEventHandler*/]), function (require, exports, dom, mouseEvent_1, async_1, lifecycle_1, platform, mouseTarget_1, editorDom_1, editorZoom_1, position_1, selection_1, viewEventHandler_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MouseHandler = exports.createMouseMoveEventMerger = void 0;
/**
* Merges mouse events when mouse move events are throttled
*/
function createMouseMoveEventMerger(mouseTargetFactory) {
return function (lastEvent, currentEvent) {
let targetIsWidget = false;
if (mouseTargetFactory) {
targetIsWidget = mouseTargetFactory.mouseTargetIsWidget(currentEvent);
}
if (!targetIsWidget) {
currentEvent.preventDefault();
}
return currentEvent;
};
}
exports.createMouseMoveEventMerger = createMouseMoveEventMerger;
class MouseHandler extends viewEventHandler_1.ViewEventHandler {
constructor(context, viewController, viewHelper) {
super();
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, (e, testEventTarget) => this._createMouseTarget(e, testEventTarget), (e) => this._getMouseColumn(e)));
this.lastMouseLeaveTime = -1;
this._height = this._context.configuration.options.get(129 /* 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.onMouseMoveThrottled(this.viewHelper.viewDomNode, (e) => this._onMouseMove(e), createMouseMoveEventMerger(this.mouseTargetFactory), MouseHandler.MOUSE_MOVE_MINIMUM_TIME));
this._register(mouseEvents.onMouseUp(this.viewHelper.viewDomNode, (e) => this._onMouseUp(e)));
this._register(mouseEvents.onMouseLeave(this.viewHelper.viewDomNode, (e) => this._onMouseLeave(e)));
this._register(mouseEvents.onMouseDown(this.viewHelper.viewDomNode, (e) => this._onMouseDown(e)));
const onMouseWheel = (browserEvent) => {
this.viewController.emitMouseWheel(browserEvent);
if (!this._context.configuration.options.get(66 /* mouseWheelZoom */)) {
return;
}
const e = new mouseEvent_1.StandardWheelEvent(browserEvent);
const doMouseWheelZoom = (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));
if (doMouseWheelZoom) {
const zoomLevel = editorZoom_1.EditorZoom.getZoomLevel();
const delta = e.deltaY > 0 ? 1 : -1;
editorZoom_1.EditorZoom.setZoomLevel(zoomLevel + delta);
e.preventDefault();
e.stopPropagation();
}
};
this._register(dom.addDisposableListener(this.viewHelper.viewDomNode, dom.EventType.MOUSE_WHEEL, onMouseWheel, { capture: true, passive: false }));
this._context.addEventHandler(this);
}
dispose() {
this._context.removeEventHandler(this);
super.dispose();
}
// --- begin event handlers
onConfigurationChanged(e) {
if (e.hasChanged(129 /* layoutInfo */)) {
// layout change
const height = this._context.configuration.options.get(129 /* 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;
}
onScrollChanged(e) {
this._mouseDownOperation.onScrollChanged();
return false;
}
// --- end event handlers
getTargetAtClientPoint(clientX, clientY) {
const clientPos = new editorDom_1.ClientCoordinates(clientX, clientY);
const pos = clientPos.toPageCoordinates();
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;
}
return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), editorPos, pos, null);
}
_createMouseTarget(e, testEventTarget) {
return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), e.editorPos, e.pos, testEventTarget ? e.target : null);
}
_getMouseColumn(e) {
return this.mouseTargetFactory.getMouseColumn(e.editorPos, e.pos);
}
_onContextMenu(e, testEventTarget) {
this.viewController.emitContextMenu({
event: e,
target: this._createMouseTarget(e, testEventTarget)
});
}
_onMouseMove(e) {
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) {
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) {
const t = this._createMouseTarget(e, true);
const targetIsContent = (t.type === 6 /* CONTENT_TEXT */ || t.type === 7 /* CONTENT_EMPTY */);
const targetIsGutter = (t.type === 2 /* GUTTER_GLYPH_MARGIN */ || t.type === 3 /* GUTTER_LINE_NUMBERS */ || t.type === 4 /* GUTTER_LINE_DECORATIONS */);
const targetIsLineNumbers = (t.type === 3 /* GUTTER_LINE_NUMBERS */);
const selectOnLineNumbers = this._context.configuration.options.get(97 /* selectOnLineNumbers */);
const targetIsViewZone = (t.type === 8 /* CONTENT_VIEW_ZONE */ || t.type === 5 /* GUTTER_VIEW_ZONE */);
const targetIsWidget = (t.type === 9 /* 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);
}
else if (targetIsGutter) {
// Do not steal focus
e.preventDefault();
}
else if (targetIsViewZone) {
const viewZoneData = t.detail;
if (this.viewHelper.shouldSuppressMouseDownOnViewZone(viewZoneData.viewZoneId)) {
focus();
this._mouseDownOperation.start(t.type, e);
e.preventDefault();
}
}
else if (targetIsWidget && this.viewHelper.shouldSuppressMouseDownOnWidget(t.detail)) {
focus();
e.preventDefault();
}
this.viewController.emitMouseDown({
event: e,
target: t
});
}
}
exports.MouseHandler = MouseHandler;
MouseHandler.MOUSE_MOVE_MINIMUM_TIME = 100; // ms
class MouseDownOperation extends lifecycle_1.Disposable {
constructor(context, viewController, viewHelper, createMouseTarget, getMouseColumn) {
super();
this._context = context;
this._viewController = viewController;
this._viewHelper = viewHelper;
this._createMouseTarget = createMouseTarget;
this._getMouseColumn = getMouseColumn;
this._mouseMoveMonitor = this._register(new editorDom_1.GlobalEditorMouseMoveMonitor(this._viewHelper.viewDomNode));
this._onScrollTimeout = this._register(new async_1.TimeoutTimer());
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, true);
if (!position) {
// Ignoring because position is unknown
return;
}
if (this._mouseState.isDragAndDrop) {
this._viewController.emitMouseDrag({
event: e,
target: position
});
}
else {
this._dispatchMouse(position, true);
}
}
start(targetType, e) {
this._lastMouseEvent = e;
this._mouseState.setStartedOnLineNumbers(targetType === 3 /* 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(79 /* readOnly */)
&& options.get(29 /* dragAndDrop */)
&& !options.get(16 /* 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 /* 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(e.target, e.buttons, createMouseMoveEventMerger(null), (e) => this._onMouseDownThenMove(e), (browserEvent) => {
const position = this._findMousePosition(this._lastMouseEvent, true);
if (browserEvent && browserEvent instanceof KeyboardEvent) {
// 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);
if (!this._isActive) {
this._isActive = true;
this._mouseMoveMonitor.startMonitoring(e.target, e.buttons, createMouseMoveEventMerger(null), (e) => this._onMouseDownThenMove(e), () => this._stop());
}
}
_stop() {
this._isActive = false;
this._onScrollTimeout.cancel();
}
onHeightChanged() {
this._mouseMoveMonitor.stopMonitoring();
}
onScrollChanged() {
if (!this._isActive) {
return;
}
this._onScrollTimeout.setIfNotSet(() => {
if (!this._lastMouseEvent) {
return;
}
const position = this._findMousePosition(this._lastMouseEvent, false);
if (!position) {
// Ignoring because position is unknown
return;
}
if (this._mouseState.isDragAndDrop) {
// Ignoring because users are dragging the text
return;
}
this._dispatchMouse(position, true);
}, 10);
}
onCursorStateChanged(e) {
this._currentSelection = e.selections[0];
}
_getPositionOutsideEditor(e) {
const editorContent = e.editorPos;
const model = this._context.model;
const viewLayout = this._context.viewLayout;
const mouseColumn = this._getMouseColumn(e);
if (e.posy < editorContent.y) {
const verticalOffset = Math.max(viewLayout.getCurrentScrollTop() - (editorContent.y - e.posy), 0);
const viewZoneData = mouseTarget_1.HitTestContext.getZoneAtCoord(this._context, verticalOffset);
if (viewZoneData) {
const newPosition = this._helpPositionJumpOverViewZone(viewZoneData);
if (newPosition) {
return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, newPosition);
}
}
const aboveLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset);
return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, new position_1.Position(aboveLineNumber, 1));
}
if (e.posy > editorContent.y + editorContent.height) {
const verticalOffset = viewLayout.getCurrentScrollTop() + (e.posy - editorContent.y);
const viewZoneData = mouseTarget_1.HitTestContext.getZoneAtCoord(this._context, verticalOffset);
if (viewZoneData) {
const newPosition = this._helpPositionJumpOverViewZone(viewZoneData);
if (newPosition) {
return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, newPosition);
}
}
const belowLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset);
return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, new position_1.Position(belowLineNumber, model.getLineMaxColumn(belowLineNumber)));
}
const possibleLineNumber = viewLayout.getLineNumberAtVerticalOffset(viewLayout.getCurrentScrollTop() + (e.posy - editorContent.y));
if (e.posx < editorContent.x) {
return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, new position_1.Position(possibleLineNumber, 1));
}
if (e.posx > editorContent.x + editorContent.width) {
return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, new position_1.Position(possibleLineNumber, model.getLineMaxColumn(possibleLineNumber)));
}
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 /* CONTENT_VIEW_ZONE */ || t.type === 5 /* GUTTER_VIEW_ZONE */) {
const newPosition = this._helpPositionJumpOverViewZone(t.detail);
if (newPosition) {
return new mouseTarget_1.MouseTarget(t.element, t.type, t.mouseColumn, newPosition, null, 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) {
if (!position.position) {
return;
}
this._viewController.dispatchMouse({
position: position.position,
mouseColumn: position.mouseColumn,
startedOnLineNumbers: this._mouseState.startedOnLineNumbers,
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,
});
}
}
class MouseDownState {
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 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; }
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);
}
}
MouseDownState.CLEAR_MOUSE_DOWN_COUNT_TIME = 400; // ms
});
/*---------------------------------------------------------------------------------------------
* 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/controller/pointerHandler*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,17/*vs/base/common/platform*/,60/*vs/base/browser/touch*/,2/*vs/base/common/lifecycle*/,594/*vs/editor/browser/controller/mouseHandler*/,167/*vs/editor/browser/editorDom*/,156/*vs/base/browser/canIUse*/,169/*vs/editor/browser/controller/textAreaInput*/]), function (require, exports, dom, platform, touch_1, lifecycle_1, mouseHandler_1, editorDom_1, canIUse_1, textAreaInput_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, 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.onPointerMoveThrottled(this.viewHelper.viewDomNode, (e) => this._onMouseMove(e), (0, mouseHandler_1.createMouseMoveEventMerger)(this.mouseTargetFactory), mouseHandler_1.MouseHandler.MOUSE_MOVE_MINIMUM_TIME));
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) => this._onMouseDown(e)));
}
onTap(event) {
if (!event.initialTarget || !this.viewHelper.linesContentDomNode.contains(event.initialTarget)) {
return;
}
event.preventDefault();
this.viewHelper.focusTextArea();
const target = this._createMouseTarget(new editorDom_1.EditorMouseEvent(event, this.viewHelper.viewDomNode), false);
if (target.position) {
// this.viewController.moveTo(target.position);
this.viewController.dispatchMouse({
position: target.position,
mouseColumn: target.position.column,
startedOnLineNumbers: false,
mouseDownCount: event.tapCount,
inSelectionMode: false,
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
leftButton: false,
middleButton: false,
});
}
}
onChange(e) {
if (this._lastPointerType === 'touch') {
this._context.model.deltaScrollNow(-e.translationX, -e.translationY);
}
}
_onMouseDown(e) {
if (e.browserEvent.pointerType === 'touch') {
return;
}
super._onMouseDown(e);
}
}
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, this.viewHelper.viewDomNode), false)));
}
onTap(event) {
event.preventDefault();
this.viewHelper.focusTextArea();
const target = this._createMouseTarget(new editorDom_1.EditorMouseEvent(event, 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);
}
}
onChange(e) {
this._context.model.deltaScrollNow(-e.translationX, -e.translationY);
}
}
class PointerHandler extends lifecycle_1.Disposable {
constructor(context, viewController, viewHelper) {
super();
if ((platform.isIOS && canIUse_1.BrowserFeatures.pointerEvents)) {
this.handler = this._register(new PointerEventHandler(context, viewController, viewHelper));
}
else if (window.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[259/*vs/editor/browser/view/viewUserInputEvents*/], __M([0/*require*/,1/*exports*/,191/*vs/editor/browser/controller/mouseTarget*/]), function (require, exports, mouseTarget_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) {
if (this.onKeyDown) {
this.onKeyDown(e);
}
}
emitKeyUp(e) {
if (this.onKeyUp) {
this.onKeyUp(e);
}
}
emitContextMenu(e) {
if (this.onContextMenu) {
this.onContextMenu(this._convertViewToModelMouseEvent(e));
}
}
emitMouseMove(e) {
if (this.onMouseMove) {
this.onMouseMove(this._convertViewToModelMouseEvent(e));
}
}
emitMouseLeave(e) {
if (this.onMouseLeave) {
this.onMouseLeave(this._convertViewToModelMouseEvent(e));
}
}
emitMouseDown(e) {
if (this.onMouseDown) {
this.onMouseDown(this._convertViewToModelMouseEvent(e));
}
}
emitMouseUp(e) {
if (this.onMouseUp) {
this.onMouseUp(this._convertViewToModelMouseEvent(e));
}
}
emitMouseDrag(e) {
if (this.onMouseDrag) {
this.onMouseDrag(this._convertViewToModelMouseEvent(e));
}
}
emitMouseDrop(e) {
if (this.onMouseDrop) {
this.onMouseDrop(this._convertViewToModelMouseEvent(e));
}
}
emitMouseDropCanceled() {
if (this.onMouseDropCanceled) {
this.onMouseDropCanceled();
}
}
emitMouseWheel(e) {
if (this.onMouseWheel) {
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) {
return new ExternalMouseTarget(target.element, target.type, target.mouseColumn, target.position ? coordinatesConverter.convertViewPositionToModelPosition(target.position) : null, target.range ? coordinatesConverter.convertViewRangeToModelRange(target.range) : null, target.detail);
}
}
exports.ViewUserInputEvents = ViewUserInputEvents;
class ExternalMouseTarget {
constructor(element, type, mouseColumn, position, range, detail) {
this.element = element;
this.type = type;
this.mouseColumn = mouseColumn;
this.position = position;
this.range = range;
this.detail = detail;
}
toString() {
return mouseTarget_1.MouseTarget.toString(this);
}
}
});
/*---------------------------------------------------------------------------------------------
* 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/lines/viewLines*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,15/*vs/base/common/async*/,65/*vs/editor/browser/config/configuration*/,170/*vs/editor/browser/view/viewLayer*/,47/*vs/editor/browser/view/viewPart*/,258/*vs/editor/browser/viewParts/lines/viewLine*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,113/*vs/editor/common/view/renderingContext*/,131/*vs/base/browser/ui/mouseCursor/mouseCursor*/,331/*vs/css!vs/editor/browser/viewParts/lines/viewLines*/]), function (require, exports, platform, async_1, configuration_1, viewLayer_1, viewPart_1, viewLine_1, position_1, range_1, renderingContext_1, mouseCursor_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(lineNumber, startColumn, endColumn, startScrollTop, stopScrollTop, scrollType) {
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(selections, startScrollTop, stopScrollTop, scrollType) {
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 {
constructor(context, linesContent) {
super(context);
this._linesContent = linesContent;
this._textRangeRestingSpot = document.createElement('div');
this._visibleLines = new viewLayer_1.VisibleLinesCollection(this);
this.domNode = this._visibleLines.domNode;
const conf = this._context.configuration;
const options = this._context.configuration.options;
const fontInfo = options.get(41 /* fontInfo */);
const wrappingInfo = options.get(130 /* wrappingInfo */);
this._lineHeight = options.get(57 /* lineHeight */);
this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
this._isViewportWrapping = wrappingInfo.isViewportWrapping;
this._revealHorizontalRightPadding = options.get(88 /* revealHorizontalRightPadding */);
this._cursorSurroundingLines = options.get(23 /* cursorSurroundingLines */);
this._cursorSurroundingLinesStyle = options.get(24 /* cursorSurroundingLinesStyle */);
this._canUseLayerHinting = !options.get(26 /* disableLayerHinting */);
this._viewLineOptions = new viewLine_1.ViewLineOptions(conf, this._context.theme.type);
viewPart_1.PartFingerprints.write(this.domNode, 7 /* ViewLines */);
this.domNode.setClassName(`view-lines ${mouseCursor_1.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
configuration_1.Configuration.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;
}
dispose() {
this._asyncUpdateLineWidths.dispose();
this._asyncCheckMonospaceFontAssumptions.dispose();
super.dispose();
}
getDomNode() {
return this.domNode;
}
// ---- begin IVisibleLinesHost
createVisibleLine() {
return new viewLine_1.ViewLine(this._viewLineOptions);
}
// ---- end IVisibleLinesHost
// ---- begin view event handlers
onConfigurationChanged(e) {
this._visibleLines.onConfigurationChanged(e);
if (e.hasChanged(130 /* wrappingInfo */)) {
this._maxLineWidth = 0;
}
const options = this._context.configuration.options;
const fontInfo = options.get(41 /* fontInfo */);
const wrappingInfo = options.get(130 /* wrappingInfo */);
this._lineHeight = options.get(57 /* lineHeight */);
this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
this._isViewportWrapping = wrappingInfo.isViewportWrapping;
this._revealHorizontalRightPadding = options.get(88 /* revealHorizontalRightPadding */);
this._cursorSurroundingLines = options.get(23 /* cursorSurroundingLines */);
this._cursorSurroundingLinesStyle = options.get(24 /* cursorSurroundingLinesStyle */);
this._canUseLayerHinting = !options.get(26 /* disableLayerHinting */);
configuration_1.Configuration.applyFontInfo(this.domNode, fontInfo);
this._onOptionsMaybeChanged();
if (e.hasChanged(129 /* 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.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.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.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 /* Immediate */ : e.scrollType);
this._context.model.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.model.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.model.getLineCount()) {
// lineNumber is outside range
return null;
}
if (this._context.model.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(lineNumber, spanNode, offset);
const minColumn = this._context.model.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;
}
return this._visibleLines.getVisibleLine(lineNumber).getWidth();
}
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;
}
let visibleRanges = [], visibleRangesLen = 0;
const domReadingContext = new viewLine_1.DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot);
let nextLineModelLineNumber = 0;
if (includeNewLines) {
nextLineModelLineNumber = this._context.model.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 endColumn = lineNumber === range.endLineNumber ? range.endColumn : this._context.model.getLineMaxColumn(lineNumber);
const visibleRangesForLine = this._visibleLines.getVisibleLine(lineNumber).getVisibleRangesForRange(startColumn, endColumn, domReadingContext);
if (!visibleRangesForLine) {
continue;
}
if (includeNewLines && lineNumber < originalEndLineNumber) {
const currentLineModelLineNumber = nextLineModelLineNumber;
nextLineModelLineNumber = this._context.model.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, visibleRangesForLine.ranges);
}
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;
}
return this._visibleLines.getVisibleLine(lineNumber).getVisibleRangesForRange(startColumn, endColumn, new viewLine_1.DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot));
}
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);
}
// --- implementation
updateLineWidths() {
this._updateLineWidths(false);
}
/**
* 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);
}
_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());
}
if (allWidthsComputed && rendStartLineNumber === 1 && rendEndLineNumber === this._context.model.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();
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.model.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();
}
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.model.setMaxLineWidth(this._maxLineWidth);
}
}
_computeScrollTopToRevealRange(viewport, source, range, selections, verticalType) {
const viewportStartY = viewport.top;
const viewportHeight = viewport.height;
const viewportEndY = viewportStartY + viewportHeight;
let boxIsSingleRange;
let boxStartY;
let boxEndY;
// Have a box that includes one extra line height (for the horizontal scrollbar)
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' && this._cursorSurroundingLinesStyle === 'default';
if (!shouldIgnoreScrollOff) {
const context = Math.min((viewportHeight / this._lineHeight) / 2, this._cursorSurroundingLines);
boxStartY -= context * this._lineHeight;
boxEndY += Math.max(0, (context - 1)) * this._lineHeight;
}
if (verticalType === 0 /* Simple */ || verticalType === 4 /* 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
boxEndY += this._lineHeight;
}
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 /* NearTop */ || verticalType === 6 /* NearTopIfOutsideViewport */) {
if (verticalType === 6 /* 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 /* Center */ || verticalType === 2 /* CenterIfOutsideViewport */) {
if (verticalType === 2 /* 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 /* Top */, verticalType === 4 /* Bottom */);
}
return newScrollTop;
}
_computeScrollLeftToReveal(horizontalRevealRequest) {
const viewport = this._context.viewLayout.getCurrentViewport();
const viewportStartX = viewport.left;
const viewportEndX = viewportStartX + viewport.width;
let boxStartX = 1073741824 /* 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, visibleRange.left);
boxEndX = Math.max(boxEndX, 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, visibleRange.left);
boxEndX = Math.max(boxEndX, visibleRange.left + visibleRange.width);
}
}
}
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;
/**
* Adds this amount of pixels to the right of lines (no-one wants to type near the edge of the viewport)
*/
ViewLines.HORIZONTAL_EXTRA_PX = 30;
});
/*---------------------------------------------------------------------------------------------
* 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/platform/theme/common/themeService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,2/*vs/base/common/lifecycle*/,32/*vs/platform/registry/common/platform*/,6/*vs/base/common/event*/,100/*vs/platform/theme/common/theme*/,27/*vs/base/common/codicons*/]), function (require, exports, instantiation_1, lifecycle_1, platform, event_1, theme_1, codicons_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Themable = exports.registerThemingParticipant = exports.Extensions = exports.getThemeTypeSelector = exports.ThemeIcon = exports.themeColorFromId = exports.ThemeColor = exports.IThemeService = void 0;
exports.IThemeService = (0, instantiation_1.createDecorator)('themeService');
var ThemeColor;
(function (ThemeColor) {
function isThemeColor(obj) {
return obj && typeof obj === 'object' && typeof obj.id === 'string';
}
ThemeColor.isThemeColor = isThemeColor;
})(ThemeColor = exports.ThemeColor || (exports.ThemeColor = {}));
function themeColorFromId(id) {
return { id };
}
exports.themeColorFromId = themeColorFromId;
var ThemeIcon;
(function (ThemeIcon) {
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(`^\\$\\((${codicons_1.CSSIcon.iconNameExpression}(?:${codicons_1.CSSIcon.iconModifierExpression})?)\\)$`);
function fromString(str) {
const match = _regexFromString.exec(str);
if (!match) {
return undefined;
}
let [, name] = match;
return { id: name };
}
ThemeIcon.fromString = fromString;
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 isEqual(ti1, ti2) {
var _a, _b;
return ti1.id === ti2.id && ((_a = ti1.color) === null || _a === void 0 ? void 0 : _a.id) === ((_b = ti2.color) === null || _b === void 0 ? void 0 : _b.id);
}
ThemeIcon.isEqual = isEqual;
function asThemeIcon(codicon, color) {
return { id: codicon.id, color: color ? themeColorFromId(color) : undefined };
}
ThemeIcon.asThemeIcon = asThemeIcon;
ThemeIcon.asClassNameArray = codicons_1.CSSIcon.asClassNameArray;
ThemeIcon.asClassName = codicons_1.CSSIcon.asClassName;
ThemeIcon.asCSSSelector = codicons_1.CSSIcon.asCSSSelector;
})(ThemeIcon = exports.ThemeIcon || (exports.ThemeIcon = {}));
function getThemeTypeSelector(type) {
switch (type) {
case theme_1.ColorScheme.DARK: return 'vs-dark';
case theme_1.ColorScheme.HIGH_CONTRAST: return 'hc-black';
default: return 'vs';
}
}
exports.getThemeTypeSelector = getThemeTypeSelector;
// 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;
}
}
let themingRegistry = new ThemingRegistry();
platform.Registry.add(exports.Extensions.ThemingContribution, themingRegistry);
function registerThemingParticipant(participant) {
return themingRegistry.onColorThemeChange(participant);
}
exports.registerThemingParticipant = registerThemingParticipant;
/**
* 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;
});
/*---------------------------------------------------------------------------------------------
* 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/services/codeEditorServiceImpl*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,24/*vs/base/common/uri*/,371/*vs/editor/browser/services/abstractCodeEditorService*/,110/*vs/editor/common/editorCommon*/,53/*vs/editor/common/model*/,11/*vs/platform/theme/common/themeService*/]), function (require, exports, dom, lifecycle_1, strings, uri_1, abstractCodeEditorService_1, editorCommon_1, model_1, themeService_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports._CSS_MAP = exports.DecorationTypeOptionsProvider = exports.DecorationSubTypeOptionsProvider = exports.CodeEditorServiceImpl = exports.GlobalStyleSheet = exports.RefCountedStyleSheet = void 0;
class RefCountedStyleSheet {
constructor(parent, editorId, styleSheet) {
this._parent = parent;
this._editorId = editorId;
this._styleSheet = styleSheet;
this._refCount = 0;
}
ref() {
this._refCount++;
}
unref() {
var _a;
this._refCount--;
if (this._refCount === 0) {
(_a = this._styleSheet.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this._styleSheet);
this._parent._removeEditorStyleSheets(this._editorId);
}
}
insertRule(rule, index) {
const sheet = this._styleSheet.sheet;
sheet.insertRule(rule, index);
}
removeRulesContainingSelector(ruleName) {
dom.removeCSSRulesContainingSelector(ruleName, this._styleSheet);
}
}
exports.RefCountedStyleSheet = RefCountedStyleSheet;
class GlobalStyleSheet {
constructor(styleSheet) {
this._styleSheet = styleSheet;
}
ref() {
}
unref() {
}
insertRule(rule, index) {
const sheet = this._styleSheet.sheet;
sheet.insertRule(rule, index);
}
removeRulesContainingSelector(ruleName) {
dom.removeCSSRulesContainingSelector(ruleName, this._styleSheet);
}
}
exports.GlobalStyleSheet = GlobalStyleSheet;
let CodeEditorServiceImpl = class CodeEditorServiceImpl extends abstractCodeEditorService_1.AbstractCodeEditorService {
constructor(styleSheet, themeService) {
super();
this._decorationOptionProviders = new Map();
this._editorStyleSheets = new Map();
this._globalStyleSheet = styleSheet ? styleSheet : null;
this._themeService = themeService;
}
_getOrCreateGlobalStyleSheet() {
if (!this._globalStyleSheet) {
this._globalStyleSheet = new GlobalStyleSheet(dom.createStyleSheet());
}
return this._globalStyleSheet;
}
_getOrCreateStyleSheet(editor) {
if (!editor) {
return this._getOrCreateGlobalStyleSheet();
}
const domNode = editor.getContainerDomNode();
if (!dom.isInShadowDOM(domNode)) {
return this._getOrCreateGlobalStyleSheet();
}
const editorId = editor.getId();
if (!this._editorStyleSheets.has(editorId)) {
const refCountedStyleSheet = new RefCountedStyleSheet(this, editorId, dom.createStyleSheet(domNode));
this._editorStyleSheets.set(editorId, refCountedStyleSheet);
}
return this._editorStyleSheets.get(editorId);
}
_removeEditorStyleSheets(editorId) {
this._editorStyleSheets.delete(editorId);
}
registerDecorationType(description, key, options, parentTypeKey, editor) {
let provider = this._decorationOptionProviders.get(key);
if (!provider) {
const styleSheet = this._getOrCreateStyleSheet(editor);
const providerArgs = {
styleSheet: styleSheet,
key: key,
parentTypeKey: parentTypeKey,
options: options || Object.create(null)
};
if (!parentTypeKey) {
provider = new DecorationTypeOptionsProvider(description, this._themeService, styleSheet, providerArgs);
}
else {
provider = new DecorationSubTypeOptionsProvider(this._themeService, styleSheet, providerArgs);
}
this._decorationOptionProviders.set(key, provider);
this._onDecorationTypeRegistered.fire(key);
}
provider.refCount++;
}
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.removeDecorations(key));
}
}
}
resolveDecorationOptions(decorationTypeKey, writable) {
const provider = this._decorationOptionProviders.get(decorationTypeKey);
if (!provider) {
throw new Error('Unknown decoration type key: ' + decorationTypeKey);
}
return provider.getOptions(this, writable);
}
};
CodeEditorServiceImpl = __decorate([
__param(1, themeService_1.IThemeService)
], CodeEditorServiceImpl);
exports.CodeEditorServiceImpl = CodeEditorServiceImpl;
class DecorationSubTypeOptionsProvider {
constructor(themeService, styleSheet, providerArgs) {
this._styleSheet = styleSheet;
this._styleSheet.ref();
this._parentTypeKey = providerArgs.parentTypeKey;
this.refCount = 0;
this._beforeContentRules = new DecorationCSSRules(3 /* BeforeContentClassName */, providerArgs, themeService);
this._afterContentRules = new DecorationCSSRules(4 /* AfterContentClassName */, providerArgs, themeService);
}
getOptions(codeEditorService, writable) {
const options = codeEditorService.resolveDecorationOptions(this._parentTypeKey, true);
if (this._beforeContentRules) {
options.beforeContentClassName = this._beforeContentRules.className;
}
if (this._afterContentRules) {
options.afterContentClassName = this._afterContentRules.className;
}
return options;
}
dispose() {
if (this._beforeContentRules) {
this._beforeContentRules.dispose();
this._beforeContentRules = null;
}
if (this._afterContentRules) {
this._afterContentRules.dispose();
this._afterContentRules = null;
}
this._styleSheet.unref();
}
}
exports.DecorationSubTypeOptionsProvider = DecorationSubTypeOptionsProvider;
class DecorationTypeOptionsProvider {
constructor(description, themeService, styleSheet, providerArgs) {
this._disposables = new lifecycle_1.DisposableStore();
this.description = description;
this._styleSheet = styleSheet;
this._styleSheet.ref();
this.refCount = 0;
const createCSSRules = (type) => {
const rules = new DecorationCSSRules(type, providerArgs, themeService);
this._disposables.add(rules);
if (rules.hasContent) {
return rules.className;
}
return undefined;
};
const createInlineCSSRules = (type) => {
const rules = new DecorationCSSRules(type, providerArgs, themeService);
this._disposables.add(rules);
if (rules.hasContent) {
return { className: rules.className, hasLetterSpacing: rules.hasLetterSpacing };
}
return null;
};
this.className = createCSSRules(0 /* ClassName */);
const inlineData = createInlineCSSRules(1 /* InlineClassName */);
if (inlineData) {
this.inlineClassName = inlineData.className;
this.inlineClassNameAffectsLetterSpacing = inlineData.hasLetterSpacing;
}
this.beforeContentClassName = createCSSRules(3 /* BeforeContentClassName */);
this.afterContentClassName = createCSSRules(4 /* AfterContentClassName */);
if (providerArgs.options.beforeInjectedText && providerArgs.options.beforeInjectedText.contentText) {
const beforeInlineData = createInlineCSSRules(5 /* BeforeInjectedTextClassName */);
this.beforeInjectedText = {
content: providerArgs.options.beforeInjectedText.contentText,
inlineClassName: beforeInlineData === null || beforeInlineData === void 0 ? void 0 : beforeInlineData.className,
inlineClassNameAffectsLetterSpacing: (beforeInlineData === null || beforeInlineData === void 0 ? void 0 : beforeInlineData.hasLetterSpacing) || providerArgs.options.beforeInjectedText.affectsLetterSpacing
};
}
if (providerArgs.options.afterInjectedText && providerArgs.options.afterInjectedText.contentText) {
const afterInlineData = createInlineCSSRules(6 /* AfterInjectedTextClassName */);
this.afterInjectedText = {
content: providerArgs.options.afterInjectedText.contentText,
inlineClassName: afterInlineData === null || afterInlineData === void 0 ? void 0 : afterInlineData.className,
inlineClassNameAffectsLetterSpacing: (afterInlineData === null || afterInlineData === void 0 ? void 0 : afterInlineData.hasLetterSpacing) || providerArgs.options.afterInjectedText.affectsLetterSpacing
};
}
this.glyphMarginClassName = createCSSRules(2 /* GlyphMarginClassName */);
const options = providerArgs.options;
this.isWholeLine = Boolean(options.isWholeLine);
this.stickiness = options.rangeBehavior;
const lightOverviewRulerColor = options.light && options.light.overviewRulerColor || options.overviewRulerColor;
const darkOverviewRulerColor = options.dark && options.dark.overviewRulerColor || options.overviewRulerColor;
if (typeof lightOverviewRulerColor !== 'undefined'
|| typeof darkOverviewRulerColor !== 'undefined') {
this.overviewRuler = {
color: lightOverviewRulerColor || darkOverviewRulerColor,
darkColor: darkOverviewRulerColor || lightOverviewRulerColor,
position: options.overviewRulerLane || model_1.OverviewRulerLane.Center
};
}
}
getOptions(codeEditorService, writable) {
if (!writable) {
return this;
}
return {
description: this.description,
inlineClassName: this.inlineClassName,
beforeContentClassName: this.beforeContentClassName,
afterContentClassName: this.afterContentClassName,
className: this.className,
glyphMarginClassName: this.glyphMarginClassName,
isWholeLine: this.isWholeLine,
overviewRuler: this.overviewRuler,
stickiness: this.stickiness,
before: this.beforeInjectedText
};
}
dispose() {
this._disposables.dispose();
this._styleSheet.unref();
}
}
exports.DecorationTypeOptionsProvider = DecorationTypeOptionsProvider;
exports._CSS_MAP = {
color: 'color:{0} !important;',
opacity: 'opacity:{0};',
backgroundColor: 'background-color:{0};',
outline: 'outline:{0};',
outlineColor: 'outline-color:{0};',
outlineStyle: 'outline-style:{0};',
outlineWidth: 'outline-width:{0};',
border: 'border:{0};',
borderColor: 'border-color:{0};',
borderRadius: 'border-radius:{0};',
borderSpacing: 'border-spacing:{0};',
borderStyle: 'border-style:{0};',
borderWidth: 'border-width:{0};',
fontStyle: 'font-style:{0};',
fontWeight: 'font-weight:{0};',
fontSize: 'font-size:{0};',
fontFamily: 'font-family:{0};',
textDecoration: 'text-decoration:{0};',
cursor: 'cursor:{0};',
letterSpacing: 'letter-spacing:{0};',
gutterIconPath: 'background:{0} center center no-repeat;',
gutterIconSize: 'background-size:{0};',
contentText: 'content:\'{0}\';',
contentIconPath: 'content:{0};',
margin: 'margin:{0};',
padding: 'padding:{0};',
width: 'width:{0};',
height: 'height:{0};'
};
class DecorationCSSRules {
constructor(ruleType, providerArgs, themeService) {
this._theme = themeService.getColorTheme();
this._ruleType = ruleType;
this._providerArgs = providerArgs;
this._usesThemeColors = false;
this._hasContent = false;
this._hasLetterSpacing = false;
let className = CSSNameHelper.getClassName(this._providerArgs.key, ruleType);
if (this._providerArgs.parentTypeKey) {
className = className + ' ' + CSSNameHelper.getClassName(this._providerArgs.parentTypeKey, ruleType);
}
this._className = className;
this._unThemedSelector = CSSNameHelper.getSelector(this._providerArgs.key, this._providerArgs.parentTypeKey, ruleType);
this._buildCSS();
if (this._usesThemeColors) {
this._themeListener = themeService.onDidColorThemeChange(theme => {
this._theme = themeService.getColorTheme();
this._removeCSS();
this._buildCSS();
});
}
else {
this._themeListener = null;
}
}
dispose() {
if (this._hasContent) {
this._removeCSS();
this._hasContent = false;
}
if (this._themeListener) {
this._themeListener.dispose();
this._themeListener = null;
}
}
get hasContent() {
return this._hasContent;
}
get hasLetterSpacing() {
return this._hasLetterSpacing;
}
get className() {
return this._className;
}
_buildCSS() {
const options = this._providerArgs.options;
let unthemedCSS, lightCSS, darkCSS;
switch (this._ruleType) {
case 0 /* ClassName */:
unthemedCSS = this.getCSSTextForModelDecorationClassName(options);
lightCSS = this.getCSSTextForModelDecorationClassName(options.light);
darkCSS = this.getCSSTextForModelDecorationClassName(options.dark);
break;
case 1 /* InlineClassName */:
unthemedCSS = this.getCSSTextForModelDecorationInlineClassName(options);
lightCSS = this.getCSSTextForModelDecorationInlineClassName(options.light);
darkCSS = this.getCSSTextForModelDecorationInlineClassName(options.dark);
break;
case 2 /* GlyphMarginClassName */:
unthemedCSS = this.getCSSTextForModelDecorationGlyphMarginClassName(options);
lightCSS = this.getCSSTextForModelDecorationGlyphMarginClassName(options.light);
darkCSS = this.getCSSTextForModelDecorationGlyphMarginClassName(options.dark);
break;
case 3 /* BeforeContentClassName */:
unthemedCSS = this.getCSSTextForModelDecorationContentClassName(options.before);
lightCSS = this.getCSSTextForModelDecorationContentClassName(options.light && options.light.before);
darkCSS = this.getCSSTextForModelDecorationContentClassName(options.dark && options.dark.before);
break;
case 4 /* AfterContentClassName */:
unthemedCSS = this.getCSSTextForModelDecorationContentClassName(options.after);
lightCSS = this.getCSSTextForModelDecorationContentClassName(options.light && options.light.after);
darkCSS = this.getCSSTextForModelDecorationContentClassName(options.dark && options.dark.after);
break;
case 5 /* BeforeInjectedTextClassName */:
unthemedCSS = this.getCSSTextForModelDecorationContentClassName(options.beforeInjectedText);
lightCSS = this.getCSSTextForModelDecorationContentClassName(options.light && options.light.beforeInjectedText);
darkCSS = this.getCSSTextForModelDecorationContentClassName(options.dark && options.dark.beforeInjectedText);
break;
case 6 /* AfterInjectedTextClassName */:
unthemedCSS = this.getCSSTextForModelDecorationContentClassName(options.afterInjectedText);
lightCSS = this.getCSSTextForModelDecorationContentClassName(options.light && options.light.afterInjectedText);
darkCSS = this.getCSSTextForModelDecorationContentClassName(options.dark && options.dark.afterInjectedText);
break;
default:
throw new Error('Unknown rule type: ' + this._ruleType);
}
const sheet = this._providerArgs.styleSheet;
let hasContent = false;
if (unthemedCSS.length > 0) {
sheet.insertRule(`${this._unThemedSelector} {${unthemedCSS}}`, 0);
hasContent = true;
}
if (lightCSS.length > 0) {
sheet.insertRule(`.vs${this._unThemedSelector} {${lightCSS}}`, 0);
hasContent = true;
}
if (darkCSS.length > 0) {
sheet.insertRule(`.vs-dark${this._unThemedSelector}, .hc-black${this._unThemedSelector} {${darkCSS}}`, 0);
hasContent = true;
}
this._hasContent = hasContent;
}
_removeCSS() {
this._providerArgs.styleSheet.removeRulesContainingSelector(this._unThemedSelector);
}
/**
* Build the CSS for decorations styled via `className`.
*/
getCSSTextForModelDecorationClassName(opts) {
if (!opts) {
return '';
}
const cssTextArr = [];
this.collectCSSText(opts, ['backgroundColor'], cssTextArr);
this.collectCSSText(opts, ['outline', 'outlineColor', 'outlineStyle', 'outlineWidth'], cssTextArr);
this.collectBorderSettingsCSSText(opts, cssTextArr);
return cssTextArr.join('');
}
/**
* Build the CSS for decorations styled via `inlineClassName`.
*/
getCSSTextForModelDecorationInlineClassName(opts) {
if (!opts) {
return '';
}
const cssTextArr = [];
this.collectCSSText(opts, ['fontStyle', 'fontWeight', 'textDecoration', 'cursor', 'color', 'opacity', 'letterSpacing'], cssTextArr);
if (opts.letterSpacing) {
this._hasLetterSpacing = true;
}
return cssTextArr.join('');
}
/**
* Build the CSS for decorations styled before or after content.
*/
getCSSTextForModelDecorationContentClassName(opts) {
if (!opts) {
return '';
}
const cssTextArr = [];
if (typeof opts !== 'undefined') {
this.collectBorderSettingsCSSText(opts, cssTextArr);
if (typeof opts.contentIconPath !== 'undefined') {
cssTextArr.push(strings.format(exports._CSS_MAP.contentIconPath, dom.asCSSUrl(uri_1.URI.revive(opts.contentIconPath))));
}
if (typeof opts.contentText === 'string') {
const truncated = opts.contentText.match(/^.*$/m)[0]; // only take first line
const escaped = truncated.replace(/['\\]/g, '\\$&');
cssTextArr.push(strings.format(exports._CSS_MAP.contentText, escaped));
}
this.collectCSSText(opts, ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textDecoration', 'color', 'opacity', 'backgroundColor', 'margin', 'padding'], cssTextArr);
if (this.collectCSSText(opts, ['width', 'height'], cssTextArr)) {
cssTextArr.push('display:inline-block;');
}
}
return cssTextArr.join('');
}
/**
* Build the CSS for decorations styled via `glpyhMarginClassName`.
*/
getCSSTextForModelDecorationGlyphMarginClassName(opts) {
if (!opts) {
return '';
}
const cssTextArr = [];
if (typeof opts.gutterIconPath !== 'undefined') {
cssTextArr.push(strings.format(exports._CSS_MAP.gutterIconPath, dom.asCSSUrl(uri_1.URI.revive(opts.gutterIconPath))));
if (typeof opts.gutterIconSize !== 'undefined') {
cssTextArr.push(strings.format(exports._CSS_MAP.gutterIconSize, opts.gutterIconSize));
}
}
return cssTextArr.join('');
}
collectBorderSettingsCSSText(opts, cssTextArr) {
if (this.collectCSSText(opts, ['border', 'borderColor', 'borderRadius', 'borderSpacing', 'borderStyle', 'borderWidth'], cssTextArr)) {
cssTextArr.push(strings.format('box-sizing: border-box;'));
return true;
}
return false;
}
collectCSSText(opts, properties, cssTextArr) {
const lenBefore = cssTextArr.length;
for (let property of properties) {
const value = this.resolveValue(opts[property]);
if (typeof value === 'string') {
cssTextArr.push(strings.format(exports._CSS_MAP[property], value));
}
}
return cssTextArr.length !== lenBefore;
}
resolveValue(value) {
if ((0, editorCommon_1.isThemeColor)(value)) {
this._usesThemeColors = true;
const color = this._theme.getColor(value.id);
if (color) {
return color.toString();
}
return 'transparent';
}
return value;
}
}
class CSSNameHelper {
static getClassName(key, type) {
return 'ced-' + key + '-' + type;
}
static getSelector(key, parentKey, ruleType) {
let selector = '.monaco-editor .' + this.getClassName(key, ruleType);
if (parentKey) {
selector = selector + '.' + this.getClassName(parentKey, ruleType);
}
if (ruleType === 3 /* BeforeContentClassName */) {
selector += '::before';
}
else if (ruleType === 4 /* AfterContentClassName */) {
selector += '::after';
}
return selector;
}
}
});
/*---------------------------------------------------------------------------------------------
* 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/browser/viewParts/editorScrollbar/editorScrollbar*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,47/*vs/editor/browser/view/viewPart*/,11/*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(91 /* scrollbar */);
const mouseWheelScrollSensitivity = options.get(65 /* mouseWheelScrollSensitivity */);
const fastScrollSensitivity = options.get(32 /* fastScrollSensitivity */);
const scrollPredominantAxis = options.get(94 /* 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(), 5 /* 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.model.setScrollPosition(newScrollPosition, 1 /* 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(129 /* layoutInfo */);
this.scrollbarDomNode.setLeft(layoutInfo.contentLeft);
const minimap = options.get(63 /* 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;
}
delegateVerticalScrollbarMouseDown(browserEvent) {
this.scrollbar.delegateVerticalScrollbarMouseDown(browserEvent);
}
// --- begin event handlers
onConfigurationChanged(e) {
if (e.hasChanged(91 /* scrollbar */)
|| e.hasChanged(65 /* mouseWheelScrollSensitivity */)
|| e.hasChanged(32 /* fastScrollSensitivity */)) {
const options = this._context.configuration.options;
const scrollbar = options.get(91 /* scrollbar */);
const mouseWheelScrollSensitivity = options.get(65 /* mouseWheelScrollSensitivity */);
const fastScrollSensitivity = options.get(32 /* fastScrollSensitivity */);
const scrollPredominantAxis = options.get(94 /* 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(129 /* 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[599/*vs/editor/browser/viewParts/minimap/minimap*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,93/*vs/base/browser/globalMouseMoveMonitor*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,8/*vs/base/common/strings*/,170/*vs/editor/browser/view/viewLayer*/,47/*vs/editor/browser/view/viewPart*/,35/*vs/editor/common/config/editorOptions*/,3/*vs/editor/common/core/range*/,218/*vs/editor/common/core/rgba*/,247/*vs/editor/common/viewModel/minimapTokensColorTracker*/,62/*vs/editor/common/viewModel/viewModel*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,21/*vs/editor/common/core/selection*/,60/*vs/base/browser/touch*/,374/*vs/editor/browser/viewParts/minimap/minimapCharRendererFactory*/,53/*vs/editor/common/model*/,80/*vs/base/common/functional*/,334/*vs/css!vs/editor/browser/viewParts/minimap/minimap*/]), function (require, exports, dom, fastDomNode_1, globalMouseMoveMonitor_1, lifecycle_1, platform, strings, viewLayer_1, viewPart_1, editorOptions_1, range_1, rgba_1, minimapTokensColorTracker_1, viewModel_1, colorRegistry_1, themeService_1, selection_1, touch_1, minimapCharRendererFactory_1, model_1, functional_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 MOUSE_DRAG_RESET_DISTANCE = 140;
const GUTTER_DECORATION_WIDTH = 2;
class MinimapOptions {
constructor(configuration, theme, tokensColorTracker) {
const options = configuration.options;
const pixelRatio = options.get(127 /* pixelRatio */);
const layoutInfo = options.get(129 /* layoutInfo */);
const minimapLayout = layoutInfo.minimap;
const fontInfo = options.get(41 /* fontInfo */);
const minimapOpts = options.get(63 /* minimap */);
this.renderMinimap = minimapLayout.renderMinimap;
this.size = minimapOpts.size;
this.minimapHeightIsEditorHeight = minimapLayout.minimapHeightIsEditorHeight;
this.scrollBeyondLastLine = options.get(93 /* scrollBeyondLastLine */);
this.showSlider = minimapOpts.showSlider;
this.pixelRatio = pixelRatio;
this.typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
this.lineHeight = options.get(57 /* 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 /* BASE_CHAR_WIDTH */ * this.fontScale;
this.charRenderer = (0, functional_1.once)(() => minimapCharRendererFactory_1.MinimapCharRendererFactory.create(this.fontScale, fontInfo.fontFamily));
this.backgroundColor = MinimapOptions._getMinimapBackground(theme, tokensColorTracker);
}
static _getMinimapBackground(theme, tokensColorTracker) {
const themeColor = theme.getColor(colorRegistry_1.minimapBackground);
if (themeColor) {
return new rgba_1.RGBA8(themeColor.rgba.r, themeColor.rgba.g, themeColor.rgba.b, themeColor.rgba.a);
}
return tokensColorTracker.getColor(2 /* DefaultBackground */);
}
equals(other) {
return (this.renderMinimap === other.renderMinimap
&& this.size === other.size
&& this.minimapHeightIsEditorHeight === other.minimapHeightIsEditorHeight
&& this.scrollBeyondLastLine === other.scrollBeyondLastLine
&& this.showSlider === other.showSlider
&& 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.backgroundColor && this.backgroundColor.equals(other.backgroundColor));
}
}
class MinimapLayout {
constructor(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio, sliderTop, sliderHeight, startLineNumber, endLineNumber) {
this.scrollTop = scrollTop;
this.scrollHeight = scrollHeight;
this.sliderNeeded = sliderNeeded;
this._computedSliderRatio = computedSliderRatio;
this.sliderTop = sliderTop;
this.sliderHeight = sliderHeight;
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);
}
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) {
const logicalScrollHeight = (realLineCount * options.lineHeight
+ (options.scrollBeyondLastLine ? viewportHeight - options.lineHeight : 0));
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);
return new MinimapLayout(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio, sliderTop, sliderHeight, 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);
}
let maxMinimapSliderTop;
if (options.scrollBeyondLastLine) {
// The minimap slider, when dragged all the way down, will contain the last line at its top
maxMinimapSliderTop = (lineCount - 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, 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);
let extraLinesAtTheBottom = 0;
if (options.scrollBeyondLastLine) {
const expectedViewportLineCount = viewportHeight / lineHeight;
extraLinesAtTheBottom = expectedViewportLineCount - 1;
}
if (minimapLinesFitting >= lineCount + extraLinesAtTheBottom) {
// All lines fit in the minimap
const startLineNumber = 1;
const endLineNumber = lineCount;
const sliderNeeded = (maxMinimapSliderTop > 0);
return new MinimapLayout(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio, sliderTop, sliderHeight, startLineNumber, endLineNumber);
}
else {
let startLineNumber = Math.max(1, Math.floor(viewportStartLineNumber - sliderTop * pixelRatio / minimapLineHeight));
// 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);
}
if (previousLayout.scrollTop < scrollTop) {
// Scrolling down => never decrease `startLineNumber`
startLineNumber = Math.max(startLineNumber, previousLayout.startLineNumber);
}
}
const endLineNumber = Math.min(lineCount, startLineNumber + minimapLinesFitting - 1);
const partialLine = (scrollTop - viewportStartLineNumberVerticalOffset) / lineHeight;
const sliderTopAligned = (viewportStartLineNumber - startLineNumber + partialLine) * minimapLineHeight / pixelRatio;
return new MinimapLayout(scrollTop, scrollHeight, true, computedSliderRatio, sliderTopAligned, sliderHeight, startLineNumber, endLineNumber);
}
}
}
class MinimapLine {
constructor(dy) {
this.dy = dy;
}
onContentChanged() {
this.dy = -1;
}
onTokensChanged() {
this.dy = -1;
}
}
MinimapLine.INVALID = new MinimapLine(-1);
class RenderData {
constructor(renderedLayout, imageData, lines) {
this.renderedLayout = renderedLayout;
this._imageData = imageData;
this._renderedLines = new viewLayer_1.RenderedLinesCollection(() => 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, changeToLineNumber) {
return this._renderedLines.onLinesChanged(changeFromLineNumber, changeToLineNumber);
}
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 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] = 255;
offset += 4;
}
}
return result;
}
}
class MinimapSamplingState {
constructor(samplingRatio, minimapLines) {
this.samplingRatio = samplingRatio;
this.minimapLines = minimapLines;
}
static compute(options, viewLineCount, oldSamplingState) {
if (options.renderMinimap === 0 /* 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 pixelRatio = options.pixelRatio;
const lineHeight = options.lineHeight;
const scrollBeyondLastLine = options.scrollBeyondLastLine;
const { minimapLineCount } = editorOptions_1.EditorLayoutInfoComputer.computeContainedMinimapLineCount({
viewLineCount: viewLineCount,
scrollBeyondLastLine: scrollBeyondLastLine,
height: options.editorHeight,
lineHeight: lineHeight,
pixelRatio: pixelRatio
});
const ratio = viewLineCount / minimapLineCount;
const halfRatio = ratio / 2;
if (!oldSamplingState || oldSamplingState.minimapLines.length === 0) {
let 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;
let 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];
}
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.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.model.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.toLineNumber);
if (minimapLineRange) {
return this._actual.onLinesChanged(minimapLineRange[0], minimapLineRange[1]);
}
else {
return false;
}
}
else {
return this._actual.onLinesChanged(e.fromLineNumber, e.toLineNumber);
}
}
onLinesDeleted(e) {
if (this._samplingState) {
const [changeStartIndex, changeEndIndex] = this._samplingState.onLinesDeleted(e);
if (changeStartIndex <= changeEndIndex) {
this._actual.onLinesChanged(changeStartIndex + 1, changeEndIndex + 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._context.model.invalidateMinimapColorCache();
this._actual.onThemeChanged();
this._onOptionsMaybeChanged();
return true;
}
onTokensChanged(e) {
if (this._samplingState) {
let 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.model.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.model.getLineCount();
}
getRealLineCount() {
return this._context.model.getLineCount();
}
getLineContent(lineNumber) {
if (this._samplingState) {
return this._context.model.getLineContent(this._samplingState.minimapLines[lineNumber - 1]);
}
return this._context.model.getLineContent(lineNumber);
}
getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed) {
if (this._samplingState) {
let result = [];
for (let lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) {
if (needed[lineIndex]) {
result[lineIndex] = this._context.model.getViewLineData(this._samplingState.minimapLines[startLineNumber + lineIndex - 1]);
}
else {
result[lineIndex] = null;
}
}
return result;
}
return this._context.model.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) {
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.model.getLineMaxColumn(modelEndLineNumber));
}
else {
visibleRange = new range_1.Range(startLineNumber, 1, endLineNumber, this._context.model.getLineMaxColumn(endLineNumber));
}
const decorations = this._context.model.getDecorationsInViewport(visibleRange);
if (this._samplingState) {
let 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;
}
getOptions() {
return this._context.model.getTextModelOptions();
}
revealLineNumber(lineNumber) {
if (this._samplingState) {
lineNumber = this._samplingState.minimapLines[lineNumber - 1];
}
this._context.model.revealRange('mouse', false, new range_1.Range(lineNumber, 1, lineNumber, 1), 1 /* Center */, 0 /* Smooth */);
}
setScrollTop(scrollTop) {
this._context.model.setScrollPosition({
scrollTop: scrollTop
}, 1 /* 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, 8 /* 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._mouseDownListener = dom.addStandardDisposableListener(this._domNode.domNode, 'mousedown', (e) => {
e.preventDefault();
const renderMinimap = this._model.options.renderMinimap;
if (renderMinimap === 0 /* None */) {
return;
}
if (!this._lastRenderData) {
return;
}
if (this._model.options.size !== 'proportional') {
if (e.leftButton && 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.buttons, e.posx, initialPosY, e.posy, this._lastRenderData.renderedLayout);
}
return;
}
const minimapLineHeight = this._model.options.minimapLineHeight;
const internalOffsetY = (this._model.options.canvasInnerHeight / this._model.options.canvasOuterHeight) * e.browserEvent.offsetY;
const lineIndex = Math.floor(internalOffsetY / minimapLineHeight);
let lineNumber = lineIndex + this._lastRenderData.renderedLayout.startLineNumber;
lineNumber = Math.min(lineNumber, this._model.getLineCount());
this._model.revealLineNumber(lineNumber);
});
this._sliderMouseMoveMonitor = new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor();
this._sliderMouseDownListener = dom.addStandardDisposableListener(this._slider.domNode, 'mousedown', (e) => {
e.preventDefault();
e.stopPropagation();
if (e.leftButton && this._lastRenderData) {
this._startSliderDragging(e.buttons, e.posx, e.posy, e.posy, 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(initialButtons, initialPosX, initialPosY, posy, initialSliderState) {
this._slider.toggleClassName('active', true);
const handleMouseMove = (posy, posx) => {
const mouseOrthogonalDelta = Math.abs(posx - initialPosX);
if (platform.isWindows && mouseOrthogonalDelta > MOUSE_DRAG_RESET_DISTANCE) {
// The mouse has wondered away from the scrollbar => reset dragging
this._model.setScrollTop(initialSliderState.scrollTop);
return;
}
const mouseDelta = posy - initialPosY;
this._model.setScrollTop(initialSliderState.getDesiredScrollTopFromDelta(mouseDelta));
};
if (posy !== initialPosY) {
handleMouseMove(posy, initialPosX);
}
this._sliderMouseMoveMonitor.startMonitoring(this._slider.domNode, initialButtons, globalMouseMoveMonitor_1.standardMouseMoveMerger, (mouseMoveData) => handleMouseMove(mouseMoveData.posy, mouseMoveData.posx), () => {
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._mouseDownListener.dispose();
this._sliderMouseMoveMonitor.dispose();
this._sliderMouseDownListener.dispose();
this._gestureDisposable.dispose();
this._sliderTouchStartListener.dispose();
this._sliderTouchMoveListener.dispose();
this._sliderTouchEndListener.dispose();
super.dispose();
}
_getMinimapDomNodeClassName() {
if (this._model.options.showSlider === 'always') {
return 'minimap slider-always';
}
return 'minimap slider-mouseover';
}
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, changeToLineNumber) {
if (this._lastRenderData) {
return this._lastRenderData.onLinesChanged(changeFromLineNumber, changeToLineNumber);
}
return false;
}
onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
if (this._lastRenderData) {
this._lastRenderData.onLinesDeleted(deleteFromLineNumber, deleteToLineNumber);
}
return true;
}
onLinesInserted(insertFromLineNumber, insertToLineNumber) {
if (this._lastRenderData) {
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 /* 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
const scrollLeftChars = renderingCtx.scrollLeft / this._model.options.typicalHalfwidthCharacterWidth;
const horizontalSliderLeft = Math.min(this._model.options.minimapWidth, Math.round(scrollLeftChars * this._model.options.minimapCharWidth / this._model.options.pixelRatio));
this._sliderHorizontal.setLeft(horizontalSliderLeft);
this._sliderHorizontal.setWidth(this._model.options.minimapWidth - horizontalSliderLeft);
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();
const decorations = this._model.getMinimapDecorationsInViewport(layout.startLineNumber, layout.endLineNumber);
const { canvasInnerWidth, canvasInnerHeight } = this._model.options;
const lineHeight = this._model.options.minimapLineHeight;
const characterWidth = this._model.options.minimapCharWidth;
const tabSize = this._model.getOptions().tabSize;
const canvasContext = this._decorationsCanvas.domNode.getContext('2d');
canvasContext.clearRect(0, 0, canvasInnerWidth, canvasInnerHeight);
const lineOffsetMap = new Map();
for (let i = 0; i < selections.length; i++) {
const selection = selections[i];
for (let line = selection.startLineNumber; line <= selection.endLineNumber; line++) {
this.renderDecorationOnLine(canvasContext, lineOffsetMap, selection, this._selectionColor, layout, line, lineHeight, lineHeight, tabSize, characterWidth);
}
}
// Loop over decorations, ignoring those that don't have the minimap property set and rendering rectangles for each line the decoration spans
for (let i = 0; i < decorations.length; i++) {
const decoration = decorations[i];
if (!decoration.options.minimap) {
continue;
}
const decorationColor = decoration.options.minimap.getColor(this._theme);
for (let line = decoration.range.startLineNumber; line <= decoration.range.endLineNumber; line++) {
switch (decoration.options.minimap.position) {
case model_1.MinimapPosition.Inline:
this.renderDecorationOnLine(canvasContext, lineOffsetMap, decoration.range, decorationColor, layout, line, lineHeight, lineHeight, tabSize, characterWidth);
continue;
case model_1.MinimapPosition.Gutter:
const y = (line - layout.startLineNumber) * lineHeight;
const x = 2;
this.renderDecoration(canvasContext, decorationColor, x, y, GUTTER_DECORATION_WIDTH, lineHeight);
continue;
}
}
}
}
}
renderDecorationOnLine(canvasContext, lineOffsetMap, decorationRange, decorationColor, layout, lineNumber, height, lineHeight, tabSize, charWidth) {
const y = (lineNumber - layout.startLineNumber) * lineHeight;
// Skip rendering the line if it's vertically outside our viewport
if (y + height < 0 || y > this._model.options.canvasInnerHeight) {
return;
}
// Cache line offset data so that it is only read once per line
let lineIndexToXOffset = lineOffsetMap.get(lineNumber);
const isFirstDecorationForLine = !lineIndexToXOffset;
if (!lineIndexToXOffset) {
const lineData = this._model.getLineContent(lineNumber);
lineIndexToXOffset = [editorOptions_1.MINIMAP_GUTTER_WIDTH];
for (let i = 1; i < lineData.length + 1; i++) {
const charCode = lineData.charCodeAt(i - 1);
const dx = charCode === 9 /* Tab */
? tabSize * charWidth
: strings.isFullWidthCharacter(charCode)
? 2 * charWidth
: charWidth;
lineIndexToXOffset[i] = lineIndexToXOffset[i - 1] + dx;
}
lineOffsetMap.set(lineNumber, lineIndexToXOffset);
}
const { startColumn, endColumn, startLineNumber, endLineNumber } = decorationRange;
const x = startLineNumber === lineNumber ? lineIndexToXOffset[startColumn - 1] : editorOptions_1.MINIMAP_GUTTER_WIDTH;
const endColumnForLine = endLineNumber > lineNumber ? lineIndexToXOffset.length - 1 : endColumn - 1;
if (endColumnForLine > 0) {
// If the decoration starts at the last character of the column and spans over it, ensure it has a width
const width = lineIndexToXOffset[endColumnForLine] - x || 2;
this.renderDecoration(canvasContext, decorationColor, x, y, width, height);
}
if (isFirstDecorationForLine) {
this.renderLineHighlight(canvasContext, decorationColor, y, height);
}
}
renderLineHighlight(canvasContext, decorationColor, y, height) {
canvasContext.fillStyle = decorationColor && decorationColor.transparent(0.5).toString() || '';
canvasContext.fillRect(editorOptions_1.MINIMAP_GUTTER_WIDTH, y, canvasContext.canvas.width, height);
}
renderDecoration(canvasContext, decorationColor, x, y, width, height) {
canvasContext.fillStyle = decorationColor && decorationColor.toString() || '';
canvasContext.fillRect(x, y, width, height);
}
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.
let [_dirtyY1, _dirtyY2, needed] = InnerMinimap._renderUntouchedLines(imageData, 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 background = this._model.options.backgroundColor;
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 /* Text */ ? 2 /* BASE_CHAR_HEIGHT */ : 2 /* BASE_CHAR_HEIGHT */ + 1);
const renderMinimapLineHeight = baseCharHeight * fontScale;
const innerLinePadding = (minimapLineHeight > renderMinimapLineHeight ? Math.floor((minimapLineHeight - renderMinimapLineHeight) / 2) : 0);
// Render the rest of lines
let dy = 0;
const renderedLines = [];
for (let lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) {
if (needed[lineIndex]) {
InnerMinimap._renderLine(imageData, background, useLighterFont, renderMinimap, minimapCharWidth, tokensColorTracker, 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, 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 = 0;
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, useLighterFont, renderMinimap, charWidth, colorTracker, 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 /* 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 /* 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 /* Blocks */) {
minimapCharRenderer.blockRenderChar(target, dx, dy + innerLinePadding, tokenColor, backgroundColor, useLighterFont, force1pxHeight);
}
else { // RenderMinimap.Text
minimapCharRenderer.renderChar(target, dx, dy + innerLinePadding, charCode, tokenColor, backgroundColor, fontScale, useLighterFont, force1pxHeight);
}
dx += charWidth;
if (dx > maxDx) {
// hit edge of minimap
return;
}
}
}
}
}
}
}
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const minimapBackgroundValue = theme.getColor(colorRegistry_1.minimapBackground);
if (minimapBackgroundValue) {
collector.addRule(`.monaco-editor .minimap > canvas { opacity: ${minimapBackgroundValue.rgba.a}; will-change: opacity; }`);
}
const sliderBackground = theme.getColor(colorRegistry_1.minimapSliderBackground);
if (sliderBackground) {
collector.addRule(`.monaco-editor .minimap-slider .minimap-slider-horizontal { background: ${sliderBackground}; }`);
}
const sliderHoverBackground = theme.getColor(colorRegistry_1.minimapSliderHoverBackground);
if (sliderHoverBackground) {
collector.addRule(`.monaco-editor .minimap-slider:hover .minimap-slider-horizontal { background: ${sliderHoverBackground}; }`);
}
const sliderActiveBackground = theme.getColor(colorRegistry_1.minimapSliderActiveBackground);
if (sliderActiveBackground) {
collector.addRule(`.monaco-editor .minimap-slider.active .minimap-slider-horizontal { background: ${sliderActiveBackground}; }`);
}
const shadow = theme.getColor(colorRegistry_1.scrollbarShadow);
if (shadow) {
collector.addRule(`.monaco-editor .minimap-shadow-visible { box-shadow: ${shadow} -6px 0 6px -6px 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[600/*vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,47/*vs/editor/browser/view/viewPart*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,337/*vs/css!vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/]), function (require, exports, fastDomNode_1, viewPart_1, colorRegistry_1, themeService_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(91 /* 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(129 /* layoutInfo */);
if (layoutInfo.minimap.renderMinimap === 0 || (layoutInfo.minimap.minimapWidth > 0 && layoutInfo.minimap.minimapLeft === 0)) {
this._width = layoutInfo.width;
}
else {
this._width = layoutInfo.width - layoutInfo.minimap.minimapWidth - layoutInfo.verticalScrollbarWidth;
}
}
// --- begin event handlers
onConfigurationChanged(e) {
const options = this._context.configuration.options;
const scrollbar = options.get(91 /* 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;
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const shadow = theme.getColor(colorRegistry_1.scrollbarShadow);
if (shadow) {
collector.addRule(`.monaco-editor .scroll-decoration { box-shadow: ${shadow} 0 6px 6px -6px 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[601/*vs/editor/browser/viewParts/selections/selections*/], __M([0/*require*/,1/*exports*/,97/*vs/editor/browser/view/dynamicViewOverlay*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,338/*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 {
constructor(context) {
super();
this._previousFrameVisibleRangesWithStyle = [];
this._context = context;
const options = this._context.configuration.options;
this._lineHeight = options.get(57 /* lineHeight */);
this._roundedSelection = options.get(89 /* roundedSelection */);
this._typicalHalfwidthCharacterWidth = options.get(41 /* 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._lineHeight = options.get(57 /* lineHeight */);
this._roundedSelection = options.get(89 /* roundedSelection */);
this._typicalHalfwidthCharacterWidth = options.get(41 /* 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 /* EXTERN */,
bottom: 0 /* EXTERN */
};
const endStyle = {
top: 0 /* EXTERN */,
bottom: 0 /* 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 /* FLAT */;
}
else if (curLeft > prevLeft) {
startStyle.top = 1 /* INTERN */;
}
if (abs(curRight - prevRight) < epsilon) {
endStyle.top = 2 /* FLAT */;
}
else if (prevLeft < curRight && curRight < prevRight) {
endStyle.top = 1 /* 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 /* FLAT */;
}
else if (nextLeft < curLeft && curLeft < nextRight) {
startStyle.bottom = 1 /* INTERN */;
}
if (abs(curRight - nextRight) < epsilon) {
endStyle.bottom = 2 /* FLAT */;
}
else if (curRight < nextRight) {
endStyle.bottom = 1 /* 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, height, className, left, width) {
return ('<div class="cslr '
+ className
+ '" style="top:'
+ top.toString()
+ 'px;left:'
+ left.toString()
+ 'px;width:'
+ width.toString()
+ 'px;height:'
+ height
+ 'px;"></div>');
}
_actualRenderOneSelection(output2, visibleStartLineNumber, hasMultipleSelections, visibleRanges) {
if (visibleRanges.length === 0) {
return;
}
const visibleRangesHaveStyle = !!visibleRanges[0].ranges[0].startStyle;
const fullLineHeight = (this._lineHeight).toString();
const reducedLineHeight = (this._lineHeight - 1).toString();
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 lineHeight = hasMultipleSelections ? (lineNumber === lastLineNumber || lineNumber === firstLineNumber ? reducedLineHeight : fullLineHeight) : fullLineHeight;
const top = hasMultipleSelections ? (lineNumber === firstLineNumber ? 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 /* INTERN */ || startStyle.bottom === 1 /* INTERN */) {
// Reverse rounded corner to the left
// First comes the selection (blue layer)
innerCornerOutput += this._createSelectionPiece(top, lineHeight, 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 /* INTERN */) {
className += ' ' + SelectionsOverlay.SELECTION_TOP_RIGHT;
}
if (startStyle.bottom === 1 /* INTERN */) {
className += ' ' + SelectionsOverlay.SELECTION_BOTTOM_RIGHT;
}
innerCornerOutput += this._createSelectionPiece(top, lineHeight, className, visibleRange.left - SelectionsOverlay.ROUNDED_PIECE_WIDTH, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
}
if (endStyle.top === 1 /* INTERN */ || endStyle.bottom === 1 /* INTERN */) {
// Reverse rounded corner to the right
// First comes the selection (blue layer)
innerCornerOutput += this._createSelectionPiece(top, lineHeight, 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 /* INTERN */) {
className += ' ' + SelectionsOverlay.SELECTION_TOP_LEFT;
}
if (endStyle.bottom === 1 /* INTERN */) {
className += ' ' + SelectionsOverlay.SELECTION_BOTTOM_LEFT;
}
innerCornerOutput += this._createSelectionPiece(top, lineHeight, 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 /* EXTERN */) {
className += ' ' + SelectionsOverlay.SELECTION_TOP_LEFT;
}
if (startStyle.bottom === 0 /* EXTERN */) {
className += ' ' + SelectionsOverlay.SELECTION_BOTTOM_LEFT;
}
if (endStyle.top === 0 /* EXTERN */) {
className += ' ' + SelectionsOverlay.SELECTION_TOP_RIGHT;
}
if (endStyle.bottom === 0 /* EXTERN */) {
className += ' ' + SelectionsOverlay.SELECTION_BOTTOM_RIGHT;
}
}
restOfSelectionOutput += this._createSelectionPiece(top, lineHeight, 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;
SelectionsOverlay.SELECTION_CLASS_NAME = 'selected-text';
SelectionsOverlay.SELECTION_TOP_LEFT = 'top-left-radius';
SelectionsOverlay.SELECTION_BOTTOM_LEFT = 'bottom-left-radius';
SelectionsOverlay.SELECTION_TOP_RIGHT = 'top-right-radius';
SelectionsOverlay.SELECTION_BOTTOM_RIGHT = 'bottom-right-radius';
SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME = 'monaco-editor-background';
SelectionsOverlay.ROUNDED_PIECE_WIDTH = 10;
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const editorSelectionColor = theme.getColor(colorRegistry_1.editorSelectionBackground);
if (editorSelectionColor) {
collector.addRule(`.monaco-editor .focused .selected-text { background-color: ${editorSelectionColor}; }`);
}
const editorInactiveSelectionColor = theme.getColor(colorRegistry_1.editorInactiveSelection);
if (editorInactiveSelectionColor) {
collector.addRule(`.monaco-editor .selected-text { background-color: ${editorInactiveSelectionColor}; }`);
}
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[48/*vs/editor/common/view/editorColorRegistry*/], __M([0/*require*/,1/*exports*/,470/*vs/nls!vs/editor/common/view/editorColorRegistry*/,29/*vs/base/common/color*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/]), function (require, exports, nls, color_1, colorRegistry_1, themeService_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.overviewRulerInfo = exports.overviewRulerWarning = exports.overviewRulerError = exports.overviewRulerRangeHighlight = exports.ghostTextForeground = exports.ghostTextBorder = exports.editorUnnecessaryCodeOpacity = exports.editorUnnecessaryCodeBorder = exports.editorGutter = exports.editorOverviewRulerBackground = exports.editorOverviewRulerBorder = exports.editorBracketMatchBorder = exports.editorBracketMatchBackground = exports.editorCodeLensForeground = exports.editorRuler = exports.editorActiveLineNumber = exports.editorLineNumbers = exports.editorActiveIndentGuides = exports.editorIndentGuides = exports.editorWhitespaces = 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', { dark: null, light: null, hc: null }, nls.localize(0, null));
exports.editorLineHighlightBorder = (0, colorRegistry_1.registerColor)('editor.lineHighlightBorder', { dark: '#282828', light: '#eeeeee', hc: '#f38518' }, nls.localize(1, null));
exports.editorRangeHighlight = (0, colorRegistry_1.registerColor)('editor.rangeHighlightBackground', { dark: '#ffffff0b', light: '#fdff0033', hc: null }, nls.localize(2, null), true);
exports.editorRangeHighlightBorder = (0, colorRegistry_1.registerColor)('editor.rangeHighlightBorder', { dark: null, light: null, hc: colorRegistry_1.activeContrastBorder }, nls.localize(3, null), true);
exports.editorSymbolHighlight = (0, colorRegistry_1.registerColor)('editor.symbolHighlightBackground', { dark: colorRegistry_1.editorFindMatchHighlight, light: colorRegistry_1.editorFindMatchHighlight, hc: null }, nls.localize(4, null), true);
exports.editorSymbolHighlightBorder = (0, colorRegistry_1.registerColor)('editor.symbolHighlightBorder', { dark: null, light: null, hc: colorRegistry_1.activeContrastBorder }, nls.localize(5, null), true);
exports.editorCursorForeground = (0, colorRegistry_1.registerColor)('editorCursor.foreground', { dark: '#AEAFAD', light: color_1.Color.black, hc: color_1.Color.white }, nls.localize(6, null));
exports.editorCursorBackground = (0, colorRegistry_1.registerColor)('editorCursor.background', null, nls.localize(7, null));
exports.editorWhitespaces = (0, colorRegistry_1.registerColor)('editorWhitespace.foreground', { dark: '#e3e4e229', light: '#33333333', hc: '#e3e4e229' }, nls.localize(8, null));
exports.editorIndentGuides = (0, colorRegistry_1.registerColor)('editorIndentGuide.background', { dark: exports.editorWhitespaces, light: exports.editorWhitespaces, hc: exports.editorWhitespaces }, nls.localize(9, null));
exports.editorActiveIndentGuides = (0, colorRegistry_1.registerColor)('editorIndentGuide.activeBackground', { dark: exports.editorWhitespaces, light: exports.editorWhitespaces, hc: exports.editorWhitespaces }, nls.localize(10, null));
exports.editorLineNumbers = (0, colorRegistry_1.registerColor)('editorLineNumber.foreground', { dark: '#858585', light: '#237893', hc: color_1.Color.white }, nls.localize(11, null));
const deprecatedEditorActiveLineNumber = (0, colorRegistry_1.registerColor)('editorActiveLineNumber.foreground', { dark: '#c6c6c6', light: '#0B216F', hc: colorRegistry_1.activeContrastBorder }, nls.localize(12, null), false, nls.localize(13, null));
exports.editorActiveLineNumber = (0, colorRegistry_1.registerColor)('editorLineNumber.activeForeground', { dark: deprecatedEditorActiveLineNumber, light: deprecatedEditorActiveLineNumber, hc: deprecatedEditorActiveLineNumber }, nls.localize(14, null));
exports.editorRuler = (0, colorRegistry_1.registerColor)('editorRuler.foreground', { dark: '#5A5A5A', light: color_1.Color.lightgrey, hc: color_1.Color.white }, nls.localize(15, null));
exports.editorCodeLensForeground = (0, colorRegistry_1.registerColor)('editorCodeLens.foreground', { dark: '#999999', light: '#919191', hc: '#999999' }, nls.localize(16, null));
exports.editorBracketMatchBackground = (0, colorRegistry_1.registerColor)('editorBracketMatch.background', { dark: '#0064001a', light: '#0064001a', hc: '#0064001a' }, nls.localize(17, null));
exports.editorBracketMatchBorder = (0, colorRegistry_1.registerColor)('editorBracketMatch.border', { dark: '#888', light: '#B9B9B9', hc: colorRegistry_1.contrastBorder }, nls.localize(18, null));
exports.editorOverviewRulerBorder = (0, colorRegistry_1.registerColor)('editorOverviewRuler.border', { dark: '#7f7f7f4d', light: '#7f7f7f4d', hc: '#7f7f7f4d' }, nls.localize(19, null));
exports.editorOverviewRulerBackground = (0, colorRegistry_1.registerColor)('editorOverviewRuler.background', null, nls.localize(20, null));
exports.editorGutter = (0, colorRegistry_1.registerColor)('editorGutter.background', { dark: colorRegistry_1.editorBackground, light: colorRegistry_1.editorBackground, hc: colorRegistry_1.editorBackground }, nls.localize(21, null));
exports.editorUnnecessaryCodeBorder = (0, colorRegistry_1.registerColor)('editorUnnecessaryCode.border', { dark: null, light: null, hc: color_1.Color.fromHex('#fff').transparent(0.8) }, nls.localize(22, null));
exports.editorUnnecessaryCodeOpacity = (0, colorRegistry_1.registerColor)('editorUnnecessaryCode.opacity', { dark: color_1.Color.fromHex('#000a'), light: color_1.Color.fromHex('#0007'), hc: null }, nls.localize(23, null));
exports.ghostTextBorder = (0, colorRegistry_1.registerColor)('editorGhostText.border', { dark: null, light: null, hc: color_1.Color.fromHex('#fff').transparent(0.8) }, nls.localize(24, null));
exports.ghostTextForeground = (0, colorRegistry_1.registerColor)('editorGhostText.foreground', { dark: color_1.Color.fromHex('#ffffff56'), light: color_1.Color.fromHex('#0007'), hc: null }, nls.localize(25, null));
const rulerRangeDefault = new color_1.Color(new color_1.RGBA(0, 122, 204, 0.6));
exports.overviewRulerRangeHighlight = (0, colorRegistry_1.registerColor)('editorOverviewRuler.rangeHighlightForeground', { dark: rulerRangeDefault, light: rulerRangeDefault, hc: rulerRangeDefault }, nls.localize(26, null), 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)), hc: new color_1.Color(new color_1.RGBA(255, 50, 50, 1)) }, nls.localize(27, null));
exports.overviewRulerWarning = (0, colorRegistry_1.registerColor)('editorOverviewRuler.warningForeground', { dark: colorRegistry_1.editorWarningForeground, light: colorRegistry_1.editorWarningForeground, hc: colorRegistry_1.editorWarningBorder }, nls.localize(28, null));
exports.overviewRulerInfo = (0, colorRegistry_1.registerColor)('editorOverviewRuler.infoForeground', { dark: colorRegistry_1.editorInfoForeground, light: colorRegistry_1.editorInfoForeground, hc: colorRegistry_1.editorInfoBorder }, nls.localize(29, null));
// 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);
if (background) {
collector.addRule(`.monaco-editor, .monaco-editor-background, .monaco-editor .inputarea.ime-input { background-color: ${background}; }`);
}
const foreground = theme.getColor(colorRegistry_1.editorForeground);
if (foreground) {
collector.addRule(`.monaco-editor, .monaco-editor .inputarea.ime-input { color: ${foreground}; }`);
}
const gutter = theme.getColor(exports.editorGutter);
if (gutter) {
collector.addRule(`.monaco-editor .margin { background-color: ${gutter}; }`);
}
const rangeHighlight = theme.getColor(exports.editorRangeHighlight);
if (rangeHighlight) {
collector.addRule(`.monaco-editor .rangeHighlight { background-color: ${rangeHighlight}; }`);
}
const rangeHighlightBorder = theme.getColor(exports.editorRangeHighlightBorder);
if (rangeHighlightBorder) {
collector.addRule(`.monaco-editor .rangeHighlight { border: 1px ${theme.type === 'hc' ? 'dotted' : 'solid'} ${rangeHighlightBorder}; }`);
}
const symbolHighlight = theme.getColor(exports.editorSymbolHighlight);
if (symbolHighlight) {
collector.addRule(`.monaco-editor .symbolHighlight { background-color: ${symbolHighlight}; }`);
}
const symbolHighlightBorder = theme.getColor(exports.editorSymbolHighlightBorder);
if (symbolHighlightBorder) {
collector.addRule(`.monaco-editor .symbolHighlight { border: 1px ${theme.type === 'hc' ? 'dotted' : 'solid'} ${symbolHighlightBorder}; }`);
}
const invisibles = theme.getColor(exports.editorWhitespaces);
if (invisibles) {
collector.addRule(`.monaco-editor .mtkw { color: ${invisibles} !important; }`);
collector.addRule(`.monaco-editor .mtkz { color: ${invisibles} !important; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/browser/viewParts/currentLineHighlight/currentLineHighlight*/], __M([0/*require*/,1/*exports*/,97/*vs/editor/browser/view/dynamicViewOverlay*/,48/*vs/editor/common/view/editorColorRegistry*/,19/*vs/base/common/arrays*/,11/*vs/platform/theme/common/themeService*/,21/*vs/editor/common/core/selection*/,326/*vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/]), function (require, exports, dynamicViewOverlay_1, editorColorRegistry_1, arrays, themeService_1, selection_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CurrentLineMarginHighlightOverlay = exports.CurrentLineHighlightOverlay = exports.AbstractLineHighlightOverlay = void 0;
let isRenderedUsingBorder = true;
class AbstractLineHighlightOverlay extends dynamicViewOverlay_1.DynamicViewOverlay {
constructor(context) {
super();
this._context = context;
const options = this._context.configuration.options;
const layoutInfo = options.get(129 /* layoutInfo */);
this._lineHeight = options.get(57 /* lineHeight */);
this._renderLineHighlight = options.get(84 /* renderLineHighlight */);
this._renderLineHighlightOnlyWhenFocus = options.get(85 /* renderLineHighlightOnlyWhenFocus */);
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;
// Only render the first selection when using border
const renderSelections = isRenderedUsingBorder ? this._selections.slice(0, 1) : this._selections;
const cursorsLineNumbers = renderSelections.map(s => s.positionLineNumber);
cursorsLineNumbers.sort((a, b) => a - b);
if (!arrays.equals(this._cursorLineNumbers, cursorsLineNumbers)) {
this._cursorLineNumbers = cursorsLineNumbers;
hasChanged = true;
}
const selectionIsEmpty = renderSelections.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(129 /* layoutInfo */);
this._lineHeight = options.get(57 /* lineHeight */);
this._renderLineHighlight = options.get(84 /* renderLineHighlight */);
this._renderLineHighlightOnlyWhenFocus = options.get(85 /* renderLineHighlightOnlyWhenFocus */);
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 renderedLine = this._renderOne(ctx);
const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
const len = this._cursorLineNumbers.length;
let index = 0;
const renderData = [];
for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
const lineIndex = lineNumber - visibleStartLineNumber;
while (index < len && this._cursorLineNumbers[index] < lineNumber) {
index++;
}
if (index < len && this._cursorLineNumbers[index] === lineNumber) {
renderData[lineIndex] = renderedLine;
}
else {
renderData[lineIndex] = '';
}
}
this._renderData = renderData;
}
render(startLineNumber, lineNumber) {
if (!this._renderData) {
return '';
}
const lineIndex = lineNumber - startLineNumber;
if (lineIndex >= this._renderData.length) {
return '';
}
return this._renderData[lineIndex];
}
}
exports.AbstractLineHighlightOverlay = AbstractLineHighlightOverlay;
class CurrentLineHighlightOverlay extends AbstractLineHighlightOverlay {
_renderOne(ctx) {
const className = 'current-line' + (this._shouldRenderOther() ? ' current-line-both' : '');
return `<div class="${className}" style="width:${Math.max(ctx.scrollWidth, this._contentWidth)}px; height:${this._lineHeight}px;"></div>`;
}
_shouldRenderThis() {
return ((this._renderLineHighlight === 'line' || this._renderLineHighlight === 'all')
&& this._selectionIsEmpty
&& (!this._renderLineHighlightOnlyWhenFocus || this._focused));
}
_shouldRenderOther() {
return ((this._renderLineHighlight === 'gutter' || this._renderLineHighlight === 'all')
&& (!this._renderLineHighlightOnlyWhenFocus || this._focused));
}
}
exports.CurrentLineHighlightOverlay = CurrentLineHighlightOverlay;
class CurrentLineMarginHighlightOverlay extends AbstractLineHighlightOverlay {
_renderOne(ctx) {
const className = 'current-line' + (this._shouldRenderMargin() ? ' current-line-margin' : '') + (this._shouldRenderOther() ? ' current-line-margin-both' : '');
return `<div class="${className}" style="width:${this._contentLeft}px; height:${this._lineHeight}px;"></div>`;
}
_shouldRenderMargin() {
return ((this._renderLineHighlight === 'gutter' || this._renderLineHighlight === 'all')
&& (!this._renderLineHighlightOnlyWhenFocus || this._focused));
}
_shouldRenderThis() {
return true;
}
_shouldRenderOther() {
return ((this._renderLineHighlight === 'line' || this._renderLineHighlight === 'all')
&& this._selectionIsEmpty
&& (!this._renderLineHighlightOnlyWhenFocus || this._focused));
}
}
exports.CurrentLineMarginHighlightOverlay = CurrentLineMarginHighlightOverlay;
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
isRenderedUsingBorder = false;
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) {
isRenderedUsingBorder = true;
collector.addRule(`.monaco-editor .view-overlays .current-line { border: 2px solid ${lineHighlightBorder}; }`);
collector.addRule(`.monaco-editor .margin-view-overlays .current-line-margin { border: 2px solid ${lineHighlightBorder}; }`);
if (theme.type === 'hc') {
collector.addRule(`.monaco-editor .view-overlays .current-line { border-width: 1px; }`);
collector.addRule(`.monaco-editor .margin-view-overlays .current-line-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[603/*vs/editor/browser/viewParts/indentGuides/indentGuides*/], __M([0/*require*/,1/*exports*/,97/*vs/editor/browser/view/dynamicViewOverlay*/,13/*vs/editor/common/core/position*/,48/*vs/editor/common/view/editorColorRegistry*/,11/*vs/platform/theme/common/themeService*/,329/*vs/css!vs/editor/browser/viewParts/indentGuides/indentGuides*/]), function (require, exports, dynamicViewOverlay_1, position_1, editorColorRegistry_1, themeService_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._primaryLineNumber = 0;
const options = this._context.configuration.options;
const wrappingInfo = options.get(130 /* wrappingInfo */);
const fontInfo = options.get(41 /* fontInfo */);
this._lineHeight = options.get(57 /* lineHeight */);
this._spaceWidth = fontInfo.spaceWidth;
this._enabled = options.get(82 /* renderIndentGuides */);
this._activeIndentEnabled = options.get(50 /* highlightActiveIndentGuide */);
this._maxIndentLeft = wrappingInfo.wrappingColumn === -1 ? -1 : (wrappingInfo.wrappingColumn * 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;
const wrappingInfo = options.get(130 /* wrappingInfo */);
const fontInfo = options.get(41 /* fontInfo */);
this._lineHeight = options.get(57 /* lineHeight */);
this._spaceWidth = fontInfo.spaceWidth;
this._enabled = options.get(82 /* renderIndentGuides */);
this._activeIndentEnabled = options.get(50 /* highlightActiveIndentGuide */);
this._maxIndentLeft = wrappingInfo.wrappingColumn === -1 ? -1 : (wrappingInfo.wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth);
return true;
}
onCursorStateChanged(e) {
const selection = e.selections[0];
const newPrimaryLineNumber = selection.isEmpty() ? selection.positionLineNumber : 0;
if (this._primaryLineNumber !== newPrimaryLineNumber) {
this._primaryLineNumber = newPrimaryLineNumber;
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._enabled) {
this._renderResult = null;
return;
}
const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
const { indentSize } = this._context.model.getTextModelOptions();
const indentWidth = indentSize * this._spaceWidth;
const scrollWidth = ctx.scrollWidth;
const lineHeight = this._lineHeight;
const indents = this._context.model.getLinesIndentGuides(visibleStartLineNumber, visibleEndLineNumber);
let activeIndentStartLineNumber = 0;
let activeIndentEndLineNumber = 0;
let activeIndentLevel = 0;
if (this._activeIndentEnabled && this._primaryLineNumber) {
const activeIndentInfo = this._context.model.getActiveIndentGuide(this._primaryLineNumber, visibleStartLineNumber, visibleEndLineNumber);
activeIndentStartLineNumber = activeIndentInfo.startLineNumber;
activeIndentEndLineNumber = activeIndentInfo.endLineNumber;
activeIndentLevel = activeIndentInfo.indent;
}
const output = [];
for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
const containsActiveIndentGuide = (activeIndentStartLineNumber <= lineNumber && lineNumber <= activeIndentEndLineNumber);
const lineIndex = lineNumber - visibleStartLineNumber;
const indent = indents[lineIndex];
let result = '';
if (indent >= 1) {
const leftMostVisiblePosition = ctx.visibleRangeForPosition(new position_1.Position(lineNumber, 1));
let left = leftMostVisiblePosition ? leftMostVisiblePosition.left : 0;
for (let i = 1; i <= indent; i++) {
const className = (containsActiveIndentGuide && i === activeIndentLevel ? 'cigra' : 'cigr');
result += `<div class="${className}" style="left:${left}px;height:${lineHeight}px;width:${indentWidth}px"></div>`;
left += indentWidth;
if (left > scrollWidth || (this._maxIndentLeft > 0 && left > this._maxIndentLeft)) {
break;
}
}
}
output[lineIndex] = result;
}
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.IndentGuidesOverlay = IndentGuidesOverlay;
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const editorIndentGuidesColor = theme.getColor(editorColorRegistry_1.editorIndentGuides);
if (editorIndentGuidesColor) {
collector.addRule(`.monaco-editor .lines-content .cigr { box-shadow: 1px 0 0 0 ${editorIndentGuidesColor} inset; }`);
}
const editorActiveIndentGuidesColor = theme.getColor(editorColorRegistry_1.editorActiveIndentGuides) || editorIndentGuidesColor;
if (editorActiveIndentGuidesColor) {
collector.addRule(`.monaco-editor .lines-content .cigra { box-shadow: 1px 0 0 0 ${editorActiveIndentGuidesColor} 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[260/*vs/editor/browser/viewParts/lineNumbers/lineNumbers*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,97/*vs/editor/browser/view/dynamicViewOverlay*/,13/*vs/editor/common/core/position*/,48/*vs/editor/common/view/editorColorRegistry*/,11/*vs/platform/theme/common/themeService*/,330/*vs/css!vs/editor/browser/viewParts/lineNumbers/lineNumbers*/]), function (require, exports, platform, dynamicViewOverlay_1, position_1, editorColorRegistry_1, themeService_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LineNumbersOverlay = void 0;
class LineNumbersOverlay extends dynamicViewOverlay_1.DynamicViewOverlay {
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(57 /* lineHeight */);
const lineNumbers = options.get(58 /* lineNumbers */);
this._renderLineNumbers = lineNumbers.renderType;
this._renderCustomLineNumbers = lineNumbers.renderFn;
this._renderFinalNewline = options.get(83 /* renderFinalNewline */);
const layoutInfo = options.get(129 /* 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.model.coordinatesConverter.convertViewPositionToModelPosition(primaryViewPosition);
let shouldRender = false;
if (this._activeLineNumber !== primaryViewPosition.lineNumber) {
this._activeLineNumber = primaryViewPosition.lineNumber;
shouldRender = true;
}
if (this._renderLineNumbers === 2 /* Relative */ || this._renderLineNumbers === 3 /* 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;
}
// --- end event handlers
_getLineRenderLineNumber(viewLineNumber) {
const modelPosition = this._context.model.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 /* 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 /* Interval */) {
if (this._lastCursorModelPosition.lineNumber === modelLineNumber) {
return String(modelLineNumber);
}
if (modelLineNumber % 10 === 0) {
return String(modelLineNumber);
}
return '';
}
return String(modelLineNumber);
}
prepareRender(ctx) {
if (this._renderLineNumbers === 0 /* 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 common = '<div class="' + LineNumbersOverlay.CLASS_NAME + lineHeightClassName + '" style="left:' + this._lineNumbersLeft + 'px;width:' + this._lineNumbersWidth + 'px;">';
const lineCount = this._context.model.getLineCount();
const output = [];
for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
const lineIndex = lineNumber - visibleStartLineNumber;
if (!this._renderFinalNewline) {
if (lineNumber === lineCount && this._context.model.getLineLength(lineNumber) === 0) {
// Do not render last (empty) line
output[lineIndex] = '';
continue;
}
}
const renderLineNumber = this._getLineRenderLineNumber(lineNumber);
if (renderLineNumber) {
if (lineNumber === this._activeLineNumber) {
output[lineIndex] = ('<div class="active-line-number ' + LineNumbersOverlay.CLASS_NAME + lineHeightClassName + '" style="left:' + this._lineNumbersLeft + 'px;width:' + this._lineNumbersWidth + 'px;">'
+ renderLineNumber
+ '</div>');
}
else {
output[lineIndex] = (common
+ renderLineNumber
+ '</div>');
}
}
else {
output[lineIndex] = '';
}
}
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;
LineNumbersOverlay.CLASS_NAME = 'line-numbers';
// theming
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const lineNumbers = theme.getColor(editorColorRegistry_1.editorLineNumbers);
if (lineNumbers) {
collector.addRule(`.monaco-editor .line-numbers { color: ${lineNumbers}; }`);
}
const activeLineNumber = theme.getColor(editorColorRegistry_1.editorActiveLineNumber);
if (activeLineNumber) {
collector.addRule(`.monaco-editor .line-numbers.active-line-number { color: ${activeLineNumber}; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/controller/textAreaHandler*/], __M([0/*require*/,1/*exports*/,455/*vs/nls!vs/editor/browser/controller/textAreaHandler*/,39/*vs/base/browser/browser*/,30/*vs/base/browser/fastDomNode*/,17/*vs/base/common/platform*/,8/*vs/base/common/strings*/,65/*vs/editor/browser/config/configuration*/,169/*vs/editor/browser/controller/textAreaInput*/,216/*vs/editor/browser/controller/textAreaState*/,47/*vs/editor/browser/view/viewPart*/,260/*vs/editor/browser/viewParts/lineNumbers/lineNumbers*/,225/*vs/editor/browser/viewParts/margin/margin*/,35/*vs/editor/common/config/editorOptions*/,109/*vs/editor/common/controller/wordCharacterClassifier*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,131/*vs/base/browser/ui/mouseCursor/mouseCursor*/,325/*vs/css!vs/editor/browser/controller/textAreaHandler*/]), function (require, exports, nls, browser, fastDomNode_1, platform, strings, configuration_1, textAreaInput_1, textAreaState_1, viewPart_1, lineNumbers_1, margin_1, editorOptions_1, wordCharacterClassifier_1, position_1, range_1, selection_1, mouseCursor_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TextAreaHandler = void 0;
class VisibleTextAreaData {
constructor(top, left, width) {
this._visibleTextAreaBrand = undefined;
this.top = top;
this.left = left;
this.width = width;
}
setWidth(width) {
return new VisibleTextAreaData(this.top, this.left, width);
}
}
const canUseZeroSizeTextarea = (browser.isFirefox);
class TextAreaHandler extends viewPart_1.ViewPart {
constructor(context, viewController, viewHelper) {
super(context);
// --- end view API
this._primaryCursorPosition = new position_1.Position(1, 1);
this._primaryCursorVisibleRange = null;
this._viewController = viewController;
this._viewHelper = viewHelper;
this._scrollLeft = 0;
this._scrollTop = 0;
const options = this._context.configuration.options;
const layoutInfo = options.get(129 /* layoutInfo */);
this._setAccessibilityOptions(options);
this._contentLeft = layoutInfo.contentLeft;
this._contentWidth = layoutInfo.contentWidth;
this._contentHeight = layoutInfo.height;
this._fontInfo = options.get(41 /* fontInfo */);
this._lineHeight = options.get(57 /* lineHeight */);
this._emptySelectionClipboard = options.get(30 /* emptySelectionClipboard */);
this._copyWithSyntaxHighlighting = options.get(19 /* 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, 6 /* TextArea */);
this.textArea.setClassName(`inputarea ${mouseCursor_1.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
this.textArea.setAttribute('wrap', 'off');
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('tabindex', String(options.get(111 /* tabIndex */)));
this.textArea.setAttribute('role', 'textbox');
this.textArea.setAttribute('aria-roledescription', nls.localize(0, null));
this.textArea.setAttribute('aria-multiline', 'true');
this.textArea.setAttribute('aria-haspopup', 'false');
this.textArea.setAttribute('aria-autocomplete', 'both');
if (options.get(28 /* domReadOnly */) && options.get(79 /* readOnly */)) {
this.textArea.setAttribute('readonly', 'true');
}
this.textAreaCover = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
this.textAreaCover.setPosition('absolute');
const simpleModel = {
getLineCount: () => {
return this._context.model.getLineCount();
},
getLineMaxColumn: (lineNumber) => {
return this._context.model.getLineMaxColumn(lineNumber);
},
getValueInRange: (range, eol) => {
return this._context.model.getValueInRange(range, eol);
}
};
const textAreaInputHost = {
getDataToCopy: (generateHTML) => {
const rawTextToCopy = this._context.model.getPlainTextToCopy(this._modelSelections, this._emptySelectionClipboard, platform.isWindows);
const newLineCharacter = this._context.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 (generateHTML) {
if (textAreaInput_1.CopyOptions.forceCopyWithSyntaxHighlighting || (this._copyWithSyntaxHighlighting && text.length < 65536)) {
const richText = this._context.model.getRichTextToCopy(this._modelSelections, this._emptySelectionClipboard);
if (richText) {
html = richText.html;
mode = richText.mode;
}
}
}
return {
isFromEmptySelection,
multicursorText,
text,
html,
mode
};
},
getScreenReaderContent: (currentState) => {
if (this._accessibilitySupport === 1 /* 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
if (platform.isMacintosh) {
const selection = this._selections[0];
if (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, position, position);
}
}
}
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, position, position);
}
}
return textAreaState_1.TextAreaState.EMPTY;
}
return textAreaState_1.PagedScreenReaderStrategy.fromEditorSelection(currentState, simpleModel, this._selections[0], this._accessibilityPageSize, this._accessibilitySupport === 0 /* Unknown */);
},
deduceModelPosition: (viewAnchorPosition, deltaOffset, lineFeedCnt) => {
return this._context.model.deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt);
}
};
this._textAreaInput = this._register(new textAreaInput_1.TextAreaInput(textAreaInputHost, this.textArea));
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) => {
const lineNumber = this._selections[0].startLineNumber;
const column = this._selections[0].startColumn + e.revealDeltaColumns;
this._context.model.revealRange('keyboard', true, new range_1.Range(lineNumber, column, lineNumber, column), 0 /* Simple */, 1 /* Immediate */);
// Find range pixel position
const visibleRange = this._viewHelper.visibleRangeForPositionRelativeToEditor(lineNumber, column);
if (visibleRange) {
this._visibleTextArea = new VisibleTextAreaData(this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber), visibleRange.left, canUseZeroSizeTextarea ? 0 : 1);
this._render();
}
// Show the textarea
this.textArea.setClassName(`inputarea ${mouseCursor_1.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME} ime-input`);
this._viewController.compositionStart();
this._context.model.onCompositionStart();
}));
this._register(this._textAreaInput.onCompositionUpdate((e) => {
if (!this._visibleTextArea) {
return;
}
// adjust width by its size
this._visibleTextArea = this._visibleTextArea.setWidth(measureText(e.data, this._fontInfo));
this._render();
}));
this._register(this._textAreaInput.onCompositionEnd(() => {
this._visibleTextArea = null;
this._render();
this.textArea.setClassName(`inputarea ${mouseCursor_1.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
this._viewController.compositionEnd();
this._context.model.onCompositionEnd();
}));
this._register(this._textAreaInput.onFocus(() => {
this._context.model.setHasFocus(true);
}));
this._register(this._textAreaInput.onBlur(() => {
this._context.model.setHasFocus(false);
}));
}
dispose() {
super.dispose();
}
_getAndroidWordAtPosition(position) {
const ANDROID_WORD_SEPARATORS = '`~!@#$%^&*()-=+[{]}\\|;:",.<>/?';
const lineContent = this._context.model.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 /* 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 /* Regular */) {
goingRight = false;
}
else {
endColumn++;
}
}
distance++;
}
return [lineContent.substring(startColumn - 1, endColumn - 1), position.column - startColumn];
}
_getWordBeforePosition(position) {
const lineContent = this._context.model.getLineContent(position.lineNumber);
const wordSeparators = (0, wordCharacterClassifier_1.getMapForWordSeparators)(this._context.configuration.options.get(115 /* 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 /* 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.model.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 /* accessibilitySupport */);
if (accessibilitySupport === 1 /* Disabled */) {
return nls.localize(1, null, platform.isLinux ? 'Shift+Alt+F1' : 'Alt+F1');
}
return options.get(4 /* ariaLabel */);
}
_setAccessibilityOptions(options) {
this._accessibilitySupport = options.get(2 /* accessibilitySupport */);
const accessibilityPageSize = options.get(3 /* accessibilityPageSize */);
if (this._accessibilitySupport === 2 /* Enabled */ && accessibilityPageSize === editorOptions_1.EditorOptions.accessibilityPageSize.defaultValue) {
// If a screen reader is attached and the default value is not set we shuold automatically increase the page size to 500 for a better experience
this._accessibilityPageSize = 500;
}
else {
this._accessibilityPageSize = accessibilityPageSize;
}
}
// --- begin event handlers
onConfigurationChanged(e) {
const options = this._context.configuration.options;
const layoutInfo = options.get(129 /* layoutInfo */);
this._setAccessibilityOptions(options);
this._contentLeft = layoutInfo.contentLeft;
this._contentWidth = layoutInfo.contentWidth;
this._contentHeight = layoutInfo.height;
this._fontInfo = options.get(41 /* fontInfo */);
this._lineHeight = options.get(57 /* lineHeight */);
this._emptySelectionClipboard = options.get(30 /* emptySelectionClipboard */);
this._copyWithSyntaxHighlighting = options.get(19 /* copyWithSyntaxHighlighting */);
this.textArea.setAttribute('aria-label', this._getAriaLabel(options));
this.textArea.setAttribute('tabindex', String(options.get(111 /* tabIndex */)));
if (e.hasChanged(28 /* domReadOnly */) || e.hasChanged(79 /* readOnly */)) {
if (options.get(28 /* domReadOnly */) && options.get(79 /* readOnly */)) {
this.textArea.setAttribute('readonly', 'true');
}
else {
this.textArea.removeAttribute('readonly');
}
}
if (e.hasChanged(2 /* accessibilitySupport */)) {
this._textAreaInput.writeScreenReaderContent('strategy changed');
}
return true;
}
onCursorStateChanged(e) {
this._selections = e.selections.slice(0);
this._modelSelections = e.modelSelections.slice(0);
this._textAreaInput.writeScreenReaderContent('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);
}
}
prepareRender(ctx) {
this._primaryCursorPosition = new position_1.Position(this._selections[0].positionLineNumber, this._selections[0].positionColumn);
this._primaryCursorVisibleRange = ctx.visibleRangeForPosition(this._primaryCursorPosition);
}
render(ctx) {
this._textAreaInput.writeScreenReaderContent('render');
this._render();
}
_render() {
if (this._visibleTextArea) {
// The text area is visible for composition reasons
this._renderInsideEditor(null, this._visibleTextArea.top - this._scrollTop, this._contentLeft + this._visibleTextArea.left - this._scrollLeft, this._visibleTextArea.width, this._lineHeight);
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) {
// 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._renderInsideEditor(this._primaryCursorPosition, top, left, canUseZeroSizeTextarea ? 0 : 1, this._lineHeight);
return;
}
this._renderInsideEditor(this._primaryCursorPosition, top, left, canUseZeroSizeTextarea ? 0 : 1, canUseZeroSizeTextarea ? 0 : 1);
}
_renderInsideEditor(renderedPosition, top, left, width, height) {
this._lastRenderPosition = renderedPosition;
const ta = this.textArea;
const tac = this.textAreaCover;
configuration_1.Configuration.applyFontInfo(ta, this._fontInfo);
ta.setTop(top);
ta.setLeft(left);
ta.setWidth(width);
ta.setHeight(height);
tac.setTop(0);
tac.setLeft(0);
tac.setWidth(0);
tac.setHeight(0);
}
_renderAtTopLeft() {
this._lastRenderPosition = null;
const ta = this.textArea;
const tac = this.textAreaCover;
configuration_1.Configuration.applyFontInfo(ta, this._fontInfo);
ta.setTop(0);
ta.setLeft(0);
tac.setTop(0);
tac.setLeft(0);
if (canUseZeroSizeTextarea) {
ta.setWidth(0);
ta.setHeight(0);
tac.setWidth(0);
tac.setHeight(0);
return;
}
// (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.
ta.setWidth(1);
ta.setHeight(1);
tac.setWidth(1);
tac.setHeight(1);
const options = this._context.configuration.options;
if (options.get(47 /* glyphMargin */)) {
tac.setClassName('monaco-editor-background textAreaCover ' + margin_1.Margin.OUTER_CLASS_NAME);
}
else {
if (options.get(58 /* lineNumbers */).renderType !== 0 /* Off */) {
tac.setClassName('monaco-editor-background textAreaCover ' + lineNumbers_1.LineNumbersOverlay.CLASS_NAME);
}
else {
tac.setClassName('monaco-editor-background textAreaCover');
}
}
}
}
exports.TextAreaHandler = TextAreaHandler;
function measureText(text, fontInfo) {
// adjust width by its size
const canvasElem = document.createElement('canvas');
const context = canvasElem.getContext('2d');
context.font = createFontString(fontInfo);
const metrics = context.measureText(text);
if (browser.isFirefox) {
return metrics.width + 2; // +2 for Japanese...
}
else {
return metrics.width;
}
}
function createFontString(bareFontInfo) {
return doCreateFontString('normal', bareFontInfo.fontWeight, bareFontInfo.fontSize, bareFontInfo.lineHeight, bareFontInfo.fontFamily);
}
function doCreateFontString(fontStyle, fontWeight, fontSize, lineHeight, fontFamily) {
// The full font syntax is:
// style | variant | weight | stretch | size/line-height | fontFamily
// (https://developer.mozilla.org/en-US/docs/Web/CSS/font)
// But it appears Edge and IE11 cannot properly parse `stretch`.
return `${fontStyle} normal ${fontWeight} ${fontSize}px / ${lineHeight}px ${fontFamily}`;
}
});
/*---------------------------------------------------------------------------------------------
* 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/browser/viewParts/overviewRuler/decorationsOverviewRuler*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,29/*vs/base/common/color*/,47/*vs/editor/browser/view/viewPart*/,13/*vs/editor/common/core/position*/,18/*vs/editor/common/modes*/,48/*vs/editor/common/view/editorColorRegistry*/]), function (require, exports, fastDomNode_1, color_1, viewPart_1, position_1, modes_1, editorColorRegistry_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(57 /* lineHeight */);
this.pixelRatio = options.get(127 /* pixelRatio */);
this.overviewRulerLanes = options.get(72 /* overviewRulerLanes */);
this.renderBorder = options.get(71 /* overviewRulerBorder */);
const borderColor = theme.getColor(editorColorRegistry_1.editorOverviewRulerBorder);
this.borderColor = borderColor ? borderColor.toString() : null;
this.hideCursor = options.get(49 /* hideCursorInOverviewRuler */);
const cursorColor = theme.getColor(editorColorRegistry_1.editorCursorForeground);
this.cursorColor = cursorColor ? cursorColor.transparent(0.7).toString() : null;
this.themeType = theme.type;
const minimapOpts = options.get(63 /* minimap */);
const minimapEnabled = minimapOpts.enabled;
const minimapSide = minimapOpts.side;
const backgroundColor = minimapEnabled
? theme.getColor(editorColorRegistry_1.editorOverviewRulerBackground) || modes_1.TokenizationRegistry.getDefaultBackground()
: null;
if (backgroundColor === null || minimapSide === 'left') {
this.backgroundColor = null;
}
else {
this.backgroundColor = color_1.Color.Format.CSS.formatHex(backgroundColor);
}
const layoutInfo = options.get(129 /* 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,
centerOffset,
leftOffset,
rightOffset,
leftOffset,
centerOffset,
leftOffset, // Left | Center | Right
], [
0,
leftWidth,
centerWidth,
leftWidth + centerWidth,
rightWidth,
leftWidth + centerWidth + rightWidth,
centerWidth + rightWidth,
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,
leftOffset,
leftOffset,
rightOffset,
leftOffset,
leftOffset,
leftOffset, // Left | Center | Right
], [
0,
leftWidth,
leftWidth,
leftWidth,
rightWidth,
leftWidth + rightWidth,
leftWidth + rightWidth,
leftWidth + rightWidth, // Left | Center | Right
]
];
}
else {
const offset = canvasLeftOffset;
const width = remainingWidth;
return [
[
0,
offset,
offset,
offset,
offset,
offset,
offset,
offset, // Left | Center | Right
], [
0,
width,
width,
width,
width,
width,
width,
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.cursorColor === other.cursorColor
&& this.themeType === other.themeType
&& 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._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 = modes_1.TokenizationRegistry.onDidChange((e) => {
if (e.changedColorMap) {
this._updateSettings(true);
}
});
this._cursorPositions = [];
}
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
onConfigurationChanged(e) {
return this._updateSettings(false);
}
onCursorStateChanged(e) {
this._cursorPositions = [];
for (let i = 0, len = e.selections.length; i < len; i++) {
this._cursorPositions[i] = e.selections[i].getPosition();
}
this._cursorPositions.sort(position_1.Position.compare);
return true;
}
onDecorationsChanged(e) {
if (e.affectsOverviewRuler) {
return true;
}
return false;
}
onFlushed(e) {
return true;
}
onScrollChanged(e) {
return e.scrollHeightChanged;
}
onZonesChanged(e) {
return true;
}
onThemeChanged(e) {
// invalidate color cache
this._context.model.invalidateOverviewRulerColorCache();
return this._updateSettings(false);
}
// ---- end view event handlers
getDomNode() {
return this._domNode.domNode;
}
prepareRender(ctx) {
// Nothing to read
}
render(editorCtx) {
this._render();
}
_render() {
if (this._settings.overviewRulerLanes === 0) {
// overview ruler is off
this._domNode.setBackgroundColor(this._settings.backgroundColor ? this._settings.backgroundColor : '');
return;
}
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 decorations = this._context.model.getAllOverviewRulerDecorations(this._context.theme);
const minDecorationHeight = (6 /* MIN_DECORATION_HEIGHT */ * this._settings.pixelRatio) | 0;
const halfMinDecorationHeight = (minDecorationHeight / 2) | 0;
const canvasCtx = this._domNode.domNode.getContext('2d');
if (this._settings.backgroundColor === null) {
canvasCtx.clearRect(0, 0, canvasWidth, canvasHeight);
}
else {
canvasCtx.fillStyle = this._settings.backgroundColor;
canvasCtx.fillRect(0, 0, canvasWidth, canvasHeight);
}
const x = this._settings.x;
const w = this._settings.w;
// Avoid flickering by always rendering the colors in the same order
// colors that don't use transparency will be sorted last (they start with #)
const colors = Object.keys(decorations);
colors.sort();
for (let cIndex = 0, cLen = colors.length; cIndex < cLen; cIndex++) {
const color = colors[cIndex];
const colorDecorations = decorations[color];
canvasCtx.fillStyle = color;
let prevLane = 0;
let prevY1 = 0;
let prevY2 = 0;
for (let i = 0, len = colorDecorations.length; i < len; i++) {
const lane = colorDecorations[3 * i];
const startLineNumber = colorDecorations[3 * i + 1];
const endLineNumber = colorDecorations[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 && this._settings.cursorColor) {
const cursorHeight = (2 * this._settings.pixelRatio) | 0;
const halfCursorHeight = (cursorHeight / 2) | 0;
const cursorX = this._settings.x[7 /* Full */];
const cursorW = this._settings.w[7 /* Full */];
canvasCtx.fillStyle = this._settings.cursorColor;
let prevY1 = -100;
let prevY2 = -100;
for (let i = 0, len = this._cursorPositions.length; i < len; i++) {
const cursor = this._cursorPositions[i];
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) {
// flush prev
if (i !== 0) {
canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1);
}
prevY1 = y1;
prevY2 = y2;
}
else {
// merge into prev
if (y2 > prevY2) {
prevY2 = y2;
}
}
}
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.stroke();
canvasCtx.moveTo(0, 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[606/*vs/editor/browser/viewParts/rulers/rulers*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,47/*vs/editor/browser/view/viewPart*/,48/*vs/editor/common/view/editorColorRegistry*/,11/*vs/platform/theme/common/themeService*/,336/*vs/css!vs/editor/browser/viewParts/rulers/rulers*/]), function (require, exports, fastDomNode_1, viewPart_1, editorColorRegistry_1, themeService_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(90 /* rulers */);
this._typicalHalfwidthCharacterWidth = options.get(41 /* fontInfo */).typicalHalfwidthCharacterWidth;
}
dispose() {
super.dispose();
}
// --- begin event handlers
onConfigurationChanged(e) {
const options = this._context.configuration.options;
this._rulers = options.get(90 /* rulers */);
this._typicalHalfwidthCharacterWidth = options.get(41 /* 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.model.getTextModelOptions();
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;
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const rulerColor = theme.getColor(editorColorRegistry_1.editorRuler);
if (rulerColor) {
collector.addRule(`.monaco-editor .view-ruler { box-shadow: 1px 0 0 0 ${rulerColor} 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[607/*vs/editor/browser/viewParts/viewCursors/viewCursors*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,15/*vs/base/common/async*/,47/*vs/editor/browser/view/viewPart*/,579/*vs/editor/browser/viewParts/viewCursors/viewCursor*/,35/*vs/editor/common/config/editorOptions*/,48/*vs/editor/common/view/editorColorRegistry*/,11/*vs/platform/theme/common/themeService*/,339/*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) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ViewCursors = void 0;
class ViewCursors extends viewPart_1.ViewPart {
constructor(context) {
super(context);
const options = this._context.configuration.options;
this._readOnly = options.get(79 /* readOnly */);
this._cursorBlinking = options.get(20 /* cursorBlinking */);
this._cursorStyle = options.get(22 /* cursorStyle */);
this._cursorSmoothCaretAnimation = options.get(21 /* cursorSmoothCaretAnimation */);
this._selectionIsEmpty = true;
this._isComposingInput = false;
this._isVisible = false;
this._primaryCursor = new viewCursor_1.ViewCursor(this._context);
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 async_1.IntervalTimer();
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(79 /* readOnly */);
this._cursorBlinking = options.get(20 /* cursorBlinking */);
this._cursorStyle = options.get(22 /* cursorStyle */);
this._cursorSmoothCaretAnimation = options.get(21 /* 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) {
this._primaryCursor.onCursorPositionChanged(position);
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);
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]);
}
}
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));
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 /* Hidden */;
}
if (!this._editorHasFocus) {
return 0 /* Hidden */;
}
if (this._readOnly) {
return 5 /* 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 /* Hidden */);
const isSolid = (blinkingStyle === 5 /* Solid */);
if (isHidden) {
this._hide();
}
else {
this._show();
}
this._blinkingEnabled = false;
this._updateDomClassName();
if (!isHidden && !isSolid) {
if (blinkingStyle === 1 /* 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);
}
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 /* Blink */:
result += ' cursor-blink';
break;
case 2 /* Smooth */:
result += ' cursor-smooth';
break;
case 3 /* Phase */:
result += ' cursor-phase';
break;
case 4 /* Expand */:
result += ' cursor-expand';
break;
case 5 /* Solid */:
result += ' cursor-solid';
break;
default:
result += ' cursor-solid';
}
}
else {
result += ' cursor-solid';
}
if (this._cursorSmoothCaretAnimation) {
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) {
let renderData = [], 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;
ViewCursors.BLINK_INTERVAL = 500;
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const caret = theme.getColor(editorColorRegistry_1.editorCursorForeground);
if (caret) {
let caretBackground = theme.getColor(editorColorRegistry_1.editorCursorBackground);
if (!caretBackground) {
caretBackground = caret.opposite();
}
collector.addRule(`.monaco-editor .cursors-layer .cursor { background-color: ${caret}; border-color: ${caret}; color: ${caretBackground}; }`);
if (theme.type === 'hc') {
collector.addRule(`.monaco-editor .cursors-layer.has-selection .cursor { 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[608/*vs/editor/common/services/markerDecorationsServiceImpl*/], __M([0/*require*/,1/*exports*/,87/*vs/platform/markers/common/markers*/,2/*vs/base/common/lifecycle*/,53/*vs/editor/common/model*/,11/*vs/platform/theme/common/themeService*/,48/*vs/editor/common/view/editorColorRegistry*/,36/*vs/editor/common/services/modelService*/,3/*vs/editor/common/core/range*/,46/*vs/base/common/network*/,6/*vs/base/common/event*/,22/*vs/platform/theme/common/colorRegistry*/,49/*vs/base/common/map*/]), function (require, exports, markers_1, lifecycle_1, model_1, themeService_1, editorColorRegistry_1, modelService_1, range_1, network_1, event_1, colorRegistry_1, map_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MarkerDecorationsService = void 0;
class MarkerDecorations extends lifecycle_1.Disposable {
constructor(model) {
super();
this.model = model;
this._markersData = new Map();
this._register((0, lifecycle_1.toDisposable)(() => {
this.model.deltaDecorations([...this._markersData.keys()], []);
this._markersData.clear();
}));
}
update(markers, newDecorations) {
const oldIds = [...this._markersData.keys()];
this._markersData.clear();
const ids = this.model.deltaDecorations(oldIds, newDecorations);
for (let index = 0; index < ids.length; index++) {
this._markersData.set(ids[index], markers[index]);
}
return oldIds.length !== 0 || ids.length !== 0;
}
getMarker(decoration) {
return this._markersData.get(decoration.id);
}
}
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) {
if (this._markerService) {
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 });
let newModelDecorations = markers.map((marker) => {
return {
range: this._createDecorationRange(markerDecorations.model, marker),
options: this._createDecorationOption(marker)
};
});
if (markerDecorations.update(markers, newModelDecorations)) {
this._onDidChangeMarker.fire(markerDecorations.model);
}
}
_createDecorationRange(model, rawMarker) {
let ret = range_1.Range.lift(rawMarker);
if (rawMarker.severity === markers_1.MarkerSeverity.Hint && !this._hasMarkerTag(rawMarker, 1 /* Unnecessary */) && !this._hasMarkerTag(rawMarker, 2 /* 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()) {
let word = model.getWordAtPosition(ret.getStartPosition());
if (word) {
ret = new range_1.Range(ret.startLineNumber, word.startColumn, ret.endLineNumber, word.endColumn);
}
else {
let maxColumn = model.getLineLastNonWhitespaceColumn(ret.startLineNumber) ||
model.getLineMaxColumn(ret.startLineNumber);
if (maxColumn === 1) {
// empty line
// console.warn('marker on empty line:', marker);
}
else if (ret.endColumn >= maxColumn) {
// behind eol
ret = new range_1.Range(ret.startLineNumber, maxColumn - 1, ret.endLineNumber, maxColumn);
}
else {
// extend marker to width = 1
ret = new range_1.Range(ret.startLineNumber, ret.startColumn, ret.endLineNumber, ret.endColumn + 1);
}
}
}
else if (rawMarker.endColumn === Number.MAX_VALUE && rawMarker.startColumn === 1 && ret.startLineNumber === ret.endLineNumber) {
let 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 /* Deprecated */)) {
className = undefined;
}
else if (this._hasMarkerTag(marker, 1 /* Unnecessary */)) {
className = "squiggly-unnecessary" /* EditorUnnecessaryDecoration */;
}
else {
className = "squiggly-hint" /* EditorHintDecoration */;
}
zIndex = 0;
break;
case markers_1.MarkerSeverity.Warning:
className = "squiggly-warning" /* EditorWarningDecoration */;
color = (0, themeService_1.themeColorFromId)(editorColorRegistry_1.overviewRulerWarning);
zIndex = 20;
minimap = {
color: (0, themeService_1.themeColorFromId)(colorRegistry_1.minimapWarning),
position: model_1.MinimapPosition.Inline
};
break;
case markers_1.MarkerSeverity.Info:
className = "squiggly-info" /* EditorInfoDecoration */;
color = (0, themeService_1.themeColorFromId)(editorColorRegistry_1.overviewRulerInfo);
zIndex = 10;
break;
case markers_1.MarkerSeverity.Error:
default:
className = "squiggly-error" /* EditorErrorDecoration */;
color = (0, themeService_1.themeColorFromId)(editorColorRegistry_1.overviewRulerError);
zIndex = 30;
minimap = {
color: (0, themeService_1.themeColorFromId)(colorRegistry_1.minimapError),
position: model_1.MinimapPosition.Inline
};
break;
}
if (marker.tags) {
if (marker.tags.indexOf(1 /* Unnecessary */) !== -1) {
inlineClassName = "squiggly-inline-unnecessary" /* EditorUnnecessaryInlineDecoration */;
}
if (marker.tags.indexOf(2 /* Deprecated */) !== -1) {
inlineClassName = "squiggly-inline-deprecated" /* EditorDeprecatedInlineDecoration */;
}
}
return {
description: 'marker-decoration',
stickiness: 1 /* 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;
}
};
MarkerDecorationsService = __decorate([
__param(0, modelService_1.IModelService),
__param(1, markers_1.IMarkerService)
], MarkerDecorationsService);
exports.MarkerDecorationsService = 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[609/*vs/editor/contrib/codeAction/lightBulbWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,93/*vs/base/browser/globalMouseMoveMonitor*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,31/*vs/editor/common/model/textModel*/,477/*vs/nls!vs/editor/contrib/codeAction/lightBulbWidget*/,37/*vs/platform/keybinding/common/keybinding*/,11/*vs/platform/theme/common/themeService*/,22/*vs/platform/theme/common/colorRegistry*/,60/*vs/base/browser/touch*/,27/*vs/base/common/codicons*/,345/*vs/css!vs/editor/contrib/codeAction/lightBulbWidget*/]), function (require, exports, dom, globalMouseMoveMonitor_1, event_1, lifecycle_1, textModel_1, nls, keybinding_1, themeService_1, colorRegistry_1, touch_1, codicons_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LightBulbWidget = void 0;
var LightBulbState;
(function (LightBulbState) {
LightBulbState.Hidden = { type: 0 /* Hidden */ };
class Showing {
constructor(actions, trigger, editorPosition, widgetPosition) {
this.actions = actions;
this.trigger = trigger;
this.editorPosition = editorPosition;
this.widgetPosition = widgetPosition;
this.type = 1 /* Showing */;
}
}
LightBulbState.Showing = Showing;
})(LightBulbState || (LightBulbState = {}));
let LightBulbWidget = class LightBulbWidget extends lifecycle_1.Disposable {
constructor(_editor, _quickFixActionId, _preferredFixActionId, _keybindingService) {
super();
this._editor = _editor;
this._quickFixActionId = _quickFixActionId;
this._preferredFixActionId = _preferredFixActionId;
this._keybindingService = _keybindingService;
this._onClick = this._register(new event_1.Emitter());
this.onClick = this._onClick.event;
this._state = LightBulbState.Hidden;
this._domNode = document.createElement('div');
this._domNode.className = codicons_1.Codicon.lightBulb.classNames;
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 /* Showing */ || !editorModel || this.state.editorPosition.lineNumber >= editorModel.getLineCount()) {
this.hide();
}
}));
touch_1.Gesture.ignoreTarget(this._domNode);
this._register(dom.addStandardDisposableGenericMouseDownListner(this._domNode, e => {
if (this.state.type !== 1 /* 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(57 /* 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 and block future
// showings until mouse is released
this.hide();
const monitor = new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor();
monitor.startMonitoring(e.target, e.buttons, globalMouseMoveMonitor_1.standardMouseMoveMerger, () => { }, () => {
monitor.dispose();
});
}));
this._register(this._editor.onDidChangeConfiguration(e => {
// hide when told to do so
if (e.hasChanged(55 /* lightbulb */) && !this._editor.getOption(55 /* lightbulb */).enabled) {
this.hide();
}
}));
this._updateLightBulbTitleAndIcon();
this._register(this._keybindingService.onDidUpdateKeybindings(this._updateLightBulbTitleAndIcon, this));
}
dispose() {
super.dispose();
this._editor.removeContentWidget(this);
}
getId() {
return 'LightBulbWidget';
}
getDomNode() {
return this._domNode;
}
getPosition() {
return this._state.type === 1 /* Showing */ ? this._state.widgetPosition : null;
}
update(actions, trigger, atPosition) {
if (actions.validActions.length <= 0) {
return this.hide();
}
const options = this._editor.getOptions();
if (!options.get(55 /* lightbulb */).enabled) {
return this.hide();
}
const model = this._editor.getModel();
if (!model) {
return this.hide();
}
const { lineNumber, column } = model.validatePosition(atPosition);
const tabSize = model.getOptions().tabSize;
const fontInfo = options.get(41 /* fontInfo */);
const lineContent = model.getLineContent(lineNumber);
const indent = textModel_1.TextModel.computeIndentLevel(lineContent, tabSize);
const lineHasSpace = fontInfo.spaceWidth * indent > 22;
const isFolded = (lineNumber) => {
return lineNumber > 2 && this._editor.getTopForLineNumber(lineNumber) === this._editor.getTopForLineNumber(lineNumber - 1);
};
let effectiveLineNumber = lineNumber;
if (!lineHasSpace) {
if (lineNumber > 1 && !isFolded(lineNumber - 1)) {
effectiveLineNumber -= 1;
}
else if (!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();
}
}
this.state = new LightBulbState.Showing(actions, trigger, atPosition, {
position: { lineNumber: effectiveLineNumber, column: 1 },
preference: LightBulbWidget._posPref
});
this._editor.layoutContentWidget(this);
}
hide() {
this.state = LightBulbState.Hidden;
this._editor.layoutContentWidget(this);
}
get state() { return this._state; }
set state(value) {
this._state = value;
this._updateLightBulbTitleAndIcon();
}
_updateLightBulbTitleAndIcon() {
if (this.state.type === 1 /* Showing */ && this.state.actions.hasAutoFix) {
// update icon
this._domNode.classList.remove(...codicons_1.Codicon.lightBulb.classNamesArray);
this._domNode.classList.add(...codicons_1.Codicon.lightbulbAutofix.classNamesArray);
const preferredKb = this._keybindingService.lookupKeybinding(this._preferredFixActionId);
if (preferredKb) {
this.title = nls.localize(0, null, preferredKb.getLabel());
return;
}
}
// update icon
this._domNode.classList.remove(...codicons_1.Codicon.lightbulbAutofix.classNamesArray);
this._domNode.classList.add(...codicons_1.Codicon.lightBulb.classNamesArray);
const kb = this._keybindingService.lookupKeybinding(this._quickFixActionId);
if (kb) {
this.title = nls.localize(1, null, kb.getLabel());
}
else {
this.title = nls.localize(2, null);
}
}
set title(value) {
this._domNode.title = value;
}
};
LightBulbWidget._posPref = [0 /* EXACT */];
LightBulbWidget = __decorate([
__param(3, keybinding_1.IKeybindingService)
], LightBulbWidget);
exports.LightBulbWidget = LightBulbWidget;
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
var _a;
const editorBackgroundColor = (_a = theme.getColor(colorRegistry_1.editorBackground)) === null || _a === void 0 ? void 0 : _a.transparent(0.7);
// Lightbulb Icon
const editorLightBulbForegroundColor = theme.getColor(colorRegistry_1.editorLightBulbForeground);
if (editorLightBulbForegroundColor) {
collector.addRule(`
.monaco-editor .contentWidgets ${codicons_1.Codicon.lightBulb.cssSelector} {
color: ${editorLightBulbForegroundColor};
background-color: ${editorBackgroundColor};
}`);
}
// Lightbulb Auto Fix Icon
const editorLightBulbAutoFixForegroundColor = theme.getColor(colorRegistry_1.editorLightBulbAutoFixForeground);
if (editorLightBulbAutoFixForegroundColor) {
collector.addRule(`
.monaco-editor .contentWidgets ${codicons_1.Codicon.lightbulbAutofix.cssSelector} {
color: ${editorLightBulbAutoFixForegroundColor};
background-color: ${editorBackgroundColor};
}`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/codelens/codelensWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,3/*vs/editor/common/core/range*/,31/*vs/editor/common/model/textModel*/,48/*vs/editor/common/view/editorColorRegistry*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,105/*vs/base/browser/ui/iconLabel/iconLabels*/,346/*vs/css!vs/editor/contrib/codelens/codelensWidget*/]), function (require, exports, dom, range_1, textModel_1, editorColorRegistry_1, colorRegistry_1, themeService_1, iconLabels_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeLensWidget = exports.CodeLensHelper = void 0;
class CodeLensViewZone {
constructor(afterLineNumber, heightInPx, onHeight) {
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();
}
}
}
class CodeLensContentWidget {
constructor(editor, className, 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 ${className}`;
}
withCommands(lenses, animate) {
this._commands.clear();
let 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) {
children.push(dom.$('a', { id: String(i), title: lens.command.tooltip }, ...title));
this._commands.set(String(i), 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 /* ABOVE */]
};
}
getPosition() {
return this._widgetPosition || null;
}
}
CodeLensContentWidget._idPool = 0;
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) {
let 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;
class CodeLensWidget {
constructor(data, editor, className, helper, viewZoneChangeAccessor, heightInPx, updateCallback) {
this._isDisposed = false;
this._editor = editor;
this._className = className;
this._data = data;
// create combined range, track all ranges with decorations,
// check if there is already something to render
this._decorationIds = [];
let range;
let lenses = [];
this._data.forEach((codeLensData, i) => {
if (codeLensData.symbol.command) {
lenses.push(codeLensData.symbol);
}
helper.addDecoration({
range: codeLensData.symbol.range,
options: textModel_1.ModelDecorationOptions.EMPTY
}, 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._className, 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 = [];
if (viewZoneChangeAccessor) {
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: textModel_1.ModelDecorationOptions.EMPTY
}, 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.domNode.hasAttribute('monaco-visible-view-zone')) {
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) {
var _a;
return (_a = this._contentWidget) === null || _a === void 0 ? void 0 : _a.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);
}
}
}
}
getItems() {
return this._data;
}
}
exports.CodeLensWidget = CodeLensWidget;
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const codeLensForeground = theme.getColor(editorColorRegistry_1.editorCodeLensForeground);
if (codeLensForeground) {
collector.addRule(`.monaco-editor .codelens-decoration { color: ${codeLensForeground}; }`);
collector.addRule(`.monaco-editor .codelens-decoration .codicon { color: ${codeLensForeground}; }`);
}
const activeLinkForeground = theme.getColor(colorRegistry_1.editorActiveLinkForeground);
if (activeLinkForeground) {
collector.addRule(`.monaco-editor .codelens-decoration > a:hover { color: ${activeLinkForeground} !important; }`);
collector.addRule(`.monaco-editor .codelens-decoration > a:hover .codicon { color: ${activeLinkForeground} !important; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/colorPicker/colorPickerWidget*/], __M([0/*require*/,1/*exports*/,39/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,93/*vs/base/browser/globalMouseMoveMonitor*/,52/*vs/base/browser/ui/widget*/,29/*vs/base/common/color*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,347/*vs/css!vs/editor/contrib/colorPicker/colorPicker*/]), function (require, exports, browser_1, dom, globalMouseMoveMonitor_1, widget_1, color_1, event_1, lifecycle_1, colorRegistry_1, themeService_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ColorPickerWidget = exports.ColorPickerBody = exports.ColorPickerHeader = void 0;
const $ = dom.$;
class ColorPickerHeader extends lifecycle_1.Disposable {
constructor(container, model, themeService) {
super();
this.model = model;
this.domNode = $('.colorpicker-header');
dom.append(container, this.domNode);
this.pickedColorNode = dom.append(this.domNode, $('.picked-color'));
const colorBox = dom.append(this.domNode, $('.original-color'));
colorBox.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((0, themeService_1.registerThemingParticipant)((theme, collector) => {
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(colorBox, 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());
}
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.pickedColorNode.textContent = this.model.presentation ? this.model.presentation.label : '';
}
}
exports.ColorPickerHeader = ColorPickerHeader;
class ColorPickerBody extends lifecycle_1.Disposable {
constructor(container, model, pixelRatio) {
super();
this.model = model;
this.pixelRatio = pixelRatio;
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);
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);
this._register(this.hueStrip);
this._register(this.hueStrip.onDidChange(this.onDidHueChange, this));
this._register(this.hueStrip.onColorFlushed(this.flushColor, this));
}
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));
}
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.addDisposableGenericMouseDownListner(this.domNode, e => this.onMouseDown(e)));
this._register(this.model.onDidChangeColor(this.onDidChangeColor, this));
this.monitor = null;
}
onMouseDown(e) {
this.monitor = this._register(new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor());
const origin = dom.getDomNodePagePosition(this.domNode);
if (e.target !== this.selection) {
this.onDidChangePosition(e.offsetX, e.offsetY);
}
this.monitor.startMonitoring(e.target, e.buttons, globalMouseMoveMonitor_1.standardMouseMoveMerger, event => this.onDidChangePosition(event.posx - origin.left, event.posy - origin.top), () => null);
const mouseUpListener = dom.addDisposableGenericMouseUpListner(document, () => {
this._onColorFlushed.fire();
mouseUpListener.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() {
if (this.monitor && this.monitor.isMonitoring()) {
return;
}
this.paint();
}
}
class Strip extends lifecycle_1.Disposable {
constructor(container, model) {
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;
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.addDisposableGenericMouseDownListner(this.domNode, e => this.onMouseDown(e)));
this.layout();
}
layout() {
this.height = this.domNode.offsetHeight - this.slider.offsetHeight;
const value = this.getValue(this.model.color);
this.updateSliderPosition(value);
}
onMouseDown(e) {
const monitor = this._register(new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor());
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.buttons, globalMouseMoveMonitor_1.standardMouseMoveMerger, event => this.onDidChangeTop(event.posy - origin.top), () => null);
const mouseUpListener = dom.addDisposableGenericMouseUpListner(document, () => {
this._onColorFlushed.fire();
mouseUpListener.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) {
super(container, model);
this.domNode.classList.add('opacity-strip');
this._register(model.onDidChangeColor(this.onDidChangeColor, this));
this.onDidChangeColor(this.model.color);
}
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) {
super(container, model);
this.domNode.classList.add('hue-strip');
}
getValue(color) {
return 1 - (color.hsva.h / 360);
}
}
class ColorPickerWidget extends widget_1.Widget {
constructor(container, model, pixelRatio, themeService) {
super();
this.model = model;
this.pixelRatio = pixelRatio;
this._register((0, browser_1.onDidChangeZoomLevel)(() => this.layout()));
const element = $('.colorpicker-widget');
container.appendChild(element);
const header = new ColorPickerHeader(element, this.model, themeService);
this.body = new ColorPickerBody(element, this.model, this.pixelRatio);
this._register(header);
this._register(this.body);
}
layout() {
this.body.layout();
}
}
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[612/*vs/editor/contrib/find/findDecorations*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,53/*vs/editor/common/model*/,31/*vs/editor/common/model/textModel*/,22/*vs/platform/theme/common/colorRegistry*/,11/*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.deltaDecorations(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;
}
getCurrentMatchesPosition(desiredRange) {
let 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++) {
let 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) {
let lineBeforeEnd = rng.endLineNumber - 1;
let 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;
let 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
let 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 === null || findScopes === void 0 ? void 0 : 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--) {
let decorationId = this._decorations[i];
let 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++) {
let decorationId = this._decorations[i];
let 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;
}
}
exports.FindDecorations = FindDecorations;
FindDecorations._CURRENT_FIND_MATCH_DECORATION = textModel_1.ModelDecorationOptions.register({
description: 'current-find-match',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
zIndex: 13,
className: 'currentFindMatch',
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: model_1.MinimapPosition.Inline
}
});
FindDecorations._FIND_MATCH_DECORATION = textModel_1.ModelDecorationOptions.register({
description: 'find-match',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
className: 'findMatch',
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: model_1.MinimapPosition.Inline
}
});
FindDecorations._FIND_MATCH_NO_OVERVIEW_DECORATION = textModel_1.ModelDecorationOptions.register({
description: 'find-match-no-overview',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
className: 'findMatch',
showIfCollapsed: true
});
FindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION = textModel_1.ModelDecorationOptions.register({
description: 'find-match-only-overview',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
overviewRuler: {
color: (0, themeService_1.themeColorFromId)(colorRegistry_1.overviewRulerFindMatchForeground),
position: model_1.OverviewRulerLane.Center
}
});
FindDecorations._RANGE_HIGHLIGHT_DECORATION = textModel_1.ModelDecorationOptions.register({
description: 'find-range-highlight',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
className: 'rangeHighlight',
isWholeLine: true
});
FindDecorations._FIND_SCOPE_DECORATION = textModel_1.ModelDecorationOptions.register({
description: 'find-scope',
className: 'findScope',
isWholeLine: 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[147/*vs/editor/contrib/find/findModel*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,95/*vs/editor/common/commands/replaceCommand*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,171/*vs/editor/common/model/textModelSearch*/,612/*vs/editor/contrib/find/findDecorations*/,411/*vs/editor/contrib/find/replaceAllCommand*/,412/*vs/editor/contrib/find/replacePattern*/,16/*vs/platform/contextkey/common/contextkey*/,19/*vs/base/common/arrays*/]), function (require, exports, async_1, lifecycle_1, replaceCommand_1, position_1, range_1, selection_1, textModelSearch_1, findDecorations_1, replaceAllCommand_1, replacePattern_1, contextkey_1, arrays_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_VISIBLE = void 0;
exports.CONTEXT_FIND_WIDGET_VISIBLE = new contextkey_1.RawContextKey('findWidgetVisible', false);
// 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 /* Alt */ | 33 /* KEY_C */,
mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 33 /* KEY_C */ }
};
exports.ToggleWholeWordKeybinding = {
primary: 512 /* Alt */ | 53 /* KEY_W */,
mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 53 /* KEY_W */ }
};
exports.ToggleRegexKeybinding = {
primary: 512 /* Alt */ | 48 /* KEY_R */,
mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 48 /* KEY_R */ }
};
exports.ToggleSearchScopeKeybinding = {
primary: 512 /* Alt */ | 42 /* KEY_L */,
mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 42 /* KEY_L */ }
};
exports.TogglePreserveCaseKeybinding = {
primary: 512 /* Alt */ | 46 /* KEY_P */,
mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 46 /* KEY_P */ }
};
exports.FIND_IDS = {
StartFindAction: 'actions.find',
StartFindWithSelection: 'actions.findWithSelection',
NextMatchFindAction: 'editor.action.nextMatchFindAction',
PreviousMatchFindAction: 'editor.action.previousMatchFindAction',
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(() => this.research(false), 100);
this._toDispose.add(this._updateDecorationsScheduler);
this._toDispose.add(this._editor.onDidChangeCursorPosition((e) => {
if (e.reason === 3 /* Explicit */
|| e.reason === 5 /* Undo */
|| e.reason === 6 /* 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) {
let 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;
});
}
let 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, arrays_1.findFirstInSorted)(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(33 /* find */).cursorMoveOnType) {
this._moveToNextMatch(this._decorations.getStartPosition());
}
}
_hasMatches() {
return (this._state.matchesCount > 0);
}
_cannotFind() {
if (!this._hasMatches()) {
let findScope = this._decorations.getFindScope();
if (findScope) {
// Reveal the selection so user is reminded that 'selection find' is on.
this._editor.revealRangeInCenterIfOutsideViewport(findScope, 0 /* Smooth */);
}
return true;
}
return false;
}
_setCurrentFindMatch(match) {
let matchesPosition = this._decorations.setCurrentFindMatch(match);
this._state.changeMatchInfo(matchesPosition, this._decorations.getCount(), match);
this._editor.setSelection(match);
this._editor.revealRangeInCenterIfOutsideViewport(match, 0 /* Smooth */);
}
_prevSearchPosition(before) {
let isUsingLineStops = this._state.isRegex && (this._state.searchString.indexOf('^') >= 0
|| this._state.searchString.indexOf('$') >= 0);
let { lineNumber, column } = before;
let 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;
}
let findScope = this._decorations.getFindScope();
let searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), findScope);
// ...(----)...|...
if (searchRange.getEndPosition().isBefore(before)) {
before = searchRange.getEndPosition();
}
// ...|...(----)...
if (before.isBefore(searchRange.getStartPosition())) {
before = searchRange.getEndPosition();
}
let { lineNumber, column } = before;
let 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(115 /* 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(115 /* 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) {
let isUsingLineStops = this._state.isRegex && (this._state.searchString.indexOf('^') >= 0
|| this._state.searchString.indexOf('$') >= 0);
let { lineNumber, column } = after;
let 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;
}
let nextMatch = this._getNextMatch(after, false, true);
if (nextMatch) {
this._setCurrentFindMatch(nextMatch.range);
}
}
_getNextMatch(after, captureMatches, forceMove, isRecursed = false) {
if (this._cannotFind()) {
return null;
}
let findScope = this._decorations.getFindScope();
let searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), findScope);
// ...(----)...|...
if (searchRange.getEndPosition().isBefore(after)) {
after = searchRange.getStartPosition();
}
// ...|...(----)...
if (after.isBefore(searchRange.getStartPosition())) {
after = searchRange.getStartPosition();
}
let { lineNumber, column } = after;
let 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(115 /* 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(115 /* 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());
}
_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;
}
let replacePattern = this._getReplacePattern();
let selection = this._editor.getSelection();
let nextMatch = this._getNextMatch(selection.getStartPosition(), true, false);
if (nextMatch) {
if (selection.equalsRange(nextMatch.range)) {
// selection sits on a find match => replace it!
let replaceString = replacePattern.buildReplaceString(nextMatch.matches, this._state.preserveCase);
let 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(115 /* 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(115 /* 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 /* 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));
}
let 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)
let matches = this._findMatches(findScopes, replacePattern.hasReplacementPatterns || this._state.preserveCase, 1073741824 /* MAX_SAFE_SMALL_INTEGER */);
let replaceStrings = [];
for (let i = 0, len = matches.length; i < len; i++) {
replaceStrings[i] = replacePattern.buildReplaceString(matches[i].matches, this._state.preserveCase);
}
let command = new replaceAllCommand_1.ReplaceAllCommand(this._editor.getSelection(), matches.map(m => m.range), replaceStrings);
this._executeEditorCommand('replaceAll', command);
}
selectAllMatches() {
if (!this._hasMatches()) {
return;
}
let findScopes = this._decorations.getFindScopes();
// Get all the ranges (even more than the highlighted ones)
let matches = this._findMatches(findScopes, false, 1073741824 /* 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
let editorSelection = this._editor.getSelection();
for (let i = 0, len = selections.length; i < len; i++) {
let 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[613/*vs/editor/contrib/find/findOptionsWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,237/*vs/base/browser/ui/findinput/findInputCheckboxes*/,52/*vs/base/browser/ui/widget*/,15/*vs/base/common/async*/,147/*vs/editor/contrib/find/findModel*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/]), function (require, exports, dom, findInputCheckboxes_1, widget_1, async_1, findModel_1, colorRegistry_1, themeService_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FindOptionsWidget = void 0;
class FindOptionsWidget extends widget_1.Widget {
constructor(editor, state, keybindingService, themeService) {
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.setAttribute('role', 'presentation');
this._domNode.setAttribute('aria-hidden', 'true');
const inputActiveOptionBorderColor = themeService.getColorTheme().getColor(colorRegistry_1.inputActiveOptionBorder);
const inputActiveOptionForegroundColor = themeService.getColorTheme().getColor(colorRegistry_1.inputActiveOptionForeground);
const inputActiveOptionBackgroundColor = themeService.getColorTheme().getColor(colorRegistry_1.inputActiveOptionBackground);
this.caseSensitive = this._register(new findInputCheckboxes_1.CaseSensitiveCheckbox({
appendTitle: this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleCaseSensitiveCommand),
isChecked: this._state.matchCase,
inputActiveOptionBorder: inputActiveOptionBorderColor,
inputActiveOptionForeground: inputActiveOptionForegroundColor,
inputActiveOptionBackground: inputActiveOptionBackgroundColor
}));
this._domNode.appendChild(this.caseSensitive.domNode);
this._register(this.caseSensitive.onChange(() => {
this._state.change({
matchCase: this.caseSensitive.checked
}, false);
}));
this.wholeWords = this._register(new findInputCheckboxes_1.WholeWordsCheckbox({
appendTitle: this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleWholeWordCommand),
isChecked: this._state.wholeWord,
inputActiveOptionBorder: inputActiveOptionBorderColor,
inputActiveOptionForeground: inputActiveOptionForegroundColor,
inputActiveOptionBackground: inputActiveOptionBackgroundColor
}));
this._domNode.appendChild(this.wholeWords.domNode);
this._register(this.wholeWords.onChange(() => {
this._state.change({
wholeWord: this.wholeWords.checked
}, false);
}));
this.regex = this._register(new findInputCheckboxes_1.RegexCheckbox({
appendTitle: this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleRegexCommand),
isChecked: this._state.isRegex,
inputActiveOptionBorder: inputActiveOptionBorderColor,
inputActiveOptionForeground: inputActiveOptionForegroundColor,
inputActiveOptionBackground: inputActiveOptionBackgroundColor
}));
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.addDisposableNonBubblingMouseOutListener(this._domNode, (e) => this._onMouseOut()));
this._register(dom.addDisposableListener(this._domNode, 'mouseover', (e) => this._onMouseOver()));
this._applyTheme(themeService.getColorTheme());
this._register(themeService.onDidColorThemeChange(this._applyTheme.bind(this)));
}
_keybindingLabelFor(actionId) {
let 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 /* TOP_RIGHT_CORNER */
};
}
highlightFindOptions() {
this._revealTemporarily();
}
_revealTemporarily() {
this._show();
this._hideSoon.schedule();
}
_onMouseOut() {
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';
}
_applyTheme(theme) {
let inputStyles = {
inputActiveOptionBorder: theme.getColor(colorRegistry_1.inputActiveOptionBorder),
inputActiveOptionForeground: theme.getColor(colorRegistry_1.inputActiveOptionForeground),
inputActiveOptionBackground: theme.getColor(colorRegistry_1.inputActiveOptionBackground)
};
this.caseSensitive.style(inputStyles);
this.wholeWords.style(inputStyles);
this.regex.style(inputStyles);
}
}
exports.FindOptionsWidget = FindOptionsWidget;
FindOptionsWidget.ID = 'editor.contrib.findOptionsWidget';
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const widgetBackground = theme.getColor(colorRegistry_1.editorWidgetBackground);
if (widgetBackground) {
collector.addRule(`.monaco-editor .findOptionsWidget { background-color: ${widgetBackground}; }`);
}
const widgetForeground = theme.getColor(colorRegistry_1.editorWidgetForeground);
if (widgetForeground) {
collector.addRule(`.monaco-editor .findOptionsWidget { color: ${widgetForeground}; }`);
}
const widgetShadowColor = theme.getColor(colorRegistry_1.widgetShadow);
if (widgetShadowColor) {
collector.addRule(`.monaco-editor .findOptionsWidget { box-shadow: 0 0 8px 2px ${widgetShadowColor}; }`);
}
const hcBorder = theme.getColor(colorRegistry_1.contrastBorder);
if (hcBorder) {
collector.addRule(`.monaco-editor .findOptionsWidget { border: 2px solid ${hcBorder}; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/find/findState*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/,147/*vs/editor/contrib/find/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 /* True */) {
return true;
}
if (override === 2 /* False */) {
return false;
}
return value;
}
class FindReplaceState extends lifecycle_1.Disposable {
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 /* NotSet */;
this._wholeWord = false;
this._wholeWordOverride = 0 /* NotSet */;
this._matchCase = false;
this._matchCaseOverride = 0 /* NotSet */;
this._preserveCase = false;
this._preserveCaseOverride = 0 /* NotSet */;
this._searchScope = null;
this._matchesPosition = 0;
this._matchesCount = 0;
this._currentMatch = null;
this._loop = true;
}
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; }
changeMatchInfo(matchesPosition, matchesCount, currentMatch) {
let 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
};
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) {
var _a;
let 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
};
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 (!((_a = newState.searchScope) === null || _a === void 0 ? void 0 : _a.every((newSearchScope) => {
var _a;
return (_a = this._searchScope) === null || _a === void 0 ? void 0 : _a.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;
}
}
// Overrides get set when they explicitly come in and get reset anytime something else changes
this._isRegexOverride = (typeof newState.isRegexOverride !== 'undefined' ? newState.isRegexOverride : 0 /* NotSet */);
this._wholeWordOverride = (typeof newState.wholeWordOverride !== 'undefined' ? newState.wholeWordOverride : 0 /* NotSet */);
this._matchCaseOverride = (typeof newState.matchCaseOverride !== 'undefined' ? newState.matchCaseOverride : 0 /* NotSet */);
this._preserveCaseOverride = (typeof newState.preserveCaseOverride !== 'undefined' ? newState.preserveCaseOverride : 0 /* 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[615/*vs/editor/contrib/gotoSymbol/peek/referencesTree*/], __M([0/*require*/,1/*exports*/,118/*vs/editor/contrib/gotoSymbol/referencesModel*/,68/*vs/editor/common/services/resolverService*/,179/*vs/base/browser/ui/iconLabel/iconLabel*/,208/*vs/base/browser/ui/countBadge/countBadge*/,121/*vs/platform/label/common/label*/,11/*vs/platform/theme/common/themeService*/,122/*vs/platform/theme/common/styler*/,7/*vs/base/browser/dom*/,494/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesTree*/,163/*vs/base/common/labels*/,43/*vs/base/common/resources*/,2/*vs/base/common/lifecycle*/,9/*vs/platform/instantiation/common/instantiation*/,37/*vs/platform/keybinding/common/keybinding*/,67/*vs/base/common/filters*/,161/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/]), function (require, exports, referencesModel_1, resolverService_1, iconLabel_1, countBadge_1, label_1, themeService_1, styler_1, dom, nls_1, labels_1, resources_1, lifecycle_1, instantiation_1, keybinding_1, filters_1, highlightedLabel_1) {
"use strict";
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');
}
};
DataSource = __decorate([
__param(0, resolverService_1.ITextModelService)
], DataSource);
exports.DataSource = 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) {
var _a;
if (element instanceof referencesModel_1.OneReference) {
const parts = (_a = element.parent.getPreview(element)) === null || _a === void 0 ? void 0 : _a.preview(element.range);
if (parts) {
return parts.value;
}
}
// FileReferences or unresolved OneReference
return (0, resources_1.basename)(element.uri);
}
};
StringRepresentationProvider = __decorate([
__param(0, keybinding_1.IKeybindingService)
], StringRepresentationProvider);
exports.StringRepresentationProvider = 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, _uriLabel, themeService) {
super();
this._uriLabel = _uriLabel;
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')));
this._register((0, styler_1.attachBadgeStyler)(this.badge, themeService));
container.appendChild(parent);
}
set(element, matches) {
let parent = (0, resources_1.dirname)(element.uri);
this.file.setLabel((0, labels_1.getBaseLabel)(element.uri), this._uriLabel.getUriLabel(parent, { relative: true }), { title: this._uriLabel.getUriLabel(element.uri), matches });
const len = element.children.length;
this.badge.setCount(len);
if (len > 1) {
this.badge.setTitleFormat((0, nls_1.localize)(0, null, len));
}
else {
this.badge.setTitleFormat((0, nls_1.localize)(1, null, len));
}
}
};
FileReferencesTemplate = __decorate([
__param(1, label_1.ILabelService),
__param(2, themeService_1.IThemeService)
], FileReferencesTemplate);
let FileReferencesRenderer = class FileReferencesRenderer {
constructor(_instantiationService) {
this._instantiationService = _instantiationService;
this.templateId = FileReferencesRenderer.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();
}
};
FileReferencesRenderer.id = 'FileReferencesRenderer';
FileReferencesRenderer = __decorate([
__param(0, instantiation_1.IInstantiationService)
], FileReferencesRenderer);
exports.FileReferencesRenderer = FileReferencesRenderer;
//#endregion
//#region render: Reference
class OneReferenceTemplate {
constructor(container) {
this.label = new highlightedLabel_1.HighlightedLabel(container, false);
}
set(element, score) {
var _a;
const preview = (_a = element.parent.getPreview(element)) === null || _a === void 0 ? void 0 : _a.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;
}
renderTemplate(container) {
return new OneReferenceTemplate(container);
}
renderElement(node, index, templateData) {
templateData.set(node.element, node.filterData);
}
disposeTemplate() {
}
}
exports.OneReferenceRenderer = OneReferenceRenderer;
OneReferenceRenderer.id = 'OneReferenceRenderer';
//#endregion
class AccessibilityProvider {
getWidgetAriaLabel() {
return (0, nls_1.localize)(2, null);
}
getAriaLabel(element) {
return element.ariaMessage;
}
}
exports.AccessibilityProvider = AccessibilityProvider;
});
/*---------------------------------------------------------------------------------------------
* 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/inlineCompletions/ghostTextWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/,28/*vs/editor/browser/services/codeEditorService*/,8/*vs/base/common/strings*/,114/*vs/editor/common/viewLayout/viewLineRenderer*/,35/*vs/editor/common/config/editorOptions*/,83/*vs/editor/common/core/stringBuilder*/,65/*vs/editor/browser/config/configuration*/,85/*vs/editor/common/core/lineTokens*/,13/*vs/editor/common/core/position*/,11/*vs/platform/theme/common/themeService*/,48/*vs/editor/common/view/editorColorRegistry*/,29/*vs/base/common/color*/,40/*vs/editor/common/controller/cursorCommon*/,136/*vs/editor/common/viewLayout/lineDecorations*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/,354/*vs/css!vs/editor/contrib/inlineCompletions/ghostText*/]), function (require, exports, dom, lifecycle_1, range_1, codeEditorService_1, strings, viewLineRenderer_1, editorOptions_1, stringBuilder_1, configuration_1, lineTokens_1, position_1, themeService_1, editorColorRegistry_1, color_1, cursorCommon_1, lineDecorations_1, contextkey_1, instantiation_1) {
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.GhostTextWidget = void 0;
const ttPolicy = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('editorGhostText', { createHTML: value => value });
let GhostTextWidget = class GhostTextWidget extends lifecycle_1.Disposable {
constructor(editor, model, instantiationService) {
super();
this.editor = editor;
this.model = model;
this.instantiationService = instantiationService;
this.disposed = false;
this.partsWidget = this._register(this.instantiationService.createInstance(DecorationsWidget, this.editor));
this.additionalLinesWidget = this._register(new AdditionalLinesWidget(this.editor));
this.viewMoreContentWidget = undefined;
this._register(this.editor.onDidChangeConfiguration((e) => {
if (e.hasChanged(27 /* disableMonospaceOptimizations */)
|| e.hasChanged(104 /* stopRenderingLineAfter */)
|| e.hasChanged(87 /* renderWhitespace */)
|| e.hasChanged(81 /* renderControlCharacters */)
|| e.hasChanged(42 /* fontLigatures */)
|| e.hasChanged(41 /* fontInfo */)
|| e.hasChanged(57 /* lineHeight */)) {
this.update();
}
}));
this._register((0, lifecycle_1.toDisposable)(() => {
var _a;
this.disposed = true;
this.update();
(_a = this.viewMoreContentWidget) === null || _a === void 0 ? void 0 : _a.dispose();
this.viewMoreContentWidget = undefined;
}));
this._register(model.onDidChange(() => {
this.update();
}));
this.update();
}
shouldShowHoverAtViewZone(viewZoneId) {
return (this.additionalLinesWidget.viewZoneId === viewZoneId);
}
update() {
var _a;
const ghostText = this.model.ghostText;
if (!this.editor.hasModel() || !ghostText || this.disposed) {
this.partsWidget.clear();
this.additionalLinesWidget.clear();
return;
}
const inlineTexts = new Array();
const additionalLines = new Array();
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 /* 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 /* Regular */)] : []
});
}
}
const textBufferLine = this.editor.getModel().getLineContent(ghostText.lineNumber);
this.editor.getModel().getLineTokens(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],
});
lines = lines.slice(1);
}
else {
addToAdditionalLines([textBufferLine.substring(lastIdx, part.column - 1)], undefined);
}
if (lines.length > 0) {
addToAdditionalLines(lines, 'ghost-text');
if (hiddenTextStartColumn === undefined && part.column <= textBufferLine.length) {
hiddenTextStartColumn = part.column;
}
}
lastIdx = part.column - 1;
}
if (hiddenTextStartColumn !== undefined) {
addToAdditionalLines([textBufferLine.substring(lastIdx)], undefined);
}
this.partsWidget.setParts(ghostText.lineNumber, inlineTexts, hiddenTextStartColumn !== undefined ? { column: hiddenTextStartColumn, length: textBufferLine.length + 1 - hiddenTextStartColumn } : undefined);
this.additionalLinesWidget.updateLines(ghostText.lineNumber, additionalLines, ghostText.additionalReservedLineCount);
if (ghostText.parts.some(p => p.lines.length < 0)) {
// Not supported at the moment, condition is always false.
this.viewMoreContentWidget = this.renderViewMoreLines(new position_1.Position(ghostText.lineNumber, this.editor.getModel().getLineMaxColumn(ghostText.lineNumber)), '', 0);
}
else {
(_a = this.viewMoreContentWidget) === null || _a === void 0 ? void 0 : _a.dispose();
this.viewMoreContentWidget = undefined;
}
}
renderViewMoreLines(position, firstLineText, remainingLinesLength) {
const fontInfo = this.editor.getOption(41 /* fontInfo */);
const domNode = document.createElement('div');
domNode.className = 'suggest-preview-additional-widget';
configuration_1.Configuration.applyFontInfoSlow(domNode, fontInfo);
const spacer = document.createElement('span');
spacer.className = 'content-spacer';
spacer.append(firstLineText);
domNode.append(spacer);
const newline = document.createElement('span');
newline.className = 'content-newline suggest-preview-text';
newline.append('⏎ ');
domNode.append(newline);
const disposableStore = new lifecycle_1.DisposableStore();
const button = document.createElement('div');
button.className = 'button suggest-preview-text';
button.append(`+${remainingLinesLength} lines…`);
disposableStore.add(dom.addStandardDisposableListener(button, 'mousedown', (e) => {
var _a;
(_a = this.model) === null || _a === void 0 ? void 0 : _a.setExpanded(true);
e.preventDefault();
this.editor.focus();
}));
domNode.append(button);
return new ViewMoreLinesContentWidget(this.editor, position, domNode, disposableStore);
}
};
GhostTextWidget = __decorate([
__param(2, instantiation_1.IInstantiationService)
], GhostTextWidget);
exports.GhostTextWidget = GhostTextWidget;
let DecorationsWidget = class DecorationsWidget {
constructor(editor, codeEditorService, themeService, contextKeyService) {
this.editor = editor;
this.codeEditorService = codeEditorService;
this.themeService = themeService;
this.contextKeyService = contextKeyService;
this.decorationIds = [];
this.disposableStore = new lifecycle_1.DisposableStore();
}
dispose() {
this.clear();
this.disposableStore.dispose();
}
clear() {
this.editor.deltaDecorations(this.decorationIds, []);
this.disposableStore.clear();
}
setParts(lineNumber, parts, hiddenText) {
this.disposableStore.clear();
const colorTheme = this.themeService.getColorTheme();
const foreground = colorTheme.getColor(editorColorRegistry_1.ghostTextForeground);
let opacity = undefined;
let color = undefined;
if (foreground) {
opacity = String(foreground.rgba.a);
color = color_1.Color.Format.CSS.format(opaque(foreground));
}
const borderColor = colorTheme.getColor(editorColorRegistry_1.ghostTextBorder);
let border = undefined;
if (borderColor) {
border = `2px dashed ${borderColor}`;
}
const textModel = this.editor.getModel();
if (!textModel) {
return;
}
const { tabSize } = textModel.getOptions();
const line = textModel.getLineContent(lineNumber) || '';
let lastIndex = 0;
let currentLinePrefix = '';
const hiddenTextDecorations = new Array();
if (hiddenText) {
hiddenTextDecorations.push({
range: range_1.Range.fromPositions(new position_1.Position(lineNumber, hiddenText.column), new position_1.Position(lineNumber, hiddenText.column + hiddenText.length)),
options: {
inlineClassName: 'ghost-text-hidden',
description: 'ghost-text-hidden'
}
});
}
const key = this.contextKeyService.getContextKeyValue('config.editor.useInjectedText');
const shouldUseInjectedText = key === undefined ? true : !!key;
this.decorationIds = this.editor.deltaDecorations(this.decorationIds, parts.map(p => {
currentLinePrefix += line.substring(lastIndex, p.column - 1);
lastIndex = p.column - 1;
// To avoid visual confusion, we don't want to render visible whitespace
const contentText = shouldUseInjectedText ? p.text : this.renderSingleLineText(p.text, currentLinePrefix, tabSize, false);
const decorationType = this.disposableStore.add(registerDecorationType(this.codeEditorService, 'ghost-text', '0-ghost-text-', {
after: {
// TODO: escape?
contentText,
opacity,
color,
border,
},
}));
return ({
range: range_1.Range.fromPositions(new position_1.Position(lineNumber, p.column)),
options: shouldUseInjectedText ? {
description: 'ghost-text',
after: { content: contentText, inlineClassName: 'ghost-text-decoration' }
} : Object.assign({}, decorationType.resolve())
});
}).concat(hiddenTextDecorations));
}
renderSingleLineText(text, lineStart, tabSize, renderWhitespace) {
const newLine = lineStart + text;
const visibleColumnsByColumns = cursorCommon_1.CursorColumns.visibleColumnsByColumns(newLine, tabSize);
let contentText = '';
let curCol = lineStart.length + 1;
for (const c of text) {
if (c === '\t') {
const width = visibleColumnsByColumns[curCol + 1] - visibleColumnsByColumns[curCol];
if (renderWhitespace) {
contentText += '→';
for (let i = 1; i < width; i++) {
contentText += '\xa0';
}
}
else {
for (let i = 0; i < width; i++) {
contentText += '\xa0';
}
}
}
else if (c === ' ') {
if (renderWhitespace) {
contentText += '·';
}
else {
contentText += '\xa0';
}
}
else {
contentText += c;
}
curCol += 1;
}
return contentText;
}
};
DecorationsWidget = __decorate([
__param(1, codeEditorService_1.ICodeEditorService),
__param(2, themeService_1.IThemeService),
__param(3, contextkey_1.IContextKeyService)
], DecorationsWidget);
function opaque(color) {
const { r, b, g } = color.rgba;
return new color_1.Color(new color_1.RGBA(r, g, b, 255));
}
class AdditionalLinesWidget {
constructor(editor) {
this.editor = editor;
this._viewZoneId = undefined;
}
get viewZoneId() { return this._viewZoneId; }
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._viewZoneId = changeAccessor.addZone({
afterLineNumber: lineNumber,
heightInLines: heightInLines,
domNode,
});
}
});
}
}
function renderLines(domNode, tabSize, lines, opts) {
const disableMonospaceOptimizations = opts.get(27 /* disableMonospaceOptimizations */);
const stopRenderingLineAfter = opts.get(104 /* stopRenderingLineAfter */);
// To avoid visual confusion, we don't want to render visible whitespace
const renderWhitespace = 'none';
const renderControlCharacters = opts.get(81 /* renderControlCharacters */);
const fontLigatures = opts.get(42 /* fontLigatures */);
const fontInfo = opts.get(41 /* fontInfo */);
const lineHeight = opts.get(57 /* lineHeight */);
const sb = (0, stringBuilder_1.createStringBuilder)(10000);
sb.appendASCIIString('<div class="suggest-preview-text">');
for (let i = 0, len = lines.length; i < len; i++) {
const lineData = lines[i];
const line = lineData.content;
sb.appendASCIIString('<div class="view-line');
sb.appendASCIIString('" style="top:');
sb.appendASCIIString(String(i * lineHeight));
sb.appendASCIIString('px;width:1000000px;">');
const isBasicASCII = strings.isBasicASCII(line);
const containsRTL = strings.containsRTL(line);
const lineTokens = lineTokens_1.LineTokens.createEmpty(line);
(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.appendASCIIString('</div>');
}
sb.appendASCIIString('</div>');
configuration_1.Configuration.applyFontInfoSlow(domNode, fontInfo);
const html = sb.build();
const trustedhtml = ttPolicy ? ttPolicy.createHTML(html) : html;
domNode.innerHTML = trustedhtml;
}
let keyCounter = 0;
function registerDecorationType(service, description, keyPrefix, options) {
const key = keyPrefix + (keyCounter++);
service.registerDecorationType(description, key, options);
return {
dispose() {
service.removeDecorationType(key);
},
resolve() {
return service.resolveDecorationOptions(key, true);
}
};
}
class ViewMoreLinesContentWidget extends lifecycle_1.Disposable {
constructor(editor, position, domNode, disposableStore) {
super();
this.editor = editor;
this.position = position;
this.domNode = domNode;
this.allowEditorOverflow = false;
this.suppressMouseDown = false;
this._register(disposableStore);
this._register((0, lifecycle_1.toDisposable)(() => {
this.editor.removeContentWidget(this);
}));
this.editor.addContentWidget(this);
}
getId() {
return 'editor.widget.viewMoreLinesWidget';
}
getDomNode() {
return this.domNode;
}
getPosition() {
return {
position: this.position,
preference: [0 /* EXACT */]
};
}
}
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const foreground = theme.getColor(editorColorRegistry_1.ghostTextForeground);
if (foreground) {
const opacity = String(foreground.rgba.a);
const color = color_1.Color.Format.CSS.format(opaque(foreground));
collector.addRule(`.monaco-editor .ghost-text-decoration { opacity: ${opacity}; color: ${color}; }`);
collector.addRule(`.monaco-editor .suggest-preview-text .ghost-text { opacity: ${opacity}; color: ${color}; }`);
}
const border = theme.getColor(editorColorRegistry_1.ghostTextBorder);
if (border) {
collector.addRule(`.monaco-editor .suggest-preview-text .ghost-text { border: 2px dashed ${border}; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/quickAccess/editorNavigationQuickAccess*/], __M([0/*require*/,1/*exports*/,53/*vs/editor/common/model*/,11/*vs/platform/theme/common/themeService*/,48/*vs/editor/common/view/editorColorRegistry*/,2/*vs/base/common/lifecycle*/,111/*vs/editor/browser/editorBrowser*/,20/*vs/base/common/types*/,80/*vs/base/common/functional*/]), function (require, exports, model_1, themeService_1, editorColorRegistry_1, lifecycle_1, editorBrowser_1, types_1, functional_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) {
var _a;
const disposables = new lifecycle_1.DisposableStore();
// Apply options if any
picker.canAcceptInBackground = !!((_a = this.options) === null || _a === void 0 ? void 0 : _a.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);
// 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) {
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 = (0, types_1.withNullAsUndefined)(editor.saveViewState());
disposables.add(codeEditor.onDidChangeCursorPosition(() => {
lastKnownEditorViewState = (0, types_1.withNullAsUndefined)(editor.saveViewState());
}));
context.restoreViewState = () => {
if (lastKnownEditorViewState && editor === this.activeTextEditorControl) {
editor.restoreViewState(lastKnownEditorViewState);
}
};
disposables.add((0, functional_1.once)(token.onCancellationRequested)(() => { var _a; return (_a = context.restoreViewState) === null || _a === void 0 ? void 0 : _a.call(context); }));
}
// 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));
}
// 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);
editor.revealRangeInCenter(options.range, 0 /* Smooth */);
if (!options.preserveFocus) {
editor.focus();
}
}
getModel(editor) {
var _a;
return (0, editorBrowser_1.isDiffEditor)(editor) ?
(_a = editor.getModel()) === null || _a === void 0 ? void 0 : _a.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[617/*vs/editor/contrib/quickAccess/gotoLineQuickAccess*/], __M([0/*require*/,1/*exports*/,513/*vs/nls!vs/editor/contrib/quickAccess/gotoLineQuickAccess*/,2/*vs/base/common/lifecycle*/,261/*vs/editor/contrib/quickAccess/editorNavigationQuickAccess*/,111/*vs/editor/browser/editorBrowser*/]), function (require, exports, nls_1, lifecycle_1, editorNavigationQuickAccess_1, editorBrowser_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AbstractGotoLineQuickAccessProvider = void 0;
class AbstractGotoLineQuickAccessProvider extends editorNavigationQuickAccess_1.AbstractEditorNavigationQuickAccessProvider {
constructor() {
super({ canAcceptInBackground: true });
}
provideWithoutTextEditor(picker) {
const label = (0, nls_1.localize)(0, null);
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 /* 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(58 /* lineNumbers */);
if (lineNumbers.renderType === 2 /* 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)(1, null, lineNumber, column);
}
return (0, nls_1.localize)(2, null, 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)(3, null, position.lineNumber, position.column, lineCount);
}
return (0, nls_1.localize)(4, null, 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) {
var _a, _b;
return (_b = (_a = this.getModel(editor)) === null || _a === void 0 ? void 0 : _a.getLineCount()) !== null && _b !== void 0 ? _b : 0;
}
}
exports.AbstractGotoLineQuickAccessProvider = AbstractGotoLineQuickAccessProvider;
AbstractGotoLineQuickAccessProvider.PREFIX = ':';
});
/*---------------------------------------------------------------------------------------------
* 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/quickAccess/gotoSymbolQuickAccess*/], __M([0/*require*/,1/*exports*/,514/*vs/nls!vs/editor/contrib/quickAccess/gotoSymbolQuickAccess*/,23/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/,261/*vs/editor/contrib/quickAccess/editorNavigationQuickAccess*/,18/*vs/editor/common/modes*/,248/*vs/editor/contrib/documentSymbols/outlineModel*/,8/*vs/base/common/strings*/,294/*vs/base/common/fuzzyScorer*/,27/*vs/base/common/codicons*/]), function (require, exports, nls_1, cancellation_1, lifecycle_1, range_1, editorNavigationQuickAccess_1, modes_1, outlineModel_1, strings_1, fuzzyScorer_1, codicons_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AbstractGotoSymbolQuickAccessProvider = void 0;
class AbstractGotoSymbolQuickAccessProvider extends editorNavigationQuickAccess_1.AbstractEditorNavigationQuickAccessProvider {
constructor(options = Object.create(null)) {
super(options);
this.options = options;
this.options.canAcceptInBackground = true;
}
provideWithoutTextEditor(picker) {
this.provideLabelPick(picker, (0, nls_1.localize)(0, null));
return lifecycle_1.Disposable.None;
}
provideWithTextEditor(context, picker, token) {
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 (modes_1.DocumentSymbolProviderRegistry.has(model)) {
return this.doProvideWithEditorSymbols(context, model, picker, token);
}
// 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)(1, null));
// 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
(() => __awaiter(this, void 0, void 0, function* () {
const result = yield 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 /* String */ }];
picker.ariaLabel = label;
}
waitForLanguageSymbolRegistry(model, disposables) {
return __awaiter(this, void 0, void 0, function* () {
if (modes_1.DocumentSymbolProviderRegistry.has(model)) {
return true;
}
let symbolProviderRegistryPromiseResolve;
const symbolProviderRegistryPromise = new Promise(resolve => symbolProviderRegistryPromiseResolve = resolve);
// Resolve promise when registry knows model
const symbolProviderListener = disposables.add(modes_1.DocumentSymbolProviderRegistry.onDidChange(() => {
if (modes_1.DocumentSymbolProviderRegistry.has(model)) {
symbolProviderListener.dispose();
symbolProviderRegistryPromiseResolve(true);
}
}));
// Resolve promise when we get disposed too
disposables.add((0, lifecycle_1.toDisposable)(() => symbolProviderRegistryPromiseResolve(false)));
return symbolProviderRegistryPromise;
});
}
doProvideWithEditorSymbols(context, model, picker, token) {
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 });
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 = () => __awaiter(this, void 0, void 0, function* () {
// Cancel any previous ask for picks and busy
picksCts === null || picksCts === void 0 ? void 0 : 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.PREFIX.length).trim());
const items = yield this.doGetSymbolPicks(symbolsPromise, query, undefined, picksCts.token);
if (token.isCancellationRequested) {
return;
}
if (items.length > 0) {
picker.items = items;
}
else {
if (query.original.length > 0) {
this.provideLabelPick(picker, (0, nls_1.localize)(2, null));
}
else {
this.provideLabelPick(picker, (0, nls_1.localize)(3, null));
}
}
}
finally {
if (!token.isCancellationRequested) {
picker.busy = false;
}
}
});
disposables.add(picker.onDidChangeValue(() => updatePickerItems()));
updatePickerItems();
// Reveal and decorate when active item changes
// However, ignore the very first event so that
// opening the picker is not immediately revealing
// and decorating the first entry.
let ignoreFirstActiveEvent = true;
disposables.add(picker.onDidChangeActive(() => {
const [item] = picker.activeItems;
if (item && item.range) {
if (ignoreFirstActiveEvent) {
ignoreFirstActiveEvent = false;
return;
}
// Reveal
editor.revealRangeInCenter(item.range.selection, 0 /* Smooth */);
// Decorate
this.addDecorations(editor, item.range.decoration);
}
}));
return disposables;
}
doGetSymbolPicks(symbolsPromise, query, options, token) {
return __awaiter(this, void 0, void 0, function* () {
const symbols = yield symbolsPromise;
if (token.isCancellationRequested) {
return [];
}
const filterBySymbolKind = query.original.indexOf(AbstractGotoSymbolQuickAccessProvider.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
const filteredSymbolPicks = [];
for (let index = 0; index < symbols.length; index++) {
const symbol = symbols[index];
const symbolLabel = (0, strings_1.trim)(symbol.name);
const symbolLabelWithIcon = `$(symbol-${modes_1.SymbolKinds.toString(symbol.kind) || 'property'}) ${symbolLabel}`;
const symbolLabelIconOffset = symbolLabelWithIcon.length - symbolLabel.length;
let containerLabel = symbol.containerName;
if (options === null || options === void 0 ? void 0 : 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, Object.assign(Object.assign({}, 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 /* Deprecated */) >= 0;
filteredSymbolPicks.push({
index,
kind: symbol.kind,
score: symbolScore,
label: symbolLabelWithIcon,
ariaLabel: symbolLabel,
description: containerLabel,
highlights: deprecated ? undefined : {
label: symbolMatches,
description: containerMatches
},
range: {
selection: range_1.Range.collapseToStart(symbol.selectionRange),
decoration: symbol.range
},
strikethrough: deprecated,
buttons: (() => {
var _a, _b;
const openSideBySideDirection = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.openSideBySideDirection) ? (_b = this.options) === null || _b === void 0 ? void 0 : _b.openSideBySideDirection() : undefined;
if (!openSideBySideDirection) {
return undefined;
}
return [
{
iconClass: openSideBySideDirection === 'right' ? codicons_1.Codicon.splitHorizontal.classNames : codicons_1.Codicon.splitVertical.classNames,
tooltip: openSideBySideDirection === 'right' ? (0, nls_1.localize)(4, null) : (0, nls_1.localize)(5, null)
}
];
})()
});
}
// 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)(6, null, 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;
}
getDocumentSymbols(document, token) {
return __awaiter(this, void 0, void 0, function* () {
const model = yield outlineModel_1.OutlineModel.create(document, token);
return token.isCancellationRequested ? [] : model.asListOfDocumentSymbols();
});
}
}
exports.AbstractGotoSymbolQuickAccessProvider = AbstractGotoSymbolQuickAccessProvider;
AbstractGotoSymbolQuickAccessProvider.PREFIX = '@';
AbstractGotoSymbolQuickAccessProvider.SCOPE_PREFIX = ':';
AbstractGotoSymbolQuickAccessProvider.PREFIX_BY_CATEGORY = `${AbstractGotoSymbolQuickAccessProvider.PREFIX}${AbstractGotoSymbolQuickAccessProvider.SCOPE_PREFIX}`;
// #region NLS Helpers
const FALLBACK_NLS_SYMBOL_KIND = (0, nls_1.localize)(7, null);
const NLS_SYMBOL_KIND_CACHE = {
[5 /* Method */]: (0, nls_1.localize)(8, null),
[11 /* Function */]: (0, nls_1.localize)(9, null),
[8 /* Constructor */]: (0, nls_1.localize)(10, null),
[12 /* Variable */]: (0, nls_1.localize)(11, null),
[4 /* Class */]: (0, nls_1.localize)(12, null),
[22 /* Struct */]: (0, nls_1.localize)(13, null),
[23 /* Event */]: (0, nls_1.localize)(14, null),
[24 /* Operator */]: (0, nls_1.localize)(15, null),
[10 /* Interface */]: (0, nls_1.localize)(16, null),
[2 /* Namespace */]: (0, nls_1.localize)(17, null),
[3 /* Package */]: (0, nls_1.localize)(18, null),
[25 /* TypeParameter */]: (0, nls_1.localize)(19, null),
[1 /* Module */]: (0, nls_1.localize)(20, null),
[6 /* Property */]: (0, nls_1.localize)(21, null),
[9 /* Enum */]: (0, nls_1.localize)(22, null),
[21 /* EnumMember */]: (0, nls_1.localize)(23, null),
[14 /* String */]: (0, nls_1.localize)(24, null),
[0 /* File */]: (0, nls_1.localize)(25, null),
[17 /* Array */]: (0, nls_1.localize)(26, null),
[15 /* Number */]: (0, nls_1.localize)(27, null),
[16 /* Boolean */]: (0, nls_1.localize)(28, null),
[18 /* Object */]: (0, nls_1.localize)(29, null),
[19 /* Key */]: (0, nls_1.localize)(30, null),
[7 /* Field */]: (0, nls_1.localize)(31, null),
[13 /* Constant */]: (0, nls_1.localize)(32, null)
};
});
//#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[619/*vs/editor/contrib/rename/renameInputField*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,13/*vs/editor/common/core/position*/,516/*vs/nls!vs/editor/contrib/rename/renameInputField*/,16/*vs/platform/contextkey/common/contextkey*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,37/*vs/platform/keybinding/common/keybinding*/,359/*vs/css!vs/editor/contrib/rename/renameInputField*/]), function (require, exports, lifecycle_1, position_1, nls_1, contextkey_1, colorRegistry_1, themeService_1, keybinding_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RenameInputField = exports.CONTEXT_RENAME_INPUT_VISIBLE = void 0;
exports.CONTEXT_RENAME_INPUT_VISIBLE = new contextkey_1.RawContextKey('renameInputVisible', false, (0, nls_1.localize)(0, null));
let RenameInputField = class RenameInputField {
constructor(_editor, _acceptKeybindings, _themeService, _keybindingService, contextKeyService) {
this._editor = _editor;
this._acceptKeybindings = _acceptKeybindings;
this._themeService = _themeService;
this._keybindingService = _keybindingService;
this._disposables = new lifecycle_1.DisposableStore();
this.allowEditorOverflow = true;
this._visibleContextKey = exports.CONTEXT_RENAME_INPUT_VISIBLE.bindTo(contextKeyService);
this._editor.addContentWidget(this);
this._disposables.add(this._editor.onDidChangeConfiguration(e => {
if (e.hasChanged(41 /* 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._input = document.createElement('input');
this._input.className = 'rename-input';
this._input.type = 'text';
this._input.setAttribute('aria-label', (0, nls_1.localize)(1, null));
this._domNode.appendChild(this._input);
this._label = document.createElement('div');
this._label.className = 'rename-label';
this._domNode.appendChild(this._label);
const updateLabel = () => {
var _a, _b;
const [accept, preview] = this._acceptKeybindings;
this._keybindingService.lookupKeybinding(accept);
this._label.innerText = (0, nls_1.localize)(2, null, (_a = this._keybindingService.lookupKeybinding(accept)) === null || _a === void 0 ? void 0 : _a.getLabel(), (_b = this._keybindingService.lookupKeybinding(preview)) === null || _b === void 0 ? void 0 : _b.getLabel());
};
updateLabel();
this._disposables.add(this._keybindingService.onDidUpdateKeybindings(updateLabel));
this._updateFont();
this._updateStyles(this._themeService.getColorTheme());
}
return this._domNode;
}
_updateStyles(theme) {
var _a, _b, _c, _d;
if (!this._input || !this._domNode) {
return;
}
const widgetShadowColor = theme.getColor(colorRegistry_1.widgetShadow);
this._domNode.style.backgroundColor = String((_a = theme.getColor(colorRegistry_1.editorWidgetBackground)) !== null && _a !== void 0 ? _a : '');
this._domNode.style.boxShadow = widgetShadowColor ? ` 0 0 8px 2px ${widgetShadowColor}` : '';
this._domNode.style.color = String((_b = theme.getColor(colorRegistry_1.inputForeground)) !== null && _b !== void 0 ? _b : '');
this._input.style.backgroundColor = String((_c = theme.getColor(colorRegistry_1.inputBackground)) !== null && _c !== void 0 ? _c : '');
// this._input.style.color = String(theme.getColor(inputForeground) ?? '');
const border = theme.getColor(colorRegistry_1.inputBorder);
this._input.style.borderWidth = border ? '1px' : '0px';
this._input.style.borderStyle = border ? 'solid' : 'none';
this._input.style.borderColor = (_d = border === null || border === void 0 ? void 0 : border.toString()) !== null && _d !== void 0 ? _d : 'none';
}
_updateFont() {
if (!this._input || !this._label) {
return;
}
const fontInfo = this._editor.getOption(41 /* fontInfo */);
this._input.style.fontFamily = fontInfo.fontFamily;
this._input.style.fontWeight = fontInfo.fontWeight;
this._input.style.fontSize = `${fontInfo.fontSize}px`;
this._label.style.fontSize = `${fontInfo.fontSize * 0.8}px`;
}
getPosition() {
if (!this._visible) {
return null;
}
return {
position: this._position,
preference: [2 /* BELOW */, 1 /* ABOVE */]
};
}
afterRender(position) {
if (!position) {
// cancel rename when input widget isn't rendered anymore
this.cancelInput(true);
}
}
acceptInput(wantsPreview) {
if (this._currentAcceptInput) {
this._currentAcceptInput(wantsPreview);
}
}
cancelInput(focusEditor) {
if (this._currentCancelInput) {
this._currentCancelInput(focusEditor);
}
}
getInput(where, value, selectionStart, selectionEnd, supportPreview, token) {
this._domNode.classList.toggle('preview', supportPreview);
this._position = new position_1.Position(where.startLineNumber, where.startColumn);
this._input.value = value;
this._input.setAttribute('selectionStart', selectionStart.toString());
this._input.setAttribute('selectionEnd', selectionEnd.toString());
this._input.size = Math.max((where.endColumn - where.startColumn) * 1.1, 20);
const disposeOnDone = new lifecycle_1.DisposableStore();
return new Promise(resolve => {
this._currentCancelInput = (focusEditor) => {
this._currentAcceptInput = undefined;
this._currentCancelInput = undefined;
resolve(focusEditor);
return true;
};
this._currentAcceptInput = (wantsPreview) => {
if (this._input.value.trim().length === 0 || this._input.value === value) {
// empty or whitespace only or not changed
this.cancelInput(true);
return;
}
this._currentAcceptInput = undefined;
this._currentCancelInput = undefined;
resolve({
newName: this._input.value,
wantsPreview: supportPreview && wantsPreview
});
};
token.onCancellationRequested(() => this.cancelInput(true));
disposeOnDone.add(this._editor.onDidBlurEditorWidget(() => this.cancelInput(false)));
this._show();
}).finally(() => {
disposeOnDone.dispose();
this._hide();
});
}
_show() {
this._editor.revealLineInCenterIfOutsideViewport(this._position.lineNumber, 0 /* Smooth */);
this._visible = true;
this._visibleContextKey.set(true);
this._editor.layoutContentWidget(this);
setTimeout(() => {
this._input.focus();
this._input.setSelectionRange(parseInt(this._input.getAttribute('selectionStart')), parseInt(this._input.getAttribute('selectionEnd')));
}, 100);
}
_hide() {
this._visible = false;
this._visibleContextKey.reset();
this._editor.layoutContentWidget(this);
}
};
RenameInputField = __decorate([
__param(2, themeService_1.IThemeService),
__param(3, keybinding_1.IKeybindingService),
__param(4, contextkey_1.IContextKeyService)
], RenameInputField);
exports.RenameInputField = RenameInputField;
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/symbolIcons/symbolIcons*/], __M([0/*require*/,1/*exports*/,526/*vs/nls!vs/editor/contrib/symbolIcons/symbolIcons*/,11/*vs/platform/theme/common/themeService*/,22/*vs/platform/theme/common/colorRegistry*/,27/*vs/base/common/codicons*/]), function (require, exports, nls_1, themeService_1, colorRegistry_1, codicons_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', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(0, null));
exports.SYMBOL_ICON_BOOLEAN_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.booleanForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(1, null));
exports.SYMBOL_ICON_CLASS_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.classForeground', {
dark: '#EE9D28',
light: '#D67E00',
hc: '#EE9D28'
}, (0, nls_1.localize)(2, null));
exports.SYMBOL_ICON_COLOR_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.colorForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(3, null));
exports.SYMBOL_ICON_CONSTANT_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.constantForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(4, null));
exports.SYMBOL_ICON_CONSTRUCTOR_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.constructorForeground', {
dark: '#B180D7',
light: '#652D90',
hc: '#B180D7'
}, (0, nls_1.localize)(5, null));
exports.SYMBOL_ICON_ENUMERATOR_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.enumeratorForeground', {
dark: '#EE9D28',
light: '#D67E00',
hc: '#EE9D28'
}, (0, nls_1.localize)(6, null));
exports.SYMBOL_ICON_ENUMERATOR_MEMBER_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.enumeratorMemberForeground', {
dark: '#75BEFF',
light: '#007ACC',
hc: '#75BEFF'
}, (0, nls_1.localize)(7, null));
exports.SYMBOL_ICON_EVENT_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.eventForeground', {
dark: '#EE9D28',
light: '#D67E00',
hc: '#EE9D28'
}, (0, nls_1.localize)(8, null));
exports.SYMBOL_ICON_FIELD_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.fieldForeground', {
dark: '#75BEFF',
light: '#007ACC',
hc: '#75BEFF'
}, (0, nls_1.localize)(9, null));
exports.SYMBOL_ICON_FILE_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.fileForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(10, null));
exports.SYMBOL_ICON_FOLDER_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.folderForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(11, null));
exports.SYMBOL_ICON_FUNCTION_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.functionForeground', {
dark: '#B180D7',
light: '#652D90',
hc: '#B180D7'
}, (0, nls_1.localize)(12, null));
exports.SYMBOL_ICON_INTERFACE_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.interfaceForeground', {
dark: '#75BEFF',
light: '#007ACC',
hc: '#75BEFF'
}, (0, nls_1.localize)(13, null));
exports.SYMBOL_ICON_KEY_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.keyForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(14, null));
exports.SYMBOL_ICON_KEYWORD_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.keywordForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(15, null));
exports.SYMBOL_ICON_METHOD_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.methodForeground', {
dark: '#B180D7',
light: '#652D90',
hc: '#B180D7'
}, (0, nls_1.localize)(16, null));
exports.SYMBOL_ICON_MODULE_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.moduleForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(17, null));
exports.SYMBOL_ICON_NAMESPACE_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.namespaceForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(18, null));
exports.SYMBOL_ICON_NULL_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.nullForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(19, null));
exports.SYMBOL_ICON_NUMBER_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.numberForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(20, null));
exports.SYMBOL_ICON_OBJECT_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.objectForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(21, null));
exports.SYMBOL_ICON_OPERATOR_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.operatorForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(22, null));
exports.SYMBOL_ICON_PACKAGE_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.packageForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(23, null));
exports.SYMBOL_ICON_PROPERTY_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.propertyForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(24, null));
exports.SYMBOL_ICON_REFERENCE_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.referenceForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(25, null));
exports.SYMBOL_ICON_SNIPPET_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.snippetForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(26, null));
exports.SYMBOL_ICON_STRING_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.stringForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(27, null));
exports.SYMBOL_ICON_STRUCT_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.structForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(28, null));
exports.SYMBOL_ICON_TEXT_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.textForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(29, null));
exports.SYMBOL_ICON_TYPEPARAMETER_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.typeParameterForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(30, null));
exports.SYMBOL_ICON_UNIT_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.unitForeground', {
dark: colorRegistry_1.foreground,
light: colorRegistry_1.foreground,
hc: colorRegistry_1.foreground
}, (0, nls_1.localize)(31, null));
exports.SYMBOL_ICON_VARIABLE_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.variableForeground', {
dark: '#75BEFF',
light: '#007ACC',
hc: '#75BEFF'
}, (0, nls_1.localize)(32, null));
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const symbolIconArrayColor = theme.getColor(exports.SYMBOL_ICON_ARRAY_FOREGROUND);
if (symbolIconArrayColor) {
collector.addRule(`${codicons_1.Codicon.symbolArray.cssSelector} { color: ${symbolIconArrayColor}; }`);
}
const symbolIconBooleanColor = theme.getColor(exports.SYMBOL_ICON_BOOLEAN_FOREGROUND);
if (symbolIconBooleanColor) {
collector.addRule(`${codicons_1.Codicon.symbolBoolean.cssSelector} { color: ${symbolIconBooleanColor}; }`);
}
const symbolIconClassColor = theme.getColor(exports.SYMBOL_ICON_CLASS_FOREGROUND);
if (symbolIconClassColor) {
collector.addRule(`${codicons_1.Codicon.symbolClass.cssSelector} { color: ${symbolIconClassColor}; }`);
}
const symbolIconMethodColor = theme.getColor(exports.SYMBOL_ICON_METHOD_FOREGROUND);
if (symbolIconMethodColor) {
collector.addRule(`${codicons_1.Codicon.symbolMethod.cssSelector} { color: ${symbolIconMethodColor}; }`);
}
const symbolIconColorColor = theme.getColor(exports.SYMBOL_ICON_COLOR_FOREGROUND);
if (symbolIconColorColor) {
collector.addRule(`${codicons_1.Codicon.symbolColor.cssSelector} { color: ${symbolIconColorColor}; }`);
}
const symbolIconConstantColor = theme.getColor(exports.SYMBOL_ICON_CONSTANT_FOREGROUND);
if (symbolIconConstantColor) {
collector.addRule(`${codicons_1.Codicon.symbolConstant.cssSelector} { color: ${symbolIconConstantColor}; }`);
}
const symbolIconConstructorColor = theme.getColor(exports.SYMBOL_ICON_CONSTRUCTOR_FOREGROUND);
if (symbolIconConstructorColor) {
collector.addRule(`${codicons_1.Codicon.symbolConstructor.cssSelector} { color: ${symbolIconConstructorColor}; }`);
}
const symbolIconEnumeratorColor = theme.getColor(exports.SYMBOL_ICON_ENUMERATOR_FOREGROUND);
if (symbolIconEnumeratorColor) {
collector.addRule(`
${codicons_1.Codicon.symbolValue.cssSelector},${codicons_1.Codicon.symbolEnum.cssSelector} { color: ${symbolIconEnumeratorColor}; }`);
}
const symbolIconEnumeratorMemberColor = theme.getColor(exports.SYMBOL_ICON_ENUMERATOR_MEMBER_FOREGROUND);
if (symbolIconEnumeratorMemberColor) {
collector.addRule(`${codicons_1.Codicon.symbolEnumMember.cssSelector} { color: ${symbolIconEnumeratorMemberColor}; }`);
}
const symbolIconEventColor = theme.getColor(exports.SYMBOL_ICON_EVENT_FOREGROUND);
if (symbolIconEventColor) {
collector.addRule(`${codicons_1.Codicon.symbolEvent.cssSelector} { color: ${symbolIconEventColor}; }`);
}
const symbolIconFieldColor = theme.getColor(exports.SYMBOL_ICON_FIELD_FOREGROUND);
if (symbolIconFieldColor) {
collector.addRule(`${codicons_1.Codicon.symbolField.cssSelector} { color: ${symbolIconFieldColor}; }`);
}
const symbolIconFileColor = theme.getColor(exports.SYMBOL_ICON_FILE_FOREGROUND);
if (symbolIconFileColor) {
collector.addRule(`${codicons_1.Codicon.symbolFile.cssSelector} { color: ${symbolIconFileColor}; }`);
}
const symbolIconFolderColor = theme.getColor(exports.SYMBOL_ICON_FOLDER_FOREGROUND);
if (symbolIconFolderColor) {
collector.addRule(`${codicons_1.Codicon.symbolFolder.cssSelector} { color: ${symbolIconFolderColor}; }`);
}
const symbolIconFunctionColor = theme.getColor(exports.SYMBOL_ICON_FUNCTION_FOREGROUND);
if (symbolIconFunctionColor) {
collector.addRule(`${codicons_1.Codicon.symbolFunction.cssSelector} { color: ${symbolIconFunctionColor}; }`);
}
const symbolIconInterfaceColor = theme.getColor(exports.SYMBOL_ICON_INTERFACE_FOREGROUND);
if (symbolIconInterfaceColor) {
collector.addRule(`${codicons_1.Codicon.symbolInterface.cssSelector} { color: ${symbolIconInterfaceColor}; }`);
}
const symbolIconKeyColor = theme.getColor(exports.SYMBOL_ICON_KEY_FOREGROUND);
if (symbolIconKeyColor) {
collector.addRule(`${codicons_1.Codicon.symbolKey.cssSelector} { color: ${symbolIconKeyColor}; }`);
}
const symbolIconKeywordColor = theme.getColor(exports.SYMBOL_ICON_KEYWORD_FOREGROUND);
if (symbolIconKeywordColor) {
collector.addRule(`${codicons_1.Codicon.symbolKeyword.cssSelector} { color: ${symbolIconKeywordColor}; }`);
}
const symbolIconModuleColor = theme.getColor(exports.SYMBOL_ICON_MODULE_FOREGROUND);
if (symbolIconModuleColor) {
collector.addRule(`${codicons_1.Codicon.symbolModule.cssSelector} { color: ${symbolIconModuleColor}; }`);
}
const outlineNamespaceColor = theme.getColor(exports.SYMBOL_ICON_NAMESPACE_FOREGROUND);
if (outlineNamespaceColor) {
collector.addRule(`${codicons_1.Codicon.symbolNamespace.cssSelector} { color: ${outlineNamespaceColor}; }`);
}
const symbolIconNullColor = theme.getColor(exports.SYMBOL_ICON_NULL_FOREGROUND);
if (symbolIconNullColor) {
collector.addRule(`${codicons_1.Codicon.symbolNull.cssSelector} { color: ${symbolIconNullColor}; }`);
}
const symbolIconNumberColor = theme.getColor(exports.SYMBOL_ICON_NUMBER_FOREGROUND);
if (symbolIconNumberColor) {
collector.addRule(`${codicons_1.Codicon.symbolNumber.cssSelector} { color: ${symbolIconNumberColor}; }`);
}
const symbolIconObjectColor = theme.getColor(exports.SYMBOL_ICON_OBJECT_FOREGROUND);
if (symbolIconObjectColor) {
collector.addRule(`${codicons_1.Codicon.symbolObject.cssSelector} { color: ${symbolIconObjectColor}; }`);
}
const symbolIconOperatorColor = theme.getColor(exports.SYMBOL_ICON_OPERATOR_FOREGROUND);
if (symbolIconOperatorColor) {
collector.addRule(`${codicons_1.Codicon.symbolOperator.cssSelector} { color: ${symbolIconOperatorColor}; }`);
}
const symbolIconPackageColor = theme.getColor(exports.SYMBOL_ICON_PACKAGE_FOREGROUND);
if (symbolIconPackageColor) {
collector.addRule(`${codicons_1.Codicon.symbolPackage.cssSelector} { color: ${symbolIconPackageColor}; }`);
}
const symbolIconPropertyColor = theme.getColor(exports.SYMBOL_ICON_PROPERTY_FOREGROUND);
if (symbolIconPropertyColor) {
collector.addRule(`${codicons_1.Codicon.symbolProperty.cssSelector} { color: ${symbolIconPropertyColor}; }`);
}
const symbolIconReferenceColor = theme.getColor(exports.SYMBOL_ICON_REFERENCE_FOREGROUND);
if (symbolIconReferenceColor) {
collector.addRule(`${codicons_1.Codicon.symbolReference.cssSelector} { color: ${symbolIconReferenceColor}; }`);
}
const symbolIconSnippetColor = theme.getColor(exports.SYMBOL_ICON_SNIPPET_FOREGROUND);
if (symbolIconSnippetColor) {
collector.addRule(`${codicons_1.Codicon.symbolSnippet.cssSelector} { color: ${symbolIconSnippetColor}; }`);
}
const symbolIconStringColor = theme.getColor(exports.SYMBOL_ICON_STRING_FOREGROUND);
if (symbolIconStringColor) {
collector.addRule(`${codicons_1.Codicon.symbolString.cssSelector} { color: ${symbolIconStringColor}; }`);
}
const symbolIconStructColor = theme.getColor(exports.SYMBOL_ICON_STRUCT_FOREGROUND);
if (symbolIconStructColor) {
collector.addRule(`${codicons_1.Codicon.symbolStruct.cssSelector} { color: ${symbolIconStructColor}; }`);
}
const symbolIconTextColor = theme.getColor(exports.SYMBOL_ICON_TEXT_FOREGROUND);
if (symbolIconTextColor) {
collector.addRule(`${codicons_1.Codicon.symbolText.cssSelector} { color: ${symbolIconTextColor}; }`);
}
const symbolIconTypeParameterColor = theme.getColor(exports.SYMBOL_ICON_TYPEPARAMETER_FOREGROUND);
if (symbolIconTypeParameterColor) {
collector.addRule(`${codicons_1.Codicon.symbolTypeParameter.cssSelector} { color: ${symbolIconTypeParameterColor}; }`);
}
const symbolIconUnitColor = theme.getColor(exports.SYMBOL_ICON_UNIT_FOREGROUND);
if (symbolIconUnitColor) {
collector.addRule(`${codicons_1.Codicon.symbolUnit.cssSelector} { color: ${symbolIconUnitColor}; }`);
}
const symbolIconVariableColor = theme.getColor(exports.SYMBOL_ICON_VARIABLE_FOREGROUND);
if (symbolIconVariableColor) {
collector.addRule(`${codicons_1.Codicon.symbolVariable.cssSelector} { color: ${symbolIconVariableColor}; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/standalone/browser/standaloneCodeServiceImpl*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,46/*vs/base/common/network*/,597/*vs/editor/browser/services/codeEditorServiceImpl*/,16/*vs/platform/contextkey/common/contextkey*/,11/*vs/platform/theme/common/themeService*/]), function (require, exports, dom_1, network_1, codeEditorServiceImpl_1, contextkey_1, themeService_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StandaloneCodeEditorServiceImpl = void 0;
let StandaloneCodeEditorServiceImpl = class StandaloneCodeEditorServiceImpl extends codeEditorServiceImpl_1.CodeEditorServiceImpl {
constructor(styleSheet, contextKeyService, themeService) {
super(styleSheet, themeService);
this.onCodeEditorAdd(() => this._checkContextKey());
this.onCodeEditorRemove(() => this._checkContextKey());
this._editorIsOpen = contextKeyService.createKey('editorIsOpen', false);
this._activeCodeEditor = null;
}
_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;
}
openCodeEditor(input, source, sideBySide) {
if (!source) {
return Promise.resolve(null);
}
return Promise.resolve(this.doOpenEditor(source, input));
}
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 /* Immediate */);
}
else {
const pos = {
lineNumber: selection.startLineNumber,
column: selection.startColumn
};
editor.setPosition(pos);
editor.revealPositionInCenter(pos, 1 /* Immediate */);
}
}
return editor;
}
findModel(editor, resource) {
const model = editor.getModel();
if (model && model.uri.toString() !== resource.toString()) {
return null;
}
return model;
}
};
StandaloneCodeEditorServiceImpl = __decorate([
__param(1, contextkey_1.IContextKeyService),
__param(2, themeService_1.IThemeService)
], StandaloneCodeEditorServiceImpl);
exports.StandaloneCodeEditorServiceImpl = StandaloneCodeEditorServiceImpl;
});
/*---------------------------------------------------------------------------------------------
* 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/standalone/common/themes*/], __M([0/*require*/,1/*exports*/,48/*vs/editor/common/view/editorColorRegistry*/,22/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, editorColorRegistry_1, colorRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
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.editorIndentGuides]: '#D3D3D3',
[editorColorRegistry_1.editorActiveIndentGuides]: '#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.editorIndentGuides]: '#404040',
[editorColorRegistry_1.editorActiveIndentGuides]: '#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.editorIndentGuides]: '#FFFFFF',
[editorColorRegistry_1.editorActiveIndentGuides]: '#FFFFFF',
}
};
});
/* -------------------------------- End hc-black 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[33/*vs/platform/actions/common/actions*/], __M([0/*require*/,1/*exports*/,50/*vs/base/common/actions*/,9/*vs/platform/instantiation/common/instantiation*/,16/*vs/platform/contextkey/common/contextkey*/,26/*vs/platform/commands/common/commands*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/,11/*vs/platform/theme/common/themeService*/,54/*vs/base/common/iterator*/,72/*vs/base/common/linkedList*/,27/*vs/base/common/codicons*/]), function (require, exports, actions_1, instantiation_1, contextkey_1, commands_1, lifecycle_1, event_1, themeService_1, iterator_1, linkedList_1, codicons_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MenuItemAction = exports.SubmenuItemAction = exports.MenuRegistry = exports.IMenuService = exports.MenuId = exports.isIMenuItem = void 0;
function isIMenuItem(item) {
return item.command !== undefined;
}
exports.isIMenuItem = isIMenuItem;
class MenuId {
constructor(debugName) {
this.id = MenuId._idPool++;
this._debugName = debugName;
}
}
exports.MenuId = MenuId;
MenuId._idPool = 0;
MenuId.CommandPalette = new MenuId('CommandPalette');
MenuId.EditorContext = new MenuId('EditorContext');
MenuId.SimpleEditorContext = new MenuId('SimpleEditorContext');
MenuId.EditorContextCopy = new MenuId('EditorContextCopy');
MenuId.EditorContextPeek = new MenuId('EditorContextPeek');
MenuId.MenubarEditMenu = new MenuId('MenubarEditMenu');
MenuId.MenubarCopy = new MenuId('MenubarCopy');
MenuId.MenubarGoMenu = new MenuId('MenubarGoMenu');
MenuId.MenubarSelectionMenu = new MenuId('MenubarSelectionMenu');
MenuId.InlineCompletionsActions = new MenuId('InlineCompletionsActions');
exports.IMenuService = (0, instantiation_1.createDecorator)('menuService');
exports.MenuRegistry = new class {
constructor() {
this._commands = new Map();
this._menuItems = new Map();
this._onDidChangeMenu = new event_1.Emitter();
this.onDidChangeMenu = this._onDidChangeMenu.event;
this._commandPaletteChangeEvent = {
has: id => id === MenuId.CommandPalette
};
}
addCommand(command) {
return this.addCommands(iterator_1.Iterable.single(command));
}
addCommands(commands) {
for (const command of commands) {
this._commands.set(command.id, command);
}
this._onDidChangeMenu.fire(this._commandPaletteChangeEvent);
return (0, lifecycle_1.toDisposable)(() => {
let didChange = false;
for (const command of commands) {
didChange = this._commands.delete(command.id) || didChange;
}
if (didChange) {
this._onDidChangeMenu.fire(this._commandPaletteChangeEvent);
}
});
}
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) {
return this.appendMenuItems(iterator_1.Iterable.single({ id, item }));
}
appendMenuItems(items) {
const changedIds = new Set();
const toRemove = new linkedList_1.LinkedList();
for (const { id, item } of items) {
let list = this._menuItems.get(id);
if (!list) {
list = new linkedList_1.LinkedList();
this._menuItems.set(id, list);
}
toRemove.push(list.push(item));
changedIds.add(id);
}
this._onDidChangeMenu.fire(changedIds);
return (0, lifecycle_1.toDisposable)(() => {
if (toRemove.size > 0) {
for (let fn of toRemove) {
fn();
}
this._onDidChangeMenu.fire(changedIds);
toRemove.clear();
}
});
}
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, _menuService, _contextKeyService, _options) {
super(`submenuitem.${item.submenu.id}`, typeof item.title === 'string' ? item.title : item.title.value, [], 'submenu');
this.item = item;
this._menuService = _menuService;
this._contextKeyService = _contextKeyService;
this._options = _options;
}
get actions() {
const result = [];
const menu = this._menuService.createMenu(this.item.submenu, this._contextKeyService);
const groups = menu.getActions(this._options);
menu.dispose();
for (const [, actions] of groups) {
if (actions.length > 0) {
result.push(...actions);
result.push(new actions_1.Separator());
}
}
if (result.length) {
result.pop(); // remove last separator
}
return result;
}
}
exports.SubmenuItemAction = SubmenuItemAction;
// implements IAction, does NOT extend Action, so that no one
// subscribes to events of Action or modified properties
let MenuItemAction = class MenuItemAction {
constructor(item, alt, options, contextKeyService, _commandService) {
var _a;
this._commandService = _commandService;
this.id = item.id;
this.label = (options === null || options === void 0 ? void 0 : options.renderShortTitle) && item.shortTitle
? (typeof item.shortTitle === 'string' ? item.shortTitle : item.shortTitle.value)
: (typeof item.title === 'string' ? item.title : item.title.value);
this.tooltip = (_a = item.tooltip) !== null && _a !== void 0 ? _a : '';
this.enabled = !item.precondition || contextKeyService.contextMatchesRules(item.precondition);
this.checked = false;
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 (toggled.title) {
this.label = typeof toggled.title === 'string' ? toggled.title : toggled.title.value;
}
}
this.item = item;
this.alt = alt ? new MenuItemAction(alt, undefined, options, contextKeyService, _commandService) : undefined;
this._options = options;
if (themeService_1.ThemeIcon.isThemeIcon(item.icon)) {
this.class = codicons_1.CSSIcon.asClassName(item.icon);
}
}
dispose() {
// there is NOTHING to dispose and the MenuItemAction should
// never have anything to dispose as it is a convenience type
// to bridge into the rendering world.
}
run(...args) {
var _a, _b;
let runArgs = [];
if ((_a = this._options) === null || _a === void 0 ? void 0 : _a.arg) {
runArgs = [...runArgs, this._options.arg];
}
if ((_b = this._options) === null || _b === void 0 ? void 0 : _b.shouldForwardArgs) {
runArgs = [...runArgs, ...args];
}
return this._commandService.executeCommand(this.id, ...runArgs);
}
};
MenuItemAction = __decorate([
__param(3, contextkey_1.IContextKeyService),
__param(4, commands_1.ICommandService)
], MenuItemAction);
exports.MenuItemAction = MenuItemAction;
});
//#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[14/*vs/editor/browser/editorExtensions*/], __M([0/*require*/,1/*exports*/,457/*vs/nls!vs/editor/browser/editorExtensions*/,24/*vs/base/common/uri*/,28/*vs/editor/browser/services/codeEditorService*/,13/*vs/editor/common/core/position*/,36/*vs/editor/common/services/modelService*/,68/*vs/editor/common/services/resolverService*/,33/*vs/platform/actions/common/actions*/,26/*vs/platform/commands/common/commands*/,16/*vs/platform/contextkey/common/contextkey*/,88/*vs/platform/keybinding/common/keybindingsRegistry*/,32/*vs/platform/registry/common/platform*/,89/*vs/platform/telemetry/common/telemetry*/,20/*vs/base/common/types*/,70/*vs/platform/log/common/log*/]), function (require, exports, nls, uri_1, codeEditorService_1, position_1, modelService_1, resolverService_1, actions_1, commands_1, contextkey_1, keybindingsRegistry_1, platform_1, telemetry_1, types_1, log_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SelectAllCommand = exports.RedoCommand = exports.UndoCommand = exports.EditorExtensionsRegistry = exports.registerEditorContribution = exports.registerInstantiatedEditorAction = exports.registerMultiEditorAction = exports.registerEditorAction = exports.registerEditorCommand = exports.registerModelCommand = exports.registerModelAndPositionCommand = exports.MultiEditorAction = exports.EditorAction = exports.EditorCommand = exports.ProxyCommand = exports.MultiCommand = exports.Command = void 0;
class Command {
constructor(opts) {
this.id = opts.id;
this.precondition = opts.precondition;
this._kbOpts = opts.kbOpts;
this._menuOpts = opts.menuOpts;
this._description = opts.description;
}
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),
description: this._description
});
}
_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) {
this._implementations.push({ priority, name, implementation });
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);
for (const impl of this._implementations) {
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;
}
}
}
}
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(controllerGetter(editor), args);
}
}
};
}
runCommand(accessor, args) {
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((0, types_1.withNullAsUndefined)(this.precondition))) {
// precondition does not hold
return;
}
return this.runEditorCommand(editorAccessor, editor, args);
});
}
}
exports.EditorCommand = EditorCommand;
class EditorAction extends EditorCommand {
constructor(opts) {
super(EditorAction.convertOptions(opts));
this.label = opts.label;
this.alias = opts.alias;
}
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;
}
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
// --- Registration of commands and actions
function registerModelAndPositionCommand(id, handler) {
commands_1.CommandsRegistry.registerCommand(id, function (accessor, ...args) {
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(modelService_1.IModelService).getModel(resource);
if (model) {
const editorPosition = position_1.Position.lift(position);
return handler(model, editorPosition, ...args.slice(2));
}
return accessor.get(resolverService_1.ITextModelService).createModelReference(resource).then(reference => {
return new Promise((resolve, reject) => {
try {
const result = handler(reference.object.textEditorModel, position_1.Position.lift(position), args.slice(2));
resolve(result);
}
catch (err) {
reject(err);
}
}).finally(() => {
reference.dispose();
});
});
});
}
exports.registerModelAndPositionCommand = registerModelAndPositionCommand;
function registerModelCommand(id, handler) {
commands_1.CommandsRegistry.registerCommand(id, function (accessor, ...args) {
const [resource] = args;
(0, types_1.assertType)(uri_1.URI.isUri(resource));
const model = accessor.get(modelService_1.IModelService).getModel(resource);
if (model) {
return handler(model, ...args.slice(1));
}
return accessor.get(resolverService_1.ITextModelService).createModelReference(resource).then(reference => {
return new Promise((resolve, reject) => {
try {
const result = handler(reference.object.textEditorModel, args.slice(1));
resolve(result);
}
catch (err) {
reject(err);
}
}).finally(() => {
reference.dispose();
});
});
});
}
exports.registerModelCommand = registerModelCommand;
function registerEditorCommand(editorCommand) {
EditorContributionRegistry.INSTANCE.registerEditorCommand(editorCommand);
return editorCommand;
}
exports.registerEditorCommand = registerEditorCommand;
function registerEditorAction(ctor) {
const action = new ctor();
EditorContributionRegistry.INSTANCE.registerEditorAction(action);
return action;
}
exports.registerEditorAction = registerEditorAction;
function registerMultiEditorAction(action) {
EditorContributionRegistry.INSTANCE.registerEditorAction(action);
return action;
}
exports.registerMultiEditorAction = registerMultiEditorAction;
function registerInstantiatedEditorAction(editorAction) {
EditorContributionRegistry.INSTANCE.registerEditorAction(editorAction);
}
exports.registerInstantiatedEditorAction = registerInstantiatedEditorAction;
function registerEditorContribution(id, ctor) {
EditorContributionRegistry.INSTANCE.registerEditorContribution(id, ctor);
}
exports.registerEditorContribution = registerEditorContribution;
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 || (exports.EditorExtensionsRegistry = {}));
// Editor extension points
const Extensions = {
EditorCommonContributions: 'editor.contributions'
};
class EditorContributionRegistry {
constructor() {
this.editorContributions = [];
this.diffEditorContributions = [];
this.editorActions = [];
this.editorCommands = Object.create(null);
}
registerEditorContribution(id, ctor) {
this.editorContributions.push({ id, ctor: ctor });
}
getEditorContributions() {
return this.editorContributions.slice(0);
}
getDiffEditorContributions() {
return this.diffEditorContributions.slice(0);
}
registerEditorAction(action) {
action.register();
this.editorActions.push(action);
}
getEditorActions() {
return this.editorActions.slice(0);
}
registerEditorCommand(editorCommand) {
editorCommand.register();
this.editorCommands[editorCommand.id] = editorCommand;
}
getEditorCommand(commandId) {
return (this.editorCommands[commandId] || null);
}
}
EditorContributionRegistry.INSTANCE = new EditorContributionRegistry();
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 /* EditorCore */,
primary: 2048 /* CtrlCmd */ | 56 /* KEY_Z */
},
menuOpts: [{
menuId: actions_1.MenuId.MenubarEditMenu,
group: '1_do',
title: nls.localize(0, null),
order: 1
}, {
menuId: actions_1.MenuId.CommandPalette,
group: '',
title: nls.localize(1, null),
order: 1
}]
}));
registerCommand(new ProxyCommand(exports.UndoCommand, { id: 'default:undo', precondition: undefined }));
exports.RedoCommand = registerCommand(new MultiCommand({
id: 'redo',
precondition: undefined,
kbOpts: {
weight: 0 /* EditorCore */,
primary: 2048 /* CtrlCmd */ | 55 /* KEY_Y */,
secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 56 /* KEY_Z */],
mac: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 56 /* KEY_Z */ }
},
menuOpts: [{
menuId: actions_1.MenuId.MenubarEditMenu,
group: '1_do',
title: nls.localize(2, null),
order: 2
}, {
menuId: actions_1.MenuId.CommandPalette,
group: '',
title: nls.localize(3, null),
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 /* EditorCore */,
kbExpr: null,
primary: 2048 /* CtrlCmd */ | 31 /* KEY_A */
},
menuOpts: [{
menuId: actions_1.MenuId.MenubarSelectionMenu,
group: '1_basic',
title: nls.localize(4, null),
order: 1
}, {
menuId: actions_1.MenuId.CommandPalette,
group: '',
title: nls.localize(5, null),
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[148/*vs/editor/browser/controller/coreCommands*/], __M([0/*require*/,1/*exports*/,454/*vs/nls!vs/editor/browser/controller/coreCommands*/,39/*vs/base/browser/browser*/,20/*vs/base/common/types*/,44/*vs/base/browser/ui/aria/aria*/,14/*vs/editor/browser/editorExtensions*/,28/*vs/editor/browser/services/codeEditorService*/,550/*vs/editor/common/controller/cursorColumnSelection*/,40/*vs/editor/common/controller/cursorCommon*/,186/*vs/editor/common/controller/cursorDeleteOperations*/,244/*vs/editor/common/controller/cursorMoveCommands*/,187/*vs/editor/common/controller/cursorTypeOperations*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,25/*vs/editor/common/editorContextKeys*/,16/*vs/platform/contextkey/common/contextkey*/,88/*vs/platform/keybinding/common/keybindingsRegistry*/]), 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) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CoreEditingCommands = exports.CoreNavigationCommands = exports.RevealLine_ = exports.EditorScroll_ = exports.CoreEditorCommand = void 0;
const CORE_WEIGHT = 0 /* 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_.description = {
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'
\`\`\`
* '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']
},
'value': {
'type': 'number',
'default': 1
},
'revealCursor': {
'type': 'boolean',
}
}
}
}
]
};
/**
* Directions in the view for editor scroll command.
*/
EditorScroll_.RawDirection = {
Up: 'up',
Down: 'down',
};
/**
* Units for editor scroll 'by' argument
*/
EditorScroll_.RawUnit = {
Line: 'line',
WrappedLine: 'wrappedLine',
Page: 'page',
HalfPage: 'halfPage'
};
function parse(args) {
let direction;
switch (args.to) {
case EditorScroll_.RawDirection.Up:
direction = 1 /* Up */;
break;
case EditorScroll_.RawDirection.Down:
direction = 2 /* Down */;
break;
default:
// Illegal arguments
return null;
}
let unit;
switch (args.by) {
case EditorScroll_.RawUnit.Line:
unit = 1 /* Line */;
break;
case EditorScroll_.RawUnit.WrappedLine:
unit = 2 /* WrappedLine */;
break;
case EditorScroll_.RawUnit.Page:
unit = 3 /* Page */;
break;
case EditorScroll_.RawUnit.HalfPage:
unit = 4 /* HalfPage */;
break;
default:
unit = 2 /* 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_ || (exports.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_.description = {
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_ || (exports.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 = document.activeElement;
if (activeElement && ['input', 'textarea'].indexOf(activeElement.tagName.toLowerCase()) >= 0) {
this.runDOMCommand();
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) {
viewModel.model.pushStackElement();
viewModel.setCursorStates(args.source, 3 /* Explicit */, [
cursorMoveCommands_1.CursorMoveCommands.moveTo(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position, args.viewPosition)
]);
viewModel.revealPrimaryCursor(args.source, 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);
viewModel.setCursorStates(args.source, 3 /* 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) {
// 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);
let fromViewLineNumber = args.doColumnSelect ? prevColumnSelectData.fromViewLineNumber : validatedViewPosition.lineNumber;
let 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 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 15 /* 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 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 17 /* 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 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 16 /* 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 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 11 /* 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 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 18 /* 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 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 12 /* PageDown */,
linux: { primary: 0 }
}
}));
class CursorMoveImpl extends CoreEditorCommand {
constructor() {
super({
id: 'cursorMove',
precondition: undefined,
description: cursorMoveCommands_1.CursorMove.description
});
}
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 /* Explicit */, CursorMoveImpl._move(viewModel, viewModel.getCursorStates(), args));
viewModel.revealPrimaryCursor(source, true);
}
static _move(viewModel, cursors, args) {
const inSelectionMode = args.select;
const value = args.value;
switch (args.direction) {
case 0 /* Left */:
case 1 /* Right */:
case 2 /* Up */:
case 3 /* Down */:
case 4 /* PrevBlankLine */:
case 5 /* NextBlankLine */:
case 6 /* WrappedLineStart */:
case 7 /* WrappedLineFirstNonWhitespaceCharacter */:
case 8 /* WrappedLineColumnCenter */:
case 9 /* WrappedLineEnd */:
case 10 /* WrappedLineLastNonWhitespaceCharacter */:
return cursorMoveCommands_1.CursorMoveCommands.simpleMove(viewModel, cursors, args.direction, inSelectionMode, value, args.unit);
case 11 /* ViewPortTop */:
case 13 /* ViewPortBottom */:
case 12 /* ViewPortCenter */:
case 14 /* 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 /* PAGE_SIZE_MARKER */) {
// -1 is a marker for page size
args = {
direction: this._staticArgs.direction,
unit: this._staticArgs.unit,
select: this._staticArgs.select,
value: viewModel.cursorConfig.pageSize
};
}
viewModel.model.pushStackElement();
viewModel.setCursorStates(dynamicArgs.source, 3 /* Explicit */, cursorMoveCommands_1.CursorMoveCommands.simpleMove(viewModel, viewModel.getCursorStates(), args.direction, args.select, args.value, args.unit));
viewModel.revealPrimaryCursor(dynamicArgs.source, true);
}
}
CoreNavigationCommands.CursorLeft = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
args: {
direction: 0 /* Left */,
unit: 0 /* None */,
select: false,
value: 1
},
id: 'cursorLeft',
precondition: undefined,
kbOpts: {
weight: CORE_WEIGHT,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 15 /* LeftArrow */,
mac: { primary: 15 /* LeftArrow */, secondary: [256 /* WinCtrl */ | 32 /* KEY_B */] }
}
}));
CoreNavigationCommands.CursorLeftSelect = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
args: {
direction: 0 /* Left */,
unit: 0 /* None */,
select: true,
value: 1
},
id: 'cursorLeftSelect',
precondition: undefined,
kbOpts: {
weight: CORE_WEIGHT,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 1024 /* Shift */ | 15 /* LeftArrow */
}
}));
CoreNavigationCommands.CursorRight = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
args: {
direction: 1 /* Right */,
unit: 0 /* None */,
select: false,
value: 1
},
id: 'cursorRight',
precondition: undefined,
kbOpts: {
weight: CORE_WEIGHT,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 17 /* RightArrow */,
mac: { primary: 17 /* RightArrow */, secondary: [256 /* WinCtrl */ | 36 /* KEY_F */] }
}
}));
CoreNavigationCommands.CursorRightSelect = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
args: {
direction: 1 /* Right */,
unit: 0 /* None */,
select: true,
value: 1
},
id: 'cursorRightSelect',
precondition: undefined,
kbOpts: {
weight: CORE_WEIGHT,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 1024 /* Shift */ | 17 /* RightArrow */
}
}));
CoreNavigationCommands.CursorUp = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
args: {
direction: 2 /* Up */,
unit: 2 /* WrappedLine */,
select: false,
value: 1
},
id: 'cursorUp',
precondition: undefined,
kbOpts: {
weight: CORE_WEIGHT,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 16 /* UpArrow */,
mac: { primary: 16 /* UpArrow */, secondary: [256 /* WinCtrl */ | 46 /* KEY_P */] }
}
}));
CoreNavigationCommands.CursorUpSelect = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
args: {
direction: 2 /* Up */,
unit: 2 /* WrappedLine */,
select: true,
value: 1
},
id: 'cursorUpSelect',
precondition: undefined,
kbOpts: {
weight: CORE_WEIGHT,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 1024 /* Shift */ | 16 /* UpArrow */,
secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 16 /* UpArrow */],
mac: { primary: 1024 /* Shift */ | 16 /* UpArrow */ },
linux: { primary: 1024 /* Shift */ | 16 /* UpArrow */ }
}
}));
CoreNavigationCommands.CursorPageUp = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
args: {
direction: 2 /* Up */,
unit: 2 /* WrappedLine */,
select: false,
value: -1 /* PAGE_SIZE_MARKER */
},
id: 'cursorPageUp',
precondition: undefined,
kbOpts: {
weight: CORE_WEIGHT,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 11 /* PageUp */
}
}));
CoreNavigationCommands.CursorPageUpSelect = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
args: {
direction: 2 /* Up */,
unit: 2 /* WrappedLine */,
select: true,
value: -1 /* PAGE_SIZE_MARKER */
},
id: 'cursorPageUpSelect',
precondition: undefined,
kbOpts: {
weight: CORE_WEIGHT,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 1024 /* Shift */ | 11 /* PageUp */
}
}));
CoreNavigationCommands.CursorDown = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
args: {
direction: 3 /* Down */,
unit: 2 /* WrappedLine */,
select: false,
value: 1
},
id: 'cursorDown',
precondition: undefined,
kbOpts: {
weight: CORE_WEIGHT,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 18 /* DownArrow */,
mac: { primary: 18 /* DownArrow */, secondary: [256 /* WinCtrl */ | 44 /* KEY_N */] }
}
}));
CoreNavigationCommands.CursorDownSelect = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
args: {
direction: 3 /* Down */,
unit: 2 /* WrappedLine */,
select: true,
value: 1
},
id: 'cursorDownSelect',
precondition: undefined,
kbOpts: {
weight: CORE_WEIGHT,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 1024 /* Shift */ | 18 /* DownArrow */,
secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 18 /* DownArrow */],
mac: { primary: 1024 /* Shift */ | 18 /* DownArrow */ },
linux: { primary: 1024 /* Shift */ | 18 /* DownArrow */ }
}
}));
CoreNavigationCommands.CursorPageDown = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
args: {
direction: 3 /* Down */,
unit: 2 /* WrappedLine */,
select: false,
value: -1 /* PAGE_SIZE_MARKER */
},
id: 'cursorPageDown',
precondition: undefined,
kbOpts: {
weight: CORE_WEIGHT,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 12 /* PageDown */
}
}));
CoreNavigationCommands.CursorPageDownSelect = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
args: {
direction: 3 /* Down */,
unit: 2 /* WrappedLine */,
select: true,
value: -1 /* PAGE_SIZE_MARKER */
},
id: 'cursorPageDownSelect',
precondition: undefined,
kbOpts: {
weight: CORE_WEIGHT,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 1024 /* Shift */ | 12 /* PageDown */
}
}));
CoreNavigationCommands.CreateCursor = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
constructor() {
super({
id: 'createCursor',
precondition: undefined
});
}
runCoreEditorCommand(viewModel, args) {
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 /* Explicit */, states);
return;
}
}
// => Add the new cursor
states.push(newState);
viewModel.model.pushStackElement();
viewModel.setCursorStates(args.source, 3 /* Explicit */, states);
}
});
CoreNavigationCommands.LastCursorMoveToSelect = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
constructor() {
super({
id: '_lastCursorMoveToSelect',
precondition: undefined
});
}
runCoreEditorCommand(viewModel, args) {
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 /* 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 /* Explicit */, cursorMoveCommands_1.CursorMoveCommands.moveToBeginningOfLine(viewModel, viewModel.getCursorStates(), this._inSelectionMode));
viewModel.revealPrimaryCursor(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 /* Home */,
mac: { primary: 14 /* Home */, secondary: [2048 /* CtrlCmd */ | 15 /* 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 /* Shift */ | 14 /* Home */,
mac: { primary: 1024 /* Shift */ | 14 /* Home */, secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 15 /* LeftArrow */] }
}
}));
class LineStartCommand extends CoreEditorCommand {
constructor(opts) {
super(opts);
this._inSelectionMode = opts.inSelectionMode;
}
runCoreEditorCommand(viewModel, args) {
viewModel.model.pushStackElement();
viewModel.setCursorStates(args.source, 3 /* Explicit */, this._exec(viewModel.getCursorStates()));
viewModel.revealPrimaryCursor(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 /* WinCtrl */ | 31 /* KEY_A */ }
}
}));
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 /* WinCtrl */ | 1024 /* Shift */ | 31 /* KEY_A */ }
}
}));
class EndCommand extends CoreEditorCommand {
constructor(opts) {
super(opts);
this._inSelectionMode = opts.inSelectionMode;
}
runCoreEditorCommand(viewModel, args) {
viewModel.model.pushStackElement();
viewModel.setCursorStates(args.source, 3 /* Explicit */, cursorMoveCommands_1.CursorMoveCommands.moveToEndOfLine(viewModel, viewModel.getCursorStates(), this._inSelectionMode, args.sticky || false));
viewModel.revealPrimaryCursor(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 /* End */,
mac: { primary: 13 /* End */, secondary: [2048 /* CtrlCmd */ | 17 /* RightArrow */] }
},
description: {
description: `Go to End`,
args: [{
name: 'args',
schema: {
type: 'object',
properties: {
'sticky': {
description: nls.localize(0, null),
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 /* Shift */ | 13 /* End */,
mac: { primary: 1024 /* Shift */ | 13 /* End */, secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 17 /* RightArrow */] }
},
description: {
description: `Select to End`,
args: [{
name: 'args',
schema: {
type: 'object',
properties: {
'sticky': {
description: nls.localize(1, null),
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 /* Explicit */, this._exec(viewModel, viewModel.getCursorStates()));
viewModel.revealPrimaryCursor(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 /* WinCtrl */ | 35 /* KEY_E */ }
}
}));
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 /* WinCtrl */ | 1024 /* Shift */ | 35 /* KEY_E */ }
}
}));
class TopCommand extends CoreEditorCommand {
constructor(opts) {
super(opts);
this._inSelectionMode = opts.inSelectionMode;
}
runCoreEditorCommand(viewModel, args) {
viewModel.model.pushStackElement();
viewModel.setCursorStates(args.source, 3 /* Explicit */, cursorMoveCommands_1.CursorMoveCommands.moveToBeginningOfBuffer(viewModel, viewModel.getCursorStates(), this._inSelectionMode));
viewModel.revealPrimaryCursor(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 /* CtrlCmd */ | 14 /* Home */,
mac: { primary: 2048 /* CtrlCmd */ | 16 /* 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 /* CtrlCmd */ | 1024 /* Shift */ | 14 /* Home */,
mac: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 16 /* UpArrow */ }
}
}));
class BottomCommand extends CoreEditorCommand {
constructor(opts) {
super(opts);
this._inSelectionMode = opts.inSelectionMode;
}
runCoreEditorCommand(viewModel, args) {
viewModel.model.pushStackElement();
viewModel.setCursorStates(args.source, 3 /* Explicit */, cursorMoveCommands_1.CursorMoveCommands.moveToEndOfBuffer(viewModel, viewModel.getCursorStates(), this._inSelectionMode));
viewModel.revealPrimaryCursor(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 /* CtrlCmd */ | 13 /* End */,
mac: { primary: 2048 /* CtrlCmd */ | 18 /* 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 /* CtrlCmd */ | 1024 /* Shift */ | 13 /* End */,
mac: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 18 /* DownArrow */ }
}
}));
class EditorScrollImpl extends CoreEditorCommand {
constructor() {
super({
id: 'editorScroll',
precondition: undefined,
description: EditorScroll_.description
});
}
runCoreEditorCommand(viewModel, args) {
const parsed = EditorScroll_.parse(args);
if (!parsed) {
// illegal arguments
return;
}
this._runEditorScroll(viewModel, args.source, parsed);
}
_runEditorScroll(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 /* Explicit */, [
cursorMoveCommands_1.CursorMoveCommands.findPositionInViewportIfOutside(viewModel, viewModel.getPrimaryCursorState(), desiredVisibleViewRange, args.select)
]);
}
viewModel.setScrollTop(desiredScrollTop, 0 /* Smooth */);
}
_computeDesiredScrollTop(viewModel, args) {
if (args.unit === 1 /* Line */) {
// scrolling by model lines
const visibleViewRange = viewModel.getCompletelyVisibleViewRange();
const visibleModelRange = viewModel.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
let desiredTopModelLineNumber;
if (args.direction === 1 /* 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.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
}
let noOfLines;
if (args.unit === 3 /* Page */) {
noOfLines = viewModel.cursorConfig.pageSize * args.value;
}
else if (args.unit === 4 /* HalfPage */) {
noOfLines = Math.round(viewModel.cursorConfig.pageSize / 2) * args.value;
}
else {
noOfLines = args.value;
}
const deltaLines = (args.direction === 1 /* Up */ ? -1 : 1) * noOfLines;
return viewModel.getScrollTop() + deltaLines * viewModel.cursorConfig.lineHeight;
}
}
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 /* CtrlCmd */ | 16 /* UpArrow */,
mac: { primary: 256 /* WinCtrl */ | 11 /* PageUp */ }
}
});
}
runCoreEditorCommand(viewModel, args) {
CoreNavigationCommands.EditorScroll._runEditorScroll(viewModel, args.source, {
direction: 1 /* Up */,
unit: 2 /* WrappedLine */,
value: 1,
revealCursor: false,
select: false
});
}
});
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 /* CtrlCmd */ | 11 /* PageUp */,
win: { primary: 512 /* Alt */ | 11 /* PageUp */ },
linux: { primary: 512 /* Alt */ | 11 /* PageUp */ }
}
});
}
runCoreEditorCommand(viewModel, args) {
CoreNavigationCommands.EditorScroll._runEditorScroll(viewModel, args.source, {
direction: 1 /* Up */,
unit: 3 /* Page */,
value: 1,
revealCursor: false,
select: false
});
}
});
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 /* CtrlCmd */ | 18 /* DownArrow */,
mac: { primary: 256 /* WinCtrl */ | 12 /* PageDown */ }
}
});
}
runCoreEditorCommand(viewModel, args) {
CoreNavigationCommands.EditorScroll._runEditorScroll(viewModel, args.source, {
direction: 2 /* Down */,
unit: 2 /* WrappedLine */,
value: 1,
revealCursor: false,
select: false
});
}
});
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 /* CtrlCmd */ | 12 /* PageDown */,
win: { primary: 512 /* Alt */ | 12 /* PageDown */ },
linux: { primary: 512 /* Alt */ | 12 /* PageDown */ }
}
});
}
runCoreEditorCommand(viewModel, args) {
CoreNavigationCommands.EditorScroll._runEditorScroll(viewModel, args.source, {
direction: 2 /* Down */,
unit: 3 /* Page */,
value: 1,
revealCursor: false,
select: false
});
}
});
class WordCommand extends CoreEditorCommand {
constructor(opts) {
super(opts);
this._inSelectionMode = opts.inSelectionMode;
}
runCoreEditorCommand(viewModel, args) {
viewModel.model.pushStackElement();
viewModel.setCursorStates(args.source, 3 /* Explicit */, [
cursorMoveCommands_1.CursorMoveCommands.word(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position)
]);
viewModel.revealPrimaryCursor(args.source, 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) {
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 /* Explicit */, newStates);
}
});
class LineCommand extends CoreEditorCommand {
constructor(opts) {
super(opts);
this._inSelectionMode = opts.inSelectionMode;
}
runCoreEditorCommand(viewModel, args) {
viewModel.model.pushStackElement();
viewModel.setCursorStates(args.source, 3 /* Explicit */, [
cursorMoveCommands_1.CursorMoveCommands.line(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position, args.viewPosition)
]);
viewModel.revealPrimaryCursor(args.source, false);
}
}
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) {
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 /* 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.ExpandLineSelection = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
constructor() {
super({
id: 'expandLineSelection',
precondition: undefined,
kbOpts: {
weight: CORE_WEIGHT,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 2048 /* CtrlCmd */ | 42 /* KEY_L */
}
});
}
runCoreEditorCommand(viewModel, args) {
viewModel.model.pushStackElement();
viewModel.setCursorStates(args.source, 3 /* Explicit */, cursorMoveCommands_1.CursorMoveCommands.expandLineSelection(viewModel, viewModel.getCursorStates()));
viewModel.revealPrimaryCursor(args.source, true);
}
});
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 /* Escape */,
secondary: [1024 /* Shift */ | 9 /* Escape */]
}
});
}
runCoreEditorCommand(viewModel, args) {
viewModel.model.pushStackElement();
viewModel.setCursorStates(args.source, 3 /* Explicit */, [
cursorMoveCommands_1.CursorMoveCommands.cancelSelection(viewModel, viewModel.getPrimaryCursorState())
]);
viewModel.revealPrimaryCursor(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 /* Escape */,
secondary: [1024 /* Shift */ | 9 /* Escape */]
}
});
}
runCoreEditorCommand(viewModel, args) {
viewModel.model.pushStackElement();
viewModel.setCursorStates(args.source, 3 /* Explicit */, [
viewModel.getPrimaryCursorState()
]);
viewModel.revealPrimaryCursor(args.source, true);
(0, aria_1.status)(nls.localize(2, null));
}
});
CoreNavigationCommands.RevealLine = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
constructor() {
super({
id: 'revealLine',
precondition: undefined,
description: RevealLine_.description
});
}
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 /* Simple */;
if (revealLineArg.at) {
switch (revealLineArg.at) {
case RevealLine_.RawAtArgument.Top:
revealAt = 3 /* Top */;
break;
case RevealLine_.RawAtArgument.Center:
revealAt = 1 /* Center */;
break;
case RevealLine_.RawAtArgument.Bottom:
revealAt = 4 /* Bottom */;
break;
default:
break;
}
}
const viewRange = viewModel.coordinatesConverter.convertModelRangeToViewRange(range);
viewModel.revealRange(args.source, false, viewRange, revealAt, 0 /* Smooth */);
}
});
CoreNavigationCommands.SelectAll = new class extends EditorOrNativeTextInputCommand {
constructor() {
super(editorExtensions_1.SelectAllCommand);
}
runDOMCommand() {
if (browser_1.isFirefox) {
document.activeElement.focus();
document.activeElement.select();
}
document.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 /* 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) {
viewModel.model.pushStackElement();
viewModel.setCursorStates(args.source, 3 /* Explicit */, [
cursorCommon_1.CursorState.fromModelSelection(args.selection)
]);
}
});
})(CoreNavigationCommands = exports.CoreNavigationCommands || (exports.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 /* Shift */ | 15 /* LeftArrow */);
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectRight.id, 1024 /* Shift */ | 17 /* RightArrow */);
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectUp.id, 1024 /* Shift */ | 16 /* UpArrow */);
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectPageUp.id, 1024 /* Shift */ | 11 /* PageUp */);
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectDown.id, 1024 /* Shift */ | 18 /* DownArrow */);
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectPageDown.id, 1024 /* Shift */ | 12 /* 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 /* WinCtrl */ | 45 /* KEY_O */ }
}
});
}
runCoreEditingCommand(editor, viewModel, args) {
editor.pushUndoStop();
editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.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 /* Shift */ | 2 /* 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 /* 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 /* Backspace */,
secondary: [1024 /* Shift */ | 1 /* Backspace */],
mac: { primary: 1 /* Backspace */, secondary: [1024 /* Shift */ | 1 /* Backspace */, 256 /* WinCtrl */ | 38 /* KEY_H */, 256 /* WinCtrl */ | 1 /* 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 /* 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 /* Delete */,
mac: { primary: 20 /* Delete */, secondary: [256 /* WinCtrl */ | 34 /* KEY_D */, 256 /* WinCtrl */ | 20 /* 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 /* DeletingRight */);
}
});
CoreEditingCommands.Undo = new class extends EditorOrNativeTextInputCommand {
constructor() {
super(editorExtensions_1.UndoCommand);
}
runDOMCommand() {
document.execCommand('undo');
}
runEditorCommand(accessor, editor, args) {
if (!editor.hasModel() || editor.getOption(79 /* readOnly */) === true) {
return;
}
return editor.getModel().undo();
}
}();
CoreEditingCommands.Redo = new class extends EditorOrNativeTextInputCommand {
constructor() {
super(editorExtensions_1.RedoCommand);
}
runDOMCommand() {
document.execCommand('redo');
}
runEditorCommand(accessor, editor, args) {
if (!editor.hasModel() || editor.getOption(79 /* readOnly */) === true) {
return;
}
return editor.getModel().redo();
}
}();
})(CoreEditingCommands = exports.CoreEditingCommands || (exports.CoreEditingCommands = {}));
/**
* A command that will invoke a command on the focused editor.
*/
class EditorHandlerCommand extends editorExtensions_1.Command {
constructor(id, handlerId, description) {
super({
id: id,
precondition: undefined,
description: description
});
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, description) {
registerCommand(new EditorHandlerCommand('default:' + handlerId, handlerId));
registerCommand(new EditorHandlerCommand(handlerId, handlerId, description));
}
registerOverwritableCommand("type" /* Type */, {
description: `Type`,
args: [{
name: 'args',
schema: {
'type': 'object',
'required': ['text'],
'properties': {
'text': {
'type': 'string'
}
},
}
}]
});
registerOverwritableCommand("replacePreviousChar" /* ReplacePreviousChar */);
registerOverwritableCommand("compositionType" /* CompositionType */);
registerOverwritableCommand("compositionStart" /* CompositionStart */);
registerOverwritableCommand("compositionEnd" /* CompositionEnd */);
registerOverwritableCommand("paste" /* Paste */);
registerOverwritableCommand("cut" /* 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[621/*vs/editor/browser/core/keybindingCancellation*/], __M([0/*require*/,1/*exports*/,14/*vs/editor/browser/editorExtensions*/,16/*vs/platform/contextkey/common/contextkey*/,23/*vs/base/common/cancellation*/,72/*vs/base/common/linkedList*/,9/*vs/platform/instantiation/common/instantiation*/,75/*vs/platform/instantiation/common/extensions*/,456/*vs/nls!vs/editor/browser/core/keybindingCancellation*/]), 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)(0, null));
(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());
}
}
}, true);
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 /* EditorContrib */,
primary: 9 /* 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[66/*vs/editor/browser/core/editorState*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/,23/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,621/*vs/editor/browser/core/keybindingCancellation*/]), function (require, exports, strings, range_1, cancellation_1, lifecycle_1, keybindingCancellation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StableEditorScrollState = exports.TextModelCancellationTokenSource = exports.EditorStateCancellationTokenSource = exports.EditorState = void 0;
class EditorState {
constructor(editor, flags) {
this.flags = flags;
if ((this.flags & 1 /* 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 /* Position */) !== 0) {
this.position = editor.getPosition();
}
else {
this.position = null;
}
if ((this.flags & 2 /* Selection */) !== 0) {
this.selection = editor.getSelection();
}
else {
this.selection = null;
}
if ((this.flags & 8 /* 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 /* Position */) {
this._listener.add(editor.onDidChangeCursorPosition(e => {
if (!range || !range_1.Range.containsPosition(range, e.position)) {
this.cancel();
}
}));
}
if (flags & 2 /* Selection */) {
this._listener.add(editor.onDidChangeCursorSelection(e => {
if (!range || !range_1.Range.containsRange(range, e.selection)) {
this.cancel();
}
}));
}
if (flags & 8 /* Scroll */) {
this._listener.add(editor.onDidScrollChange(_ => this.cancel()));
}
if (flags & 1 /* 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;
class StableEditorScrollState {
constructor(_visiblePosition, _visiblePositionScrollDelta, _cursorPosition) {
this._visiblePosition = _visiblePosition;
this._visiblePositionScrollDelta = _visiblePositionScrollDelta;
this._cursorPosition = _cursorPosition;
}
static capture(editor) {
let visiblePosition = null;
let visiblePositionScrollDelta = 0;
if (editor.getScrollTop() !== 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(visiblePosition, visiblePositionScrollDelta, editor.getPosition());
}
restore(editor) {
if (this._visiblePosition) {
const visiblePositionScrollTop = editor.getTopForPosition(this._visiblePosition.lineNumber, this._visiblePosition.column);
editor.setScrollTop(visiblePositionScrollTop + this._visiblePositionScrollDelta);
}
}
restoreRelativeVerticalPositionOfCursor(editor) {
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);
}
}
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[622/*vs/editor/browser/services/markerDecorations*/], __M([0/*require*/,1/*exports*/,183/*vs/editor/common/services/markersDecorationService*/,14/*vs/editor/browser/editorExtensions*/]), function (require, exports, markersDecorationService_1, editorExtensions_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MarkerDecorationsContribution = void 0;
let MarkerDecorationsContribution = class MarkerDecorationsContribution {
constructor(_editor, _markerDecorationsService) {
// Doesn't do anything, just requires `IMarkerDecorationsService` to make sure it gets instantiated
}
dispose() {
}
};
MarkerDecorationsContribution.ID = 'editor.contrib.markerDecorations';
MarkerDecorationsContribution = __decorate([
__param(1, markersDecorationService_1.IMarkerDecorationsService)
], MarkerDecorationsContribution);
exports.MarkerDecorationsContribution = MarkerDecorationsContribution;
(0, editorExtensions_1.registerEditorContribution)(MarkerDecorationsContribution.ID, MarkerDecorationsContribution);
});
/*---------------------------------------------------------------------------------------------
* 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/browser/view/viewController*/], __M([0/*require*/,1/*exports*/,148/*vs/editor/browser/controller/coreCommands*/,13/*vs/editor/common/core/position*/,17/*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(68 /* 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(68 /* 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(95 /* selectionClipboard */));
const columnSelection = options.get(16 /* 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);
}
else {
this._createCursor(data.position, true);
}
}
else {
if (data.inSelectionMode) {
this._lineSelectDrag(data.position);
}
else {
this._lineSelect(data.position);
}
}
}
else if (data.mouseDownCount >= 4) {
this._selectAll();
}
else if (data.mouseDownCount === 3) {
if (this._hasMulticursorModifier(data)) {
if (data.inSelectionMode) {
this._lastCursorLineSelectDrag(data.position);
}
else {
this._lastCursorLineSelect(data.position);
}
}
else {
if (data.inSelectionMode) {
this._lineSelectDrag(data.position);
}
else {
this._lineSelect(data.position);
}
}
}
else if (data.mouseDownCount === 2) {
if (this._hasMulticursorModifier(data)) {
this._lastCursorWordSelect(data.position);
}
else {
if (data.inSelectionMode) {
this._wordSelectDrag(data.position);
}
else {
this._wordSelect(data.position);
}
}
}
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);
}
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);
}
}
}
else {
this.moveTo(data.position);
}
}
}
}
_usualArgs(viewPosition) {
viewPosition = this._validateViewColumn(viewPosition);
return {
source: 'mouse',
position: this._convertViewToModelPosition(viewPosition),
viewPosition: viewPosition
};
}
moveTo(viewPosition) {
coreCommands_1.CoreNavigationCommands.MoveTo.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
}
_moveToSelect(viewPosition) {
coreCommands_1.CoreNavigationCommands.MoveToSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
}
_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) {
coreCommands_1.CoreNavigationCommands.LastCursorMoveToSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
}
_wordSelect(viewPosition) {
coreCommands_1.CoreNavigationCommands.WordSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
}
_wordSelectDrag(viewPosition) {
coreCommands_1.CoreNavigationCommands.WordSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
}
_lastCursorWordSelect(viewPosition) {
coreCommands_1.CoreNavigationCommands.LastCursorWordSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
}
_lineSelect(viewPosition) {
coreCommands_1.CoreNavigationCommands.LineSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
}
_lineSelectDrag(viewPosition) {
coreCommands_1.CoreNavigationCommands.LineSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
}
_lastCursorLineSelect(viewPosition) {
coreCommands_1.CoreNavigationCommands.LastCursorLineSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
}
_lastCursorLineSelectDrag(viewPosition) {
coreCommands_1.CoreNavigationCommands.LastCursorLineSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
}
_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[624/*vs/editor/browser/view/viewImpl*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,39/*vs/base/browser/browser*/,21/*vs/editor/common/core/selection*/,30/*vs/base/browser/fastDomNode*/,12/*vs/base/common/errors*/,595/*vs/editor/browser/controller/pointerHandler*/,604/*vs/editor/browser/controller/textAreaHandler*/,623/*vs/editor/browser/view/viewController*/,259/*vs/editor/browser/view/viewUserInputEvents*/,578/*vs/editor/browser/view/viewOverlays*/,47/*vs/editor/browser/view/viewPart*/,398/*vs/editor/browser/viewParts/contentWidgets/contentWidgets*/,602/*vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/,399/*vs/editor/browser/viewParts/decorations/decorations*/,598/*vs/editor/browser/viewParts/editorScrollbar/editorScrollbar*/,176/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/,603/*vs/editor/browser/viewParts/indentGuides/indentGuides*/,260/*vs/editor/browser/viewParts/lineNumbers/lineNumbers*/,596/*vs/editor/browser/viewParts/lines/viewLines*/,400/*vs/editor/browser/viewParts/linesDecorations/linesDecorations*/,225/*vs/editor/browser/viewParts/margin/margin*/,401/*vs/editor/browser/viewParts/marginDecorations/marginDecorations*/,599/*vs/editor/browser/viewParts/minimap/minimap*/,402/*vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/,605/*vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler*/,403/*vs/editor/browser/viewParts/overviewRuler/overviewRuler*/,606/*vs/editor/browser/viewParts/rulers/rulers*/,600/*vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/,601/*vs/editor/browser/viewParts/selections/selections*/,607/*vs/editor/browser/viewParts/viewCursors/viewCursors*/,404/*vs/editor/browser/viewParts/viewZones/viewZones*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,113/*vs/editor/common/view/renderingContext*/,393/*vs/editor/common/view/viewContext*/,395/*vs/editor/common/viewLayout/viewLinesViewportData*/,115/*vs/editor/common/viewModel/viewEventHandler*/,11/*vs/platform/theme/common/themeService*/,191/*vs/editor/browser/controller/mouseTarget*/]), function (require, exports, dom, browser, selection_1, fastDomNode_1, errors_1, pointerHandler_1, textAreaHandler_1, viewController_1, viewUserInputEvents_1, viewOverlays_1, viewPart_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, position_1, range_1, renderingContext_1, viewContext_1, viewLinesViewportData_1, viewEventHandler_1, themeService_1, mouseTarget_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.View = void 0;
class View extends viewEventHandler_1.ViewEventHandler {
constructor(commandDelegate, configuration, themeService, model, userInputEvents, overflowWidgetsDomNode) {
super();
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, themeService.getColorTheme(), model);
this._configPixelRatio = this._context.configuration.options.get(127 /* pixelRatio */);
// Ensure the view is the first event handler in order to update the layout
this._context.addEventHandler(this);
this._register(themeService.onDidColorThemeChange(theme => {
this._context.theme.update(theme);
this._context.model.onDidColorThemeChange();
this.render(true, false);
}));
this._viewParts = [];
// Keyboard handler
this._textAreaHandler = new 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 /* 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));
const marginViewOverlays = new viewOverlays_1.MarginViewOverlays(this._context);
this._viewParts.push(marginViewOverlays);
marginViewOverlays.addDynamicOverlay(new currentLineHighlight_1.CurrentLineMarginHighlightOverlay(this._context));
marginViewOverlays.addDynamicOverlay(new glyphMargin_1.GlyphMarginOverlay(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));
const margin = new margin_1.Margin(this._context);
margin.getDomNode().appendChild(this._viewZones.marginDomNode);
margin.getDomNode().appendChild(marginViewOverlays.getDomNode());
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._viewParts.push(this._overlayWidgets);
const rulers = new rulers_1.Rulers(this._context);
this._viewParts.push(rulers);
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.domNode.appendChild(this._overflowGuardContainer);
if (overflowWidgetsDomNode) {
overflowWidgetsDomNode.appendChild(this._contentWidgets.overflowingContentWidgetsDomNode.domNode);
}
else {
this.domNode.appendChild(this._contentWidgets.overflowingContentWidgetsDomNode);
}
this._applyLayout();
// Pointer handler
this._pointerHandler = this._register(new pointerHandler_1.PointerHandler(this._context, viewController, this._createPointerHandlerHelper()));
}
_flushAccumulatedAndRenderNow() {
this._renderNow();
}
_createPointerHandlerHelper() {
return {
viewDomNode: this.domNode.domNode,
linesContentDomNode: this._linesContent.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);
},
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 {
visibleRangeForPositionRelativeToEditor: (lineNumber, column) => {
this._flushAccumulatedAndRenderNow();
return this._viewLines.visibleRangeForPosition(new position_1.Position(lineNumber, column));
}
};
}
_applyLayout() {
const options = this._context.configuration.options;
const layoutInfo = options.get(129 /* layoutInfo */);
this.domNode.setWidth(layoutInfo.width);
this.domNode.setHeight(layoutInfo.height);
this._overflowGuardContainer.setWidth(layoutInfo.width);
this._overflowGuardContainer.setHeight(layoutInfo.height);
this._linesContent.setWidth(1000000);
this._linesContent.setHeight(1000000);
}
_getEditorClassName() {
const focused = this._textAreaHandler.isFocused() ? ' focused' : '';
return this._context.configuration.options.get(126 /* editorClassName */) + ' ' + (0, themeService_1.getThemeTypeSelector)(this._context.theme.type) + focused;
}
// --- begin event handlers
handleEvents(events) {
super.handleEvents(events);
this._scheduleRender();
}
onConfigurationChanged(e) {
this._configPixelRatio = this._context.configuration.options.get(127 /* pixelRatio */);
this.domNode.setClassName(this._getEditorClassName());
this._applyLayout();
return false;
}
onCursorStateChanged(e) {
this._selections = e.selections;
return false;
}
onFocusChanged(e) {
this.domNode.setClassName(this._getEditorClassName());
return false;
}
onThemeChanged(e) {
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._renderAnimationFrame === null) {
this._renderAnimationFrame = dom.runAtThisOrScheduleAtNextAnimationFrame(this._onRenderScheduled.bind(this), 100);
}
}
_onRenderScheduled() {
this._renderAnimationFrame = null;
this._flushAccumulatedAndRenderNow();
}
_renderNow() {
safeInvokeNoArg(() => this._actualRender());
}
_getViewPartsToRender() {
let result = [], resultLen = 0;
for (const viewPart of this._viewParts) {
if (viewPart.shouldRender()) {
result[resultLen++] = viewPart;
}
}
return result;
}
_actualRender() {
if (!dom.isInDOM(this.domNode.domNode)) {
return;
}
let viewPartsToRender = this._getViewPartsToRender();
if (!this._viewLines.shouldRender() && viewPartsToRender.length === 0) {
// Nothing to render
return;
}
const partialViewportData = this._context.viewLayout.getLinesViewportData();
this._context.model.setViewport(partialViewportData.startLineNumber, partialViewportData.endLineNumber, partialViewportData.centeredLineNumber);
const viewportData = new viewLinesViewportData_1.ViewportData(this._selections, partialViewportData, this._context.viewLayout.getWhitespaceViewportData(), this._context.model);
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();
}
const renderingContext = new renderingContext_1.RenderingContext(this._context.viewLayout, viewportData, this._viewLines);
// Render the rest of the parts
for (const viewPart of viewPartsToRender) {
viewPart.prepareRender(renderingContext);
}
for (const viewPart of viewPartsToRender) {
viewPart.render(renderingContext);
viewPart.onDidRender();
}
// Try to detect browser zooming and paint again if necessary
if (Math.abs(browser.getPixelRatio() - this._configPixelRatio) > 0.001) {
// looks like the pixel ratio has changed
this._context.configuration.updatePixelRatio();
}
}
// --- BEGIN CodeEditor helpers
delegateVerticalScrollbarMouseDown(browserEvent) {
this._scrollbar.delegateVerticalScrollbarMouseDown(browserEvent);
}
restoreState(scrollPosition) {
this._context.model.setScrollPosition({ scrollTop: scrollPosition.scrollTop }, 1 /* Immediate */);
this._context.model.tokenizeViewport();
this._renderNow();
this._viewLines.updateLineWidths();
this._context.model.setScrollPosition({ scrollLeft: scrollPosition.scrollLeft }, 1 /* Immediate */);
}
getOffsetForColumn(modelLineNumber, modelColumn) {
const modelPosition = this._context.model.validateModelPosition({
lineNumber: modelLineNumber,
column: modelColumn
});
const viewPosition = this._context.model.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.model.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();
}
}
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) {
let newRange = widgetData.position ? widgetData.position.range || null : null;
if (newRange === null) {
const newPosition = widgetData.position ? widgetData.position.position : null;
if (newPosition !== null) {
newRange = new range_1.Range(newPosition.lineNumber, newPosition.column, newPosition.lineNumber, newPosition.column);
}
}
const newPreference = widgetData.position ? widgetData.position.preference : null;
this._contentWidgets.setWidgetPosition(widgetData.widget, newRange, newPreference);
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 newPreference = widgetData.position ? widgetData.position.preference : null;
const shouldRender = this._overlayWidgets.setWidgetPosition(widgetData.widget, newPreference);
if (shouldRender) {
this._scheduleRender();
}
}
removeOverlayWidget(widgetData) {
this._overlayWidgets.removeWidget(widgetData.widget);
this._scheduleRender();
}
}
exports.View = View;
function safeInvokeNoArg(func) {
try {
return func();
}
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[149/*vs/editor/browser/widget/codeEditorWidget*/], __M([0/*require*/,1/*exports*/,458/*vs/nls!vs/editor/browser/widget/codeEditorWidget*/,7/*vs/base/browser/dom*/,12/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,46/*vs/base/common/network*/,65/*vs/editor/browser/config/configuration*/,14/*vs/editor/browser/editorExtensions*/,28/*vs/editor/browser/services/codeEditorService*/,624/*vs/editor/browser/view/viewImpl*/,259/*vs/editor/browser/view/viewUserInputEvents*/,35/*vs/editor/common/config/editorOptions*/,245/*vs/editor/common/controller/cursor*/,40/*vs/editor/common/controller/cursorCommon*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,219/*vs/editor/common/editorAction*/,110/*vs/editor/common/editorCommon*/,25/*vs/editor/common/editorContextKeys*/,18/*vs/editor/common/modes*/,48/*vs/editor/common/view/editorColorRegistry*/,22/*vs/platform/theme/common/colorRegistry*/,554/*vs/editor/common/viewModel/viewModelImpl*/,26/*vs/platform/commands/common/commands*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/,143/*vs/platform/instantiation/common/serviceCollection*/,34/*vs/platform/notification/common/notification*/,11/*vs/platform/theme/common/themeService*/,64/*vs/platform/accessibility/common/accessibility*/,20/*vs/base/common/types*/,405/*vs/editor/common/viewModel/monospaceLineBreaksComputer*/,577/*vs/editor/browser/view/domLineBreaksComputer*/,141/*vs/editor/common/controller/cursorWordOperations*/,622/*vs/editor/browser/services/markerDecorations*/,342/*vs/css!vs/editor/browser/widget/media/editor*/]), function (require, exports, nls, dom, errors_1, event_1, lifecycle_1, network_1, configuration_1, editorExtensions_1, codeEditorService_1, viewImpl_1, viewUserInputEvents_1, editorOptions_1, cursor_1, cursorCommon_1, position_1, range_1, selection_1, editorAction_1, editorCommon, editorContextKeys_1, modes, editorColorRegistry_1, colorRegistry_1, viewModelImpl_1, commands_1, contextkey_1, instantiation_1, serviceCollection_1, notification_1, themeService_1, accessibility_1, types_1, monospaceLineBreaksComputer_1, domLineBreaksComputer_1, cursorWordOperations_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EditorModeContext = exports.BooleanEventEmitter = exports.CodeEditorWidget = void 0;
let EDITOR_ID = 0;
class ModelData {
constructor(model, viewModel, view, hasRealView, listenersToRemove) {
this.model = model;
this.viewModel = viewModel;
this.view = view;
this.hasRealView = hasRealView;
this.listenersToRemove = listenersToRemove;
}
dispose() {
(0, lifecycle_1.dispose)(this.listenersToRemove);
this.model.onBeforeDetached();
if (this.hasRealView) {
this.view.dispose();
}
this.viewModel.dispose();
}
}
let CodeEditorWidget = class CodeEditorWidget extends lifecycle_1.Disposable {
constructor(domElement, _options, codeEditorWidgetOptions, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService) {
super();
//#region Eventing
this._onDidDispose = this._register(new event_1.Emitter());
this.onDidDispose = this._onDidDispose.event;
this._onDidChangeModelContent = this._register(new event_1.Emitter());
this.onDidChangeModelContent = this._onDidChangeModelContent.event;
this._onDidChangeModelLanguage = this._register(new event_1.Emitter());
this.onDidChangeModelLanguage = this._onDidChangeModelLanguage.event;
this._onDidChangeModelLanguageConfiguration = this._register(new event_1.Emitter());
this.onDidChangeModelLanguageConfiguration = this._onDidChangeModelLanguageConfiguration.event;
this._onDidChangeModelOptions = this._register(new event_1.Emitter());
this.onDidChangeModelOptions = this._onDidChangeModelOptions.event;
this._onDidChangeModelDecorations = this._register(new event_1.Emitter());
this.onDidChangeModelDecorations = this._onDidChangeModelDecorations.event;
this._onDidChangeConfiguration = this._register(new event_1.Emitter());
this.onDidChangeConfiguration = this._onDidChangeConfiguration.event;
this._onDidChangeModel = this._register(new event_1.Emitter());
this.onDidChangeModel = this._onDidChangeModel.event;
this._onDidChangeCursorPosition = this._register(new event_1.Emitter());
this.onDidChangeCursorPosition = this._onDidChangeCursorPosition.event;
this._onDidChangeCursorSelection = this._register(new event_1.Emitter());
this.onDidChangeCursorSelection = this._onDidChangeCursorSelection.event;
this._onDidAttemptReadOnlyEdit = this._register(new event_1.Emitter());
this.onDidAttemptReadOnlyEdit = this._onDidAttemptReadOnlyEdit.event;
this._onDidLayoutChange = this._register(new event_1.Emitter());
this.onDidLayoutChange = this._onDidLayoutChange.event;
this._editorTextFocus = this._register(new BooleanEventEmitter());
this.onDidFocusEditorText = this._editorTextFocus.onDidChangeToTrue;
this.onDidBlurEditorText = this._editorTextFocus.onDidChangeToFalse;
this._editorWidgetFocus = this._register(new BooleanEventEmitter());
this.onDidFocusEditorWidget = this._editorWidgetFocus.onDidChangeToTrue;
this.onDidBlurEditorWidget = this._editorWidgetFocus.onDidChangeToFalse;
this._onWillType = this._register(new event_1.Emitter());
this.onWillType = this._onWillType.event;
this._onDidType = this._register(new event_1.Emitter());
this.onDidType = this._onDidType.event;
this._onDidCompositionStart = this._register(new event_1.Emitter());
this.onDidCompositionStart = this._onDidCompositionStart.event;
this._onDidCompositionEnd = this._register(new event_1.Emitter());
this.onDidCompositionEnd = this._onDidCompositionEnd.event;
this._onDidPaste = this._register(new event_1.Emitter());
this.onDidPaste = this._onDidPaste.event;
this._onMouseUp = this._register(new event_1.Emitter());
this.onMouseUp = this._onMouseUp.event;
this._onMouseDown = this._register(new event_1.Emitter());
this.onMouseDown = this._onMouseDown.event;
this._onMouseDrag = this._register(new event_1.Emitter());
this.onMouseDrag = this._onMouseDrag.event;
this._onMouseDrop = this._register(new event_1.Emitter());
this.onMouseDrop = this._onMouseDrop.event;
this._onMouseDropCanceled = this._register(new event_1.Emitter());
this.onMouseDropCanceled = this._onMouseDropCanceled.event;
this._onContextMenu = this._register(new event_1.Emitter());
this.onContextMenu = this._onContextMenu.event;
this._onMouseMove = this._register(new event_1.Emitter());
this.onMouseMove = this._onMouseMove.event;
this._onMouseLeave = this._register(new event_1.Emitter());
this.onMouseLeave = this._onMouseLeave.event;
this._onMouseWheel = this._register(new event_1.Emitter());
this.onMouseWheel = this._onMouseWheel.event;
this._onKeyUp = this._register(new event_1.Emitter());
this.onKeyUp = this._onKeyUp.event;
this._onKeyDown = this._register(new event_1.Emitter());
this.onKeyDown = this._onKeyDown.event;
this._onDidContentSizeChange = this._register(new event_1.Emitter());
this.onDidContentSizeChange = this._onDidContentSizeChange.event;
this._onDidScrollChange = this._register(new event_1.Emitter());
this.onDidScrollChange = this._onDidScrollChange.event;
this._onDidChangeViewZones = this._register(new event_1.Emitter());
this.onDidChangeViewZones = this._onDidChangeViewZones.event;
const options = Object.assign({}, _options);
this._domElement = domElement;
this._overflowWidgetsDomNode = options.overflowWidgetsDomNode;
delete options.overflowWidgetsDomNode;
this._id = (++EDITOR_ID);
this._decorationTypeKeysToIds = {};
this._decorationTypeSubtypes = {};
this.isSimpleWidget = codeEditorWidgetOptions.isSimpleWidget || false;
this._telemetryData = codeEditorWidgetOptions.telemetryData;
this._configuration = this._register(this._createConfiguration(options, accessibilityService));
this._register(this._configuration.onDidChange((e) => {
this._onDidChangeConfiguration.fire(e);
const options = this._configuration.options;
if (e.hasChanged(129 /* layoutInfo */)) {
const layoutInfo = options.get(129 /* 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));
this._instantiationService = instantiationService.createChild(new serviceCollection_1.ServiceCollection([contextkey_1.IContextKeyService, this._contextKeyService]));
this._modelData = null;
this._contributions = {};
this._actions = {};
this._focusTracker = new CodeEditorWidgetFocusTracker(domElement);
this._register(this._focusTracker.onChange(() => {
this._editorWidgetFocus.setValue(this._focusTracker.hasFocus());
}));
this._contentWidgets = {};
this._overlayWidgets = {};
let contributions;
if (Array.isArray(codeEditorWidgetOptions.contributions)) {
contributions = codeEditorWidgetOptions.contributions;
}
else {
contributions = editorExtensions_1.EditorExtensionsRegistry.getEditorContributions();
}
for (const desc of contributions) {
if (this._contributions[desc.id]) {
(0, errors_1.onUnexpectedError)(new Error(`Cannot have two contributions with the same id ${desc.id}`));
continue;
}
try {
const contribution = this._instantiationService.createInstance(desc.ctor, this);
this._contributions[desc.id] = contribution;
}
catch (err) {
(0, errors_1.onUnexpectedError)(err);
}
}
editorExtensions_1.EditorExtensionsRegistry.getEditorActions().forEach((action) => {
if (this._actions[action.id]) {
(0, errors_1.onUnexpectedError)(new Error(`Cannot have two actions with the same id ${action.id}`));
return;
}
const internalAction = new editorAction_1.InternalEditorAction(action.id, action.label, action.alias, (0, types_1.withNullAsUndefined)(action.precondition), () => {
return this._instantiationService.invokeFunction((accessor) => {
return Promise.resolve(action.runEditorCommand(accessor, this, null));
});
}, this._contextKeyService);
this._actions[internalAction.id] = internalAction;
});
this._codeEditorService.addCodeEditor(this);
}
_createConfiguration(options, accessibilityService) {
return new configuration_1.Configuration(this.isSimpleWidget, options, this._domElement, accessibilityService);
}
getId() {
return this.getEditorType() + ':' + this._id;
}
getEditorType() {
return editorCommon.EditorType.ICodeEditor;
}
dispose() {
this._codeEditorService.removeCodeEditor(this);
this._focusTracker.dispose();
const keys = Object.keys(this._contributions);
for (let i = 0, len = keys.length; i < len; i++) {
const contributionId = keys[i];
this._contributions[contributionId].dispose();
}
this._contributions = {};
this._actions = {};
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(115 /* wordSeparators */), position);
}
getValue(options = null) {
if (!this._modelData) {
return '';
}
const preserveBOM = (options && options.preserveBOM) ? true : false;
let eolPreference = 0 /* TextDefined */;
if (options && options.lineEnding && options.lineEnding === '\n') {
eolPreference = 1 /* LF */;
}
else if (options && options.lineEnding && options.lineEnding === '\r\n') {
eolPreference = 2 /* CRLF */;
}
return this._modelData.model.getValue(eolPreference, preserveBOM);
}
setValue(newValue) {
if (!this._modelData) {
return;
}
this._modelData.model.setValue(newValue);
}
getModel() {
if (!this._modelData) {
return null;
}
return this._modelData.model;
}
setModel(_model = null) {
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 hasTextFocus = this.hasTextFocus();
const detachedModel = this._detachModel();
this._attachModel(model);
if (hasTextFocus && this.hasModel()) {
this.focus();
}
const e = {
oldModelUrl: detachedModel ? detachedModel.uri : null,
newModelUrl: model ? model.uri : null
};
this._removeDecorationTypes();
this._onDidChangeModel.fire(e);
this._postDetachModelCleanup(detachedModel);
}
_removeDecorationTypes() {
this._decorationTypeKeysToIds = {};
if (this._decorationTypeSubtypes) {
for (let decorationType in this._decorationTypeSubtypes) {
const subTypes = this._decorationTypeSubtypes[decorationType];
for (let 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 _getVerticalOffsetForPosition(modelData, modelLineNumber, modelColumn) {
const modelPosition = modelData.model.validatePosition({
lineNumber: modelLineNumber,
column: modelColumn
});
const viewPosition = modelData.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
return modelData.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
}
getTopForLineNumber(lineNumber) {
if (!this._modelData) {
return -1;
}
return CodeEditorWidget._getVerticalOffsetForPosition(this._modelData, lineNumber, 1);
}
getTopForPosition(lineNumber, column) {
if (!this._modelData) {
return -1;
}
return CodeEditorWidget._getVerticalOffsetForPosition(this._modelData, lineNumber, column);
}
setHiddenAreas(ranges) {
if (this._modelData) {
this._modelData.viewModel.setHiddenAreas(ranges.map(r => range_1.Range.lift(r)));
}
}
getVisibleColumnFromPosition(rawPosition) {
if (!this._modelData) {
return rawPosition.column;
}
const position = this._modelData.model.validatePosition(rawPosition);
const tabSize = this._modelData.model.getOptions().tabSize;
return cursorCommon_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) {
if (!this._modelData) {
return;
}
if (!position_1.Position.isIPosition(position)) {
throw new Error('Invalid arguments');
}
this._modelData.viewModel.setSelections('api', [{
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 /* Smooth */) {
this._revealLine(lineNumber, 0 /* Simple */, scrollType);
}
revealLineInCenter(lineNumber, scrollType = 0 /* Smooth */) {
this._revealLine(lineNumber, 1 /* Center */, scrollType);
}
revealLineInCenterIfOutsideViewport(lineNumber, scrollType = 0 /* Smooth */) {
this._revealLine(lineNumber, 2 /* CenterIfOutsideViewport */, scrollType);
}
revealLineNearTop(lineNumber, scrollType = 0 /* Smooth */) {
this._revealLine(lineNumber, 5 /* 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 /* Smooth */) {
this._revealPosition(position, 0 /* Simple */, true, scrollType);
}
revealPositionInCenter(position, scrollType = 0 /* Smooth */) {
this._revealPosition(position, 1 /* Center */, true, scrollType);
}
revealPositionInCenterIfOutsideViewport(position, scrollType = 0 /* Smooth */) {
this._revealPosition(position, 2 /* CenterIfOutsideViewport */, true, scrollType);
}
revealPositionNearTop(position, scrollType = 0 /* Smooth */) {
this._revealPosition(position, 5 /* 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) {
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);
}
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);
}
}
_setSelectionImpl(sel) {
if (!this._modelData) {
return;
}
const selection = new selection_1.Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
this._modelData.viewModel.setSelections('api', [selection]);
}
revealLines(startLineNumber, endLineNumber, scrollType = 0 /* Smooth */) {
this._revealLines(startLineNumber, endLineNumber, 0 /* Simple */, scrollType);
}
revealLinesInCenter(startLineNumber, endLineNumber, scrollType = 0 /* Smooth */) {
this._revealLines(startLineNumber, endLineNumber, 1 /* Center */, scrollType);
}
revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType = 0 /* Smooth */) {
this._revealLines(startLineNumber, endLineNumber, 2 /* CenterIfOutsideViewport */, scrollType);
}
revealLinesNearTop(startLineNumber, endLineNumber, scrollType = 0 /* Smooth */) {
this._revealLines(startLineNumber, endLineNumber, 5 /* 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 /* Smooth */, revealVerticalInCenter = false, revealHorizontal = true) {
this._revealRange(range, revealVerticalInCenter ? 1 /* Center */ : 0 /* Simple */, revealHorizontal, scrollType);
}
revealRangeInCenter(range, scrollType = 0 /* Smooth */) {
this._revealRange(range, 1 /* Center */, true, scrollType);
}
revealRangeInCenterIfOutsideViewport(range, scrollType = 0 /* Smooth */) {
this._revealRange(range, 2 /* CenterIfOutsideViewport */, true, scrollType);
}
revealRangeNearTop(range, scrollType = 0 /* Smooth */) {
this._revealRange(range, 5 /* NearTop */, true, scrollType);
}
revealRangeNearTopIfOutsideViewport(range, scrollType = 0 /* Smooth */) {
this._revealRange(range, 6 /* NearTopIfOutsideViewport */, true, scrollType);
}
revealRangeAtTop(range, scrollType = 0 /* Smooth */) {
this._revealRange(range, 3 /* 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 /* 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 /* Immediate */) {
if (!this._modelData) {
return;
}
if (typeof newScrollLeft !== 'number') {
throw new Error('Invalid arguments');
}
this._modelData.viewModel.setScrollPosition({
scrollLeft: newScrollLeft
}, scrollType);
}
setScrollTop(newScrollTop, scrollType = 1 /* Immediate */) {
if (!this._modelData) {
return;
}
if (typeof newScrollTop !== 'number') {
throw new Error('Invalid arguments');
}
this._modelData.viewModel.setScrollPosition({
scrollTop: newScrollTop
}, scrollType);
}
setScrollPosition(position, scrollType = 1 /* Immediate */) {
if (!this._modelData) {
return;
}
this._modelData.viewModel.setScrollPosition(position, scrollType);
}
saveViewState() {
if (!this._modelData) {
return null;
}
const contributionsState = {};
const keys = Object.keys(this._contributions);
for (const id of keys) {
const contribution = this._contributions[id];
if (typeof contribution.saveViewState === 'function') {
contributionsState[id] = contribution.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)) {
this._modelData.viewModel.restoreCursorState(cursorState);
}
else {
// Backwards compatibility
this._modelData.viewModel.restoreCursorState([cursorState]);
}
const contributionsState = codeEditorState.contributionsState || {};
const keys = Object.keys(this._contributions);
for (let i = 0, len = keys.length; i < len; i++) {
const id = keys[i];
const contribution = this._contributions[id];
if (typeof contribution.restoreViewState === 'function') {
contribution.restoreViewState(contributionsState[id]);
}
}
const reducedState = this._modelData.viewModel.reduceRestoreState(codeEditorState.viewState);
this._modelData.view.restoreState(reducedState);
}
}
getContribution(id) {
return (this._contributions[id] || null);
}
getActions() {
const result = [];
const keys = Object.keys(this._actions);
for (let i = 0, len = keys.length; i < len; i++) {
const id = keys[i];
result.push(this._actions[id]);
}
return result;
}
getSupportedActions() {
let result = this.getActions();
result = result.filter(action => action.isSupported());
return result;
}
getAction(id) {
return this._actions[id] || null;
}
trigger(source, handlerId, payload) {
payload = payload || {};
switch (handlerId) {
case "compositionStart" /* CompositionStart */:
this._startComposition();
return;
case "compositionEnd" /* CompositionEnd */:
this._endComposition(source);
return;
case "type" /* Type */: {
const args = payload;
this._type(source, args.text || '');
return;
}
case "replacePreviousChar" /* ReplacePreviousChar */: {
const args = payload;
this._compositionType(source, args.text || '', args.replaceCharCnt || 0, 0, 0);
return;
}
case "compositionType" /* CompositionType */: {
const args = payload;
this._compositionType(source, args.text || '', args.replacePrevCharCnt || 0, args.replaceNextCharCnt || 0, args.positionDelta || 0);
return;
}
case "paste" /* Paste */: {
const args = payload;
this._paste(source, args.text || '', args.pasteOnNewLine || false, args.multicursorText || null, args.mode || null);
return;
}
case "cut" /* Cut */:
this._cut(source);
return;
}
const action = this.getAction(handlerId);
if (action) {
Promise.resolve(action.run()).then(undefined, errors_1.onUnexpectedError);
return;
}
if (!this._modelData) {
return;
}
if (this._triggerEditorCommand(source, handlerId, payload)) {
return;
}
this._triggerCommand(handlerId, payload);
}
_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) {
if (!this._modelData || text.length === 0) {
return;
}
const startPosition = this._modelData.viewModel.getSelection().getStartPosition();
this._modelData.viewModel.paste(text, pasteOnNewLine, multicursorText, source);
const endPosition = this._modelData.viewModel.getSelection().getStartPosition();
if (source === 'keyboard') {
this._onDidPaste.fire({
range: new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column),
mode: 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(79 /* readOnly */)) {
// read only editor => sorry!
return false;
}
this._modelData.model.pushStackElement();
return true;
}
popUndoStop() {
if (!this._modelData) {
return false;
}
if (this._configuration.options.get(79 /* 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(79 /* 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);
}
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));
}
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(decorationTypeKey) {
// remove decorations for type and sub type
const oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey];
if (oldDecorationsIds) {
this.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(129 /* 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;
}
delegateVerticalScrollbarMouseDown(browserEvent) {
if (!this._modelData || !this._modelData.hasRealView) {
return;
}
this._modelData.view.delegateVerticalScrollbarMouseDown(browserEvent);
}
layout(dimension) {
this._configuration.observeReferenceElement(dimension);
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.');
}
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);
}
}
}
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(129 /* layoutInfo */);
const top = CodeEditorWidget._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(57 /* 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.view.render(true, forceRedraw);
}
setAriaOptions(options) {
if (!this._modelData || !this._modelData.hasRealView) {
return;
}
this._modelData.view.setAriaOptions(options);
}
applyFontInfo(target) {
configuration_1.Configuration.applyFontInfoSlow(target, this._configuration.options.get(41 /* fontInfo */));
}
_attachModel(model) {
if (!model) {
this._modelData = null;
return;
}
const listenersToRemove = [];
this._domElement.setAttribute('data-mode-id', model.getLanguageIdentifier().language);
this._configuration.setIsDominatedByLongLines(model.isDominatedByLongLines());
this._configuration.setMaxLineNumber(model.getLineCount());
model.onBeforeAttached();
const viewModel = new viewModelImpl_1.ViewModel(this._id, this._configuration, model, domLineBreaksComputer_1.DOMLineBreaksComputerFactory.create(), monospaceLineBreaksComputer_1.MonospaceLineBreaksComputerFactory.create(this._configuration.options), (callback) => dom.scheduleAtNextAnimationFrame(callback));
listenersToRemove.push(model.onDidChangeDecorations((e) => this._onDidChangeModelDecorations.fire(e)));
listenersToRemove.push(model.onDidChangeLanguage((e) => {
this._domElement.setAttribute('data-mode-id', model.getLanguageIdentifier().language);
this._onDidChangeModelLanguage.fire(e);
}));
listenersToRemove.push(model.onDidChangeLanguageConfiguration((e) => this._onDidChangeModelLanguageConfiguration.fire(e)));
listenersToRemove.push(model.onDidChangeContent((e) => this._onDidChangeModelContent.fire(e)));
listenersToRemove.push(model.onDidChangeOptions((e) => this._onDidChangeModelOptions.fire(e)));
// 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 /* ContentSizeChanged */:
this._onDidContentSizeChange.fire(e);
break;
case 1 /* FocusChanged */:
this._editorTextFocus.setValue(e.hasFocus);
break;
case 2 /* ScrollChanged */:
this._onDidScrollChange.fire(e);
break;
case 3 /* ViewZonesChanged */:
this._onDidChangeViewZones.fire();
break;
case 4 /* ReadOnlyEditAttempt */:
this._onDidAttemptReadOnlyEdit.fire();
break;
case 5 /* CursorStateChanged */: {
if (e.reachedMaxCursorCount) {
this._notificationService.warn(nls.localize(0, null, cursor_1.CursorsController.MAX_CURSOR_COUNT));
}
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;
}
}
}));
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]);
}
view.render(false, true);
view.domNode.domNode.setAttribute('data-uri', model.uri.toString());
}
this._modelData = new ModelData(model, viewModel, view, hasRealView, listenersToRemove);
}
_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" /* Paste */, payload);
},
type: (text) => {
const payload = { text };
this._commandService.executeCommand("type" /* 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" /* CompositionType */, payload);
}
else {
const payload = { text, replaceCharCnt: replacePrevCharCnt };
this._commandService.executeCommand("replacePreviousChar" /* ReplacePreviousChar */, payload);
}
},
startComposition: () => {
this._commandService.executeCommand("compositionStart" /* CompositionStart */, {});
},
endComposition: () => {
this._commandService.executeCommand("compositionEnd" /* CompositionEnd */, {});
},
cut: () => {
this._commandService.executeCommand("cut" /* 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 viewImpl_1.View(commandDelegate, this._configuration, this._themeService, viewModel, viewUserInputEvents, this._overflowWidgetsDomNode);
return [view, true];
}
_postDetachModelCleanup(detachedModel) {
if (detachedModel) {
detachedModel.removeAllDecorationsWithOwnerId(this._id);
}
}
_detachModel() {
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)) {
this._domElement.removeChild(removeDomNode);
}
return model;
}
_removeDecorationType(key) {
this._codeEditorService.removeDecorationType(key);
}
hasModel() {
return (this._modelData !== null);
}
};
CodeEditorWidget = __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)
], CodeEditorWidget);
exports.CodeEditorWidget = CodeEditorWidget;
class BooleanEventEmitter extends lifecycle_1.Disposable {
constructor() {
super();
this._onDidChangeToTrue = this._register(new event_1.Emitter());
this.onDidChangeToTrue = this._onDidChangeToTrue.event;
this._onDidChangeToFalse = this._register(new event_1.Emitter());
this.onDidChangeToFalse = this._onDidChangeToFalse.event;
this._value = 0 /* NotSet */;
}
setValue(_value) {
const value = (_value ? 2 /* True */ : 1 /* False */);
if (this._value === value) {
return;
}
this._value = value;
if (this._value === 2 /* True */) {
this._onDidChangeToTrue.fire();
}
else if (this._value === 1 /* False */) {
this._onDidChangeToFalse.fire();
}
}
}
exports.BooleanEventEmitter = BooleanEventEmitter;
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._editorTabMovesFocus = 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._updateFromConfig();
this._updateFromSelection();
this._updateFromFocus();
this._updateFromModel();
this._editorSimpleInput.set(this._editor.isSimpleWidget);
}
_updateFromConfig() {
const options = this._editor.getOptions();
this._editorTabMovesFocus.set(options.get(128 /* tabFocusMode */));
this._editorReadonly.set(options.get(79 /* readOnly */));
this._inDiffEditor.set(options.get(52 /* inDiffEditor */));
this._editorColumnSelection.set(options.get(16 /* 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) {
super();
this._editor = _editor;
this._contextKeyService = _contextKeyService;
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._isInWalkThrough = editorContextKeys_1.EditorContextKeys.isInWalkThroughSnippet.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(modes.CompletionProviderRegistry.onDidChange(update));
this._register(modes.CodeActionProviderRegistry.onDidChange(update));
this._register(modes.CodeLensProviderRegistry.onDidChange(update));
this._register(modes.DefinitionProviderRegistry.onDidChange(update));
this._register(modes.DeclarationProviderRegistry.onDidChange(update));
this._register(modes.ImplementationProviderRegistry.onDidChange(update));
this._register(modes.TypeDefinitionProviderRegistry.onDidChange(update));
this._register(modes.HoverProviderRegistry.onDidChange(update));
this._register(modes.DocumentHighlightProviderRegistry.onDidChange(update));
this._register(modes.DocumentSymbolProviderRegistry.onDidChange(update));
this._register(modes.ReferenceProviderRegistry.onDidChange(update));
this._register(modes.RenameProviderRegistry.onDidChange(update));
this._register(modes.DocumentFormattingEditProviderRegistry.onDidChange(update));
this._register(modes.DocumentRangeFormattingEditProviderRegistry.onDidChange(update));
this._register(modes.SignatureHelpProviderRegistry.onDidChange(update));
this._register(modes.InlayHintsProviderRegistry.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._isInWalkThrough.reset();
});
}
_update() {
const model = this._editor.getModel();
if (!model) {
this.reset();
return;
}
this._contextKeyService.bufferChangeEvents(() => {
this._langId.set(model.getLanguageIdentifier().language);
this._hasCompletionItemProvider.set(modes.CompletionProviderRegistry.has(model));
this._hasCodeActionsProvider.set(modes.CodeActionProviderRegistry.has(model));
this._hasCodeLensProvider.set(modes.CodeLensProviderRegistry.has(model));
this._hasDefinitionProvider.set(modes.DefinitionProviderRegistry.has(model));
this._hasDeclarationProvider.set(modes.DeclarationProviderRegistry.has(model));
this._hasImplementationProvider.set(modes.ImplementationProviderRegistry.has(model));
this._hasTypeDefinitionProvider.set(modes.TypeDefinitionProviderRegistry.has(model));
this._hasHoverProvider.set(modes.HoverProviderRegistry.has(model));
this._hasDocumentHighlightProvider.set(modes.DocumentHighlightProviderRegistry.has(model));
this._hasDocumentSymbolProvider.set(modes.DocumentSymbolProviderRegistry.has(model));
this._hasReferenceProvider.set(modes.ReferenceProviderRegistry.has(model));
this._hasRenameProvider.set(modes.RenameProviderRegistry.has(model));
this._hasSignatureHelpProvider.set(modes.SignatureHelpProviderRegistry.has(model));
this._hasInlayHintsProvider.set(modes.InlayHintsProviderRegistry.has(model));
this._hasDocumentFormattingProvider.set(modes.DocumentFormattingEditProviderRegistry.has(model) || modes.DocumentRangeFormattingEditProviderRegistry.has(model));
this._hasDocumentSelectionFormattingProvider.set(modes.DocumentRangeFormattingEditProviderRegistry.has(model));
this._hasMultipleDocumentFormattingProvider.set(modes.DocumentFormattingEditProviderRegistry.all(model).length + modes.DocumentRangeFormattingEditProviderRegistry.all(model).length > 1);
this._hasMultipleDocumentSelectionFormattingProvider.set(modes.DocumentRangeFormattingEditProviderRegistry.all(model).length > 1);
this._isInWalkThrough.set(model.uri.scheme === network_1.Schemas.walkThroughSnippet);
});
}
}
exports.EditorModeContext = EditorModeContext;
class CodeEditorWidgetFocusTracker extends lifecycle_1.Disposable {
constructor(domElement) {
super();
this._onChange = this._register(new event_1.Emitter());
this.onChange = this._onChange.event;
this._hasFocus = false;
this._domFocusTracker = this._register(dom.trackFocus(domElement));
this._register(this._domFocusTracker.onDidFocus(() => {
this._hasFocus = true;
this._onChange.fire(undefined);
}));
this._register(this._domFocusTracker.onDidBlur(() => {
this._hasFocus = false;
this._onChange.fire(undefined);
}));
}
hasFocus() {
return this._hasFocus;
}
}
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 errorBorderColor = theme.getColor(colorRegistry_1.editorErrorBorder);
if (errorBorderColor) {
collector.addRule(`.monaco-editor .${"squiggly-error" /* EditorErrorDecoration */} { border-bottom: 4px double ${errorBorderColor}; }`);
}
const errorForeground = theme.getColor(colorRegistry_1.editorErrorForeground);
if (errorForeground) {
collector.addRule(`.monaco-editor .${"squiggly-error" /* EditorErrorDecoration */} { background: url("data:image/svg+xml,${getSquigglySVGData(errorForeground)}") repeat-x bottom left; }`);
}
const errorBackground = theme.getColor(colorRegistry_1.editorErrorBackground);
if (errorBackground) {
collector.addRule(`.monaco-editor .${"squiggly-error" /* EditorErrorDecoration */}::before { display: block; content: ''; width: 100%; height: 100%; background: ${errorBackground}; }`);
}
const warningBorderColor = theme.getColor(colorRegistry_1.editorWarningBorder);
if (warningBorderColor) {
collector.addRule(`.monaco-editor .${"squiggly-warning" /* EditorWarningDecoration */} { border-bottom: 4px double ${warningBorderColor}; }`);
}
const warningForeground = theme.getColor(colorRegistry_1.editorWarningForeground);
if (warningForeground) {
collector.addRule(`.monaco-editor .${"squiggly-warning" /* EditorWarningDecoration */} { background: url("data:image/svg+xml,${getSquigglySVGData(warningForeground)}") repeat-x bottom left; }`);
}
const warningBackground = theme.getColor(colorRegistry_1.editorWarningBackground);
if (warningBackground) {
collector.addRule(`.monaco-editor .${"squiggly-warning" /* EditorWarningDecoration */}::before { display: block; content: ''; width: 100%; height: 100%; background: ${warningBackground}; }`);
}
const infoBorderColor = theme.getColor(colorRegistry_1.editorInfoBorder);
if (infoBorderColor) {
collector.addRule(`.monaco-editor .${"squiggly-info" /* EditorInfoDecoration */} { border-bottom: 4px double ${infoBorderColor}; }`);
}
const infoForeground = theme.getColor(colorRegistry_1.editorInfoForeground);
if (infoForeground) {
collector.addRule(`.monaco-editor .${"squiggly-info" /* EditorInfoDecoration */} { background: url("data:image/svg+xml,${getSquigglySVGData(infoForeground)}") repeat-x bottom left; }`);
}
const infoBackground = theme.getColor(colorRegistry_1.editorInfoBackground);
if (infoBackground) {
collector.addRule(`.monaco-editor .${"squiggly-info" /* EditorInfoDecoration */}::before { display: block; content: ''; width: 100%; height: 100%; background: ${infoBackground}; }`);
}
const hintBorderColor = theme.getColor(colorRegistry_1.editorHintBorder);
if (hintBorderColor) {
collector.addRule(`.monaco-editor .${"squiggly-hint" /* EditorHintDecoration */} { border-bottom: 2px dotted ${hintBorderColor}; }`);
}
const hintForeground = theme.getColor(colorRegistry_1.editorHintForeground);
if (hintForeground) {
collector.addRule(`.monaco-editor .${"squiggly-hint" /* 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" /* EditorUnnecessaryInlineDecoration */} { opacity: ${unnecessaryForeground.rgba.a}; }`);
}
const unnecessaryBorder = theme.getColor(editorColorRegistry_1.editorUnnecessaryCodeBorder);
if (unnecessaryBorder) {
collector.addRule(`.monaco-editor.showUnused .${"squiggly-unnecessary" /* EditorUnnecessaryDecoration */} { border-bottom: 2px dashed ${unnecessaryBorder}; }`);
}
const deprecatedForeground = theme.getColor(colorRegistry_1.editorForeground) || 'inherit';
collector.addRule(`.monaco-editor.showDeprecated .${"squiggly-inline-deprecated" /* EditorDeprecatedInlineDecoration */} { text-decoration: line-through; text-decoration-color: ${deprecatedForeground}}`);
});
});
/*---------------------------------------------------------------------------------------------
* 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/browser/widget/embeddedCodeEditorWidget*/], __M([0/*require*/,1/*exports*/,42/*vs/base/common/objects*/,28/*vs/editor/browser/services/codeEditorService*/,149/*vs/editor/browser/widget/codeEditorWidget*/,26/*vs/platform/commands/common/commands*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/,34/*vs/platform/notification/common/notification*/,11/*vs/platform/theme/common/themeService*/,64/*vs/platform/accessibility/common/accessibility*/]), function (require, exports, objects, codeEditorService_1, codeEditorWidget_1, commands_1, contextkey_1, instantiation_1, notification_1, themeService_1, accessibility_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EmbeddedCodeEditorWidget = void 0;
let EmbeddedCodeEditorWidget = class EmbeddedCodeEditorWidget extends codeEditorWidget_1.CodeEditorWidget {
constructor(domElement, options, parentEditor, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService) {
super(domElement, Object.assign(Object.assign({}, parentEditor.getRawOptions()), { overflowWidgetsDomNode: parentEditor.getOverflowWidgetsDomNode() }), {}, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService);
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);
}
};
EmbeddedCodeEditorWidget = __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)
], EmbeddedCodeEditorWidget);
exports.EmbeddedCodeEditorWidget = EmbeddedCodeEditorWidget;
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/anchorSelect/anchorSelect*/], __M([0/*require*/,1/*exports*/,14/*vs/editor/browser/editorExtensions*/,471/*vs/nls!vs/editor/contrib/anchorSelect/anchorSelect*/,25/*vs/editor/common/editorContextKeys*/,21/*vs/editor/common/core/selection*/,41/*vs/base/common/keyCodes*/,16/*vs/platform/contextkey/common/contextkey*/,82/*vs/base/common/htmlContent*/,44/*vs/base/browser/ui/aria/aria*/,343/*vs/css!vs/editor/contrib/anchorSelect/anchorSelect*/]), function (require, exports, editorExtensions_1, nls_1, editorContextKeys_1, selection_1, keyCodes_1, contextkey_1, htmlContent_1, aria_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SelectionAnchorSet = void 0;
exports.SelectionAnchorSet = new contextkey_1.RawContextKey('selectionAnchorSet', false);
let SelectionAnchorController = class SelectionAnchorController {
constructor(editor, contextKeyService) {
this.editor = editor;
this.selectionAnchorSetContextKey = exports.SelectionAnchorSet.bindTo(contextKeyService);
this.modelChangeListener = editor.onDidChangeModel(() => this.selectionAnchorSetContextKey.reset());
}
static get(editor) {
return editor.getContribution(SelectionAnchorController.ID);
}
setSelectionAnchor() {
if (this.editor.hasModel()) {
const position = this.editor.getPosition();
const previousDecorations = this.decorationId ? [this.decorationId] : [];
const newDecorationId = this.editor.deltaDecorations(previousDecorations, [{
range: selection_1.Selection.fromPositions(position, position),
options: {
description: 'selection-anchor',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
hoverMessage: new htmlContent_1.MarkdownString().appendText((0, nls_1.localize)(0, null)),
className: 'selection-anchor'
}
}]);
this.decorationId = newDecorationId[0];
this.selectionAnchorSetContextKey.set(!!this.decorationId);
(0, aria_1.alert)((0, nls_1.localize)(1, null, 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) {
this.editor.deltaDecorations([this.decorationId], []);
this.decorationId = undefined;
this.selectionAnchorSetContextKey.set(false);
}
}
dispose() {
this.cancelSelectionAnchor();
this.modelChangeListener.dispose();
}
};
SelectionAnchorController.ID = 'editor.contrib.selectionAnchorController';
SelectionAnchorController = __decorate([
__param(1, contextkey_1.IContextKeyService)
], SelectionAnchorController);
class SetSelectionAnchor extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.setSelectionAnchor',
label: (0, nls_1.localize)(2, null),
alias: 'Set Selection Anchor',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 32 /* KEY_B */),
weight: 100 /* EditorContrib */
}
});
}
run(_accessor, editor) {
return __awaiter(this, void 0, void 0, function* () {
const controller = SelectionAnchorController.get(editor);
controller.setSelectionAnchor();
});
}
}
class GoToSelectionAnchor extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.goToSelectionAnchor',
label: (0, nls_1.localize)(3, null),
alias: 'Go to Selection Anchor',
precondition: exports.SelectionAnchorSet,
});
}
run(_accessor, editor) {
return __awaiter(this, void 0, void 0, function* () {
const controller = SelectionAnchorController.get(editor);
controller.goToSelectionAnchor();
});
}
}
class SelectFromAnchorToCursor extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.selectFromAnchorToCursor',
label: (0, nls_1.localize)(4, null),
alias: 'Select from Anchor to Cursor',
precondition: exports.SelectionAnchorSet,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 41 /* KEY_K */),
weight: 100 /* EditorContrib */
}
});
}
run(_accessor, editor) {
return __awaiter(this, void 0, void 0, function* () {
const controller = SelectionAnchorController.get(editor);
controller.selectFromAnchorToCursor();
});
}
}
class CancelSelectionAnchor extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.cancelSelectionAnchor',
label: (0, nls_1.localize)(5, null),
alias: 'Cancel Selection Anchor',
precondition: exports.SelectionAnchorSet,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 9 /* Escape */,
weight: 100 /* EditorContrib */
}
});
}
run(_accessor, editor) {
return __awaiter(this, void 0, void 0, function* () {
const controller = SelectionAnchorController.get(editor);
controller.cancelSelectionAnchor();
});
}
}
(0, editorExtensions_1.registerEditorContribution)(SelectionAnchorController.ID, SelectionAnchorController);
(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[626/*vs/editor/contrib/bracketMatching/bracketMatching*/], __M([0/*require*/,1/*exports*/,472/*vs/nls!vs/editor/contrib/bracketMatching/bracketMatching*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,25/*vs/editor/common/editorContextKeys*/,53/*vs/editor/common/model*/,31/*vs/editor/common/model/textModel*/,48/*vs/editor/common/view/editorColorRegistry*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,33/*vs/platform/actions/common/actions*/,344/*vs/css!vs/editor/contrib/bracketMatching/bracketMatching*/]), function (require, exports, nls, async_1, lifecycle_1, editorExtensions_1, position_1, range_1, selection_1, editorContextKeys_1, model_1, textModel_1, editorColorRegistry_1, colorRegistry_1, themeService_1, actions_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BracketMatchingController = void 0;
const overviewRulerBracketMatchForeground = (0, colorRegistry_1.registerColor)('editorOverviewRuler.bracketMatchForeground', { dark: '#A0A0A0', light: '#A0A0A0', hc: '#A0A0A0' }, nls.localize(0, null));
class JumpToBracketAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.jumpToBracket',
label: nls.localize(1, null),
alias: 'Go to Bracket',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 88 /* US_BACKSLASH */,
weight: 100 /* EditorContrib */
}
});
}
run(accessor, editor) {
let controller = BracketMatchingController.get(editor);
if (!controller) {
return;
}
controller.jumpToBracket();
}
}
class SelectToBracketAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.selectToBracket',
label: nls.localize(2, null),
alias: 'Select to Bracket',
precondition: undefined,
description: {
description: `Select to Bracket`,
args: [{
name: 'args',
schema: {
type: 'object',
properties: {
'selectBrackets': {
type: 'boolean',
default: true
}
},
}
}]
}
});
}
run(accessor, editor, args) {
const controller = BracketMatchingController.get(editor);
if (!controller) {
return;
}
let selectBrackets = true;
if (args && args.selectBrackets === false) {
selectBrackets = false;
}
controller.selectToBracket(selectBrackets);
}
}
class BracketsData {
constructor(position, brackets, options) {
this.position = position;
this.brackets = brackets;
this.options = options;
}
}
class BracketMatchingController extends lifecycle_1.Disposable {
constructor(editor) {
super();
this._editor = editor;
this._lastBracketsData = [];
this._lastVersionId = 0;
this._decorations = [];
this._updateBracketsSoon = this._register(new async_1.RunOnceScheduler(() => this._updateBrackets(), 50));
this._matchBrackets = this._editor.getOption(62 /* 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._decorations = [];
this._updateBracketsSoon.schedule();
}));
this._register(editor.onDidChangeModelLanguageConfiguration((e) => {
this._lastBracketsData = [];
this._updateBracketsSoon.schedule();
}));
this._register(editor.onDidChangeConfiguration((e) => {
if (e.hasChanged(62 /* matchBrackets */)) {
this._matchBrackets = this._editor.getOption(62 /* matchBrackets */);
this._decorations = this._editor.deltaDecorations(this._decorations, []);
this._lastBracketsData = [];
this._lastVersionId = 0;
this._updateBracketsSoon.schedule();
}
}));
}
static get(editor) {
return editor.getContribution(BracketMatchingController.ID);
}
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.matchBracket(position);
let newCursorPosition = null;
if (brackets) {
if (brackets[0].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.findEnclosingBrackets(position);
if (enclosingBrackets) {
newCursorPosition = enclosingBrackets[0].getStartPosition();
}
else {
// no enclosing brackets, try the very first next bracket
const nextBracket = model.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.matchBracket(position);
if (!brackets) {
brackets = model.findEnclosingBrackets(position);
if (!brackets) {
const nextBracket = model.findNextBracket(position);
if (nextBracket && nextBracket.range) {
brackets = model.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 (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]);
}
}
_updateBrackets() {
if (this._matchBrackets === 'never') {
return;
}
this._recomputeBrackets();
let newDecorations = [], newDecorationsLen = 0;
for (const bracketData of this._lastBracketsData) {
let brackets = bracketData.brackets;
if (brackets) {
newDecorations[newDecorationsLen++] = { range: brackets[0], options: bracketData.options };
newDecorations[newDecorationsLen++] = { range: brackets[1], options: bracketData.options };
}
}
this._decorations = this._editor.deltaDecorations(this._decorations, newDecorations);
}
_recomputeBrackets() {
if (!this._editor.hasModel()) {
// no model => 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;
}
let positions = [], positionsLen = 0;
for (let i = 0, len = selections.length; i < len; i++) {
let 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);
}
let newData = [], newDataLen = 0;
let previousIndex = 0, previousLen = previousData.length;
for (let i = 0, len = positions.length; i < len; i++) {
let 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.matchBracket(position);
let options = BracketMatchingController._DECORATION_OPTIONS_WITH_OVERVIEW_RULER;
if (!brackets && this._matchBrackets === 'always') {
brackets = model.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;
BracketMatchingController.ID = 'editor.contrib.bracketMatchingController';
BracketMatchingController._DECORATION_OPTIONS_WITH_OVERVIEW_RULER = textModel_1.ModelDecorationOptions.register({
description: 'bracket-match-overview',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
className: 'bracket-match',
overviewRuler: {
color: (0, themeService_1.themeColorFromId)(overviewRulerBracketMatchForeground),
position: model_1.OverviewRulerLane.Center
}
});
BracketMatchingController._DECORATION_OPTIONS_WITHOUT_OVERVIEW_RULER = textModel_1.ModelDecorationOptions.register({
description: 'bracket-match-no-overview',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
className: 'bracket-match'
});
(0, editorExtensions_1.registerEditorContribution)(BracketMatchingController.ID, BracketMatchingController);
(0, editorExtensions_1.registerEditorAction)(SelectToBracketAction);
(0, editorExtensions_1.registerEditorAction)(JumpToBracketAction);
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const bracketMatchBackground = theme.getColor(editorColorRegistry_1.editorBracketMatchBackground);
if (bracketMatchBackground) {
collector.addRule(`.monaco-editor .bracket-match { background-color: ${bracketMatchBackground}; }`);
}
const bracketMatchBorder = theme.getColor(editorColorRegistry_1.editorBracketMatchBorder);
if (bracketMatchBorder) {
collector.addRule(`.monaco-editor .bracket-match { border: 1px solid ${bracketMatchBorder}; }`);
}
});
// Go to menu
actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.MenubarGoMenu, {
group: '5_infile_nav',
command: {
id: 'editor.action.jumpToBracket',
title: nls.localize(3, null)
},
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[627/*vs/editor/contrib/caretOperations/caretOperations*/], __M([0/*require*/,1/*exports*/,473/*vs/nls!vs/editor/contrib/caretOperations/caretOperations*/,14/*vs/editor/browser/editorExtensions*/,25/*vs/editor/common/editorContextKeys*/,407/*vs/editor/contrib/caretOperations/moveCaretCommand*/]), function (require, exports, nls, editorExtensions_1, editorContextKeys_1, moveCaretCommand_1) {
"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;
}
let commands = [];
let 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(0, null),
alias: 'Move Selected Text Left',
precondition: editorContextKeys_1.EditorContextKeys.writable
});
}
}
class MoveCaretRightAction extends MoveCaretAction {
constructor() {
super(false, {
id: 'editor.action.moveCarretRightAction',
label: nls.localize(1, null),
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[628/*vs/editor/contrib/caretOperations/transpose*/], __M([0/*require*/,1/*exports*/,474/*vs/nls!vs/editor/contrib/caretOperations/transpose*/,14/*vs/editor/browser/editorExtensions*/,95/*vs/editor/common/commands/replaceCommand*/,3/*vs/editor/common/core/range*/,25/*vs/editor/common/editorContextKeys*/,185/*vs/editor/common/controller/cursorMoveOperations*/]), function (require, exports, nls, editorExtensions_1, replaceCommand_1, range_1, editorContextKeys_1, cursorMoveOperations_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class TransposeLettersAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.transposeLetters',
label: nls.localize(0, null),
alias: 'Transpose Letters',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 0,
mac: {
primary: 256 /* WinCtrl */ | 50 /* KEY_T */
},
weight: 100 /* EditorContrib */
}
});
}
run(accessor, editor) {
if (!editor.hasModel()) {
return;
}
let model = editor.getModel();
let commands = [];
let selections = editor.getSelections();
for (let selection of selections) {
if (!selection.isEmpty()) {
continue;
}
let lineNumber = selection.startLineNumber;
let column = selection.startColumn;
let 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
let endPosition = (column === lastColumn) ?
selection.getPosition() :
cursorMoveOperations_1.MoveOperations.rightPosition(model, selection.getPosition().lineNumber, selection.getPosition().column);
let middlePosition = cursorMoveOperations_1.MoveOperations.leftPosition(model, endPosition);
let beginPosition = cursorMoveOperations_1.MoveOperations.leftPosition(model, middlePosition);
let leftChar = model.getValueInRange(range_1.Range.fromPositions(beginPosition, middlePosition));
let rightChar = model.getValueInRange(range_1.Range.fromPositions(middlePosition, endPosition));
let 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[629/*vs/editor/contrib/clipboard/clipboard*/], __M([0/*require*/,1/*exports*/,475/*vs/nls!vs/editor/contrib/clipboard/clipboard*/,39/*vs/base/browser/browser*/,17/*vs/base/common/platform*/,169/*vs/editor/browser/controller/textAreaInput*/,14/*vs/editor/browser/editorExtensions*/,28/*vs/editor/browser/services/codeEditorService*/,25/*vs/editor/common/editorContextKeys*/,33/*vs/platform/actions/common/actions*/,86/*vs/platform/clipboard/common/clipboardService*/]), function (require, exports, nls, browser, platform, textAreaInput_1, editorExtensions_1, codeEditorService_1, editorContextKeys_1, actions_1, clipboardService_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 /* CtrlCmd */ | 54 /* KEY_X */,
win: { primary: 2048 /* CtrlCmd */ | 54 /* KEY_X */, secondary: [1024 /* Shift */ | 20 /* Delete */] },
weight: 100 /* EditorContrib */
} : undefined),
menuOpts: [{
menuId: actions_1.MenuId.MenubarEditMenu,
group: '2_ccp',
title: nls.localize(0, null),
order: 1
}, {
menuId: actions_1.MenuId.EditorContext,
group: CLIPBOARD_CONTEXT_MENU_GROUP,
title: nls.localize(1, null),
when: editorContextKeys_1.EditorContextKeys.writable,
order: 1,
}, {
menuId: actions_1.MenuId.CommandPalette,
group: '',
title: nls.localize(2, null),
order: 1
}, {
menuId: actions_1.MenuId.SimpleEditorContext,
group: CLIPBOARD_CONTEXT_MENU_GROUP,
title: nls.localize(3, null),
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 /* CtrlCmd */ | 33 /* KEY_C */,
win: { primary: 2048 /* CtrlCmd */ | 33 /* KEY_C */, secondary: [2048 /* CtrlCmd */ | 19 /* Insert */] },
weight: 100 /* EditorContrib */
} : undefined),
menuOpts: [{
menuId: actions_1.MenuId.MenubarEditMenu,
group: '2_ccp',
title: nls.localize(4, null),
order: 2
}, {
menuId: actions_1.MenuId.EditorContext,
group: CLIPBOARD_CONTEXT_MENU_GROUP,
title: nls.localize(5, null),
order: 2,
}, {
menuId: actions_1.MenuId.CommandPalette,
group: '',
title: nls.localize(6, null),
order: 1
}, {
menuId: actions_1.MenuId.SimpleEditorContext,
group: CLIPBOARD_CONTEXT_MENU_GROUP,
title: nls.localize(7, null),
order: 2,
}]
})) : undefined;
actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.MenubarEditMenu, { submenu: actions_1.MenuId.MenubarCopy, title: { value: nls.localize(8, null), original: 'Copy As', }, group: '2_ccp', order: 3 });
actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.EditorContext, { submenu: actions_1.MenuId.EditorContextCopy, title: { value: nls.localize(9, null), original: 'Copy As', }, group: CLIPBOARD_CONTEXT_MENU_GROUP, order: 3 });
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 /* CtrlCmd */ | 52 /* KEY_V */,
win: { primary: 2048 /* CtrlCmd */ | 52 /* KEY_V */, secondary: [1024 /* Shift */ | 19 /* Insert */] },
linux: { primary: 2048 /* CtrlCmd */ | 52 /* KEY_V */, secondary: [1024 /* Shift */ | 19 /* Insert */] },
weight: 100 /* EditorContrib */
} : undefined),
menuOpts: [{
menuId: actions_1.MenuId.MenubarEditMenu,
group: '2_ccp',
title: nls.localize(10, null),
order: 4
}, {
menuId: actions_1.MenuId.EditorContext,
group: CLIPBOARD_CONTEXT_MENU_GROUP,
title: nls.localize(11, null),
when: editorContextKeys_1.EditorContextKeys.writable,
order: 4,
}, {
menuId: actions_1.MenuId.CommandPalette,
group: '',
title: nls.localize(12, null),
order: 1
}, {
menuId: actions_1.MenuId.SimpleEditorContext,
group: CLIPBOARD_CONTEXT_MENU_GROUP,
title: nls.localize(13, null),
when: editorContextKeys_1.EditorContextKeys.writable,
order: 4,
}]
})) : undefined;
class ExecCommandCopyWithSyntaxHighlightingAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.clipboardCopyWithSyntaxHighlightingAction',
label: nls.localize(14, null),
alias: 'Copy With Syntax Highlighting',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 0,
weight: 100 /* EditorContrib */
}
});
}
run(accessor, editor) {
if (!editor.hasModel()) {
return;
}
const emptySelectionClipboard = editor.getOption(30 /* emptySelectionClipboard */);
if (!emptySelectionClipboard && editor.getSelection().isEmpty()) {
return;
}
textAreaInput_1.CopyOptions.forceCopyWithSyntaxHighlighting = true;
editor.focus();
document.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(30 /* emptySelectionClipboard */);
const selection = focusedEditor.getSelection();
if (selection && selection.isEmpty() && !emptySelectionClipboard) {
return true;
}
document.execCommand(browserCommand);
return true;
}
return false;
});
// 2. (default) handle case when focus is somewhere else.
target.addImplementation(0, 'generic-dom', (accessor, args) => {
document.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 = document.execCommand('paste');
// Use the clipboard service if document.execCommand('paste') was not successful
if (!result && platform.isWeb) {
(() => __awaiter(void 0, void 0, void 0, function* () {
const clipboardText = yield 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(30 /* emptySelectionClipboard */) && !!metadata.isFromEmptySelection);
multicursorText = (typeof metadata.multicursorText !== 'undefined' ? metadata.multicursorText : null);
mode = metadata.mode;
}
focusedEditor.trigger('keyboard', "paste" /* Paste */, {
text: clipboardText,
pasteOnNewLine,
multicursorText,
mode
});
}
}))();
return true;
}
return true;
}
return false;
});
// 2. Paste: (default) handle case when focus is somewhere else.
exports.PasteAction.addImplementation(0, 'generic-dom', (accessor, args) => {
document.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[151/*vs/editor/contrib/codeAction/codeAction*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,24/*vs/base/common/uri*/,66/*vs/editor/browser/core/editorState*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,18/*vs/editor/common/modes*/,36/*vs/editor/common/services/modelService*/,137/*vs/editor/contrib/codeAction/types*/,59/*vs/platform/progress/common/progress*/,26/*vs/platform/commands/common/commands*/]), function (require, exports, arrays_1, cancellation_1, errors_1, lifecycle_1, uri_1, editorState_1, range_1, selection_1, modes, modelService_1, types_1, progress_1, commands_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCodeActions = exports.CodeActionItem = exports.fixAllCommandId = exports.organizeImportsCommandId = exports.sourceActionCommandId = exports.refactorCommandId = exports.codeActionCommandId = void 0;
exports.codeActionCommandId = 'editor.action.codeAction';
exports.refactorCommandId = 'editor.action.refactor';
exports.sourceActionCommandId = 'editor.action.sourceAction';
exports.organizeImportsCommandId = 'editor.action.organizeImports';
exports.fixAllCommandId = 'editor.action.fixAll';
class CodeActionItem {
constructor(action, provider) {
this.action = action;
this.provider = provider;
}
resolve(token) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
if (((_a = this.provider) === null || _a === void 0 ? void 0 : _a.resolveCodeAction) && !this.action.edit) {
let action;
try {
action = yield 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;
class ManagedCodeActionSet extends lifecycle_1.Disposable {
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);
}
static codeActionsComparator({ action: a }, { action: b }) {
if (a.isPreferred && !b.isPreferred) {
return -1;
}
else if (!a.isPreferred && b.isPreferred) {
return 1;
}
if ((0, arrays_1.isNonEmptyArray)(a.diagnostics)) {
if ((0, arrays_1.isNonEmptyArray)(b.diagnostics)) {
return a.diagnostics[0].message.localeCompare(b.diagnostics[0].message);
}
else {
return -1;
}
}
else if ((0, arrays_1.isNonEmptyArray)(b.diagnostics)) {
return 1;
}
else {
return 0; // both have no diagnostics
}
}
get hasAutoFix() {
return this.validActions.some(({ action: fix }) => !!fix.kind && types_1.CodeActionKind.QuickFix.contains(new types_1.CodeActionKind(fix.kind)) && !!fix.isPreferred);
}
}
const emptyCodeActionsResponse = { actions: [], documentation: undefined };
function getCodeActions(model, rangeOrSelection, trigger, progress, token) {
var _a;
const filter = trigger.filter || {};
const codeActionContext = {
only: (_a = filter.include) === null || _a === void 0 ? void 0 : _a.value,
trigger: trigger.type,
};
const cts = new editorState_1.TextModelCancellationTokenSource(model, token);
const providers = getCodeActionProviders(model, filter);
const disposables = new lifecycle_1.DisposableStore();
const promises = providers.map((provider) => __awaiter(this, void 0, void 0, function* () {
try {
progress.report(provider);
const providedCodeActions = yield provider.provideCodeActions(model, rangeOrSelection, codeActionContext, cts.token);
if (providedCodeActions) {
disposables.add(providedCodeActions);
}
if (cts.token.isCancellationRequested) {
return emptyCodeActionsResponse;
}
const filteredActions = ((providedCodeActions === null || providedCodeActions === void 0 ? void 0 : providedCodeActions.actions) || []).filter(action => action && (0, types_1.filtersAction)(filter, action));
const documentation = getDocumentation(provider, filteredActions, filter.include);
return {
actions: filteredActions.map(action => new CodeActionItem(action, provider)),
documentation
};
}
catch (err) {
if ((0, errors_1.isPromiseCanceledError)(err)) {
throw err;
}
(0, errors_1.onUnexpectedExternalError)(err);
return emptyCodeActionsResponse;
}
}));
const listener = modes.CodeActionProviderRegistry.onDidChange(() => {
const newProviders = modes.CodeActionProviderRegistry.all(model);
if (!(0, arrays_1.equals)(newProviders, providers)) {
cts.cancel();
}
});
return Promise.all(promises).then(actions => {
const allActions = (0, arrays_1.flatten)(actions.map(x => x.actions));
const allDocumentation = (0, arrays_1.coalesce)(actions.map(x => x.documentation));
return new ManagedCodeActionSet(allActions, allDocumentation, disposables);
})
.finally(() => {
listener.dispose();
cts.dispose();
});
}
exports.getCodeActions = getCodeActions;
function getCodeActionProviders(model, filter) {
return modes.CodeActionProviderRegistry.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 types_1.CodeActionKind(kind)));
});
}
function getDocumentation(provider, providedCodeActions, only) {
if (!provider.documentation) {
return undefined;
}
const documentation = provider.documentation.map(entry => ({ kind: new types_1.CodeActionKind(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 === null || currentBest === void 0 ? void 0 : 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 types_1.CodeActionKind(action.kind))) {
return entry.command;
}
}
}
return undefined;
}
commands_1.CommandsRegistry.registerCommand('_executeCodeActionProvider', function (accessor, resource, rangeOrSelection, kind, itemResolveCount) {
return __awaiter(this, void 0, void 0, function* () {
if (!(resource instanceof uri_1.URI)) {
throw (0, errors_1.illegalArgument)();
}
const model = accessor.get(modelService_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 types_1.CodeActionKind(kind) : undefined;
const codeActionSet = yield getCodeActions(model, validatedRangeOrSelection, { type: 1 /* Invoke */, 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 {
yield 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[630/*vs/editor/contrib/codeAction/codeActionMenu*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,50/*vs/base/common/actions*/,12/*vs/base/common/errors*/,155/*vs/base/common/lazy*/,2/*vs/base/common/lifecycle*/,13/*vs/editor/common/core/position*/,18/*vs/editor/common/modes*/,151/*vs/editor/contrib/codeAction/codeAction*/,137/*vs/editor/contrib/codeAction/types*/,69/*vs/platform/contextview/browser/contextView*/,37/*vs/platform/keybinding/common/keybinding*/]), function (require, exports, dom_1, actions_1, errors_1, lazy_1, lifecycle_1, position_1, modes_1, codeAction_1, types_1, contextView_1, keybinding_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeActionKeybindingResolver = exports.CodeActionMenu = void 0;
class CodeActionAction extends actions_1.Action {
constructor(action, callback) {
super(action.command ? action.command.id : action.title, stripNewlines(action.title), undefined, !action.disabled, callback);
this.action = action;
}
}
function stripNewlines(str) {
return str.replace(/\r\n|\r|\n/g, ' ');
}
let CodeActionMenu = class CodeActionMenu extends lifecycle_1.Disposable {
constructor(_editor, _delegate, _contextMenuService, keybindingService) {
super();
this._editor = _editor;
this._delegate = _delegate;
this._contextMenuService = _contextMenuService;
this._visible = false;
this._showingActions = this._register(new lifecycle_1.MutableDisposable());
this._keybindingResolver = new CodeActionKeybindingResolver({
getKeybindings: () => keybindingService.getKeybindings()
});
}
get isVisible() {
return this._visible;
}
show(trigger, codeActions, at, options) {
return __awaiter(this, void 0, void 0, function* () {
const actionsToShow = options.includeDisabledActions ? codeActions.allActions : codeActions.validActions;
if (!actionsToShow.length) {
this._visible = false;
return;
}
if (!this._editor.getDomNode()) {
// cancel when editor went off-dom
this._visible = false;
throw (0, errors_1.canceled)();
}
this._visible = true;
this._showingActions.value = codeActions;
const menuActions = this.getMenuActions(trigger, actionsToShow, codeActions.documentation);
const anchor = position_1.Position.isIPosition(at) ? this._toCoords(at) : at || { x: 0, y: 0 };
const resolver = this._keybindingResolver.getResolver();
const useShadowDOM = this._editor.getOption(113 /* useShadowDOM */);
this._contextMenuService.showContextMenu({
domForShadowRoot: useShadowDOM ? this._editor.getDomNode() : undefined,
getAnchor: () => anchor,
getActions: () => menuActions,
onHide: () => {
this._visible = false;
this._editor.focus();
},
autoSelectFirstItem: true,
getKeyBinding: action => action instanceof CodeActionAction ? resolver(action.action) : undefined,
});
});
}
getMenuActions(trigger, actionsToShow, documentation) {
var _a, _b;
const toCodeActionAction = (item) => new CodeActionAction(item.action, () => this._delegate.onSelectCodeAction(item));
const result = actionsToShow
.map(toCodeActionAction);
const allDocumentation = [...documentation];
const model = this._editor.getModel();
if (model && result.length) {
for (const provider of modes_1.CodeActionProviderRegistry.all(model)) {
if (provider._getAdditionalMenuItems) {
allDocumentation.push(...provider._getAdditionalMenuItems({ trigger: trigger.type, only: (_b = (_a = trigger.filter) === null || _a === void 0 ? void 0 : _a.include) === null || _b === void 0 ? void 0 : _b.value }, actionsToShow.map(item => item.action)));
}
}
}
if (allDocumentation.length) {
result.push(new actions_1.Separator(), ...allDocumentation.map(command => toCodeActionAction(new codeAction_1.CodeActionItem({
title: command.title,
command: command,
}, undefined))));
}
return result;
}
_toCoords(position) {
if (!this._editor.hasModel()) {
return { x: 0, y: 0 };
}
this._editor.revealPosition(position, 1 /* 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 };
}
};
CodeActionMenu = __decorate([
__param(2, contextView_1.IContextMenuService),
__param(3, keybinding_1.IKeybindingService)
], CodeActionMenu);
exports.CodeActionMenu = CodeActionMenu;
class CodeActionKeybindingResolver {
constructor(_keybindingProvider) {
this._keybindingProvider = _keybindingProvider;
}
getResolver() {
// Lazy since we may not actually ever read the value
const allCodeActionBindings = new lazy_1.Lazy(() => this._keybindingProvider.getKeybindings()
.filter(item => CodeActionKeybindingResolver.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 Object.assign({ resolvedKeybinding: item.resolvedKeybinding }, types_1.CodeActionCommandArgs.fromUser(commandArgs, {
kind: types_1.CodeActionKind.None,
apply: "never" /* Never */
}));
}));
return (action) => {
if (action.kind) {
const binding = this.bestKeybindingForCodeAction(action, allCodeActionBindings.getValue());
return binding === null || binding === void 0 ? void 0 : binding.resolvedKeybinding;
}
return undefined;
};
}
bestKeybindingForCodeAction(action, candidates) {
if (!action.kind) {
return undefined;
}
const kind = new types_1.CodeActionKind(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;
CodeActionKeybindingResolver.codeActionCommands = [
codeAction_1.refactorCommandId,
codeAction_1.codeActionCommandId,
codeAction_1.sourceActionCommandId,
codeAction_1.organizeImportsCommandId,
codeAction_1.fixAllCommandId
];
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
define(__m[631/*vs/editor/contrib/codeAction/codeActionModel*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,12/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,43/*vs/base/common/resources*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/modes*/,16/*vs/platform/contextkey/common/contextkey*/,59/*vs/platform/progress/common/progress*/,151/*vs/editor/contrib/codeAction/codeAction*/]), function (require, exports, async_1, errors_1, event_1, lifecycle_1, resources_1, range_1, modes_1, contextkey_1, progress_1, codeAction_1) {
"use strict";
var _CodeActionModel_isDisposed;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeActionModel = exports.CodeActionsState = exports.SUPPORTED_CODE_ACTIONS = void 0;
exports.SUPPORTED_CODE_ACTIONS = new contextkey_1.RawContextKey('supportedCodeAction', '');
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._onCursorChange()));
}
trigger(trigger) {
const selection = this._getRangeOfSelectionUnlessWhitespaceEnclosed(trigger);
return this._createEventAndSignalChange(trigger, selection);
}
_onMarkerChanges(resources) {
const model = this._editor.getModel();
if (!model) {
return;
}
if (resources.some(resource => (0, resources_1.isEqual)(resource, model.uri))) {
this._autoTriggerTimer.cancelAndSet(() => {
this.trigger({ type: 2 /* Auto */ });
}, this._delay);
}
}
_onCursorChange() {
this._autoTriggerTimer.cancelAndSet(() => {
this.trigger({ type: 2 /* Auto */ });
}, this._delay);
}
_getRangeOfMarker(selection) {
const model = this._editor.getModel();
if (!model) {
return undefined;
}
for (const marker of this._markerService.read({ resource: model.uri })) {
const markerRange = model.validateRange(marker);
if (range_1.Range.intersectRanges(markerRange, selection)) {
return range_1.Range.lift(markerRange);
}
}
return undefined;
}
_getRangeOfSelectionUnlessWhitespaceEnclosed(trigger) {
if (!this._editor.hasModel()) {
return undefined;
}
const model = this._editor.getModel();
const selection = this._editor.getSelection();
if (selection.isEmpty() && trigger.type === 2 /* Auto */) {
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;
}
_createEventAndSignalChange(trigger, selection) {
const model = this._editor.getModel();
if (!selection || !model) {
// cancel
this._signalChange(undefined);
return undefined;
}
const markerRange = this._getRangeOfMarker(selection);
const position = markerRange ? markerRange.getStartPosition() : selection.getStartPosition();
const e = {
trigger,
selection,
position
};
this._signalChange(e);
return e;
}
}
var CodeActionsState;
(function (CodeActionsState) {
CodeActionsState.Empty = { type: 0 /* Empty */ };
class Triggered {
constructor(trigger, rangeOrSelection, position, _cancellablePromise) {
this.trigger = trigger;
this.rangeOrSelection = rangeOrSelection;
this.position = position;
this._cancellablePromise = _cancellablePromise;
this.type = 1 /* Triggered */;
this.actions = _cancellablePromise.catch((e) => {
if ((0, errors_1.isPromiseCanceledError)(e)) {
return emptyCodeActionSet;
}
throw e;
});
}
cancel() {
this._cancellablePromise.cancel();
}
}
CodeActionsState.Triggered = Triggered;
})(CodeActionsState = exports.CodeActionsState || (exports.CodeActionsState = {}));
const emptyCodeActionSet = {
allActions: [],
validActions: [],
dispose: () => { },
documentation: [],
hasAutoFix: false
};
class CodeActionModel extends lifecycle_1.Disposable {
constructor(_editor, _markerService, contextKeyService, _progressService) {
super();
this._editor = _editor;
this._markerService = _markerService;
this._progressService = _progressService;
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;
_CodeActionModel_isDisposed.set(this, 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(modes_1.CodeActionProviderRegistry.onDidChange(() => this._update()));
this._update();
}
dispose() {
if (__classPrivateFieldGet(this, _CodeActionModel_isDisposed, "f")) {
return;
}
__classPrivateFieldSet(this, _CodeActionModel_isDisposed, true, "f");
super.dispose();
this.setState(CodeActionsState.Empty, true);
}
_update() {
if (__classPrivateFieldGet(this, _CodeActionModel_isDisposed, "f")) {
return;
}
this._codeActionOracle.value = undefined;
this.setState(CodeActionsState.Empty);
const model = this._editor.getModel();
if (model
&& modes_1.CodeActionProviderRegistry.has(model)
&& !this._editor.getOption(79 /* readOnly */)) {
const supportedActions = [];
for (const provider of modes_1.CodeActionProviderRegistry.all(model)) {
if (Array.isArray(provider.providedCodeActionKinds)) {
supportedActions.push(...provider.providedCodeActionKinds);
}
}
this._supportedCodeActions.set(supportedActions.join(' '));
this._codeActionOracle.value = new CodeActionOracle(this._editor, this._markerService, trigger => {
var _a;
if (!trigger) {
this.setState(CodeActionsState.Empty);
return;
}
const actions = (0, async_1.createCancelablePromise)(token => (0, codeAction_1.getCodeActions)(model, trigger.selection, trigger.trigger, progress_1.Progress.None, token));
if (trigger.trigger.type === 1 /* Invoke */) {
(_a = this._progressService) === null || _a === void 0 ? void 0 : _a.showWhile(actions, 250);
}
this.setState(new CodeActionsState.Triggered(trigger.trigger, trigger.selection, trigger.position, actions));
}, undefined);
this._codeActionOracle.value.trigger({ type: 2 /* Auto */ });
}
else {
this._supportedCodeActions.reset();
}
}
trigger(trigger) {
if (this._codeActionOracle.value) {
this._codeActionOracle.value.trigger(trigger);
}
}
setState(newState, skipNotify) {
if (newState === this._state) {
return;
}
// Cancel old request
if (this._state.type === 1 /* Triggered */) {
this._state.cancel();
}
this._state = newState;
if (!skipNotify && !__classPrivateFieldGet(this, _CodeActionModel_isDisposed, "f")) {
this._onDidChangeState.fire(newState);
}
}
}
exports.CodeActionModel = CodeActionModel;
_CodeActionModel_isDisposed = 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[632/*vs/editor/contrib/codelens/codelensController*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,12/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,66/*vs/editor/browser/core/editorState*/,14/*vs/editor/browser/editorExtensions*/,18/*vs/editor/common/modes*/,251/*vs/editor/contrib/codelens/codelens*/,610/*vs/editor/contrib/codelens/codelensWidget*/,26/*vs/platform/commands/common/commands*/,34/*vs/platform/notification/common/notification*/,589/*vs/editor/contrib/codelens/codeLensCache*/,7/*vs/base/browser/dom*/,92/*vs/base/common/hash*/,78/*vs/platform/quickinput/common/quickInput*/,478/*vs/nls!vs/editor/contrib/codelens/codelensController*/,25/*vs/editor/common/editorContextKeys*/,139/*vs/editor/common/modes/languageFeatureRegistry*/]), function (require, exports, async_1, errors_1, lifecycle_1, editorState_1, editorExtensions_1, modes_1, codelens_1, codelensWidget_1, commands_1, notification_1, codeLensCache_1, dom, hash_1, quickInput_1, nls_1, editorContextKeys_1, languageFeatureRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeLensContribution = void 0;
let CodeLensContribution = class CodeLensContribution {
constructor(_editor, _commandService, _notificationService, _codeLensCache) {
this._editor = _editor;
this._commandService = _commandService;
this._notificationService = _notificationService;
this._codeLensCache = _codeLensCache;
this._disposables = new lifecycle_1.DisposableStore();
this._localToDispose = new lifecycle_1.DisposableStore();
this._lenses = [];
this._getCodeLensModelDelays = new languageFeatureRegistry_1.LanguageFeatureRequestDelays(modes_1.CodeLensProviderRegistry, 250, 2500);
this._oldCodeLensModels = new lifecycle_1.DisposableStore();
this._resolveCodeLensesDelays = new languageFeatureRegistry_1.LanguageFeatureRequestDelays(modes_1.CodeLensProviderRegistry, 250, 2500);
this._resolveCodeLensesScheduler = new async_1.RunOnceScheduler(() => this._resolveCodeLensesInViewport(), this._resolveCodeLensesDelays.min);
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(41 /* fontInfo */) || e.hasChanged(14 /* codeLensFontSize */) || e.hasChanged(13 /* codeLensFontFamily */)) {
this._updateLensStyle();
}
if (e.hasChanged(12 /* codeLens */)) {
this._onModelChange();
}
}));
this._disposables.add(modes_1.CodeLensProviderRegistry.onDidChange(this._onModelChange, this));
this._onModelChange();
this._styleClassName = '_' + (0, hash_1.hash)(this._editor.getId()).toString(16);
this._styleElement = dom.createStyleSheet(dom.isInShadowDOM(this._editor.getContainerDomNode())
? this._editor.getContainerDomNode()
: undefined);
this._updateLensStyle();
}
dispose() {
var _a;
this._localDispose();
this._disposables.dispose();
this._oldCodeLensModels.dispose();
(_a = this._currentCodeLensModel) === null || _a === void 0 ? void 0 : _a.dispose();
this._styleElement.remove();
}
_getLayoutInfo() {
let fontSize = this._editor.getOption(14 /* codeLensFontSize */);
let codeLensHeight;
if (!fontSize || fontSize < 5) {
fontSize = (this._editor.getOption(43 /* fontSize */) * .9) | 0;
codeLensHeight = this._editor.getOption(57 /* lineHeight */);
}
else {
codeLensHeight = (fontSize * Math.max(1.3, this._editor.getOption(57 /* lineHeight */) / this._editor.getOption(43 /* fontSize */))) | 0;
}
return { codeLensHeight, fontSize };
}
_updateLensStyle() {
const { codeLensHeight, fontSize } = this._getLayoutInfo();
const fontFamily = this._editor.getOption(13 /* codeLensFontFamily */);
const editorFontInfo = this._editor.getOption(41 /* fontInfo */);
const fontFamilyVar = `--codelens-font-family${this._styleClassName}`;
const fontFeaturesVar = `--codelens-font-features${this._styleClassName}`;
let newStyle = `
.monaco-editor .codelens-decoration.${this._styleClassName} { line-height: ${codeLensHeight}px; font-size: ${fontSize}px; padding-right: ${Math.round(fontSize * 0.5)}px; font-feature-settings: var(${fontFeaturesVar}) }
.monaco-editor .codelens-decoration.${this._styleClassName} span.codicon { line-height: ${codeLensHeight}px; font-size: ${fontSize}px; }
`;
if (fontFamily) {
newStyle += `.monaco-editor .codelens-decoration.${this._styleClassName} { font-family: var(${fontFamilyVar})}`;
}
this._styleElement.textContent = newStyle;
this._editor.getContainerDomNode().style.setProperty(fontFamilyVar, fontFamily !== null && fontFamily !== void 0 ? fontFamily : 'inherit');
this._editor.getContainerDomNode().style.setProperty(fontFeaturesVar, editorFontInfo.fontFeatureSettings);
//
this._editor.changeViewZones(accessor => {
for (let lens of this._lenses) {
lens.updateHeight(codeLensHeight, accessor);
}
});
}
_localDispose() {
var _a, _b, _c;
(_a = this._getCodeLensModelPromise) === null || _a === void 0 ? void 0 : _a.cancel();
this._getCodeLensModelPromise = undefined;
(_b = this._resolveCodeLensesPromise) === null || _b === void 0 ? void 0 : _b.cancel();
this._resolveCodeLensesPromise = undefined;
this._localToDispose.clear();
this._oldCodeLensModels.clear();
(_c = this._currentCodeLensModel) === null || _c === void 0 ? void 0 : _c.dispose();
}
_onModelChange() {
this._localDispose();
const model = this._editor.getModel();
if (!model) {
return;
}
if (!this._editor.getOption(12 /* codeLens */)) {
return;
}
const cachedLenses = this._codeLensCache.get(model);
if (cachedLenses) {
this._renderCodeLensSymbols(cachedLenses);
}
if (!modes_1.CodeLensProviderRegistry.has(model)) {
// no provider -> return but check with
// cached lenses. they expire after 30 seconds
if (cachedLenses) {
this._localToDispose.add((0, async_1.disposableTimeout)(() => {
const cachedLensesNow = this._codeLensCache.get(model);
if (cachedLenses === cachedLensesNow) {
this._codeLensCache.delete(model);
this._onModelChange();
}
}, 30 * 1000));
}
return;
}
for (const provider of modes_1.CodeLensProviderRegistry.all(model)) {
if (typeof provider.onDidChange === 'function') {
let registration = provider.onDidChange(() => scheduler.schedule());
this._localToDispose.add(registration);
}
}
const scheduler = new async_1.RunOnceScheduler(() => {
var _a;
const t1 = Date.now();
(_a = this._getCodeLensModelPromise) === null || _a === void 0 ? void 0 : _a.cancel();
this._getCodeLensModelPromise = (0, async_1.createCancelablePromise)(token => (0, codelens_1.getCodeLensModel)(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._getCodeLensModelDelays.update(model, Date.now() - t1);
scheduler.delay = newDelay;
// render lenses
this._renderCodeLensSymbols(result);
this._resolveCodeLensesInViewport();
}, errors_1.onUnexpectedError);
}, this._getCodeLensModelDelays.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 => {
let 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();
}
});
let 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();
}));
this._localToDispose.add(this._editor.onDidFocusEditorWidget(() => {
scheduler.schedule();
}));
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 = editorState_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 /* CONTENT_WIDGET */) {
return;
}
let target = e.target.element;
if ((target === null || target === void 0 ? void 0 : target.tagName) === 'SPAN') {
target = target.parentElement;
}
if ((target === null || target === void 0 ? void 0 : target.tagName) === 'A') {
for (const lens of this._lenses) {
let 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;
}
let maxLineNumber = this._editor.getModel().getLineCount();
let groups = [];
let lastGroup;
for (let symbol of symbols.lenses) {
let 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);
}
}
const scrollState = editorState_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) {
let symbolsLineNumber = groups[groupsIndex][0].symbol.range.startLineNumber;
let 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, this._styleClassName, 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, this._styleClassName, 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() {
var _a;
(_a = this._resolveCodeLensesPromise) === null || _a === void 0 ? void 0 : _a.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._resolveCodeLensesDelays.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;
}
});
}
getLenses() {
return this._lenses;
}
};
CodeLensContribution.ID = 'css.editor.codeLens';
CodeLensContribution = __decorate([
__param(1, commands_1.ICommandService),
__param(2, notification_1.INotificationService),
__param(3, codeLensCache_1.ICodeLensCache)
], CodeLensContribution);
exports.CodeLensContribution = CodeLensContribution;
(0, editorExtensions_1.registerEditorContribution)(CodeLensContribution.ID, CodeLensContribution);
(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)(0, null),
alias: 'Show CodeLens Commands For Current Line',
});
}
run(accessor, editor) {
return __awaiter(this, void 0, void 0, function* () {
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);
const items = [];
for (let lens of codelensController.getLenses()) {
if (lens.getLineNumber() === lineNumber) {
for (let item of lens.getItems()) {
const { command } = item.symbol;
if (command) {
items.push({
label: command.title,
command: command
});
}
}
}
}
if (items.length === 0) {
// We dont want an empty picker
return;
}
const item = yield quickInputService.pick(items, { canPickMany: false });
if (!item) {
// Nothing picked
return;
}
try {
yield commandService.executeCommand(item.command.id, ...(item.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[264/*vs/editor/contrib/colorPicker/colorDetector*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,29/*vs/base/common/color*/,12/*vs/base/common/errors*/,92/*vs/base/common/hash*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,28/*vs/editor/browser/services/codeEditorService*/,3/*vs/editor/common/core/range*/,31/*vs/editor/common/model/textModel*/,18/*vs/editor/common/modes*/,252/*vs/editor/contrib/colorPicker/color*/,38/*vs/platform/configuration/common/configuration*/]), function (require, exports, async_1, color_1, errors_1, hash_1, lifecycle_1, editorExtensions_1, codeEditorService_1, range_1, textModel_1, modes_1, color_2, configuration_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ColorDetector = void 0;
const MAX_DECORATORS = 500;
let ColorDetector = class ColorDetector extends lifecycle_1.Disposable {
constructor(_editor, _codeEditorService, _configurationService) {
super();
this._editor = _editor;
this._codeEditorService = _codeEditorService;
this._configurationService = _configurationService;
this._localToDispose = this._register(new lifecycle_1.DisposableStore());
this._decorationsIds = [];
this._colorDatas = new Map();
this._colorDecoratorIds = [];
this._decorationsTypes = new Set();
this._register(_editor.onDidChangeModel(() => {
this._isEnabled = this.isEnabled();
this.onModelChanged();
}));
this._register(_editor.onDidChangeModelLanguage(() => this.onModelChanged()));
this._register(modes_1.ColorProviderRegistry.onDidChange(() => this.onModelChanged()));
this._register(_editor.onDidChangeConfiguration(() => {
let prevIsEnabled = this._isEnabled;
this._isEnabled = this.isEnabled();
if (prevIsEnabled !== this._isEnabled) {
if (this._isEnabled) {
this.onModelChanged();
}
else {
this.removeAllDecorations();
}
}
}));
this._timeoutTimer = null;
this._computePromise = null;
this._isEnabled = this.isEnabled();
this.onModelChanged();
}
isEnabled() {
const model = this._editor.getModel();
if (!model) {
return false;
}
const languageId = model.getLanguageIdentifier();
// handle deprecated settings. [languageId].colorDecorators.enable
const deprecatedConfig = this._configurationService.getValue(languageId.language);
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(15 /* colorDecorators */);
}
static get(editor) {
return editor.getContribution(this.ID);
}
dispose() {
this.stop();
this.removeAllDecorations();
super.dispose();
}
onModelChanged() {
this.stop();
if (!this._isEnabled) {
return;
}
const model = this._editor.getModel();
if (!model || !modes_1.ColorProviderRegistry.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();
}, ColorDetector.RECOMPUTE_TIME);
}
}));
this.beginCompute();
}
beginCompute() {
this._computePromise = (0, async_1.createCancelablePromise)(token => {
const model = this._editor.getModel();
if (!model) {
return Promise.resolve([]);
}
return (0, color_2.getColors)(model, token);
});
this._computePromise.then((colorInfos) => {
this.updateDecorations(colorInfos);
this.updateColorDecorators(colorInfos);
this._computePromise = null;
}, errors_1.onUnexpectedError);
}
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._decorationsIds = this._editor.deltaDecorations(this._decorationsIds, decorations);
this._colorDatas = new Map();
this._decorationsIds.forEach((id, i) => this._colorDatas.set(id, colorDatas[i]));
}
updateColorDecorators(colorData) {
let decorations = [];
let newDecorationsTypes = {};
for (let i = 0; i < colorData.length && decorations.length < MAX_DECORATORS; 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);
let subKey = (0, hash_1.hash)(`rgba(${rgba.r},${rgba.g},${rgba.b},${rgba.a})`).toString(16);
let color = `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
let key = 'colorBox-' + subKey;
if (!this._decorationsTypes.has(key) && !newDecorationsTypes[key]) {
this._codeEditorService.registerDecorationType('color-detector-color', key, {
before: {
contentText: ' ',
border: 'solid 0.1em #000',
margin: '0.1em 0.2em 0 0.2em',
width: '0.8em',
height: '0.8em',
backgroundColor: color
},
dark: {
before: {
border: 'solid 0.1em #eee'
}
}
}, undefined, this._editor);
}
newDecorationsTypes[key] = true;
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: this._codeEditorService.resolveDecorationOptions(key, true)
});
}
this._decorationsTypes.forEach(subType => {
if (!newDecorationsTypes[subType]) {
this._codeEditorService.removeDecorationType(subType);
}
});
this._colorDecoratorIds = this._editor.deltaDecorations(this._colorDecoratorIds, decorations);
}
removeAllDecorations() {
this._decorationsIds = this._editor.deltaDecorations(this._decorationsIds, []);
this._colorDecoratorIds = this._editor.deltaDecorations(this._colorDecoratorIds, []);
this._decorationsTypes.forEach(subType => {
this._codeEditorService.removeDecorationType(subType);
});
}
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);
}
};
ColorDetector.ID = 'editor.contrib.colorDetector';
ColorDetector.RECOMPUTE_TIME = 1000; // ms
ColorDetector = __decorate([
__param(1, codeEditorService_1.ICodeEditorService),
__param(2, configuration_1.IConfigurationService)
], ColorDetector);
exports.ColorDetector = ColorDetector;
(0, editorExtensions_1.registerEditorContribution)(ColorDetector.ID, ColorDetector);
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/comment/comment*/], __M([0/*require*/,1/*exports*/,479/*vs/nls!vs/editor/contrib/comment/comment*/,41/*vs/base/common/keyCodes*/,14/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,25/*vs/editor/common/editorContextKeys*/,226/*vs/editor/contrib/comment/blockCommentCommand*/,409/*vs/editor/contrib/comment/lineCommentCommand*/,33/*vs/platform/actions/common/actions*/]), function (require, exports, nls, keyCodes_1, editorExtensions_1, range_1, editorContextKeys_1, blockCommentCommand_1, lineCommentCommand_1, 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) {
if (!editor.hasModel()) {
return;
}
const model = editor.getModel();
const commands = [];
const modelOptions = model.getOptions();
const commentsOptions = editor.getOption(17 /* 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(selection.selection, modelOptions.tabSize, this._type, commentsOptions.insertSpace, commentsOptions.ignoreEmptyLines, selection.ignoreFirstLine));
}
editor.pushUndoStop();
editor.executeCommands(this.id, commands);
editor.pushUndoStop();
}
}
class ToggleCommentLineAction extends CommentLineAction {
constructor() {
super(0 /* Toggle */, {
id: 'editor.action.commentLine',
label: nls.localize(0, null),
alias: 'Toggle Line Comment',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 85 /* US_SLASH */,
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarEditMenu,
group: '5_insert',
title: nls.localize(1, null),
order: 1
}
});
}
}
class AddLineCommentAction extends CommentLineAction {
constructor() {
super(1 /* ForceAdd */, {
id: 'editor.action.addCommentLine',
label: nls.localize(2, null),
alias: 'Add Line Comment',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 33 /* KEY_C */),
weight: 100 /* EditorContrib */
}
});
}
}
class RemoveLineCommentAction extends CommentLineAction {
constructor() {
super(2 /* ForceRemove */, {
id: 'editor.action.removeCommentLine',
label: nls.localize(3, null),
alias: 'Remove Line Comment',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 51 /* KEY_U */),
weight: 100 /* EditorContrib */
}
});
}
}
class BlockCommentAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.blockComment',
label: nls.localize(4, null),
alias: 'Toggle Block Comment',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 1024 /* Shift */ | 512 /* Alt */ | 31 /* KEY_A */,
linux: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 31 /* KEY_A */ },
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarEditMenu,
group: '5_insert',
title: nls.localize(5, null),
order: 2
}
});
}
run(accessor, editor) {
if (!editor.hasModel()) {
return;
}
const commentsOptions = editor.getOption(17 /* comments */);
const commands = [];
const selections = editor.getSelections();
for (const selection of selections) {
commands.push(new blockCommentCommand_1.BlockCommentCommand(selection, commentsOptions.insertSpace));
}
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[634/*vs/editor/contrib/contextmenu/contextmenu*/], __M([0/*require*/,1/*exports*/,480/*vs/nls!vs/editor/contrib/contextmenu/contextmenu*/,7/*vs/base/browser/dom*/,50/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,25/*vs/editor/common/editorContextKeys*/,33/*vs/platform/actions/common/actions*/,16/*vs/platform/contextkey/common/contextkey*/,69/*vs/platform/contextview/browser/contextView*/,37/*vs/platform/keybinding/common/keybinding*/,117/*vs/base/browser/ui/actionbar/actionViewItems*/,17/*vs/base/common/platform*/]), function (require, exports, nls, dom, actions_1, lifecycle_1, editorExtensions_1, editorContextKeys_1, actions_2, contextkey_1, contextView_1, keybinding_1, actionViewItems_1, platform_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextMenuController = void 0;
let ContextMenuController = class ContextMenuController {
constructor(editor, _contextMenuService, _contextViewService, _contextKeyService, _keybindingService, _menuService) {
this._contextMenuService = _contextMenuService;
this._contextViewService = _contextViewService;
this._contextKeyService = _contextKeyService;
this._keybindingService = _keybindingService;
this._menuService = _menuService;
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 (e.keyCode === 58 /* ContextMenu */) {
// Chrome is funny like that
e.preventDefault();
e.stopPropagation();
this.showContextMenu();
}
}));
}
static get(editor) {
return editor.getContribution(ContextMenuController.ID);
}
_onContextMenu(e) {
if (!this._editor.hasModel()) {
return;
}
if (!this._editor.getOption(18 /* 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 /* OVERLAY_WIDGET */) {
return; // allow native menu on widgets to support right click on input field for example in find
}
e.event.preventDefault();
if (e.target.type !== 6 /* CONTENT_TEXT */ && e.target.type !== 7 /* CONTENT_EMPTY */ && e.target.type !== 1 /* 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 /* TEXTAREA */) {
anchor = { x: e.event.posx - 1, width: 2, y: e.event.posy - 1, height: 2 };
}
// Show the context menu
this.showContextMenu(anchor);
}
showContextMenu(anchor) {
if (!this._editor.getOption(18 /* contextmenu */)) {
return; // Context menu is turned off through configuration
}
if (!this._editor.hasModel()) {
return;
}
if (!this._contextMenuService) {
this._editor.focus();
return; // We need the context menu service to function
}
// Find actions available for menu
const menuActions = this._getMenuActions(this._editor.getModel(), this._editor.isSimpleWidget ? actions_2.MenuId.SimpleEditorContext : actions_2.MenuId.EditorContext);
// 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 menu = this._menuService.createMenu(menuId, this._contextKeyService);
const groups = menu.getActions({ arg: model.uri });
menu.dispose();
// translate them into other actions
for (let 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, anchor = null) {
if (!this._editor.hasModel()) {
return;
}
// Disable hover
const oldHoverSetting = this._editor.getOption(51 /* hover */);
this._editor.updateOptions({
hover: {
enabled: false
}
});
if (!anchor) {
// Ensure selection is visible
this._editor.revealPosition(this._editor.getPosition(), 1 /* 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(113 /* useShadowDOM */) && !platform_1.isIOS; // Do not use shadow dom on IOS #122035
// Show menu
this._contextMenuIsBeingShownCount++;
this._contextMenuService.showContextMenu({
domForShadowRoot: useShadowDOM ? 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.focus();
this._editor.updateOptions({
hover: oldHoverSetting
});
}
});
}
_keybindingFor(action) {
return this._keybindingService.lookupKeybinding(action.id);
}
dispose() {
if (this._contextMenuIsBeingShownCount > 0) {
this._contextViewService.hideContextView();
}
this._toDispose.dispose();
}
};
ContextMenuController.ID = 'editor.contrib.contextmenu';
ContextMenuController = __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)
], ContextMenuController);
exports.ContextMenuController = ContextMenuController;
class ShowContextMenu extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.showContextMenu',
label: nls.localize(0, null),
alias: 'Show Editor Context Menu',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 1024 /* Shift */ | 68 /* F10 */,
weight: 100 /* EditorContrib */
}
});
}
run(accessor, editor) {
let contribution = ContextMenuController.get(editor);
contribution.showContextMenu();
}
}
(0, editorExtensions_1.registerEditorContribution)(ContextMenuController.ID, ContextMenuController);
(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[635/*vs/editor/contrib/cursorUndo/cursorUndo*/], __M([0/*require*/,1/*exports*/,481/*vs/nls!vs/editor/contrib/cursorUndo/cursorUndo*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,25/*vs/editor/common/editorContextKeys*/]), function (require, exports, nls, lifecycle_1, editorExtensions_1, editorContextKeys_1) {
"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 {
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();
}
}
}));
}
static get(editor) {
return editor.getContribution(CursorUndoRedoController.ID);
}
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;
CursorUndoRedoController.ID = 'editor.contrib.cursorUndoRedoController';
class CursorUndo extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'cursorUndo',
label: nls.localize(0, null),
alias: 'Cursor Undo',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 2048 /* CtrlCmd */ | 51 /* KEY_U */,
weight: 100 /* 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(1, null),
alias: 'Cursor Redo',
precondition: undefined
});
}
run(accessor, editor, args) {
CursorUndoRedoController.get(editor).cursorRedo();
}
}
exports.CursorRedo = CursorRedo;
(0, editorExtensions_1.registerEditorContribution)(CursorUndoRedoController.ID, CursorUndoRedoController);
(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[636/*vs/editor/contrib/dnd/dnd*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,14/*vs/editor/browser/editorExtensions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,410/*vs/editor/contrib/dnd/dragAndDropCommand*/,31/*vs/editor/common/model/textModel*/,348/*vs/css!vs/editor/contrib/dnd/dnd*/]), function (require, exports, lifecycle_1, platform_1, editorExtensions_1, position_1, range_1, selection_1, dragAndDropCommand_1, textModel_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 {
constructor(editor) {
super();
this._editor = editor;
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._dndDecorationIds = [];
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(29 /* dragAndDrop */) || this._editor.getOption(16 /* columnSelection */)) {
return;
}
if (hasTriggerModifier(e)) {
this._modifierPressed = true;
}
if (this._mouseDown && hasTriggerModifier(e)) {
this._editor.updateOptions({
mouseStyle: 'copy'
});
}
}
onEditorKeyUp(e) {
if (!this._editor.getOption(29 /* dragAndDrop */) || this._editor.getOption(16 /* 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) {
let target = mouseEvent.target;
if (this._dragSelection === null) {
const selections = this._editor.getSelections() || [];
let 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) {
let newCursorPosition = new position_1.Position(mouseEvent.target.position.lineNumber, mouseEvent.target.position.column);
if (this._dragSelection === null) {
let newSelections = null;
if (mouseEvent.event.shiftKey) {
let 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 /* 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;
}
showAt(position) {
let newDecorations = [{
range: new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column),
options: DragAndDropController._DECORATION_OPTIONS
}];
this._dndDecorationIds = this._editor.deltaDecorations(this._dndDecorationIds, newDecorations);
this._editor.revealPosition(position, 1 /* Immediate */);
}
_removeDecoration() {
this._dndDecorationIds = this._editor.deltaDecorations(this._dndDecorationIds, []);
}
_hitContent(target) {
return target.type === 6 /* CONTENT_TEXT */ ||
target.type === 7 /* CONTENT_EMPTY */;
}
_hitMargin(target) {
return target.type === 2 /* GUTTER_GLYPH_MARGIN */ ||
target.type === 3 /* GUTTER_LINE_NUMBERS */ ||
target.type === 4 /* GUTTER_LINE_DECORATIONS */;
}
dispose() {
this._removeDecoration();
this._dragSelection = null;
this._mouseDown = false;
this._modifierPressed = false;
super.dispose();
}
}
exports.DragAndDropController = DragAndDropController;
DragAndDropController.ID = 'editor.contrib.dragAndDrop';
DragAndDropController.TRIGGER_KEY_VALUE = platform_1.isMacintosh ? 6 /* Alt */ : 5 /* Ctrl */;
DragAndDropController._DECORATION_OPTIONS = textModel_1.ModelDecorationOptions.register({
description: 'dnd-target',
className: 'dnd-target'
});
(0, editorExtensions_1.registerEditorContribution)(DragAndDropController.ID, DragAndDropController);
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/fontZoom/fontZoom*/], __M([0/*require*/,1/*exports*/,486/*vs/nls!vs/editor/contrib/fontZoom/fontZoom*/,14/*vs/editor/browser/editorExtensions*/,133/*vs/editor/common/config/editorZoom*/]), function (require, exports, nls, editorExtensions_1, editorZoom_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class EditorFontZoomIn extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.fontZoomIn',
label: nls.localize(0, null),
alias: 'Editor Font Zoom In',
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(1, null),
alias: 'Editor Font Zoom Out',
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(2, null),
alias: 'Editor Font Zoom Reset',
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[265/*vs/editor/contrib/format/format*/], __M([0/*require*/,1/*exports*/,44/*vs/base/browser/ui/aria/aria*/,19/*vs/base/common/arrays*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,24/*vs/base/common/uri*/,66/*vs/editor/browser/core/editorState*/,111/*vs/editor/browser/editorBrowser*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,18/*vs/editor/common/modes*/,76/*vs/editor/common/services/editorWorkerService*/,36/*vs/editor/common/services/modelService*/,228/*vs/editor/contrib/format/formattingEdit*/,487/*vs/nls!vs/editor/contrib/format/format*/,546/*vs/platform/extensions/common/extensions*/,9/*vs/platform/instantiation/common/instantiation*/,72/*vs/base/common/linkedList*/,26/*vs/platform/commands/common/commands*/,20/*vs/base/common/types*/,54/*vs/base/common/iterator*/]), function (require, exports, aria_1, arrays_1, cancellation_1, errors_1, uri_1, editorState_1, editorBrowser_1, position_1, range_1, selection_1, modes_1, editorWorkerService_1, modelService_1, formattingEdit_1, nls, extensions_1, instantiation_1, linkedList_1, commands_1, types_1, iterator_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOnTypeFormattingEdits = exports.getDocumentFormattingEditsUntilResult = exports.getDocumentRangeFormattingEditsUntilResult = exports.formatDocumentWithProvider = exports.formatDocumentWithSelectedProvider = exports.formatDocumentRangesWithProvider = exports.formatDocumentRangesWithSelectedProvider = exports.FormattingConflicts = exports.getRealAndSyntheticDocumentFormattersOrdered = exports.alertFormattingEdits = void 0;
function alertFormattingEdits(edits) {
edits = edits.filter(edit => edit.range);
if (!edits.length) {
return;
}
let { range } = edits[0];
for (let i = 1; i < edits.length; i++) {
range = range_1.Range.plusRange(range, edits[i].range);
}
const { startLineNumber, endLineNumber } = range;
if (startLineNumber === endLineNumber) {
if (edits.length === 1) {
(0, aria_1.alert)(nls.localize(0, null, startLineNumber));
}
else {
(0, aria_1.alert)(nls.localize(1, null, edits.length, startLineNumber));
}
}
else {
if (edits.length === 1) {
(0, aria_1.alert)(nls.localize(2, null, startLineNumber, endLineNumber));
}
else {
(0, aria_1.alert)(nls.localize(3, null, edits.length, startLineNumber, endLineNumber));
}
}
}
exports.alertFormattingEdits = alertFormattingEdits;
function getRealAndSyntheticDocumentFormattersOrdered(model) {
const result = [];
const seen = new Set();
// (1) add all document formatter
const docFormatter = modes_1.DocumentFormattingEditProviderRegistry.ordered(model);
for (const formatter of docFormatter) {
result.push(formatter);
if (formatter.extensionId) {
seen.add(extensions_1.ExtensionIdentifier.toKey(formatter.extensionId));
}
}
// (2) add all range formatter as document formatter (unless the same extension already did that)
const rangeFormatter = modes_1.DocumentRangeFormattingEditProviderRegistry.ordered(model);
for (const formatter of rangeFormatter) {
if (formatter.extensionId) {
if (seen.has(extensions_1.ExtensionIdentifier.toKey(formatter.extensionId))) {
continue;
}
seen.add(extensions_1.ExtensionIdentifier.toKey(formatter.extensionId));
}
result.push({
displayName: formatter.displayName,
extensionId: formatter.extensionId,
provideDocumentFormattingEdits(model, options, token) {
return formatter.provideDocumentRangeFormattingEdits(model, model.getFullModelRange(), options, token);
}
});
}
return result;
}
exports.getRealAndSyntheticDocumentFormattersOrdered = getRealAndSyntheticDocumentFormattersOrdered;
class FormattingConflicts {
static setFormatterSelector(selector) {
const remove = FormattingConflicts._selectors.unshift(selector);
return { dispose: remove };
}
static select(formatter, document, mode) {
return __awaiter(this, void 0, void 0, function* () {
if (formatter.length === 0) {
return undefined;
}
const selector = iterator_1.Iterable.first(FormattingConflicts._selectors);
if (selector) {
return yield selector(formatter, document, mode);
}
return undefined;
});
}
}
exports.FormattingConflicts = FormattingConflicts;
FormattingConflicts._selectors = new linkedList_1.LinkedList();
function formatDocumentRangesWithSelectedProvider(accessor, editorOrModel, rangeOrRanges, mode, progress, token) {
return __awaiter(this, void 0, void 0, function* () {
const instaService = accessor.get(instantiation_1.IInstantiationService);
const model = (0, editorBrowser_1.isCodeEditor)(editorOrModel) ? editorOrModel.getModel() : editorOrModel;
const provider = modes_1.DocumentRangeFormattingEditProviderRegistry.ordered(model);
const selected = yield FormattingConflicts.select(provider, model, mode);
if (selected) {
progress.report(selected);
yield instaService.invokeFunction(formatDocumentRangesWithProvider, selected, editorOrModel, rangeOrRanges, token);
}
});
}
exports.formatDocumentRangesWithSelectedProvider = formatDocumentRangesWithSelectedProvider;
function formatDocumentRangesWithProvider(accessor, provider, editorOrModel, rangeOrRanges, token) {
return __awaiter(this, void 0, void 0, function* () {
const workerService = accessor.get(editorWorkerService_1.IEditorWorkerService);
let model;
let cts;
if ((0, editorBrowser_1.isCodeEditor)(editorOrModel)) {
model = editorOrModel.getModel();
cts = new editorState_1.EditorStateCancellationTokenSource(editorOrModel, 1 /* Value */ | 4 /* Position */, undefined, token);
}
else {
model = editorOrModel;
cts = new editorState_1.TextModelCancellationTokenSource(editorOrModel, token);
}
// make sure that ranges don't overlap nor touch each other
let ranges = [];
let len = 0;
for (let 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 = (range) => __awaiter(this, void 0, void 0, function* () {
return (yield provider.provideDocumentRangeFormattingEdits(model, range, model.getFormattingOptions(), cts.token)) || [];
});
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 (let edit of a) {
for (let otherEdit of b) {
if (range_1.Range.intersectRanges(edit.range, otherEdit.range)) {
return true;
}
}
}
return false;
};
const allEdits = [];
const rawEditsList = [];
try {
for (let range of ranges) {
if (cts.token.isCancellationRequested) {
return true;
}
rawEditsList.push(yield 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 = yield 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 (let rawEdits of rawEditsList) {
if (cts.token.isCancellationRequested) {
return true;
}
const minimalEdits = yield 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);
alertFormattingEdits(allEdits);
editorOrModel.revealPositionInCenterIfOutsideViewport(editorOrModel.getPosition(), 1 /* 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;
});
}
return true;
});
}
exports.formatDocumentRangesWithProvider = formatDocumentRangesWithProvider;
function formatDocumentWithSelectedProvider(accessor, editorOrModel, mode, progress, token) {
return __awaiter(this, void 0, void 0, function* () {
const instaService = accessor.get(instantiation_1.IInstantiationService);
const model = (0, editorBrowser_1.isCodeEditor)(editorOrModel) ? editorOrModel.getModel() : editorOrModel;
const provider = getRealAndSyntheticDocumentFormattersOrdered(model);
const selected = yield FormattingConflicts.select(provider, model, mode);
if (selected) {
progress.report(selected);
yield instaService.invokeFunction(formatDocumentWithProvider, selected, editorOrModel, mode, token);
}
});
}
exports.formatDocumentWithSelectedProvider = formatDocumentWithSelectedProvider;
function formatDocumentWithProvider(accessor, provider, editorOrModel, mode, token) {
return __awaiter(this, void 0, void 0, function* () {
const workerService = accessor.get(editorWorkerService_1.IEditorWorkerService);
let model;
let cts;
if ((0, editorBrowser_1.isCodeEditor)(editorOrModel)) {
model = editorOrModel.getModel();
cts = new editorState_1.EditorStateCancellationTokenSource(editorOrModel, 1 /* Value */ | 4 /* Position */, undefined, token);
}
else {
model = editorOrModel;
cts = new editorState_1.TextModelCancellationTokenSource(editorOrModel, token);
}
let edits;
try {
const rawEdits = yield provider.provideDocumentFormattingEdits(model, model.getFormattingOptions(), cts.token);
edits = yield 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 /* Silent */);
if (mode !== 2 /* Silent */) {
alertFormattingEdits(edits);
editorOrModel.revealPositionInCenterIfOutsideViewport(editorOrModel.getPosition(), 1 /* 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;
});
}
return true;
});
}
exports.formatDocumentWithProvider = formatDocumentWithProvider;
function getDocumentRangeFormattingEditsUntilResult(workerService, model, range, options, token) {
return __awaiter(this, void 0, void 0, function* () {
const providers = modes_1.DocumentRangeFormattingEditProviderRegistry.ordered(model);
for (const provider of providers) {
let rawEdits = yield Promise.resolve(provider.provideDocumentRangeFormattingEdits(model, range, options, token)).catch(errors_1.onUnexpectedExternalError);
if ((0, arrays_1.isNonEmptyArray)(rawEdits)) {
return yield workerService.computeMoreMinimalEdits(model.uri, rawEdits);
}
}
return undefined;
});
}
exports.getDocumentRangeFormattingEditsUntilResult = getDocumentRangeFormattingEditsUntilResult;
function getDocumentFormattingEditsUntilResult(workerService, model, options, token) {
return __awaiter(this, void 0, void 0, function* () {
const providers = getRealAndSyntheticDocumentFormattersOrdered(model);
for (const provider of providers) {
let rawEdits = yield Promise.resolve(provider.provideDocumentFormattingEdits(model, options, token)).catch(errors_1.onUnexpectedExternalError);
if ((0, arrays_1.isNonEmptyArray)(rawEdits)) {
return yield workerService.computeMoreMinimalEdits(model.uri, rawEdits);
}
}
return undefined;
});
}
exports.getDocumentFormattingEditsUntilResult = getDocumentFormattingEditsUntilResult;
function getOnTypeFormattingEdits(workerService, model, position, ch, options) {
const providers = modes_1.OnTypeFormattingEditProviderRegistry.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, cancellation_1.CancellationToken.None)).catch(errors_1.onUnexpectedExternalError).then(edits => {
return workerService.computeMoreMinimalEdits(model.uri, edits);
});
}
exports.getOnTypeFormattingEdits = getOnTypeFormattingEdits;
commands_1.CommandsRegistry.registerCommand('_executeFormatRangeProvider', 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 model = accessor.get(modelService_1.IModelService).getModel(resource);
if (!model) {
throw (0, errors_1.illegalArgument)('resource');
}
return getDocumentRangeFormattingEditsUntilResult(accessor.get(editorWorkerService_1.IEditorWorkerService), model, range_1.Range.lift(range), options, cancellation_1.CancellationToken.None);
});
commands_1.CommandsRegistry.registerCommand('_executeFormatDocumentProvider', function (accessor, ...args) {
const [resource, options] = args;
(0, types_1.assertType)(uri_1.URI.isUri(resource));
const model = accessor.get(modelService_1.IModelService).getModel(resource);
if (!model) {
throw (0, errors_1.illegalArgument)('resource');
}
return getDocumentFormattingEditsUntilResult(accessor.get(editorWorkerService_1.IEditorWorkerService), model, options, cancellation_1.CancellationToken.None);
});
commands_1.CommandsRegistry.registerCommand('_executeFormatOnTypeProvider', 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 model = accessor.get(modelService_1.IModelService).getModel(resource);
if (!model) {
throw (0, errors_1.illegalArgument)('resource');
}
return getOnTypeFormattingEdits(accessor.get(editorWorkerService_1.IEditorWorkerService), model, position_1.Position.lift(position), ch, 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[638/*vs/editor/contrib/format/formatActions*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,23/*vs/base/common/cancellation*/,41/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,28/*vs/editor/browser/services/codeEditorService*/,94/*vs/editor/common/core/characterClassifier*/,3/*vs/editor/common/core/range*/,25/*vs/editor/common/editorContextKeys*/,18/*vs/editor/common/modes*/,76/*vs/editor/common/services/editorWorkerService*/,265/*vs/editor/contrib/format/format*/,228/*vs/editor/contrib/format/formattingEdit*/,488/*vs/nls!vs/editor/contrib/format/formatActions*/,26/*vs/platform/commands/common/commands*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/,12/*vs/base/common/errors*/,59/*vs/platform/progress/common/progress*/]), function (require, exports, arrays_1, cancellation_1, keyCodes_1, lifecycle_1, editorExtensions_1, codeEditorService_1, characterClassifier_1, range_1, editorContextKeys_1, modes_1, editorWorkerService_1, format_1, formattingEdit_1, nls, commands_1, contextkey_1, instantiation_1, errors_1, progress_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let FormatOnType = class FormatOnType {
constructor(editor, _workerService) {
this._workerService = _workerService;
this._callOnDispose = new lifecycle_1.DisposableStore();
this._callOnModel = new lifecycle_1.DisposableStore();
this._editor = editor;
this._callOnDispose.add(editor.onDidChangeConfiguration(() => this._update()));
this._callOnDispose.add(editor.onDidChangeModel(() => this._update()));
this._callOnDispose.add(editor.onDidChangeModelLanguage(() => this._update()));
this._callOnDispose.add(modes_1.OnTypeFormattingEditProviderRegistry.onDidChange(this._update, this));
}
dispose() {
this._callOnDispose.dispose();
this._callOnModel.dispose();
}
_update() {
// clean up
this._callOnModel.clear();
// we are disabled
if (!this._editor.getOption(46 /* formatOnType */)) {
return;
}
// no model
if (!this._editor.hasModel()) {
return;
}
const model = this._editor.getModel();
// no support
const [support] = modes_1.OnTypeFormattingEditProviderRegistry.ordered(model);
if (!support || !support.autoFormatTriggerCharacters) {
return;
}
// register typing listeners that will trigger the format
let triggerChars = new characterClassifier_1.CharacterSet();
for (let ch of support.autoFormatTriggerCharacters) {
triggerChars.add(ch.charCodeAt(0));
}
this._callOnModel.add(this._editor.onDidType((text) => {
let 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) {
return;
}
const model = this._editor.getModel();
const position = this._editor.getPosition();
let canceled = false;
// 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
canceled = true;
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
canceled = true;
unbind.dispose();
return;
}
}
});
(0, format_1.getOnTypeFormattingEdits)(this._workerService, model, position, ch, model.getFormattingOptions()).then(edits => {
unbind.dispose();
if (canceled) {
return;
}
if ((0, arrays_1.isNonEmptyArray)(edits)) {
formattingEdit_1.FormattingEdit.execute(this._editor, edits, true);
(0, format_1.alertFormattingEdits)(edits);
}
}, (err) => {
unbind.dispose();
throw err;
});
}
};
FormatOnType.ID = 'editor.contrib.autoFormat';
FormatOnType = __decorate([
__param(1, editorWorkerService_1.IEditorWorkerService)
], FormatOnType);
let FormatOnPaste = class FormatOnPaste {
constructor(editor, _instantiationService) {
this.editor = editor;
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(modes_1.DocumentRangeFormattingEditProviderRegistry.onDidChange(this._update, this));
}
dispose() {
this._callOnDispose.dispose();
this._callOnModel.dispose();
}
_update() {
// clean up
this._callOnModel.clear();
// we are disabled
if (!this.editor.getOption(45 /* formatOnPaste */)) {
return;
}
// no model
if (!this.editor.hasModel()) {
return;
}
// no formatter
if (!modes_1.DocumentRangeFormattingEditProviderRegistry.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 /* Silent */, progress_1.Progress.None, cancellation_1.CancellationToken.None).catch(errors_1.onUnexpectedError);
}
};
FormatOnPaste.ID = 'editor.contrib.formatOnPaste';
FormatOnPaste = __decorate([
__param(1, instantiation_1.IInstantiationService)
], FormatOnPaste);
class FormatDocumentAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.formatDocument',
label: nls.localize(0, null),
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 /* Shift */ | 512 /* Alt */ | 36 /* KEY_F */,
linux: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 39 /* KEY_I */ },
weight: 100 /* EditorContrib */
},
contextMenuOpts: {
group: '1_modification',
order: 1.3
}
});
}
run(accessor, editor) {
return __awaiter(this, void 0, void 0, function* () {
if (editor.hasModel()) {
const instaService = accessor.get(instantiation_1.IInstantiationService);
const progressService = accessor.get(progress_1.IEditorProgressService);
yield progressService.showWhile(instaService.invokeFunction(format_1.formatDocumentWithSelectedProvider, editor, 1 /* Explicit */, progress_1.Progress.None, cancellation_1.CancellationToken.None), 250);
}
});
}
}
class FormatSelectionAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.formatSelection',
label: nls.localize(1, null),
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 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 36 /* KEY_F */),
weight: 100 /* EditorContrib */
},
contextMenuOpts: {
when: editorContextKeys_1.EditorContextKeys.hasNonEmptySelection,
group: '1_modification',
order: 1.31
}
});
}
run(accessor, editor) {
return __awaiter(this, void 0, void 0, function* () {
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);
yield progressService.showWhile(instaService.invokeFunction(format_1.formatDocumentRangesWithSelectedProvider, editor, ranges, 1 /* Explicit */, progress_1.Progress.None, cancellation_1.CancellationToken.None), 250);
});
}
}
(0, editorExtensions_1.registerEditorContribution)(FormatOnType.ID, FormatOnType);
(0, editorExtensions_1.registerEditorContribution)(FormatOnPaste.ID, FormatOnPaste);
(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', (accessor) => __awaiter(void 0, void 0, void 0, function* () {
const editor = accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor();
if (!editor || !editor.hasModel()) {
return;
}
const commandService = accessor.get(commands_1.ICommandService);
if (editor.getSelection().isEmpty()) {
yield commandService.executeCommand('editor.action.formatDocument');
}
else {
yield 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[266/*vs/editor/contrib/gotoSymbol/goToSymbol*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,14/*vs/editor/browser/editorExtensions*/,18/*vs/editor/common/modes*/,118/*vs/editor/contrib/gotoSymbol/referencesModel*/]), function (require, exports, cancellation_1, errors_1, editorExtensions_1, modes_1, referencesModel_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getReferencesAtPosition = exports.getTypeDefinitionsAtPosition = exports.getImplementationsAtPosition = exports.getDeclarationsAtPosition = exports.getDefinitionsAtPosition = void 0;
function getLocationLinks(model, position, registry, provide) {
const provider = registry.ordered(model);
// get results
const promises = provider.map((provider) => {
return Promise.resolve(provide(provider, model, position)).then(undefined, err => {
(0, errors_1.onUnexpectedExternalError)(err);
return undefined;
});
});
return Promise.all(promises).then(values => {
const result = [];
for (let value of values) {
if (Array.isArray(value)) {
result.push(...value);
}
else if (value) {
result.push(value);
}
}
return result;
});
}
function getDefinitionsAtPosition(model, position, token) {
return getLocationLinks(model, position, modes_1.DefinitionProviderRegistry, (provider, model, position) => {
return provider.provideDefinition(model, position, token);
});
}
exports.getDefinitionsAtPosition = getDefinitionsAtPosition;
function getDeclarationsAtPosition(model, position, token) {
return getLocationLinks(model, position, modes_1.DeclarationProviderRegistry, (provider, model, position) => {
return provider.provideDeclaration(model, position, token);
});
}
exports.getDeclarationsAtPosition = getDeclarationsAtPosition;
function getImplementationsAtPosition(model, position, token) {
return getLocationLinks(model, position, modes_1.ImplementationProviderRegistry, (provider, model, position) => {
return provider.provideImplementation(model, position, token);
});
}
exports.getImplementationsAtPosition = getImplementationsAtPosition;
function getTypeDefinitionsAtPosition(model, position, token) {
return getLocationLinks(model, position, modes_1.TypeDefinitionProviderRegistry, (provider, model, position) => {
return provider.provideTypeDefinition(model, position, token);
});
}
exports.getTypeDefinitionsAtPosition = getTypeDefinitionsAtPosition;
function getReferencesAtPosition(model, position, compact, token) {
return getLocationLinks(model, position, modes_1.ReferenceProviderRegistry, (provider, model, position) => __awaiter(this, void 0, void 0, function* () {
const result = yield provider.provideReferences(model, position, { includeDeclaration: true }, token);
if (!compact || !result || result.length !== 2) {
return result;
}
const resultWithoutDeclaration = yield provider.provideReferences(model, position, { includeDeclaration: false }, token);
if (resultWithoutDeclaration && resultWithoutDeclaration.length === 1) {
return resultWithoutDeclaration;
}
return result;
}));
}
exports.getReferencesAtPosition = getReferencesAtPosition;
// -- API commands ----
function _sortedAndDeduped(callback) {
return __awaiter(this, void 0, void 0, function* () {
const rawLinks = yield 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', (model, position) => _sortedAndDeduped(() => getDefinitionsAtPosition(model, position, cancellation_1.CancellationToken.None)));
(0, editorExtensions_1.registerModelAndPositionCommand)('_executeDeclarationProvider', (model, position) => _sortedAndDeduped(() => getDeclarationsAtPosition(model, position, cancellation_1.CancellationToken.None)));
(0, editorExtensions_1.registerModelAndPositionCommand)('_executeImplementationProvider', (model, position) => _sortedAndDeduped(() => getImplementationsAtPosition(model, position, cancellation_1.CancellationToken.None)));
(0, editorExtensions_1.registerModelAndPositionCommand)('_executeTypeDefinitionProvider', (model, position) => _sortedAndDeduped(() => getTypeDefinitionsAtPosition(model, position, cancellation_1.CancellationToken.None)));
(0, editorExtensions_1.registerModelAndPositionCommand)('_executeReferenceProvider', (model, position) => _sortedAndDeduped(() => getReferencesAtPosition(model, position, false, cancellation_1.CancellationToken.None)));
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/gotoSymbol/symbolNavigation*/], __M([0/*require*/,1/*exports*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/,75/*vs/platform/instantiation/common/extensions*/,88/*vs/platform/keybinding/common/keybindingsRegistry*/,14/*vs/editor/browser/editorExtensions*/,28/*vs/editor/browser/services/codeEditorService*/,3/*vs/editor/common/core/range*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/,497/*vs/nls!vs/editor/contrib/gotoSymbol/symbolNavigation*/,37/*vs/platform/keybinding/common/keybinding*/,34/*vs/platform/notification/common/notification*/,43/*vs/base/common/resources*/]), function (require, exports, contextkey_1, instantiation_1, extensions_1, keybindingsRegistry_1, editorExtensions_1, codeEditorService_1, range_1, lifecycle_1, event_1, nls_1, keybinding_1, notification_1, resources_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)(0, null));
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() {
var _a, _b;
this._ctxHasSymbols.reset();
(_a = this._currentState) === null || _a === void 0 ? void 0 : _a.dispose();
(_b = this._currentMessage) === null || _b === void 0 ? void 0 : _b.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 /* NearTopIfOutsideViewport */
}
}, source).finally(() => {
this._ignoreEditorChange = false;
});
}
_showMessage() {
var _a;
(_a = this._currentMessage) === null || _a === void 0 ? void 0 : _a.dispose();
const kb = this._keybindingService.lookupKeybinding('editor.gotoNextSymbolFromResult');
const message = kb
? (0, nls_1.localize)(1, null, this._currentIdx + 1, this._currentModel.references.length, kb.getLabel())
: (0, nls_1.localize)(2, null, 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, true);
(0, editorExtensions_1.registerEditorCommand)(new class extends editorExtensions_1.EditorCommand {
constructor() {
super({
id: 'editor.gotoNextSymbolFromResult',
precondition: exports.ctxHasSymbols,
kbOpts: {
weight: 100 /* EditorContrib */,
primary: 70 /* F12 */
}
});
}
runEditorCommand(accessor, editor) {
return accessor.get(exports.ISymbolNavigationService).revealNext(editor);
}
});
keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'editor.gotoNextSymbolFromResult.cancel',
weight: 100 /* EditorContrib */,
when: exports.ctxHasSymbols,
primary: 9 /* 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) {
var _a;
(_a = this._listener.get(editor)) === null || _a === void 0 ? void 0 : _a.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[640/*vs/editor/contrib/hover/colorHoverParticipant*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/,23/*vs/base/common/cancellation*/,252/*vs/editor/contrib/colorPicker/color*/,264/*vs/editor/contrib/colorPicker/colorDetector*/,29/*vs/base/common/color*/,408/*vs/editor/contrib/colorPicker/colorPickerModel*/,611/*vs/editor/contrib/colorPicker/colorPickerWidget*/,11/*vs/platform/theme/common/themeService*/]), function (require, exports, lifecycle_1, range_1, cancellation_1, color_1, colorDetector_1, color_2, colorPickerModel_1, colorPickerWidget_1, themeService_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
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 /* Range */
&& this.range.startColumn <= anchor.range.startColumn
&& this.range.endColumn >= anchor.range.endColumn);
}
}
exports.ColorHover = ColorHover;
let ColorHoverParticipant = class ColorHoverParticipant {
constructor(_editor, _hover, _themeService) {
this._editor = _editor;
this._hover = _hover;
this._themeService = _themeService;
}
computeSync(anchor, lineDecorations) {
return [];
}
computeAsync(anchor, lineDecorations, token) {
return __awaiter(this, void 0, void 0, function* () {
if (!this._editor.hasModel()) {
return [];
}
const colorDetector = colorDetector_1.ColorDetector.get(this._editor);
for (const d of lineDecorations) {
const colorData = colorDetector.getColorData(d.range.getStartPosition());
if (colorData) {
const colorHover = yield this._createColorHover(this._editor.getModel(), colorData.colorInfo, colorData.provider);
return [colorHover];
}
}
return [];
});
}
_createColorHover(editorModel, colorInfo, provider) {
return __awaiter(this, void 0, void 0, function* () {
const originalText = editorModel.getValueInRange(colorInfo.range);
const { red, green, blue, alpha } = colorInfo.color;
const rgba = new color_2.RGBA(Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255), alpha);
const color = new color_2.Color(rgba);
const colorPresentations = yield (0, color_1.getColorPresentations)(editorModel, colorInfo, provider, cancellation_1.CancellationToken.None);
const model = new colorPickerModel_1.ColorPickerModel(color, [], 0);
model.colorPresentations = colorPresentations || [];
model.guessColorPresentation(color, originalText);
return new ColorHover(this, range_1.Range.lift(colorInfo.range), model, provider);
});
}
renderHoverParts(hoverParts, fragment, statusBar) {
if (hoverParts.length === 0 || !this._editor.hasModel()) {
return lifecycle_1.Disposable.None;
}
const disposables = new lifecycle_1.DisposableStore();
const colorHover = hoverParts[0];
const editorModel = this._editor.getModel();
const model = colorHover.model;
const widget = disposables.add(new colorPickerWidget_1.ColorPickerWidget(fragment, model, this._editor.getOption(127 /* pixelRatio */), this._themeService));
let range = new range_1.Range(colorHover.range.startLineNumber, colorHover.range.startColumn, colorHover.range.endLineNumber, colorHover.range.endColumn);
const updateEditorModel = () => {
let textEdits;
let newRange;
if (model.presentation.textEdit) {
textEdits = [model.presentation.textEdit];
newRange = new range_1.Range(model.presentation.textEdit.range.startLineNumber, model.presentation.textEdit.range.startColumn, model.presentation.textEdit.range.endLineNumber, model.presentation.textEdit.range.endColumn);
const trackedRange = this._editor.getModel()._setTrackedRange(null, newRange, 3 /* GrowsOnlyWhenTypingAfter */);
this._editor.pushUndoStop();
this._editor.executeEdits('colorpicker', textEdits);
newRange = this._editor.getModel()._getTrackedRange(trackedRange) || newRange;
}
else {
textEdits = [{ identifier: null, range, text: model.presentation.label, forceMoveMarkers: false }];
newRange = range.setEndPosition(range.endLineNumber, range.startColumn + model.presentation.label.length);
this._editor.pushUndoStop();
this._editor.executeEdits('colorpicker', textEdits);
}
if (model.presentation.additionalTextEdits) {
textEdits = [...model.presentation.additionalTextEdits];
this._editor.executeEdits('colorpicker', textEdits);
this._hover.hide();
}
this._editor.pushUndoStop();
range = newRange;
};
const updateColorPresentations = (color) => {
return (0, color_1.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).then((colorPresentations) => {
model.colorPresentations = colorPresentations || [];
});
};
disposables.add(model.onColorFlushed((color) => {
updateColorPresentations(color).then(updateEditorModel);
}));
disposables.add(model.onDidChangeColor(updateColorPresentations));
this._hover.setColorPicker(widget);
return disposables;
}
};
ColorHoverParticipant = __decorate([
__param(2, themeService_1.IThemeService)
], ColorHoverParticipant);
exports.ColorHoverParticipant = 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[641/*vs/editor/contrib/hover/getHover*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,14/*vs/editor/browser/editorExtensions*/,18/*vs/editor/common/modes*/]), function (require, exports, arrays_1, cancellation_1, errors_1, editorExtensions_1, modes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getHover = void 0;
function getHover(model, position, token) {
const supports = modes_1.HoverProviderRegistry.ordered(model);
const promises = supports.map(support => {
return Promise.resolve(support.provideHover(model, position, token)).then(hover => {
return hover && isValid(hover) ? hover : undefined;
}, err => {
(0, errors_1.onUnexpectedExternalError)(err);
return undefined;
});
});
return Promise.all(promises).then(arrays_1.coalesce);
}
exports.getHover = getHover;
(0, editorExtensions_1.registerModelAndPositionCommand)('_executeHoverProvider', (model, position) => getHover(model, position, cancellation_1.CancellationToken.None));
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[642/*vs/editor/contrib/hover/markdownHoverParticipant*/], __M([0/*require*/,1/*exports*/,499/*vs/nls!vs/editor/contrib/hover/markdownHoverParticipant*/,7/*vs/base/browser/dom*/,82/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/,145/*vs/editor/browser/core/markdownRenderer*/,19/*vs/base/common/arrays*/,58/*vs/platform/opener/common/opener*/,57/*vs/editor/common/services/modeService*/,18/*vs/editor/common/modes*/,641/*vs/editor/contrib/hover/getHover*/,13/*vs/editor/common/core/position*/,38/*vs/platform/configuration/common/configuration*/]), function (require, exports, nls, dom, htmlContent_1, lifecycle_1, range_1, markdownRenderer_1, arrays_1, opener_1, modeService_1, modes_1, getHover_1, position_1, configuration_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MarkdownHoverParticipant = exports.MarkdownHover = void 0;
const $ = dom.$;
class MarkdownHover {
constructor(owner, range, contents) {
this.owner = owner;
this.range = range;
this.contents = contents;
}
isValidForHoverAnchor(anchor) {
return (anchor.type === 1 /* Range */
&& this.range.startColumn <= anchor.range.startColumn
&& this.range.endColumn >= anchor.range.endColumn);
}
}
exports.MarkdownHover = MarkdownHover;
let MarkdownHoverParticipant = class MarkdownHoverParticipant {
constructor(_editor, _hover, _modeService, _openerService, _configurationService) {
this._editor = _editor;
this._hover = _hover;
this._modeService = _modeService;
this._openerService = _openerService;
this._configurationService = _configurationService;
}
createLoadingMessage(anchor) {
return new MarkdownHover(this, anchor.range, [new htmlContent_1.MarkdownString().appendText(nls.localize(0, null))]);
}
computeSync(anchor, lineDecorations) {
if (!this._editor.hasModel() || anchor.type !== 1 /* Range */) {
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 hoverMessage = d.options.hoverMessage;
if (!hoverMessage || (0, htmlContent_1.isEmptyMarkdownString)(hoverMessage)) {
continue;
}
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)));
}
const lineLength = this._editor.getModel().getLineLength(lineNumber);
const maxTokenizationLineLength = this._configurationService.getValue('editor.maxTokenizationLineLength');
if (typeof maxTokenizationLineLength === 'number' && lineLength >= maxTokenizationLineLength) {
result.push(new MarkdownHover(this, new range_1.Range(lineNumber, 1, lineNumber, lineLength + 1), [{
value: nls.localize(1, null)
}]));
}
return result;
}
computeAsync(anchor, lineDecorations, token) {
return __awaiter(this, void 0, void 0, function* () {
if (!this._editor.hasModel() || anchor.type !== 1 /* Range */) {
return Promise.resolve([]);
}
const model = this._editor.getModel();
if (!modes_1.HoverProviderRegistry.has(model)) {
return Promise.resolve([]);
}
const hovers = yield (0, getHover_1.getHover)(model, new position_1.Position(anchor.range.startLineNumber, anchor.range.startColumn), token);
const result = [];
for (const hover of hovers) {
if ((0, htmlContent_1.isEmptyMarkdownString)(hover.contents)) {
continue;
}
const rng = hover.range ? range_1.Range.lift(hover.range) : anchor.range;
result.push(new MarkdownHover(this, rng, hover.contents));
}
return result;
});
}
renderHoverParts(hoverParts, fragment, statusBar) {
const disposables = new lifecycle_1.DisposableStore();
for (const hoverPart of hoverParts) {
for (const contents of hoverPart.contents) {
if ((0, htmlContent_1.isEmptyMarkdownString)(contents)) {
continue;
}
const markdownHoverElement = $('div.hover-row.markdown-hover');
const hoverContentsElement = dom.append(markdownHoverElement, $('div.hover-contents'));
const renderer = disposables.add(new markdownRenderer_1.MarkdownRenderer({ editor: this._editor }, this._modeService, this._openerService));
disposables.add(renderer.onDidRenderAsync(() => {
hoverContentsElement.className = 'hover-contents code-hover-contents';
this._hover.onContentsChanged();
}));
const renderedContents = disposables.add(renderer.render(contents));
hoverContentsElement.appendChild(renderedContents.element);
fragment.appendChild(markdownHoverElement);
}
}
return disposables;
}
};
MarkdownHoverParticipant = __decorate([
__param(2, modeService_1.IModeService),
__param(3, opener_1.IOpenerService),
__param(4, configuration_1.IConfigurationService)
], MarkdownHoverParticipant);
exports.MarkdownHoverParticipant = MarkdownHoverParticipant;
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/inPlaceReplace/inPlaceReplace*/], __M([0/*require*/,1/*exports*/,501/*vs/nls!vs/editor/contrib/inPlaceReplace/inPlaceReplace*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,25/*vs/editor/common/editorContextKeys*/,14/*vs/editor/browser/editorExtensions*/,76/*vs/editor/common/services/editorWorkerService*/,417/*vs/editor/contrib/inPlaceReplace/inPlaceReplaceCommand*/,66/*vs/editor/browser/core/editorState*/,11/*vs/platform/theme/common/themeService*/,48/*vs/editor/common/view/editorColorRegistry*/,31/*vs/editor/common/model/textModel*/,15/*vs/base/common/async*/,12/*vs/base/common/errors*/]), function (require, exports, nls, range_1, selection_1, editorContextKeys_1, editorExtensions_1, editorWorkerService_1, inPlaceReplaceCommand_1, editorState_1, themeService_1, editorColorRegistry_1, textModel_1, async_1, errors_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let InPlaceReplaceController = class InPlaceReplaceController {
constructor(editor, editorWorkerService) {
this.decorationIds = [];
this.editor = editor;
this.editorWorkerService = editorWorkerService;
}
static get(editor) {
return editor.getContribution(InPlaceReplaceController.ID);
}
dispose() {
}
run(source, up) {
// cancel any pending request
if (this.currentRequest) {
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 /* Value */ | 4 /* 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
let editRange = range_1.Range.lift(result.range);
let highlightRange = result.range;
let 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.decorationIds = this.editor.deltaDecorations(this.decorationIds, [{
range: highlightRange,
options: InPlaceReplaceController.DECORATION
}]);
// remove decoration after delay
if (this.decorationRemover) {
this.decorationRemover.cancel();
}
this.decorationRemover = (0, async_1.timeout)(350);
this.decorationRemover.then(() => this.decorationIds = this.editor.deltaDecorations(this.decorationIds, [])).catch(errors_1.onUnexpectedError);
}).catch(errors_1.onUnexpectedError);
}
};
InPlaceReplaceController.ID = 'editor.contrib.inPlaceReplaceController';
InPlaceReplaceController.DECORATION = textModel_1.ModelDecorationOptions.register({
description: 'in-place-replace',
className: 'valueSetReplacement'
});
InPlaceReplaceController = __decorate([
__param(1, editorWorkerService_1.IEditorWorkerService)
], InPlaceReplaceController);
class InPlaceReplaceUp extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.inPlaceReplace.up',
label: nls.localize(0, null),
alias: 'Replace with Previous Value',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 82 /* US_COMMA */,
weight: 100 /* EditorContrib */
}
});
}
run(accessor, editor) {
const controller = InPlaceReplaceController.get(editor);
if (!controller) {
return Promise.resolve(undefined);
}
return controller.run(this.id, true);
}
}
class InPlaceReplaceDown extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.inPlaceReplace.down',
label: nls.localize(1, null),
alias: 'Replace with Next Value',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 84 /* US_DOT */,
weight: 100 /* EditorContrib */
}
});
}
run(accessor, editor) {
const controller = InPlaceReplaceController.get(editor);
if (!controller) {
return Promise.resolve(undefined);
}
return controller.run(this.id, false);
}
}
(0, editorExtensions_1.registerEditorContribution)(InPlaceReplaceController.ID, InPlaceReplaceController);
(0, editorExtensions_1.registerEditorAction)(InPlaceReplaceUp);
(0, editorExtensions_1.registerEditorAction)(InPlaceReplaceDown);
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const border = theme.getColor(editorColorRegistry_1.editorBracketMatchBorder);
if (border) {
collector.addRule(`.monaco-editor.vs .valueSetReplacement { outline: solid 2px ${border}; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/indentation/indentation*/], __M([0/*require*/,1/*exports*/,502/*vs/nls!vs/editor/contrib/indentation/indentation*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,14/*vs/editor/browser/editorExtensions*/,184/*vs/editor/common/commands/shiftCommand*/,56/*vs/editor/common/core/editOperation*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,25/*vs/editor/common/editorContextKeys*/,31/*vs/editor/common/model/textModel*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/,36/*vs/editor/common/services/modelService*/,232/*vs/editor/contrib/indentation/indentUtils*/,78/*vs/platform/quickinput/common/quickInput*/]), function (require, exports, nls, lifecycle_1, strings, editorExtensions_1, shiftCommand_1, editOperation_1, range_1, selection_1, editorContextKeys_1, textModel_1, languageConfigurationRegistry_1, modelService_1, indentUtils, quickInput_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IndentationToTabsCommand = exports.IndentationToSpacesCommand = exports.AutoIndentOnPaste = exports.AutoIndentOnPasteCommand = exports.ReindentSelectedLinesAction = exports.ReindentLinesAction = exports.DetectIndentation = exports.IndentUsingSpaces = exports.IndentUsingTabs = exports.ChangeIndentationSizeAction = exports.IndentationToTabsAction = exports.IndentationToSpacesAction = exports.getReindentEditOperations = void 0;
function getReindentEditOperations(model, startLineNumber, endLineNumber, inheritedIndent) {
if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
// Model is empty
return [];
}
let indentationRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentationRules(model.getLanguageIdentifier().id);
if (!indentationRules) {
return [];
}
endLineNumber = Math.min(endLineNumber, model.getLineCount());
// Skip `unIndentedLinePattern` lines
while (startLineNumber <= endLineNumber) {
if (!indentationRules.unIndentedLinePattern) {
break;
}
let text = model.getLineContent(startLineNumber);
if (!indentationRules.unIndentedLinePattern.test(text)) {
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);
};
let indentEdits = [];
// indentation being passed to lines below
let globalIndent;
// Calculate indentation for the first line
// If there is no passed-in indentation, we use the indentation of the first line as base.
let currentLineText = model.getLineContent(startLineNumber);
let adjustedLineContent = currentLineText;
if (inheritedIndent !== undefined && inheritedIndent !== null) {
globalIndent = inheritedIndent;
let oldIndentation = strings.getLeadingWhitespace(currentLineText);
adjustedLineContent = globalIndent + currentLineText.substring(oldIndentation.length);
if (indentationRules.decreaseIndentPattern && indentationRules.decreaseIndentPattern.test(adjustedLineContent)) {
globalIndent = unshiftIndent(globalIndent);
adjustedLineContent = globalIndent + currentLineText.substring(oldIndentation.length);
}
if (currentLineText !== adjustedLineContent) {
indentEdits.push(editOperation_1.EditOperation.replaceMove(new selection_1.Selection(startLineNumber, 1, startLineNumber, oldIndentation.length + 1), textModel_1.TextModel.normalizeIndentation(globalIndent, indentSize, insertSpaces)));
}
}
else {
globalIndent = strings.getLeadingWhitespace(currentLineText);
}
// idealIndentForNextLine doesn't equal globalIndent when there is a line matching `indentNextLinePattern`.
let idealIndentForNextLine = globalIndent;
if (indentationRules.increaseIndentPattern && indentationRules.increaseIndentPattern.test(adjustedLineContent)) {
idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
globalIndent = shiftIndent(globalIndent);
}
else if (indentationRules.indentNextLinePattern && indentationRules.indentNextLinePattern.test(adjustedLineContent)) {
idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
}
startLineNumber++;
// Calculate indentation adjustment for all following lines
for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
let text = model.getLineContent(lineNumber);
let oldIndentation = strings.getLeadingWhitespace(text);
let adjustedLineContent = idealIndentForNextLine + text.substring(oldIndentation.length);
if (indentationRules.decreaseIndentPattern && indentationRules.decreaseIndentPattern.test(adjustedLineContent)) {
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), textModel_1.TextModel.normalizeIndentation(idealIndentForNextLine, indentSize, insertSpaces)));
}
// calculate idealIndentForNextLine
if (indentationRules.unIndentedLinePattern && indentationRules.unIndentedLinePattern.test(text)) {
// In reindent phase, if the line matches `unIndentedLinePattern` we inherit indentation from above lines
// but don't change globalIndent and idealIndentForNextLine.
continue;
}
else if (indentationRules.increaseIndentPattern && indentationRules.increaseIndentPattern.test(adjustedLineContent)) {
globalIndent = shiftIndent(globalIndent);
idealIndentForNextLine = globalIndent;
}
else if (indentationRules.indentNextLinePattern && indentationRules.indentNextLinePattern.test(adjustedLineContent)) {
idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
}
else {
idealIndentForNextLine = globalIndent;
}
}
return indentEdits;
}
exports.getReindentEditOperations = getReindentEditOperations;
class IndentationToSpacesAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: IndentationToSpacesAction.ID,
label: nls.localize(0, null),
alias: 'Convert Indentation to Spaces',
precondition: editorContextKeys_1.EditorContextKeys.writable
});
}
run(accessor, editor) {
let model = editor.getModel();
if (!model) {
return;
}
let modelOpts = model.getOptions();
let 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;
IndentationToSpacesAction.ID = 'editor.action.indentationToSpaces';
class IndentationToTabsAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: IndentationToTabsAction.ID,
label: nls.localize(1, null),
alias: 'Convert Indentation to Tabs',
precondition: editorContextKeys_1.EditorContextKeys.writable
});
}
run(accessor, editor) {
let model = editor.getModel();
if (!model) {
return;
}
let modelOpts = model.getOptions();
let 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;
IndentationToTabsAction.ID = 'editor.action.indentationToTabs';
class ChangeIndentationSizeAction extends editorExtensions_1.EditorAction {
constructor(insertSpaces, opts) {
super(opts);
this.insertSpaces = insertSpaces;
}
run(accessor, editor) {
const quickInputService = accessor.get(quickInput_1.IQuickInputService);
const modelService = accessor.get(modelService_1.IModelService);
let model = editor.getModel();
if (!model) {
return;
}
let creationOpts = modelService.getCreationOptions(model.getLanguageIdentifier().language, model.uri, model.isForSimpleWidget);
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 ? nls.localize(2, null) : 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(3, null), activeItem: picks[autoFocusIndex] }).then(pick => {
if (pick) {
if (model && !model.isDisposed()) {
model.updateOptions({
tabSize: parseInt(pick.label, 10),
insertSpaces: this.insertSpaces
});
}
}
});
}, 50 /* quick input is sensitive to being opened so soon after another */);
}
}
exports.ChangeIndentationSizeAction = ChangeIndentationSizeAction;
class IndentUsingTabs extends ChangeIndentationSizeAction {
constructor() {
super(false, {
id: IndentUsingTabs.ID,
label: nls.localize(4, null),
alias: 'Indent Using Tabs',
precondition: undefined
});
}
}
exports.IndentUsingTabs = IndentUsingTabs;
IndentUsingTabs.ID = 'editor.action.indentUsingTabs';
class IndentUsingSpaces extends ChangeIndentationSizeAction {
constructor() {
super(true, {
id: IndentUsingSpaces.ID,
label: nls.localize(5, null),
alias: 'Indent Using Spaces',
precondition: undefined
});
}
}
exports.IndentUsingSpaces = IndentUsingSpaces;
IndentUsingSpaces.ID = 'editor.action.indentUsingSpaces';
class DetectIndentation extends editorExtensions_1.EditorAction {
constructor() {
super({
id: DetectIndentation.ID,
label: nls.localize(6, null),
alias: 'Detect Indentation from Content',
precondition: undefined
});
}
run(accessor, editor) {
const modelService = accessor.get(modelService_1.IModelService);
let model = editor.getModel();
if (!model) {
return;
}
let creationOpts = modelService.getCreationOptions(model.getLanguageIdentifier().language, model.uri, model.isForSimpleWidget);
model.detectIndentation(creationOpts.insertSpaces, creationOpts.tabSize);
}
}
exports.DetectIndentation = DetectIndentation;
DetectIndentation.ID = 'editor.action.detectIndentation';
class ReindentLinesAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.reindentlines',
label: nls.localize(7, null),
alias: 'Reindent Lines',
precondition: editorContextKeys_1.EditorContextKeys.writable
});
}
run(accessor, editor) {
let model = editor.getModel();
if (!model) {
return;
}
let edits = getReindentEditOperations(model, 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(8, null),
alias: 'Reindent Selected Lines',
precondition: editorContextKeys_1.EditorContextKeys.writable
});
}
run(accessor, editor) {
let model = editor.getModel();
if (!model) {
return;
}
let selections = editor.getSelections();
if (selections === null) {
return;
}
let edits = [];
for (let 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--;
}
let editOperations = getReindentEditOperations(model, 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 (let edit of edits) {
if (edit.range && typeof edit.text === 'string') {
this._edits.push(edit);
}
}
}
getEditOperations(model, builder) {
for (let 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;
class AutoIndentOnPaste {
constructor(editor) {
this.callOnDispose = new lifecycle_1.DisposableStore();
this.callOnModel = new lifecycle_1.DisposableStore();
this.editor = editor;
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(9 /* autoIndent */) < 4 /* Full */ || this.editor.getOption(45 /* formatOnPaste */)) {
return;
}
// no model
if (!this.editor.hasModel()) {
return;
}
this.callOnModel.add(this.editor.onDidPaste(({ range }) => {
this.trigger(range);
}));
}
trigger(range) {
let selections = this.editor.getSelections();
if (selections === null || selections.length > 1) {
return;
}
const model = this.editor.getModel();
if (!model) {
return;
}
if (!model.isCheapToTokenize(range.getStartPosition().lineNumber)) {
return;
}
const autoIndent = this.editor.getOption(9 /* autoIndent */);
const { tabSize, indentSize, insertSpaces } = model.getOptions();
let textEdits = [];
let 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))) {
let indentOfFirstLine = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getGoodIndentForLine(autoIndent, model, model.getLanguageIdentifier().id, startLineNumber, indentConverter);
if (indentOfFirstLine !== null) {
let oldIndentation = strings.getLeadingWhitespace(firstLineText);
let newSpaceCnt = indentUtils.getSpaceCnt(indentOfFirstLine, tabSize);
let oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize);
if (newSpaceCnt !== oldSpaceCnt) {
let newIndent = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces);
textEdits.push({
range: new range_1.Range(startLineNumber, 1, startLineNumber, oldIndentation.length + 1),
text: newIndent
});
firstLineText = newIndent + firstLineText.substr(oldIndentation.length);
}
else {
let indentMetadata = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentMetadata(model, startLineNumber);
if (indentMetadata === 0 || indentMetadata === 8 /* 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) {
let virtualModel = {
getLineTokens: (lineNumber) => {
return model.getLineTokens(lineNumber);
},
getLanguageIdentifier: () => {
return model.getLanguageIdentifier();
},
getLanguageIdAtPosition: (lineNumber, column) => {
return model.getLanguageIdAtPosition(lineNumber, column);
},
getLineContent: (lineNumber) => {
if (lineNumber === firstLineNumber) {
return firstLineText;
}
else {
return model.getLineContent(lineNumber);
}
}
};
let indentOfSecondLine = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getGoodIndentForLine(autoIndent, virtualModel, model.getLanguageIdentifier().id, startLineNumber + 1, indentConverter);
if (indentOfSecondLine !== null) {
let newSpaceCntOfSecondLine = indentUtils.getSpaceCnt(indentOfSecondLine, tabSize);
let oldSpaceCntOfSecondLine = indentUtils.getSpaceCnt(strings.getLeadingWhitespace(model.getLineContent(startLineNumber + 1)), tabSize);
if (newSpaceCntOfSecondLine !== oldSpaceCntOfSecondLine) {
let spaceCntOffset = newSpaceCntOfSecondLine - oldSpaceCntOfSecondLine;
for (let i = startLineNumber + 1; i <= range.endLineNumber; i++) {
let lineContent = model.getLineContent(i);
let originalIndent = strings.getLeadingWhitespace(lineContent);
let originalSpacesCnt = indentUtils.getSpaceCnt(originalIndent, tabSize);
let newSpacesCnt = originalSpacesCnt + spaceCntOffset;
let 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();
let cmd = new AutoIndentOnPasteCommand(textEdits, this.editor.getSelection());
this.editor.executeCommand('autoIndentOnPaste', cmd);
this.editor.pushUndoStop();
}
}
shouldIgnoreLine(model, lineNumber) {
model.forceTokenization(lineNumber);
let nonWhitespaceColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
if (nonWhitespaceColumn === 0) {
return true;
}
let tokens = model.getLineTokens(lineNumber);
if (tokens.getCount() > 0) {
let firstNonWhitespaceTokenIndex = tokens.findTokenIndexAtOffset(nonWhitespaceColumn);
if (firstNonWhitespaceTokenIndex >= 0 && tokens.getStandardTokenType(firstNonWhitespaceTokenIndex) === 1 /* Comment */) {
return true;
}
}
return false;
}
dispose() {
this.callOnDispose.dispose();
this.callOnModel.dispose();
}
}
exports.AutoIndentOnPaste = AutoIndentOnPaste;
AutoIndentOnPaste.ID = 'editor.contrib.autoIndentOnPaste';
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 += ' ';
}
let 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);
(0, editorExtensions_1.registerEditorAction)(IndentationToSpacesAction);
(0, editorExtensions_1.registerEditorAction)(IndentationToTabsAction);
(0, editorExtensions_1.registerEditorAction)(IndentUsingTabs);
(0, editorExtensions_1.registerEditorAction)(IndentUsingSpaces);
(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[645/*vs/editor/contrib/inlayHints/inlayHintsController*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,12/*vs/base/common/errors*/,92/*vs/base/common/hash*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,28/*vs/editor/browser/services/codeEditorService*/,18/*vs/editor/common/modes*/,19/*vs/base/common/arrays*/,22/*vs/platform/theme/common/colorRegistry*/,23/*vs/base/common/cancellation*/,11/*vs/platform/theme/common/themeService*/,3/*vs/editor/common/core/range*/,139/*vs/editor/common/modes/languageFeatureRegistry*/,26/*vs/platform/commands/common/commands*/,24/*vs/base/common/uri*/,20/*vs/base/common/types*/,68/*vs/editor/common/services/resolverService*/,13/*vs/editor/common/core/position*/,38/*vs/platform/configuration/common/configuration*/]), function (require, exports, async_1, errors_1, hash_1, lifecycle_1, editorExtensions_1, codeEditorService_1, modes_1, arrays_1, colorRegistry_1, cancellation_1, themeService_1, range_1, languageFeatureRegistry_1, commands_1, uri_1, types_1, resolverService_1, position_1, configuration_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InlayHintsController = exports.getInlayHints = void 0;
const MAX_DECORATORS = 500;
function getInlayHints(model, ranges, token) {
return __awaiter(this, void 0, void 0, function* () {
const datas = [];
const providers = modes_1.InlayHintsProviderRegistry.ordered(model).reverse();
const promises = (0, arrays_1.flatten)(providers.map(provider => ranges.map(range => Promise.resolve(provider.provideInlayHints(model, range, token)).then(result => {
if (result) {
datas.push({ list: result, provider });
}
}, err => {
(0, errors_1.onUnexpectedExternalError)(err);
}))));
yield Promise.all(promises);
return datas;
});
}
exports.getInlayHints = getInlayHints;
let InlayHintsController = class InlayHintsController {
constructor(_editor, _codeEditorService, _themeService, _configurationService) {
this._editor = _editor;
this._codeEditorService = _codeEditorService;
this._themeService = _themeService;
this._configurationService = _configurationService;
this._disposables = new lifecycle_1.DisposableStore();
this._sessionDisposables = new lifecycle_1.DisposableStore();
this._getInlayHintsDelays = new languageFeatureRegistry_1.LanguageFeatureRequestDelays(modes_1.InlayHintsProviderRegistry, 25, 2500);
this._decorationsTypeIds = [];
this._decorationIds = [];
this._disposables.add(modes_1.InlayHintsProviderRegistry.onDidChange(() => this._update()));
this._disposables.add(_themeService.onDidColorThemeChange(() => 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(125 /* inlayHints */)) {
this._update();
}
}));
this._update();
}
dispose() {
this._sessionDisposables.dispose();
this._removeAllDecorations();
this._disposables.dispose();
}
_update() {
this._sessionDisposables.clear();
if (!this._editor.getOption(125 /* inlayHints */).enabled) {
this._removeAllDecorations();
return;
}
const model = this._editor.getModel();
if (!model || !modes_1.InlayHintsProviderRegistry.has(model)) {
this._removeAllDecorations();
return;
}
const scheduler = new async_1.RunOnceScheduler(() => __awaiter(this, void 0, void 0, function* () {
const t1 = Date.now();
const cts = new cancellation_1.CancellationTokenSource();
this._sessionDisposables.add((0, lifecycle_1.toDisposable)(() => cts.dispose(true)));
const visibleRanges = this._editor.getVisibleRangesPlusViewportAboveBelow();
const result = yield getInlayHints(model, visibleRanges, cts.token);
// update moving average
const newDelay = this._getInlayHintsDelays.update(model, Date.now() - t1);
scheduler.delay = newDelay;
// render hints
this._updateHintsDecorators(result);
}), this._getInlayHintsDelays.get(model));
this._sessionDisposables.add(scheduler);
// update inline hints when content or scroll position changes
this._sessionDisposables.add(this._editor.onDidChangeModelContent(() => scheduler.schedule()));
this._disposables.add(this._editor.onDidScrollChange(() => scheduler.schedule()));
scheduler.schedule();
// update inline hints when any any provider fires an event
const providerListener = new lifecycle_1.DisposableStore();
this._sessionDisposables.add(providerListener);
for (const provider of modes_1.InlayHintsProviderRegistry.all(model)) {
if (typeof provider.onDidChangeInlayHints === 'function') {
providerListener.add(provider.onDidChangeInlayHints(() => scheduler.schedule()));
}
}
}
_updateHintsDecorators(hintsData) {
const { fontSize, fontFamily } = this._getLayoutInfo();
const backgroundColor = this._themeService.getColorTheme().getColor(colorRegistry_1.editorInlayHintBackground);
const fontColor = this._themeService.getColorTheme().getColor(colorRegistry_1.editorInlayHintForeground);
const newDecorationsTypeIds = [];
const newDecorationsData = [];
const fontFamilyVar = '--inlayHintsFontFamily';
this._editor.getContainerDomNode().style.setProperty(fontFamilyVar, fontFamily);
const key = this._configurationService.getValue('editor.useInjectedText');
const shouldUseInjectedText = key === undefined ? true : !!key;
for (const { list: hints } of hintsData) {
for (let j = 0; j < hints.length && newDecorationsData.length < MAX_DECORATORS; j++) {
const { text, position, whitespaceBefore, whitespaceAfter } = hints[j];
const marginBefore = whitespaceBefore ? (fontSize / 3) | 0 : 0;
const marginAfter = whitespaceAfter ? (fontSize / 3) | 0 : 0;
const massagedText = fixSpace(text);
const before = {
contentText: massagedText,
backgroundColor: `${backgroundColor}`,
color: `${fontColor}`,
margin: `0px ${marginAfter}px 0px ${marginBefore}px`,
fontSize: `${fontSize}px`,
fontFamily: `var(${fontFamilyVar})`,
padding: `0px ${(fontSize / 4) | 0}px`,
borderRadius: `${(fontSize / 4) | 0}px`,
};
const key = 'inlayHints-' + (0, hash_1.hash)(before).toString(16);
this._codeEditorService.registerDecorationType('inlay-hints-controller', key, shouldUseInjectedText ? { beforeInjectedText: Object.assign(Object.assign({}, before), { affectsLetterSpacing: true }) } : { before }, undefined, this._editor);
// decoration types are ref-counted which means we only need to
// call register und remove equally often
newDecorationsTypeIds.push(key);
const options = this._codeEditorService.resolveDecorationOptions(key, true);
newDecorationsData.push({
range: range_1.Range.fromPositions(position),
options
});
}
}
this._decorationsTypeIds.forEach(this._codeEditorService.removeDecorationType, this._codeEditorService);
this._decorationsTypeIds = newDecorationsTypeIds;
this._decorationIds = this._editor.deltaDecorations(this._decorationIds, newDecorationsData);
}
_getLayoutInfo() {
const options = this._editor.getOption(125 /* inlayHints */);
const editorFontSize = this._editor.getOption(43 /* fontSize */);
let fontSize = options.fontSize;
if (!fontSize || fontSize < 5 || fontSize > editorFontSize) {
fontSize = (editorFontSize * .9) | 0;
}
const fontFamily = options.fontFamily || this._editor.getOption(40 /* fontFamily */);
return { fontSize, fontFamily };
}
_removeAllDecorations() {
this._decorationIds = this._editor.deltaDecorations(this._decorationIds, []);
this._decorationsTypeIds.forEach(this._codeEditorService.removeDecorationType, this._codeEditorService);
this._decorationsTypeIds = [];
}
};
InlayHintsController.ID = 'editor.contrib.InlayHints';
InlayHintsController = __decorate([
__param(1, codeEditorService_1.ICodeEditorService),
__param(2, themeService_1.IThemeService),
__param(3, configuration_1.IConfigurationService)
], InlayHintsController);
exports.InlayHintsController = InlayHintsController;
function fixSpace(str) {
const noBreakWhitespace = '\xa0';
return str.replace(/[ \t]/g, noBreakWhitespace);
}
(0, editorExtensions_1.registerEditorContribution)(InlayHintsController.ID, InlayHintsController);
commands_1.CommandsRegistry.registerCommand('_executeInlayHintProvider', (accessor, ...args) => __awaiter(void 0, void 0, void 0, function* () {
const [uri, range] = args;
(0, types_1.assertType)(uri_1.URI.isUri(uri));
(0, types_1.assertType)(range_1.Range.isIRange(range));
const ref = yield accessor.get(resolverService_1.ITextModelService).createModelReference(uri);
try {
const data = yield getInlayHints(ref.object.textEditorModel, [range_1.Range.lift(range)], cancellation_1.CancellationToken.None);
return (0, arrays_1.flatten)(data.map(item => item.list)).sort((a, b) => position_1.Position.compare(a.position, b.position));
}
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[267/*vs/editor/contrib/inlineCompletions/inlineCompletionsModel*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/modes*/,56/*vs/editor/common/core/editOperation*/,26/*vs/platform/commands/common/commands*/,14/*vs/editor/browser/editorExtensions*/,148/*vs/editor/browser/controller/coreCommands*/,128/*vs/base/common/diff/diff*/,233/*vs/editor/contrib/inlineCompletions/ghostText*/]), function (require, exports, async_1, cancellation_1, errors_1, event_1, lifecycle_1, strings, range_1, modes_1, editOperation_1, commands_1, editorExtensions_1, coreCommands_1, diff_1, ghostText_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.inlineCompletionToGhostText = exports.InlineCompletionsSession = exports.InlineCompletionsModel = void 0;
let InlineCompletionsModel = class InlineCompletionsModel extends lifecycle_1.Disposable {
constructor(editor, commandService) {
super();
this.editor = editor;
this.commandService = commandService;
this.onDidChangeEmitter = new event_1.Emitter();
this.onDidChange = this.onDidChangeEmitter.event;
this.completionSession = this._register(new lifecycle_1.MutableDisposable());
this.active = false;
this._register(commandService.onDidExecuteCommand(e => {
// These commands don't trigger onDidType.
const commands = new Set([
editorExtensions_1.UndoCommand.id,
editorExtensions_1.RedoCommand.id,
coreCommands_1.CoreEditingCommands.Tab.id,
coreCommands_1.CoreEditingCommands.DeleteLeft.id,
coreCommands_1.CoreEditingCommands.DeleteRight.id
]);
if (commands.has(e.commandId) && editor.hasTextFocus()) {
this.handleUserInput();
}
}));
this._register(this.editor.onDidType((e) => {
this.handleUserInput();
}));
this._register(this.editor.onDidChangeCursorPosition((e) => {
if (this.session && !this.session.isValid) {
this.hide();
}
}));
}
handleUserInput() {
if (this.session && !this.session.isValid) {
this.hide();
}
setTimeout(() => {
// Wait for the cursor update that happens in the same iteration loop iteration
this.startSessionIfTriggered();
}, 0);
}
get session() {
return this.completionSession.value;
}
get ghostText() {
var _a;
return (_a = this.session) === null || _a === void 0 ? void 0 : _a.ghostText;
}
get minReservedLineCount() {
return this.session ? this.session.minReservedLineCount : 0;
}
get expanded() {
return this.session ? this.session.expanded : false;
}
setExpanded(expanded) {
var _a;
(_a = this.session) === null || _a === void 0 ? void 0 : _a.setExpanded(expanded);
}
setActive(active) {
var _a;
this.active = active;
if (active) {
(_a = this.session) === null || _a === void 0 ? void 0 : _a.scheduleAutomaticUpdate();
}
}
startSessionIfTriggered() {
const suggestOptions = this.editor.getOption(53 /* inlineSuggest */);
if (!suggestOptions.enabled) {
return;
}
if (this.session && this.session.isValid) {
return;
}
this.trigger();
}
trigger() {
if (this.completionSession.value) {
return;
}
this.completionSession.value = new InlineCompletionsSession(this.editor, this.editor.getPosition(), () => this.active, this.commandService);
this.completionSession.value.takeOwnership(this.completionSession.value.onDidChange(() => {
this.onDidChangeEmitter.fire();
}));
}
hide() {
this.completionSession.clear();
this.onDidChangeEmitter.fire();
}
commitCurrentSuggestion() {
var _a;
// Don't dispose the session, so that after committing, more suggestions are shown.
(_a = this.session) === null || _a === void 0 ? void 0 : _a.commitCurrentCompletion();
}
showNext() {
var _a;
(_a = this.session) === null || _a === void 0 ? void 0 : _a.showNextInlineCompletion();
}
showPrevious() {
var _a;
(_a = this.session) === null || _a === void 0 ? void 0 : _a.showPreviousInlineCompletion();
}
hasMultipleInlineCompletions() {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const result = yield ((_a = this.session) === null || _a === void 0 ? void 0 : _a.hasMultipleInlineCompletions());
return result !== undefined ? result : false;
});
}
};
InlineCompletionsModel = __decorate([
__param(1, commands_1.ICommandService)
], InlineCompletionsModel);
exports.InlineCompletionsModel = InlineCompletionsModel;
class InlineCompletionsSession extends ghostText_1.BaseGhostTextWidgetModel {
constructor(editor, triggerPosition, shouldUpdate, commandService) {
super(editor);
this.triggerPosition = triggerPosition;
this.shouldUpdate = shouldUpdate;
this.commandService = commandService;
this.minReservedLineCount = 0;
this.updateOperation = this._register(new lifecycle_1.MutableDisposable());
this.cache = this._register(new lifecycle_1.MutableDisposable());
this.updateSoon = this._register(new async_1.RunOnceScheduler(() => this.update(modes_1.InlineCompletionTriggerKind.Automatic), 50));
this.textModel = this.editor.getModel();
//#region Selection
// We use a semantic id to track the selection even if the cache changes.
this.currentlySelectedCompletionId = undefined;
let lastCompletionItem = undefined;
this._register(this.onDidChange(() => {
const currentCompletion = this.currentCompletion;
if (currentCompletion && currentCompletion.sourceInlineCompletion !== lastCompletionItem) {
lastCompletionItem = currentCompletion.sourceInlineCompletion;
const provider = currentCompletion.sourceProvider;
if (provider.handleItemDidShow) {
provider.handleItemDidShow(currentCompletion.sourceInlineCompletions, lastCompletionItem);
}
}
}));
this._register(this.editor.onDidChangeCursorPosition((e) => {
if (this.cache.value) {
this.onDidChangeEmitter.fire();
}
}));
this._register(this.editor.onDidChangeModelContent((e) => {
if (this.cache.value) {
let hasChanged = false;
for (const c of this.cache.value.completions) {
const newRange = this.textModel.getDecorationRange(c.decorationId);
if (!newRange) {
(0, errors_1.onUnexpectedError)(new Error('Decoration has no range'));
continue;
}
if (!c.synchronizedRange.equalsRange(newRange)) {
hasChanged = true;
c.synchronizedRange = newRange;
}
}
if (hasChanged) {
this.onDidChangeEmitter.fire();
}
}
this.scheduleAutomaticUpdate();
}));
this._register(modes_1.InlineCompletionsProviderRegistry.onDidChange(() => {
this.updateSoon.schedule();
}));
this.scheduleAutomaticUpdate();
}
fixAndGetIndexOfCurrentSelection() {
if (!this.currentlySelectedCompletionId || !this.cache.value) {
return 0;
}
if (this.cache.value.completions.length === 0) {
// don't reset the selection in this case
return 0;
}
const idx = this.cache.value.completions.findIndex(v => v.semanticId === this.currentlySelectedCompletionId);
if (idx === -1) {
// Reset the selection so that the selection does not jump back when it appears again
this.currentlySelectedCompletionId = undefined;
return 0;
}
return idx;
}
get currentCachedCompletion() {
if (!this.cache.value) {
return undefined;
}
return this.cache.value.completions[this.fixAndGetIndexOfCurrentSelection()];
}
showNextInlineCompletion() {
var _a;
return __awaiter(this, void 0, void 0, function* () {
yield this.ensureUpdateWithExplicitContext();
const completions = ((_a = this.cache.value) === null || _a === void 0 ? void 0 : _a.completions) || [];
if (completions.length > 0) {
const newIdx = (this.fixAndGetIndexOfCurrentSelection() + 1) % completions.length;
this.currentlySelectedCompletionId = completions[newIdx].semanticId;
}
else {
this.currentlySelectedCompletionId = undefined;
}
this.onDidChangeEmitter.fire();
});
}
showPreviousInlineCompletion() {
var _a;
return __awaiter(this, void 0, void 0, function* () {
yield this.ensureUpdateWithExplicitContext();
const completions = ((_a = this.cache.value) === null || _a === void 0 ? void 0 : _a.completions) || [];
if (completions.length > 0) {
const newIdx = (this.fixAndGetIndexOfCurrentSelection() + completions.length - 1) % completions.length;
this.currentlySelectedCompletionId = completions[newIdx].semanticId;
}
else {
this.currentlySelectedCompletionId = undefined;
}
this.onDidChangeEmitter.fire();
});
}
ensureUpdateWithExplicitContext() {
var _a;
return __awaiter(this, void 0, void 0, function* () {
if (this.updateOperation.value) {
// Restart or wait for current update operation
if (this.updateOperation.value.triggerKind === modes_1.InlineCompletionTriggerKind.Explicit) {
yield this.updateOperation.value.promise;
}
else {
yield this.update(modes_1.InlineCompletionTriggerKind.Explicit);
}
}
else if (((_a = this.cache.value) === null || _a === void 0 ? void 0 : _a.triggerKind) !== modes_1.InlineCompletionTriggerKind.Explicit) {
// Refresh cache
yield this.update(modes_1.InlineCompletionTriggerKind.Explicit);
}
});
}
hasMultipleInlineCompletions() {
var _a;
return __awaiter(this, void 0, void 0, function* () {
yield this.ensureUpdateWithExplicitContext();
return (((_a = this.cache.value) === null || _a === void 0 ? void 0 : _a.completions.length) || 0) > 1;
});
}
//#endregion
get ghostText() {
const currentCompletion = this.currentCompletion;
const mode = this.editor.getOptions().get(53 /* inlineSuggest */).mode;
return currentCompletion ? inlineCompletionToGhostText(currentCompletion, this.editor.getModel(), mode, this.editor.getPosition()) : undefined;
}
get currentCompletion() {
const completion = this.currentCachedCompletion;
if (!completion) {
return undefined;
}
return {
text: completion.inlineCompletion.text,
range: completion.synchronizedRange,
command: completion.inlineCompletion.command,
sourceProvider: completion.inlineCompletion.sourceProvider,
sourceInlineCompletions: completion.inlineCompletion.sourceInlineCompletions,
sourceInlineCompletion: completion.inlineCompletion.sourceInlineCompletion,
};
}
get isValid() {
return this.editor.getPosition().lineNumber === this.triggerPosition.lineNumber;
}
scheduleAutomaticUpdate() {
// Since updateSoon debounces, starvation can happen.
// To prevent stale cache, we clear the current update operation.
this.updateOperation.clear();
this.updateSoon.schedule();
}
update(triggerKind) {
return __awaiter(this, void 0, void 0, function* () {
if (!this.shouldUpdate()) {
return;
}
const position = this.editor.getPosition();
const promise = (0, async_1.createCancelablePromise)((token) => __awaiter(this, void 0, void 0, function* () {
let result;
try {
result = yield provideInlineCompletions(position, this.editor.getModel(), { triggerKind }, token);
}
catch (e) {
(0, errors_1.onUnexpectedError)(e);
return;
}
if (token.isCancellationRequested) {
return;
}
this.cache.value = new SynchronizedInlineCompletionsCache(this.editor, result, () => this.onDidChangeEmitter.fire(), triggerKind);
this.onDidChangeEmitter.fire();
}));
const operation = new UpdateOperation(promise, triggerKind);
this.updateOperation.value = operation;
yield promise;
if (this.updateOperation.value === operation) {
this.updateOperation.clear();
}
});
}
takeOwnership(disposable) {
this._register(disposable);
}
commitCurrentCompletion() {
if (!this.ghostText) {
// No ghost text was shown for this completion.
// Thus, we don't want to commit anything.
return;
}
const completion = this.currentCompletion;
if (completion) {
this.commit(completion);
}
}
commit(completion) {
// Mark the cache as stale, but don't dispose it yet,
// otherwise command args might get disposed.
const cache = this.cache.clearAndLeak();
this.editor.executeEdits('inlineSuggestion.accept', [
editOperation_1.EditOperation.replaceMove(completion.range, completion.text)
]);
if (completion.command) {
this.commandService
.executeCommand(completion.command.id, ...(completion.command.arguments || []))
.finally(() => {
cache === null || cache === void 0 ? void 0 : cache.dispose();
})
.then(undefined, errors_1.onUnexpectedExternalError);
}
else {
cache === null || cache === void 0 ? void 0 : cache.dispose();
}
this.onDidChangeEmitter.fire();
}
}
exports.InlineCompletionsSession = InlineCompletionsSession;
class UpdateOperation {
constructor(promise, triggerKind) {
this.promise = promise;
this.triggerKind = triggerKind;
}
dispose() {
this.promise.cancel();
}
}
/**
* The cache keeps itself in sync with the editor.
* It also owns the completions result and disposes it when the cache is diposed.
*/
class SynchronizedInlineCompletionsCache extends lifecycle_1.Disposable {
constructor(editor, completionsSource, onChange, triggerKind) {
super();
this.triggerKind = triggerKind;
const decorationIds = editor.deltaDecorations([], completionsSource.items.map(i => ({
range: i.range,
options: {
description: 'inline-completion-tracking-range'
},
})));
this._register((0, lifecycle_1.toDisposable)(() => {
editor.deltaDecorations(decorationIds, []);
}));
this.completions = completionsSource.items.map((c, idx) => new CachedInlineCompletion(c, decorationIds[idx]));
this._register(editor.onDidChangeModelContent(() => {
let hasChanged = false;
const model = editor.getModel();
for (const c of this.completions) {
const newRange = model.getDecorationRange(c.decorationId);
if (!newRange) {
(0, errors_1.onUnexpectedError)(new Error('Decoration has no range'));
continue;
}
if (!c.synchronizedRange.equalsRange(newRange)) {
hasChanged = true;
c.synchronizedRange = newRange;
}
}
if (hasChanged) {
onChange();
}
}));
this._register(completionsSource);
}
}
class CachedInlineCompletion {
constructor(inlineCompletion, decorationId) {
this.inlineCompletion = inlineCompletion;
this.decorationId = decorationId;
this.semanticId = JSON.stringify({
text: this.inlineCompletion.text,
startLine: this.inlineCompletion.range.startLineNumber,
startColumn: this.inlineCompletion.range.startColumn,
command: this.inlineCompletion.command
});
this.synchronizedRange = inlineCompletion.range;
}
}
function inlineCompletionToGhostText(inlineCompletion, textModel, mode, cursorPosition) {
if (inlineCompletion.range.startLineNumber !== inlineCompletion.range.endLineNumber) {
// Only single line replacements are supported.
return undefined;
}
// This is a single line string
const valueToBeReplaced = textModel.getValueInRange(inlineCompletion.range);
const changes = cachingDiff(valueToBeReplaced, inlineCompletion.text);
const lineNumber = inlineCompletion.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;
}
}
for (const c of changes) {
const insertColumn = inlineCompletion.range.startColumn + c.originalStart + c.originalLength;
if (mode === 'subwordSmart' && cursorPosition && cursorPosition.lineNumber === inlineCompletion.range.startLineNumber && insertColumn < cursorPosition.column) {
// No ghost text before cursor
return undefined;
}
if (c.originalLength > 0) {
const originalText = valueToBeReplaced.substr(c.originalStart, c.originalLength);
const firstNonWsCol = textModel.getLineFirstNonWhitespaceColumn(lineNumber);
if (!(/^(\t| )*$/.test(originalText) && (firstNonWsCol === 0 || insertColumn <= firstNonWsCol))) {
return undefined;
}
}
if (c.modifiedLength === 0) {
continue;
}
const text = inlineCompletion.text.substr(c.modifiedStart, c.modifiedLength);
const lines = strings.splitLines(text);
parts.push(new ghostText_1.GhostTextPart(insertColumn, lines));
}
return new ghostText_1.GhostText(lineNumber, parts, 0);
}
exports.inlineCompletionToGhostText = inlineCompletionToGhostText;
let lastRequest = undefined;
function cachingDiff(originalValue, newValue) {
if ((lastRequest === null || lastRequest === void 0 ? void 0 : lastRequest.originalValue) === originalValue && (lastRequest === null || lastRequest === void 0 ? void 0 : lastRequest.newValue) === newValue) {
return lastRequest === null || lastRequest === void 0 ? void 0 : lastRequest.changes;
}
else {
const changes = smartDiff(originalValue, newValue);
lastRequest = {
originalValue,
newValue,
changes
};
return changes;
}
}
/**
* 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) {
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++) {
const id = group * 100 + level;
// TODO support more brackets
if (source[i] === '(') {
characters[i] = getUniqueCharCode(2 * id);
level++;
}
else if (source[i] === ')') {
characters[i] = getUniqueCharCode(2 * id + 1);
if (level === 1) {
group++;
}
level = Math.max(level - 1, 0);
}
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;
}
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 provideInlineCompletions(position, model, context, token = cancellation_1.CancellationToken.None) {
return __awaiter(this, void 0, void 0, function* () {
const defaultReplaceRange = getDefaultRange(position, model);
const providers = modes_1.InlineCompletionsProviderRegistry.all(model);
const results = yield Promise.all(providers.map((provider) => __awaiter(this, void 0, void 0, function* () {
const completions = yield provider.provideInlineCompletions(model, position, context, token);
return ({
completions,
provider,
dispose: () => {
if (completions) {
provider.freeInlineCompletions(completions);
}
}
});
})));
const itemsByHash = new Map();
for (const result of results) {
const completions = result.completions;
if (completions) {
for (const item of completions.items.map(item => ({
text: item.text,
range: item.range ? range_1.Range.lift(item.range) : defaultReplaceRange,
command: item.command,
sourceProvider: result.provider,
sourceInlineCompletions: completions,
sourceInlineCompletion: item
}))) {
if (item.range.startLineNumber !== item.range.endLineNumber) {
// Ignore invalid ranges.
continue;
}
itemsByHash.set(JSON.stringify({ text: item.text, range: item.range }), item);
}
}
}
return {
items: [...itemsByHash.values()],
dispose: () => {
for (const result of results) {
result.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[646/*vs/editor/contrib/linesOperations/linesOperations*/], __M([0/*require*/,1/*exports*/,505/*vs/nls!vs/editor/contrib/linesOperations/linesOperations*/,41/*vs/base/common/keyCodes*/,148/*vs/editor/browser/controller/coreCommands*/,14/*vs/editor/browser/editorExtensions*/,95/*vs/editor/common/commands/replaceCommand*/,375/*vs/editor/common/commands/trimTrailingWhitespaceCommand*/,187/*vs/editor/common/controller/cursorTypeOperations*/,56/*vs/editor/common/core/editOperation*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,25/*vs/editor/common/editorContextKeys*/,419/*vs/editor/contrib/linesOperations/copyLinesCommand*/,556/*vs/editor/contrib/linesOperations/moveLinesCommand*/,420/*vs/editor/contrib/linesOperations/sortLinesCommand*/,33/*vs/platform/actions/common/actions*/]), function (require, exports, nls, keyCodes_1, coreCommands_1, editorExtensions_1, replaceCommand_1, trimTrailingWhitespaceCommand_1, cursorTypeOperations_1, editOperation_1, position_1, range_1, selection_1, editorContextKeys_1, copyLinesCommand_1, moveLinesCommand_1, sortLinesCommand_1, actions_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
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.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(0, null),
alias: 'Copy Line Up',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 512 /* Alt */ | 1024 /* Shift */ | 16 /* UpArrow */,
linux: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 1024 /* Shift */ | 16 /* UpArrow */ },
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarSelectionMenu,
group: '2_line',
title: nls.localize(1, null),
order: 1
}
});
}
}
class CopyLinesDownAction extends AbstractCopyLinesAction {
constructor() {
super(true, {
id: 'editor.action.copyLinesDownAction',
label: nls.localize(2, null),
alias: 'Copy Line Down',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 512 /* Alt */ | 1024 /* Shift */ | 18 /* DownArrow */,
linux: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 1024 /* Shift */ | 18 /* DownArrow */ },
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarSelectionMenu,
group: '2_line',
title: nls.localize(3, null),
order: 2
}
});
}
}
class DuplicateSelectionAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.duplicateSelection',
label: nls.localize(4, null),
alias: 'Duplicate Selection',
precondition: editorContextKeys_1.EditorContextKeys.writable,
menuOpts: {
menuId: actions_1.MenuId.MenubarSelectionMenu,
group: '2_line',
title: nls.localize(5, null),
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) {
let commands = [];
let selections = editor.getSelections() || [];
const autoIndent = editor.getOption(9 /* autoIndent */);
for (const selection of selections) {
commands.push(new moveLinesCommand_1.MoveLinesCommand(selection, this.down, autoIndent));
}
editor.pushUndoStop();
editor.executeCommands(this.id, commands);
editor.pushUndoStop();
}
}
class MoveLinesUpAction extends AbstractMoveLinesAction {
constructor() {
super(false, {
id: 'editor.action.moveLinesUpAction',
label: nls.localize(6, null),
alias: 'Move Line Up',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 512 /* Alt */ | 16 /* UpArrow */,
linux: { primary: 512 /* Alt */ | 16 /* UpArrow */ },
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarSelectionMenu,
group: '2_line',
title: nls.localize(7, null),
order: 3
}
});
}
}
class MoveLinesDownAction extends AbstractMoveLinesAction {
constructor() {
super(true, {
id: 'editor.action.moveLinesDownAction',
label: nls.localize(8, null),
alias: 'Move Line Down',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 512 /* Alt */ | 18 /* DownArrow */,
linux: { primary: 512 /* Alt */ | 18 /* DownArrow */ },
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarSelectionMenu,
group: '2_line',
title: nls.localize(9, null),
order: 4
}
});
}
}
class AbstractSortLinesAction extends editorExtensions_1.EditorAction {
constructor(descending, opts) {
super(opts);
this.descending = descending;
}
run(_accessor, editor) {
const selections = editor.getSelections() || [];
for (const selection of selections) {
if (!sortLinesCommand_1.SortLinesCommand.canRun(editor.getModel(), selection, this.descending)) {
return;
}
}
let 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(10, null),
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(11, null),
alias: 'Sort Lines Descending',
precondition: editorContextKeys_1.EditorContextKeys.writable
});
}
}
exports.SortLinesDescendingAction = SortLinesDescendingAction;
class TrimTrailingWhitespaceAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: TrimTrailingWhitespaceAction.ID,
label: nls.localize(12, null),
alias: 'Trim Trailing Whitespace',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 54 /* KEY_X */),
weight: 100 /* 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));
}
let selection = editor.getSelection();
if (selection === null) {
return;
}
let command = new trimTrailingWhitespaceCommand_1.TrimTrailingWhitespaceCommand(selection, cursors);
editor.pushUndoStop();
editor.executeCommands(this.id, [command]);
editor.pushUndoStop();
}
}
exports.TrimTrailingWhitespaceAction = TrimTrailingWhitespaceAction;
TrimTrailingWhitespaceAction.ID = 'editor.action.trimTrailingWhitespace';
class DeleteLinesAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.deleteLines',
label: nls.localize(13, null),
alias: 'Delete Line',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 41 /* KEY_K */,
weight: 100 /* EditorContrib */
}
});
}
run(_accessor, editor) {
if (!editor.hasModel()) {
return;
}
let ops = this._getLinesToRemove(editor);
let model = editor.getModel();
if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
// Model is empty
return;
}
let linesDeleted = 0;
let edits = [];
let 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
let 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
let 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(14, null),
alias: 'Indent Line',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 89 /* US_CLOSE_SQUARE_BRACKET */,
weight: 100 /* 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(15, null),
alias: 'Outdent Line',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 87 /* US_OPEN_SQUARE_BRACKET */,
weight: 100 /* 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(16, null),
alias: 'Insert Line Above',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 3 /* Enter */,
weight: 100 /* EditorContrib */
}
});
}
run(_accessor, editor) {
const viewModel = editor._getViewModel();
if (!viewModel) {
return;
}
editor.pushUndoStop();
editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.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(17, null),
alias: 'Insert Line Below',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 3 /* Enter */,
weight: 100 /* EditorContrib */
}
});
}
run(_accessor, editor) {
const viewModel = editor._getViewModel();
if (!viewModel) {
return;
}
editor.pushUndoStop();
editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.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();
let rangesToDelete = this._getRangesToDelete(editor);
// merge overlapping selections
let effectiveRanges = [];
for (let i = 0, count = rangesToDelete.length - 1; i < count; i++) {
let range = rangesToDelete[i];
let 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]);
let endCursorState = this._getEndCursorState(primaryCursor, effectiveRanges);
let 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(18, null),
alias: 'Delete All Left',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 0,
mac: { primary: 2048 /* CtrlCmd */ | 1 /* Backspace */ },
weight: 100 /* EditorContrib */
}
});
}
_getEndCursorState(primaryCursor, rangesToDelete) {
let endPrimaryCursor = null;
let endCursorState = [];
let deletedLines = 0;
rangesToDelete.forEach(range => {
let endCursor;
if (range.endColumn === 1 && deletedLines > 0) {
let 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) {
let selections = editor.getSelections();
if (selections === null) {
return [];
}
let rangesToDelete = selections;
let model = editor.getModel();
if (model === null) {
return [];
}
rangesToDelete.sort(range_1.Range.compareRangesUsingStarts);
rangesToDelete = rangesToDelete.map(selection => {
if (selection.isEmpty()) {
if (selection.startColumn === 1) {
let deleteFromLine = Math.max(1, selection.startLineNumber - 1);
let deleteFromColumn = selection.startLineNumber === 1 ? 1 : model.getLineContent(deleteFromLine).length + 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(19, null),
alias: 'Delete All Right',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 0,
mac: { primary: 256 /* WinCtrl */ | 41 /* KEY_K */, secondary: [2048 /* CtrlCmd */ | 20 /* Delete */] },
weight: 100 /* EditorContrib */
}
});
}
_getEndCursorState(primaryCursor, rangesToDelete) {
let endPrimaryCursor = null;
let endCursorState = [];
for (let i = 0, len = rangesToDelete.length, offset = 0; i < len; i++) {
let range = rangesToDelete[i];
let 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) {
let model = editor.getModel();
if (model === null) {
return [];
}
let selections = editor.getSelections();
if (selections === null) {
return [];
}
let 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(20, null),
alias: 'Join Lines',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 0,
mac: { primary: 256 /* WinCtrl */ | 40 /* KEY_J */ },
weight: 100 /* EditorContrib */
}
});
}
run(_accessor, editor) {
let selections = editor.getSelections();
if (selections === null) {
return;
}
let primaryCursor = editor.getSelection();
if (primaryCursor === null) {
return;
}
selections.sort(range_1.Range.compareRangesUsingStarts);
let reducedSelections = [];
let 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);
let model = editor.getModel();
if (model === null) {
return;
}
let edits = [];
let endCursorState = [];
let endPrimaryCursor = primaryCursor;
let lineOffset = 0;
for (let i = 0, len = reducedSelections.length; i < len; i++) {
let selection = reducedSelections[i];
let startLineNumber = selection.startLineNumber;
let startColumn = 1;
let columnDeltaOffset = 0;
let endLineNumber, endColumn;
let selectionEndPositionOffset = model.getLineContent(selection.endLineNumber).length - selection.endColumn;
if (selection.isEmpty() || selection.startLineNumber === selection.endLineNumber) {
let 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++) {
let lineText = model.getLineContent(i);
let 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, ' ');
}
let lineTextWithoutIndent = lineText.substr(firstNonWhitespaceIdx - 1);
trimmedLinesContent += (insertSpace ? ' ' : '') + lineTextWithoutIndent;
if (insertSpace) {
columnDeltaOffset = lineTextWithoutIndent.length + 1;
}
else {
columnDeltaOffset = lineTextWithoutIndent.length;
}
}
else {
columnDeltaOffset = 0;
}
}
let 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(21, null),
alias: 'Transpose characters around the cursor',
precondition: editorContextKeys_1.EditorContextKeys.writable
});
}
run(_accessor, editor) {
let selections = editor.getSelections();
if (selections === null) {
return;
}
let model = editor.getModel();
if (model === null) {
return;
}
let commands = [];
for (let i = 0, len = selections.length; i < len; i++) {
let selection = selections[i];
if (!selection.isEmpty()) {
continue;
}
let cursor = selection.getStartPosition();
let 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.
let deleteSelection = new range_1.Range(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1);
let 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 {
let deleteSelection = new range_1.Range(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber, cursor.column + 1);
let 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(115 /* 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(22, null),
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(23, null),
alias: 'Transform to Lowercase',
precondition: editorContextKeys_1.EditorContextKeys.writable
});
}
_modifyText(text, wordSeparators) {
return text.toLocaleLowerCase();
}
}
exports.LowerCaseAction = LowerCaseAction;
class TitleCaseAction extends AbstractCaseAction {
constructor() {
super({
id: 'editor.action.transformToTitlecase',
label: nls.localize(24, null),
alias: 'Transform to Title Case',
precondition: editorContextKeys_1.EditorContextKeys.writable
});
}
_modifyText(text, wordSeparators) {
const separators = '\r\n\t ' + wordSeparators;
const excludedChars = separators.split('');
let title = '';
let startUpperCase = true;
for (let i = 0; i < text.length; i++) {
let currentChar = text[i];
if (excludedChars.indexOf(currentChar) >= 0) {
startUpperCase = true;
title += currentChar;
}
else if (startUpperCase) {
startUpperCase = false;
title += currentChar.toLocaleUpperCase();
}
else {
title += currentChar.toLocaleLowerCase();
}
}
return title;
}
}
exports.TitleCaseAction = TitleCaseAction;
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 SnakeCaseAction extends AbstractCaseAction {
constructor() {
super({
id: 'editor.action.transformToSnakecase',
label: nls.localize(25, null),
alias: 'Transform to Snake Case',
precondition: editorContextKeys_1.EditorContextKeys.writable
});
}
_modifyText(text, wordSeparators) {
const regExp1 = SnakeCaseAction.regExp1.get();
const regExp2 = SnakeCaseAction.regExp2.get();
if (!regExp1 || !regExp2) {
// cannot support this
return text;
}
return (text
.replace(regExp1, '$1_$2')
.replace(regExp2, '$1_$2$3')
.toLocaleLowerCase());
}
}
exports.SnakeCaseAction = SnakeCaseAction;
SnakeCaseAction.regExp1 = new BackwardsCompatibleRegExp('(\\p{Ll})(\\p{Lu})', 'gmu');
SnakeCaseAction.regExp2 = new BackwardsCompatibleRegExp('(\\p{Lu}|\\p{N})(\\p{Lu})(\\p{Ll})', 'gmu');
(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)(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);
(0, editorExtensions_1.registerEditorAction)(TitleCaseAction);
if (SnakeCaseAction.regExp1.isSupported() && SnakeCaseAction.regExp2.isSupported()) {
(0, editorExtensions_1.registerEditorAction)(SnakeCaseAction);
}
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/linkedEditing/linkedEditing*/], __M([0/*require*/,1/*exports*/,506/*vs/nls!vs/editor/contrib/linkedEditing/linkedEditing*/,14/*vs/editor/browser/editorExtensions*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,13/*vs/editor/common/core/position*/,23/*vs/base/common/cancellation*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/modes*/,15/*vs/base/common/async*/,31/*vs/editor/common/model/textModel*/,16/*vs/platform/contextkey/common/contextkey*/,25/*vs/editor/common/editorContextKeys*/,24/*vs/base/common/uri*/,28/*vs/editor/browser/services/codeEditorService*/,12/*vs/base/common/errors*/,8/*vs/base/common/strings*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,29/*vs/base/common/color*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, nls, editorExtensions_1, arrays, lifecycle_1, position_1, cancellation_1, range_1, modes_1, async_1, textModel_1, contextkey_1, editorContextKeys_1, uri_1, codeEditorService_1, errors_1, strings, colorRegistry_1, themeService_1, color_1, languageConfigurationRegistry_1) {
"use strict";
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 {
constructor(editor, contextKeyService) {
super();
this._debounceDuration = 200;
this._localToDispose = this._register(new lifecycle_1.DisposableStore());
this._editor = editor;
this._enabled = false;
this._visibleContextKey = exports.CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE.bindTo(contextKeyService);
this._currentDecorations = [];
this._languageWordPattern = null;
this._currentWordPattern = null;
this._ignoreChangeEvent = false;
this._localToDispose = this._register(new lifecycle_1.DisposableStore());
this._rangeUpdateTriggerPromise = null;
this._rangeSyncTriggerPromise = null;
this._currentRequest = null;
this._currentRequestPosition = null;
this._currentRequestModelVersion = null;
this._register(this._editor.onDidChangeModel(() => this.reinitialize(true)));
this._register(this._editor.onDidChangeConfiguration(e => {
if (e.hasChanged(60 /* linkedEditing */) || e.hasChanged(80 /* renameOnType */)) {
this.reinitialize(false);
}
}));
this._register(modes_1.LinkedEditingRangeProviderRegistry.onDidChange(() => this.reinitialize(false)));
this._register(this._editor.onDidChangeModelLanguage(() => this.reinitialize(true)));
this.reinitialize(true);
}
static get(editor) {
return editor.getContribution(LinkedEditingContribution.ID);
}
reinitialize(forceRefresh) {
const model = this._editor.getModel();
const isEnabled = model !== null && (this._editor.getOption(60 /* linkedEditing */) || this._editor.getOption(80 /* renameOnType */)) && modes_1.LinkedEditingRangeProviderRegistry.has(model);
if (isEnabled === this._enabled && !forceRefresh) {
return;
}
this._enabled = isEnabled;
this.clearRanges();
this._localToDispose.clear();
if (!isEnabled || model === null) {
return;
}
this._languageWordPattern = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id);
this._localToDispose.add(model.onDidChangeLanguageConfiguration(() => {
this._languageWordPattern = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id);
}));
const rangeUpdateScheduler = new async_1.Delayer(this._debounceDuration);
const triggerRangeUpdate = () => {
this._rangeUpdateTriggerPromise = rangeUpdateScheduler.trigger(() => this.updateRanges(), this._debounceDuration);
};
const rangeSyncScheduler = new async_1.Delayer(0);
const triggerRangeSync = (decorations) => {
this._rangeSyncTriggerPromise = rangeSyncScheduler.trigger(() => this._syncRanges(decorations));
};
this._localToDispose.add(this._editor.onDidChangeCursorPosition(() => {
triggerRangeUpdate();
}));
this._localToDispose.add(this._editor.onDidChangeModelContent((e) => {
if (!this._ignoreChangeEvent) {
if (this._currentDecorations.length > 0) {
const referenceRange = model.getDecorationRange(this._currentDecorations[0]);
if (referenceRange && e.changes.every(c => referenceRange.intersectRanges(c.range))) {
triggerRangeSync(this._currentDecorations);
return;
}
}
}
triggerRangeUpdate();
}));
this._localToDispose.add({
dispose: () => {
rangeUpdateScheduler.cancel();
rangeSyncScheduler.cancel();
}
});
this.updateRanges();
}
_syncRanges(decorations) {
// dalayed invocation, make sure we're still on
if (!this._editor.hasModel() || decorations !== this._currentDecorations || decorations.length === 0) {
// nothing to do
return;
}
const model = this._editor.getModel();
const referenceRange = model.getDecorationRange(decorations[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();
}
}
let edits = [];
for (let i = 1, len = decorations.length; i < len; i++) {
const mirrorRange = model.getDecorationRange(decorations[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 = this._editor.deltaDecorations(this._currentDecorations, []);
if (this._currentRequest) {
this._currentRequest.cancel();
this._currentRequest = null;
this._currentRequestPosition = null;
}
}
updateRanges(force = false) {
return __awaiter(this, void 0, void 0, function* () {
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 && this._currentDecorations.length > 0) {
const range = model.getDecorationRange(this._currentDecorations[0]);
if (range && range.containsPosition(position)) {
return; // just moving inside the existing primary range
}
}
}
this._currentRequestPosition = position;
this._currentRequestModelVersion = modelVersionId;
const request = (0, async_1.createCancelablePromise)((token) => __awaiter(this, void 0, void 0, function* () {
try {
const response = yield getLinkedEditingRanges(model, position, token);
if (request !== this._currentRequest) {
return;
}
this._currentRequest = null;
if (modelVersionId !== model.getVersionId()) {
return;
}
let ranges = [];
if (response === null || response === void 0 ? void 0 : response.ranges) {
ranges = response.ranges;
}
this._currentWordPattern = (response === null || response === void 0 ? void 0 : 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.DECORATION }));
this._visibleContextKey.set(true);
this._currentDecorations = this._editor.deltaDecorations(this._currentDecorations, decorations);
}
catch (err) {
if (!(0, errors_1.isPromiseCanceledError)(err)) {
(0, errors_1.onUnexpectedError)(err);
}
if (this._currentRequest === request || !this._currentRequest) {
// stop if we are still the latest request
this.clearRanges();
}
}
}));
this._currentRequest = request;
return request;
});
}
};
LinkedEditingContribution.ID = 'editor.contrib.linkedEditing';
LinkedEditingContribution.DECORATION = textModel_1.ModelDecorationOptions.register({
description: 'linked-editing',
stickiness: 0 /* AlwaysGrowsWhenTypingAtEdges */,
className: DECORATION_CLASS_NAME
});
LinkedEditingContribution = __decorate([
__param(1, contextkey_1.IContextKeyService)
], LinkedEditingContribution);
exports.LinkedEditingContribution = LinkedEditingContribution;
class LinkedEditingAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.linkedEditing',
label: nls.localize(0, null),
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 /* CtrlCmd */ | 1024 /* Shift */ | 60 /* F2 */,
weight: 100 /* 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 /* EditorContrib */ + 99,
primary: 9 /* Escape */,
secondary: [1024 /* Shift */ | 9 /* Escape */]
}
}));
function getLinkedEditingRanges(model, position, token) {
const orderedByScore = modes_1.LinkedEditingRangeProviderRegistry.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 => () => __awaiter(this, void 0, void 0, function* () {
try {
return yield provider.provideLinkedEditingRanges(model, position, token);
}
catch (e) {
(0, errors_1.onUnexpectedExternalError)(e);
return undefined;
}
})), result => !!result && arrays.isNonEmptyArray(result === null || result === void 0 ? void 0 : 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), hc: color_1.Color.fromHex('#f00').transparent(0.3) }, nls.localize(1, null));
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const editorLinkedEditingBackgroundColor = theme.getColor(exports.editorLinkedEditingBackground);
if (editorLinkedEditingBackgroundColor) {
collector.addRule(`.monaco-editor .${DECORATION_CLASS_NAME} { background: ${editorLinkedEditingBackgroundColor}; border-left-color: ${editorLinkedEditingBackgroundColor}; }`);
}
});
(0, editorExtensions_1.registerModelAndPositionCommand)('_executeLinkedEditingProvider', (model, position) => getLinkedEditingRanges(model, position, cancellation_1.CancellationToken.None));
(0, editorExtensions_1.registerEditorContribution)(LinkedEditingContribution.ID, LinkedEditingContribution);
(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[648/*vs/editor/contrib/links/links*/], __M([0/*require*/,1/*exports*/,507/*vs/nls!vs/editor/contrib/links/links*/,15/*vs/base/common/async*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,82/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,14/*vs/editor/browser/editorExtensions*/,31/*vs/editor/common/model/textModel*/,18/*vs/editor/common/modes*/,229/*vs/editor/contrib/gotoSymbol/link/clickLinkGesture*/,560/*vs/editor/contrib/links/getLinks*/,34/*vs/platform/notification/common/notification*/,58/*vs/platform/opener/common/opener*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,24/*vs/base/common/uri*/,46/*vs/base/common/network*/,43/*vs/base/common/resources*/,355/*vs/css!vs/editor/contrib/links/links*/]), function (require, exports, nls, async, cancellation_1, errors_1, htmlContent_1, lifecycle_1, platform, editorExtensions_1, textModel_1, modes_1, clickLinkGesture_1, getLinks_1, notification_1, opener_1, colorRegistry_1, themeService_1, uri_1, network_1, resources) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LinkDetector = void 0;
function getHoverMessage(link, useMetaKey) {
const executeCmd = link.url && /^command:/i.test(link.url.toString());
const label = link.tooltip
? link.tooltip
: executeCmd
? nls.localize(0, null)
: nls.localize(1, null);
const kb = useMetaKey
? platform.isMacintosh
? nls.localize(2, null)
: nls.localize(3, null)
: platform.isMacintosh
? nls.localize(4, null)
: nls.localize(5, null);
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];
const nativeLabelText = nls.localize(6, null, commandId);
nativeLabel = ` "${nativeLabelText}"`;
}
}
const hoverMessage = new htmlContent_1.MarkdownString('', true).appendMarkdown(`[${label}](${link.url.toString(true)}${nativeLabel}) (${kb})`);
return hoverMessage;
}
else {
return new htmlContent_1.MarkdownString().appendText(`${label} (${kb})`);
}
}
const decoration = {
general: textModel_1.ModelDecorationOptions.register({
description: 'detected-link',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
collapseOnReplaceEdit: true,
inlineClassName: 'detected-link'
}),
active: textModel_1.ModelDecorationOptions.register({
description: 'detected-link-active',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
collapseOnReplaceEdit: true,
inlineClassName: 'detected-link-active'
})
};
class LinkOccurrence {
constructor(link, decorationId) {
this.link = link;
this.decorationId = decorationId;
}
static decoration(link, useMetaKey) {
return {
range: link.range,
options: LinkOccurrence._getOptions(link, useMetaKey, false)
};
}
static _getOptions(link, useMetaKey, isActive) {
const options = Object.assign({}, (isActive ? decoration.active : decoration.general));
options.hoverMessage = getHoverMessage(link, useMetaKey);
return options;
}
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));
}
}
let LinkDetector = class LinkDetector {
constructor(editor, openerService, notificationService) {
this.listenersToRemove = new lifecycle_1.DisposableStore();
this.editor = editor;
this.openerService = openerService;
this.notificationService = notificationService;
let clickLinkGesture = new clickLinkGesture_1.ClickLinkGesture(editor);
this.listenersToRemove.add(clickLinkGesture);
this.listenersToRemove.add(clickLinkGesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
this._onEditorMouseMove(mouseEvent, keyboardEvent);
}));
this.listenersToRemove.add(clickLinkGesture.onExecute((e) => {
this.onEditorMouseUp(e);
}));
this.listenersToRemove.add(clickLinkGesture.onCancel((e) => {
this.cleanUpActiveLinkDecoration();
}));
this.enabled = editor.getOption(61 /* links */);
this.listenersToRemove.add(editor.onDidChangeConfiguration((e) => {
const enabled = editor.getOption(61 /* links */);
if (this.enabled === enabled) {
// No change in our configuration option
return;
}
this.enabled = enabled;
// 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.beginCompute();
}));
this.listenersToRemove.add(editor.onDidChangeModelContent((e) => this.onChange()));
this.listenersToRemove.add(editor.onDidChangeModel((e) => this.onModelChanged()));
this.listenersToRemove.add(editor.onDidChangeModelLanguage((e) => this.onModelModeChanged()));
this.listenersToRemove.add(modes_1.LinkProviderRegistry.onDidChange((e) => this.onModelModeChanged()));
this.timeout = new async.TimeoutTimer();
this.computePromise = null;
this.activeLinksList = null;
this.currentOccurrences = {};
this.activeLinkDecorationId = null;
this.beginCompute();
}
static get(editor) {
return editor.getContribution(LinkDetector.ID);
}
onModelChanged() {
this.currentOccurrences = {};
this.activeLinkDecorationId = null;
this.stop();
this.beginCompute();
}
onModelModeChanged() {
this.stop();
this.beginCompute();
}
onChange() {
this.timeout.setIfNotSet(() => this.beginCompute(), LinkDetector.RECOMPUTE_TIME);
}
beginCompute() {
return __awaiter(this, void 0, void 0, function* () {
if (!this.editor.hasModel() || !this.enabled) {
return;
}
const model = this.editor.getModel();
if (!modes_1.LinkProviderRegistry.has(model)) {
return;
}
if (this.activeLinksList) {
this.activeLinksList.dispose();
this.activeLinksList = null;
}
this.computePromise = async.createCancelablePromise(token => (0, getLinks_1.getLinks)(model, token));
try {
this.activeLinksList = yield this.computePromise;
this.updateDecorations(this.activeLinksList.links);
}
catch (err) {
(0, errors_1.onUnexpectedError)(err);
}
finally {
this.computePromise = null;
}
});
}
updateDecorations(links) {
const useMetaKey = (this.editor.getOption(68 /* multiCursorModifier */) === 'altKey');
let oldDecorations = [];
let keys = Object.keys(this.currentOccurrences);
for (let i = 0, len = keys.length; i < len; i++) {
let decorationId = keys[i];
let occurance = this.currentOccurrences[decorationId];
oldDecorations.push(occurance.decorationId);
}
let newDecorations = [];
if (links) {
// Not sure why this is sometimes null
for (const link of links) {
newDecorations.push(LinkOccurrence.decoration(link, useMetaKey));
}
}
let decorations = this.editor.deltaDecorations(oldDecorations, newDecorations);
this.currentOccurrences = {};
this.activeLinkDecorationId = null;
for (let i = 0, len = decorations.length; i < len; i++) {
let occurance = new LinkOccurrence(links[i], decorations[i]);
this.currentOccurrences[occurance.decorationId] = occurance;
}
}
_onEditorMouseMove(mouseEvent, withKey) {
const useMetaKey = (this.editor.getOption(68 /* 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(68 /* 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('/./')) {
relativePath = `.${fsPath.substr(1)}`;
}
else if (fsPath.startsWith('//./')) {
relativePath = `.${fsPath.substr(2)}`;
}
if (relativePath) {
uri = resources.joinPath(modelUri, relativePath);
}
}
}
}
return this.openerService.open(uri, { openToSide, fromUserGesture, allowContributedOpeners: true, allowCommands: true });
}, err => {
const messageOrError = err instanceof Error ? err.message : err;
// different error cases
if (messageOrError === 'invalid') {
this.notificationService.warn(nls.localize(7, null, link.url.toString()));
}
else if (messageOrError === 'missing') {
this.notificationService.warn(nls.localize(8, null));
}
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 /* CONTENT_TEXT */)
&& (mouseEvent.hasTriggerModifier || (withKey && withKey.keyCodeIsTriggerKey)));
}
stop() {
var _a;
this.timeout.cancel();
if (this.activeLinksList) {
(_a = this.activeLinksList) === null || _a === void 0 ? void 0 : _a.dispose();
this.activeLinksList = null;
}
if (this.computePromise) {
this.computePromise.cancel();
this.computePromise = null;
}
}
dispose() {
this.listenersToRemove.dispose();
this.stop();
this.timeout.dispose();
}
};
LinkDetector.ID = 'editor.linkDetector';
LinkDetector.RECOMPUTE_TIME = 1000; // ms
LinkDetector = __decorate([
__param(1, opener_1.IOpenerService),
__param(2, notification_1.INotificationService)
], LinkDetector);
exports.LinkDetector = LinkDetector;
class OpenLinkAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.openLink',
label: nls.localize(9, null),
alias: 'Open Link',
precondition: undefined
});
}
run(accessor, editor) {
let linkDetector = LinkDetector.get(editor);
if (!linkDetector) {
return;
}
if (!editor.hasModel()) {
return;
}
let selections = editor.getSelections();
for (let sel of selections) {
let link = linkDetector.getLinkOccurrence(sel.getEndPosition());
if (link) {
linkDetector.openLinkOccurrence(link, false);
}
}
}
}
(0, editorExtensions_1.registerEditorContribution)(LinkDetector.ID, LinkDetector);
(0, editorExtensions_1.registerEditorAction)(OpenLinkAction);
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const activeLinkForeground = theme.getColor(colorRegistry_1.editorActiveLinkForeground);
if (activeLinkForeground) {
collector.addRule(`.monaco-editor .detected-link-active { color: ${activeLinkForeground} !important; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/message/messageController*/], __M([0/*require*/,1/*exports*/,508/*vs/nls!vs/editor/contrib/message/messageController*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,44/*vs/base/browser/ui/aria/aria*/,3/*vs/editor/common/core/range*/,14/*vs/editor/browser/editorExtensions*/,16/*vs/platform/contextkey/common/contextkey*/,11/*vs/platform/theme/common/themeService*/,22/*vs/platform/theme/common/colorRegistry*/,100/*vs/platform/theme/common/theme*/,356/*vs/css!vs/editor/contrib/message/messageController*/]), function (require, exports, nls, async_1, lifecycle_1, aria_1, range_1, editorExtensions_1, contextkey_1, themeService_1, colorRegistry_1, theme_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageController = void 0;
let MessageController = class MessageController {
constructor(editor, contextKeyService) {
this._messageWidget = new lifecycle_1.MutableDisposable();
this._messageListeners = new lifecycle_1.DisposableStore();
this._editor = editor;
this._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService);
this._editorListener = this._editor.onDidAttemptReadOnlyEdit(() => this._onDidAttemptReadOnlyEdit());
}
static get(editor) {
return editor.getContribution(MessageController.ID);
}
dispose() {
this._editorListener.dispose();
this._messageListeners.dispose();
this._messageWidget.dispose();
this._visible.reset();
}
showMessage(message, position) {
(0, aria_1.alert)(message);
this._visible.set(true);
this._messageWidget.clear();
this._messageListeners.clear();
this._messageWidget.value = new MessageWidget(this._editor, position, message);
// close on blur, cursor, model change, dispose
this._messageListeners.add(this._editor.onDidBlurEditorText(() => 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()));
// 3sec
this._messageListeners.add(new async_1.TimeoutTimer(() => this.closeMessage(), 3000));
// 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));
}
}
_onDidAttemptReadOnlyEdit() {
if (this._editor.hasModel()) {
this.showMessage(nls.localize(1, null), this._editor.getPosition());
}
}
};
MessageController.ID = 'editor.contrib.messageController';
MessageController.MESSAGE_VISIBLE = new contextkey_1.RawContextKey('messageVisible', false, nls.localize(0, null));
MessageController = __decorate([
__param(1, contextkey_1.IContextKeyService)
], MessageController);
exports.MessageController = 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 /* EditorContrib */ + 30,
primary: 9 /* Escape */
}
}));
class MessageWidget {
constructor(editor, { lineNumber, column }, text) {
// Editor.IContentWidget.allowEditorOverflow
this.allowEditorOverflow = true;
this.suppressMouseDown = false;
this._editor = editor;
this._editor.revealLinesInCenterIfOutsideViewport(lineNumber, lineNumber, 0 /* Smooth */);
this._position = { lineNumber, column: column - 1 };
this._domNode = document.createElement('div');
this._domNode.classList.add('monaco-editor-overlaymessage');
const anchorTop = document.createElement('div');
anchorTop.classList.add('anchor', 'top');
this._domNode.appendChild(anchorTop);
const message = document.createElement('div');
message.classList.add('message');
message.textContent = 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');
}
static fadeOut(messageWidget) {
let handle;
const dispose = () => {
messageWidget.dispose();
clearTimeout(handle);
messageWidget.getDomNode().removeEventListener('animationend', dispose);
};
handle = setTimeout(dispose, 110);
messageWidget.getDomNode().addEventListener('animationend', dispose);
messageWidget.getDomNode().classList.add('fadeOut');
return { dispose };
}
dispose() {
this._editor.removeContentWidget(this);
}
getId() {
return 'messageoverlay';
}
getDomNode() {
return this._domNode;
}
getPosition() {
return { position: this._position, preference: [1 /* ABOVE */, 2 /* BELOW */] };
}
afterRender(position) {
this._domNode.classList.toggle('below', position === 2 /* BELOW */);
}
}
(0, editorExtensions_1.registerEditorContribution)(MessageController.ID, MessageController);
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const border = theme.getColor(colorRegistry_1.inputValidationInfoBorder);
if (border) {
let borderWidth = theme.type === theme_1.ColorScheme.HIGH_CONTRAST ? 2 : 1;
collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .anchor.below { border-top-color: ${border}; }`);
collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .anchor.top { border-bottom-color: ${border}; }`);
collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .message { border: ${borderWidth}px solid ${border}; }`);
}
const background = theme.getColor(colorRegistry_1.inputValidationInfoBackground);
if (background) {
collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .message { background-color: ${background}; }`);
}
const foreground = theme.getColor(colorRegistry_1.inputValidationInfoForeground);
if (foreground) {
collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .message { color: ${foreground}; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
define(__m[649/*vs/editor/contrib/codeAction/codeActionUi*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,155/*vs/base/common/lazy*/,2/*vs/base/common/lifecycle*/,152/*vs/editor/contrib/message/messageController*/,9/*vs/platform/instantiation/common/instantiation*/,630/*vs/editor/contrib/codeAction/codeActionMenu*/,609/*vs/editor/contrib/codeAction/lightBulbWidget*/]), function (require, exports, errors_1, lazy_1, lifecycle_1, messageController_1, instantiation_1, codeActionMenu_1, lightBulbWidget_1) {
"use strict";
var _CodeActionUi_disposed;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeActionUi = void 0;
let CodeActionUi = class CodeActionUi extends lifecycle_1.Disposable {
constructor(_editor, quickFixActionId, preferredFixActionId, delegate, instantiationService) {
super();
this._editor = _editor;
this.delegate = delegate;
this._activeCodeActions = this._register(new lifecycle_1.MutableDisposable());
_CodeActionUi_disposed.set(this, false);
this._codeActionWidget = new lazy_1.Lazy(() => {
return this._register(instantiationService.createInstance(codeActionMenu_1.CodeActionMenu, this._editor, {
onSelectCodeAction: (action) => __awaiter(this, void 0, void 0, function* () {
this.delegate.applyCodeAction(action, /* retrigger */ true);
})
}));
});
this._lightBulbWidget = new lazy_1.Lazy(() => {
const widget = this._register(instantiationService.createInstance(lightBulbWidget_1.LightBulbWidget, this._editor, quickFixActionId, preferredFixActionId));
this._register(widget.onClick(e => this.showCodeActionList(e.trigger, e.actions, e, { includeDisabledActions: false })));
return widget;
});
}
dispose() {
__classPrivateFieldSet(this, _CodeActionUi_disposed, true, "f");
super.dispose();
}
update(newState) {
var _a, _b, _c;
return __awaiter(this, void 0, void 0, function* () {
if (newState.type !== 1 /* Triggered */) {
(_a = this._lightBulbWidget.rawValue) === null || _a === void 0 ? void 0 : _a.hide();
return;
}
let actions;
try {
actions = yield newState.actions;
}
catch (e) {
(0, errors_1.onUnexpectedError)(e);
return;
}
if (__classPrivateFieldGet(this, _CodeActionUi_disposed, "f")) {
return;
}
this._lightBulbWidget.getValue().update(actions, newState.trigger, newState.position);
if (newState.trigger.type === 1 /* Invoke */) {
if ((_b = newState.trigger.filter) === null || _b === void 0 ? void 0 : _b.include) { // Triggered for specific scope
// Check to see if we want to auto apply.
const validActionToApply = this.tryGetValidActionToApply(newState.trigger, actions);
if (validActionToApply) {
try {
yield this.delegate.applyCodeAction(validActionToApply, false);
}
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 = !!((_c = newState.trigger.filter) === null || _c === void 0 ? void 0 : _c.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._codeActionWidget.getValue().show(newState.trigger, actions, newState.position, { includeDisabledActions });
}
else {
// auto magically triggered
if (this._codeActionWidget.getValue().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" /* First */ && actions.validActions.length === 0)
|| (trigger.autoApply === "ifSingle" /* 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" /* First */ && actions.validActions.length > 0)
|| (trigger.autoApply === "ifSingle" /* IfSingle */ && actions.validActions.length === 1)) {
return actions.validActions[0];
}
return undefined;
}
showCodeActionList(trigger, actions, at, options) {
return __awaiter(this, void 0, void 0, function* () {
this._codeActionWidget.getValue().show(trigger, actions, at, options);
});
}
};
_CodeActionUi_disposed = new WeakMap();
CodeActionUi = __decorate([
__param(4, instantiation_1.IInstantiationService)
], CodeActionUi);
exports.CodeActionUi = CodeActionUi;
});
/*---------------------------------------------------------------------------------------------
* 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/codeAction/codeActionCommands*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,155/*vs/base/common/lazy*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,14/*vs/editor/browser/editorExtensions*/,138/*vs/editor/browser/services/bulkEditService*/,25/*vs/editor/common/editorContextKeys*/,151/*vs/editor/contrib/codeAction/codeAction*/,649/*vs/editor/contrib/codeAction/codeActionUi*/,152/*vs/editor/contrib/message/messageController*/,476/*vs/nls!vs/editor/contrib/codeAction/codeActionCommands*/,26/*vs/platform/commands/common/commands*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/,87/*vs/platform/markers/common/markers*/,34/*vs/platform/notification/common/notification*/,59/*vs/platform/progress/common/progress*/,89/*vs/platform/telemetry/common/telemetry*/,631/*vs/editor/contrib/codeAction/codeActionModel*/,137/*vs/editor/contrib/codeAction/types*/]), function (require, exports, cancellation_1, lazy_1, lifecycle_1, strings_1, editorExtensions_1, bulkEditService_1, editorContextKeys_1, codeAction_1, codeActionUi_1, messageController_1, nls, commands_1, contextkey_1, instantiation_1, markers_1, notification_1, progress_1, telemetry_1, codeActionModel_1, types_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AutoFixAction = exports.FixAllAction = exports.OrganizeImportsAction = exports.SourceAction = exports.RefactorAction = exports.CodeActionCommand = exports.QuickFixAction = exports.applyCodeAction = exports.QuickFixController = 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(0, null),
},
'apply': {
type: 'string',
description: nls.localize(1, null),
default: "ifSingle" /* IfSingle */,
enum: ["first" /* First */, "ifSingle" /* IfSingle */, "never" /* Never */],
enumDescriptions: [
nls.localize(2, null),
nls.localize(3, null),
nls.localize(4, null),
]
},
'preferred': {
type: 'boolean',
default: false,
description: nls.localize(5, null),
}
}
};
let QuickFixController = class QuickFixController extends lifecycle_1.Disposable {
constructor(editor, markerService, contextKeyService, progressService, _instantiationService) {
super();
this._instantiationService = _instantiationService;
this._editor = editor;
this._model = this._register(new codeActionModel_1.CodeActionModel(this._editor, markerService, contextKeyService, progressService));
this._register(this._model.onDidChangeState(newState => this.update(newState)));
this._ui = new lazy_1.Lazy(() => this._register(new codeActionUi_1.CodeActionUi(editor, QuickFixAction.Id, AutoFixAction.Id, {
applyCodeAction: (action, retrigger) => __awaiter(this, void 0, void 0, function* () {
try {
yield this._applyCodeAction(action);
}
finally {
if (retrigger) {
this._trigger({ type: 2 /* Auto */, filter: {} });
}
}
})
}, this._instantiationService)));
}
static get(editor) {
return editor.getContribution(QuickFixController.ID);
}
update(newState) {
this._ui.getValue().update(newState);
}
showCodeActions(trigger, actions, at) {
return this._ui.getValue().showCodeActionList(trigger, actions, at, { includeDisabledActions: false });
}
manualTriggerAtCurrentPosition(notAvailableMessage, filter, autoApply) {
if (!this._editor.hasModel()) {
return;
}
messageController_1.MessageController.get(this._editor).closeMessage();
const triggerPosition = this._editor.getPosition();
this._trigger({ type: 1 /* Invoke */, filter, autoApply, context: { notAvailableMessage, position: triggerPosition } });
}
_trigger(trigger) {
return this._model.trigger(trigger);
}
_applyCodeAction(action) {
return this._instantiationService.invokeFunction(applyCodeAction, action, this._editor);
}
};
QuickFixController.ID = 'editor.contrib.quickFixController';
QuickFixController = __decorate([
__param(1, markers_1.IMarkerService),
__param(2, contextkey_1.IContextKeyService),
__param(3, progress_1.IEditorProgressService),
__param(4, instantiation_1.IInstantiationService)
], QuickFixController);
exports.QuickFixController = QuickFixController;
function applyCodeAction(accessor, item, editor) {
return __awaiter(this, void 0, void 0, function* () {
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,
});
yield item.resolve(cancellation_1.CancellationToken.None);
if (item.action.edit) {
yield bulkEditService.apply(bulkEditService_1.ResourceEdit.convert(item.action.edit), { editor, label: item.action.title });
}
if (item.action.command) {
try {
yield commandService.executeCommand(item.action.command.id, ...(item.action.command.arguments || []));
}
catch (err) {
const message = asMessage(err);
notificationService.error(typeof message === 'string'
? message
: nls.localize(6, null));
}
}
});
}
exports.applyCodeAction = applyCodeAction;
function asMessage(err) {
if (typeof err === 'string') {
return err;
}
else if (err instanceof Error && typeof err.message === 'string') {
return err.message;
}
else {
return undefined;
}
}
function triggerCodeActionsForEditorSelection(editor, notAvailableMessage, filter, autoApply) {
if (editor.hasModel()) {
const controller = QuickFixController.get(editor);
if (controller) {
controller.manualTriggerAtCurrentPosition(notAvailableMessage, filter, autoApply);
}
}
}
class QuickFixAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: QuickFixAction.Id,
label: nls.localize(7, null),
alias: 'Quick Fix...',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasCodeActionsProvider),
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 84 /* US_DOT */,
weight: 100 /* EditorContrib */
}
});
}
run(_accessor, editor) {
return triggerCodeActionsForEditorSelection(editor, nls.localize(8, null), undefined, undefined);
}
}
exports.QuickFixAction = QuickFixAction;
QuickFixAction.Id = 'editor.action.quickFix';
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),
description: {
description: 'Trigger a code action',
args: [{ name: 'args', schema: argsSchema, }]
}
});
}
runEditorCommand(_accessor, editor, userArgs) {
const args = types_1.CodeActionCommandArgs.fromUser(userArgs, {
kind: types_1.CodeActionKind.Empty,
apply: "ifSingle" /* IfSingle */,
});
return triggerCodeActionsForEditorSelection(editor, typeof (userArgs === null || userArgs === void 0 ? void 0 : userArgs.kind) === 'string'
? args.preferred
? nls.localize(9, null, userArgs.kind)
: nls.localize(10, null, userArgs.kind)
: args.preferred
? nls.localize(11, null)
: nls.localize(12, null), {
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(13, null),
alias: 'Refactor...',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasCodeActionsProvider),
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 48 /* KEY_R */,
mac: {
primary: 256 /* WinCtrl */ | 1024 /* Shift */ | 48 /* KEY_R */
},
weight: 100 /* EditorContrib */
},
contextMenuOpts: {
group: '1_modification',
order: 2,
when: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(types_1.CodeActionKind.Refactor)),
},
description: {
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" /* Never */
});
return triggerCodeActionsForEditorSelection(editor, typeof (userArgs === null || userArgs === void 0 ? void 0 : userArgs.kind) === 'string'
? args.preferred
? nls.localize(14, null, userArgs.kind)
: nls.localize(15, null, userArgs.kind)
: args.preferred
? nls.localize(16, null)
: nls.localize(17, null), {
include: types_1.CodeActionKind.Refactor.contains(args.kind) ? args.kind : types_1.CodeActionKind.None,
onlyIncludePreferredActions: args.preferred,
}, args.apply);
}
}
exports.RefactorAction = RefactorAction;
class SourceAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: codeAction_1.sourceActionCommandId,
label: nls.localize(18, null),
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)),
},
description: {
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" /* Never */
});
return triggerCodeActionsForEditorSelection(editor, typeof (userArgs === null || userArgs === void 0 ? void 0 : userArgs.kind) === 'string'
? args.preferred
? nls.localize(19, null, userArgs.kind)
: nls.localize(20, null, userArgs.kind)
: args.preferred
? nls.localize(21, null)
: nls.localize(22, null), {
include: types_1.CodeActionKind.Source.contains(args.kind) ? args.kind : types_1.CodeActionKind.None,
includeSourceActions: true,
onlyIncludePreferredActions: args.preferred,
}, args.apply);
}
}
exports.SourceAction = SourceAction;
class OrganizeImportsAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: codeAction_1.organizeImportsCommandId,
label: nls.localize(23, null),
alias: 'Organize Imports',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(types_1.CodeActionKind.SourceOrganizeImports)),
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 1024 /* Shift */ | 512 /* Alt */ | 45 /* KEY_O */,
weight: 100 /* EditorContrib */
},
});
}
run(_accessor, editor) {
return triggerCodeActionsForEditorSelection(editor, nls.localize(24, null), { include: types_1.CodeActionKind.SourceOrganizeImports, includeSourceActions: true }, "ifSingle" /* IfSingle */);
}
}
exports.OrganizeImportsAction = OrganizeImportsAction;
class FixAllAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: codeAction_1.fixAllCommandId,
label: nls.localize(25, null),
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(26, null), { include: types_1.CodeActionKind.SourceFixAll, includeSourceActions: true }, "ifSingle" /* IfSingle */);
}
}
exports.FixAllAction = FixAllAction;
class AutoFixAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: AutoFixAction.Id,
label: nls.localize(27, null),
alias: 'Auto Fix...',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(types_1.CodeActionKind.QuickFix)),
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 512 /* Alt */ | 1024 /* Shift */ | 84 /* US_DOT */,
mac: {
primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 84 /* US_DOT */
},
weight: 100 /* EditorContrib */
}
});
}
run(_accessor, editor) {
return triggerCodeActionsForEditorSelection(editor, nls.localize(28, null), {
include: types_1.CodeActionKind.QuickFix,
onlyIncludePreferredActions: true
}, "ifSingle" /* IfSingle */);
}
}
exports.AutoFixAction = AutoFixAction;
AutoFixAction.Id = 'editor.action.autoFix';
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/codeAction/codeActionContributions*/], __M([0/*require*/,1/*exports*/,14/*vs/editor/browser/editorExtensions*/,268/*vs/editor/contrib/codeAction/codeActionCommands*/]), function (require, exports, editorExtensions_1, codeActionCommands_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
(0, editorExtensions_1.registerEditorContribution)(codeActionCommands_1.QuickFixController.ID, codeActionCommands_1.QuickFixController);
(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());
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/rename/rename*/], __M([0/*require*/,1/*exports*/,515/*vs/nls!vs/editor/contrib/rename/rename*/,12/*vs/base/common/errors*/,16/*vs/platform/contextkey/common/contextkey*/,59/*vs/platform/progress/common/progress*/,14/*vs/editor/browser/editorExtensions*/,25/*vs/editor/common/editorContextKeys*/,619/*vs/editor/contrib/rename/renameInputField*/,18/*vs/editor/common/modes*/,13/*vs/editor/common/core/position*/,44/*vs/base/browser/ui/aria/aria*/,3/*vs/editor/common/core/range*/,152/*vs/editor/contrib/message/messageController*/,66/*vs/editor/browser/core/editorState*/,34/*vs/platform/notification/common/notification*/,138/*vs/editor/browser/services/bulkEditService*/,24/*vs/base/common/uri*/,28/*vs/editor/browser/services/codeEditorService*/,23/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,15/*vs/base/common/async*/,70/*vs/platform/log/common/log*/,9/*vs/platform/instantiation/common/instantiation*/,32/*vs/platform/registry/common/platform*/,98/*vs/platform/configuration/common/configurationRegistry*/,142/*vs/editor/common/services/textResourceConfigurationService*/,20/*vs/base/common/types*/]), function (require, exports, nls, errors_1, contextkey_1, progress_1, editorExtensions_1, editorContextKeys_1, renameInputField_1, modes_1, position_1, aria_1, range_1, messageController_1, editorState_1, notification_1, bulkEditService_1, uri_1, codeEditorService_1, cancellation_1, lifecycle_1, async_1, log_1, instantiation_1, platform_1, configurationRegistry_1, textResourceConfigurationService_1, types_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RenameAction = exports.rename = void 0;
class RenameSkeleton {
constructor(model, position) {
this.model = model;
this.position = position;
this._providerRenameIdx = 0;
this._providers = modes_1.RenameProviderRegistry.ordered(model);
}
hasProvider() {
return this._providers.length > 0;
}
resolveRenameLocation(token) {
return __awaiter(this, void 0, void 0, function* () {
const rejects = [];
for (this._providerRenameIdx = 0; this._providerRenameIdx < this._providers.length; this._providerRenameIdx++) {
const provider = this._providers[this._providerRenameIdx];
if (!provider.resolveRenameLocation) {
break;
}
let res = yield provider.resolveRenameLocation(this.model, this.position, token);
if (!res) {
continue;
}
if (res.rejectReason) {
rejects.push(res.rejectReason);
continue;
}
return res;
}
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
};
});
}
provideRenameEdits(newName, token) {
return __awaiter(this, void 0, void 0, function* () {
return this._provideRenameEdits(newName, this._providerRenameIdx, [], token);
});
}
_provideRenameEdits(newName, i, rejects, token) {
return __awaiter(this, void 0, void 0, function* () {
const provider = this._providers[i];
if (!provider) {
return {
edits: [],
rejectReason: rejects.join('\n')
};
}
const result = yield provider.provideRenameEdits(this.model, this.position, newName, token);
if (!result) {
return this._provideRenameEdits(newName, i + 1, rejects.concat(nls.localize(0, null)), token);
}
else if (result.rejectReason) {
return this._provideRenameEdits(newName, i + 1, rejects.concat(result.rejectReason), token);
}
return result;
});
}
}
function rename(model, position, newName) {
return __awaiter(this, void 0, void 0, function* () {
const skeleton = new RenameSkeleton(model, position);
const loc = yield skeleton.resolveRenameLocation(cancellation_1.CancellationToken.None);
if (loc === null || loc === void 0 ? void 0 : loc.rejectReason) {
return { edits: [], rejectReason: loc.rejectReason };
}
return skeleton.provideRenameEdits(newName, cancellation_1.CancellationToken.None);
});
}
exports.rename = rename;
// --- register actions and commands
let RenameController = class RenameController {
constructor(editor, _instaService, _notificationService, _bulkEditService, _progressService, _logService, _configService) {
this.editor = editor;
this._instaService = _instaService;
this._notificationService = _notificationService;
this._bulkEditService = _bulkEditService;
this._progressService = _progressService;
this._logService = _logService;
this._configService = _configService;
this._dispoableStore = new lifecycle_1.DisposableStore();
this._cts = new cancellation_1.CancellationTokenSource();
this._renameInputField = this._dispoableStore.add(new async_1.IdleValue(() => this._dispoableStore.add(this._instaService.createInstance(renameInputField_1.RenameInputField, this.editor, ['acceptRenameInput', 'acceptRenameInputWithPreview']))));
}
static get(editor) {
return editor.getContribution(RenameController.ID);
}
dispose() {
this._dispoableStore.dispose();
this._cts.dispose(true);
}
run() {
return __awaiter(this, void 0, void 0, function* () {
this._cts.dispose(true);
if (!this.editor.hasModel()) {
return undefined;
}
const position = this.editor.getPosition();
const skeleton = new RenameSkeleton(this.editor.getModel(), position);
if (!skeleton.hasProvider()) {
return undefined;
}
this._cts = new editorState_1.EditorStateCancellationTokenSource(this.editor, 4 /* Position */ | 1 /* Value */);
// resolve rename location
let loc;
try {
const resolveLocationOperation = skeleton.resolveRenameLocation(this._cts.token);
this._progressService.showWhile(resolveLocationOperation, 250);
loc = yield resolveLocationOperation;
}
catch (e) {
messageController_1.MessageController.get(this.editor).showMessage(e || nls.localize(1, null), position);
return undefined;
}
if (!loc) {
return undefined;
}
if (loc.rejectReason) {
messageController_1.MessageController.get(this.editor).showMessage(loc.rejectReason, position);
return undefined;
}
if (this._cts.token.isCancellationRequested) {
return undefined;
}
this._cts.dispose();
this._cts = new editorState_1.EditorStateCancellationTokenSource(this.editor, 4 /* Position */ | 1 /* Value */, loc.range);
// do rename at location
let selection = this.editor.getSelection();
let selectionStart = 0;
let selectionEnd = loc.text.length;
if (!range_1.Range.isEmpty(selection) && !range_1.Range.spansMultipleLines(selection) && range_1.Range.containsRange(loc.range, selection)) {
selectionStart = Math.max(0, selection.startColumn - loc.range.startColumn);
selectionEnd = Math.min(loc.range.endColumn, selection.endColumn) - loc.range.startColumn;
}
const supportPreview = this._bulkEditService.hasPreviewHandler() && this._configService.getValue(this.editor.getModel().uri, 'editor.rename.enablePreview');
const inputFieldResult = yield this._renameInputField.value.getInput(loc.range, loc.text, selectionStart, selectionEnd, supportPreview, this._cts.token);
// no result, only hint to focus the editor or not
if (typeof inputFieldResult === 'boolean') {
if (inputFieldResult) {
this.editor.focus();
}
return undefined;
}
this.editor.focus();
const renameOperation = (0, async_1.raceCancellation)(skeleton.provideRenameEdits(inputFieldResult.newName, this._cts.token), this._cts.token).then((renameResult) => __awaiter(this, void 0, void 0, function* () {
if (!renameResult || !this.editor.hasModel()) {
return;
}
if (renameResult.rejectReason) {
this._notificationService.info(renameResult.rejectReason);
return;
}
this._bulkEditService.apply(bulkEditService_1.ResourceEdit.convert(renameResult), {
editor: this.editor,
showPreview: inputFieldResult.wantsPreview,
label: nls.localize(2, null, loc === null || loc === void 0 ? void 0 : loc.text),
quotableLabel: nls.localize(3, null, loc === null || loc === void 0 ? void 0 : loc.text),
}).then(result => {
if (result.ariaSummary) {
(0, aria_1.alert)(nls.localize(4, null, loc.text, inputFieldResult.newName, result.ariaSummary));
}
}).catch(err => {
this._notificationService.error(nls.localize(5, null));
this._logService.error(err);
});
}), err => {
this._notificationService.error(nls.localize(6, null));
this._logService.error(err);
});
this._progressService.showWhile(renameOperation, 250);
return renameOperation;
});
}
acceptRenameInput(wantsPreview) {
this._renameInputField.value.acceptInput(wantsPreview);
}
cancelRenameInput() {
this._renameInputField.value.cancelInput(true);
}
};
RenameController.ID = 'editor.contrib.renameController';
RenameController = __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, textResourceConfigurationService_1.ITextResourceConfigurationService)
], RenameController);
// ---- action implementation
class RenameAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.rename',
label: nls.localize(7, null),
alias: 'Rename Symbol',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasRenameProvider),
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 60 /* F2 */,
weight: 100 /* 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 controller = RenameController.get(editor);
if (controller) {
return controller.run();
}
return Promise.resolve();
}
}
exports.RenameAction = RenameAction;
(0, editorExtensions_1.registerEditorContribution)(RenameController.ID, RenameController);
(0, editorExtensions_1.registerEditorAction)(RenameAction);
const RenameCommand = editorExtensions_1.EditorCommand.bindToContribution(RenameController.get);
(0, editorExtensions_1.registerEditorCommand)(new RenameCommand({
id: 'acceptRenameInput',
precondition: renameInputField_1.CONTEXT_RENAME_INPUT_VISIBLE,
handler: x => x.acceptRenameInput(false),
kbOpts: {
weight: 100 /* EditorContrib */ + 99,
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 3 /* Enter */
}
}));
(0, editorExtensions_1.registerEditorCommand)(new RenameCommand({
id: 'acceptRenameInputWithPreview',
precondition: contextkey_1.ContextKeyExpr.and(renameInputField_1.CONTEXT_RENAME_INPUT_VISIBLE, contextkey_1.ContextKeyExpr.has('config.editor.rename.enablePreview')),
handler: x => x.acceptRenameInput(true),
kbOpts: {
weight: 100 /* EditorContrib */ + 99,
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 1024 /* Shift */ + 3 /* Enter */
}
}));
(0, editorExtensions_1.registerEditorCommand)(new RenameCommand({
id: 'cancelRenameInput',
precondition: renameInputField_1.CONTEXT_RENAME_INPUT_VISIBLE,
handler: x => x.cancelRenameInput(),
kbOpts: {
weight: 100 /* EditorContrib */ + 99,
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 9 /* Escape */,
secondary: [1024 /* Shift */ | 9 /* Escape */]
}
}));
// ---- api bridge command
(0, editorExtensions_1.registerModelAndPositionCommand)('_executeDocumentRenameProvider', function (model, position, ...args) {
const [newName] = args;
(0, types_1.assertType)(typeof newName === 'string');
return rename(model, position, newName);
});
//todo@jrieken use editor options world
platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).registerConfiguration({
id: 'editor',
properties: {
'editor.rename.enablePreview': {
scope: 5 /* LANGUAGE_OVERRIDABLE */,
description: nls.localize(8, null),
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[652/*vs/editor/contrib/smartSelect/smartSelect*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,23/*vs/base/common/cancellation*/,14/*vs/editor/browser/editorExtensions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,25/*vs/editor/common/editorContextKeys*/,18/*vs/editor/common/modes*/,517/*vs/nls!vs/editor/contrib/smartSelect/smartSelect*/,33/*vs/platform/actions/common/actions*/,421/*vs/editor/contrib/smartSelect/wordSelections*/,234/*vs/editor/contrib/smartSelect/bracketSelections*/,26/*vs/platform/commands/common/commands*/,12/*vs/base/common/errors*/]), function (require, exports, arrays, cancellation_1, editorExtensions_1, position_1, range_1, selection_1, editorContextKeys_1, modes, nls, actions_1, wordSelections_1, bracketSelections_1, commands_1, errors_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.provideSelectionRanges = void 0;
class SelectionRanges {
constructor(index, ranges) {
this.index = index;
this.ranges = ranges;
}
mov(fwd) {
let 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;
}
}
class SmartSelectController {
constructor(_editor) {
this._editor = _editor;
this._ignoreSelection = false;
}
static get(editor) {
return editor.getContribution(SmartSelectController.ID);
}
dispose() {
var _a;
(_a = this._selectionListener) === null || _a === void 0 ? void 0 : _a.dispose();
}
run(forward) {
return __awaiter(this, void 0, void 0, function* () {
if (!this._editor.hasModel()) {
return;
}
const selections = this._editor.getSelections();
const model = this._editor.getModel();
if (!modes.SelectionRangeRegistry.has(model)) {
return;
}
if (!this._state) {
yield provideSelectionRanges(model, selections.map(s => s.getPosition()), this._editor.getOption(101 /* smartSelect */), cancellation_1.CancellationToken.None).then(ranges => {
var _a;
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
(_a = this._selectionListener) === null || _a === void 0 ? void 0 : _a.dispose();
this._selectionListener = this._editor.onDidChangeCursorPosition(() => {
var _a;
if (!this._ignoreSelection) {
(_a = this._selectionListener) === null || _a === void 0 ? void 0 : _a.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;
}
});
}
}
SmartSelectController.ID = 'editor.contrib.smartSelectController';
class AbstractSmartSelect extends editorExtensions_1.EditorAction {
constructor(forward, opts) {
super(opts);
this._forward = forward;
}
run(_accessor, editor) {
return __awaiter(this, void 0, void 0, function* () {
let controller = SmartSelectController.get(editor);
if (controller) {
yield controller.run(this._forward);
}
});
}
}
class GrowSelectionAction extends AbstractSmartSelect {
constructor() {
super(true, {
id: 'editor.action.smartSelect.expand',
label: nls.localize(0, null),
alias: 'Expand Selection',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 1024 /* Shift */ | 512 /* Alt */ | 17 /* RightArrow */,
mac: {
primary: 2048 /* CtrlCmd */ | 256 /* WinCtrl */ | 1024 /* Shift */ | 17 /* RightArrow */,
secondary: [256 /* WinCtrl */ | 1024 /* Shift */ | 17 /* RightArrow */],
},
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarSelectionMenu,
group: '1_basic',
title: nls.localize(1, null),
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(2, null),
alias: 'Shrink Selection',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 1024 /* Shift */ | 512 /* Alt */ | 15 /* LeftArrow */,
mac: {
primary: 2048 /* CtrlCmd */ | 256 /* WinCtrl */ | 1024 /* Shift */ | 15 /* LeftArrow */,
secondary: [256 /* WinCtrl */ | 1024 /* Shift */ | 15 /* LeftArrow */],
},
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarSelectionMenu,
group: '1_basic',
title: nls.localize(3, null),
order: 3
}
});
}
}
(0, editorExtensions_1.registerEditorContribution)(SmartSelectController.ID, SmartSelectController);
(0, editorExtensions_1.registerEditorAction)(GrowSelectionAction);
(0, editorExtensions_1.registerEditorAction)(ShrinkSelectionAction);
// word selection
modes.SelectionRangeRegistry.register('*', new wordSelections_1.WordSelectionRangeProvider());
function provideSelectionRanges(model, positions, options, token) {
return __awaiter(this, void 0, void 0, function* () {
const providers = modes.SelectionRangeRegistry.all(model);
if (providers.length === 1) {
// add word selection and bracket selection when no provider exists
providers.unshift(new bracketSelections_1.BracketSelectionRangeProvider());
}
let work = [];
let 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));
}
yield 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
let 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
let 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;
});
});
}
exports.provideSelectionRanges = provideSelectionRanges;
(0, editorExtensions_1.registerModelCommand)('_executeSelectionRangeProvider', function (model, ...args) {
const [positions] = args;
return provideSelectionRanges(model, positions, { selectLeadingAndTrailingWhitespace: true }, cancellation_1.CancellationToken.None);
});
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/suggest/suggest*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,18/*vs/editor/common/modes*/,13/*vs/editor/common/core/position*/,16/*vs/platform/contextkey/common/contextkey*/,23/*vs/base/common/cancellation*/,3/*vs/editor/common/core/range*/,67/*vs/base/common/filters*/,2/*vs/base/common/lifecycle*/,33/*vs/platform/actions/common/actions*/,116/*vs/editor/contrib/snippet/snippetParser*/,81/*vs/base/common/stopwatch*/,26/*vs/platform/commands/common/commands*/,20/*vs/base/common/types*/,24/*vs/base/common/uri*/,68/*vs/editor/common/services/resolverService*/,520/*vs/nls!vs/editor/contrib/suggest/suggest*/]), function (require, exports, errors_1, modes, position_1, contextkey_1, cancellation_1, range_1, filters_1, lifecycle_1, actions_1, snippetParser_1, stopwatch_1, commands_1, types_1, uri_1, resolverService_1, nls_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.showSimpleSuggestions = exports.getSuggestionComparator = exports.provideSuggestionItems = exports.CompletionItemModel = exports.getSnippetSuggestSupport = exports.CompletionOptions = exports.CompletionItem = exports.suggestWidgetStatusbarMenu = exports.Context = void 0;
exports.Context = {
Visible: new contextkey_1.RawContextKey('suggestWidgetVisible', false, (0, nls_1.localize)(0, null)),
DetailsVisible: new contextkey_1.RawContextKey('suggestWidgetDetailsVisible', false, (0, nls_1.localize)(1, null)),
MultipleSuggestions: new contextkey_1.RawContextKey('suggestWidgetMultipleSuggestions', false, (0, nls_1.localize)(2, null)),
MakesTextEdit: new contextkey_1.RawContextKey('suggestionMakesTextEdit', true, (0, nls_1.localize)(3, null)),
AcceptSuggestionsOnEnter: new contextkey_1.RawContextKey('acceptSuggestionOnEnter', true, (0, nls_1.localize)(4, null)),
HasInsertAndReplaceRange: new contextkey_1.RawContextKey('suggestionHasInsertAndReplaceRange', false, (0, nls_1.localize)(5, null)),
InsertMode: new contextkey_1.RawContextKey('suggestionInsertMode', undefined, { type: 'string', description: (0, nls_1.localize)(6, null) }),
CanResolve: new contextkey_1.RawContextKey('suggestionCanResolve', false, (0, nls_1.localize)(7, null)),
};
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();
// 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._isResolved = true;
}
}
// ---- resolving
get isResolved() {
return !!this._isResolved;
}
resolve(token) {
return __awaiter(this, void 0, void 0, function* () {
if (!this._resolveCache) {
const sub = token.onCancellationRequested(() => {
this._resolveCache = undefined;
this._isResolved = false;
});
this._resolveCache = Promise.resolve(this.provider.resolveCompletionItem(this.completion, token)).then(value => {
Object.assign(this.completion, value);
this._isResolved = true;
sub.dispose();
}, err => {
if ((0, errors_1.isPromiseCanceledError)(err)) {
// the IPC queue will reject the request with the
// cancellation error -> reset cached
this._resolveCache = undefined;
this._isResolved = false;
}
});
}
return this._resolveCache;
});
}
}
exports.CompletionItem = CompletionItem;
class CompletionOptions {
constructor(snippetSortOrder = 2 /* Bottom */, kindFilter = new Set(), providerFilter = new Set(), showDeprecated = true) {
this.snippetSortOrder = snippetSortOrder;
this.kindFilter = kindFilter;
this.providerFilter = providerFilter;
this.showDeprecated = showDeprecated;
}
}
exports.CompletionOptions = CompletionOptions;
CompletionOptions.default = new CompletionOptions();
let _snippetSuggestSupport;
function getSnippetSuggestSupport() {
return _snippetSuggestSupport;
}
exports.getSnippetSuggestSupport = getSnippetSuggestSupport;
class CompletionItemModel {
constructor(items, needsClipboard, durations, disposable) {
this.items = items;
this.needsClipboard = needsClipboard;
this.durations = durations;
this.disposable = disposable;
}
}
exports.CompletionItemModel = CompletionItemModel;
function provideSuggestionItems(model, position, options = CompletionOptions.default, context = { triggerKind: 0 /* Invoke */ }, token = cancellation_1.CancellationToken.None) {
return __awaiter(this, void 0, void 0, function* () {
const sw = new stopwatch_1.StopWatch(true);
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) => {
var _a, _b, _c;
if (!container) {
return;
}
for (let suggestion of container.suggestions) {
if (!options.kindFilter.has(suggestion.kind)) {
// skip if not showing deprecated suggestions
if (!options.showDeprecated && ((_a = suggestion === null || suggestion === void 0 ? void 0 : suggestion.tags) === null || _a === void 0 ? void 0 : _a.includes(1 /* 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 /* InsertAsSnippet */) {
needsClipboard = snippetParser_1.SnippetParser.guessNeedsClipboard(suggestion.insertText);
}
result.push(new CompletionItem(position, suggestion, container, provider));
}
}
if ((0, lifecycle_1.isDisposable)(container)) {
disposables.add(container);
}
durations.push({
providerName: (_b = provider._debugDisplayName) !== null && _b !== void 0 ? _b : 'unkown_provider', elapsedProvider: (_c = container.duration) !== null && _c !== void 0 ? _c : -1, elapsedOverall: sw.elapsed()
});
};
// 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 = (() => __awaiter(this, void 0, void 0, function* () {
if (!_snippetSuggestSupport || options.kindFilter.has(27 /* Snippet */)) {
return;
}
if (options.providerFilter.size > 0 && !options.providerFilter.has(_snippetSuggestSupport)) {
return;
}
const sw = new stopwatch_1.StopWatch(true);
const list = yield _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 (let providerGroup of modes.CompletionProviderRegistry.orderedGroups(model)) {
// for each support in the group ask for suggestions
let lenBefore = result.length;
yield Promise.all(providerGroup.map((provider) => __awaiter(this, void 0, void 0, function* () {
if (options.providerFilter.size > 0 && !options.providerFilter.has(provider)) {
return;
}
try {
const sw = new stopwatch_1.StopWatch(true);
const list = yield provider.provideCompletionItems(model, position, context, token);
onCompletionList(provider, list, sw);
}
catch (err) {
(0, errors_1.onUnexpectedExternalError)(err);
}
})));
if (lenBefore !== result.length || token.isCancellationRequested) {
break;
}
}
yield snippetCompletions;
if (token.isCancellationRequested) {
disposables.dispose();
return Promise.reject((0, errors_1.canceled)());
}
return new CompletionItemModel(result.sort(getSuggestionComparator(options.snippetSortOrder)), needsClipboard, { entries: durations, elapsed: sw.elapsed() }, disposables);
});
}
exports.provideSuggestionItems = provideSuggestionItems;
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.completion.label < b.completion.label) {
return -1;
}
else if (a.completion.label > b.completion.label) {
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 /* Snippet */) {
return -1;
}
else if (b.completion.kind === 27 /* Snippet */) {
return 1;
}
}
return defaultComparator(a, b);
}
function snippetDownComparator(a, b) {
if (a.completion.kind !== b.completion.kind) {
if (a.completion.kind === 27 /* Snippet */) {
return 1;
}
else if (b.completion.kind === 27 /* Snippet */) {
return -1;
}
}
return defaultComparator(a, b);
}
const _snippetComparators = new Map();
_snippetComparators.set(0 /* Top */, snippetUpComparator);
_snippetComparators.set(2 /* Bottom */, snippetDownComparator);
_snippetComparators.set(1 /* Inline */, defaultComparator);
function getSuggestionComparator(snippetConfig) {
return _snippetComparators.get(snippetConfig);
}
exports.getSuggestionComparator = getSuggestionComparator;
commands_1.CommandsRegistry.registerCommand('_executeCompletionItemProvider', (accessor, ...args) => __awaiter(void 0, void 0, void 0, function* () {
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 ref = yield accessor.get(resolverService_1.ITextModelService).createModelReference(uri);
try {
const result = {
incomplete: false,
suggestions: []
};
const resolving = [];
const completions = yield provideSuggestionItems(ref.object.textEditorModel, position_1.Position.lift(position), undefined, { triggerCharacter, triggerKind: triggerCharacter ? 1 /* TriggerCharacter */ : 0 /* Invoke */ });
for (const item of completions.items) {
if (resolving.length < (maxItemsToResolve !== null && maxItemsToResolve !== void 0 ? maxItemsToResolve : 0)) {
resolving.push(item.resolve(cancellation_1.CancellationToken.None));
}
result.incomplete = result.incomplete || item.container.incomplete;
result.suggestions.push(item.completion);
}
try {
yield Promise.all(resolving);
return result;
}
finally {
setTimeout(() => completions.disposable.dispose(), 100);
}
}
finally {
ref.dispose();
}
}));
const _provider = new class {
constructor() {
this.onlyOnceSuggestions = [];
}
provideCompletionItems() {
let suggestions = this.onlyOnceSuggestions.slice(0);
let result = { suggestions };
this.onlyOnceSuggestions.length = 0;
return result;
}
};
modes.CompletionProviderRegistry.register('*', _provider);
function showSimpleSuggestions(editor, suggestions) {
setTimeout(() => {
_provider.onlyOnceSuggestions.push(...suggestions);
editor.getContribution('editor.contrib.suggestController').triggerSuggest(new Set().add(_provider));
}, 0);
}
exports.showSimpleSuggestions = showSimpleSuggestions;
});
/*---------------------------------------------------------------------------------------------
* 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/toggleTabFocusMode/toggleTabFocusMode*/], __M([0/*require*/,1/*exports*/,527/*vs/nls!vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/,44/*vs/base/browser/ui/aria/aria*/,14/*vs/editor/browser/editorExtensions*/,190/*vs/editor/common/config/commonEditorConfig*/]), function (require, exports, nls, aria_1, editorExtensions_1, commonEditorConfig_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ToggleTabFocusModeAction = void 0;
class ToggleTabFocusModeAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: ToggleTabFocusModeAction.ID,
label: nls.localize(0, null),
alias: 'Toggle Tab Key Moves Focus',
precondition: undefined,
kbOpts: {
kbExpr: null,
primary: 2048 /* CtrlCmd */ | 43 /* KEY_M */,
mac: { primary: 256 /* WinCtrl */ | 1024 /* Shift */ | 43 /* KEY_M */ },
weight: 100 /* EditorContrib */
}
});
}
run(accessor, editor) {
const oldValue = commonEditorConfig_1.TabFocus.getTabFocusMode();
const newValue = !oldValue;
commonEditorConfig_1.TabFocus.setTabFocusMode(newValue);
if (newValue) {
(0, aria_1.alert)(nls.localize(1, null));
}
else {
(0, aria_1.alert)(nls.localize(2, null));
}
}
}
exports.ToggleTabFocusModeAction = ToggleTabFocusModeAction;
ToggleTabFocusModeAction.ID = 'editor.action.toggleTabFocusMode';
(0, editorExtensions_1.registerEditorAction)(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[653/*vs/editor/contrib/tokenization/tokenization*/], __M([0/*require*/,1/*exports*/,528/*vs/nls!vs/editor/contrib/tokenization/tokenization*/,14/*vs/editor/browser/editorExtensions*/,81/*vs/base/common/stopwatch*/]), function (require, exports, nls, editorExtensions_1, stopwatch_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class ForceRetokenizeAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.forceRetokenize',
label: nls.localize(0, null),
alias: 'Developer: Force Retokenize',
precondition: undefined
});
}
run(accessor, editor) {
if (!editor.hasModel()) {
return;
}
const model = editor.getModel();
model.resetTokenization();
const sw = new stopwatch_1.StopWatch(true);
model.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[654/*vs/editor/contrib/unusualLineTerminators/unusualLineTerminators*/], __M([0/*require*/,1/*exports*/,529/*vs/nls!vs/editor/contrib/unusualLineTerminators/unusualLineTerminators*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,28/*vs/editor/browser/services/codeEditorService*/,120/*vs/platform/dialogs/common/dialogs*/,43/*vs/base/common/resources*/]), function (require, exports, nls, lifecycle_1, editorExtensions_1, codeEditorService_1, dialogs_1, resources_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 {
constructor(_editor, _dialogService, _codeEditorService) {
super();
this._editor = _editor;
this._dialogService = _dialogService;
this._codeEditorService = _codeEditorService;
this._config = this._editor.getOption(112 /* unusualLineTerminators */);
this._register(this._editor.onDidChangeConfiguration((e) => {
if (e.hasChanged(112 /* unusualLineTerminators */)) {
this._config = this._editor.getOption(112 /* 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();
}));
}
_checkForUnusualLineTerminators() {
return __awaiter(this, void 0, void 0, function* () {
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(79 /* readOnly */)) {
// read only editor => sorry!
return;
}
if (this._config === 'auto') {
// just do it!
model.removeUnusualLineTerminators(this._editor.getSelections());
return;
}
const result = yield this._dialogService.confirm({
title: nls.localize(0, null),
message: nls.localize(1, null),
detail: nls.localize(2, null, (0, resources_1.basename)(model.uri)),
primaryButton: nls.localize(3, null),
secondaryButton: nls.localize(4, null)
});
if (!result.confirmed) {
// this model should be ignored
writeIgnoreState(this._codeEditorService, model, true);
return;
}
model.removeUnusualLineTerminators(this._editor.getSelections());
});
}
};
UnusualLineTerminatorsDetector.ID = 'editor.contrib.unusualLineTerminatorsDetector';
UnusualLineTerminatorsDetector = __decorate([
__param(1, dialogs_1.IDialogService),
__param(2, codeEditorService_1.ICodeEditorService)
], UnusualLineTerminatorsDetector);
exports.UnusualLineTerminatorsDetector = UnusualLineTerminatorsDetector;
(0, editorExtensions_1.registerEditorContribution)(UnusualLineTerminatorsDetector.ID, UnusualLineTerminatorsDetector);
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/wordHighlighter/wordHighlighter*/], __M([0/*require*/,1/*exports*/,530/*vs/nls!vs/editor/contrib/wordHighlighter/wordHighlighter*/,19/*vs/base/common/arrays*/,15/*vs/base/common/async*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,25/*vs/editor/common/editorContextKeys*/,53/*vs/editor/common/model*/,31/*vs/editor/common/model/textModel*/,18/*vs/editor/common/modes*/,16/*vs/platform/contextkey/common/contextkey*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,44/*vs/base/browser/ui/aria/aria*/]), function (require, exports, nls, arrays, async_1, cancellation_1, errors_1, lifecycle_1, editorExtensions_1, range_1, editorContextKeys_1, model_1, textModel_1, modes_1, contextkey_1, colorRegistry_1, themeService_1, aria_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOccurrencesAtPosition = void 0;
const editorWordHighlight = (0, colorRegistry_1.registerColor)('editor.wordHighlightBackground', { dark: '#575757B8', light: '#57575740', hc: null }, nls.localize(0, null), true);
const editorWordHighlightStrong = (0, colorRegistry_1.registerColor)('editor.wordHighlightStrongBackground', { dark: '#004972B8', light: '#0e639c40', hc: null }, nls.localize(1, null), true);
const editorWordHighlightBorder = (0, colorRegistry_1.registerColor)('editor.wordHighlightBorder', { light: null, dark: null, hc: colorRegistry_1.activeContrastBorder }, nls.localize(2, null));
const editorWordHighlightStrongBorder = (0, colorRegistry_1.registerColor)('editor.wordHighlightStrongBorder', { light: null, dark: null, hc: colorRegistry_1.activeContrastBorder }, nls.localize(3, null));
const overviewRulerWordHighlightForeground = (0, colorRegistry_1.registerColor)('editorOverviewRuler.wordHighlightForeground', { dark: '#A0A0A0CC', light: '#A0A0A0CC', hc: '#A0A0A0CC' }, nls.localize(4, null), true);
const overviewRulerWordHighlightStrongForeground = (0, colorRegistry_1.registerColor)('editorOverviewRuler.wordHighlightStrongForeground', { dark: '#C0A0C0CC', light: '#C0A0C0CC', hc: '#C0A0C0CC' }, nls.localize(5, null), true);
const ctxHasWordHighlights = new contextkey_1.RawContextKey('hasWordHighlights', false);
function getOccurrencesAtPosition(model, position, token) {
const orderedByScore = modes_1.DocumentHighlightProviderRegistry.ordered(model);
// in order of score ask the occurrences provider
// until someone response with a good result
// (good = none empty array)
return (0, async_1.first)(orderedByScore.map(provider => () => {
return Promise.resolve(provider.provideDocumentHighlights(model, position, token))
.then(undefined, errors_1.onUnexpectedExternalError);
}), arrays.isNonEmptyArray);
}
exports.getOccurrencesAtPosition = getOccurrencesAtPosition;
class OccurenceAtPositionRequest {
constructor(model, selection, wordSeparators) {
this._wordRange = this._getCurrentWordRange(model, selection);
this.result = (0, async_1.createCancelablePromise)(token => this._compute(model, selection, wordSeparators, token));
}
_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, decorationIds) {
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 = decorationIds.length; !requestIsValid && i < len; i++) {
let range = model.getDecorationRange(decorationIds[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 {
_compute(model, selection, wordSeparators, token) {
return getOccurrencesAtPosition(model, selection.getPosition(), token).then(value => value || []);
}
}
class TextualOccurenceAtPositionRequest extends OccurenceAtPositionRequest {
constructor(model, selection, wordSeparators) {
super(model, selection, wordSeparators);
this._selectionIsEmpty = selection.isEmpty();
}
_compute(model, selection, wordSeparators, token) {
return (0, async_1.timeout)(250, token).then(() => {
if (!selection.isEmpty()) {
return [];
}
const word = model.getWordAtPosition(selection.getPosition());
if (!word || word.word.length > 1000) {
return [];
}
const matches = model.findMatches(word.word, true, false, true, wordSeparators, false);
return matches.map(m => {
return {
range: m.range,
kind: modes_1.DocumentHighlightKind.Text
};
});
});
}
isValid(model, selection, decorationIds) {
const currentSelectionIsEmpty = selection.isEmpty();
if (this._selectionIsEmpty !== currentSelectionIsEmpty) {
return false;
}
return super.isValid(model, selection, decorationIds);
}
}
function computeOccurencesAtPosition(model, selection, wordSeparators) {
if (modes_1.DocumentHighlightProviderRegistry.has(model)) {
return new SemanticOccurenceAtPositionRequest(model, selection, wordSeparators);
}
return new TextualOccurenceAtPositionRequest(model, selection, wordSeparators);
}
(0, editorExtensions_1.registerModelAndPositionCommand)('_executeDocumentHighlights', (model, position) => getOccurrencesAtPosition(model, position, cancellation_1.CancellationToken.None));
class WordHighlighter {
constructor(editor, contextKeyService) {
this.toUnhook = new lifecycle_1.DisposableStore();
this.workerRequestTokenId = 0;
this.workerRequestCompleted = false;
this.workerRequestValue = [];
this.lastCursorPositionChangeTime = 0;
this.renderDecorationsTimer = -1;
this.editor = editor;
this._hasWordHighlights = ctxHasWordHighlights.bindTo(contextKeyService);
this._ignorePositionChangeEvent = false;
this.occurrencesHighlight = this.editor.getOption(70 /* 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) {
// 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._onPositionChanged(e);
}));
this.toUnhook.add(editor.onDidChangeModelContent((e) => {
this._stopAll();
}));
this.toUnhook.add(editor.onDidChangeConfiguration((e) => {
let newValue = this.editor.getOption(70 /* occurrencesHighlight */);
if (this.occurrencesHighlight !== newValue) {
this.occurrencesHighlight = newValue;
this._stopAll();
}
}));
this._decorationIds = [];
this.workerRequestTokenId = 0;
this.workerRequest = null;
this.workerRequestCompleted = false;
this.lastCursorPositionChangeTime = 0;
this.renderDecorationsTimer = -1;
}
hasDecorations() {
return (this._decorationIds.length > 0);
}
restore() {
if (!this.occurrencesHighlight) {
return;
}
this._run();
}
_getSortedHighlights() {
return arrays.coalesce(this._decorationIds
.map((id) => this.model.getDecorationRange(id))
.sort(range_1.Range.compareRangesUsingStarts));
}
moveNext() {
let highlights = this._getSortedHighlights();
let index = highlights.findIndex((range) => range.containsPosition(this.editor.getPosition()));
let newIndex = ((index + 1) % highlights.length);
let 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() {
let highlights = this._getSortedHighlights();
let index = highlights.findIndex((range) => range.containsPosition(this.editor.getPosition()));
let newIndex = ((index - 1 + highlights.length) % highlights.length);
let 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;
}
}
_removeDecorations() {
if (this._decorationIds.length > 0) {
// remove decorations
this._decorationIds = this.editor.deltaDecorations(this._decorationIds, []);
this._hasWordHighlights.set(false);
}
}
_stopAll() {
// Remove any existing decorations
this._removeDecorations();
// 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) {
this._stopAll();
return;
}
// ignore typing & other
if (e.reason !== 3 /* Explicit */) {
this._stopAll();
return;
}
this._run();
}
_getWord() {
let editorSelection = this.editor.getSelection();
let lineNumber = editorSelection.startLineNumber;
let startColumn = editorSelection.startColumn;
return this.model.getWordAtPosition({
lineNumber: lineNumber,
column: startColumn
});
}
_run() {
let editorSelection = this.editor.getSelection();
// ignore multiline selection
if (editorSelection.startLineNumber !== editorSelection.endLineNumber) {
this._stopAll();
return;
}
let startColumn = editorSelection.startColumn;
let 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) {
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!
const workerRequestIsValid = (this.workerRequest && this.workerRequest.isValid(this.model, editorSelection, this._decorationIds));
// 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 {
// case d)
// Stop all previous actions and start fresh
this._stopAll();
let myRequestId = ++this.workerRequestTokenId;
this.workerRequestCompleted = false;
this.workerRequest = computeOccurencesAtPosition(this.model, this.editor.getSelection(), this.editor.getOption(115 /* wordSeparators */));
this.workerRequest.result.then(data => {
if (myRequestId === this.workerRequestTokenId) {
this.workerRequestCompleted = true;
this.workerRequestValue = data || [];
this._beginRenderDecorations();
}
}, errors_1.onUnexpectedError);
}
}
_beginRenderDecorations() {
let currentTime = (new Date()).getTime();
let 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;
let decorations = [];
for (const info of this.workerRequestValue) {
if (info.range) {
decorations.push({
range: info.range,
options: WordHighlighter._getDecorationOptions(info.kind)
});
}
}
this._decorationIds = this.editor.deltaDecorations(this._decorationIds, decorations);
this._hasWordHighlights.set(this.hasDecorations());
}
static _getDecorationOptions(kind) {
if (kind === modes_1.DocumentHighlightKind.Write) {
return this._WRITE_OPTIONS;
}
else if (kind === modes_1.DocumentHighlightKind.Text) {
return this._TEXT_OPTIONS;
}
else {
return this._REGULAR_OPTIONS;
}
}
dispose() {
this._stopAll();
this.toUnhook.dispose();
}
}
WordHighlighter._WRITE_OPTIONS = textModel_1.ModelDecorationOptions.register({
description: 'word-highlight-strong',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
className: 'wordHighlightStrong',
overviewRuler: {
color: (0, themeService_1.themeColorFromId)(overviewRulerWordHighlightStrongForeground),
position: model_1.OverviewRulerLane.Center
}
});
WordHighlighter._TEXT_OPTIONS = textModel_1.ModelDecorationOptions.register({
description: 'selection-highlight',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
className: 'selectionHighlight',
overviewRuler: {
color: (0, themeService_1.themeColorFromId)(colorRegistry_1.overviewRulerSelectionHighlightForeground),
position: model_1.OverviewRulerLane.Center
}
});
WordHighlighter._REGULAR_OPTIONS = textModel_1.ModelDecorationOptions.register({
description: 'word-highlight',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
className: 'wordHighlight',
overviewRuler: {
color: (0, themeService_1.themeColorFromId)(overviewRulerWordHighlightForeground),
position: model_1.OverviewRulerLane.Center
}
});
let WordHighlighterContribution = class WordHighlighterContribution extends lifecycle_1.Disposable {
constructor(editor, contextKeyService) {
super();
this.wordHighlighter = null;
const createWordHighlighterIfPossible = () => {
if (editor.hasModel()) {
this.wordHighlighter = new WordHighlighter(editor, contextKeyService);
}
};
this._register(editor.onDidChangeModel((e) => {
if (this.wordHighlighter) {
this.wordHighlighter.dispose();
this.wordHighlighter = null;
}
createWordHighlighterIfPossible();
}));
createWordHighlighterIfPossible();
}
static get(editor) {
return editor.getContribution(WordHighlighterContribution.ID);
}
saveViewState() {
if (this.wordHighlighter && this.wordHighlighter.hasDecorations()) {
return true;
}
return false;
}
moveNext() {
if (this.wordHighlighter) {
this.wordHighlighter.moveNext();
}
}
moveBack() {
if (this.wordHighlighter) {
this.wordHighlighter.moveBack();
}
}
restoreViewState(state) {
if (this.wordHighlighter && state) {
this.wordHighlighter.restore();
}
}
dispose() {
if (this.wordHighlighter) {
this.wordHighlighter.dispose();
this.wordHighlighter = null;
}
super.dispose();
}
};
WordHighlighterContribution.ID = 'editor.contrib.wordHighlighter';
WordHighlighterContribution = __decorate([
__param(1, contextkey_1.IContextKeyService)
], 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(6, null),
alias: 'Go to Next Symbol Highlight',
precondition: ctxHasWordHighlights,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 65 /* F7 */,
weight: 100 /* EditorContrib */
}
});
}
}
class PrevWordHighlightAction extends WordHighlightNavigationAction {
constructor() {
super(false, {
id: 'editor.action.wordHighlight.prev',
label: nls.localize(7, null),
alias: 'Go to Previous Symbol Highlight',
precondition: ctxHasWordHighlights,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 1024 /* Shift */ | 65 /* F7 */,
weight: 100 /* EditorContrib */
}
});
}
}
class TriggerWordHighlightAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.wordHighlight.trigger',
label: nls.localize(8, null),
alias: 'Trigger Symbol Highlight',
precondition: ctxHasWordHighlights.toNegated(),
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 0,
weight: 100 /* EditorContrib */
}
});
}
run(accessor, editor, args) {
const controller = WordHighlighterContribution.get(editor);
if (!controller) {
return;
}
controller.restoreViewState(true);
}
}
(0, editorExtensions_1.registerEditorContribution)(WordHighlighterContribution.ID, WordHighlighterContribution);
(0, editorExtensions_1.registerEditorAction)(NextWordHighlightAction);
(0, editorExtensions_1.registerEditorAction)(PrevWordHighlightAction);
(0, editorExtensions_1.registerEditorAction)(TriggerWordHighlightAction);
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const selectionHighlight = theme.getColor(colorRegistry_1.editorSelectionHighlight);
if (selectionHighlight) {
collector.addRule(`.monaco-editor .focused .selectionHighlight { background-color: ${selectionHighlight}; }`);
collector.addRule(`.monaco-editor .selectionHighlight { background-color: ${selectionHighlight.transparent(0.5)}; }`);
}
const wordHighlight = theme.getColor(editorWordHighlight);
if (wordHighlight) {
collector.addRule(`.monaco-editor .wordHighlight { background-color: ${wordHighlight}; }`);
}
const wordHighlightStrong = theme.getColor(editorWordHighlightStrong);
if (wordHighlightStrong) {
collector.addRule(`.monaco-editor .wordHighlightStrong { background-color: ${wordHighlightStrong}; }`);
}
const selectionHighlightBorder = theme.getColor(colorRegistry_1.editorSelectionHighlightBorder);
if (selectionHighlightBorder) {
collector.addRule(`.monaco-editor .selectionHighlight { border: 1px ${theme.type === 'hc' ? 'dotted' : 'solid'} ${selectionHighlightBorder}; box-sizing: border-box; }`);
}
const wordHighlightBorder = theme.getColor(editorWordHighlightBorder);
if (wordHighlightBorder) {
collector.addRule(`.monaco-editor .wordHighlight { border: 1px ${theme.type === 'hc' ? 'dashed' : 'solid'} ${wordHighlightBorder}; box-sizing: border-box; }`);
}
const wordHighlightStrongBorder = theme.getColor(editorWordHighlightStrongBorder);
if (wordHighlightStrongBorder) {
collector.addRule(`.monaco-editor .wordHighlightStrong { border: 1px ${theme.type === 'hc' ? 'dashed' : 'solid'} ${wordHighlightStrongBorder}; 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[270/*vs/editor/contrib/wordOperations/wordOperations*/], __M([0/*require*/,1/*exports*/,531/*vs/nls!vs/editor/contrib/wordOperations/wordOperations*/,14/*vs/editor/browser/editorExtensions*/,95/*vs/editor/common/commands/replaceCommand*/,40/*vs/editor/common/controller/cursorCommon*/,141/*vs/editor/common/controller/cursorWordOperations*/,109/*vs/editor/common/controller/wordCharacterClassifier*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,25/*vs/editor/common/editorContextKeys*/,64/*vs/platform/accessibility/common/accessibility*/,16/*vs/platform/contextkey/common/contextkey*/,35/*vs/editor/common/config/editorOptions*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/,253/*vs/platform/contextkey/common/contextkeys*/]), function (require, exports, nls, editorExtensions_1, replaceCommand_1, cursorCommon_1, cursorWordOperations_1, wordCharacterClassifier_1, position_1, range_1, selection_1, editorContextKeys_1, accessibility_1, contextkey_1, editorOptions_1, languageConfigurationRegistry_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(115 /* wordSeparators */));
const model = editor.getModel();
const selections = editor.getSelections();
const result = selections.map((sel) => {
const inPosition = new position_1.Position(sel.positionLineNumber, sel.positionColumn);
const outPosition = this._move(wordSeparators, model, inPosition, this._wordNavigationType);
return this._moveTo(sel, outPosition, this._inSelectionMode);
});
model.pushStackElement();
editor._getViewModel().setCursorStates('moveWordCommand', 3 /* 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 /* 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) {
return cursorWordOperations_1.WordOperations.moveWordLeft(wordSeparators, model, position, wordNavigationType);
}
}
exports.WordLeftCommand = WordLeftCommand;
class WordRightCommand extends MoveWordCommand {
_move(wordSeparators, model, position, wordNavigationType) {
return cursorWordOperations_1.WordOperations.moveWordRight(wordSeparators, model, position, wordNavigationType);
}
}
exports.WordRightCommand = WordRightCommand;
class CursorWordStartLeft extends WordLeftCommand {
constructor() {
super({
inSelectionMode: false,
wordNavigationType: 0 /* WordStart */,
id: 'cursorWordStartLeft',
precondition: undefined
});
}
}
exports.CursorWordStartLeft = CursorWordStartLeft;
class CursorWordEndLeft extends WordLeftCommand {
constructor() {
super({
inSelectionMode: false,
wordNavigationType: 2 /* WordEnd */,
id: 'cursorWordEndLeft',
precondition: undefined
});
}
}
exports.CursorWordEndLeft = CursorWordEndLeft;
class CursorWordLeft extends WordLeftCommand {
constructor() {
var _a;
super({
inSelectionMode: false,
wordNavigationType: 1 /* WordStartFast */,
id: 'cursorWordLeft',
precondition: undefined,
kbOpts: {
kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, (_a = contextkey_1.ContextKeyExpr.and(accessibility_1.CONTEXT_ACCESSIBILITY_MODE_ENABLED, contextkeys_1.IsWindowsContext)) === null || _a === void 0 ? void 0 : _a.negate()),
primary: 2048 /* CtrlCmd */ | 15 /* LeftArrow */,
mac: { primary: 512 /* Alt */ | 15 /* LeftArrow */ },
weight: 100 /* EditorContrib */
}
});
}
}
exports.CursorWordLeft = CursorWordLeft;
class CursorWordStartLeftSelect extends WordLeftCommand {
constructor() {
super({
inSelectionMode: true,
wordNavigationType: 0 /* WordStart */,
id: 'cursorWordStartLeftSelect',
precondition: undefined
});
}
}
exports.CursorWordStartLeftSelect = CursorWordStartLeftSelect;
class CursorWordEndLeftSelect extends WordLeftCommand {
constructor() {
super({
inSelectionMode: true,
wordNavigationType: 2 /* WordEnd */,
id: 'cursorWordEndLeftSelect',
precondition: undefined
});
}
}
exports.CursorWordEndLeftSelect = CursorWordEndLeftSelect;
class CursorWordLeftSelect extends WordLeftCommand {
constructor() {
var _a;
super({
inSelectionMode: true,
wordNavigationType: 1 /* WordStartFast */,
id: 'cursorWordLeftSelect',
precondition: undefined,
kbOpts: {
kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, (_a = contextkey_1.ContextKeyExpr.and(accessibility_1.CONTEXT_ACCESSIBILITY_MODE_ENABLED, contextkeys_1.IsWindowsContext)) === null || _a === void 0 ? void 0 : _a.negate()),
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 15 /* LeftArrow */,
mac: { primary: 512 /* Alt */ | 1024 /* Shift */ | 15 /* LeftArrow */ },
weight: 100 /* 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 /* WordAccessibility */,
id: 'cursorWordAccessibilityLeft',
precondition: undefined
});
}
_move(_, model, position, wordNavigationType) {
return super._move((0, wordCharacterClassifier_1.getMapForWordSeparators)(editorOptions_1.EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType);
}
}
exports.CursorWordAccessibilityLeft = CursorWordAccessibilityLeft;
class CursorWordAccessibilityLeftSelect extends WordLeftCommand {
constructor() {
super({
inSelectionMode: true,
wordNavigationType: 3 /* WordAccessibility */,
id: 'cursorWordAccessibilityLeftSelect',
precondition: undefined
});
}
_move(_, model, position, wordNavigationType) {
return super._move((0, wordCharacterClassifier_1.getMapForWordSeparators)(editorOptions_1.EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType);
}
}
exports.CursorWordAccessibilityLeftSelect = CursorWordAccessibilityLeftSelect;
class CursorWordStartRight extends WordRightCommand {
constructor() {
super({
inSelectionMode: false,
wordNavigationType: 0 /* WordStart */,
id: 'cursorWordStartRight',
precondition: undefined
});
}
}
exports.CursorWordStartRight = CursorWordStartRight;
class CursorWordEndRight extends WordRightCommand {
constructor() {
var _a;
super({
inSelectionMode: false,
wordNavigationType: 2 /* WordEnd */,
id: 'cursorWordEndRight',
precondition: undefined,
kbOpts: {
kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, (_a = contextkey_1.ContextKeyExpr.and(accessibility_1.CONTEXT_ACCESSIBILITY_MODE_ENABLED, contextkeys_1.IsWindowsContext)) === null || _a === void 0 ? void 0 : _a.negate()),
primary: 2048 /* CtrlCmd */ | 17 /* RightArrow */,
mac: { primary: 512 /* Alt */ | 17 /* RightArrow */ },
weight: 100 /* EditorContrib */
}
});
}
}
exports.CursorWordEndRight = CursorWordEndRight;
class CursorWordRight extends WordRightCommand {
constructor() {
super({
inSelectionMode: false,
wordNavigationType: 2 /* WordEnd */,
id: 'cursorWordRight',
precondition: undefined
});
}
}
exports.CursorWordRight = CursorWordRight;
class CursorWordStartRightSelect extends WordRightCommand {
constructor() {
super({
inSelectionMode: true,
wordNavigationType: 0 /* WordStart */,
id: 'cursorWordStartRightSelect',
precondition: undefined
});
}
}
exports.CursorWordStartRightSelect = CursorWordStartRightSelect;
class CursorWordEndRightSelect extends WordRightCommand {
constructor() {
var _a;
super({
inSelectionMode: true,
wordNavigationType: 2 /* WordEnd */,
id: 'cursorWordEndRightSelect',
precondition: undefined,
kbOpts: {
kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, (_a = contextkey_1.ContextKeyExpr.and(accessibility_1.CONTEXT_ACCESSIBILITY_MODE_ENABLED, contextkeys_1.IsWindowsContext)) === null || _a === void 0 ? void 0 : _a.negate()),
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 17 /* RightArrow */,
mac: { primary: 512 /* Alt */ | 1024 /* Shift */ | 17 /* RightArrow */ },
weight: 100 /* EditorContrib */
}
});
}
}
exports.CursorWordEndRightSelect = CursorWordEndRightSelect;
class CursorWordRightSelect extends WordRightCommand {
constructor() {
super({
inSelectionMode: true,
wordNavigationType: 2 /* WordEnd */,
id: 'cursorWordRightSelect',
precondition: undefined
});
}
}
exports.CursorWordRightSelect = CursorWordRightSelect;
class CursorWordAccessibilityRight extends WordRightCommand {
constructor() {
super({
inSelectionMode: false,
wordNavigationType: 3 /* WordAccessibility */,
id: 'cursorWordAccessibilityRight',
precondition: undefined
});
}
_move(_, model, position, wordNavigationType) {
return super._move((0, wordCharacterClassifier_1.getMapForWordSeparators)(editorOptions_1.EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType);
}
}
exports.CursorWordAccessibilityRight = CursorWordAccessibilityRight;
class CursorWordAccessibilityRightSelect extends WordRightCommand {
constructor() {
super({
inSelectionMode: true,
wordNavigationType: 3 /* WordAccessibility */,
id: 'cursorWordAccessibilityRightSelect',
precondition: undefined
});
}
_move(_, model, position, wordNavigationType) {
return super._move((0, wordCharacterClassifier_1.getMapForWordSeparators)(editorOptions_1.EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType);
}
}
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) {
if (!editor.hasModel()) {
return;
}
const wordSeparators = (0, wordCharacterClassifier_1.getMapForWordSeparators)(editor.getOption(115 /* wordSeparators */));
const model = editor.getModel();
const selections = editor.getSelections();
const autoClosingBrackets = editor.getOption(5 /* autoClosingBrackets */);
const autoClosingQuotes = editor.getOption(8 /* autoClosingQuotes */);
const autoClosingPairs = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getAutoClosingPairs(model.getLanguageIdentifier().id);
const viewModel = editor._getViewModel();
const commands = selections.map((sel) => {
const deleteRange = this._delete({
wordSeparators,
model,
selection: sel,
whitespaceHeuristics: this._whitespaceHeuristics,
autoClosingDelete: editor.getOption(6 /* 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) {
let 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) {
let 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 /* WordStart */,
id: 'deleteWordStartLeft',
precondition: editorContextKeys_1.EditorContextKeys.writable
});
}
}
exports.DeleteWordStartLeft = DeleteWordStartLeft;
class DeleteWordEndLeft extends DeleteWordLeftCommand {
constructor() {
super({
whitespaceHeuristics: false,
wordNavigationType: 2 /* WordEnd */,
id: 'deleteWordEndLeft',
precondition: editorContextKeys_1.EditorContextKeys.writable
});
}
}
exports.DeleteWordEndLeft = DeleteWordEndLeft;
class DeleteWordLeft extends DeleteWordLeftCommand {
constructor() {
super({
whitespaceHeuristics: true,
wordNavigationType: 0 /* WordStart */,
id: 'deleteWordLeft',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 2048 /* CtrlCmd */ | 1 /* Backspace */,
mac: { primary: 512 /* Alt */ | 1 /* Backspace */ },
weight: 100 /* EditorContrib */
}
});
}
}
exports.DeleteWordLeft = DeleteWordLeft;
class DeleteWordStartRight extends DeleteWordRightCommand {
constructor() {
super({
whitespaceHeuristics: false,
wordNavigationType: 0 /* WordStart */,
id: 'deleteWordStartRight',
precondition: editorContextKeys_1.EditorContextKeys.writable
});
}
}
exports.DeleteWordStartRight = DeleteWordStartRight;
class DeleteWordEndRight extends DeleteWordRightCommand {
constructor() {
super({
whitespaceHeuristics: false,
wordNavigationType: 2 /* WordEnd */,
id: 'deleteWordEndRight',
precondition: editorContextKeys_1.EditorContextKeys.writable
});
}
}
exports.DeleteWordEndRight = DeleteWordEndRight;
class DeleteWordRight extends DeleteWordRightCommand {
constructor() {
super({
whitespaceHeuristics: true,
wordNavigationType: 2 /* WordEnd */,
id: 'deleteWordRight',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 2048 /* CtrlCmd */ | 20 /* Delete */,
mac: { primary: 512 /* Alt */ | 20 /* Delete */ },
weight: 100 /* EditorContrib */
}
});
}
}
exports.DeleteWordRight = DeleteWordRight;
class DeleteInsideWord extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'deleteInsideWord',
precondition: editorContextKeys_1.EditorContextKeys.writable,
label: nls.localize(0, null),
alias: 'Delete Word'
});
}
run(accessor, editor, args) {
if (!editor.hasModel()) {
return;
}
const wordSeparators = (0, wordCharacterClassifier_1.getMapForWordSeparators)(editor.getOption(115 /* wordSeparators */));
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[656/*vs/editor/contrib/wordPartOperations/wordPartOperations*/], __M([0/*require*/,1/*exports*/,14/*vs/editor/browser/editorExtensions*/,141/*vs/editor/common/controller/cursorWordOperations*/,3/*vs/editor/common/core/range*/,25/*vs/editor/common/editorContextKeys*/,270/*vs/editor/contrib/wordOperations/wordOperations*/,26/*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 /* WordStart */,
id: 'deleteWordPartLeft',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 0,
mac: { primary: 256 /* WinCtrl */ | 512 /* Alt */ | 1 /* Backspace */ },
weight: 100 /* EditorContrib */
}
});
}
_delete(ctx, wordNavigationType) {
let 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 /* WordEnd */,
id: 'deleteWordPartRight',
precondition: editorContextKeys_1.EditorContextKeys.writable,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 0,
mac: { primary: 256 /* WinCtrl */ | 512 /* Alt */ | 20 /* Delete */ },
weight: 100 /* EditorContrib */
}
});
}
_delete(ctx, wordNavigationType) {
let 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) {
return cursorWordOperations_1.WordPartOperations.moveWordPartLeft(wordSeparators, model, position);
}
}
exports.WordPartLeftCommand = WordPartLeftCommand;
class CursorWordPartLeft extends WordPartLeftCommand {
constructor() {
super({
inSelectionMode: false,
wordNavigationType: 0 /* WordStart */,
id: 'cursorWordPartLeft',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 0,
mac: { primary: 256 /* WinCtrl */ | 512 /* Alt */ | 15 /* LeftArrow */ },
weight: 100 /* 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 /* WordStart */,
id: 'cursorWordPartLeftSelect',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 0,
mac: { primary: 256 /* WinCtrl */ | 512 /* Alt */ | 1024 /* Shift */ | 15 /* LeftArrow */ },
weight: 100 /* 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) {
return cursorWordOperations_1.WordPartOperations.moveWordPartRight(wordSeparators, model, position);
}
}
exports.WordPartRightCommand = WordPartRightCommand;
class CursorWordPartRight extends WordPartRightCommand {
constructor() {
super({
inSelectionMode: false,
wordNavigationType: 2 /* WordEnd */,
id: 'cursorWordPartRight',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 0,
mac: { primary: 256 /* WinCtrl */ | 512 /* Alt */ | 17 /* RightArrow */ },
weight: 100 /* EditorContrib */
}
});
}
}
exports.CursorWordPartRight = CursorWordPartRight;
class CursorWordPartRightSelect extends WordPartRightCommand {
constructor() {
super({
inSelectionMode: true,
wordNavigationType: 2 /* WordEnd */,
id: 'cursorWordPartRightSelect',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 0,
mac: { primary: 256 /* WinCtrl */ | 512 /* Alt */ | 1024 /* Shift */ | 17 /* RightArrow */ },
weight: 100 /* 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[657/*vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,160/*vs/base/browser/formattedTextRenderer*/,44/*vs/base/browser/ui/aria/aria*/,52/*vs/base/browser/ui/widget*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,8/*vs/base/common/strings*/,24/*vs/base/common/uri*/,14/*vs/editor/browser/editorExtensions*/,25/*vs/editor/common/editorContextKeys*/,269/*vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/,37/*vs/platform/keybinding/common/keybinding*/,58/*vs/platform/opener/common/opener*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,63/*vs/editor/common/standaloneStrings*/,363/*vs/css!vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/]), function (require, exports, dom, fastDomNode_1, formattedTextRenderer_1, aria_1, widget_1, lifecycle_1, platform, strings, uri_1, editorExtensions_1, editorContextKeys_1, toggleTabFocusMode_1, contextkey_1, instantiation_1, keybinding_1, opener_1, colorRegistry_1, themeService_1, standaloneStrings_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE = new contextkey_1.RawContextKey('accessibilityHelpWidgetVisible', false);
let AccessibilityHelpController = class AccessibilityHelpController extends lifecycle_1.Disposable {
constructor(editor, instantiationService) {
super();
this._editor = editor;
this._widget = this._register(instantiationService.createInstance(AccessibilityHelpWidget, this._editor));
}
static get(editor) {
return editor.getContribution(AccessibilityHelpController.ID);
}
show() {
this._widget.show();
}
hide() {
this._widget.hide();
}
};
AccessibilityHelpController.ID = 'editor.contrib.accessibilityHelpController';
AccessibilityHelpController = __decorate([
__param(1, instantiation_1.IInstantiationService)
], AccessibilityHelpController);
function getSelectionLabel(selections, charactersSelected) {
if (!selections || selections.length === 0) {
return standaloneStrings_1.AccessibilityHelpNLS.noSelection;
}
if (selections.length === 1) {
if (charactersSelected) {
return strings.format(standaloneStrings_1.AccessibilityHelpNLS.singleSelectionRange, selections[0].positionLineNumber, selections[0].positionColumn, charactersSelected);
}
return strings.format(standaloneStrings_1.AccessibilityHelpNLS.singleSelection, selections[0].positionLineNumber, selections[0].positionColumn);
}
if (charactersSelected) {
return strings.format(standaloneStrings_1.AccessibilityHelpNLS.multiSelectionRange, selections.length, charactersSelected);
}
if (selections.length > 0) {
return strings.format(standaloneStrings_1.AccessibilityHelpNLS.multiSelection, selections.length);
}
return '';
}
let AccessibilityHelpWidget = class AccessibilityHelpWidget extends widget_1.Widget {
constructor(editor, _contextKeyService, _keybindingService, _openerService) {
super();
this._contextKeyService = _contextKeyService;
this._keybindingService = _keybindingService;
this._openerService = _openerService;
this._editor = editor;
this._isVisibleKey = CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE.bindTo(this._contextKeyService);
this._domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
this._domNode.setClassName('accessibilityHelpWidget');
this._domNode.setDisplay('none');
this._domNode.setAttribute('role', 'dialog');
this._domNode.setAttribute('aria-hidden', 'true');
this._contentDomNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
this._contentDomNode.setAttribute('role', 'document');
this._domNode.appendChild(this._contentDomNode);
this._isVisible = false;
this._register(this._editor.onDidLayoutChange(() => {
if (this._isVisible) {
this._layout();
}
}));
// Intentionally not configurable!
this._register(dom.addStandardDisposableListener(this._contentDomNode.domNode, 'keydown', (e) => {
if (!this._isVisible) {
return;
}
if (e.equals(2048 /* CtrlCmd */ | 35 /* KEY_E */)) {
(0, aria_1.alert)(standaloneStrings_1.AccessibilityHelpNLS.emergencyConfOn);
this._editor.updateOptions({
accessibilitySupport: 'on'
});
dom.clearNode(this._contentDomNode.domNode);
this._buildContent();
this._contentDomNode.domNode.focus();
e.preventDefault();
e.stopPropagation();
}
if (e.equals(2048 /* CtrlCmd */ | 38 /* KEY_H */)) {
(0, aria_1.alert)(standaloneStrings_1.AccessibilityHelpNLS.openingDocs);
let url = this._editor.getRawOptions().accessibilityHelpUrl;
if (typeof url === 'undefined') {
url = 'https://go.microsoft.com/fwlink/?linkid=852450';
}
this._openerService.open(uri_1.URI.parse(url));
e.preventDefault();
e.stopPropagation();
}
}));
this.onblur(this._contentDomNode.domNode, () => {
this.hide();
});
this._editor.addOverlayWidget(this);
}
dispose() {
this._editor.removeOverlayWidget(this);
super.dispose();
}
getId() {
return AccessibilityHelpWidget.ID;
}
getDomNode() {
return this._domNode.domNode;
}
getPosition() {
return {
preference: null
};
}
show() {
if (this._isVisible) {
return;
}
this._isVisible = true;
this._isVisibleKey.set(true);
this._layout();
this._domNode.setDisplay('block');
this._domNode.setAttribute('aria-hidden', 'false');
this._contentDomNode.domNode.tabIndex = 0;
this._buildContent();
this._contentDomNode.domNode.focus();
}
_descriptionForCommand(commandId, msg, noKbMsg) {
let kb = this._keybindingService.lookupKeybinding(commandId);
if (kb) {
return strings.format(msg, kb.getAriaLabel());
}
return strings.format(noKbMsg, commandId);
}
_buildContent() {
const options = this._editor.getOptions();
const selections = this._editor.getSelections();
let charactersSelected = 0;
if (selections) {
const model = this._editor.getModel();
if (model) {
selections.forEach((selection) => {
charactersSelected += model.getValueLengthInRange(selection);
});
}
}
let text = getSelectionLabel(selections, charactersSelected);
if (options.get(52 /* inDiffEditor */)) {
if (options.get(79 /* readOnly */)) {
text += standaloneStrings_1.AccessibilityHelpNLS.readonlyDiffEditor;
}
else {
text += standaloneStrings_1.AccessibilityHelpNLS.editableDiffEditor;
}
}
else {
if (options.get(79 /* readOnly */)) {
text += standaloneStrings_1.AccessibilityHelpNLS.readonlyEditor;
}
else {
text += standaloneStrings_1.AccessibilityHelpNLS.editableEditor;
}
}
const turnOnMessage = (platform.isMacintosh
? standaloneStrings_1.AccessibilityHelpNLS.changeConfigToOnMac
: standaloneStrings_1.AccessibilityHelpNLS.changeConfigToOnWinLinux);
switch (options.get(2 /* accessibilitySupport */)) {
case 0 /* Unknown */:
text += '\n\n - ' + turnOnMessage;
break;
case 2 /* Enabled */:
text += '\n\n - ' + standaloneStrings_1.AccessibilityHelpNLS.auto_on;
break;
case 1 /* Disabled */:
text += '\n\n - ' + standaloneStrings_1.AccessibilityHelpNLS.auto_off;
text += ' ' + turnOnMessage;
break;
}
if (options.get(128 /* tabFocusMode */)) {
text += '\n\n - ' + this._descriptionForCommand(toggleTabFocusMode_1.ToggleTabFocusModeAction.ID, standaloneStrings_1.AccessibilityHelpNLS.tabFocusModeOnMsg, standaloneStrings_1.AccessibilityHelpNLS.tabFocusModeOnMsgNoKb);
}
else {
text += '\n\n - ' + this._descriptionForCommand(toggleTabFocusMode_1.ToggleTabFocusModeAction.ID, standaloneStrings_1.AccessibilityHelpNLS.tabFocusModeOffMsg, standaloneStrings_1.AccessibilityHelpNLS.tabFocusModeOffMsgNoKb);
}
const openDocMessage = (platform.isMacintosh
? standaloneStrings_1.AccessibilityHelpNLS.openDocMac
: standaloneStrings_1.AccessibilityHelpNLS.openDocWinLinux);
text += '\n\n - ' + openDocMessage;
text += '\n\n' + standaloneStrings_1.AccessibilityHelpNLS.outroMsg;
this._contentDomNode.domNode.appendChild((0, formattedTextRenderer_1.renderFormattedText)(text));
// Per https://www.w3.org/TR/wai-aria/roles#document, Authors SHOULD provide a title or label for documents
this._contentDomNode.domNode.setAttribute('aria-label', text);
}
hide() {
if (!this._isVisible) {
return;
}
this._isVisible = false;
this._isVisibleKey.reset();
this._domNode.setDisplay('none');
this._domNode.setAttribute('aria-hidden', 'true');
this._contentDomNode.domNode.tabIndex = -1;
dom.clearNode(this._contentDomNode.domNode);
this._editor.focus();
}
_layout() {
let editorLayout = this._editor.getLayoutInfo();
let w = Math.max(5, Math.min(AccessibilityHelpWidget.WIDTH, editorLayout.width - 40));
let h = Math.max(5, Math.min(AccessibilityHelpWidget.HEIGHT, editorLayout.height - 40));
this._domNode.setWidth(w);
this._domNode.setHeight(h);
let top = Math.round((editorLayout.height - h) / 2);
this._domNode.setTop(top);
let left = Math.round((editorLayout.width - w) / 2);
this._domNode.setLeft(left);
}
};
AccessibilityHelpWidget.ID = 'editor.contrib.accessibilityHelpWidget';
AccessibilityHelpWidget.WIDTH = 500;
AccessibilityHelpWidget.HEIGHT = 300;
AccessibilityHelpWidget = __decorate([
__param(1, contextkey_1.IContextKeyService),
__param(2, keybinding_1.IKeybindingService),
__param(3, opener_1.IOpenerService)
], AccessibilityHelpWidget);
class ShowAccessibilityHelpAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.showAccessibilityHelp',
label: standaloneStrings_1.AccessibilityHelpNLS.showAccessibilityHelpAction,
alias: 'Show Accessibility Help',
precondition: undefined,
kbOpts: {
primary: 512 /* Alt */ | 59 /* F1 */,
weight: 100 /* EditorContrib */,
linux: {
primary: 512 /* Alt */ | 1024 /* Shift */ | 59 /* F1 */,
secondary: [512 /* Alt */ | 59 /* F1 */]
}
}
});
}
run(accessor, editor) {
let controller = AccessibilityHelpController.get(editor);
if (controller) {
controller.show();
}
}
}
(0, editorExtensions_1.registerEditorContribution)(AccessibilityHelpController.ID, AccessibilityHelpController);
(0, editorExtensions_1.registerEditorAction)(ShowAccessibilityHelpAction);
const AccessibilityHelpCommand = editorExtensions_1.EditorCommand.bindToContribution(AccessibilityHelpController.get);
(0, editorExtensions_1.registerEditorCommand)(new AccessibilityHelpCommand({
id: 'closeAccessibilityHelp',
precondition: CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE,
handler: x => x.hide(),
kbOpts: {
weight: 100 /* EditorContrib */ + 100,
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 9 /* Escape */,
secondary: [1024 /* Shift */ | 9 /* Escape */]
}
}));
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const widgetBackground = theme.getColor(colorRegistry_1.editorWidgetBackground);
if (widgetBackground) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { background-color: ${widgetBackground}; }`);
}
const widgetForeground = theme.getColor(colorRegistry_1.editorWidgetForeground);
if (widgetForeground) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { color: ${widgetForeground}; }`);
}
const widgetShadowColor = theme.getColor(colorRegistry_1.widgetShadow);
if (widgetShadowColor) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { box-shadow: 0 2px 8px ${widgetShadowColor}; }`);
}
const hcBorder = theme.getColor(colorRegistry_1.contrastBorder);
if (hcBorder) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { border: 2px solid ${hcBorder}; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,17/*vs/base/common/platform*/,364/*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 {
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(79 /* 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;
IPadShowKeyboard.ID = 'editor.contrib.iPadShowKeyboard';
class ShowKeyboardWidget extends lifecycle_1.Disposable {
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 /* BOTTOM_RIGHT_CORNER */
};
}
}
ShowKeyboardWidget.ID = 'editor.contrib.ShowKeyboardWidget';
(0, editorExtensions_1.registerEditorContribution)(IPadShowKeyboard.ID, IPadShowKeyboard);
});
/*---------------------------------------------------------------------------------------------
* 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/standalone/browser/inspectTokens/inspectTokens*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,29/*vs/base/common/color*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,18/*vs/editor/common/modes*/,77/*vs/editor/common/modes/nullMode*/,57/*vs/editor/common/services/modeService*/,119/*vs/editor/standalone/common/standaloneThemeService*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,63/*vs/editor/common/standaloneStrings*/,100/*vs/platform/theme/common/theme*/,365/*vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens*/]), function (require, exports, dom_1, color_1, lifecycle_1, editorExtensions_1, modes_1, nullMode_1, modeService_1, standaloneThemeService_1, colorRegistry_1, themeService_1, standaloneStrings_1, theme_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let InspectTokensController = class InspectTokensController extends lifecycle_1.Disposable {
constructor(editor, standaloneColorService, modeService) {
super();
this._editor = editor;
this._modeService = modeService;
this._widget = null;
this._register(this._editor.onDidChangeModel((e) => this.stop()));
this._register(this._editor.onDidChangeModelLanguage((e) => this.stop()));
this._register(modes_1.TokenizationRegistry.onDidChange((e) => this.stop()));
this._register(this._editor.onKeyUp((e) => e.keyCode === 9 /* Escape */ && this.stop()));
}
static get(editor) {
return editor.getContribution(InspectTokensController.ID);
}
dispose() {
this.stop();
super.dispose();
}
launch() {
if (this._widget) {
return;
}
if (!this._editor.hasModel()) {
return;
}
this._widget = new InspectTokensWidget(this._editor, this._modeService);
}
stop() {
if (this._widget) {
this._widget.dispose();
this._widget = null;
}
}
};
InspectTokensController.ID = 'editor.contrib.inspectTokens';
InspectTokensController = __decorate([
__param(1, standaloneThemeService_1.IStandaloneThemeService),
__param(2, modeService_1.IModeService)
], 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) {
let controller = InspectTokensController.get(editor);
if (controller) {
controller.launch();
}
}
}
function renderTokenText(tokenText) {
let result = '';
for (let charIndex = 0, len = tokenText.length; charIndex < len; charIndex++) {
let charCode = tokenText.charCodeAt(charIndex);
switch (charCode) {
case 9 /* Tab */:
result += '\u2192'; // &rarr;
break;
case 32 /* Space */:
result += '\u00B7'; // &middot;
break;
default:
result += String.fromCharCode(charCode);
}
}
return result;
}
function getSafeTokenizationSupport(languageIdentifier) {
let tokenizationSupport = modes_1.TokenizationRegistry.get(languageIdentifier.language);
if (tokenizationSupport) {
return tokenizationSupport;
}
return {
getInitialState: () => nullMode_1.NULL_STATE,
tokenize: (line, hasEOL, state, deltaOffset) => (0, nullMode_1.nullTokenize)(languageIdentifier.language, line, state, deltaOffset),
tokenize2: (line, hasEOL, state, deltaOffset) => (0, nullMode_1.nullTokenize2)(languageIdentifier.id, line, state, deltaOffset)
};
}
class InspectTokensWidget extends lifecycle_1.Disposable {
constructor(editor, modeService) {
super();
// Editor.IContentWidget.allowEditorOverflow
this.allowEditorOverflow = true;
this._editor = editor;
this._modeService = modeService;
this._model = this._editor.getModel();
this._domNode = document.createElement('div');
this._domNode.className = 'tokens-inspect-widget';
this._tokenizationSupport = getSafeTokenizationSupport(this._model.getLanguageIdentifier());
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) {
let data = this._getTokensAtLine(position.lineNumber);
let token1Index = 0;
for (let i = data.tokens1.length - 1; i >= 0; i--) {
let 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;
}
}
let lineContent = this._model.getLineContent(position.lineNumber);
let tokenText = '';
if (token1Index < data.tokens1.length) {
let tokenStartIndex = data.tokens1[token1Index].offset;
let 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.languageIdentifier.language : '-?-'}`)), (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) {
let colorMap = modes_1.TokenizationRegistry.getColorMap();
let languageId = modes_1.TokenMetadata.getLanguageId(metadata);
let tokenType = modes_1.TokenMetadata.getTokenType(metadata);
let fontStyle = modes_1.TokenMetadata.getFontStyle(metadata);
let foreground = modes_1.TokenMetadata.getForeground(metadata);
let background = modes_1.TokenMetadata.getBackground(metadata);
return {
languageIdentifier: this._modeService.getLanguageIdentifier(languageId),
tokenType: tokenType,
fontStyle: fontStyle,
foreground: colorMap[foreground],
background: colorMap[background]
};
}
_tokenTypeToString(tokenType) {
switch (tokenType) {
case 0 /* Other */: return 'Other';
case 1 /* Comment */: return 'Comment';
case 2 /* String */: return 'String';
case 4 /* RegEx */: return 'RegEx';
default: return '??';
}
}
_fontStyleToString(fontStyle) {
let r = '';
if (fontStyle & 1 /* Italic */) {
r += 'italic ';
}
if (fontStyle & 2 /* Bold */) {
r += 'bold ';
}
if (fontStyle & 4 /* Underline */) {
r += 'underline ';
}
if (r.length === 0) {
r = '---';
}
return r;
}
_getTokensAtLine(lineNumber) {
let stateBeforeLine = this._getStateBeforeLine(lineNumber);
let tokenizationResult1 = this._tokenizationSupport.tokenize(this._model.getLineContent(lineNumber), true, stateBeforeLine, 0);
let tokenizationResult2 = this._tokenizationSupport.tokenize2(this._model.getLineContent(lineNumber), true, stateBeforeLine, 0);
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++) {
let tokenizationResult = this._tokenizationSupport.tokenize(this._model.getLineContent(i), true, state, 0);
state = tokenizationResult.endState;
}
return state;
}
getDomNode() {
return this._domNode;
}
getPosition() {
return {
position: this._editor.getPosition(),
preference: [2 /* BELOW */, 1 /* ABOVE */]
};
}
}
InspectTokensWidget._ID = 'editor.contrib.inspectTokensWidget';
(0, editorExtensions_1.registerEditorContribution)(InspectTokensController.ID, InspectTokensController);
(0, editorExtensions_1.registerEditorAction)(InspectTokens);
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const border = theme.getColor(colorRegistry_1.editorHoverBorder);
if (border) {
let borderWidth = theme.type === theme_1.ColorScheme.HIGH_CONTRAST ? 2 : 1;
collector.addRule(`.monaco-editor .tokens-inspect-widget { border: ${borderWidth}px solid ${border}; }`);
collector.addRule(`.monaco-editor .tokens-inspect-widget .tokens-inspect-separator { background-color: ${border}; }`);
}
const background = theme.getColor(colorRegistry_1.editorHoverBackground);
if (background) {
collector.addRule(`.monaco-editor .tokens-inspect-widget { background-color: ${background}; }`);
}
const foreground = theme.getColor(colorRegistry_1.editorHoverForeground);
if (foreground) {
collector.addRule(`.monaco-editor .tokens-inspect-widget { color: ${foreground}; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/standalone/browser/quickAccess/standaloneCommandsQuickAccess*/], __M([0/*require*/,1/*exports*/,32/*vs/platform/registry/common/platform*/,99/*vs/platform/quickinput/common/quickAccess*/,63/*vs/editor/common/standaloneStrings*/,28/*vs/editor/browser/services/codeEditorService*/,592/*vs/editor/contrib/quickAccess/commandsQuickAccess*/,20/*vs/base/common/types*/,9/*vs/platform/instantiation/common/instantiation*/,37/*vs/platform/keybinding/common/keybinding*/,26/*vs/platform/commands/common/commands*/,89/*vs/platform/telemetry/common/telemetry*/,120/*vs/platform/dialogs/common/dialogs*/,14/*vs/editor/browser/editorExtensions*/,25/*vs/editor/common/editorContextKeys*/,78/*vs/platform/quickinput/common/quickInput*/]), function (require, exports, platform_1, quickAccess_1, standaloneStrings_1, codeEditorService_1, commandsQuickAccess_1, types_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 {
constructor(instantiationService, codeEditorService, keybindingService, commandService, telemetryService, dialogService) {
super({ showAlias: false }, instantiationService, keybindingService, commandService, telemetryService, dialogService);
this.codeEditorService = codeEditorService;
}
get activeTextEditorControl() { return (0, types_1.withNullAsUndefined)(this.codeEditorService.getFocusedCodeEditor()); }
getCommandPicks() {
return __awaiter(this, void 0, void 0, function* () {
return this.getCodeEditorCommandPicks();
});
}
};
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);
exports.StandaloneCommandsQuickAccessProvider = StandaloneCommandsQuickAccessProvider;
platform_1.Registry.as(quickAccess_1.Extensions.Quickaccess).registerQuickAccessProvider({
ctor: StandaloneCommandsQuickAccessProvider,
prefix: StandaloneCommandsQuickAccessProvider.PREFIX,
helpEntries: [{ description: standaloneStrings_1.QuickCommandNLS.quickCommandHelp, needsEditor: true }]
});
class GotoLineAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.quickCommand',
label: standaloneStrings_1.QuickCommandNLS.quickCommandActionLabel,
alias: 'Command Palette',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 59 /* F1 */,
weight: 100 /* 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);
});
/*---------------------------------------------------------------------------------------------
* 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/standalone/browser/quickAccess/standaloneGotoLineQuickAccess*/], __M([0/*require*/,1/*exports*/,617/*vs/editor/contrib/quickAccess/gotoLineQuickAccess*/,32/*vs/platform/registry/common/platform*/,99/*vs/platform/quickinput/common/quickAccess*/,28/*vs/editor/browser/services/codeEditorService*/,20/*vs/base/common/types*/,63/*vs/editor/common/standaloneStrings*/,6/*vs/base/common/event*/,14/*vs/editor/browser/editorExtensions*/,25/*vs/editor/common/editorContextKeys*/,78/*vs/platform/quickinput/common/quickInput*/]), function (require, exports, gotoLineQuickAccess_1, platform_1, quickAccess_1, codeEditorService_1, types_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 (0, types_1.withNullAsUndefined)(this.editorService.getFocusedCodeEditor());
}
};
StandaloneGotoLineQuickAccessProvider = __decorate([
__param(0, codeEditorService_1.ICodeEditorService)
], StandaloneGotoLineQuickAccessProvider);
exports.StandaloneGotoLineQuickAccessProvider = StandaloneGotoLineQuickAccessProvider;
platform_1.Registry.as(quickAccess_1.Extensions.Quickaccess).registerQuickAccessProvider({
ctor: StandaloneGotoLineQuickAccessProvider,
prefix: StandaloneGotoLineQuickAccessProvider.PREFIX,
helpEntries: [{ description: standaloneStrings_1.GoToLineNLS.gotoLineActionLabel, needsEditor: true }]
});
class GotoLineAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.gotoLine',
label: standaloneStrings_1.GoToLineNLS.gotoLineActionLabel,
alias: 'Go to Line/Column...',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 2048 /* CtrlCmd */ | 37 /* KEY_G */,
mac: { primary: 256 /* WinCtrl */ | 37 /* KEY_G */ },
weight: 100 /* EditorContrib */
}
});
}
run(accessor) {
accessor.get(quickInput_1.IQuickInputService).quickAccess.show(StandaloneGotoLineQuickAccessProvider.PREFIX);
}
}
exports.GotoLineAction = GotoLineAction;
(0, editorExtensions_1.registerEditorAction)(GotoLineAction);
});
/*---------------------------------------------------------------------------------------------
* 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/standalone/browser/quickAccess/standaloneGotoSymbolQuickAccess*/], __M([0/*require*/,1/*exports*/,618/*vs/editor/contrib/quickAccess/gotoSymbolQuickAccess*/,32/*vs/platform/registry/common/platform*/,99/*vs/platform/quickinput/common/quickAccess*/,28/*vs/editor/browser/services/codeEditorService*/,20/*vs/base/common/types*/,63/*vs/editor/common/standaloneStrings*/,6/*vs/base/common/event*/,14/*vs/editor/browser/editorExtensions*/,25/*vs/editor/common/editorContextKeys*/,78/*vs/platform/quickinput/common/quickInput*/,130/*vs/base/browser/ui/codicons/codiconStyles*/,262/*vs/editor/contrib/symbolIcons/symbolIcons*/]), function (require, exports, gotoSymbolQuickAccess_1, platform_1, quickAccess_1, codeEditorService_1, types_1, standaloneStrings_1, event_1, editorExtensions_1, editorContextKeys_1, quickInput_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GotoLineAction = exports.StandaloneGotoSymbolQuickAccessProvider = void 0;
let StandaloneGotoSymbolQuickAccessProvider = class StandaloneGotoSymbolQuickAccessProvider extends gotoSymbolQuickAccess_1.AbstractGotoSymbolQuickAccessProvider {
constructor(editorService) {
super();
this.editorService = editorService;
this.onDidActiveTextEditorControlChange = event_1.Event.None;
}
get activeTextEditorControl() {
return (0, types_1.withNullAsUndefined)(this.editorService.getFocusedCodeEditor());
}
};
StandaloneGotoSymbolQuickAccessProvider = __decorate([
__param(0, codeEditorService_1.ICodeEditorService)
], StandaloneGotoSymbolQuickAccessProvider);
exports.StandaloneGotoSymbolQuickAccessProvider = StandaloneGotoSymbolQuickAccessProvider;
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, needsEditor: true },
{ description: standaloneStrings_1.QuickOutlineNLS.quickOutlineByCategoryActionLabel, prefix: gotoSymbolQuickAccess_1.AbstractGotoSymbolQuickAccessProvider.PREFIX_BY_CATEGORY, needsEditor: true }
]
});
class GotoLineAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.quickOutline',
label: standaloneStrings_1.QuickOutlineNLS.quickOutlineActionLabel,
alias: 'Go to Symbol...',
precondition: editorContextKeys_1.EditorContextKeys.hasDocumentSymbolProvider,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 45 /* KEY_O */,
weight: 100 /* EditorContrib */
},
contextMenuOpts: {
group: 'navigation',
order: 3
}
});
}
run(accessor) {
accessor.get(quickInput_1.IQuickInputService).quickAccess.show(gotoSymbolQuickAccess_1.AbstractGotoSymbolQuickAccessProvider.PREFIX);
}
}
exports.GotoLineAction = GotoLineAction;
(0, editorExtensions_1.registerEditorAction)(GotoLineAction);
});
/*---------------------------------------------------------------------------------------------
* 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/standalone/browser/toggleHighContrast/toggleHighContrast*/], __M([0/*require*/,1/*exports*/,14/*vs/editor/browser/editorExtensions*/,119/*vs/editor/standalone/common/standaloneThemeService*/,63/*vs/editor/common/standaloneStrings*/]), function (require, exports, editorExtensions_1, standaloneThemeService_1, standaloneStrings_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(standaloneThemeService_1.IStandaloneThemeService);
if (this._originalThemeName) {
// We must toggle back to the integrator's theme
standaloneThemeService.setTheme(this._originalThemeName);
this._originalThemeName = null;
}
else {
this._originalThemeName = standaloneThemeService.getColorTheme().themeName;
standaloneThemeService.setTheme('hc-black');
}
}
}
(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[192/*vs/platform/actions/browser/menuEntryActionViewItem*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,50/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,532/*vs/nls!vs/platform/actions/browser/menuEntryActionViewItem*/,33/*vs/platform/actions/common/actions*/,69/*vs/platform/contextview/browser/contextView*/,37/*vs/platform/keybinding/common/keybinding*/,182/*vs/base/common/keybindingLabels*/,34/*vs/platform/notification/common/notification*/,11/*vs/platform/theme/common/themeService*/,117/*vs/base/browser/ui/actionbar/actionViewItems*/,441/*vs/base/browser/ui/dropdown/dropdownActionViewItem*/,17/*vs/base/common/platform*/,9/*vs/platform/instantiation/common/instantiation*/,16/*vs/platform/contextkey/common/contextkey*/,51/*vs/base/browser/keyboardEvent*/,71/*vs/platform/storage/common/storage*/,368/*vs/css!vs/platform/actions/browser/menuEntryActionViewItem*/]), function (require, exports, dom_1, actions_1, lifecycle_1, nls_1, actions_2, contextView_1, keybinding_1, keybindingLabels_1, notification_1, themeService_1, actionViewItems_1, dropdownActionViewItem_1, platform_1, instantiation_1, contextkey_1, keyboardEvent_1, storage_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createActionViewItem = exports.SubmenuEntryActionViewItem = exports.MenuEntryActionViewItem = exports.createAndFillInActionBarActions = void 0;
function createAndFillInActionBarActions(menu, options, target, primaryGroup, primaryMaxCount, shouldInlineSubmenu, useSeparatorsInPrimaryActions) {
const groups = menu.getActions(options);
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, primaryMaxCount, shouldInlineSubmenu, useSeparatorsInPrimaryActions);
return asDisposable(groups);
}
exports.createAndFillInActionBarActions = createAndFillInActionBarActions;
function asDisposable(groups) {
const disposables = new lifecycle_1.DisposableStore();
for (const [, actions] of groups) {
for (const action of actions) {
disposables.add(action);
}
}
return disposables;
}
function fillInActions(groups, target, useAlternativeActions, isPrimaryAction = actionGroup => actionGroup === 'navigation', primaryMaxCount = Number.MAX_SAFE_INTEGER, 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 ((submenuActions.length <= 1 || target.length + submenuActions.length - 2 <= primaryMaxCount) && shouldInlineSubmenu(action, group, target.length)) {
target.splice(index, 1, ...submenuActions);
}
}
// overflow items from the primary group into the secondary bucket
if (primaryBucket !== secondaryBucket && primaryBucket.length > primaryMaxCount) {
const overflow = primaryBucket.splice(primaryMaxCount, primaryBucket.length - primaryMaxCount);
secondaryBucket.unshift(...overflow, new actions_1.Separator());
}
}
let MenuEntryActionViewItem = class MenuEntryActionViewItem extends actionViewItems_1.ActionViewItem {
constructor(_action, options, _keybindingService, _notificationService, _contextKeyService) {
super(undefined, _action, { icon: !!(_action.class || _action.item.icon), label: !_action.class && !_action.item.icon, draggable: options === null || options === void 0 ? void 0 : options.draggable });
this._keybindingService = _keybindingService;
this._notificationService = _notificationService;
this._contextKeyService = _contextKeyService;
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;
}
onClick(event) {
return __awaiter(this, void 0, void 0, function* () {
event.preventDefault();
event.stopPropagation();
try {
yield this.actionRunner.run(this._commandAction, this._context);
}
catch (err) {
this._notificationService.error(err);
}
});
}
render(container) {
super.render(container);
container.classList.add('menu-entry');
this._updateItemClass(this._menuItemAction.item);
let mouseOver = false;
let alternativeKeyDown = this._altKey.keyStatus.altKey || ((platform_1.isWindows || platform_1.isLinux) && this._altKey.keyStatus.shiftKey);
const updateAltState = () => {
const wantsAltCommand = mouseOver && alternativeKeyDown;
if (wantsAltCommand !== this._wantsAltCommand) {
this._wantsAltCommand = wantsAltCommand;
this.updateLabel();
this.updateTooltip();
this.updateClass();
}
};
if (this._menuItemAction.alt) {
this._register(this._altKey.event(value => {
alternativeKeyDown = value.altKey || ((platform_1.isWindows || platform_1.isLinux) && value.shiftKey);
updateAltState();
}));
}
this._register((0, dom_1.addDisposableListener)(container, 'mouseleave', _ => {
mouseOver = false;
updateAltState();
}));
this._register((0, dom_1.addDisposableListener)(container, 'mouseenter', _ => {
mouseOver = true;
updateAltState();
}));
}
updateLabel() {
if (this.options.label && this.label) {
this.label.textContent = this._commandAction.label;
}
}
updateTooltip() {
if (this.label) {
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)(0, null, tooltip, keybindingLabel)
: tooltip;
if (!this._wantsAltCommand && this._menuItemAction.alt) {
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)(1, null, altTooltip, altKeybindingLabel)
: altTooltip;
title += `\n[${keybindingLabels_1.UILabelProvider.modifierLabels[platform_1.OS].altKey}] ${altTitleSection}`;
}
this.label.title = title;
}
}
updateClass() {
if (this.options.icon) {
if (this._commandAction !== this._menuItemAction) {
if (this._menuItemAction.alt) {
this._updateItemClass(this._menuItemAction.alt.item);
}
}
else if (this._menuItemAction.alt) {
this._updateItemClass(this._menuItemAction.item);
}
}
}
_updateItemClass(item) {
var _a;
this._itemClassDispose.value = undefined;
const { element, label } = this;
if (!element || !label) {
return;
}
const icon = this._commandAction.checked && ((_a = item.toggled) === null || _a === void 0 ? void 0 : _a.icon) ? item.toggled.icon : item.icon;
if (!icon) {
return;
}
if (themeService_1.ThemeIcon.isThemeIcon(icon)) {
// theme icons
const iconClasses = themeService_1.ThemeIcon.asClassNameArray(icon);
label.classList.add(...iconClasses);
this._itemClassDispose.value = (0, lifecycle_1.toDisposable)(() => {
label.classList.remove(...iconClasses);
});
}
else {
// icon path/url
if (icon.light) {
label.style.setProperty('--menu-entry-icon-light', (0, dom_1.asCSSUrl)(icon.light));
}
if (icon.dark) {
label.style.setProperty('--menu-entry-icon-dark', (0, dom_1.asCSSUrl)(icon.dark));
}
label.classList.add('icon');
this._itemClassDispose.value = (0, lifecycle_1.toDisposable)(() => {
label.classList.remove('icon');
label.style.removeProperty('--menu-entry-icon-light');
label.style.removeProperty('--menu-entry-icon-dark');
});
}
}
};
MenuEntryActionViewItem = __decorate([
__param(2, keybinding_1.IKeybindingService),
__param(3, notification_1.INotificationService),
__param(4, contextkey_1.IContextKeyService)
], MenuEntryActionViewItem);
exports.MenuEntryActionViewItem = MenuEntryActionViewItem;
let SubmenuEntryActionViewItem = class SubmenuEntryActionViewItem extends dropdownActionViewItem_1.DropdownMenuActionViewItem {
constructor(action, contextMenuService) {
super(action, { getActions: () => action.actions }, contextMenuService, {
menuAsChild: true,
classNames: themeService_1.ThemeIcon.isThemeIcon(action.item.icon) ? themeService_1.ThemeIcon.asClassName(action.item.icon) : undefined,
});
}
render(container) {
super.render(container);
if (this.element) {
container.classList.add('menu-entry');
const { icon } = this._action.item;
if (icon && !themeService_1.ThemeIcon.isThemeIcon(icon)) {
this.element.classList.add('icon');
if (icon.light) {
this.element.style.setProperty('--menu-entry-icon-light', (0, dom_1.asCSSUrl)(icon.light));
}
if (icon.dark) {
this.element.style.setProperty('--menu-entry-icon-dark', (0, dom_1.asCSSUrl)(icon.dark));
}
}
}
}
};
SubmenuEntryActionViewItem = __decorate([
__param(1, contextView_1.IContextMenuService)
], SubmenuEntryActionViewItem);
exports.SubmenuEntryActionViewItem = SubmenuEntryActionViewItem;
let DropdownWithDefaultActionViewItem = class DropdownWithDefaultActionViewItem extends actionViewItems_1.BaseActionViewItem {
constructor(submenuAction, _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._storageKey = `${submenuAction.item.submenu._debugName}_lastActionId`;
// determine default action
let defaultAction;
let defaultActionId = _storageService.get(this._storageKey, 1 /* WORKSPACE */);
if (defaultActionId) {
defaultAction = submenuAction.actions.find(a => defaultActionId === a.id);
}
if (!defaultAction) {
defaultAction = submenuAction.actions[0];
}
this._defaultAction = this._instaService.createInstance(MenuEntryActionViewItem, defaultAction, undefined);
this._dropdown = new dropdownActionViewItem_1.DropdownMenuActionViewItem(submenuAction, submenuAction.actions, this._contextMenuService, {
menuAsChild: true,
classNames: ['codicon', 'codicon-chevron-down']
});
this._dropdown.actionRunner.onDidRun((e) => {
if (e.action instanceof actions_2.MenuItemAction) {
this.update(e.action);
}
});
}
update(lastAction) {
this._storageService.store(this._storageKey, lastAction.id, 1 /* WORKSPACE */, 0 /* USER */);
this._defaultAction.dispose();
this._defaultAction = this._instaService.createInstance(MenuEntryActionViewItem, lastAction, undefined);
this._defaultAction.actionRunner = new class extends actions_1.ActionRunner {
runAction(action, context) {
return __awaiter(this, void 0, void 0, function* () {
yield action.run(undefined);
});
}
}();
if (this._container) {
this._defaultAction.render((0, dom_1.prepend)(this._container, (0, dom_1.$)('.action-container')));
}
}
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-primary');
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 /* 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) => {
var _a;
const event = new keyboardEvent_1.StandardKeyboardEvent(e);
if (event.equals(15 /* LeftArrow */)) {
this._defaultAction.element.tabIndex = 0;
this._dropdown.setFocusable(false);
(_a = this._defaultAction.element) === null || _a === void 0 ? void 0 : _a.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();
}
};
DropdownWithDefaultActionViewItem = __decorate([
__param(1, keybinding_1.IKeybindingService),
__param(2, notification_1.INotificationService),
__param(3, contextView_1.IContextMenuService),
__param(4, actions_2.IMenuService),
__param(5, instantiation_1.IInstantiationService),
__param(6, storage_1.IStorageService)
], DropdownWithDefaultActionViewItem);
/**
* Creates action view items for menu actions or submenu actions.
*/
function createActionViewItem(instaService, action) {
if (action instanceof actions_2.MenuItemAction) {
return instaService.createInstance(MenuEntryActionViewItem, action, undefined);
}
else if (action instanceof actions_2.SubmenuItemAction) {
const allCodicons = !action.actions.some(a => a instanceof actions_2.MenuItemAction && a.item.icon && !themeService_1.ThemeIcon.isThemeIcon(a.item.icon));
if (action.item.rememberDefaultAction && allCodicons) {
return instaService.createInstance(DropdownWithDefaultActionViewItem, action);
}
else {
return instaService.createInstance(SubmenuEntryActionViewItem, action);
}
}
else {
return undefined;
}
}
exports.createActionViewItem = createActionViewItem;
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/peekView/peekView*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,84/*vs/base/browser/ui/actionbar/actionbar*/,50/*vs/base/common/actions*/,29/*vs/base/common/color*/,6/*vs/base/common/event*/,42/*vs/base/common/objects*/,28/*vs/editor/browser/services/codeEditorService*/,150/*vs/editor/browser/widget/embeddedCodeEditorWidget*/,557/*vs/editor/contrib/zoneWidget/zoneWidget*/,512/*vs/nls!vs/editor/contrib/peekView/peekView*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/,75/*vs/platform/instantiation/common/extensions*/,14/*vs/editor/browser/editorExtensions*/,22/*vs/platform/theme/common/colorRegistry*/,27/*vs/base/common/codicons*/,192/*vs/platform/actions/browser/menuEntryActionViewItem*/,358/*vs/css!vs/editor/contrib/peekView/media/peekViewWidget*/]), function (require, exports, dom, actionbar_1, actions_1, color_1, event_1, objects, codeEditorService_1, embeddedCodeEditorWidget_1, zoneWidget_1, nls, contextkey_1, instantiation_1, extensions_1, editorExtensions_1, colorRegistry_1, codicons_1, menuEntryActionViewItem_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.peekViewEditorMatchHighlightBorder = exports.peekViewEditorMatchHighlight = exports.peekViewResultsMatchHighlight = 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.getOuterEditor = exports.PeekContext = exports.IPeekViewService = void 0;
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) });
}
});
var PeekContext;
(function (PeekContext) {
PeekContext.inPeekEditor = new contextkey_1.RawContextKey('inReferenceSearchEditor', true, nls.localize(0, null));
PeekContext.notInPeekEditor = PeekContext.inPeekEditor.toNegated();
})(PeekContext = exports.PeekContext || (exports.PeekContext = {}));
let PeekContextController = class PeekContextController {
constructor(editor, contextKeyService) {
if (editor instanceof embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget) {
PeekContext.inPeekEditor.bindTo(contextKeyService);
}
}
dispose() { }
};
PeekContextController.ID = 'editor.contrib.referenceController';
PeekContextController = __decorate([
__param(1, contextkey_1.IContextKeyService)
], PeekContextController);
(0, editorExtensions_1.registerEditorContribution)(PeekContextController.ID, PeekContextController);
function getOuterEditor(accessor) {
let editor = accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor();
if (editor instanceof embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget) {
return editor.getParentEditor();
}
return editor;
}
exports.getOuterEditor = getOuterEditor;
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) {
let 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();
let 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) {
const titleElement = dom.$('.peekview-title');
dom.append(this._headElement, titleElement);
dom.addStandardDisposableListener(titleElement, 'click', event => this._onTitleClick(event));
this._fillTitleIcon(titleElement);
this._primaryHeading = dom.$('span.filename');
this._secondaryHeading = dom.$('span.dirname');
this._metaHeading = dom.$('span.meta');
dom.append(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(1, null), codicons_1.Codicon.close.classNames, true, () => {
this.dispose();
return Promise.resolve();
}), { label: false, icon: true });
}
}
_fillTitleIcon(container) {
}
_getActionBarOptions() {
return {
actionViewItemProvider: menuEntryActionViewItem_1.createActionViewItem.bind(undefined, this.instantiationService),
orientation: 0 /* HORIZONTAL */
};
}
_onTitleClick(event) {
// implement me
}
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(57 /* 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`;
}
}
};
PeekViewWidget = __decorate([
__param(2, instantiation_1.IInstantiationService)
], PeekViewWidget);
exports.PeekViewWidget = PeekViewWidget;
exports.peekViewTitleBackground = (0, colorRegistry_1.registerColor)('peekViewTitle.background', { dark: '#1E1E1E', light: '#FFFFFF', hc: '#0C141F' }, nls.localize(2, null));
exports.peekViewTitleForeground = (0, colorRegistry_1.registerColor)('peekViewTitleLabel.foreground', { dark: '#FFFFFF', light: '#333333', hc: '#FFFFFF' }, nls.localize(3, null));
exports.peekViewTitleInfoForeground = (0, colorRegistry_1.registerColor)('peekViewTitleDescription.foreground', { dark: '#ccccccb3', light: '#616161e6', hc: '#FFFFFF99' }, nls.localize(4, null));
exports.peekViewBorder = (0, colorRegistry_1.registerColor)('peekView.border', { dark: '#007acc', light: '#007acc', hc: colorRegistry_1.contrastBorder }, nls.localize(5, null));
exports.peekViewResultsBackground = (0, colorRegistry_1.registerColor)('peekViewResult.background', { dark: '#252526', light: '#F3F3F3', hc: color_1.Color.black }, nls.localize(6, null));
exports.peekViewResultsMatchForeground = (0, colorRegistry_1.registerColor)('peekViewResult.lineForeground', { dark: '#bbbbbb', light: '#646465', hc: color_1.Color.white }, nls.localize(7, null));
exports.peekViewResultsFileForeground = (0, colorRegistry_1.registerColor)('peekViewResult.fileForeground', { dark: color_1.Color.white, light: '#1E1E1E', hc: color_1.Color.white }, nls.localize(8, null));
exports.peekViewResultsSelectionBackground = (0, colorRegistry_1.registerColor)('peekViewResult.selectionBackground', { dark: '#3399ff33', light: '#3399ff33', hc: null }, nls.localize(9, null));
exports.peekViewResultsSelectionForeground = (0, colorRegistry_1.registerColor)('peekViewResult.selectionForeground', { dark: color_1.Color.white, light: '#6C6C6C', hc: color_1.Color.white }, nls.localize(10, null));
exports.peekViewEditorBackground = (0, colorRegistry_1.registerColor)('peekViewEditor.background', { dark: '#001F33', light: '#F2F8FC', hc: color_1.Color.black }, nls.localize(11, null));
exports.peekViewEditorGutterBackground = (0, colorRegistry_1.registerColor)('peekViewEditorGutter.background', { dark: exports.peekViewEditorBackground, light: exports.peekViewEditorBackground, hc: exports.peekViewEditorBackground }, nls.localize(12, null));
exports.peekViewResultsMatchHighlight = (0, colorRegistry_1.registerColor)('peekViewResult.matchHighlightBackground', { dark: '#ea5c004d', light: '#ea5c004d', hc: null }, nls.localize(13, null));
exports.peekViewEditorMatchHighlight = (0, colorRegistry_1.registerColor)('peekViewEditor.matchHighlightBackground', { dark: '#ff8f0099', light: '#f5d802de', hc: null }, nls.localize(14, null));
exports.peekViewEditorMatchHighlightBorder = (0, colorRegistry_1.registerColor)('peekViewEditor.matchHighlightBorder', { dark: null, light: null, hc: colorRegistry_1.activeContrastBorder }, nls.localize(15, 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[664/*vs/editor/contrib/suggest/suggestWidgetStatus*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,84/*vs/base/browser/ui/actionbar/actionbar*/,2/*vs/base/common/lifecycle*/,123/*vs/editor/contrib/suggest/suggest*/,525/*vs/nls!vs/editor/contrib/suggest/suggestWidgetStatus*/,192/*vs/platform/actions/browser/menuEntryActionViewItem*/,33/*vs/platform/actions/common/actions*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, dom, actionbar_1, lifecycle_1, suggest_1, nls_1, menuEntryActionViewItem_1, actions_1, contextkey_1, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SuggestWidgetStatus = void 0;
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) {
this.label.textContent = (0, nls_1.localize)(0, null, this._action.label, StatusBarViewItem.symbolPrintEnter(kb));
}
}
static symbolPrintEnter(kb) {
var _a;
return (_a = kb.getLabel()) === null || _a === void 0 ? void 0 : _a.replace(/\benter\b/gi, '\u23CE');
}
}
let SuggestWidgetStatus = class SuggestWidgetStatus {
constructor(container, instantiationService, _menuService, _contextKeyService) {
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(StatusBarViewItem, action, undefined) : 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.element.remove();
}
show() {
const menu = this._menuService.createMenu(suggest_1.suggestWidgetStatusbarMenu, this._contextKeyService);
const renderMenu = () => {
const left = [];
const right = [];
for (let [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();
}
};
SuggestWidgetStatus = __decorate([
__param(1, instantiation_1.IInstantiationService),
__param(2, actions_1.IMenuService),
__param(3, contextkey_1.IContextKeyService)
], SuggestWidgetStatus);
exports.SuggestWidgetStatus = 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[665/*vs/platform/actions/common/menuService*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,33/*vs/platform/actions/common/actions*/,26/*vs/platform/commands/common/commands*/,16/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, async_1, event_1, lifecycle_1, actions_1, commands_1, contextkey_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MenuService = void 0;
let MenuService = class MenuService {
constructor(_commandService) {
this._commandService = _commandService;
//
}
/**
* Create a new menu for the given menu identifier. A menu sends events when it's entries
* have changed (placement, enablement, checked-state). By default it does send events for
* sub menu entries. That is more expensive and must be explicitly enabled with the
* `emitEventsForSubmenuChanges` flag.
*/
createMenu(id, contextKeyService, emitEventsForSubmenuChanges = false) {
return new Menu(id, emitEventsForSubmenuChanges, this._commandService, contextKeyService, this);
}
};
MenuService = __decorate([
__param(0, commands_1.ICommandService)
], MenuService);
exports.MenuService = MenuService;
let Menu = class Menu {
constructor(_id, _fireEventsForSubmenuChanges, _commandService, _contextKeyService, _menuService) {
this._id = _id;
this._fireEventsForSubmenuChanges = _fireEventsForSubmenuChanges;
this._commandService = _commandService;
this._contextKeyService = _contextKeyService;
this._menuService = _menuService;
this._disposables = new lifecycle_1.DisposableStore();
this._menuGroups = [];
this._contextKeys = new Set();
this._build();
// 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._build();
this._onDidChange.fire(this);
}, 50);
this._disposables.add(rebuildMenuSoon);
this._disposables.add(actions_1.MenuRegistry.onDidChangeMenu(e => {
if (e.has(_id)) {
rebuildMenuSoon.schedule();
}
}));
// When context keys change we need to check if the menu also has changed. However,
// we only do that when someone listens on this menu because (1) context key events are
// firing often and (2) menu are often leaked
const contextKeyListener = this._disposables.add(new lifecycle_1.DisposableStore());
const startContextKeyListener = () => {
const fireChangeSoon = new async_1.RunOnceScheduler(() => this._onDidChange.fire(this), 50);
contextKeyListener.add(fireChangeSoon);
contextKeyListener.add(_contextKeyService.onDidChangeContext(e => {
if (e.affectsSome(this._contextKeys)) {
fireChangeSoon.schedule();
}
}));
};
this._onDidChange = new event_1.Emitter({
// start/stop context key listener
onFirstListenerAdd: startContextKeyListener,
onLastListenerRemove: contextKeyListener.clear.bind(contextKeyListener)
});
this.onDidChange = this._onDidChange.event;
}
dispose() {
this._disposables.dispose();
this._onDidChange.dispose();
}
_build() {
// reset
this._menuGroups.length = 0;
this._contextKeys.clear();
const menuItems = actions_1.MenuRegistry.getMenuItems(this._id);
let group;
menuItems.sort(Menu._compareMenuItems);
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 for eventing
this._collectContextKeys(item);
}
}
_collectContextKeys(item) {
Menu._fillInKbExprKeys(item.when, this._contextKeys);
if ((0, actions_1.isIMenuItem)(item)) {
// keep precondition keys for event if applicable
if (item.command.precondition) {
Menu._fillInKbExprKeys(item.command.precondition, this._contextKeys);
}
// keep toggled keys for event if applicable
if (item.command.toggled) {
const toggledExpression = item.command.toggled.condition || item.command.toggled;
Menu._fillInKbExprKeys(toggledExpression, this._contextKeys);
}
}
else if (this._fireEventsForSubmenuChanges) {
// 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._collectContextKeys, this);
}
}
getActions(options) {
const result = [];
for (let group of this._menuGroups) {
const [id, items] = group;
const activeActions = [];
for (const item of items) {
if (this._contextKeyService.contextMatchesRules(item.when)) {
const action = (0, actions_1.isIMenuItem)(item)
? new actions_1.MenuItemAction(item.command, item.alt, options, this._contextKeyService, this._commandService)
: new actions_1.SubmenuItemAction(item, this._menuService, this._contextKeyService, options);
activeActions.push(action);
}
}
if (activeActions.length > 0) {
result.push([id, activeActions]);
}
}
return result;
}
static _fillInKbExprKeys(exp, set) {
if (exp) {
for (let key of exp.keys()) {
set.add(key);
}
}
}
static _compareMenuItems(a, b) {
let aGroup = a.group;
let 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
let value = aGroup.localeCompare(bGroup);
if (value !== 0) {
return value;
}
}
// sort on priority - default is 0
let aPrio = a.order || 0;
let bPrio = b.order || 0;
if (aPrio < bPrio) {
return -1;
}
else if (aPrio > bPrio) {
return 1;
}
// sort on titles
return Menu._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);
}
};
Menu = __decorate([
__param(2, commands_1.ICommandService),
__param(3, contextkey_1.IContextKeyService),
__param(4, actions_1.IMenuService)
], Menu);
});
/*---------------------------------------------------------------------------------------------
* 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/platform/contextview/browser/contextMenuService*/], __M([0/*require*/,1/*exports*/,593/*vs/platform/contextview/browser/contextMenuHandler*/,69/*vs/platform/contextview/browser/contextView*/,89/*vs/platform/telemetry/common/telemetry*/,34/*vs/platform/notification/common/notification*/,11/*vs/platform/theme/common/themeService*/,37/*vs/platform/keybinding/common/keybinding*/,2/*vs/base/common/lifecycle*/,7/*vs/base/browser/dom*/]), function (require, exports, contextMenuHandler_1, contextView_1, telemetry_1, notification_1, themeService_1, keybinding_1, lifecycle_1, dom_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextMenuService = void 0;
let ContextMenuService = class ContextMenuService extends lifecycle_1.Disposable {
constructor(telemetryService, notificationService, contextViewService, keybindingService, themeService) {
super();
this.contextMenuHandler = new contextMenuHandler_1.ContextMenuHandler(contextViewService, telemetryService, notificationService, keybindingService, themeService);
}
configure(options) {
this.contextMenuHandler.configure(options);
}
// ContextMenu
showContextMenu(delegate) {
this.contextMenuHandler.showContextMenu(delegate);
dom_1.ModifierKeyEmitter.getInstance().resetKeyStatus();
}
};
ContextMenuService = __decorate([
__param(0, telemetry_1.ITelemetryService),
__param(1, notification_1.INotificationService),
__param(2, contextView_1.IContextViewService),
__param(3, keybinding_1.IKeybindingService),
__param(4, themeService_1.IThemeService)
], ContextMenuService);
exports.ContextMenuService = ContextMenuService;
});
/*---------------------------------------------------------------------------------------------
* 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/platform/list/browser/listService*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,320/*vs/base/browser/ui/list/listPaging*/,108/*vs/base/browser/ui/list/listWidget*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,537/*vs/nls!vs/platform/list/browser/listService*/,38/*vs/platform/configuration/common/configuration*/,98/*vs/platform/configuration/common/configurationRegistry*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/,37/*vs/platform/keybinding/common/keybinding*/,32/*vs/platform/registry/common/platform*/,122/*vs/platform/theme/common/styler*/,11/*vs/platform/theme/common/themeService*/,253/*vs/platform/contextkey/common/contextkeys*/,238/*vs/base/browser/ui/tree/objectTree*/,438/*vs/base/browser/ui/tree/asyncDataTree*/,437/*vs/base/browser/ui/tree/dataTree*/,64/*vs/platform/accessibility/common/accessibility*/,323/*vs/base/browser/ui/table/tableWidget*/]), function (require, exports, dom_1, listPaging_1, listWidget_1, event_1, lifecycle_1, nls_1, configuration_1, configurationRegistry_1, contextkey_1, instantiation_1, keybinding_1, platform_1, styler_1, themeService_1, contextkeys_1, objectTree_1, asyncDataTree_1, dataTree_1, accessibility_1, tableWidget_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.WorkbenchListAutomaticKeyboardNavigationKey = exports.WorkbenchListSelectionNavigation = exports.WorkbenchListMultiSelection = exports.WorkbenchListDoubleSelection = exports.WorkbenchListHasSelectionOrFocus = exports.WorkbenchListFocusContextKey = exports.WorkbenchListSupportsMultiSelectContextKey = exports.ListService = exports.IListService = void 0;
exports.IListService = (0, instantiation_1.createDecorator)('listService');
let ListService = class ListService {
constructor(_themeService) {
this._themeService = _themeService;
this.disposables = new lifecycle_1.DisposableStore();
this.lists = [];
this._lastFocusedWidget = undefined;
this._hasCreatedStyleController = false;
}
get lastFocusedList() {
return this._lastFocusedWidget;
}
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)(), '');
this.disposables.add((0, styler_1.attachListStyler)(styleController, this._themeService));
}
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 (widget.getHTMLElement() === document.activeElement) {
this._lastFocusedWidget = widget;
}
return (0, lifecycle_1.combinedDisposable)(widget.onDidFocus(() => this._lastFocusedWidget = 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._lastFocusedWidget = undefined;
}
}));
}
dispose() {
this.disposables.dispose();
}
};
ListService = __decorate([
__param(0, themeService_1.IThemeService)
], ListService);
exports.ListService = ListService;
const RawWorkbenchListFocusContextKey = new contextkey_1.RawContextKey('listFocus', true);
exports.WorkbenchListSupportsMultiSelectContextKey = new contextkey_1.RawContextKey('listSupportsMultiselect', true);
exports.WorkbenchListFocusContextKey = contextkey_1.ContextKeyExpr.and(RawWorkbenchListFocusContextKey, contextkey_1.ContextKeyExpr.not(contextkeys_1.InputFocusedContextKey));
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.WorkbenchListAutomaticKeyboardNavigationKey = 'listAutomaticKeyboardNavigation';
function createScopedContextKeyService(contextKeyService, widget) {
const result = contextKeyService.createScoped(widget.getHTMLElement());
RawWorkbenchListFocusContextKey.bindTo(result);
return result;
}
const multiSelectModifierSettingKey = 'workbench.list.multiSelectModifier';
const openModeSettingKey = 'workbench.list.openMode';
const horizontalScrollingKey = 'workbench.list.horizontalScrolling';
const keyboardNavigationSettingKey = 'workbench.list.keyboardNavigation';
const automaticKeyboardNavigationSettingKey = 'workbench.list.automaticKeyboardNavigation';
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';
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(options, configurationService, keybindingService) {
var _a;
const disposables = new lifecycle_1.DisposableStore();
const result = Object.assign(Object.assign({}, options), { keyboardNavigationDelegate: { mightProducePrintableCharacter(e) { return keybindingService.mightProducePrintableCharacter(e); } }, smoothScrolling: Boolean(configurationService.getValue(listSmoothScrolling)), mouseWheelScrollSensitivity: configurationService.getValue(mouseWheelScrollSensitivityKey), fastScrollSensitivity: configurationService.getValue(fastScrollSensitivityKey), multipleSelectionController: (_a = options.multipleSelectionController) !== null && _a !== void 0 ? _a : disposables.add(new MultipleSelectionController(configurationService)) });
return [result, disposables];
}
let WorkbenchList = class WorkbenchList extends listWidget_1.List {
constructor(user, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService) {
const horizontalScrolling = typeof options.horizontalScrolling !== 'undefined' ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
const [workbenchListOptions, workbenchListOptionsDisposable] = toWorkbenchListOptions(options, configurationService, keybindingService);
super(user, container, delegate, renderers, Object.assign(Object.assign(Object.assign({ keyboardSupport: false }, (0, styler_1.computeStyles)(themeService.getColorTheme(), styler_1.defaultListStyles)), workbenchListOptions), { horizontalScrolling }));
this.disposables.add(workbenchListOptionsDisposable);
this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
this.themeService = themeService;
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));
if (options.overrideStyles) {
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 = Object.assign(Object.assign({}, options), { horizontalScrolling });
}
if (e.affectsConfiguration(listSmoothScrolling)) {
const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
options = Object.assign(Object.assign({}, options), { smoothScrolling });
}
if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
options = Object.assign(Object.assign({}, options), { mouseWheelScrollSensitivity });
}
if (e.affectsConfiguration(fastScrollSensitivityKey)) {
const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
options = Object.assign(Object.assign({}, options), { fastScrollSensitivity });
}
if (Object.keys(options).length > 0) {
this.updateOptions(options);
}
}));
this.navigator = new ListResourceNavigator(this, Object.assign({ configurationService }, options));
this.disposables.add(this.navigator);
}
updateOptions(options) {
super.updateOptions(options);
if (options.overrideStyles) {
this.updateStyles(options.overrideStyles);
}
if (options.multipleSelectionSupport !== undefined) {
this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
}
}
updateStyles(styles) {
var _a;
(_a = this._styler) === null || _a === void 0 ? void 0 : _a.dispose();
this._styler = (0, styler_1.attachListStyler)(this, this.themeService, styles);
}
dispose() {
var _a;
(_a = this._styler) === null || _a === void 0 ? void 0 : _a.dispose();
super.dispose();
}
};
WorkbenchList = __decorate([
__param(5, contextkey_1.IContextKeyService),
__param(6, exports.IListService),
__param(7, themeService_1.IThemeService),
__param(8, configuration_1.IConfigurationService),
__param(9, keybinding_1.IKeybindingService)
], WorkbenchList);
exports.WorkbenchList = WorkbenchList;
let WorkbenchPagedList = class WorkbenchPagedList extends listPaging_1.PagedList {
constructor(user, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService) {
const horizontalScrolling = typeof options.horizontalScrolling !== 'undefined' ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
const [workbenchListOptions, workbenchListOptionsDisposable] = toWorkbenchListOptions(options, configurationService, keybindingService);
super(user, container, delegate, renderers, Object.assign(Object.assign(Object.assign({ keyboardSupport: false }, (0, styler_1.computeStyles)(themeService.getColorTheme(), styler_1.defaultListStyles)), workbenchListOptions), { horizontalScrolling }));
this.disposables = new lifecycle_1.DisposableStore();
this.disposables.add(workbenchListOptionsDisposable);
this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
this.themeService = themeService;
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));
if (options.overrideStyles) {
this.updateStyles(options.overrideStyles);
}
if (options.overrideStyles) {
this.disposables.add((0, styler_1.attachListStyler)(this, themeService, 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 = Object.assign(Object.assign({}, options), { horizontalScrolling });
}
if (e.affectsConfiguration(listSmoothScrolling)) {
const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
options = Object.assign(Object.assign({}, options), { smoothScrolling });
}
if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
options = Object.assign(Object.assign({}, options), { mouseWheelScrollSensitivity });
}
if (e.affectsConfiguration(fastScrollSensitivityKey)) {
const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
options = Object.assign(Object.assign({}, options), { fastScrollSensitivity });
}
if (Object.keys(options).length > 0) {
this.updateOptions(options);
}
}));
this.navigator = new ListResourceNavigator(this, Object.assign({ configurationService }, options));
this.disposables.add(this.navigator);
}
updateOptions(options) {
super.updateOptions(options);
if (options.overrideStyles) {
this.updateStyles(options.overrideStyles);
}
if (options.multipleSelectionSupport !== undefined) {
this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
}
}
updateStyles(styles) {
var _a;
(_a = this._styler) === null || _a === void 0 ? void 0 : _a.dispose();
this._styler = (0, styler_1.attachListStyler)(this, this.themeService, styles);
}
dispose() {
var _a;
(_a = this._styler) === null || _a === void 0 ? void 0 : _a.dispose();
this.disposables.dispose();
super.dispose();
}
};
WorkbenchPagedList = __decorate([
__param(5, contextkey_1.IContextKeyService),
__param(6, exports.IListService),
__param(7, themeService_1.IThemeService),
__param(8, configuration_1.IConfigurationService),
__param(9, keybinding_1.IKeybindingService)
], WorkbenchPagedList);
exports.WorkbenchPagedList = WorkbenchPagedList;
let WorkbenchTable = class WorkbenchTable extends tableWidget_1.Table {
constructor(user, container, delegate, columns, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService) {
const horizontalScrolling = typeof options.horizontalScrolling !== 'undefined' ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
const [workbenchListOptions, workbenchListOptionsDisposable] = toWorkbenchListOptions(options, configurationService, keybindingService);
super(user, container, delegate, columns, renderers, Object.assign(Object.assign(Object.assign({ keyboardSupport: false }, (0, styler_1.computeStyles)(themeService.getColorTheme(), styler_1.defaultListStyles)), workbenchListOptions), { horizontalScrolling }));
this.disposables = new lifecycle_1.DisposableStore();
this.disposables.add(workbenchListOptionsDisposable);
this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
this.themeService = themeService;
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));
if (options.overrideStyles) {
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 = Object.assign(Object.assign({}, options), { horizontalScrolling });
}
if (e.affectsConfiguration(listSmoothScrolling)) {
const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
options = Object.assign(Object.assign({}, options), { smoothScrolling });
}
if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
options = Object.assign(Object.assign({}, options), { mouseWheelScrollSensitivity });
}
if (e.affectsConfiguration(fastScrollSensitivityKey)) {
const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
options = Object.assign(Object.assign({}, options), { fastScrollSensitivity });
}
if (Object.keys(options).length > 0) {
this.updateOptions(options);
}
}));
this.navigator = new TableResourceNavigator(this, Object.assign({ configurationService }, options));
this.disposables.add(this.navigator);
}
updateOptions(options) {
super.updateOptions(options);
if (options.overrideStyles) {
this.updateStyles(options.overrideStyles);
}
if (options.multipleSelectionSupport !== undefined) {
this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
}
}
updateStyles(styles) {
var _a;
(_a = this._styler) === null || _a === void 0 ? void 0 : _a.dispose();
this._styler = (0, styler_1.attachListStyler)(this, this.themeService, styles);
}
dispose() {
var _a;
(_a = this._styler) === null || _a === void 0 ? void 0 : _a.dispose();
this.disposables.dispose();
super.dispose();
}
};
WorkbenchTable = __decorate([
__param(6, contextkey_1.IContextKeyService),
__param(7, exports.IListService),
__param(8, themeService_1.IThemeService),
__param(9, configuration_1.IConfigurationService),
__param(10, keybinding_1.IKeybindingService)
], WorkbenchTable);
exports.WorkbenchTable = WorkbenchTable;
class ResourceNavigator extends lifecycle_1.Disposable {
constructor(widget, options) {
var _a;
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 => e.browserEvent instanceof KeyboardEvent)(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 === null || options === void 0 ? void 0 : options.openOnSingleClick) !== 'boolean' && (options === null || options === void 0 ? void 0 : options.configurationService)) {
this.openOnSingleClick = (options === null || options === void 0 ? void 0 : options.configurationService.getValue(openModeSettingKey)) !== 'doubleClick';
this._register(options === null || options === void 0 ? void 0 : options.configurationService.onDidChangeConfiguration(() => {
this.openOnSingleClick = (options === null || options === void 0 ? void 0 : options.configurationService.getValue(openModeSettingKey)) !== 'doubleClick';
}));
}
else {
this.openOnSingleClick = (_a = options === null || options === void 0 ? void 0 : options.openOnSingleClick) !== null && _a !== void 0 ? _a : 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() {
var _a;
return (_a = this.widget.getSelection()[0]) !== null && _a !== void 0 ? _a : undefined;
}
}
function createKeyboardNavigationEventFilter(container, keybindingService) {
let inChord = false;
return event => {
if (inChord) {
inChord = false;
return false;
}
const result = keybindingService.softDispatch(event, container);
if (result && result.enterChord) {
inChord = true;
return false;
}
inChord = false;
return true;
};
}
let WorkbenchObjectTree = class WorkbenchObjectTree extends objectTree_1.ObjectTree {
constructor(user, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) {
const { options: treeOptions, getAutomaticKeyboardNavigation, disposable } = workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService);
super(user, container, delegate, renderers, treeOptions);
this.disposables.add(disposable);
this.internals = new WorkbenchTreeInternals(this, options, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService);
this.disposables.add(this.internals);
}
updateOptions(options) {
super.updateOptions(options);
this.internals.updateOptions(options);
}
};
WorkbenchObjectTree = __decorate([
__param(5, contextkey_1.IContextKeyService),
__param(6, exports.IListService),
__param(7, themeService_1.IThemeService),
__param(8, configuration_1.IConfigurationService),
__param(9, keybinding_1.IKeybindingService),
__param(10, accessibility_1.IAccessibilityService)
], WorkbenchObjectTree);
exports.WorkbenchObjectTree = WorkbenchObjectTree;
let WorkbenchCompressibleObjectTree = class WorkbenchCompressibleObjectTree extends objectTree_1.CompressibleObjectTree {
constructor(user, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) {
const { options: treeOptions, getAutomaticKeyboardNavigation, disposable } = workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService);
super(user, container, delegate, renderers, treeOptions);
this.disposables.add(disposable);
this.internals = new WorkbenchTreeInternals(this, options, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService);
this.disposables.add(this.internals);
}
updateOptions(options = {}) {
super.updateOptions(options);
if (options.overrideStyles) {
this.internals.updateStyleOverrides(options.overrideStyles);
}
this.internals.updateOptions(options);
}
};
WorkbenchCompressibleObjectTree = __decorate([
__param(5, contextkey_1.IContextKeyService),
__param(6, exports.IListService),
__param(7, themeService_1.IThemeService),
__param(8, configuration_1.IConfigurationService),
__param(9, keybinding_1.IKeybindingService),
__param(10, accessibility_1.IAccessibilityService)
], WorkbenchCompressibleObjectTree);
exports.WorkbenchCompressibleObjectTree = WorkbenchCompressibleObjectTree;
let WorkbenchDataTree = class WorkbenchDataTree extends dataTree_1.DataTree {
constructor(user, container, delegate, renderers, dataSource, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) {
const { options: treeOptions, getAutomaticKeyboardNavigation, disposable } = workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService);
super(user, container, delegate, renderers, dataSource, treeOptions);
this.disposables.add(disposable);
this.internals = new WorkbenchTreeInternals(this, options, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService);
this.disposables.add(this.internals);
}
updateOptions(options = {}) {
super.updateOptions(options);
if (options.overrideStyles) {
this.internals.updateStyleOverrides(options.overrideStyles);
}
this.internals.updateOptions(options);
}
};
WorkbenchDataTree = __decorate([
__param(6, contextkey_1.IContextKeyService),
__param(7, exports.IListService),
__param(8, themeService_1.IThemeService),
__param(9, configuration_1.IConfigurationService),
__param(10, keybinding_1.IKeybindingService),
__param(11, accessibility_1.IAccessibilityService)
], WorkbenchDataTree);
exports.WorkbenchDataTree = WorkbenchDataTree;
let WorkbenchAsyncDataTree = class WorkbenchAsyncDataTree extends asyncDataTree_1.AsyncDataTree {
constructor(user, container, delegate, renderers, dataSource, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) {
const { options: treeOptions, getAutomaticKeyboardNavigation, disposable } = workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService);
super(user, container, delegate, renderers, dataSource, treeOptions);
this.disposables.add(disposable);
this.internals = new WorkbenchTreeInternals(this, options, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService);
this.disposables.add(this.internals);
}
get onDidOpen() { return this.internals.onDidOpen; }
updateOptions(options = {}) {
super.updateOptions(options);
if (options.overrideStyles) {
this.internals.updateStyleOverrides(options.overrideStyles);
}
this.internals.updateOptions(options);
}
};
WorkbenchAsyncDataTree = __decorate([
__param(6, contextkey_1.IContextKeyService),
__param(7, exports.IListService),
__param(8, themeService_1.IThemeService),
__param(9, configuration_1.IConfigurationService),
__param(10, keybinding_1.IKeybindingService),
__param(11, accessibility_1.IAccessibilityService)
], WorkbenchAsyncDataTree);
exports.WorkbenchAsyncDataTree = WorkbenchAsyncDataTree;
let WorkbenchCompressibleAsyncDataTree = class WorkbenchCompressibleAsyncDataTree extends asyncDataTree_1.CompressibleAsyncDataTree {
constructor(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) {
const { options: treeOptions, getAutomaticKeyboardNavigation, disposable } = workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService);
super(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, treeOptions);
this.disposables.add(disposable);
this.internals = new WorkbenchTreeInternals(this, options, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService);
this.disposables.add(this.internals);
}
updateOptions(options) {
super.updateOptions(options);
this.internals.updateOptions(options);
}
};
WorkbenchCompressibleAsyncDataTree = __decorate([
__param(7, contextkey_1.IContextKeyService),
__param(8, exports.IListService),
__param(9, themeService_1.IThemeService),
__param(10, configuration_1.IConfigurationService),
__param(11, keybinding_1.IKeybindingService),
__param(12, accessibility_1.IAccessibilityService)
], WorkbenchCompressibleAsyncDataTree);
exports.WorkbenchCompressibleAsyncDataTree = WorkbenchCompressibleAsyncDataTree;
function workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService) {
var _a;
const getAutomaticKeyboardNavigation = () => {
// give priority to the context key value to disable this completely
let automaticKeyboardNavigation = Boolean(contextKeyService.getContextKeyValue(exports.WorkbenchListAutomaticKeyboardNavigationKey));
if (automaticKeyboardNavigation) {
automaticKeyboardNavigation = Boolean(configurationService.getValue(automaticKeyboardNavigationSettingKey));
}
return automaticKeyboardNavigation;
};
const accessibilityOn = accessibilityService.isScreenReaderOptimized();
const keyboardNavigation = options.simpleKeyboardNavigation || accessibilityOn ? 'simple' : configurationService.getValue(keyboardNavigationSettingKey);
const horizontalScrolling = options.horizontalScrolling !== undefined ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
const [workbenchListOptions, disposable] = toWorkbenchListOptions(options, configurationService, keybindingService);
const additionalScrollHeight = options.additionalScrollHeight;
return {
getAutomaticKeyboardNavigation,
disposable,
options: Object.assign(Object.assign({
// ...options, // TODO@Joao why is this not splatted here?
keyboardSupport: false }, workbenchListOptions), { indent: typeof configurationService.getValue(treeIndentKey) === 'number' ? configurationService.getValue(treeIndentKey) : undefined, renderIndentGuides: configurationService.getValue(treeRenderIndentGuidesKey), smoothScrolling: Boolean(configurationService.getValue(listSmoothScrolling)), automaticKeyboardNavigation: getAutomaticKeyboardNavigation(), simpleKeyboardNavigation: keyboardNavigation === 'simple', filterOnType: keyboardNavigation === 'filter', horizontalScrolling, keyboardNavigationEventFilter: createKeyboardNavigationEventFilter(container, keybindingService), additionalScrollHeight, hideTwistiesOfChildlessElements: options.hideTwistiesOfChildlessElements, expandOnlyOnTwistieClick: (_a = options.expandOnlyOnTwistieClick) !== null && _a !== void 0 ? _a : (configurationService.getValue(treeExpandMode) === 'doubleClick') })
};
}
let WorkbenchTreeInternals = class WorkbenchTreeInternals {
constructor(tree, options, getAutomaticKeyboardNavigation, overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService) {
this.tree = tree;
this.themeService = themeService;
this.disposables = [];
this.contextKeyService = createScopedContextKeyService(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.hasSelectionOrFocus = exports.WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
this.hasDoubleSelection = exports.WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
this.hasMultiSelection = exports.WorkbenchListMultiSelection.bindTo(this.contextKeyService);
this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
const interestingContextKeys = new Set();
interestingContextKeys.add(exports.WorkbenchListAutomaticKeyboardNavigationKey);
const updateKeyboardNavigation = () => {
const accessibilityOn = accessibilityService.isScreenReaderOptimized();
const keyboardNavigation = accessibilityOn ? 'simple' : configurationService.getValue(keyboardNavigationSettingKey);
tree.updateOptions({
simpleKeyboardNavigation: keyboardNavigation === 'simple',
filterOnType: keyboardNavigation === 'filter'
});
};
this.updateStyleOverrides(overrideStyles);
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);
}), configurationService.onDidChangeConfiguration(e => {
let newOptions = {};
if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
}
if (e.affectsConfiguration(treeIndentKey)) {
const indent = configurationService.getValue(treeIndentKey);
newOptions = Object.assign(Object.assign({}, newOptions), { indent });
}
if (e.affectsConfiguration(treeRenderIndentGuidesKey)) {
const renderIndentGuides = configurationService.getValue(treeRenderIndentGuidesKey);
newOptions = Object.assign(Object.assign({}, newOptions), { renderIndentGuides });
}
if (e.affectsConfiguration(listSmoothScrolling)) {
const smoothScrolling = Boolean(!!configurationService.getValue(listSmoothScrolling));
newOptions = Object.assign(Object.assign({}, newOptions), { smoothScrolling });
}
if (e.affectsConfiguration(keyboardNavigationSettingKey)) {
updateKeyboardNavigation();
}
if (e.affectsConfiguration(automaticKeyboardNavigationSettingKey)) {
newOptions = Object.assign(Object.assign({}, newOptions), { automaticKeyboardNavigation: getAutomaticKeyboardNavigation() });
}
if (e.affectsConfiguration(horizontalScrollingKey) && options.horizontalScrolling === undefined) {
const horizontalScrolling = Boolean(!!configurationService.getValue(horizontalScrollingKey));
newOptions = Object.assign(Object.assign({}, newOptions), { horizontalScrolling });
}
if (e.affectsConfiguration(treeExpandMode) && options.expandOnlyOnTwistieClick === undefined) {
newOptions = Object.assign(Object.assign({}, newOptions), { expandOnlyOnTwistieClick: configurationService.getValue(treeExpandMode) === 'doubleClick' });
}
if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
newOptions = Object.assign(Object.assign({}, newOptions), { mouseWheelScrollSensitivity });
}
if (e.affectsConfiguration(fastScrollSensitivityKey)) {
const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
newOptions = Object.assign(Object.assign({}, newOptions), { fastScrollSensitivity });
}
if (Object.keys(newOptions).length > 0) {
tree.updateOptions(newOptions);
}
}), this.contextKeyService.onDidChangeContext(e => {
if (e.affectsSome(interestingContextKeys)) {
tree.updateOptions({ automaticKeyboardNavigation: getAutomaticKeyboardNavigation() });
}
}), accessibilityService.onDidChangeScreenReaderOptimized(() => updateKeyboardNavigation()));
this.navigator = new TreeResourceNavigator(tree, Object.assign({ configurationService }, options));
this.disposables.push(this.navigator);
}
get onDidOpen() { return this.navigator.onDidOpen; }
updateOptions(options) {
if (options.multipleSelectionSupport !== undefined) {
this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
}
}
updateStyleOverrides(overrideStyles) {
(0, lifecycle_1.dispose)(this.styler);
this.styler = overrideStyles ? (0, styler_1.attachListStyler)(this.tree, this.themeService, overrideStyles) : lifecycle_1.Disposable.None;
}
dispose() {
this.disposables = (0, lifecycle_1.dispose)(this.disposables);
(0, lifecycle_1.dispose)(this.styler);
this.styler = undefined;
}
};
WorkbenchTreeInternals = __decorate([
__param(4, contextkey_1.IContextKeyService),
__param(5, exports.IListService),
__param(6, themeService_1.IThemeService),
__param(7, configuration_1.IConfigurationService),
__param(8, accessibility_1.IAccessibilityService)
], WorkbenchTreeInternals);
const configurationRegistry = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration);
configurationRegistry.registerConfiguration({
id: 'workbench',
order: 7,
title: (0, nls_1.localize)(0, null),
type: 'object',
properties: {
[multiSelectModifierSettingKey]: {
type: 'string',
enum: ['ctrlCmd', 'alt'],
enumDescriptions: [
(0, nls_1.localize)(1, null),
(0, nls_1.localize)(2, null)
],
default: 'ctrlCmd',
description: (0, nls_1.localize)(3, null)
},
[openModeSettingKey]: {
type: 'string',
enum: ['singleClick', 'doubleClick'],
default: 'singleClick',
description: (0, nls_1.localize)(4, null)
},
[horizontalScrollingKey]: {
type: 'boolean',
default: false,
description: (0, nls_1.localize)(5, null)
},
[treeIndentKey]: {
type: 'number',
default: 8,
minimum: 0,
maximum: 40,
description: (0, nls_1.localize)(6, null)
},
[treeRenderIndentGuidesKey]: {
type: 'string',
enum: ['none', 'onHover', 'always'],
default: 'onHover',
description: (0, nls_1.localize)(7, null)
},
[listSmoothScrolling]: {
type: 'boolean',
default: false,
description: (0, nls_1.localize)(8, null),
},
[mouseWheelScrollSensitivityKey]: {
type: 'number',
default: 1,
description: (0, nls_1.localize)(9, null)
},
[fastScrollSensitivityKey]: {
type: 'number',
default: 5,
description: (0, nls_1.localize)(10, null)
},
[keyboardNavigationSettingKey]: {
type: 'string',
enum: ['simple', 'highlight', 'filter'],
enumDescriptions: [
(0, nls_1.localize)(11, null),
(0, nls_1.localize)(12, null),
(0, nls_1.localize)(13, null)
],
default: 'highlight',
description: (0, nls_1.localize)(14, null)
},
[automaticKeyboardNavigationSettingKey]: {
type: 'boolean',
default: true,
markdownDescription: (0, nls_1.localize)(15, null)
},
[treeExpandMode]: {
type: 'string',
enum: ['singleClick', 'doubleClick'],
default: 'singleClick',
description: (0, nls_1.localize)(16, 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[667/*vs/platform/quickinput/browser/quickInput*/], __M([0/*require*/,1/*exports*/,144/*vs/platform/layout/browser/layoutService*/,9/*vs/platform/instantiation/common/instantiation*/,11/*vs/platform/theme/common/themeService*/,22/*vs/platform/theme/common/colorRegistry*/,23/*vs/base/common/cancellation*/,122/*vs/platform/theme/common/styler*/,16/*vs/platform/contextkey/common/contextkey*/,64/*vs/platform/accessibility/common/accessibility*/,453/*vs/base/parts/quickinput/browser/quickInput*/,153/*vs/platform/list/browser/listService*/,588/*vs/platform/quickinput/browser/quickAccess*/]), function (require, exports, layoutService_1, instantiation_1, themeService_1, colorRegistry_1, cancellation_1, styler_1, contextkey_1, accessibility_1, quickInput_1, listService_1, quickAccess_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.QuickInputService = void 0;
let QuickInputService = class QuickInputService extends themeService_1.Themable {
constructor(instantiationService, contextKeyService, themeService, accessibilityService, layoutService) {
super(themeService);
this.instantiationService = instantiationService;
this.contextKeyService = contextKeyService;
this.accessibilityService = accessibilityService;
this.layoutService = layoutService;
this.contexts = new Map();
}
get controller() {
if (!this._controller) {
this._controller = this._register(this.createController());
}
return this._controller;
}
get quickAccess() {
if (!this._quickAccess) {
this._quickAccess = this._register(this.instantiationService.createInstance(quickAccess_1.QuickAccessController));
}
return this._quickAccess;
}
createController(host = this.layoutService, options) {
var _a, _b;
const defaultOptions = {
idPrefix: 'quickInput_',
container: host.container,
ignoreFocusOut: () => false,
isScreenReaderOptimized: () => this.accessibilityService.isScreenReaderOptimized(),
backKeybindingLabel: () => undefined,
setContextKey: (id) => this.setContextKey(id),
returnFocus: () => host.focus(),
createList: (user, container, delegate, renderers, options) => this.instantiationService.createInstance(listService_1.WorkbenchList, user, container, delegate, renderers, options),
styles: this.computeStyles()
};
const controller = this._register(new quickInput_1.QuickInputController(Object.assign(Object.assign({}, defaultOptions), options)));
controller.layout(host.dimension, (_b = (_a = host.offset) === null || _a === void 0 ? void 0 : _a.top) !== null && _b !== void 0 ? _b : 0);
// Layout changes
this._register(host.onDidLayout(dimension => { var _a, _b; return controller.layout(dimension, (_b = (_a = host.offset) === null || _a === void 0 ? void 0 : _a.top) !== null && _b !== void 0 ? _b : 0); }));
// Context keys
this._register(controller.onShow(() => this.resetContextKeys()));
this._register(controller.onHide(() => this.resetContextKeys()));
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();
if (key) {
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() {
return this.controller.createQuickPick();
}
updateStyles() {
this.controller.applyStyles(this.computeStyles());
}
computeStyles() {
return {
widget: Object.assign({}, (0, styler_1.computeStyles)(this.theme, {
quickInputBackground: colorRegistry_1.quickInputBackground,
quickInputForeground: colorRegistry_1.quickInputForeground,
quickInputTitleBackground: colorRegistry_1.quickInputTitleBackground,
contrastBorder: colorRegistry_1.contrastBorder,
widgetShadow: colorRegistry_1.widgetShadow
})),
inputBox: (0, styler_1.computeStyles)(this.theme, {
inputForeground: colorRegistry_1.inputForeground,
inputBackground: colorRegistry_1.inputBackground,
inputBorder: colorRegistry_1.inputBorder,
inputValidationInfoBackground: colorRegistry_1.inputValidationInfoBackground,
inputValidationInfoForeground: colorRegistry_1.inputValidationInfoForeground,
inputValidationInfoBorder: colorRegistry_1.inputValidationInfoBorder,
inputValidationWarningBackground: colorRegistry_1.inputValidationWarningBackground,
inputValidationWarningForeground: colorRegistry_1.inputValidationWarningForeground,
inputValidationWarningBorder: colorRegistry_1.inputValidationWarningBorder,
inputValidationErrorBackground: colorRegistry_1.inputValidationErrorBackground,
inputValidationErrorForeground: colorRegistry_1.inputValidationErrorForeground,
inputValidationErrorBorder: colorRegistry_1.inputValidationErrorBorder
}),
countBadge: (0, styler_1.computeStyles)(this.theme, {
badgeBackground: colorRegistry_1.badgeBackground,
badgeForeground: colorRegistry_1.badgeForeground,
badgeBorder: colorRegistry_1.contrastBorder
}),
button: (0, styler_1.computeStyles)(this.theme, {
buttonForeground: colorRegistry_1.buttonForeground,
buttonBackground: colorRegistry_1.buttonBackground,
buttonHoverBackground: colorRegistry_1.buttonHoverBackground,
buttonBorder: colorRegistry_1.contrastBorder
}),
progressBar: (0, styler_1.computeStyles)(this.theme, {
progressBarBackground: colorRegistry_1.progressBarBackground
}),
keybindingLabel: (0, styler_1.computeStyles)(this.theme, {
keybindingLabelBackground: colorRegistry_1.keybindingLabelBackground,
keybindingLabelForeground: colorRegistry_1.keybindingLabelForeground,
keybindingLabelBorder: colorRegistry_1.keybindingLabelBorder,
keybindingLabelBottomBorder: colorRegistry_1.keybindingLabelBottomBorder,
keybindingLabelShadow: colorRegistry_1.widgetShadow
}),
list: (0, styler_1.computeStyles)(this.theme, {
listBackground: colorRegistry_1.quickInputBackground,
// 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,
pickerGroupBorder: colorRegistry_1.pickerGroupBorder,
pickerGroupForeground: colorRegistry_1.pickerGroupForeground
})
};
}
};
QuickInputService = __decorate([
__param(0, instantiation_1.IInstantiationService),
__param(1, contextkey_1.IContextKeyService),
__param(2, themeService_1.IThemeService),
__param(3, accessibility_1.IAccessibilityService),
__param(4, layoutService_1.ILayoutService)
], QuickInputService);
exports.QuickInputService = 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[668/*vs/editor/standalone/browser/quickInput/standaloneQuickInputServiceImpl*/], __M([0/*require*/,1/*exports*/,14/*vs/editor/browser/editorExtensions*/,11/*vs/platform/theme/common/themeService*/,23/*vs/base/common/cancellation*/,9/*vs/platform/instantiation/common/instantiation*/,16/*vs/platform/contextkey/common/contextkey*/,64/*vs/platform/accessibility/common/accessibility*/,144/*vs/platform/layout/browser/layoutService*/,28/*vs/editor/browser/services/codeEditorService*/,667/*vs/platform/quickinput/browser/quickInput*/,80/*vs/base/common/functional*/,366/*vs/css!vs/editor/standalone/browser/quickInput/standaloneQuickInput*/]), function (require, exports, editorExtensions_1, themeService_1, cancellation_1, instantiation_1, contextkey_1, accessibility_1, layoutService_1, codeEditorService_1, quickInput_1, functional_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.QuickInputEditorWidget = exports.QuickInputEditorContribution = exports.StandaloneQuickInputServiceImpl = exports.EditorScopedQuickInputServiceImpl = void 0;
let EditorScopedQuickInputServiceImpl = class EditorScopedQuickInputServiceImpl extends quickInput_1.QuickInputService {
constructor(editor, instantiationService, contextKeyService, themeService, accessibilityService, layoutService) {
super(instantiationService, contextKeyService, themeService, accessibilityService, layoutService);
this.host = undefined;
// Use the passed in code editor as host for the quick input widget
const contribution = QuickInputEditorContribution.get(editor);
this.host = {
_serviceBrand: undefined,
get container() { return contribution.widget.getDomNode(); },
get dimension() { return editor.getLayoutInfo(); },
get onDidLayout() { return editor.onDidLayoutChange; },
focus: () => editor.focus()
};
}
createController() {
return super.createController(this.host);
}
};
EditorScopedQuickInputServiceImpl = __decorate([
__param(1, instantiation_1.IInstantiationService),
__param(2, contextkey_1.IContextKeyService),
__param(3, themeService_1.IThemeService),
__param(4, accessibility_1.IAccessibilityService),
__param(5, layoutService_1.ILayoutService)
], EditorScopedQuickInputServiceImpl);
exports.EditorScopedQuickInputServiceImpl = EditorScopedQuickInputServiceImpl;
let StandaloneQuickInputServiceImpl = class StandaloneQuickInputServiceImpl {
constructor(instantiationService, codeEditorService) {
this.instantiationService = instantiationService;
this.codeEditorService = codeEditorService;
this.mapEditorToService = new Map();
}
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(EditorScopedQuickInputServiceImpl, editor);
this.mapEditorToService.set(editor, quickInputService);
(0, functional_1.once)(editor.onDidDispose)(() => {
newQuickInputService.dispose();
this.mapEditorToService.delete(editor);
});
}
return quickInputService;
}
get quickAccess() { return this.activeService.quickAccess; }
pick(picks, options = {}, token = cancellation_1.CancellationToken.None) {
return this.activeService /* TS fail */.pick(picks, options, token);
}
createQuickPick() {
return this.activeService.createQuickPick();
}
};
StandaloneQuickInputServiceImpl = __decorate([
__param(0, instantiation_1.IInstantiationService),
__param(1, codeEditorService_1.ICodeEditorService)
], StandaloneQuickInputServiceImpl);
exports.StandaloneQuickInputServiceImpl = StandaloneQuickInputServiceImpl;
class QuickInputEditorContribution {
constructor(editor) {
this.editor = editor;
this.widget = new QuickInputEditorWidget(this.editor);
}
static get(editor) {
return editor.getContribution(QuickInputEditorContribution.ID);
}
dispose() {
this.widget.dispose();
}
}
exports.QuickInputEditorContribution = QuickInputEditorContribution;
QuickInputEditorContribution.ID = 'editor.controller.quickInput';
class QuickInputEditorWidget {
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 /* TOP_CENTER */ };
}
dispose() {
this.codeEditor.removeOverlayWidget(this);
}
}
exports.QuickInputEditorWidget = QuickInputEditorWidget;
QuickInputEditorWidget.ID = 'editor.contrib.quickInputWidget';
(0, editorExtensions_1.registerEditorContribution)(QuickInputEditorContribution.ID, QuickInputEditorContribution);
});
/*---------------------------------------------------------------------------------------------
* 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/platform/severityIcon/common/severityIcon*/], __M([0/*require*/,1/*exports*/,74/*vs/base/common/severity*/,11/*vs/platform/theme/common/themeService*/,22/*vs/platform/theme/common/colorRegistry*/,27/*vs/base/common/codicons*/]), function (require, exports, severity_1, themeService_1, colorRegistry_1, codicons_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 ' + codicons_1.Codicon.info.classNames;
case severity_1.default.Info:
return codicons_1.Codicon.info.classNames;
case severity_1.default.Warning:
return codicons_1.Codicon.warning.classNames;
case severity_1.default.Error:
return codicons_1.Codicon.error.classNames;
default:
return '';
}
}
SeverityIcon.className = className;
})(SeverityIcon = exports.SeverityIcon || (exports.SeverityIcon = {}));
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const errorIconForeground = theme.getColor(colorRegistry_1.problemsErrorIconForeground);
if (errorIconForeground) {
const errorCodiconSelector = codicons_1.Codicon.error.cssSelector;
collector.addRule(`
.monaco-editor .zone-widget ${errorCodiconSelector},
.markers-panel .marker-icon${errorCodiconSelector},
.text-search-provider-messages .providerMessage ${errorCodiconSelector},
.extensions-viewlet > .extensions ${errorCodiconSelector} {
color: ${errorIconForeground};
}
`);
}
const warningIconForeground = theme.getColor(colorRegistry_1.problemsWarningIconForeground);
if (warningIconForeground) {
const warningCodiconSelector = codicons_1.Codicon.warning.cssSelector;
collector.addRule(`
.monaco-editor .zone-widget ${warningCodiconSelector},
.markers-panel .marker-icon${warningCodiconSelector},
.extensions-viewlet > .extensions ${warningCodiconSelector},
.extension-editor ${warningCodiconSelector},
.text-search-provider-messages .providerMessage ${warningCodiconSelector},
.preferences-editor ${warningCodiconSelector} {
color: ${warningIconForeground};
}
`);
}
const infoIconForeground = theme.getColor(colorRegistry_1.problemsInfoIconForeground);
if (infoIconForeground) {
const infoCodiconSelector = codicons_1.Codicon.info.cssSelector;
collector.addRule(`
.monaco-editor .zone-widget ${infoCodiconSelector},
.markers-panel .marker-icon${infoCodiconSelector},
.extensions-viewlet > .extensions ${infoCodiconSelector},
.text-search-provider-messages .providerMessage ${infoCodiconSelector},
.extension-editor ${infoCodiconSelector} {
color: ${infoIconForeground};
}
`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/gotoError/gotoErrorWidget*/], __M([0/*require*/,1/*exports*/,490/*vs/nls!vs/editor/contrib/gotoError/gotoErrorWidget*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,87/*vs/platform/markers/common/markers*/,3/*vs/editor/common/core/range*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,29/*vs/base/common/color*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,163/*vs/base/common/labels*/,19/*vs/base/common/arrays*/,6/*vs/base/common/event*/,124/*vs/editor/contrib/peekView/peekView*/,43/*vs/base/common/resources*/,669/*vs/platform/severityIcon/common/severityIcon*/,58/*vs/platform/opener/common/opener*/,33/*vs/platform/actions/common/actions*/,16/*vs/platform/contextkey/common/contextkey*/,192/*vs/platform/actions/browser/menuEntryActionViewItem*/,9/*vs/platform/instantiation/common/instantiation*/,8/*vs/base/common/strings*/,121/*vs/platform/label/common/label*/,351/*vs/css!vs/editor/contrib/gotoError/media/gotoErrorWidget*/]), function (require, exports, nls, dom, lifecycle_1, markers_1, range_1, colorRegistry_1, themeService_1, color_1, scrollableElement_1, labels_1, arrays_1, event_1, peekView_1, resources_1, severityIcon_1, opener_1, actions_1, contextkey_1, menuEntryActionViewItem_1, instantiation_1, strings_1, label_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.editorMarkerNavigationBackground = exports.editorMarkerNavigationInfo = exports.editorMarkerNavigationWarning = exports.editorMarkerNavigationError = 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 /* Auto */,
vertical: 1 /* Auto */,
useShadows: false,
horizontalScrollbarSize: 3,
verticalScrollbarSize: 3
});
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 === null || source === void 0 ? void 0 : 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(57 /* lineHeight */) * 0.66)}px`;
this._lines += 1;
for (const related of relatedInformation) {
let container = document.createElement('div');
let relatedResource = document.createElement('a');
relatedResource.classList.add('filename');
relatedResource.innerText = `${(0, labels_1.getBaseLabel)(related.resource)}(${related.startLineNumber}, ${related.startColumn}): `;
relatedResource.title = this._labelService.getUriLabel(related.resource);
this._relatedDiagnostics.set(relatedResource, related);
let 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(41 /* 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(0, null);
break;
case markers_1.MarkerSeverity.Warning:
severityLabel = nls.localize(1, null);
break;
case markers_1.MarkerSeverity.Info:
severityLabel = nls.localize(2, null);
break;
case markers_1.MarkerSeverity.Hint:
severityLabel = nls.localize(3, null);
break;
}
let ariaLabel = nls.localize(4, null, 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 {
constructor(editor, _themeService, _openerService, _menuService, instantiationService, _contextKeyService, _labelService) {
super(editor, { showArrow: true, showFrame: true, isAccessible: true }, 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(exports.editorMarkerNavigationBackground);
let colorId = exports.editorMarkerNavigationError;
if (this._severity === markers_1.MarkerSeverity.Warning) {
colorId = exports.editorMarkerNavigationWarning;
}
else if (this._severity === markers_1.MarkerSeverity.Info) {
colorId = exports.editorMarkerNavigationInfo;
}
const frameColor = theme.getColor(colorId);
this.style({
arrowColor: frameColor,
frameColor: frameColor,
headerBackgroundColor: this._backgroundColor,
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.onBeforeRun(e => this.editor.focus()));
const actions = [];
const menu = this._menuService.createMenu(MarkerNavigationWidget.TitleMenu, this._contextKeyService);
(0, menuEntryActionViewItem_1.createAndFillInActionBarActions)(menu, undefined, actions);
this._actionbarWidget.push(actions, { label: false, icon: true, index: 0 });
menu.dispose();
}
_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
let range = range_1.Range.lift(marker);
const editorPosition = this.editor.getPosition();
let 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(5, null, markerIdx, markerCount)
: nls.localize(6, null, 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 /* 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();
}
};
MarkerNavigationWidget.TitleMenu = new actions_1.MenuId('gotoErrorTitleMenu');
MarkerNavigationWidget = __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);
exports.MarkerNavigationWidget = MarkerNavigationWidget;
// theming
let errorDefault = (0, colorRegistry_1.oneOf)(colorRegistry_1.editorErrorForeground, colorRegistry_1.editorErrorBorder);
let warningDefault = (0, colorRegistry_1.oneOf)(colorRegistry_1.editorWarningForeground, colorRegistry_1.editorWarningBorder);
let infoDefault = (0, colorRegistry_1.oneOf)(colorRegistry_1.editorInfoForeground, colorRegistry_1.editorInfoBorder);
exports.editorMarkerNavigationError = (0, colorRegistry_1.registerColor)('editorMarkerNavigationError.background', { dark: errorDefault, light: errorDefault, hc: errorDefault }, nls.localize(7, null));
exports.editorMarkerNavigationWarning = (0, colorRegistry_1.registerColor)('editorMarkerNavigationWarning.background', { dark: warningDefault, light: warningDefault, hc: warningDefault }, nls.localize(8, null));
exports.editorMarkerNavigationInfo = (0, colorRegistry_1.registerColor)('editorMarkerNavigationInfo.background', { dark: infoDefault, light: infoDefault, hc: infoDefault }, nls.localize(9, null));
exports.editorMarkerNavigationBackground = (0, colorRegistry_1.registerColor)('editorMarkerNavigation.background', { dark: '#2D2D30', light: color_1.Color.white, hc: '#0C141F' }, nls.localize(10, null));
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const linkFg = theme.getColor(colorRegistry_1.textLinkForeground);
if (linkFg) {
collector.addRule(`.monaco-editor .marker-widget a.code-link span { color: ${linkFg}; }`);
}
const activeLinkFg = theme.getColor(colorRegistry_1.textLinkActiveForeground);
if (activeLinkFg) {
collector.addRule(`.monaco-editor .marker-widget a.code-link span:hover { color: ${activeLinkFg}; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/platform/theme/common/iconRegistry*/], __M([0/*require*/,1/*exports*/,32/*vs/platform/registry/common/platform*/,11/*vs/platform/theme/common/themeService*/,6/*vs/base/common/event*/,542/*vs/nls!vs/platform/theme/common/iconRegistry*/,189/*vs/platform/jsonschemas/common/jsonContributionRegistry*/,15/*vs/base/common/async*/,27/*vs/base/common/codicons*/]), function (require, exports, platform, themeService_1, event_1, nls_1, jsonContributionRegistry_1, async_1, Codicons) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.widgetClose = exports.iconsSchemaId = exports.getIconRegistry = exports.registerIcon = exports.Extensions = void 0;
// ------ API types
// icon registry
exports.Extensions = {
IconContribution: 'base.contributions.icons'
};
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)(0, null) },
fontCharacter: { type: 'string', description: (0, nls_1.localize)(1, null) }
},
additionalProperties: false,
defaultSnippets: [{ body: { fontCharacter: '\\\\e030' } }]
}
},
type: 'object',
properties: {}
};
this.iconReferenceSchema = { type: 'string', pattern: `^${Codicons.CSSIcon.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;
}
let iconContribution = { id, description, defaults, deprecationMessage };
this.iconsById[id] = iconContribution;
let 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;
}
getIconFont(id) {
return this.iconFontsById[id];
}
toString() {
const sorter = (i1, i2) => {
return i1.id.localeCompare(i2.id);
};
const classNames = (i) => {
while (themeService_1.ThemeIcon.isThemeIcon(i.defaults)) {
i = this.iconsById[i.defaults.id];
}
return `codicon codicon-${i ? i.id : ''}`;
};
let 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}|${themeService_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 => !themeService_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);
}
exports.registerIcon = registerIcon;
function getIconRegistry() {
return iconRegistry;
}
exports.getIconRegistry = getIconRegistry;
function initialize() {
for (const icon of Codicons.iconRegistry.all) {
iconRegistry.registerIcon(icon.id, icon.definition, icon.description);
}
Codicons.iconRegistry.onDidRegister(icon => iconRegistry.registerIcon(icon.id, icon.definition, icon.description));
}
initialize();
exports.iconsSchemaId = 'vscode://schemas/icons';
let 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.Codicon.close, (0, nls_1.localize)(2, 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[671/*vs/editor/browser/widget/diffReview*/], __M([0/*require*/,1/*exports*/,460/*vs/nls!vs/editor/browser/widget/diffReview*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,84/*vs/base/browser/ui/actionbar/actionbar*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,50/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,65/*vs/editor/browser/config/configuration*/,14/*vs/editor/browser/editorExtensions*/,28/*vs/editor/browser/services/codeEditorService*/,35/*vs/editor/common/config/editorOptions*/,85/*vs/editor/common/core/lineTokens*/,13/*vs/editor/common/core/position*/,48/*vs/editor/common/view/editorColorRegistry*/,114/*vs/editor/common/viewLayout/viewLineRenderer*/,62/*vs/editor/common/viewModel/viewModel*/,16/*vs/platform/contextkey/common/contextkey*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,27/*vs/base/common/codicons*/,79/*vs/platform/theme/common/iconRegistry*/,341/*vs/css!vs/editor/browser/widget/media/diffReview*/]), function (require, exports, nls, dom, fastDomNode_1, actionbar_1, scrollableElement_1, actions_1, lifecycle_1, configuration_1, editorExtensions_1, codeEditorService_1, editorOptions_1, lineTokens_1, position_1, editorColorRegistry_1, viewLineRenderer_1, viewModel_1, contextkey_1, colorRegistry_1, themeService_1, codicons_1, iconRegistry_1) {
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiffReview = void 0;
const DIFF_LINES_PADDING = 3;
class DiffEntry {
constructor(originalLineStart, originalLineEnd, modifiedLineStart, modifiedLineEnd) {
this.originalLineStart = originalLineStart;
this.originalLineEnd = originalLineEnd;
this.modifiedLineStart = modifiedLineStart;
this.modifiedLineEnd = modifiedLineEnd;
}
getType() {
if (this.originalLineStart === 0) {
return 1 /* Insert */;
}
if (this.modifiedLineStart === 0) {
return 2 /* Delete */;
}
return 0 /* Equal */;
}
}
class Diff {
constructor(entries) {
this.entries = entries;
}
}
const diffReviewInsertIcon = (0, iconRegistry_1.registerIcon)('diff-review-insert', codicons_1.Codicon.add, nls.localize(0, null));
const diffReviewRemoveIcon = (0, iconRegistry_1.registerIcon)('diff-review-remove', codicons_1.Codicon.remove, nls.localize(1, null));
const diffReviewCloseIcon = (0, iconRegistry_1.registerIcon)('diff-review-close', codicons_1.Codicon.close, nls.localize(2, null));
class DiffReview extends lifecycle_1.Disposable {
constructor(diffEditor) {
super();
this._width = 0;
this._diffEditor = diffEditor;
this._isVisible = false;
this.shadow = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
this.shadow.setClassName('diff-review-shadow');
this.actionBarContainer = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
this.actionBarContainer.setClassName('diff-review-actions');
this._actionBar = this._register(new actionbar_1.ActionBar(this.actionBarContainer.domNode));
this._actionBar.push(new actions_1.Action('diffreview.close', nls.localize(3, null), 'close-diff-review ' + themeService_1.ThemeIcon.asClassName(diffReviewCloseIcon), true, () => __awaiter(this, void 0, void 0, function* () { return this.hide(); })), { label: false, icon: true });
this.domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
this.domNode.setClassName('diff-review monaco-editor-background');
this._content = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
this._content.setClassName('diff-review-content');
this._content.setAttribute('role', 'code');
this.scrollbar = this._register(new scrollableElement_1.DomScrollableElement(this._content.domNode, {}));
this.domNode.domNode.appendChild(this.scrollbar.getDomNode());
this._register(diffEditor.onDidUpdateDiff(() => {
if (!this._isVisible) {
return;
}
this._diffs = this._compute();
this._render();
}));
this._register(diffEditor.getModifiedEditor().onDidChangeCursorPosition(() => {
if (!this._isVisible) {
return;
}
this._render();
}));
this._register(dom.addStandardDisposableListener(this.domNode.domNode, 'click', (e) => {
e.preventDefault();
let row = dom.findParentWithClass(e.target, 'diff-review-row');
if (row) {
this._goToRow(row);
}
}));
this._register(dom.addStandardDisposableListener(this.domNode.domNode, 'keydown', (e) => {
if (e.equals(18 /* DownArrow */)
|| e.equals(2048 /* CtrlCmd */ | 18 /* DownArrow */)
|| e.equals(512 /* Alt */ | 18 /* DownArrow */)) {
e.preventDefault();
this._goToRow(this._getNextRow());
}
if (e.equals(16 /* UpArrow */)
|| e.equals(2048 /* CtrlCmd */ | 16 /* UpArrow */)
|| e.equals(512 /* Alt */ | 16 /* UpArrow */)) {
e.preventDefault();
this._goToRow(this._getPrevRow());
}
if (e.equals(9 /* Escape */)
|| e.equals(2048 /* CtrlCmd */ | 9 /* Escape */)
|| e.equals(512 /* Alt */ | 9 /* Escape */)
|| e.equals(1024 /* Shift */ | 9 /* Escape */)) {
e.preventDefault();
this.hide();
}
if (e.equals(10 /* Space */)
|| e.equals(3 /* Enter */)) {
e.preventDefault();
this.accept();
}
}));
this._diffs = [];
this._currentDiff = null;
}
prev() {
let index = 0;
if (!this._isVisible) {
this._diffs = this._compute();
}
if (this._isVisible) {
let currentIndex = -1;
for (let i = 0, len = this._diffs.length; i < len; i++) {
if (this._diffs[i] === this._currentDiff) {
currentIndex = i;
break;
}
}
index = (this._diffs.length + currentIndex - 1);
}
else {
index = this._findDiffIndex(this._diffEditor.getPosition());
}
if (this._diffs.length === 0) {
// Nothing to do
return;
}
index = index % this._diffs.length;
const entries = this._diffs[index].entries;
this._diffEditor.setPosition(new position_1.Position(entries[0].modifiedLineStart, 1));
this._diffEditor.setSelection({ startColumn: 1, startLineNumber: entries[0].modifiedLineStart, endColumn: 1073741824 /* MAX_SAFE_SMALL_INTEGER */, endLineNumber: entries[entries.length - 1].modifiedLineEnd });
this._isVisible = true;
this._diffEditor.doLayout();
this._render();
this._goToRow(this._getNextRow());
}
next() {
let index = 0;
if (!this._isVisible) {
this._diffs = this._compute();
}
if (this._isVisible) {
let currentIndex = -1;
for (let i = 0, len = this._diffs.length; i < len; i++) {
if (this._diffs[i] === this._currentDiff) {
currentIndex = i;
break;
}
}
index = (currentIndex + 1);
}
else {
index = this._findDiffIndex(this._diffEditor.getPosition());
}
if (this._diffs.length === 0) {
// Nothing to do
return;
}
index = index % this._diffs.length;
const entries = this._diffs[index].entries;
this._diffEditor.setPosition(new position_1.Position(entries[0].modifiedLineStart, 1));
this._diffEditor.setSelection({ startColumn: 1, startLineNumber: entries[0].modifiedLineStart, endColumn: 1073741824 /* MAX_SAFE_SMALL_INTEGER */, endLineNumber: entries[entries.length - 1].modifiedLineEnd });
this._isVisible = true;
this._diffEditor.doLayout();
this._render();
this._goToRow(this._getNextRow());
}
accept() {
let jumpToLineNumber = -1;
let current = this._getCurrentFocusedRow();
if (current) {
let lineNumber = parseInt(current.getAttribute('data-line'), 10);
if (!isNaN(lineNumber)) {
jumpToLineNumber = lineNumber;
}
}
this.hide();
if (jumpToLineNumber !== -1) {
this._diffEditor.setPosition(new position_1.Position(jumpToLineNumber, 1));
this._diffEditor.revealPosition(new position_1.Position(jumpToLineNumber, 1), 1 /* Immediate */);
}
}
hide() {
this._isVisible = false;
this._diffEditor.updateOptions({ readOnly: false });
this._diffEditor.focus();
this._diffEditor.doLayout();
this._render();
}
_getPrevRow() {
let current = this._getCurrentFocusedRow();
if (!current) {
return this._getFirstRow();
}
if (current.previousElementSibling) {
return current.previousElementSibling;
}
return current;
}
_getNextRow() {
let current = this._getCurrentFocusedRow();
if (!current) {
return this._getFirstRow();
}
if (current.nextElementSibling) {
return current.nextElementSibling;
}
return current;
}
_getFirstRow() {
return this.domNode.domNode.querySelector('.diff-review-row');
}
_getCurrentFocusedRow() {
let result = document.activeElement;
if (result && /diff-review-row/.test(result.className)) {
return result;
}
return null;
}
_goToRow(row) {
let prev = this._getCurrentFocusedRow();
row.tabIndex = 0;
row.focus();
if (prev && prev !== row) {
prev.tabIndex = -1;
}
this.scrollbar.scanDomNode();
}
isVisible() {
return this._isVisible;
}
layout(top, width, height) {
this._width = width;
this.shadow.setTop(top - 6);
this.shadow.setWidth(width);
this.shadow.setHeight(this._isVisible ? 6 : 0);
this.domNode.setTop(top);
this.domNode.setWidth(width);
this.domNode.setHeight(height);
this._content.setHeight(height);
this._content.setWidth(width);
if (this._isVisible) {
this.actionBarContainer.setAttribute('aria-hidden', 'false');
this.actionBarContainer.setDisplay('block');
}
else {
this.actionBarContainer.setAttribute('aria-hidden', 'true');
this.actionBarContainer.setDisplay('none');
}
}
_compute() {
const lineChanges = this._diffEditor.getLineChanges();
if (!lineChanges || lineChanges.length === 0) {
return [];
}
const originalModel = this._diffEditor.getOriginalEditor().getModel();
const modifiedModel = this._diffEditor.getModifiedEditor().getModel();
if (!originalModel || !modifiedModel) {
return [];
}
return DiffReview._mergeAdjacent(lineChanges, originalModel.getLineCount(), modifiedModel.getLineCount());
}
static _mergeAdjacent(lineChanges, originalLineCount, modifiedLineCount) {
if (!lineChanges || lineChanges.length === 0) {
return [];
}
let diffs = [], diffsLength = 0;
for (let i = 0, len = lineChanges.length; i < len; i++) {
const lineChange = lineChanges[i];
const originalStart = lineChange.originalStartLineNumber;
const originalEnd = lineChange.originalEndLineNumber;
const modifiedStart = lineChange.modifiedStartLineNumber;
const modifiedEnd = lineChange.modifiedEndLineNumber;
let r = [], rLength = 0;
// Emit before anchors
{
const originalEqualAbove = (originalEnd === 0 ? originalStart : originalStart - 1);
const modifiedEqualAbove = (modifiedEnd === 0 ? modifiedStart : modifiedStart - 1);
// Make sure we don't step into the previous diff
let minOriginal = 1;
let minModified = 1;
if (i > 0) {
const prevLineChange = lineChanges[i - 1];
if (prevLineChange.originalEndLineNumber === 0) {
minOriginal = prevLineChange.originalStartLineNumber + 1;
}
else {
minOriginal = prevLineChange.originalEndLineNumber + 1;
}
if (prevLineChange.modifiedEndLineNumber === 0) {
minModified = prevLineChange.modifiedStartLineNumber + 1;
}
else {
minModified = prevLineChange.modifiedEndLineNumber + 1;
}
}
let fromOriginal = originalEqualAbove - DIFF_LINES_PADDING + 1;
let fromModified = modifiedEqualAbove - DIFF_LINES_PADDING + 1;
if (fromOriginal < minOriginal) {
const delta = minOriginal - fromOriginal;
fromOriginal = fromOriginal + delta;
fromModified = fromModified + delta;
}
if (fromModified < minModified) {
const delta = minModified - fromModified;
fromOriginal = fromOriginal + delta;
fromModified = fromModified + delta;
}
r[rLength++] = new DiffEntry(fromOriginal, originalEqualAbove, fromModified, modifiedEqualAbove);
}
// Emit deleted lines
{
if (originalEnd !== 0) {
r[rLength++] = new DiffEntry(originalStart, originalEnd, 0, 0);
}
}
// Emit inserted lines
{
if (modifiedEnd !== 0) {
r[rLength++] = new DiffEntry(0, 0, modifiedStart, modifiedEnd);
}
}
// Emit after anchors
{
const originalEqualBelow = (originalEnd === 0 ? originalStart + 1 : originalEnd + 1);
const modifiedEqualBelow = (modifiedEnd === 0 ? modifiedStart + 1 : modifiedEnd + 1);
// Make sure we don't step into the next diff
let maxOriginal = originalLineCount;
let maxModified = modifiedLineCount;
if (i + 1 < len) {
const nextLineChange = lineChanges[i + 1];
if (nextLineChange.originalEndLineNumber === 0) {
maxOriginal = nextLineChange.originalStartLineNumber;
}
else {
maxOriginal = nextLineChange.originalStartLineNumber - 1;
}
if (nextLineChange.modifiedEndLineNumber === 0) {
maxModified = nextLineChange.modifiedStartLineNumber;
}
else {
maxModified = nextLineChange.modifiedStartLineNumber - 1;
}
}
let toOriginal = originalEqualBelow + DIFF_LINES_PADDING - 1;
let toModified = modifiedEqualBelow + DIFF_LINES_PADDING - 1;
if (toOriginal > maxOriginal) {
const delta = maxOriginal - toOriginal;
toOriginal = toOriginal + delta;
toModified = toModified + delta;
}
if (toModified > maxModified) {
const delta = maxModified - toModified;
toOriginal = toOriginal + delta;
toModified = toModified + delta;
}
r[rLength++] = new DiffEntry(originalEqualBelow, toOriginal, modifiedEqualBelow, toModified);
}
diffs[diffsLength++] = new Diff(r);
}
// Merge adjacent diffs
let curr = diffs[0].entries;
let r = [], rLength = 0;
for (let i = 1, len = diffs.length; i < len; i++) {
const thisDiff = diffs[i].entries;
const currLast = curr[curr.length - 1];
const thisFirst = thisDiff[0];
if (currLast.getType() === 0 /* Equal */
&& thisFirst.getType() === 0 /* Equal */
&& thisFirst.originalLineStart <= currLast.originalLineEnd) {
// We are dealing with equal lines that overlap
curr[curr.length - 1] = new DiffEntry(currLast.originalLineStart, thisFirst.originalLineEnd, currLast.modifiedLineStart, thisFirst.modifiedLineEnd);
curr = curr.concat(thisDiff.slice(1));
continue;
}
r[rLength++] = new Diff(curr);
curr = thisDiff;
}
r[rLength++] = new Diff(curr);
return r;
}
_findDiffIndex(pos) {
const lineNumber = pos.lineNumber;
for (let i = 0, len = this._diffs.length; i < len; i++) {
const diff = this._diffs[i].entries;
const lastModifiedLine = diff[diff.length - 1].modifiedLineEnd;
if (lineNumber <= lastModifiedLine) {
return i;
}
}
return 0;
}
_render() {
const originalOptions = this._diffEditor.getOriginalEditor().getOptions();
const modifiedOptions = this._diffEditor.getModifiedEditor().getOptions();
const originalModel = this._diffEditor.getOriginalEditor().getModel();
const modifiedModel = this._diffEditor.getModifiedEditor().getModel();
const originalModelOpts = originalModel.getOptions();
const modifiedModelOpts = modifiedModel.getOptions();
if (!this._isVisible || !originalModel || !modifiedModel) {
dom.clearNode(this._content.domNode);
this._currentDiff = null;
this.scrollbar.scanDomNode();
return;
}
this._diffEditor.updateOptions({ readOnly: true });
const diffIndex = this._findDiffIndex(this._diffEditor.getPosition());
if (this._diffs[diffIndex] === this._currentDiff) {
return;
}
this._currentDiff = this._diffs[diffIndex];
const diffs = this._diffs[diffIndex].entries;
let container = document.createElement('div');
container.className = 'diff-review-table';
container.setAttribute('role', 'list');
container.setAttribute('aria-label', 'Difference review. Use "Stage | Unstage | Revert Selected Ranges" commands');
configuration_1.Configuration.applyFontInfoSlow(container, modifiedOptions.get(41 /* fontInfo */));
let minOriginalLine = 0;
let maxOriginalLine = 0;
let minModifiedLine = 0;
let maxModifiedLine = 0;
for (let i = 0, len = diffs.length; i < len; i++) {
const diffEntry = diffs[i];
const originalLineStart = diffEntry.originalLineStart;
const originalLineEnd = diffEntry.originalLineEnd;
const modifiedLineStart = diffEntry.modifiedLineStart;
const modifiedLineEnd = diffEntry.modifiedLineEnd;
if (originalLineStart !== 0 && ((minOriginalLine === 0 || originalLineStart < minOriginalLine))) {
minOriginalLine = originalLineStart;
}
if (originalLineEnd !== 0 && ((maxOriginalLine === 0 || originalLineEnd > maxOriginalLine))) {
maxOriginalLine = originalLineEnd;
}
if (modifiedLineStart !== 0 && ((minModifiedLine === 0 || modifiedLineStart < minModifiedLine))) {
minModifiedLine = modifiedLineStart;
}
if (modifiedLineEnd !== 0 && ((maxModifiedLine === 0 || modifiedLineEnd > maxModifiedLine))) {
maxModifiedLine = modifiedLineEnd;
}
}
let header = document.createElement('div');
header.className = 'diff-review-row';
let cell = document.createElement('div');
cell.className = 'diff-review-cell diff-review-summary';
const originalChangedLinesCnt = maxOriginalLine - minOriginalLine + 1;
const modifiedChangedLinesCnt = maxModifiedLine - minModifiedLine + 1;
cell.appendChild(document.createTextNode(`${diffIndex + 1}/${this._diffs.length}: @@ -${minOriginalLine},${originalChangedLinesCnt} +${minModifiedLine},${modifiedChangedLinesCnt} @@`));
header.setAttribute('data-line', String(minModifiedLine));
const getAriaLines = (lines) => {
if (lines === 0) {
return nls.localize(4, null);
}
else if (lines === 1) {
return nls.localize(5, null);
}
else {
return nls.localize(6, null, lines);
}
};
const originalChangedLinesCntAria = getAriaLines(originalChangedLinesCnt);
const modifiedChangedLinesCntAria = getAriaLines(modifiedChangedLinesCnt);
header.setAttribute('aria-label', nls.localize(7, null, (diffIndex + 1), this._diffs.length, minOriginalLine, originalChangedLinesCntAria, minModifiedLine, modifiedChangedLinesCntAria));
header.appendChild(cell);
// @@ -504,7 +517,7 @@
header.setAttribute('role', 'listitem');
container.appendChild(header);
const lineHeight = modifiedOptions.get(57 /* lineHeight */);
let modLine = minModifiedLine;
for (let i = 0, len = diffs.length; i < len; i++) {
const diffEntry = diffs[i];
DiffReview._renderSection(container, diffEntry, modLine, lineHeight, this._width, originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts);
if (diffEntry.modifiedLineStart !== 0) {
modLine = diffEntry.modifiedLineEnd;
}
}
dom.clearNode(this._content.domNode);
this._content.domNode.appendChild(container);
this.scrollbar.scanDomNode();
}
static _renderSection(dest, diffEntry, modLine, lineHeight, width, originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts) {
const type = diffEntry.getType();
let rowClassName = 'diff-review-row';
let lineNumbersExtraClassName = '';
const spacerClassName = 'diff-review-spacer';
let spacerIcon = null;
switch (type) {
case 1 /* Insert */:
rowClassName = 'diff-review-row line-insert';
lineNumbersExtraClassName = ' char-insert';
spacerIcon = diffReviewInsertIcon;
break;
case 2 /* Delete */:
rowClassName = 'diff-review-row line-delete';
lineNumbersExtraClassName = ' char-delete';
spacerIcon = diffReviewRemoveIcon;
break;
}
const originalLineStart = diffEntry.originalLineStart;
const originalLineEnd = diffEntry.originalLineEnd;
const modifiedLineStart = diffEntry.modifiedLineStart;
const modifiedLineEnd = diffEntry.modifiedLineEnd;
const cnt = Math.max(modifiedLineEnd - modifiedLineStart, originalLineEnd - originalLineStart);
const originalLayoutInfo = originalOptions.get(129 /* layoutInfo */);
const originalLineNumbersWidth = originalLayoutInfo.glyphMarginWidth + originalLayoutInfo.lineNumbersWidth;
const modifiedLayoutInfo = modifiedOptions.get(129 /* layoutInfo */);
const modifiedLineNumbersWidth = 10 + modifiedLayoutInfo.glyphMarginWidth + modifiedLayoutInfo.lineNumbersWidth;
for (let i = 0; i <= cnt; i++) {
const originalLine = (originalLineStart === 0 ? 0 : originalLineStart + i);
const modifiedLine = (modifiedLineStart === 0 ? 0 : modifiedLineStart + i);
const row = document.createElement('div');
row.style.minWidth = width + 'px';
row.className = rowClassName;
row.setAttribute('role', 'listitem');
if (modifiedLine !== 0) {
modLine = modifiedLine;
}
row.setAttribute('data-line', String(modLine));
let 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 (originalLine !== 0) {
originalLineNumber.appendChild(document.createTextNode(String(originalLine)));
}
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 (modifiedLine !== 0) {
modifiedLineNumber.appendChild(document.createTextNode(String(modifiedLine)));
}
else {
modifiedLineNumber.innerText = '\u00a0';
}
cell.appendChild(modifiedLineNumber);
const spacer = document.createElement('span');
spacer.className = spacerClassName;
if (spacerIcon) {
const spacerCodicon = document.createElement('span');
spacerCodicon.className = themeService_1.ThemeIcon.asClassName(spacerIcon);
spacerCodicon.innerText = '\u00a0\u00a0';
spacer.appendChild(spacerCodicon);
}
else {
spacer.innerText = '\u00a0\u00a0';
}
cell.appendChild(spacer);
let lineContent;
if (modifiedLine !== 0) {
let html = this._renderLine(modifiedModel, modifiedOptions, modifiedModelOpts.tabSize, modifiedLine);
if (DiffReview._ttPolicy) {
html = DiffReview._ttPolicy.createHTML(html);
}
cell.insertAdjacentHTML('beforeend', html);
lineContent = modifiedModel.getLineContent(modifiedLine);
}
else {
let html = this._renderLine(originalModel, originalOptions, originalModelOpts.tabSize, originalLine);
if (DiffReview._ttPolicy) {
html = DiffReview._ttPolicy.createHTML(html);
}
cell.insertAdjacentHTML('beforeend', html);
lineContent = originalModel.getLineContent(originalLine);
}
if (lineContent.length === 0) {
lineContent = nls.localize(8, null);
}
let ariaLabel = '';
switch (type) {
case 0 /* Equal */:
if (originalLine === modifiedLine) {
ariaLabel = nls.localize(9, null, lineContent, originalLine);
}
else {
ariaLabel = nls.localize(10, null, lineContent, originalLine, modifiedLine);
}
break;
case 1 /* Insert */:
ariaLabel = nls.localize(11, null, lineContent, modifiedLine);
break;
case 2 /* Delete */:
ariaLabel = nls.localize(12, null, lineContent, originalLine);
break;
}
row.setAttribute('aria-label', ariaLabel);
dest.appendChild(row);
}
}
static _renderLine(model, options, tabSize, lineNumber) {
const lineContent = model.getLineContent(lineNumber);
const fontInfo = options.get(41 /* fontInfo */);
const lineTokens = lineTokens_1.LineTokens.createEmpty(lineContent);
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(27 /* disableMonospaceOptimizations */)), fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII, containsRTL, 0, lineTokens, [], tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, options.get(104 /* stopRenderingLineAfter */), options.get(87 /* renderWhitespace */), options.get(81 /* renderControlCharacters */), options.get(42 /* fontLigatures */) !== editorOptions_1.EditorFontLigatures.OFF, null));
return r.html;
}
}
exports.DiffReview = DiffReview;
DiffReview._ttPolicy = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('diffReview', { createHTML: value => value });
// theming
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const lineNumbers = theme.getColor(editorColorRegistry_1.editorLineNumbers);
if (lineNumbers) {
collector.addRule(`.monaco-diff-editor .diff-review-line-number { color: ${lineNumbers}; }`);
}
const shadow = theme.getColor(colorRegistry_1.scrollbarShadow);
if (shadow) {
collector.addRule(`.monaco-diff-editor .diff-review-shadow { box-shadow: ${shadow} 0 -6px 6px -6px inset; }`);
}
});
class DiffReviewNext extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.diffReview.next',
label: nls.localize(13, null),
alias: 'Go to Next Difference',
precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
kbOpts: {
kbExpr: null,
primary: 65 /* F7 */,
weight: 100 /* EditorContrib */
}
});
}
run(accessor, editor) {
const diffEditor = findFocusedDiffEditor(accessor);
if (diffEditor) {
diffEditor.diffReviewNext();
}
}
}
class DiffReviewPrev extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.diffReview.prev',
label: nls.localize(14, null),
alias: 'Go to Previous Difference',
precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
kbOpts: {
kbExpr: null,
primary: 1024 /* Shift */ | 65 /* F7 */,
weight: 100 /* EditorContrib */
}
});
}
run(accessor, editor) {
const diffEditor = findFocusedDiffEditor(accessor);
if (diffEditor) {
diffEditor.diffReviewPrev();
}
}
}
function findFocusedDiffEditor(accessor) {
const codeEditorService = accessor.get(codeEditorService_1.ICodeEditorService);
const diffEditors = codeEditorService.listDiffEditors();
const activeCodeEditor = codeEditorService.getActiveCodeEditor();
if (!activeCodeEditor) {
return null;
}
for (let i = 0, len = diffEditors.length; i < len; i++) {
const diffEditor = diffEditors[i];
if (diffEditor.getModifiedEditor().getId() === activeCodeEditor.getId() || diffEditor.getOriginalEditor().getId() === activeCodeEditor.getId()) {
return diffEditor;
}
}
return null;
}
(0, editorExtensions_1.registerEditorAction)(DiffReviewNext);
(0, editorExtensions_1.registerEditorAction)(DiffReviewPrev);
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[271/*vs/editor/browser/widget/diffEditorWidget*/], __M([0/*require*/,1/*exports*/,459/*vs/nls!vs/editor/browser/widget/diffEditorWidget*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,107/*vs/base/browser/ui/sash/sash*/,15/*vs/base/common/async*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,65/*vs/editor/browser/config/configuration*/,66/*vs/editor/browser/core/editorState*/,28/*vs/editor/browser/services/codeEditorService*/,149/*vs/editor/browser/widget/codeEditorWidget*/,671/*vs/editor/browser/widget/diffReview*/,35/*vs/editor/common/config/editorOptions*/,3/*vs/editor/common/core/range*/,83/*vs/editor/common/core/stringBuilder*/,110/*vs/editor/common/editorCommon*/,31/*vs/editor/common/model/textModel*/,76/*vs/editor/common/services/editorWorkerService*/,223/*vs/editor/common/view/overviewZoneManager*/,136/*vs/editor/common/viewLayout/lineDecorations*/,114/*vs/editor/common/viewLayout/viewLineRenderer*/,62/*vs/editor/common/viewModel/viewModel*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/,143/*vs/platform/instantiation/common/serviceCollection*/,34/*vs/platform/notification/common/notification*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,69/*vs/platform/contextview/browser/contextView*/,462/*vs/editor/browser/widget/inlineDiffMargin*/,86/*vs/platform/clipboard/common/clipboardService*/,14/*vs/editor/browser/editorExtensions*/,12/*vs/base/common/errors*/,59/*vs/platform/progress/common/progress*/,214/*vs/editor/browser/config/elementSizeObserver*/,27/*vs/base/common/codicons*/,131/*vs/base/browser/ui/mouseCursor/mouseCursor*/,79/*vs/platform/theme/common/iconRegistry*/,340/*vs/css!vs/editor/browser/widget/media/diffEditor*/]), function (require, exports, nls, dom, fastDomNode_1, sash_1, async_1, event_1, lifecycle_1, configuration_1, editorState_1, codeEditorService_1, codeEditorWidget_1, diffReview_1, editorOptions_1, range_1, stringBuilder_1, editorCommon, textModel_1, editorWorkerService_1, overviewZoneManager_1, lineDecorations_1, viewLineRenderer_1, viewModel_1, contextkey_1, instantiation_1, serviceCollection_1, notification_1, colorRegistry_1, themeService_1, contextView_1, inlineDiffMargin_1, clipboardService_1, editorExtensions_1, errors_1, progress_1, elementSizeObserver_1, codicons_1, mouseCursor_1, iconRegistry_1) {
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiffEditorWidget = void 0;
class VisualEditorState {
constructor(_contextMenuService, _clipboardService) {
this._contextMenuService = _contextMenuService;
this._clipboardService = _clipboardService;
this._zones = [];
this._inlineDiffMargins = [];
this._zonesMap = {};
this._decorations = [];
}
getForeignViewZones(allViewZones) {
return allViewZones.filter((z) => !this._zonesMap[String(z.id)]);
}
clean(editor) {
// (1) View zones
if (this._zones.length > 0) {
editor.changeViewZones((viewChangeAccessor) => {
for (const zoneId of this._zones) {
viewChangeAccessor.removeZone(zoneId);
}
});
}
this._zones = [];
this._zonesMap = {};
// (2) Model decorations
this._decorations = editor.deltaDecorations(this._decorations, []);
}
apply(editor, overviewRuler, newDecorations, restoreScrollState) {
const scrollState = restoreScrollState ? editorState_1.StableEditorScrollState.capture(editor) : null;
// view zones
editor.changeViewZones((viewChangeAccessor) => {
for (const zoneId of this._zones) {
viewChangeAccessor.removeZone(zoneId);
}
for (const inlineDiffMargin of this._inlineDiffMargins) {
inlineDiffMargin.dispose();
}
this._zones = [];
this._zonesMap = {};
this._inlineDiffMargins = [];
for (let i = 0, length = newDecorations.zones.length; i < length; i++) {
const viewZone = newDecorations.zones[i];
viewZone.suppressMouseDown = true;
const zoneId = viewChangeAccessor.addZone(viewZone);
this._zones.push(zoneId);
this._zonesMap[String(zoneId)] = true;
if (newDecorations.zones[i].diff && viewZone.marginDomNode) {
viewZone.suppressMouseDown = false;
this._inlineDiffMargins.push(new inlineDiffMargin_1.InlineDiffMargin(zoneId, viewZone.marginDomNode, editor, newDecorations.zones[i].diff, this._contextMenuService, this._clipboardService));
}
}
});
if (scrollState) {
scrollState.restore(editor);
}
// decorations
this._decorations = editor.deltaDecorations(this._decorations, newDecorations.decorations);
// overview ruler
if (overviewRuler) {
overviewRuler.setZones(newDecorations.overviewZones);
}
}
}
let DIFF_EDITOR_ID = 0;
const diffInsertIcon = (0, iconRegistry_1.registerIcon)('diff-insert', codicons_1.Codicon.add, nls.localize(0, null));
const diffRemoveIcon = (0, iconRegistry_1.registerIcon)('diff-remove', codicons_1.Codicon.remove, nls.localize(1, null));
const ttPolicy = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('diffEditorWidget', { createHTML: value => value });
let DiffEditorWidget = class DiffEditorWidget extends lifecycle_1.Disposable {
constructor(domElement, options, codeEditorWidgetOptions, clipboardService, editorWorkerService, contextKeyService, instantiationService, codeEditorService, themeService, notificationService, contextMenuService, _editorProgressService) {
super();
this._editorProgressService = _editorProgressService;
this._onDidDispose = this._register(new event_1.Emitter());
this.onDidDispose = this._onDidDispose.event;
this._onDidUpdateDiff = this._register(new event_1.Emitter());
this.onDidUpdateDiff = this._onDidUpdateDiff.event;
this._onDidContentSizeChange = this._register(new event_1.Emitter());
this._lastOriginalWarning = null;
this._lastModifiedWarning = null;
this._editorWorkerService = editorWorkerService;
this._codeEditorService = codeEditorService;
this._contextKeyService = this._register(contextKeyService.createScoped(domElement));
this._instantiationService = instantiationService.createChild(new serviceCollection_1.ServiceCollection([contextkey_1.IContextKeyService, this._contextKeyService]));
this._contextKeyService.createKey('isInDiffEditor', true);
this._themeService = themeService;
this._notificationService = notificationService;
this._id = (++DIFF_EDITOR_ID);
this._state = 0 /* Idle */;
this._updatingDiffProgress = null;
this._domElement = domElement;
options = options || {};
// renderSideBySide
this._renderSideBySide = true;
if (typeof options.renderSideBySide !== 'undefined') {
this._renderSideBySide = options.renderSideBySide;
}
// maxComputationTime
this._maxComputationTime = 5000;
if (typeof options.maxComputationTime !== 'undefined') {
this._maxComputationTime = options.maxComputationTime;
}
// ignoreTrimWhitespace
this._ignoreTrimWhitespace = true;
if (typeof options.ignoreTrimWhitespace !== 'undefined') {
this._ignoreTrimWhitespace = options.ignoreTrimWhitespace;
}
// renderIndicators
this._renderIndicators = true;
if (typeof options.renderIndicators !== 'undefined') {
this._renderIndicators = options.renderIndicators;
}
this._originalIsEditable = (0, editorOptions_1.boolean)(options.originalEditable, false);
this._diffCodeLens = (0, editorOptions_1.boolean)(options.diffCodeLens, false);
this._diffWordWrap = validateDiffWordWrap(options.diffWordWrap, 'inherit');
if (typeof options.isInEmbeddedEditor !== 'undefined') {
this._contextKeyService.createKey('isInEmbeddedDiffEditor', options.isInEmbeddedEditor);
}
else {
this._contextKeyService.createKey('isInEmbeddedDiffEditor', false);
}
this._renderOverviewRuler = true;
if (typeof options.renderOverviewRuler !== 'undefined') {
this._renderOverviewRuler = Boolean(options.renderOverviewRuler);
}
this._updateDecorationsRunner = this._register(new async_1.RunOnceScheduler(() => this._updateDecorations(), 0));
this._containerDomElement = document.createElement('div');
this._containerDomElement.className = DiffEditorWidget._getClassName(this._themeService.getColorTheme(), this._renderSideBySide);
this._containerDomElement.style.position = 'relative';
this._containerDomElement.style.height = '100%';
this._domElement.appendChild(this._containerDomElement);
this._overviewViewportDomElement = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
this._overviewViewportDomElement.setClassName('diffViewport');
this._overviewViewportDomElement.setPosition('absolute');
this._overviewDomElement = document.createElement('div');
this._overviewDomElement.className = 'diffOverview';
this._overviewDomElement.style.position = 'absolute';
this._overviewDomElement.appendChild(this._overviewViewportDomElement.domNode);
this._register(dom.addStandardDisposableListener(this._overviewDomElement, 'mousedown', (e) => {
this._modifiedEditor.delegateVerticalScrollbarMouseDown(e);
}));
if (this._renderOverviewRuler) {
this._containerDomElement.appendChild(this._overviewDomElement);
}
// Create left side
this._originalDomNode = document.createElement('div');
this._originalDomNode.className = 'editor original';
this._originalDomNode.style.position = 'absolute';
this._originalDomNode.style.height = '100%';
this._containerDomElement.appendChild(this._originalDomNode);
// Create right side
this._modifiedDomNode = document.createElement('div');
this._modifiedDomNode.className = 'editor modified';
this._modifiedDomNode.style.position = 'absolute';
this._modifiedDomNode.style.height = '100%';
this._containerDomElement.appendChild(this._modifiedDomNode);
this._beginUpdateDecorationsTimeout = -1;
this._currentlyChangingViewZones = false;
this._diffComputationToken = 0;
this._originalEditorState = new VisualEditorState(contextMenuService, clipboardService);
this._modifiedEditorState = new VisualEditorState(contextMenuService, clipboardService);
this._isVisible = true;
this._isHandlingScrollEvent = false;
this._elementSizeObserver = this._register(new elementSizeObserver_1.ElementSizeObserver(this._containerDomElement, options.dimension, () => this._onDidContainerSizeChanged()));
if (options.automaticLayout) {
this._elementSizeObserver.startObserving();
}
this._diffComputationResult = null;
this._originalEditor = this._createLeftHandSideEditor(options, codeEditorWidgetOptions.originalEditor || {});
this._modifiedEditor = this._createRightHandSideEditor(options, codeEditorWidgetOptions.modifiedEditor || {});
this._originalOverviewRuler = null;
this._modifiedOverviewRuler = null;
this._reviewPane = new diffReview_1.DiffReview(this);
this._containerDomElement.appendChild(this._reviewPane.domNode.domNode);
this._containerDomElement.appendChild(this._reviewPane.shadow.domNode);
this._containerDomElement.appendChild(this._reviewPane.actionBarContainer.domNode);
// enableSplitViewResizing
this._enableSplitViewResizing = true;
if (typeof options.enableSplitViewResizing !== 'undefined') {
this._enableSplitViewResizing = options.enableSplitViewResizing;
}
if (this._renderSideBySide) {
this._setStrategy(new DiffEditorWidgetSideBySide(this._createDataSource(), this._enableSplitViewResizing));
}
else {
this._setStrategy(new DiffEditorWidgetInline(this._createDataSource(), this._enableSplitViewResizing));
}
this._register(themeService.onDidColorThemeChange(t => {
if (this._strategy && this._strategy.applyColors(t)) {
this._updateDecorationsRunner.schedule();
}
this._containerDomElement.className = DiffEditorWidget._getClassName(this._themeService.getColorTheme(), this._renderSideBySide);
}));
const contributions = editorExtensions_1.EditorExtensionsRegistry.getDiffEditorContributions();
for (const desc of contributions) {
try {
this._register(instantiationService.createInstance(desc.ctor, this));
}
catch (err) {
(0, errors_1.onUnexpectedError)(err);
}
}
this._codeEditorService.addDiffEditor(this);
}
_setState(newState) {
if (this._state === newState) {
return;
}
this._state = newState;
if (this._updatingDiffProgress) {
this._updatingDiffProgress.done();
this._updatingDiffProgress = null;
}
if (this._state === 1 /* ComputingDiff */) {
this._updatingDiffProgress = this._editorProgressService.show(true, 1000);
}
}
diffReviewNext() {
this._reviewPane.next();
}
diffReviewPrev() {
this._reviewPane.prev();
}
static _getClassName(theme, renderSideBySide) {
let result = 'monaco-diff-editor monaco-editor-background ';
if (renderSideBySide) {
result += 'side-by-side ';
}
result += (0, themeService_1.getThemeTypeSelector)(theme.type);
return result;
}
_recreateOverviewRulers() {
if (!this._renderOverviewRuler) {
return;
}
if (this._originalOverviewRuler) {
this._overviewDomElement.removeChild(this._originalOverviewRuler.getDomNode());
this._originalOverviewRuler.dispose();
}
if (this._originalEditor.hasModel()) {
this._originalOverviewRuler = this._originalEditor.createOverviewRuler('original diffOverviewRuler');
this._overviewDomElement.appendChild(this._originalOverviewRuler.getDomNode());
}
if (this._modifiedOverviewRuler) {
this._overviewDomElement.removeChild(this._modifiedOverviewRuler.getDomNode());
this._modifiedOverviewRuler.dispose();
}
if (this._modifiedEditor.hasModel()) {
this._modifiedOverviewRuler = this._modifiedEditor.createOverviewRuler('modified diffOverviewRuler');
this._overviewDomElement.appendChild(this._modifiedOverviewRuler.getDomNode());
}
this._layoutOverviewRulers();
}
_createLeftHandSideEditor(options, codeEditorWidgetOptions) {
const editor = this._createInnerEditor(this._instantiationService, this._originalDomNode, this._adjustOptionsForLeftHandSide(options), codeEditorWidgetOptions);
this._register(editor.onDidScrollChange((e) => {
if (this._isHandlingScrollEvent) {
return;
}
if (!e.scrollTopChanged && !e.scrollLeftChanged && !e.scrollHeightChanged) {
return;
}
this._isHandlingScrollEvent = true;
this._modifiedEditor.setScrollPosition({
scrollLeft: e.scrollLeft,
scrollTop: e.scrollTop
});
this._isHandlingScrollEvent = false;
this._layoutOverviewViewport();
}));
this._register(editor.onDidChangeViewZones(() => {
this._onViewZonesChanged();
}));
this._register(editor.onDidChangeConfiguration((e) => {
if (!editor.getModel()) {
return;
}
if (e.hasChanged(41 /* fontInfo */)) {
this._updateDecorationsRunner.schedule();
}
if (e.hasChanged(130 /* wrappingInfo */)) {
this._updateDecorationsRunner.cancel();
this._updateDecorations();
}
}));
this._register(editor.onDidChangeModelContent(() => {
if (this._isVisible) {
this._beginUpdateDecorationsSoon();
}
}));
const isInDiffLeftEditorKey = this._contextKeyService.createKey('isInDiffLeftEditor', editor.hasWidgetFocus());
this._register(editor.onDidFocusEditorWidget(() => isInDiffLeftEditorKey.set(true)));
this._register(editor.onDidBlurEditorWidget(() => isInDiffLeftEditorKey.set(false)));
this._register(editor.onDidContentSizeChange(e => {
const width = this._originalEditor.getContentWidth() + this._modifiedEditor.getContentWidth() + DiffEditorWidget.ONE_OVERVIEW_WIDTH;
const height = Math.max(this._modifiedEditor.getContentHeight(), this._originalEditor.getContentHeight());
this._onDidContentSizeChange.fire({
contentHeight: height,
contentWidth: width,
contentHeightChanged: e.contentHeightChanged,
contentWidthChanged: e.contentWidthChanged
});
}));
return editor;
}
_createRightHandSideEditor(options, codeEditorWidgetOptions) {
const editor = this._createInnerEditor(this._instantiationService, this._modifiedDomNode, this._adjustOptionsForRightHandSide(options), codeEditorWidgetOptions);
this._register(editor.onDidScrollChange((e) => {
if (this._isHandlingScrollEvent) {
return;
}
if (!e.scrollTopChanged && !e.scrollLeftChanged && !e.scrollHeightChanged) {
return;
}
this._isHandlingScrollEvent = true;
this._originalEditor.setScrollPosition({
scrollLeft: e.scrollLeft,
scrollTop: e.scrollTop
});
this._isHandlingScrollEvent = false;
this._layoutOverviewViewport();
}));
this._register(editor.onDidChangeViewZones(() => {
this._onViewZonesChanged();
}));
this._register(editor.onDidChangeConfiguration((e) => {
if (!editor.getModel()) {
return;
}
if (e.hasChanged(41 /* fontInfo */)) {
this._updateDecorationsRunner.schedule();
}
if (e.hasChanged(130 /* wrappingInfo */)) {
this._updateDecorationsRunner.cancel();
this._updateDecorations();
}
}));
this._register(editor.onDidChangeModelContent(() => {
if (this._isVisible) {
this._beginUpdateDecorationsSoon();
}
}));
this._register(editor.onDidChangeModelOptions((e) => {
if (e.tabSize) {
this._updateDecorationsRunner.schedule();
}
}));
const isInDiffRightEditorKey = this._contextKeyService.createKey('isInDiffRightEditor', editor.hasWidgetFocus());
this._register(editor.onDidFocusEditorWidget(() => isInDiffRightEditorKey.set(true)));
this._register(editor.onDidBlurEditorWidget(() => isInDiffRightEditorKey.set(false)));
this._register(editor.onDidContentSizeChange(e => {
const width = this._originalEditor.getContentWidth() + this._modifiedEditor.getContentWidth() + DiffEditorWidget.ONE_OVERVIEW_WIDTH;
const height = Math.max(this._modifiedEditor.getContentHeight(), this._originalEditor.getContentHeight());
this._onDidContentSizeChange.fire({
contentHeight: height,
contentWidth: width,
contentHeightChanged: e.contentHeightChanged,
contentWidthChanged: e.contentWidthChanged
});
}));
return editor;
}
_createInnerEditor(instantiationService, container, options, editorWidgetOptions) {
return instantiationService.createInstance(codeEditorWidget_1.CodeEditorWidget, container, options, editorWidgetOptions);
}
dispose() {
this._codeEditorService.removeDiffEditor(this);
if (this._beginUpdateDecorationsTimeout !== -1) {
window.clearTimeout(this._beginUpdateDecorationsTimeout);
this._beginUpdateDecorationsTimeout = -1;
}
this._cleanViewZonesAndDecorations();
if (this._originalOverviewRuler) {
this._overviewDomElement.removeChild(this._originalOverviewRuler.getDomNode());
this._originalOverviewRuler.dispose();
}
if (this._modifiedOverviewRuler) {
this._overviewDomElement.removeChild(this._modifiedOverviewRuler.getDomNode());
this._modifiedOverviewRuler.dispose();
}
this._overviewDomElement.removeChild(this._overviewViewportDomElement.domNode);
if (this._renderOverviewRuler) {
this._containerDomElement.removeChild(this._overviewDomElement);
}
this._containerDomElement.removeChild(this._originalDomNode);
this._originalEditor.dispose();
this._containerDomElement.removeChild(this._modifiedDomNode);
this._modifiedEditor.dispose();
this._strategy.dispose();
this._containerDomElement.removeChild(this._reviewPane.domNode.domNode);
this._containerDomElement.removeChild(this._reviewPane.shadow.domNode);
this._containerDomElement.removeChild(this._reviewPane.actionBarContainer.domNode);
this._reviewPane.dispose();
this._domElement.removeChild(this._containerDomElement);
this._onDidDispose.fire();
super.dispose();
}
//------------ begin IDiffEditor methods
getId() {
return this.getEditorType() + ':' + this._id;
}
getEditorType() {
return editorCommon.EditorType.IDiffEditor;
}
getLineChanges() {
if (!this._diffComputationResult) {
return null;
}
return this._diffComputationResult.changes;
}
getOriginalEditor() {
return this._originalEditor;
}
getModifiedEditor() {
return this._modifiedEditor;
}
updateOptions(newOptions) {
// Handle side by side
let renderSideBySideChanged = false;
if (typeof newOptions.renderSideBySide !== 'undefined') {
if (this._renderSideBySide !== newOptions.renderSideBySide) {
this._renderSideBySide = newOptions.renderSideBySide;
renderSideBySideChanged = true;
}
}
if (typeof newOptions.maxComputationTime !== 'undefined') {
this._maxComputationTime = newOptions.maxComputationTime;
if (this._isVisible) {
this._beginUpdateDecorationsSoon();
}
}
let beginUpdateDecorations = false;
if (typeof newOptions.ignoreTrimWhitespace !== 'undefined') {
if (this._ignoreTrimWhitespace !== newOptions.ignoreTrimWhitespace) {
this._ignoreTrimWhitespace = newOptions.ignoreTrimWhitespace;
// Begin comparing
beginUpdateDecorations = true;
}
}
if (typeof newOptions.renderIndicators !== 'undefined') {
if (this._renderIndicators !== newOptions.renderIndicators) {
this._renderIndicators = newOptions.renderIndicators;
beginUpdateDecorations = true;
}
}
if (beginUpdateDecorations) {
this._beginUpdateDecorations();
}
this._originalIsEditable = (0, editorOptions_1.boolean)(newOptions.originalEditable, this._originalIsEditable);
this._diffCodeLens = (0, editorOptions_1.boolean)(newOptions.diffCodeLens, this._diffCodeLens);
this._diffWordWrap = validateDiffWordWrap(newOptions.diffWordWrap, this._diffWordWrap);
this._modifiedEditor.updateOptions(this._adjustOptionsForRightHandSide(newOptions));
this._originalEditor.updateOptions(this._adjustOptionsForLeftHandSide(newOptions));
// enableSplitViewResizing
if (typeof newOptions.enableSplitViewResizing !== 'undefined') {
this._enableSplitViewResizing = newOptions.enableSplitViewResizing;
}
this._strategy.setEnableSplitViewResizing(this._enableSplitViewResizing);
// renderSideBySide
if (renderSideBySideChanged) {
if (this._renderSideBySide) {
this._setStrategy(new DiffEditorWidgetSideBySide(this._createDataSource(), this._enableSplitViewResizing));
}
else {
this._setStrategy(new DiffEditorWidgetInline(this._createDataSource(), this._enableSplitViewResizing));
}
// Update class name
this._containerDomElement.className = DiffEditorWidget._getClassName(this._themeService.getColorTheme(), this._renderSideBySide);
}
// renderOverviewRuler
if (typeof newOptions.renderOverviewRuler !== 'undefined' && this._renderOverviewRuler !== newOptions.renderOverviewRuler) {
this._renderOverviewRuler = newOptions.renderOverviewRuler;
if (this._renderOverviewRuler) {
this._containerDomElement.appendChild(this._overviewDomElement);
}
else {
this._containerDomElement.removeChild(this._overviewDomElement);
}
}
}
getModel() {
return {
original: this._originalEditor.getModel(),
modified: this._modifiedEditor.getModel()
};
}
setModel(model) {
// Guard us against partial null model
if (model && (!model.original || !model.modified)) {
throw new Error(!model.original ? 'DiffEditorWidget.setModel: Original model is null' : 'DiffEditorWidget.setModel: Modified model is null');
}
// Remove all view zones & decorations
this._cleanViewZonesAndDecorations();
// Update code editor models
this._originalEditor.setModel(model ? model.original : null);
this._modifiedEditor.setModel(model ? model.modified : null);
this._updateDecorationsRunner.cancel();
// this.originalEditor.onDidChangeModelOptions
if (model) {
this._originalEditor.setScrollTop(0);
this._modifiedEditor.setScrollTop(0);
}
// Disable any diff computations that will come in
this._diffComputationResult = null;
this._diffComputationToken++;
this._setState(0 /* Idle */);
if (model) {
this._recreateOverviewRulers();
// Begin comparing
this._beginUpdateDecorations();
}
this._layoutOverviewViewport();
}
getDomNode() {
return this._domElement;
}
getVisibleColumnFromPosition(position) {
return this._modifiedEditor.getVisibleColumnFromPosition(position);
}
getPosition() {
return this._modifiedEditor.getPosition();
}
setPosition(position) {
this._modifiedEditor.setPosition(position);
}
revealLine(lineNumber, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealLine(lineNumber, scrollType);
}
revealLineInCenter(lineNumber, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealLineInCenter(lineNumber, scrollType);
}
revealLineInCenterIfOutsideViewport(lineNumber, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealLineInCenterIfOutsideViewport(lineNumber, scrollType);
}
revealLineNearTop(lineNumber, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealLineNearTop(lineNumber, scrollType);
}
revealPosition(position, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealPosition(position, scrollType);
}
revealPositionInCenter(position, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealPositionInCenter(position, scrollType);
}
revealPositionInCenterIfOutsideViewport(position, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealPositionInCenterIfOutsideViewport(position, scrollType);
}
revealPositionNearTop(position, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealPositionNearTop(position, scrollType);
}
getSelection() {
return this._modifiedEditor.getSelection();
}
getSelections() {
return this._modifiedEditor.getSelections();
}
setSelection(something) {
this._modifiedEditor.setSelection(something);
}
setSelections(ranges) {
this._modifiedEditor.setSelections(ranges);
}
revealLines(startLineNumber, endLineNumber, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealLines(startLineNumber, endLineNumber, scrollType);
}
revealLinesInCenter(startLineNumber, endLineNumber, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealLinesInCenter(startLineNumber, endLineNumber, scrollType);
}
revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType);
}
revealLinesNearTop(startLineNumber, endLineNumber, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealLinesNearTop(startLineNumber, endLineNumber, scrollType);
}
revealRange(range, scrollType = 0 /* Smooth */, revealVerticalInCenter = false, revealHorizontal = true) {
this._modifiedEditor.revealRange(range, scrollType, revealVerticalInCenter, revealHorizontal);
}
revealRangeInCenter(range, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealRangeInCenter(range, scrollType);
}
revealRangeInCenterIfOutsideViewport(range, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealRangeInCenterIfOutsideViewport(range, scrollType);
}
revealRangeNearTop(range, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealRangeNearTop(range, scrollType);
}
revealRangeNearTopIfOutsideViewport(range, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealRangeNearTopIfOutsideViewport(range, scrollType);
}
revealRangeAtTop(range, scrollType = 0 /* Smooth */) {
this._modifiedEditor.revealRangeAtTop(range, scrollType);
}
getSupportedActions() {
return this._modifiedEditor.getSupportedActions();
}
saveViewState() {
const originalViewState = this._originalEditor.saveViewState();
const modifiedViewState = this._modifiedEditor.saveViewState();
return {
original: originalViewState,
modified: modifiedViewState
};
}
restoreViewState(s) {
if (s && s.original && s.modified) {
const diffEditorState = s;
this._originalEditor.restoreViewState(diffEditorState.original);
this._modifiedEditor.restoreViewState(diffEditorState.modified);
}
}
layout(dimension) {
this._elementSizeObserver.observe(dimension);
}
focus() {
this._modifiedEditor.focus();
}
hasTextFocus() {
return this._originalEditor.hasTextFocus() || this._modifiedEditor.hasTextFocus();
}
trigger(source, handlerId, payload) {
this._modifiedEditor.trigger(source, handlerId, payload);
}
changeDecorations(callback) {
return this._modifiedEditor.changeDecorations(callback);
}
//------------ end IDiffEditor methods
//------------ begin layouting methods
_onDidContainerSizeChanged() {
this._doLayout();
}
_getReviewHeight() {
return this._reviewPane.isVisible() ? this._elementSizeObserver.getHeight() : 0;
}
_layoutOverviewRulers() {
if (!this._renderOverviewRuler) {
return;
}
if (!this._originalOverviewRuler || !this._modifiedOverviewRuler) {
return;
}
const height = this._elementSizeObserver.getHeight();
const reviewHeight = this._getReviewHeight();
const freeSpace = DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH - 2 * DiffEditorWidget.ONE_OVERVIEW_WIDTH;
const layoutInfo = this._modifiedEditor.getLayoutInfo();
if (layoutInfo) {
this._originalOverviewRuler.setLayout({
top: 0,
width: DiffEditorWidget.ONE_OVERVIEW_WIDTH,
right: freeSpace + DiffEditorWidget.ONE_OVERVIEW_WIDTH,
height: (height - reviewHeight)
});
this._modifiedOverviewRuler.setLayout({
top: 0,
right: 0,
width: DiffEditorWidget.ONE_OVERVIEW_WIDTH,
height: (height - reviewHeight)
});
}
}
//------------ end layouting methods
_onViewZonesChanged() {
if (this._currentlyChangingViewZones) {
return;
}
this._updateDecorationsRunner.schedule();
}
_beginUpdateDecorationsSoon() {
// Clear previous timeout if necessary
if (this._beginUpdateDecorationsTimeout !== -1) {
window.clearTimeout(this._beginUpdateDecorationsTimeout);
this._beginUpdateDecorationsTimeout = -1;
}
this._beginUpdateDecorationsTimeout = window.setTimeout(() => this._beginUpdateDecorations(), DiffEditorWidget.UPDATE_DIFF_DECORATIONS_DELAY);
}
static _equals(a, b) {
if (!a && !b) {
return true;
}
if (!a || !b) {
return false;
}
return (a.toString() === b.toString());
}
_beginUpdateDecorations() {
this._beginUpdateDecorationsTimeout = -1;
const currentOriginalModel = this._originalEditor.getModel();
const currentModifiedModel = this._modifiedEditor.getModel();
if (!currentOriginalModel || !currentModifiedModel) {
return;
}
// Prevent old diff requests to come if a new request has been initiated
// The best method would be to call cancel on the Promise, but this is not
// yet supported, so using tokens for now.
this._diffComputationToken++;
const currentToken = this._diffComputationToken;
this._setState(1 /* ComputingDiff */);
if (!this._editorWorkerService.canComputeDiff(currentOriginalModel.uri, currentModifiedModel.uri)) {
if (!DiffEditorWidget._equals(currentOriginalModel.uri, this._lastOriginalWarning)
|| !DiffEditorWidget._equals(currentModifiedModel.uri, this._lastModifiedWarning)) {
this._lastOriginalWarning = currentOriginalModel.uri;
this._lastModifiedWarning = currentModifiedModel.uri;
this._notificationService.warn(nls.localize(2, null));
}
return;
}
this._editorWorkerService.computeDiff(currentOriginalModel.uri, currentModifiedModel.uri, this._ignoreTrimWhitespace, this._maxComputationTime).then((result) => {
if (currentToken === this._diffComputationToken
&& currentOriginalModel === this._originalEditor.getModel()
&& currentModifiedModel === this._modifiedEditor.getModel()) {
this._setState(2 /* DiffComputed */);
this._diffComputationResult = result;
this._updateDecorationsRunner.schedule();
this._onDidUpdateDiff.fire();
}
}, (error) => {
if (currentToken === this._diffComputationToken
&& currentOriginalModel === this._originalEditor.getModel()
&& currentModifiedModel === this._modifiedEditor.getModel()) {
this._setState(2 /* DiffComputed */);
this._diffComputationResult = null;
this._updateDecorationsRunner.schedule();
}
});
}
_cleanViewZonesAndDecorations() {
this._originalEditorState.clean(this._originalEditor);
this._modifiedEditorState.clean(this._modifiedEditor);
}
_updateDecorations() {
if (!this._originalEditor.getModel() || !this._modifiedEditor.getModel()) {
return;
}
const lineChanges = (this._diffComputationResult ? this._diffComputationResult.changes : []);
const foreignOriginal = this._originalEditorState.getForeignViewZones(this._originalEditor.getWhitespaces());
const foreignModified = this._modifiedEditorState.getForeignViewZones(this._modifiedEditor.getWhitespaces());
const diffDecorations = this._strategy.getEditorsDiffDecorations(lineChanges, this._ignoreTrimWhitespace, this._renderIndicators, foreignOriginal, foreignModified);
try {
this._currentlyChangingViewZones = true;
this._originalEditorState.apply(this._originalEditor, this._originalOverviewRuler, diffDecorations.original, false);
this._modifiedEditorState.apply(this._modifiedEditor, this._modifiedOverviewRuler, diffDecorations.modified, true);
}
finally {
this._currentlyChangingViewZones = false;
}
}
_adjustOptionsForSubEditor(options) {
const clonedOptions = Object.assign({}, options);
clonedOptions.inDiffEditor = true;
clonedOptions.automaticLayout = false;
// Clone scrollbar options before changing them
clonedOptions.scrollbar = Object.assign({}, (clonedOptions.scrollbar || {}));
clonedOptions.scrollbar.vertical = 'visible';
clonedOptions.folding = false;
clonedOptions.codeLens = this._diffCodeLens;
clonedOptions.fixedOverflowWidgets = true;
// clonedOptions.lineDecorationsWidth = '2ch';
// Clone minimap options before changing them
clonedOptions.minimap = Object.assign({}, (clonedOptions.minimap || {}));
clonedOptions.minimap.enabled = false;
return clonedOptions;
}
_adjustOptionsForLeftHandSide(options) {
const result = this._adjustOptionsForSubEditor(options);
if (!this._renderSideBySide) {
// never wrap hidden editor
result.wordWrapOverride1 = 'off';
}
else {
result.wordWrapOverride1 = this._diffWordWrap;
}
if (options.originalAriaLabel) {
result.ariaLabel = options.originalAriaLabel;
}
result.readOnly = !this._originalIsEditable;
result.extraEditorClassName = 'original-in-monaco-diff-editor';
return Object.assign(Object.assign({}, result), { dimension: {
height: 0,
width: 0
} });
}
_adjustOptionsForRightHandSide(options) {
const result = this._adjustOptionsForSubEditor(options);
if (options.modifiedAriaLabel) {
result.ariaLabel = options.modifiedAriaLabel;
}
result.wordWrapOverride1 = this._diffWordWrap;
result.revealHorizontalRightPadding = editorOptions_1.EditorOptions.revealHorizontalRightPadding.defaultValue + DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH;
result.scrollbar.verticalHasArrows = false;
result.extraEditorClassName = 'modified-in-monaco-diff-editor';
return Object.assign(Object.assign({}, result), { dimension: {
height: 0,
width: 0
} });
}
doLayout() {
this._elementSizeObserver.observe();
this._doLayout();
}
_doLayout() {
const width = this._elementSizeObserver.getWidth();
const height = this._elementSizeObserver.getHeight();
const reviewHeight = this._getReviewHeight();
const splitPoint = this._strategy.layout();
this._originalDomNode.style.width = splitPoint + 'px';
this._originalDomNode.style.left = '0px';
this._modifiedDomNode.style.width = (width - splitPoint) + 'px';
this._modifiedDomNode.style.left = splitPoint + 'px';
this._overviewDomElement.style.top = '0px';
this._overviewDomElement.style.height = (height - reviewHeight) + 'px';
this._overviewDomElement.style.width = DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH + 'px';
this._overviewDomElement.style.left = (width - DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH) + 'px';
this._overviewViewportDomElement.setWidth(DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH);
this._overviewViewportDomElement.setHeight(30);
this._originalEditor.layout({ width: splitPoint, height: (height - reviewHeight) });
this._modifiedEditor.layout({ width: width - splitPoint - (this._renderOverviewRuler ? DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH : 0), height: (height - reviewHeight) });
if (this._originalOverviewRuler || this._modifiedOverviewRuler) {
this._layoutOverviewRulers();
}
this._reviewPane.layout(height - reviewHeight, width, reviewHeight);
this._layoutOverviewViewport();
}
_layoutOverviewViewport() {
const layout = this._computeOverviewViewport();
if (!layout) {
this._overviewViewportDomElement.setTop(0);
this._overviewViewportDomElement.setHeight(0);
}
else {
this._overviewViewportDomElement.setTop(layout.top);
this._overviewViewportDomElement.setHeight(layout.height);
}
}
_computeOverviewViewport() {
const layoutInfo = this._modifiedEditor.getLayoutInfo();
if (!layoutInfo) {
return null;
}
const scrollTop = this._modifiedEditor.getScrollTop();
const scrollHeight = this._modifiedEditor.getScrollHeight();
const computedAvailableSize = Math.max(0, layoutInfo.height);
const computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * 0);
const computedRatio = scrollHeight > 0 ? (computedRepresentableSize / scrollHeight) : 0;
const computedSliderSize = Math.max(0, Math.floor(layoutInfo.height * computedRatio));
const computedSliderPosition = Math.floor(scrollTop * computedRatio);
return {
height: computedSliderSize,
top: computedSliderPosition
};
}
_createDataSource() {
return {
getWidth: () => {
return this._elementSizeObserver.getWidth();
},
getHeight: () => {
return (this._elementSizeObserver.getHeight() - this._getReviewHeight());
},
getOptions: () => {
return {
renderOverviewRuler: this._renderOverviewRuler
};
},
getContainerDomNode: () => {
return this._containerDomElement;
},
relayoutEditors: () => {
this._doLayout();
},
getOriginalEditor: () => {
return this._originalEditor;
},
getModifiedEditor: () => {
return this._modifiedEditor;
}
};
}
_setStrategy(newStrategy) {
if (this._strategy) {
this._strategy.dispose();
}
this._strategy = newStrategy;
newStrategy.applyColors(this._themeService.getColorTheme());
if (this._diffComputationResult) {
this._updateDecorations();
}
// Just do a layout, the strategy might need it
this._doLayout();
}
_getLineChangeAtOrBeforeLineNumber(lineNumber, startLineNumberExtractor) {
const lineChanges = (this._diffComputationResult ? this._diffComputationResult.changes : []);
if (lineChanges.length === 0 || lineNumber < startLineNumberExtractor(lineChanges[0])) {
// There are no changes or `lineNumber` is before the first change
return null;
}
let min = 0;
let max = lineChanges.length - 1;
while (min < max) {
const mid = Math.floor((min + max) / 2);
const midStart = startLineNumberExtractor(lineChanges[mid]);
const midEnd = (mid + 1 <= max ? startLineNumberExtractor(lineChanges[mid + 1]) : 1073741824 /* MAX_SAFE_SMALL_INTEGER */);
if (lineNumber < midStart) {
max = mid - 1;
}
else if (lineNumber >= midEnd) {
min = mid + 1;
}
else {
// HIT!
min = mid;
max = mid;
}
}
return lineChanges[min];
}
_getEquivalentLineForOriginalLineNumber(lineNumber) {
const lineChange = this._getLineChangeAtOrBeforeLineNumber(lineNumber, (lineChange) => lineChange.originalStartLineNumber);
if (!lineChange) {
return lineNumber;
}
const originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0);
const modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0);
const lineChangeOriginalLength = (lineChange.originalEndLineNumber > 0 ? (lineChange.originalEndLineNumber - lineChange.originalStartLineNumber + 1) : 0);
const lineChangeModifiedLength = (lineChange.modifiedEndLineNumber > 0 ? (lineChange.modifiedEndLineNumber - lineChange.modifiedStartLineNumber + 1) : 0);
const delta = lineNumber - originalEquivalentLineNumber;
if (delta <= lineChangeOriginalLength) {
return modifiedEquivalentLineNumber + Math.min(delta, lineChangeModifiedLength);
}
return modifiedEquivalentLineNumber + lineChangeModifiedLength - lineChangeOriginalLength + delta;
}
_getEquivalentLineForModifiedLineNumber(lineNumber) {
const lineChange = this._getLineChangeAtOrBeforeLineNumber(lineNumber, (lineChange) => lineChange.modifiedStartLineNumber);
if (!lineChange) {
return lineNumber;
}
const originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0);
const modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0);
const lineChangeOriginalLength = (lineChange.originalEndLineNumber > 0 ? (lineChange.originalEndLineNumber - lineChange.originalStartLineNumber + 1) : 0);
const lineChangeModifiedLength = (lineChange.modifiedEndLineNumber > 0 ? (lineChange.modifiedEndLineNumber - lineChange.modifiedStartLineNumber + 1) : 0);
const delta = lineNumber - modifiedEquivalentLineNumber;
if (delta <= lineChangeModifiedLength) {
return originalEquivalentLineNumber + Math.min(delta, lineChangeOriginalLength);
}
return originalEquivalentLineNumber + lineChangeOriginalLength - lineChangeModifiedLength + delta;
}
getDiffLineInformationForOriginal(lineNumber) {
if (!this._diffComputationResult) {
// Cannot answer that which I don't know
return null;
}
return {
equivalentLineNumber: this._getEquivalentLineForOriginalLineNumber(lineNumber)
};
}
getDiffLineInformationForModified(lineNumber) {
if (!this._diffComputationResult) {
// Cannot answer that which I don't know
return null;
}
return {
equivalentLineNumber: this._getEquivalentLineForModifiedLineNumber(lineNumber)
};
}
};
DiffEditorWidget.ONE_OVERVIEW_WIDTH = 15;
DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH = 30;
DiffEditorWidget.UPDATE_DIFF_DECORATIONS_DELAY = 200; // ms
DiffEditorWidget = __decorate([
__param(3, clipboardService_1.IClipboardService),
__param(4, editorWorkerService_1.IEditorWorkerService),
__param(5, contextkey_1.IContextKeyService),
__param(6, instantiation_1.IInstantiationService),
__param(7, codeEditorService_1.ICodeEditorService),
__param(8, themeService_1.IThemeService),
__param(9, notification_1.INotificationService),
__param(10, contextView_1.IContextMenuService),
__param(11, progress_1.IEditorProgressService)
], DiffEditorWidget);
exports.DiffEditorWidget = DiffEditorWidget;
class DiffEditorWidgetStyle extends lifecycle_1.Disposable {
constructor(dataSource) {
super();
this._dataSource = dataSource;
this._insertColor = null;
this._removeColor = null;
}
applyColors(theme) {
const newInsertColor = (theme.getColor(colorRegistry_1.diffInserted) || colorRegistry_1.defaultInsertColor).transparent(2);
const newRemoveColor = (theme.getColor(colorRegistry_1.diffRemoved) || colorRegistry_1.defaultRemoveColor).transparent(2);
const hasChanges = !newInsertColor.equals(this._insertColor) || !newRemoveColor.equals(this._removeColor);
this._insertColor = newInsertColor;
this._removeColor = newRemoveColor;
return hasChanges;
}
getEditorsDiffDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators, originalWhitespaces, modifiedWhitespaces) {
// Get view zones
modifiedWhitespaces = modifiedWhitespaces.sort((a, b) => {
return a.afterLineNumber - b.afterLineNumber;
});
originalWhitespaces = originalWhitespaces.sort((a, b) => {
return a.afterLineNumber - b.afterLineNumber;
});
const zones = this._getViewZones(lineChanges, originalWhitespaces, modifiedWhitespaces, renderIndicators);
// Get decorations & overview ruler zones
const originalDecorations = this._getOriginalEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators);
const modifiedDecorations = this._getModifiedEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators);
return {
original: {
decorations: originalDecorations.decorations,
overviewZones: originalDecorations.overviewZones,
zones: zones.original
},
modified: {
decorations: modifiedDecorations.decorations,
overviewZones: modifiedDecorations.overviewZones,
zones: zones.modified
}
};
}
}
class ForeignViewZonesIterator {
constructor(source) {
this._source = source;
this._index = -1;
this.current = null;
this.advance();
}
advance() {
this._index++;
if (this._index < this._source.length) {
this.current = this._source[this._index];
}
else {
this.current = null;
}
}
}
class ViewZonesComputer {
constructor(_lineChanges, _originalForeignVZ, _modifiedForeignVZ, _originalEditor, _modifiedEditor) {
this._lineChanges = _lineChanges;
this._originalForeignVZ = _originalForeignVZ;
this._modifiedForeignVZ = _modifiedForeignVZ;
this._originalEditor = _originalEditor;
this._modifiedEditor = _modifiedEditor;
}
static _getViewLineCount(editor, startLineNumber, endLineNumber) {
const model = editor.getModel();
const viewModel = editor._getViewModel();
if (model && viewModel) {
const viewRange = getViewRange(model, viewModel, startLineNumber, endLineNumber);
return (viewRange.endLineNumber - viewRange.startLineNumber + 1);
}
return (endLineNumber - startLineNumber + 1);
}
getViewZones() {
const originalLineHeight = this._originalEditor.getOption(57 /* lineHeight */);
const modifiedLineHeight = this._modifiedEditor.getOption(57 /* lineHeight */);
const originalHasWrapping = (this._originalEditor.getOption(130 /* wrappingInfo */).wrappingColumn !== -1);
const modifiedHasWrapping = (this._modifiedEditor.getOption(130 /* wrappingInfo */).wrappingColumn !== -1);
const hasWrapping = (originalHasWrapping || modifiedHasWrapping);
const originalModel = this._originalEditor.getModel();
const originalCoordinatesConverter = this._originalEditor._getViewModel().coordinatesConverter;
const modifiedCoordinatesConverter = this._modifiedEditor._getViewModel().coordinatesConverter;
const result = {
original: [],
modified: []
};
let lineChangeModifiedLength = 0;
let lineChangeOriginalLength = 0;
let originalEquivalentLineNumber = 0;
let modifiedEquivalentLineNumber = 0;
let originalEndEquivalentLineNumber = 0;
let modifiedEndEquivalentLineNumber = 0;
const sortMyViewZones = (a, b) => {
return a.afterLineNumber - b.afterLineNumber;
};
const addAndCombineIfPossible = (destination, item) => {
if (item.domNode === null && destination.length > 0) {
const lastItem = destination[destination.length - 1];
if (lastItem.afterLineNumber === item.afterLineNumber && lastItem.domNode === null) {
lastItem.heightInLines += item.heightInLines;
return;
}
}
destination.push(item);
};
const modifiedForeignVZ = new ForeignViewZonesIterator(this._modifiedForeignVZ);
const originalForeignVZ = new ForeignViewZonesIterator(this._originalForeignVZ);
let lastOriginalLineNumber = 1;
let lastModifiedLineNumber = 1;
// In order to include foreign view zones after the last line change, the for loop will iterate once more after the end of the `lineChanges` array
for (let i = 0, length = this._lineChanges.length; i <= length; i++) {
const lineChange = (i < length ? this._lineChanges[i] : null);
if (lineChange !== null) {
originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0);
modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0);
lineChangeOriginalLength = (lineChange.originalEndLineNumber > 0 ? ViewZonesComputer._getViewLineCount(this._originalEditor, lineChange.originalStartLineNumber, lineChange.originalEndLineNumber) : 0);
lineChangeModifiedLength = (lineChange.modifiedEndLineNumber > 0 ? ViewZonesComputer._getViewLineCount(this._modifiedEditor, lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber) : 0);
originalEndEquivalentLineNumber = Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber);
modifiedEndEquivalentLineNumber = Math.max(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber);
}
else {
// Increase to very large value to get the producing tests of foreign view zones running
originalEquivalentLineNumber += 10000000 + lineChangeOriginalLength;
modifiedEquivalentLineNumber += 10000000 + lineChangeModifiedLength;
originalEndEquivalentLineNumber = originalEquivalentLineNumber;
modifiedEndEquivalentLineNumber = modifiedEquivalentLineNumber;
}
// Each step produces view zones, and after producing them, we try to cancel them out, to avoid empty-empty view zone cases
let stepOriginal = [];
let stepModified = [];
// ---------------------------- PRODUCE VIEW ZONES
// [PRODUCE] View zones due to line mapping differences (equal lines but wrapped differently)
if (hasWrapping) {
let count;
if (lineChange) {
if (lineChange.originalEndLineNumber > 0) {
count = lineChange.originalStartLineNumber - lastOriginalLineNumber;
}
else {
count = lineChange.modifiedStartLineNumber - lastModifiedLineNumber;
}
}
else {
count = originalModel.getLineCount() - lastOriginalLineNumber;
}
for (let i = 0; i < count; i++) {
const originalLineNumber = lastOriginalLineNumber + i;
const modifiedLineNumber = lastModifiedLineNumber + i;
const originalViewLineCount = originalCoordinatesConverter.getModelLineViewLineCount(originalLineNumber);
const modifiedViewLineCount = modifiedCoordinatesConverter.getModelLineViewLineCount(modifiedLineNumber);
if (originalViewLineCount < modifiedViewLineCount) {
stepOriginal.push({
afterLineNumber: originalLineNumber,
heightInLines: modifiedViewLineCount - originalViewLineCount,
domNode: null,
marginDomNode: null
});
}
else if (originalViewLineCount > modifiedViewLineCount) {
stepModified.push({
afterLineNumber: modifiedLineNumber,
heightInLines: originalViewLineCount - modifiedViewLineCount,
domNode: null,
marginDomNode: null
});
}
}
if (lineChange) {
lastOriginalLineNumber = (lineChange.originalEndLineNumber > 0 ? lineChange.originalEndLineNumber : lineChange.originalStartLineNumber) + 1;
lastModifiedLineNumber = (lineChange.modifiedEndLineNumber > 0 ? lineChange.modifiedEndLineNumber : lineChange.modifiedStartLineNumber) + 1;
}
}
// [PRODUCE] View zone(s) in original-side due to foreign view zone(s) in modified-side
while (modifiedForeignVZ.current && modifiedForeignVZ.current.afterLineNumber <= modifiedEndEquivalentLineNumber) {
let viewZoneLineNumber;
if (modifiedForeignVZ.current.afterLineNumber <= modifiedEquivalentLineNumber) {
viewZoneLineNumber = originalEquivalentLineNumber - modifiedEquivalentLineNumber + modifiedForeignVZ.current.afterLineNumber;
}
else {
viewZoneLineNumber = originalEndEquivalentLineNumber;
}
let marginDomNode = null;
if (lineChange && lineChange.modifiedStartLineNumber <= modifiedForeignVZ.current.afterLineNumber && modifiedForeignVZ.current.afterLineNumber <= lineChange.modifiedEndLineNumber) {
marginDomNode = this._createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion();
}
stepOriginal.push({
afterLineNumber: viewZoneLineNumber,
heightInLines: modifiedForeignVZ.current.height / modifiedLineHeight,
domNode: null,
marginDomNode: marginDomNode
});
modifiedForeignVZ.advance();
}
// [PRODUCE] View zone(s) in modified-side due to foreign view zone(s) in original-side
while (originalForeignVZ.current && originalForeignVZ.current.afterLineNumber <= originalEndEquivalentLineNumber) {
let viewZoneLineNumber;
if (originalForeignVZ.current.afterLineNumber <= originalEquivalentLineNumber) {
viewZoneLineNumber = modifiedEquivalentLineNumber - originalEquivalentLineNumber + originalForeignVZ.current.afterLineNumber;
}
else {
viewZoneLineNumber = modifiedEndEquivalentLineNumber;
}
stepModified.push({
afterLineNumber: viewZoneLineNumber,
heightInLines: originalForeignVZ.current.height / originalLineHeight,
domNode: null
});
originalForeignVZ.advance();
}
if (lineChange !== null && isChangeOrInsert(lineChange)) {
const r = this._produceOriginalFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength);
if (r) {
stepOriginal.push(r);
}
}
if (lineChange !== null && isChangeOrDelete(lineChange)) {
const r = this._produceModifiedFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength);
if (r) {
stepModified.push(r);
}
}
// ---------------------------- END PRODUCE VIEW ZONES
// ---------------------------- EMIT MINIMAL VIEW ZONES
// [CANCEL & EMIT] Try to cancel view zones out
let stepOriginalIndex = 0;
let stepModifiedIndex = 0;
stepOriginal = stepOriginal.sort(sortMyViewZones);
stepModified = stepModified.sort(sortMyViewZones);
while (stepOriginalIndex < stepOriginal.length && stepModifiedIndex < stepModified.length) {
const original = stepOriginal[stepOriginalIndex];
const modified = stepModified[stepModifiedIndex];
const originalDelta = original.afterLineNumber - originalEquivalentLineNumber;
const modifiedDelta = modified.afterLineNumber - modifiedEquivalentLineNumber;
if (originalDelta < modifiedDelta) {
addAndCombineIfPossible(result.original, original);
stepOriginalIndex++;
}
else if (modifiedDelta < originalDelta) {
addAndCombineIfPossible(result.modified, modified);
stepModifiedIndex++;
}
else if (original.shouldNotShrink) {
addAndCombineIfPossible(result.original, original);
stepOriginalIndex++;
}
else if (modified.shouldNotShrink) {
addAndCombineIfPossible(result.modified, modified);
stepModifiedIndex++;
}
else {
if (original.heightInLines >= modified.heightInLines) {
// modified view zone gets removed
original.heightInLines -= modified.heightInLines;
stepModifiedIndex++;
}
else {
// original view zone gets removed
modified.heightInLines -= original.heightInLines;
stepOriginalIndex++;
}
}
}
// [EMIT] Remaining original view zones
while (stepOriginalIndex < stepOriginal.length) {
addAndCombineIfPossible(result.original, stepOriginal[stepOriginalIndex]);
stepOriginalIndex++;
}
// [EMIT] Remaining modified view zones
while (stepModifiedIndex < stepModified.length) {
addAndCombineIfPossible(result.modified, stepModified[stepModifiedIndex]);
stepModifiedIndex++;
}
// ---------------------------- END EMIT MINIMAL VIEW ZONES
}
return {
original: ViewZonesComputer._ensureDomNodes(result.original),
modified: ViewZonesComputer._ensureDomNodes(result.modified),
};
}
static _ensureDomNodes(zones) {
return zones.map((z) => {
if (!z.domNode) {
z.domNode = createFakeLinesDiv();
}
return z;
});
}
}
function createDecoration(startLineNumber, startColumn, endLineNumber, endColumn, options) {
return {
range: new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn),
options: options
};
}
const DECORATIONS = {
charDelete: textModel_1.ModelDecorationOptions.register({
description: 'diff-editor-char-delete',
className: 'char-delete'
}),
charDeleteWholeLine: textModel_1.ModelDecorationOptions.register({
description: 'diff-editor-char-delete-whole-line',
className: 'char-delete',
isWholeLine: true
}),
charInsert: textModel_1.ModelDecorationOptions.register({
description: 'diff-editor-char-insert',
className: 'char-insert'
}),
charInsertWholeLine: textModel_1.ModelDecorationOptions.register({
description: 'diff-editor-char-insert-whole-line',
className: 'char-insert',
isWholeLine: true
}),
lineInsert: textModel_1.ModelDecorationOptions.register({
description: 'diff-editor-line-insert',
className: 'line-insert',
marginClassName: 'line-insert',
isWholeLine: true
}),
lineInsertWithSign: textModel_1.ModelDecorationOptions.register({
description: 'diff-editor-line-insert-with-sign',
className: 'line-insert',
linesDecorationsClassName: 'insert-sign ' + themeService_1.ThemeIcon.asClassName(diffInsertIcon),
marginClassName: 'line-insert',
isWholeLine: true
}),
lineDelete: textModel_1.ModelDecorationOptions.register({
description: 'diff-editor-line-delete',
className: 'line-delete',
marginClassName: 'line-delete',
isWholeLine: true
}),
lineDeleteWithSign: textModel_1.ModelDecorationOptions.register({
description: 'diff-editor-line-delete-with-sign',
className: 'line-delete',
linesDecorationsClassName: 'delete-sign ' + themeService_1.ThemeIcon.asClassName(diffRemoveIcon),
marginClassName: 'line-delete',
isWholeLine: true
}),
lineDeleteMargin: textModel_1.ModelDecorationOptions.register({
description: 'diff-editor-line-delete-margin',
marginClassName: 'line-delete',
})
};
class DiffEditorWidgetSideBySide extends DiffEditorWidgetStyle {
constructor(dataSource, enableSplitViewResizing) {
super(dataSource);
this._disableSash = (enableSplitViewResizing === false);
this._sashRatio = null;
this._sashPosition = null;
this._startSashPosition = null;
this._sash = this._register(new sash_1.Sash(this._dataSource.getContainerDomNode(), this, { orientation: 0 /* VERTICAL */ }));
if (this._disableSash) {
this._sash.state = 0 /* Disabled */;
}
this._sash.onDidStart(() => this._onSashDragStart());
this._sash.onDidChange((e) => this._onSashDrag(e));
this._sash.onDidEnd(() => this._onSashDragEnd());
this._sash.onDidReset(() => this._onSashReset());
}
setEnableSplitViewResizing(enableSplitViewResizing) {
const newDisableSash = (enableSplitViewResizing === false);
if (this._disableSash !== newDisableSash) {
this._disableSash = newDisableSash;
this._sash.state = this._disableSash ? 0 /* Disabled */ : 3 /* Enabled */;
}
}
layout(sashRatio = this._sashRatio) {
const w = this._dataSource.getWidth();
const contentWidth = w - (this._dataSource.getOptions().renderOverviewRuler ? DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH : 0);
let sashPosition = Math.floor((sashRatio || 0.5) * contentWidth);
const midPoint = Math.floor(0.5 * contentWidth);
sashPosition = this._disableSash ? midPoint : sashPosition || midPoint;
if (contentWidth > DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH * 2) {
if (sashPosition < DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH) {
sashPosition = DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH;
}
if (sashPosition > contentWidth - DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH) {
sashPosition = contentWidth - DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH;
}
}
else {
sashPosition = midPoint;
}
if (this._sashPosition !== sashPosition) {
this._sashPosition = sashPosition;
this._sash.layout();
}
return this._sashPosition;
}
_onSashDragStart() {
this._startSashPosition = this._sashPosition;
}
_onSashDrag(e) {
const w = this._dataSource.getWidth();
const contentWidth = w - (this._dataSource.getOptions().renderOverviewRuler ? DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH : 0);
const sashPosition = this.layout((this._startSashPosition + (e.currentX - e.startX)) / contentWidth);
this._sashRatio = sashPosition / contentWidth;
this._dataSource.relayoutEditors();
}
_onSashDragEnd() {
this._sash.layout();
}
_onSashReset() {
this._sashRatio = 0.5;
this._dataSource.relayoutEditors();
this._sash.layout();
}
getVerticalSashTop(sash) {
return 0;
}
getVerticalSashLeft(sash) {
return this._sashPosition;
}
getVerticalSashHeight(sash) {
return this._dataSource.getHeight();
}
_getViewZones(lineChanges, originalForeignVZ, modifiedForeignVZ) {
const originalEditor = this._dataSource.getOriginalEditor();
const modifiedEditor = this._dataSource.getModifiedEditor();
const c = new SideBySideViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor);
return c.getViewZones();
}
_getOriginalEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators) {
const originalEditor = this._dataSource.getOriginalEditor();
const overviewZoneColor = String(this._removeColor);
const result = {
decorations: [],
overviewZones: []
};
const originalModel = originalEditor.getModel();
const originalViewModel = originalEditor._getViewModel();
for (const lineChange of lineChanges) {
if (isChangeOrDelete(lineChange)) {
result.decorations.push({
range: new range_1.Range(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */),
options: (renderIndicators ? DECORATIONS.lineDeleteWithSign : DECORATIONS.lineDelete)
});
if (!isChangeOrInsert(lineChange) || !lineChange.charChanges) {
result.decorations.push(createDecoration(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, DECORATIONS.charDeleteWholeLine));
}
const viewRange = getViewRange(originalModel, originalViewModel, lineChange.originalStartLineNumber, lineChange.originalEndLineNumber);
result.overviewZones.push(new overviewZoneManager_1.OverviewRulerZone(viewRange.startLineNumber, viewRange.endLineNumber, overviewZoneColor));
if (lineChange.charChanges) {
for (const charChange of lineChange.charChanges) {
if (isChangeOrDelete(charChange)) {
if (ignoreTrimWhitespace) {
for (let lineNumber = charChange.originalStartLineNumber; lineNumber <= charChange.originalEndLineNumber; lineNumber++) {
let startColumn;
let endColumn;
if (lineNumber === charChange.originalStartLineNumber) {
startColumn = charChange.originalStartColumn;
}
else {
startColumn = originalModel.getLineFirstNonWhitespaceColumn(lineNumber);
}
if (lineNumber === charChange.originalEndLineNumber) {
endColumn = charChange.originalEndColumn;
}
else {
endColumn = originalModel.getLineLastNonWhitespaceColumn(lineNumber);
}
result.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charDelete));
}
}
else {
result.decorations.push(createDecoration(charChange.originalStartLineNumber, charChange.originalStartColumn, charChange.originalEndLineNumber, charChange.originalEndColumn, DECORATIONS.charDelete));
}
}
}
}
}
}
return result;
}
_getModifiedEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators) {
const modifiedEditor = this._dataSource.getModifiedEditor();
const overviewZoneColor = String(this._insertColor);
const result = {
decorations: [],
overviewZones: []
};
const modifiedModel = modifiedEditor.getModel();
const modifiedViewModel = modifiedEditor._getViewModel();
for (const lineChange of lineChanges) {
if (isChangeOrInsert(lineChange)) {
result.decorations.push({
range: new range_1.Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */),
options: (renderIndicators ? DECORATIONS.lineInsertWithSign : DECORATIONS.lineInsert)
});
if (!isChangeOrDelete(lineChange) || !lineChange.charChanges) {
result.decorations.push(createDecoration(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, DECORATIONS.charInsertWholeLine));
}
const viewRange = getViewRange(modifiedModel, modifiedViewModel, lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber);
result.overviewZones.push(new overviewZoneManager_1.OverviewRulerZone(viewRange.startLineNumber, viewRange.endLineNumber, overviewZoneColor));
if (lineChange.charChanges) {
for (const charChange of lineChange.charChanges) {
if (isChangeOrInsert(charChange)) {
if (ignoreTrimWhitespace) {
for (let lineNumber = charChange.modifiedStartLineNumber; lineNumber <= charChange.modifiedEndLineNumber; lineNumber++) {
let startColumn;
let endColumn;
if (lineNumber === charChange.modifiedStartLineNumber) {
startColumn = charChange.modifiedStartColumn;
}
else {
startColumn = modifiedModel.getLineFirstNonWhitespaceColumn(lineNumber);
}
if (lineNumber === charChange.modifiedEndLineNumber) {
endColumn = charChange.modifiedEndColumn;
}
else {
endColumn = modifiedModel.getLineLastNonWhitespaceColumn(lineNumber);
}
result.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charInsert));
}
}
else {
result.decorations.push(createDecoration(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn, DECORATIONS.charInsert));
}
}
}
}
}
}
return result;
}
}
DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH = 100;
class SideBySideViewZonesComputer extends ViewZonesComputer {
constructor(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor) {
super(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor);
}
_createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion() {
return null;
}
_produceOriginalFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
if (lineChangeModifiedLength > lineChangeOriginalLength) {
return {
afterLineNumber: Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber),
heightInLines: (lineChangeModifiedLength - lineChangeOriginalLength),
domNode: null
};
}
return null;
}
_produceModifiedFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
if (lineChangeOriginalLength > lineChangeModifiedLength) {
return {
afterLineNumber: Math.max(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber),
heightInLines: (lineChangeOriginalLength - lineChangeModifiedLength),
domNode: null
};
}
return null;
}
}
class DiffEditorWidgetInline extends DiffEditorWidgetStyle {
constructor(dataSource, enableSplitViewResizing) {
super(dataSource);
this._decorationsLeft = dataSource.getOriginalEditor().getLayoutInfo().decorationsLeft;
this._register(dataSource.getOriginalEditor().onDidLayoutChange((layoutInfo) => {
if (this._decorationsLeft !== layoutInfo.decorationsLeft) {
this._decorationsLeft = layoutInfo.decorationsLeft;
dataSource.relayoutEditors();
}
}));
}
setEnableSplitViewResizing(enableSplitViewResizing) {
// Nothing to do..
}
_getViewZones(lineChanges, originalForeignVZ, modifiedForeignVZ, renderIndicators) {
const originalEditor = this._dataSource.getOriginalEditor();
const modifiedEditor = this._dataSource.getModifiedEditor();
const computer = new InlineViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators);
return computer.getViewZones();
}
_getOriginalEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators) {
const overviewZoneColor = String(this._removeColor);
const result = {
decorations: [],
overviewZones: []
};
const originalEditor = this._dataSource.getOriginalEditor();
const originalModel = originalEditor.getModel();
const originalViewModel = originalEditor._getViewModel();
for (const lineChange of lineChanges) {
// Add overview zones in the overview ruler
if (isChangeOrDelete(lineChange)) {
result.decorations.push({
range: new range_1.Range(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */),
options: DECORATIONS.lineDeleteMargin
});
const viewRange = getViewRange(originalModel, originalViewModel, lineChange.originalStartLineNumber, lineChange.originalEndLineNumber);
result.overviewZones.push(new overviewZoneManager_1.OverviewRulerZone(viewRange.startLineNumber, viewRange.endLineNumber, overviewZoneColor));
}
}
return result;
}
_getModifiedEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators) {
const modifiedEditor = this._dataSource.getModifiedEditor();
const overviewZoneColor = String(this._insertColor);
const result = {
decorations: [],
overviewZones: []
};
const modifiedModel = modifiedEditor.getModel();
const modifiedViewModel = modifiedEditor._getViewModel();
for (const lineChange of lineChanges) {
// Add decorations & overview zones
if (isChangeOrInsert(lineChange)) {
result.decorations.push({
range: new range_1.Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */),
options: (renderIndicators ? DECORATIONS.lineInsertWithSign : DECORATIONS.lineInsert)
});
const viewRange = getViewRange(modifiedModel, modifiedViewModel, lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber);
result.overviewZones.push(new overviewZoneManager_1.OverviewRulerZone(viewRange.startLineNumber, viewRange.endLineNumber, overviewZoneColor));
if (lineChange.charChanges) {
for (const charChange of lineChange.charChanges) {
if (isChangeOrInsert(charChange)) {
if (ignoreTrimWhitespace) {
for (let lineNumber = charChange.modifiedStartLineNumber; lineNumber <= charChange.modifiedEndLineNumber; lineNumber++) {
let startColumn;
let endColumn;
if (lineNumber === charChange.modifiedStartLineNumber) {
startColumn = charChange.modifiedStartColumn;
}
else {
startColumn = modifiedModel.getLineFirstNonWhitespaceColumn(lineNumber);
}
if (lineNumber === charChange.modifiedEndLineNumber) {
endColumn = charChange.modifiedEndColumn;
}
else {
endColumn = modifiedModel.getLineLastNonWhitespaceColumn(lineNumber);
}
result.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charInsert));
}
}
else {
result.decorations.push(createDecoration(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn, DECORATIONS.charInsert));
}
}
}
}
else {
result.decorations.push(createDecoration(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, DECORATIONS.charInsertWholeLine));
}
}
}
return result;
}
layout() {
// An editor should not be smaller than 5px
return Math.max(5, this._decorationsLeft);
}
}
class InlineViewZonesComputer extends ViewZonesComputer {
constructor(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators) {
super(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor);
this._originalModel = originalEditor.getModel();
this._renderIndicators = renderIndicators;
this._pendingLineChange = [];
this._pendingViewZones = [];
this._lineBreaksComputer = this._modifiedEditor._getViewModel().createLineBreaksComputer();
}
getViewZones() {
const result = super.getViewZones();
this._finalize(result);
return result;
}
_createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion() {
const result = document.createElement('div');
result.className = 'inline-added-margin-view-zone';
return result;
}
_produceOriginalFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
const marginDomNode = document.createElement('div');
marginDomNode.className = 'inline-added-margin-view-zone';
return {
afterLineNumber: Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber),
heightInLines: lineChangeModifiedLength,
domNode: document.createElement('div'),
marginDomNode: marginDomNode
};
}
_produceModifiedFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
const domNode = document.createElement('div');
domNode.className = `view-lines line-delete ${mouseCursor_1.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`;
const marginDomNode = document.createElement('div');
marginDomNode.className = 'inline-deleted-margin-view-zone';
const viewZone = {
shouldNotShrink: true,
afterLineNumber: (lineChange.modifiedEndLineNumber === 0 ? lineChange.modifiedStartLineNumber : lineChange.modifiedStartLineNumber - 1),
heightInLines: lineChangeOriginalLength,
minWidthInPx: 0,
domNode: domNode,
marginDomNode: marginDomNode,
diff: {
originalStartLineNumber: lineChange.originalStartLineNumber,
originalEndLineNumber: lineChange.originalEndLineNumber,
modifiedStartLineNumber: lineChange.modifiedStartLineNumber,
modifiedEndLineNumber: lineChange.modifiedEndLineNumber,
originalModel: this._originalModel,
viewLineCounts: null,
}
};
for (let lineNumber = lineChange.originalStartLineNumber; lineNumber <= lineChange.originalEndLineNumber; lineNumber++) {
this._lineBreaksComputer.addRequest(this._originalModel.getLineContent(lineNumber), null, null);
}
this._pendingLineChange.push(lineChange);
this._pendingViewZones.push(viewZone);
return viewZone;
}
_finalize(result) {
const modifiedEditorOptions = this._modifiedEditor.getOptions();
const tabSize = this._modifiedEditor.getModel().getOptions().tabSize;
const fontInfo = modifiedEditorOptions.get(41 /* fontInfo */);
const disableMonospaceOptimizations = modifiedEditorOptions.get(27 /* disableMonospaceOptimizations */);
const typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
const scrollBeyondLastColumn = modifiedEditorOptions.get(92 /* scrollBeyondLastColumn */);
const mightContainNonBasicASCII = this._originalModel.mightContainNonBasicASCII();
const mightContainRTL = this._originalModel.mightContainRTL();
const lineHeight = modifiedEditorOptions.get(57 /* lineHeight */);
const layoutInfo = modifiedEditorOptions.get(129 /* layoutInfo */);
const lineDecorationsWidth = layoutInfo.decorationsWidth;
const stopRenderingLineAfter = modifiedEditorOptions.get(104 /* stopRenderingLineAfter */);
const renderWhitespace = modifiedEditorOptions.get(87 /* renderWhitespace */);
const renderControlCharacters = modifiedEditorOptions.get(81 /* renderControlCharacters */);
const fontLigatures = modifiedEditorOptions.get(42 /* fontLigatures */);
const lineBreaks = this._lineBreaksComputer.finalize();
let lineBreakIndex = 0;
for (let i = 0; i < this._pendingLineChange.length; i++) {
const lineChange = this._pendingLineChange[i];
const viewZone = this._pendingViewZones[i];
const domNode = viewZone.domNode;
configuration_1.Configuration.applyFontInfoSlow(domNode, fontInfo);
const marginDomNode = viewZone.marginDomNode;
configuration_1.Configuration.applyFontInfoSlow(marginDomNode, fontInfo);
const decorations = [];
if (lineChange.charChanges) {
for (const charChange of lineChange.charChanges) {
if (isChangeOrDelete(charChange)) {
decorations.push(new viewModel_1.InlineDecoration(new range_1.Range(charChange.originalStartLineNumber, charChange.originalStartColumn, charChange.originalEndLineNumber, charChange.originalEndColumn), 'char-delete', 0 /* Regular */));
}
}
}
const hasCharChanges = (decorations.length > 0);
const sb = (0, stringBuilder_1.createStringBuilder)(10000);
let maxCharsPerLine = 0;
let renderedLineCount = 0;
let viewLineCounts = null;
for (let lineNumber = lineChange.originalStartLineNumber; lineNumber <= lineChange.originalEndLineNumber; lineNumber++) {
const lineIndex = lineNumber - lineChange.originalStartLineNumber;
const lineTokens = this._originalModel.getLineTokens(lineNumber);
const lineContent = lineTokens.getLineContent();
const lineBreakData = lineBreaks[lineBreakIndex++];
const actualDecorations = lineDecorations_1.LineDecoration.filter(decorations, lineNumber, 1, lineContent.length + 1);
if (lineBreakData) {
let lastBreakOffset = 0;
for (const breakOffset of lineBreakData.breakOffsets) {
const viewLineTokens = lineTokens.sliceAndInflate(lastBreakOffset, breakOffset, 0);
const viewLineContent = lineContent.substring(lastBreakOffset, breakOffset);
maxCharsPerLine = Math.max(maxCharsPerLine, this._renderOriginalLine(renderedLineCount++, viewLineContent, viewLineTokens, lineDecorations_1.LineDecoration.extractWrapped(actualDecorations, lastBreakOffset, breakOffset), hasCharChanges, mightContainNonBasicASCII, mightContainRTL, fontInfo, disableMonospaceOptimizations, lineHeight, lineDecorationsWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, tabSize, sb, marginDomNode));
lastBreakOffset = breakOffset;
}
if (!viewLineCounts) {
viewLineCounts = [];
}
// make sure all lines before this one have an entry in `viewLineCounts`
while (viewLineCounts.length < lineIndex) {
viewLineCounts[viewLineCounts.length] = 1;
}
viewLineCounts[lineIndex] = lineBreakData.breakOffsets.length;
viewZone.heightInLines += (lineBreakData.breakOffsets.length - 1);
const marginDomNode2 = document.createElement('div');
marginDomNode2.className = 'line-delete';
result.original.push({
afterLineNumber: lineNumber,
afterColumn: 0,
heightInLines: lineBreakData.breakOffsets.length - 1,
domNode: createFakeLinesDiv(),
marginDomNode: marginDomNode2
});
}
else {
maxCharsPerLine = Math.max(maxCharsPerLine, this._renderOriginalLine(renderedLineCount++, lineContent, lineTokens, actualDecorations, hasCharChanges, mightContainNonBasicASCII, mightContainRTL, fontInfo, disableMonospaceOptimizations, lineHeight, lineDecorationsWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, tabSize, sb, marginDomNode));
}
}
maxCharsPerLine += scrollBeyondLastColumn;
const html = sb.build();
const trustedhtml = ttPolicy ? ttPolicy.createHTML(html) : html;
domNode.innerHTML = trustedhtml;
viewZone.minWidthInPx = (maxCharsPerLine * typicalHalfwidthCharacterWidth);
if (viewLineCounts) {
// make sure all lines have an entry in `viewLineCounts`
const cnt = lineChange.originalEndLineNumber - lineChange.originalStartLineNumber;
while (viewLineCounts.length <= cnt) {
viewLineCounts[viewLineCounts.length] = 1;
}
}
viewZone.diff.viewLineCounts = viewLineCounts;
}
result.original.sort((a, b) => {
return a.afterLineNumber - b.afterLineNumber;
});
}
_renderOriginalLine(renderedLineCount, lineContent, lineTokens, decorations, hasCharChanges, mightContainNonBasicASCII, mightContainRTL, fontInfo, disableMonospaceOptimizations, lineHeight, lineDecorationsWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, tabSize, sb, marginDomNode) {
sb.appendASCIIString('<div class="view-line');
if (!hasCharChanges) {
// No char changes
sb.appendASCIIString(' char-delete');
}
sb.appendASCIIString('" style="top:');
sb.appendASCIIString(String(renderedLineCount * lineHeight));
sb.appendASCIIString('px;width:1000000px;">');
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((fontInfo.isMonospace && !disableMonospaceOptimizations), fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII, containsRTL, 0, lineTokens, decorations, tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures !== editorOptions_1.EditorFontLigatures.OFF, null // Send no selections, original line cannot be selected
), sb);
sb.appendASCIIString('</div>');
if (this._renderIndicators) {
const marginElement = document.createElement('div');
marginElement.className = `delete-sign ${themeService_1.ThemeIcon.asClassName(diffRemoveIcon)}`;
marginElement.setAttribute('style', `position:absolute;top:${renderedLineCount * lineHeight}px;width:${lineDecorationsWidth}px;height:${lineHeight}px;right:0;`);
marginDomNode.appendChild(marginElement);
}
return output.characterMapping.getAbsoluteOffset(output.characterMapping.length);
}
}
function validateDiffWordWrap(value, defaultValue) {
return (0, editorOptions_1.stringSet)(value, defaultValue, ['off', 'on', 'inherit']);
}
function isChangeOrInsert(lineChange) {
return lineChange.modifiedEndLineNumber > 0;
}
function isChangeOrDelete(lineChange) {
return lineChange.originalEndLineNumber > 0;
}
function createFakeLinesDiv() {
const r = document.createElement('div');
r.className = 'diagonal-fill';
return r;
}
function getViewRange(model, viewModel, startLineNumber, endLineNumber) {
const lineCount = model.getLineCount();
startLineNumber = Math.min(lineCount, Math.max(1, startLineNumber));
endLineNumber = Math.min(lineCount, Math.max(1, endLineNumber));
return viewModel.coordinatesConverter.convertModelRangeToViewRange(new range_1.Range(startLineNumber, model.getLineMinColumn(startLineNumber), endLineNumber, model.getLineMaxColumn(endLineNumber)));
}
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const added = theme.getColor(colorRegistry_1.diffInserted);
if (added) {
collector.addRule(`.monaco-editor .line-insert, .monaco-editor .char-insert { background-color: ${added}; }`);
collector.addRule(`.monaco-diff-editor .line-insert, .monaco-diff-editor .char-insert { background-color: ${added}; }`);
collector.addRule(`.monaco-editor .inline-added-margin-view-zone { background-color: ${added}; }`);
}
const removed = theme.getColor(colorRegistry_1.diffRemoved);
if (removed) {
collector.addRule(`.monaco-editor .line-delete, .monaco-editor .char-delete { background-color: ${removed}; }`);
collector.addRule(`.monaco-diff-editor .line-delete, .monaco-diff-editor .char-delete { background-color: ${removed}; }`);
collector.addRule(`.monaco-editor .inline-deleted-margin-view-zone { background-color: ${removed}; }`);
}
const addedOutline = theme.getColor(colorRegistry_1.diffInsertedOutline);
if (addedOutline) {
collector.addRule(`.monaco-editor .line-insert, .monaco-editor .char-insert { border: 1px ${theme.type === 'hc' ? 'dashed' : 'solid'} ${addedOutline}; }`);
}
const removedOutline = theme.getColor(colorRegistry_1.diffRemovedOutline);
if (removedOutline) {
collector.addRule(`.monaco-editor .line-delete, .monaco-editor .char-delete { border: 1px ${theme.type === 'hc' ? 'dashed' : 'solid'} ${removedOutline}; }`);
}
const shadow = theme.getColor(colorRegistry_1.scrollbarShadow);
if (shadow) {
collector.addRule(`.monaco-diff-editor.side-by-side .editor.modified { box-shadow: -6px 0 5px -5px ${shadow}; }`);
}
const border = theme.getColor(colorRegistry_1.diffBorder);
if (border) {
collector.addRule(`.monaco-diff-editor.side-by-side .editor.modified { border-left: 1px solid ${border}; }`);
}
const scrollbarSliderBackgroundColor = theme.getColor(colorRegistry_1.scrollbarSliderBackground);
if (scrollbarSliderBackgroundColor) {
collector.addRule(`
.monaco-diff-editor .diffViewport {
background: ${scrollbarSliderBackgroundColor};
}
`);
}
const scrollbarSliderHoverBackgroundColor = theme.getColor(colorRegistry_1.scrollbarSliderHoverBackground);
if (scrollbarSliderHoverBackgroundColor) {
collector.addRule(`
.monaco-diff-editor .diffViewport:hover {
background: ${scrollbarSliderHoverBackgroundColor};
}
`);
}
const scrollbarSliderActiveBackgroundColor = theme.getColor(colorRegistry_1.scrollbarSliderActiveBackground);
if (scrollbarSliderActiveBackgroundColor) {
collector.addRule(`
.monaco-diff-editor .diffViewport:active {
background: ${scrollbarSliderActiveBackgroundColor};
}
`);
}
const diffDiagonalFillColor = theme.getColor(colorRegistry_1.diffDiagonalFill);
collector.addRule(`
.monaco-editor .diagonal-fill {
background-image: linear-gradient(
-45deg,
${diffDiagonalFillColor} 12.5%,
#0000 12.5%, #0000 50%,
${diffDiagonalFillColor} 50%, ${diffDiagonalFillColor} 62.5%,
#0000 62.5%, #0000 100%
);
background-size: 8px 8px;
}
`);
});
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/find/findWidget*/], __M([0/*require*/,1/*exports*/,483/*vs/nls!vs/editor/contrib/find/findWidget*/,7/*vs/base/browser/dom*/,44/*vs/base/browser/ui/aria/aria*/,165/*vs/base/browser/ui/checkbox/checkbox*/,107/*vs/base/browser/ui/sash/sash*/,52/*vs/base/browser/ui/widget*/,15/*vs/base/common/async*/,12/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,8/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/,147/*vs/editor/contrib/find/findModel*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,585/*vs/platform/browser/contextScopedHistoryWidget*/,27/*vs/base/common/codicons*/,79/*vs/platform/theme/common/iconRegistry*/,349/*vs/css!vs/editor/contrib/find/findWidget*/]), function (require, exports, nls, dom, aria_1, checkbox_1, sash_1, widget_1, async_1, errors_1, lifecycle_1, platform, strings, range_1, findModel_1, colorRegistry_1, themeService_1, contextScopedHistoryWidget_1, codicons_1, iconRegistry_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 = void 0;
const findSelectionIcon = (0, iconRegistry_1.registerIcon)('find-selection', codicons_1.Codicon.selection, nls.localize(0, null));
const findCollapsedIcon = (0, iconRegistry_1.registerIcon)('find-collapsed', codicons_1.Codicon.chevronRight, nls.localize(1, null));
const findExpandedIcon = (0, iconRegistry_1.registerIcon)('find-expanded', codicons_1.Codicon.chevronDown, nls.localize(2, null));
exports.findReplaceIcon = (0, iconRegistry_1.registerIcon)('find-replace', codicons_1.Codicon.replace, nls.localize(3, null));
exports.findReplaceAllIcon = (0, iconRegistry_1.registerIcon)('find-replace-all', codicons_1.Codicon.replaceAll, nls.localize(4, null));
exports.findPreviousMatchIcon = (0, iconRegistry_1.registerIcon)('find-previous-match', codicons_1.Codicon.arrowUp, nls.localize(5, null));
exports.findNextMatchIcon = (0, iconRegistry_1.registerIcon)('find-next-match', codicons_1.Codicon.arrowDown, nls.localize(6, null));
const NLS_FIND_INPUT_LABEL = nls.localize(7, null);
const NLS_FIND_INPUT_PLACEHOLDER = nls.localize(8, null);
const NLS_PREVIOUS_MATCH_BTN_LABEL = nls.localize(9, null);
const NLS_NEXT_MATCH_BTN_LABEL = nls.localize(10, null);
const NLS_TOGGLE_SELECTION_FIND_TITLE = nls.localize(11, null);
const NLS_CLOSE_BTN_LABEL = nls.localize(12, null);
const NLS_REPLACE_INPUT_LABEL = nls.localize(13, null);
const NLS_REPLACE_INPUT_PLACEHOLDER = nls.localize(14, null);
const NLS_REPLACE_BTN_LABEL = nls.localize(15, null);
const NLS_REPLACE_ALL_BTN_LABEL = nls.localize(16, null);
const NLS_TOGGLE_REPLACE_MODE_BTN_LABEL = nls.localize(17, null);
const NLS_MATCHES_COUNT_LIMIT_TITLE = nls.localize(18, null, findModel_1.MATCHES_LIMIT);
exports.NLS_MATCHES_LOCATION = nls.localize(19, null);
exports.NLS_NO_RESULTS = nls.localize(20, null);
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 /* WinCtrl */ : 2048 /* 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 {
constructor(codeEditor, controller, state, contextViewProvider, keybindingService, contextKeyService, themeService, storageService, notificationService) {
super();
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 /* GLOBAL */);
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(79 /* readOnly */)) {
if (this._codeEditor.getOption(79 /* readOnly */)) {
// Hide replace part if editor becomes read only
this._state.change({ isReplaceRevealed: false }, false);
}
this._updateButtons();
}
if (e.hasChanged(129 /* layoutInfo */)) {
this._tryUpdateWidgetWidth();
}
if (e.hasChanged(2 /* accessibilitySupport */)) {
this.updateAccessibilitySupport();
}
if (e.hasChanged(33 /* find */)) {
const addExtraSpaceOnTop = this._codeEditor.getOption(33 /* 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(() => __awaiter(this, void 0, void 0, function* () {
if (this._isVisible) {
let globalBufferTerm = yield 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(33 /* find */).addExtraSpaceOnTop) {
this._viewZone = new FindWidgetViewZone(0); // Put it before the first line then users can scroll beyond the first line.
}
this._applyTheme(themeService.getColorTheme());
this._register(themeService.onDidColorThemeChange(this._applyTheme.bind(this)));
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 /* 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(79 /* 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) {
let 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
if (this._matchesCount.firstChild) {
this._matchesCount.removeChild(this._matchesCount.firstChild);
}
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(21, null, label)
: nls.localize(22, null, label, searchString);
}
if (currentMatch) {
const ariaLabel = nls.localize(23, null, 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(24, null, 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() {
let selection = this._codeEditor.getSelection();
let isSelection = selection ? (selection.startLineNumber !== selection.endLineNumber || selection.startColumn !== selection.endColumn) : false;
let 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);
let findInputIsNonEmpty = (this._state.searchString.length > 0);
let 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);
let canReplace = !this._codeEditor.getOption(79 /* 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(33 /* 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(33 /* 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(33 /* 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(33 /* 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;
}
let 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(73 /* 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;
}
}
});
}
_applyTheme(theme) {
let inputStyles = {
inputActiveOptionBorder: theme.getColor(colorRegistry_1.inputActiveOptionBorder),
inputActiveOptionBackground: theme.getColor(colorRegistry_1.inputActiveOptionBackground),
inputActiveOptionForeground: theme.getColor(colorRegistry_1.inputActiveOptionForeground),
inputBackground: theme.getColor(colorRegistry_1.inputBackground),
inputForeground: theme.getColor(colorRegistry_1.inputForeground),
inputBorder: theme.getColor(colorRegistry_1.inputBorder),
inputValidationInfoBackground: theme.getColor(colorRegistry_1.inputValidationInfoBackground),
inputValidationInfoForeground: theme.getColor(colorRegistry_1.inputValidationInfoForeground),
inputValidationInfoBorder: theme.getColor(colorRegistry_1.inputValidationInfoBorder),
inputValidationWarningBackground: theme.getColor(colorRegistry_1.inputValidationWarningBackground),
inputValidationWarningForeground: theme.getColor(colorRegistry_1.inputValidationWarningForeground),
inputValidationWarningBorder: theme.getColor(colorRegistry_1.inputValidationWarningBorder),
inputValidationErrorBackground: theme.getColor(colorRegistry_1.inputValidationErrorBackground),
inputValidationErrorForeground: theme.getColor(colorRegistry_1.inputValidationErrorForeground),
inputValidationErrorBorder: theme.getColor(colorRegistry_1.inputValidationErrorBorder),
};
this._findInput.style(inputStyles);
this._replaceInput.style(inputStyles);
this._toggleSelectionFind.style(inputStyles);
}
_tryUpdateWidgetWidth() {
if (!this._isVisible) {
return;
}
if (!dom.isInDOM(this._domNode)) {
// 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) {
let 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`;
}
if (this._resized) {
this._findInput.inputBox.layout();
let 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) {
let 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 /* Enter */)) {
this._findInput.inputBox.insertAtCursor('\n');
e.preventDefault();
return;
}
if (e.equals(2 /* Tab */)) {
if (this._isReplaceVisible) {
this._replaceInput.focus();
}
else {
this._findInput.focusOnCaseSensitive();
}
e.preventDefault();
return;
}
if (e.equals(2048 /* CtrlCmd */ | 18 /* DownArrow */)) {
this._codeEditor.focus();
e.preventDefault();
return;
}
if (e.equals(16 /* UpArrow */)) {
return stopPropagationForMultiLineUpwards(e, this._findInput.getValue(), this._findInput.domNode.querySelector('textarea'));
}
if (e.equals(18 /* DownArrow */)) {
return stopPropagationForMultiLineDownwards(e, this._findInput.getValue(), this._findInput.domNode.querySelector('textarea'));
}
}
_onReplaceInputKeyDown(e) {
if (e.equals(ctrlKeyMod | 3 /* Enter */)) {
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(25, null));
this._ctrlEnterReplaceAllWarningPrompted = true;
this._storageService.store(ctrlEnterReplaceAllWarningPromptedKey, true, 0 /* GLOBAL */, 0 /* USER */);
}
this._replaceInput.inputBox.insertAtCursor('\n');
e.preventDefault();
return;
}
if (e.equals(2 /* Tab */)) {
this._findInput.focusOnCaseSensitive();
e.preventDefault();
return;
}
if (e.equals(1024 /* Shift */ | 2 /* Tab */)) {
this._findInput.focus();
e.preventDefault();
return;
}
if (e.equals(2048 /* CtrlCmd */ | 18 /* DownArrow */)) {
this._codeEditor.focus();
e.preventDefault();
return;
}
if (e.equals(16 /* UpArrow */)) {
return stopPropagationForMultiLineUpwards(e, this._replaceInput.inputBox.value, this._replaceInput.inputBox.element.querySelector('textarea'));
}
if (e.equals(18 /* DownArrow */)) {
return stopPropagationForMultiLineDownwards(e, this._replaceInput.inputBox.value, this._replaceInput.inputBox.element.querySelector('textarea'));
}
}
// ----- sash
getVerticalSashLeft(_sash) {
return 0;
}
// ----- initialization
_keybindingLabelFor(actionId) {
let 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
}, this._contextKeyService, true));
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 /* Shift */ | 2 /* Tab */)) {
if (this._isReplaceVisible) {
this._replaceInput.focus();
e.preventDefault();
}
}
}));
this._register(this._findInput.onRegexKeyDown((e) => {
if (e.equals(2 /* 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();
// Previous button
this._prevBtn = this._register(new SimpleButton({
label: NLS_PREVIOUS_MATCH_BTN_LABEL + this._keybindingLabelFor(findModel_1.FIND_IDS.PreviousMatchFindAction),
icon: exports.findPreviousMatchIcon,
onTrigger: () => {
this._codeEditor.getAction(findModel_1.FIND_IDS.PreviousMatchFindAction).run().then(undefined, errors_1.onUnexpectedError);
}
}));
// Next button
this._nextBtn = this._register(new SimpleButton({
label: NLS_NEXT_MATCH_BTN_LABEL + this._keybindingLabelFor(findModel_1.FIND_IDS.NextMatchFindAction),
icon: exports.findNextMatchIcon,
onTrigger: () => {
this._codeEditor.getAction(findModel_1.FIND_IDS.NextMatchFindAction).run().then(undefined, errors_1.onUnexpectedError);
}
}));
let 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 checkbox_1.Checkbox({
icon: findSelectionIcon,
title: NLS_TOGGLE_SELECTION_FIND_TITLE + this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleSearchScopeCommand),
isChecked: false
}));
this._register(this._toggleSelectionFind.onChange(() => {
if (this._toggleSelectionFind.checked) {
if (this._codeEditor.hasModel()) {
let 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));
}
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,
onTrigger: () => {
this._state.change({ isRevealed: false, searchScope: null }, false);
},
onKeyDown: (e) => {
if (e.equals(2 /* Tab */)) {
if (this._isReplaceVisible) {
if (this._replaceBtn.isEnabled()) {
this._replaceBtn.focus();
}
else {
this._codeEditor.focus();
}
e.preventDefault();
}
}
}
}));
actionsContainer.appendChild(this._closeBtn.domNode);
// 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
}, 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 /* 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();
}
}));
// Replace one button
this._replaceBtn = this._register(new SimpleButton({
label: NLS_REPLACE_BTN_LABEL + this._keybindingLabelFor(findModel_1.FIND_IDS.ReplaceOneAction),
icon: exports.findReplaceIcon,
onTrigger: () => {
this._controller.replace();
},
onKeyDown: (e) => {
if (e.equals(1024 /* Shift */ | 2 /* Tab */)) {
this._closeBtn.focus();
e.preventDefault();
}
}
}));
// 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,
onTrigger: () => {
this._controller.replaceAll();
}
}));
let 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._toggleReplaceBtn.setExpanded(this._isReplaceVisible);
// Widget
this._domNode = document.createElement('div');
this._domNode.className = 'editor-widget find-widget';
this._domNode.setAttribute('aria-hidden', 'true');
// 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(replacePart);
this._resizeSash = new sash_1.Sash(this._domNode, this, { orientation: 0 /* 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;
let 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 /* accessibilitySupport */);
this._findInput.setFocusInputOnOptionClick(value !== 2 /* Enabled */);
}
}
exports.FindWidget = FindWidget;
FindWidget.ID = 'editor.contrib.findWidget';
class SimpleButton extends widget_1.Widget {
constructor(opts) {
super();
this._opts = opts;
let className = 'button';
if (this._opts.className) {
className = className + ' ' + this._opts.className;
}
if (this._opts.icon) {
className = className + ' ' + themeService_1.ThemeIcon.asClassName(this._opts.icon);
}
this._domNode = document.createElement('div');
this._domNode.title = this._opts.label;
this._domNode.tabIndex = 0;
this._domNode.className = className;
this._domNode.setAttribute('role', 'button');
this._domNode.setAttribute('aria-label', this._opts.label);
this.onclick(this._domNode, (e) => {
this._opts.onTrigger();
e.preventDefault();
});
this.onkeydown(this._domNode, (e) => {
if (e.equals(10 /* Space */) || e.equals(3 /* Enter */)) {
this._opts.onTrigger();
e.preventDefault();
return;
}
if (this._opts.onKeyDown) {
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(...themeService_1.ThemeIcon.asClassNameArray(findCollapsedIcon));
this._domNode.classList.add(...themeService_1.ThemeIcon.asClassNameArray(findExpandedIcon));
}
else {
this._domNode.classList.remove(...themeService_1.ThemeIcon.asClassNameArray(findExpandedIcon));
this._domNode.classList.add(...themeService_1.ThemeIcon.asClassNameArray(findCollapsedIcon));
}
}
}
exports.SimpleButton = SimpleButton;
// theming
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const addBackgroundColorRule = (selector, color) => {
if (color) {
collector.addRule(`.monaco-editor ${selector} { background-color: ${color}; }`);
}
};
addBackgroundColorRule('.findMatch', theme.getColor(colorRegistry_1.editorFindMatchHighlight));
addBackgroundColorRule('.currentFindMatch', theme.getColor(colorRegistry_1.editorFindMatch));
addBackgroundColorRule('.findScope', theme.getColor(colorRegistry_1.editorFindRangeHighlight));
const widgetBackground = theme.getColor(colorRegistry_1.editorWidgetBackground);
addBackgroundColorRule('.find-widget', widgetBackground);
const widgetShadowColor = theme.getColor(colorRegistry_1.widgetShadow);
if (widgetShadowColor) {
collector.addRule(`.monaco-editor .find-widget { box-shadow: 0 0 8px 2px ${widgetShadowColor}; }`);
}
const findMatchHighlightBorder = theme.getColor(colorRegistry_1.editorFindMatchHighlightBorder);
if (findMatchHighlightBorder) {
collector.addRule(`.monaco-editor .findMatch { border: 1px ${theme.type === 'hc' ? 'dotted' : 'solid'} ${findMatchHighlightBorder}; box-sizing: border-box; }`);
}
const findMatchBorder = theme.getColor(colorRegistry_1.editorFindMatchBorder);
if (findMatchBorder) {
collector.addRule(`.monaco-editor .currentFindMatch { border: 2px solid ${findMatchBorder}; padding: 1px; box-sizing: border-box; }`);
}
const findRangeHighlightBorder = theme.getColor(colorRegistry_1.editorFindRangeHighlightBorder);
if (findRangeHighlightBorder) {
collector.addRule(`.monaco-editor .findScope { border: 1px ${theme.type === 'hc' ? 'dashed' : 'solid'} ${findRangeHighlightBorder}; }`);
}
const hcBorder = theme.getColor(colorRegistry_1.contrastBorder);
if (hcBorder) {
collector.addRule(`.monaco-editor .find-widget { border: 1px solid ${hcBorder}; }`);
}
const foreground = theme.getColor(colorRegistry_1.editorWidgetForeground);
if (foreground) {
collector.addRule(`.monaco-editor .find-widget { color: ${foreground}; }`);
}
const error = theme.getColor(colorRegistry_1.errorForeground);
if (error) {
collector.addRule(`.monaco-editor .find-widget.no-results .matchesCount { color: ${error}; }`);
}
const resizeBorderBackground = theme.getColor(colorRegistry_1.editorWidgetResizeBorder);
if (resizeBorderBackground) {
collector.addRule(`.monaco-editor .find-widget .monaco-sash { background-color: ${resizeBorderBackground}; }`);
}
else {
const border = theme.getColor(colorRegistry_1.editorWidgetBorder);
if (border) {
collector.addRule(`.monaco-editor .find-widget .monaco-sash { background-color: ${border}; }`);
}
}
// This rule is used to override the outline color for synthetic-focus find input.
const focusOutline = theme.getColor(colorRegistry_1.focusBorder);
if (focusOutline) {
collector.addRule(`.monaco-editor .find-widget .monaco-inputbox.synthetic-focus { outline-color: ${focusOutline}; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/find/findController*/], __M([0/*require*/,1/*exports*/,482/*vs/nls!vs/editor/contrib/find/findController*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,14/*vs/editor/browser/editorExtensions*/,25/*vs/editor/common/editorContextKeys*/,147/*vs/editor/contrib/find/findModel*/,613/*vs/editor/contrib/find/findOptionsWidget*/,614/*vs/editor/contrib/find/findState*/,672/*vs/editor/contrib/find/findWidget*/,33/*vs/platform/actions/common/actions*/,86/*vs/platform/clipboard/common/clipboardService*/,16/*vs/platform/contextkey/common/contextkey*/,69/*vs/platform/contextview/browser/contextView*/,37/*vs/platform/keybinding/common/keybinding*/,71/*vs/platform/storage/common/storage*/,11/*vs/platform/theme/common/themeService*/,34/*vs/platform/notification/common/notification*/]), function (require, exports, nls, async_1, lifecycle_1, strings, editorExtensions_1, editorContextKeys_1, findModel_1, findOptionsWidget_1, findState_1, findWidget_1, actions_1, clipboardService_1, contextkey_1, contextView_1, keybinding_1, storage_1, themeService_1, notification_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StartFindReplaceAction = exports.PreviousSelectionMatchFindAction = exports.NextSelectionMatchFindAction = exports.SelectionMatchFindAction = exports.PreviousMatchFindAction = exports.NextMatchFindAction = exports.MatchFindAction = exports.StartFindWithSelectionAction = exports.StartFindAction = exports.FindController = exports.CommonFindController = exports.getSelectionSearchString = void 0;
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;
}
exports.getSelectionSearchString = getSelectionSearchString;
let CommonFindController = class CommonFindController extends lifecycle_1.Disposable {
constructor(editor, contextKeyService, storageService, clipboardService) {
super();
this._editor = editor;
this._findWidgetVisible = findModel_1.CONTEXT_FIND_WIDGET_VISIBLE.bindTo(contextKeyService);
this._contextKeyService = contextKeyService;
this._storageService = storageService;
this._clipboardService = clipboardService;
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(() => {
let shouldRestartFind = (this._editor.getModel() && this._state.isRevealed);
this.disposeModel();
this._state.change({
searchScope: null,
matchCase: this._storageService.getBoolean('editor.matchCase', 1 /* WORKSPACE */, false),
wholeWord: this._storageService.getBoolean('editor.wholeWord', 1 /* WORKSPACE */, false),
isRegex: this._storageService.getBoolean('editor.isRegex', 1 /* WORKSPACE */, false),
preserveCase: this._storageService.getBoolean('editor.preserveCase', 1 /* WORKSPACE */, false)
}, false);
if (shouldRestartFind) {
this._start({
forceRevealReplace: false,
seedSearchStringFromSelection: 'none',
seedSearchStringFromNonEmptySelection: false,
seedSearchStringFromGlobalClipboard: false,
shouldFocus: 0 /* NoFocusChange */,
shouldAnimate: false,
updateSearchScope: false,
loop: this._editor.getOption(33 /* find */).loop
});
}
}));
}
get editor() {
return this._editor;
}
static get(editor) {
return editor.getContribution(CommonFindController.ID);
}
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 /* WORKSPACE */, 0 /* USER */);
}
if (e.wholeWord) {
this._storageService.store('editor.wholeWord', this._state.actualWholeWord, 1 /* WORKSPACE */, 0 /* USER */);
}
if (e.matchCase) {
this._storageService.store('editor.matchCase', this._state.actualMatchCase, 1 /* WORKSPACE */, 0 /* USER */);
}
if (e.preserveCase) {
this._storageService.store('editor.preserveCase', this._state.actualPreserveCase, 1 /* WORKSPACE */, 0 /* USER */);
}
}
loadQueryState() {
this._state.change({
matchCase: this._storageService.getBoolean('editor.matchCase', 1 /* WORKSPACE */, this._state.matchCase),
wholeWord: this._storageService.getBoolean('editor.wholeWord', 1 /* WORKSPACE */, this._state.wholeWord),
isRegex: this._storageService.getBoolean('editor.isRegex', 1 /* WORKSPACE */, this._state.isRegex),
preserveCase: this._storageService.getBoolean('editor.preserveCase', 1 /* 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.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
}
_start(opts) {
return __awaiter(this, void 0, void 0, function* () {
this.disposeModel();
if (!this._editor.hasModel()) {
// cannot do anything with an editor that doesn't have a model...
return;
}
let stateChanges = {
isRevealed: true
};
if (opts.seedSearchStringFromSelection === 'single') {
let 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) {
let selectionSearchString = getSelectionSearchString(this._editor, opts.seedSearchStringFromSelection);
if (selectionSearchString) {
stateChanges.searchString = selectionSearchString;
}
}
if (!stateChanges.searchString && opts.seedSearchStringFromGlobalClipboard) {
let selectionSearchString = yield 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 = true;
}
else if (!this._findWidgetVisible.get()) {
stateChanges.isReplaceRevealed = false;
}
if (opts.updateSearchScope) {
let 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) {
return this._start(opts);
}
moveToNextMatch() {
if (this._model) {
this._model.moveToNextMatch();
return true;
}
return false;
}
moveToPrevMatch() {
if (this._model) {
this._model.moveToPrevMatch();
return true;
}
return false;
}
replace() {
if (this._model) {
this._model.replace();
return true;
}
return false;
}
replaceAll() {
if (this._model) {
this._model.replaceAll();
return true;
}
return false;
}
selectAllMatches() {
if (this._model) {
this._model.selectAllMatches();
this._editor.focus();
return true;
}
return false;
}
getGlobalBufferTerm() {
return __awaiter(this, void 0, void 0, function* () {
if (this._editor.getOption(33 /* find */).globalFindClipboard
&& this._editor.hasModel()
&& !this._editor.getModel().isTooLargeForSyncing()) {
return this._clipboardService.readFindText();
}
return '';
});
}
setGlobalBufferTerm(text) {
if (this._editor.getOption(33 /* find */).globalFindClipboard
&& this._editor.hasModel()
&& !this._editor.getModel().isTooLargeForSyncing()) {
// intentionally not awaited
this._clipboardService.writeFindText(text);
}
}
};
CommonFindController.ID = 'editor.contrib.findController';
CommonFindController = __decorate([
__param(1, contextkey_1.IContextKeyService),
__param(2, storage_1.IStorageService),
__param(3, clipboardService_1.IClipboardService)
], CommonFindController);
exports.CommonFindController = CommonFindController;
let FindController = class FindController extends CommonFindController {
constructor(editor, _contextViewService, _contextKeyService, _keybindingService, _themeService, _notificationService, _storageService, clipboardService) {
super(editor, _contextKeyService, _storageService, clipboardService);
this._contextViewService = _contextViewService;
this._keybindingService = _keybindingService;
this._themeService = _themeService;
this._notificationService = _notificationService;
this._widget = null;
this._findOptionsWidget = null;
}
_start(opts) {
const _super = Object.create(null, {
_start: { get: () => super._start }
});
return __awaiter(this, void 0, void 0, function* () {
if (!this._widget) {
this._createFindWidget();
}
const selection = this._editor.getSelection();
let updateSearchScope = false;
switch (this._editor.getOption(33 /* 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 = updateSearchScope;
yield _super._start.call(this, opts);
if (this._widget) {
if (opts.shouldFocus === 2 /* FocusReplaceInput */) {
this._widget.focusReplaceInput();
}
else if (opts.shouldFocus === 1 /* 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._findOptionsWidget = this._register(new findOptionsWidget_1.FindOptionsWidget(this._editor, this._state, this._keybindingService, this._themeService));
}
};
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)
], FindController);
exports.FindController = FindController;
exports.StartFindAction = (0, editorExtensions_1.registerMultiEditorAction)(new editorExtensions_1.MultiEditorAction({
id: findModel_1.FIND_IDS.StartFindAction,
label: nls.localize(0, null),
alias: 'Find',
precondition: contextkey_1.ContextKeyExpr.or(editorContextKeys_1.EditorContextKeys.focus, contextkey_1.ContextKeyExpr.has('editorIsOpen')),
kbOpts: {
kbExpr: null,
primary: 2048 /* CtrlCmd */ | 36 /* KEY_F */,
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarEditMenu,
group: '3_find',
title: nls.localize(1, null),
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(33 /* find */).seedSearchStringFromSelection !== 'never' ? 'single' : 'none',
seedSearchStringFromNonEmptySelection: editor.getOption(33 /* find */).seedSearchStringFromSelection === 'selection',
seedSearchStringFromGlobalClipboard: editor.getOption(33 /* find */).globalFindClipboard,
shouldFocus: 1 /* FocusFindInput */,
shouldAnimate: true,
updateSearchScope: false,
loop: editor.getOption(33 /* find */).loop
});
});
class StartFindWithSelectionAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: findModel_1.FIND_IDS.StartFindWithSelection,
label: nls.localize(2, null),
alias: 'Find With Selection',
precondition: undefined,
kbOpts: {
kbExpr: null,
primary: 0,
mac: {
primary: 2048 /* CtrlCmd */ | 35 /* KEY_E */,
},
weight: 100 /* EditorContrib */
}
});
}
run(accessor, editor) {
return __awaiter(this, void 0, void 0, function* () {
let controller = CommonFindController.get(editor);
if (controller) {
yield controller.start({
forceRevealReplace: false,
seedSearchStringFromSelection: 'multiple',
seedSearchStringFromNonEmptySelection: false,
seedSearchStringFromGlobalClipboard: false,
shouldFocus: 0 /* NoFocusChange */,
shouldAnimate: true,
updateSearchScope: false,
loop: editor.getOption(33 /* find */).loop
});
controller.setGlobalBufferTerm(controller.getState().searchString);
}
});
}
}
exports.StartFindWithSelectionAction = StartFindWithSelectionAction;
class MatchFindAction extends editorExtensions_1.EditorAction {
run(accessor, editor) {
return __awaiter(this, void 0, void 0, function* () {
let controller = CommonFindController.get(editor);
if (controller && !this._run(controller)) {
yield controller.start({
forceRevealReplace: false,
seedSearchStringFromSelection: (controller.getState().searchString.length === 0) && editor.getOption(33 /* find */).seedSearchStringFromSelection !== 'never' ? 'single' : 'none',
seedSearchStringFromNonEmptySelection: editor.getOption(33 /* find */).seedSearchStringFromSelection === 'selection',
seedSearchStringFromGlobalClipboard: true,
shouldFocus: 0 /* NoFocusChange */,
shouldAnimate: true,
updateSearchScope: false,
loop: editor.getOption(33 /* find */).loop
});
this._run(controller);
}
});
}
}
exports.MatchFindAction = MatchFindAction;
class NextMatchFindAction extends MatchFindAction {
constructor() {
super({
id: findModel_1.FIND_IDS.NextMatchFindAction,
label: nls.localize(3, null),
alias: 'Find Next',
precondition: undefined,
kbOpts: [{
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 61 /* F3 */,
mac: { primary: 2048 /* CtrlCmd */ | 37 /* KEY_G */, secondary: [61 /* F3 */] },
weight: 100 /* EditorContrib */
}, {
kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, findModel_1.CONTEXT_FIND_INPUT_FOCUSED),
primary: 3 /* Enter */,
weight: 100 /* 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(4, null),
alias: 'Find Previous',
precondition: undefined,
kbOpts: [{
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 1024 /* Shift */ | 61 /* F3 */,
mac: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 37 /* KEY_G */, secondary: [1024 /* Shift */ | 61 /* F3 */] },
weight: 100 /* EditorContrib */
}, {
kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, findModel_1.CONTEXT_FIND_INPUT_FOCUSED),
primary: 1024 /* Shift */ | 3 /* Enter */,
weight: 100 /* EditorContrib */
}
]
});
}
_run(controller) {
return controller.moveToPrevMatch();
}
}
exports.PreviousMatchFindAction = PreviousMatchFindAction;
class SelectionMatchFindAction extends editorExtensions_1.EditorAction {
run(accessor, editor) {
return __awaiter(this, void 0, void 0, function* () {
let controller = CommonFindController.get(editor);
if (!controller) {
return;
}
const seedSearchStringFromNonEmptySelection = editor.getOption(33 /* find */).seedSearchStringFromSelection === 'selection';
let selectionSearchString = null;
if (editor.getOption(33 /* find */).seedSearchStringFromSelection !== 'never') {
selectionSearchString = getSelectionSearchString(editor, 'single', seedSearchStringFromNonEmptySelection);
}
if (selectionSearchString) {
controller.setSearchString(selectionSearchString);
}
if (!this._run(controller)) {
yield controller.start({
forceRevealReplace: false,
seedSearchStringFromSelection: editor.getOption(33 /* find */).seedSearchStringFromSelection !== 'never' ? 'single' : 'none',
seedSearchStringFromNonEmptySelection: seedSearchStringFromNonEmptySelection,
seedSearchStringFromGlobalClipboard: false,
shouldFocus: 0 /* NoFocusChange */,
shouldAnimate: true,
updateSearchScope: false,
loop: editor.getOption(33 /* find */).loop
});
this._run(controller);
}
});
}
}
exports.SelectionMatchFindAction = SelectionMatchFindAction;
class NextSelectionMatchFindAction extends SelectionMatchFindAction {
constructor() {
super({
id: findModel_1.FIND_IDS.NextSelectionMatchFindAction,
label: nls.localize(5, null),
alias: 'Find Next Selection',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 2048 /* CtrlCmd */ | 61 /* F3 */,
weight: 100 /* EditorContrib */
}
});
}
_run(controller) {
return controller.moveToNextMatch();
}
}
exports.NextSelectionMatchFindAction = NextSelectionMatchFindAction;
class PreviousSelectionMatchFindAction extends SelectionMatchFindAction {
constructor() {
super({
id: findModel_1.FIND_IDS.PreviousSelectionMatchFindAction,
label: nls.localize(6, null),
alias: 'Find Previous Selection',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 61 /* F3 */,
weight: 100 /* 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(7, null),
alias: 'Replace',
precondition: contextkey_1.ContextKeyExpr.or(editorContextKeys_1.EditorContextKeys.focus, contextkey_1.ContextKeyExpr.has('editorIsOpen')),
kbOpts: {
kbExpr: null,
primary: 2048 /* CtrlCmd */ | 38 /* KEY_H */,
mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 36 /* KEY_F */ },
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarEditMenu,
group: '3_find',
title: nls.localize(8, null),
order: 2
}
}));
exports.StartFindReplaceAction.addImplementation(0, (accessor, editor, args) => {
if (!editor.hasModel() || editor.getOption(79 /* 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(33 /* 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 /* FocusReplaceInput */ : 1 /* FocusFindInput */;
return controller.start({
forceRevealReplace: true,
seedSearchStringFromSelection: seedSearchStringFromSelection ? 'single' : 'none',
seedSearchStringFromNonEmptySelection: editor.getOption(33 /* find */).seedSearchStringFromSelection === 'selection',
seedSearchStringFromGlobalClipboard: editor.getOption(33 /* find */).seedSearchStringFromSelection !== 'never',
shouldFocus: shouldFocus,
shouldAnimate: true,
updateSearchScope: false,
loop: editor.getOption(33 /* find */).loop
});
});
(0, editorExtensions_1.registerEditorContribution)(CommonFindController.ID, FindController);
(0, editorExtensions_1.registerEditorAction)(StartFindWithSelectionAction);
(0, editorExtensions_1.registerEditorAction)(NextMatchFindAction);
(0, editorExtensions_1.registerEditorAction)(PreviousMatchFindAction);
(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 /* EditorContrib */ + 5,
kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, contextkey_1.ContextKeyExpr.not('isComposing')),
primary: 9 /* Escape */,
secondary: [1024 /* Shift */ | 9 /* Escape */]
}
}));
(0, editorExtensions_1.registerEditorCommand)(new FindCommand({
id: findModel_1.FIND_IDS.ToggleCaseSensitiveCommand,
precondition: undefined,
handler: x => x.toggleCaseSensitive(),
kbOpts: {
weight: 100 /* 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 /* 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 /* 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 /* 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 /* 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 /* EditorContrib */ + 5,
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 22 /* KEY_1 */
}
}));
(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 /* EditorContrib */ + 5,
kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, findModel_1.CONTEXT_REPLACE_INPUT_FOCUSED),
primary: 3 /* 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 /* EditorContrib */ + 5,
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 3 /* 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 /* EditorContrib */ + 5,
kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, findModel_1.CONTEXT_REPLACE_INPUT_FOCUSED),
primary: undefined,
mac: {
primary: 2048 /* CtrlCmd */ | 3 /* 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 /* EditorContrib */ + 5,
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 512 /* Alt */ | 3 /* 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[673/*vs/editor/contrib/folding/foldingDecorations*/], __M([0/*require*/,1/*exports*/,31/*vs/editor/common/model/textModel*/,27/*vs/base/common/codicons*/,485/*vs/nls!vs/editor/contrib/folding/foldingDecorations*/,79/*vs/platform/theme/common/iconRegistry*/,11/*vs/platform/theme/common/themeService*/]), function (require, exports, textModel_1, codicons_1, nls_1, iconRegistry_1, themeService_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FoldingDecorationProvider = exports.foldingCollapsedIcon = exports.foldingExpandedIcon = void 0;
exports.foldingExpandedIcon = (0, iconRegistry_1.registerIcon)('folding-expanded', codicons_1.Codicon.chevronDown, (0, nls_1.localize)(0, null));
exports.foldingCollapsedIcon = (0, iconRegistry_1.registerIcon)('folding-collapsed', codicons_1.Codicon.chevronRight, (0, nls_1.localize)(1, null));
class FoldingDecorationProvider {
constructor(editor) {
this.editor = editor;
this.autoHideFoldingControls = true;
this.showFoldingHighlights = true;
}
getDecorationOption(isCollapsed, isHidden) {
if (isHidden) {
return FoldingDecorationProvider.HIDDEN_RANGE_DECORATION;
}
if (isCollapsed) {
return this.showFoldingHighlights ? FoldingDecorationProvider.COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION : FoldingDecorationProvider.COLLAPSED_VISUAL_DECORATION;
}
else if (this.autoHideFoldingControls) {
return FoldingDecorationProvider.EXPANDED_AUTO_HIDE_VISUAL_DECORATION;
}
else {
return FoldingDecorationProvider.EXPANDED_VISUAL_DECORATION;
}
}
deltaDecorations(oldDecorations, newDecorations) {
return this.editor.deltaDecorations(oldDecorations, newDecorations);
}
changeDecorations(callback) {
return this.editor.changeDecorations(callback);
}
}
exports.FoldingDecorationProvider = FoldingDecorationProvider;
FoldingDecorationProvider.COLLAPSED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
description: 'folding-collapsed-visual-decoration',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
afterContentClassName: 'inline-folded',
isWholeLine: true,
firstLineDecorationClassName: themeService_1.ThemeIcon.asClassName(exports.foldingCollapsedIcon)
});
FoldingDecorationProvider.COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
description: 'folding-collapsed-highlighted-visual-decoration',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
afterContentClassName: 'inline-folded',
className: 'folded-background',
isWholeLine: true,
firstLineDecorationClassName: themeService_1.ThemeIcon.asClassName(exports.foldingCollapsedIcon)
});
FoldingDecorationProvider.EXPANDED_AUTO_HIDE_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
description: 'folding-expanded-auto-hide-visual-decoration',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
isWholeLine: true,
firstLineDecorationClassName: themeService_1.ThemeIcon.asClassName(exports.foldingExpandedIcon)
});
FoldingDecorationProvider.EXPANDED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
description: 'folding-expanded-visual-decoration',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
isWholeLine: true,
firstLineDecorationClassName: 'alwaysShowFoldIcons ' + themeService_1.ThemeIcon.asClassName(exports.foldingExpandedIcon)
});
FoldingDecorationProvider.HIDDEN_RANGE_DECORATION = textModel_1.ModelDecorationOptions.register({
description: 'folding-hidden-range-decoration',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[674/*vs/editor/contrib/folding/folding*/], __M([0/*require*/,1/*exports*/,484/*vs/nls!vs/editor/contrib/folding/folding*/,20/*vs/base/common/types*/,8/*vs/base/common/strings*/,15/*vs/base/common/async*/,41/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,413/*vs/editor/contrib/folding/foldingModel*/,673/*vs/editor/contrib/folding/foldingDecorations*/,25/*vs/editor/common/editorContextKeys*/,414/*vs/editor/contrib/folding/hiddenRangeModel*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/,555/*vs/editor/contrib/folding/indentRangeProvider*/,18/*vs/editor/common/modes*/,227/*vs/editor/contrib/folding/syntaxRangeProvider*/,415/*vs/editor/contrib/folding/intializingRangeProvider*/,12/*vs/base/common/errors*/,16/*vs/platform/contextkey/common/contextkey*/,11/*vs/platform/theme/common/themeService*/,22/*vs/platform/theme/common/colorRegistry*/,66/*vs/editor/browser/core/editorState*/,350/*vs/css!vs/editor/contrib/folding/folding*/]), function (require, exports, nls, types, strings_1, async_1, keyCodes_1, lifecycle_1, editorExtensions_1, foldingModel_1, foldingDecorations_1, editorContextKeys_1, hiddenRangeModel_1, languageConfigurationRegistry_1, indentRangeProvider_1, modes_1, syntaxRangeProvider_1, intializingRangeProvider_1, errors_1, contextkey_1, themeService_1, colorRegistry_1, editorState_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.editorFoldForeground = exports.foldBackgroundBackground = exports.FoldingController = void 0;
const CONTEXT_FOLDING_ENABLED = new contextkey_1.RawContextKey('foldingEnabled', false);
let FoldingController = class FoldingController extends lifecycle_1.Disposable {
constructor(editor, contextKeyService) {
super();
this.contextKeyService = contextKeyService;
this.localToDispose = this._register(new lifecycle_1.DisposableStore());
this.editor = editor;
const options = this.editor.getOptions();
this._isEnabled = options.get(35 /* folding */);
this._useFoldingProviders = options.get(36 /* foldingStrategy */) !== 'indentation';
this._unfoldOnClickAfterEndOfLine = options.get(39 /* unfoldOnClickAfterEndOfLine */);
this._restoringViewState = false;
this._currentModelHasFoldedImports = false;
this._foldingImportsByDefault = options.get(38 /* foldingImportsByDefault */);
this.foldingModel = null;
this.hiddenRangeModel = null;
this.rangeProvider = null;
this.foldingRegionPromise = null;
this.foldingStateMemento = null;
this.foldingModelPromise = null;
this.updateScheduler = null;
this.cursorChangedScheduler = null;
this.mouseDownInfo = null;
this.foldingDecorationProvider = new foldingDecorations_1.FoldingDecorationProvider(editor);
this.foldingDecorationProvider.autoHideFoldingControls = options.get(98 /* showFoldingControls */) === 'mouseover';
this.foldingDecorationProvider.showFoldingHighlights = options.get(37 /* 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(35 /* folding */)) {
this._isEnabled = this.editor.getOptions().get(35 /* folding */);
this.foldingEnabled.set(this._isEnabled);
this.onModelChanged();
}
if (e.hasChanged(98 /* showFoldingControls */) || e.hasChanged(37 /* foldingHighlight */)) {
const options = this.editor.getOptions();
this.foldingDecorationProvider.autoHideFoldingControls = options.get(98 /* showFoldingControls */) === 'mouseover';
this.foldingDecorationProvider.showFoldingHighlights = options.get(37 /* foldingHighlight */);
this.onModelContentChanged();
}
if (e.hasChanged(36 /* foldingStrategy */)) {
this._useFoldingProviders = this.editor.getOptions().get(36 /* foldingStrategy */) !== 'indentation';
this.onFoldingStrategyChanged();
}
if (e.hasChanged(39 /* unfoldOnClickAfterEndOfLine */)) {
this._unfoldOnClickAfterEndOfLine = this.editor.getOptions().get(39 /* unfoldOnClickAfterEndOfLine */);
}
if (e.hasChanged(38 /* foldingImportsByDefault */)) {
this._foldingImportsByDefault = this.editor.getOptions().get(38 /* foldingImportsByDefault */);
}
}));
this.onModelChanged();
}
static get(editor) {
return editor.getContribution(FoldingController.ID);
}
/**
* Store view state.
*/
saveViewState() {
let model = this.editor.getModel();
if (!model || !this._isEnabled || model.isTooLargeForTokenization()) {
return {};
}
if (this.foldingModel) { // disposed ?
let collapsedRegions = this.foldingModel.isInitialized ? this.foldingModel.getMemento() : this.hiddenRangeModel.getMemento();
let provider = this.rangeProvider ? this.rangeProvider.id : undefined;
return { collapsedRegions, lineCount: model.getLineCount(), provider, foldedImports: this._currentModelHasFoldedImports };
}
return undefined;
}
/**
* Restore view state.
*/
restoreViewState(state) {
let model = this.editor.getModel();
if (!model || !this._isEnabled || model.isTooLargeForTokenization() || !this.hiddenRangeModel) {
return;
}
if (!state || state.lineCount !== model.getLineCount()) {
return;
}
this._currentModelHasFoldedImports = !!state.foldedImports;
if (!state.collapsedRegions) {
return;
}
if (state.provider === syntaxRangeProvider_1.ID_SYNTAX_PROVIDER || state.provider === intializingRangeProvider_1.ID_INIT_PROVIDER) {
this.foldingStateMemento = state;
}
const collapsedRegions = state.collapsedRegions;
// set the hidden ranges right away, before waiting for the folding model.
if (this.hiddenRangeModel.applyMemento(collapsedRegions)) {
const foldingModel = this.getFoldingModel();
if (foldingModel) {
foldingModel.then(foldingModel => {
if (foldingModel) {
this._restoringViewState = true;
try {
foldingModel.applyMemento(collapsedRegions);
}
finally {
this._restoringViewState = false;
}
}
}).then(undefined, errors_1.onUnexpectedError);
}
}
}
onModelChanged() {
this.localToDispose.clear();
let 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(200);
this.cursorChangedScheduler = new async_1.RunOnceScheduler(() => this.revealCursor(), 200);
this.localToDispose.add(this.cursorChangedScheduler);
this.localToDispose.add(modes_1.FoldingRangeProviderRegistry.onDidChange(() => this.onFoldingStrategyChanged()));
this.localToDispose.add(this.editor.onDidChangeModelLanguageConfiguration(() => this.onFoldingStrategyChanged())); // covers model language changes as well
this.localToDispose.add(this.editor.onDidChangeModelContent(() => this.onModelContentChanged()));
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;
}
if (this.updateScheduler) {
this.updateScheduler.cancel();
}
this.updateScheduler = null;
this.foldingModel = null;
this.foldingModelPromise = null;
this.hiddenRangeModel = null;
this.cursorChangedScheduler = null;
this.foldingStateMemento = null;
if (this.rangeProvider) {
this.rangeProvider.dispose();
}
this.rangeProvider = null;
}
});
this.onModelContentChanged();
}
onFoldingStrategyChanged() {
if (this.rangeProvider) {
this.rangeProvider.dispose();
}
this.rangeProvider = null;
this.onModelContentChanged();
}
getRangeProvider(editorModel) {
if (this.rangeProvider) {
return this.rangeProvider;
}
this.rangeProvider = new indentRangeProvider_1.IndentRangeProvider(editorModel); // fallback
if (this._useFoldingProviders && this.foldingModel) {
let foldingProviders = modes_1.FoldingRangeProviderRegistry.ordered(this.foldingModel.textModel);
if (foldingProviders.length === 0 && this.foldingStateMemento && this.foldingStateMemento.collapsedRegions) {
const rangeProvider = this.rangeProvider = new intializingRangeProvider_1.InitializingRangeProvider(editorModel, this.foldingStateMemento.collapsedRegions, () => {
// if after 30 the InitializingRangeProvider is still not replaced, force a refresh
this.foldingStateMemento = null;
this.onFoldingStrategyChanged();
}, 30000);
return rangeProvider; // keep memento in case there are still no foldingProviders on the next request.
}
else if (foldingProviders.length > 0) {
this.rangeProvider = new syntaxRangeProvider_1.SyntaxRangeProvider(editorModel, foldingProviders, () => this.onModelContentChanged());
}
}
this.foldingStateMemento = null;
return this.rangeProvider;
}
getFoldingModel() {
return this.foldingModelPromise;
}
onModelContentChanged() {
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 provider = this.getRangeProvider(foldingModel.textModel);
let 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(modes_1.FoldingRangeKind.Imports.value, true);
if (hasChanges) {
scrollState = editorState_1.StableEditorScrollState.capture(this.editor);
this._currentModelHasFoldedImports = hasChanges;
}
}
// some cursors might have moved into hidden regions, make sure they are in expanded regions
let selections = this.editor.getSelections();
let selectionLineNumbers = selections ? selections.map(s => s.startLineNumber) : [];
foldingModel.update(foldingRanges, selectionLineNumbers);
if (scrollState) {
scrollState.restore(this.editor);
}
}
return foldingModel;
});
}).then(undefined, (err) => {
(0, errors_1.onUnexpectedError)(err);
return null;
});
}
}
onHiddenRangesChanges(hiddenRanges) {
if (this.hiddenRangeModel && hiddenRanges.length && !this._restoringViewState) {
let selections = this.editor.getSelections();
if (selections) {
if (this.hiddenRangeModel.adjustSelections(selections)) {
this.editor.setSelections(selections);
}
}
}
this.editor.setHiddenAreas(hiddenRanges);
}
onCursorPositionChanged() {
if (this.hiddenRangeModel && this.hiddenRangeModel.hasRanges()) {
this.cursorChangedScheduler.schedule();
}
}
revealCursor() {
const foldingModel = this.getFoldingModel();
if (!foldingModel) {
return;
}
foldingModel.then(foldingModel => {
if (foldingModel) {
let selections = this.editor.getSelections();
if (selections && selections.length > 0) {
let toToggle = [];
for (let selection of selections) {
let 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 /* 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 < 5) { // the whitespace between the border and the real folding icon border is 5px
return;
}
iconClicked = true;
break;
case 7 /* CONTENT_EMPTY */: {
if (this._unfoldOnClickAfterEndOfLine && this.hiddenRangeModel.hasRanges()) {
const data = e.target.detail;
if (!data.isAfterLines) {
break;
}
}
return;
}
case 6 /* CONTENT_TEXT */: {
if (this.hiddenRangeModel.hasRanges()) {
let 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.getFoldingModel();
if (!foldingModel || !this.mouseDownInfo || !e.target) {
return;
}
let lineNumber = this.mouseDownInfo.lineNumber;
let iconClicked = this.mouseDownInfo.iconClicked;
let range = e.target.range;
if (!range || range.startLineNumber !== lineNumber) {
return;
}
if (iconClicked) {
if (e.target.type !== 4 /* GUTTER_LINE_DECORATIONS */) {
return;
}
}
else {
let model = this.editor.getModel();
if (!model || range.startColumn !== model.getLineMaxColumn(lineNumber)) {
return;
}
}
foldingModel.then(foldingModel => {
if (foldingModel) {
let region = foldingModel.getRegionAtLine(lineNumber);
if (region && region.startLineNumber === lineNumber) {
let isCollapsed = region.isCollapsed;
if (iconClicked || isCollapsed) {
let surrounding = e.event.altKey;
let toToggle = [];
if (surrounding) {
let filter = (otherRegion) => !otherRegion.containedBy(region) && !region.containedBy(otherRegion);
let 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 {
let 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 });
}
}
}
}).then(undefined, errors_1.onUnexpectedError);
}
reveal(position) {
this.editor.revealPositionInCenterIfOutsideViewport(position, 0 /* Smooth */);
}
};
FoldingController.ID = 'editor.contrib.folding';
FoldingController = __decorate([
__param(1, contextkey_1.IContextKeyService)
], FoldingController);
exports.FoldingController = FoldingController;
class FoldingAction extends editorExtensions_1.EditorAction {
runEditorCommand(accessor, editor, args) {
let foldingController = FoldingController.get(editor);
if (!foldingController) {
return;
}
let foldingModelPromise = foldingController.getFoldingModel();
if (foldingModelPromise) {
this.reportTelemetry(accessor, editor);
return foldingModelPromise.then(foldingModel => {
if (foldingModel) {
this.invoke(foldingController, foldingModel, editor, args);
const selection = editor.getSelection();
if (selection) {
foldingController.reveal(selection.getStartPosition());
}
}
});
}
}
getSelectedLines(editor) {
let 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 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) && (!types.isArray(foldingArgs.selectionLines) || !foldingArgs.selectionLines.every(types.isNumber))) {
return false;
}
}
return true;
}
class UnfoldAction extends FoldingAction {
constructor() {
super({
id: 'editor.unfold',
label: nls.localize(0, null),
alias: 'Unfold',
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 89 /* US_CLOSE_SQUARE_BRACKET */,
mac: {
primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 89 /* US_CLOSE_SQUARE_BRACKET */
},
weight: 100 /* EditorContrib */
},
description: {
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': 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) {
let levels = args && args.levels || 1;
let 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(1, null),
alias: 'Unfold Recursively',
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 89 /* US_CLOSE_SQUARE_BRACKET */),
weight: 100 /* 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(2, null),
alias: 'Fold',
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 87 /* US_OPEN_SQUARE_BRACKET */,
mac: {
primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 87 /* US_OPEN_SQUARE_BRACKET */
},
weight: 100 /* EditorContrib */
},
description: {
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': 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) {
let 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(3, null),
alias: 'Toggle Fold',
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 42 /* KEY_L */),
weight: 100 /* EditorContrib */
}
});
}
invoke(_foldingController, foldingModel, editor) {
let selectedLines = this.getSelectedLines(editor);
(0, foldingModel_1.toggleCollapseState)(foldingModel, 1, selectedLines);
}
}
class FoldRecursivelyAction extends FoldingAction {
constructor() {
super({
id: 'editor.foldRecursively',
label: nls.localize(4, null),
alias: 'Fold Recursively',
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 87 /* US_OPEN_SQUARE_BRACKET */),
weight: 100 /* EditorContrib */
}
});
}
invoke(_foldingController, foldingModel, editor) {
let selectedLines = this.getSelectedLines(editor);
(0, foldingModel_1.setCollapseStateLevelsDown)(foldingModel, true, Number.MAX_VALUE, selectedLines);
}
}
class FoldAllBlockCommentsAction extends FoldingAction {
constructor() {
super({
id: 'editor.foldAllBlockComments',
label: nls.localize(5, null),
alias: 'Fold All Block Comments',
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 85 /* US_SLASH */),
weight: 100 /* EditorContrib */
}
});
}
invoke(_foldingController, foldingModel, editor) {
if (foldingModel.regions.hasTypes()) {
(0, foldingModel_1.setCollapseStateForType)(foldingModel, modes_1.FoldingRangeKind.Comment.value, true);
}
else {
const editorModel = editor.getModel();
if (!editorModel) {
return;
}
let comments = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getComments(editorModel.getLanguageIdentifier().id);
if (comments && comments.blockCommentStartToken) {
let 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(6, null),
alias: 'Fold All Regions',
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 29 /* KEY_8 */),
weight: 100 /* EditorContrib */
}
});
}
invoke(_foldingController, foldingModel, editor) {
if (foldingModel.regions.hasTypes()) {
(0, foldingModel_1.setCollapseStateForType)(foldingModel, modes_1.FoldingRangeKind.Region.value, true);
}
else {
const editorModel = editor.getModel();
if (!editorModel) {
return;
}
let foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(editorModel.getLanguageIdentifier().id);
if (foldingRules && foldingRules.markers && foldingRules.markers.start) {
let 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(7, null),
alias: 'Unfold All Regions',
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 30 /* KEY_9 */),
weight: 100 /* EditorContrib */
}
});
}
invoke(_foldingController, foldingModel, editor) {
if (foldingModel.regions.hasTypes()) {
(0, foldingModel_1.setCollapseStateForType)(foldingModel, modes_1.FoldingRangeKind.Region.value, false);
}
else {
const editorModel = editor.getModel();
if (!editorModel) {
return;
}
let foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(editorModel.getLanguageIdentifier().id);
if (foldingRules && foldingRules.markers && foldingRules.markers.start) {
let regExp = new RegExp(foldingRules.markers.start);
(0, foldingModel_1.setCollapseStateForMatchingLines)(foldingModel, regExp, false);
}
}
}
}
class FoldAllRegionsExceptAction extends FoldingAction {
constructor() {
super({
id: 'editor.foldAllExcept',
label: nls.localize(8, null),
alias: 'Fold All Regions Except Selected',
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 83 /* US_MINUS */),
weight: 100 /* EditorContrib */
}
});
}
invoke(_foldingController, foldingModel, editor) {
let selectedLines = this.getSelectedLines(editor);
(0, foldingModel_1.setCollapseStateForRest)(foldingModel, true, selectedLines);
}
}
class UnfoldAllRegionsExceptAction extends FoldingAction {
constructor() {
super({
id: 'editor.unfoldAllExcept',
label: nls.localize(9, null),
alias: 'Unfold All Regions Except Selected',
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 81 /* US_EQUAL */),
weight: 100 /* EditorContrib */
}
});
}
invoke(_foldingController, foldingModel, editor) {
let selectedLines = this.getSelectedLines(editor);
(0, foldingModel_1.setCollapseStateForRest)(foldingModel, false, selectedLines);
}
}
class FoldAllAction extends FoldingAction {
constructor() {
super({
id: 'editor.foldAll',
label: nls.localize(10, null),
alias: 'Fold All',
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 21 /* KEY_0 */),
weight: 100 /* EditorContrib */
}
});
}
invoke(_foldingController, foldingModel, _editor) {
(0, foldingModel_1.setCollapseStateLevelsDown)(foldingModel, true);
}
}
class UnfoldAllAction extends FoldingAction {
constructor() {
super({
id: 'editor.unfoldAll',
label: nls.localize(11, null),
alias: 'Unfold All',
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 40 /* KEY_J */),
weight: 100 /* EditorContrib */
}
});
}
invoke(_foldingController, foldingModel, _editor) {
(0, foldingModel_1.setCollapseStateLevelsDown)(foldingModel, false);
}
}
class FoldLevelAction extends FoldingAction {
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));
}
}
FoldLevelAction.ID_PREFIX = 'editor.foldLevel';
FoldLevelAction.ID = (level) => FoldLevelAction.ID_PREFIX + level;
/** Action to go to the parent fold of current line */
class GotoParentFoldAction extends FoldingAction {
constructor() {
super({
id: 'editor.gotoParentFold',
label: nls.localize(12, null),
alias: 'Go to Parent Fold',
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
weight: 100 /* EditorContrib */
}
});
}
invoke(_foldingController, foldingModel, editor) {
let selectedLines = this.getSelectedLines(editor);
if (selectedLines.length > 0) {
let 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(13, null),
alias: 'Go to Previous Fold',
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
weight: 100 /* EditorContrib */
}
});
}
invoke(_foldingController, foldingModel, editor) {
let selectedLines = this.getSelectedLines(editor);
if (selectedLines.length > 0) {
let 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(14, null),
alias: 'Go to Next Fold',
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
weight: 100 /* EditorContrib */
}
});
}
invoke(_foldingController, foldingModel, editor) {
let selectedLines = this.getSelectedLines(editor);
if (selectedLines.length > 0) {
let startLineNumber = (0, foldingModel_1.getNextFoldLine)(selectedLines[0], foldingModel);
if (startLineNumber !== null) {
editor.setSelection({
startLineNumber: startLineNumber,
startColumn: 1,
endLineNumber: startLineNumber,
endColumn: 1
});
}
}
}
}
(0, editorExtensions_1.registerEditorContribution)(FoldingController.ID, FoldingController);
(0, editorExtensions_1.registerEditorAction)(UnfoldAction);
(0, editorExtensions_1.registerEditorAction)(UnFoldRecursivelyAction);
(0, editorExtensions_1.registerEditorAction)(FoldAction);
(0, editorExtensions_1.registerEditorAction)(FoldRecursivelyAction);
(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)(FoldAllRegionsExceptAction);
(0, editorExtensions_1.registerEditorAction)(UnfoldAllRegionsExceptAction);
(0, editorExtensions_1.registerEditorAction)(ToggleFoldAction);
(0, editorExtensions_1.registerEditorAction)(GotoParentFoldAction);
(0, editorExtensions_1.registerEditorAction)(GotoPreviousFoldAction);
(0, editorExtensions_1.registerEditorAction)(GotoNextFoldAction);
for (let i = 1; i <= 7; i++) {
(0, editorExtensions_1.registerInstantiatedEditorAction)(new FoldLevelAction({
id: FoldLevelAction.ID(i),
label: nls.localize(15, null, i),
alias: `Fold Level ${i}`,
precondition: CONTEXT_FOLDING_ENABLED,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | (21 /* KEY_0 */ + i)),
weight: 100 /* EditorContrib */
}
}));
}
exports.foldBackgroundBackground = (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), hc: null }, nls.localize(16, null), true);
exports.editorFoldForeground = (0, colorRegistry_1.registerColor)('editorGutter.foldingControlForeground', { dark: colorRegistry_1.iconForeground, light: colorRegistry_1.iconForeground, hc: colorRegistry_1.iconForeground }, nls.localize(17, null));
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const foldBackground = theme.getColor(exports.foldBackgroundBackground);
if (foldBackground) {
collector.addRule(`.monaco-editor .folded-background { background-color: ${foldBackground}; }`);
}
const editorFoldColor = theme.getColor(exports.editorFoldForeground);
if (editorFoldColor) {
collector.addRule(`
.monaco-editor .cldr${themeService_1.ThemeIcon.asCSSSelector(foldingDecorations_1.foldingExpandedIcon)},
.monaco-editor .cldr${themeService_1.ThemeIcon.asCSSSelector(foldingDecorations_1.foldingCollapsedIcon)} {
color: ${editorFoldColor} !important;
}
`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/gotoError/gotoError*/], __M([0/*require*/,1/*exports*/,489/*vs/nls!vs/editor/contrib/gotoError/gotoError*/,2/*vs/base/common/lifecycle*/,16/*vs/platform/contextkey/common/contextkey*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,14/*vs/editor/browser/editorExtensions*/,25/*vs/editor/common/editorContextKeys*/,670/*vs/editor/contrib/gotoError/gotoErrorWidget*/,28/*vs/editor/browser/services/codeEditorService*/,33/*vs/platform/actions/common/actions*/,27/*vs/base/common/codicons*/,9/*vs/platform/instantiation/common/instantiation*/,571/*vs/editor/contrib/gotoError/markerNavigationService*/,79/*vs/platform/theme/common/iconRegistry*/]), function (require, exports, nls, lifecycle_1, contextkey_1, position_1, range_1, editorExtensions_1, editorContextKeys_1, gotoErrorWidget_1, codeEditorService_1, actions_1, codicons_1, instantiation_1, markerNavigationService_1, iconRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NextMarkerAction = exports.MarkerController = void 0;
let MarkerController = class MarkerController {
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);
}
static get(editor) {
return editor.getContribution(MarkerController.ID);
}
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 => {
var _a, _b, _c;
if (!((_a = this._model) === null || _a === void 0 ? void 0 : _a.selected) || !range_1.Range.containsPosition((_b = this._model) === null || _b === void 0 ? void 0 : _b.selected.marker, e.position)) {
(_c = this._model) === null || _c === void 0 ? void 0 : _c.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);
}
}
}
nagivate(next, multiFile) {
return __awaiter(this, void 0, void 0, function* () {
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 = yield this._editorService.openCodeEditor({
resource: model.selected.marker.resource,
options: { pinned: false, revealIfOpened: true, selectionRevealType: 2 /* NearTop */, selection: model.selected.marker }
}, this._editor);
if (otherEditor) {
MarkerController.get(otherEditor).close();
MarkerController.get(otherEditor).nagivate(next, multiFile);
}
}
else {
// show in this editor
this._widget.showAtMarker(model.selected.marker, model.selected.index, model.selected.total);
}
}
});
}
};
MarkerController.ID = 'editor.contrib.markerController';
MarkerController = __decorate([
__param(1, markerNavigationService_1.IMarkerNavigationService),
__param(2, contextkey_1.IContextKeyService),
__param(3, codeEditorService_1.ICodeEditorService),
__param(4, instantiation_1.IInstantiationService)
], MarkerController);
exports.MarkerController = MarkerController;
class MarkerNavigationAction extends editorExtensions_1.EditorAction {
constructor(_next, _multiFile, opts) {
super(opts);
this._next = _next;
this._multiFile = _multiFile;
}
run(_accessor, editor) {
return __awaiter(this, void 0, void 0, function* () {
if (editor.hasModel()) {
MarkerController.get(editor).nagivate(this._next, this._multiFile);
}
});
}
}
class NextMarkerAction extends MarkerNavigationAction {
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 /* Alt */ | 66 /* F8 */,
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: gotoErrorWidget_1.MarkerNavigationWidget.TitleMenu,
title: NextMarkerAction.LABEL,
icon: (0, iconRegistry_1.registerIcon)('marker-navigation-next', codicons_1.Codicon.chevronDown, nls.localize(1, null)),
group: 'navigation',
order: 1
}
});
}
}
exports.NextMarkerAction = NextMarkerAction;
NextMarkerAction.ID = 'editor.action.marker.next';
NextMarkerAction.LABEL = nls.localize(0, null);
class PrevMarkerAction extends MarkerNavigationAction {
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 /* Shift */ | 512 /* Alt */ | 66 /* F8 */,
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: gotoErrorWidget_1.MarkerNavigationWidget.TitleMenu,
title: NextMarkerAction.LABEL,
icon: (0, iconRegistry_1.registerIcon)('marker-navigation-previous', codicons_1.Codicon.chevronUp, nls.localize(3, null)),
group: 'navigation',
order: 2
}
});
}
}
PrevMarkerAction.ID = 'editor.action.marker.prev';
PrevMarkerAction.LABEL = nls.localize(2, null);
class NextMarkerInFilesAction extends MarkerNavigationAction {
constructor() {
super(true, true, {
id: 'editor.action.marker.nextInFiles',
label: nls.localize(4, null),
alias: 'Go to Next Problem in Files (Error, Warning, Info)',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 66 /* F8 */,
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarGoMenu,
title: nls.localize(5, null),
group: '6_problem_nav',
order: 1
}
});
}
}
class PrevMarkerInFilesAction extends MarkerNavigationAction {
constructor() {
super(false, true, {
id: 'editor.action.marker.prevInFiles',
label: nls.localize(6, null),
alias: 'Go to Previous Problem in Files (Error, Warning, Info)',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 1024 /* Shift */ | 66 /* F8 */,
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarGoMenu,
title: nls.localize(7, null),
group: '6_problem_nav',
order: 2
}
});
}
}
(0, editorExtensions_1.registerEditorContribution)(MarkerController.ID, MarkerController);
(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 /* EditorContrib */ + 50,
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 9 /* Escape */,
secondary: [1024 /* Shift */ | 9 /* 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[675/*vs/editor/contrib/hover/markerHoverParticipant*/], __M([0/*require*/,1/*exports*/,500/*vs/nls!vs/editor/contrib/hover/markerHoverParticipant*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/,19/*vs/base/common/arrays*/,87/*vs/platform/markers/common/markers*/,43/*vs/base/common/resources*/,183/*vs/editor/common/services/markersDecorationService*/,12/*vs/base/common/errors*/,58/*vs/platform/opener/common/opener*/,273/*vs/editor/contrib/gotoError/gotoError*/,15/*vs/base/common/async*/,151/*vs/editor/contrib/codeAction/codeAction*/,268/*vs/editor/contrib/codeAction/codeActionCommands*/,137/*vs/editor/contrib/codeAction/types*/,59/*vs/platform/progress/common/progress*/,11/*vs/platform/theme/common/themeService*/,22/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, nls, dom, lifecycle_1, range_1, arrays_1, markers_1, resources_1, markersDecorationService_1, errors_1, opener_1, gotoError_1, async_1, codeAction_1, codeActionCommands_1, types_1, progress_1, themeService_1, colorRegistry_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 /* Range */
&& this.range.startColumn <= anchor.range.startColumn
&& this.range.endColumn >= anchor.range.endColumn);
}
}
exports.MarkerHover = MarkerHover;
const markerCodeActionTrigger = {
type: 1 /* Invoke */,
filter: { include: types_1.CodeActionKind.QuickFix }
};
let MarkerHoverParticipant = class MarkerHoverParticipant {
constructor(_editor, _hover, _markerDecorationsService, _openerService) {
this._editor = _editor;
this._hover = _hover;
this._markerDecorationsService = _markerDecorationsService;
this._openerService = _openerService;
this.recentMarkerCodeActionsInfo = undefined;
}
computeSync(anchor, lineDecorations) {
if (!this._editor.hasModel() || anchor.type !== 1 /* Range */) {
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(hoverParts, fragment, statusBar) {
if (!hoverParts.length) {
return lifecycle_1.Disposable.None;
}
const disposables = new lifecycle_1.DisposableStore();
hoverParts.forEach(msg => fragment.appendChild(this.renderMarkerHover(msg, disposables)));
const markerHoverForStatusbar = hoverParts.length === 1 ? hoverParts[0] : hoverParts.sort((a, b) => markers_1.MarkerSeverity.compare(a.marker.severity, b.marker.severity))[0];
this.renderMarkerStatusbar(markerHoverForStatusbar, statusBar, disposables);
return disposables;
}
renderMarkerHover(markerHover, disposables) {
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) {
this._openerService.open(resource, {
fromUserGesture: true,
editorOptions: { selection: { startLineNumber, startColumn } }
}).catch(errors_1.onUnexpectedError);
}
}));
const messageElement = dom.append(relatedInfoContainer, $('span'));
messageElement.innerText = message;
this._editor.applyFontInfo(messageElement);
}
}
return hoverElement;
}
renderMarkerStatusbar(markerHover, statusBar, disposables) {
if (markerHover.marker.severity === markers_1.MarkerSeverity.Error || markerHover.marker.severity === markers_1.MarkerSeverity.Warning || markerHover.marker.severity === markers_1.MarkerSeverity.Info) {
statusBar.addAction({
label: nls.localize(0, null),
commandId: gotoError_1.NextMarkerAction.ID,
run: () => {
this._hover.hide();
gotoError_1.MarkerController.get(this._editor).showAtMarker(markerHover.marker);
this._editor.focus();
}
});
}
if (!this._editor.getOption(79 /* readOnly */)) {
const quickfixPlaceholderElement = 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(1, null);
}
}
else {
this.recentMarkerCodeActionsInfo = undefined;
}
}
const updatePlaceholderDisposable = this.recentMarkerCodeActionsInfo && !this.recentMarkerCodeActionsInfo.hasCodeActions ? lifecycle_1.Disposable.None : disposables.add((0, async_1.disposableTimeout)(() => quickfixPlaceholderElement.textContent = nls.localize(2, null), 200));
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(3, null);
return;
}
quickfixPlaceholderElement.style.display = 'none';
let showing = false;
disposables.add((0, lifecycle_1.toDisposable)(() => {
if (!showing) {
actions.dispose();
}
}));
statusBar.addAction({
label: nls.localize(4, null),
commandId: codeActionCommands_1.QuickFixAction.Id,
run: (target) => {
showing = true;
const controller = codeActionCommands_1.QuickFixController.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
this._hover.hide();
controller.showCodeActions(markerCodeActionTrigger, actions, {
x: elementPosition.left + 6,
y: elementPosition.top + elementPosition.height + 6
});
}
});
});
}
}
getCodeActions(marker) {
return (0, async_1.createCancelablePromise)(cancellationToken => {
return (0, codeAction_1.getCodeActions)(this._editor.getModel(), new range_1.Range(marker.startLineNumber, marker.startColumn, marker.endLineNumber, marker.endColumn), markerCodeActionTrigger, progress_1.Progress.None, cancellationToken);
});
}
};
MarkerHoverParticipant = __decorate([
__param(2, markersDecorationService_1.IMarkerDecorationsService),
__param(3, opener_1.IOpenerService)
], MarkerHoverParticipant);
exports.MarkerHoverParticipant = MarkerHoverParticipant;
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const linkFg = theme.getColor(colorRegistry_1.textLinkForeground);
if (linkFg) {
collector.addRule(`.monaco-hover .hover-contents a.code-link span { color: ${linkFg}; }`);
}
const activeLinkFg = theme.getColor(colorRegistry_1.textLinkActiveForeground);
if (activeLinkFg) {
collector.addRule(`.monaco-hover .hover-contents a.code-link span:hover { color: ${activeLinkFg}; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/multicursor/multicursor*/], __M([0/*require*/,1/*exports*/,509/*vs/nls!vs/editor/contrib/multicursor/multicursor*/,15/*vs/base/common/async*/,41/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,44/*vs/base/browser/ui/aria/aria*/,14/*vs/editor/browser/editorExtensions*/,244/*vs/editor/common/controller/cursorMoveCommands*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,25/*vs/editor/common/editorContextKeys*/,53/*vs/editor/common/model*/,31/*vs/editor/common/model/textModel*/,18/*vs/editor/common/modes*/,272/*vs/editor/contrib/find/findController*/,33/*vs/platform/actions/common/actions*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,16/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, nls, async_1, keyCodes_1, lifecycle_1, aria_1, editorExtensions_1, cursorMoveCommands_1, range_1, selection_1, editorContextKeys_1, model_1, textModel_1, modes_1, findController_1, actions_1, colorRegistry_1, themeService_1, contextkey_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
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(0, null, cursorPositions) : nls.localize(1, null, cursorPositions);
(0, aria_1.status)(msg);
}
}
class InsertCursorAbove extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.insertCursorAbove',
label: nls.localize(2, null),
alias: 'Add Cursor Above',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 16 /* UpArrow */,
linux: {
primary: 1024 /* Shift */ | 512 /* Alt */ | 16 /* UpArrow */,
secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 16 /* UpArrow */]
},
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarSelectionMenu,
group: '3_multi',
title: nls.localize(3, null),
order: 2
}
});
}
run(accessor, editor, args) {
if (!editor.hasModel()) {
return;
}
const useLogicalLine = (args && args.logicalLine === true);
const viewModel = editor._getViewModel();
if (viewModel.cursorConfig.readOnly) {
return;
}
viewModel.pushStackElement();
const previousCursorState = viewModel.getCursorStates();
viewModel.setCursorStates(args.source, 3 /* 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(4, null),
alias: 'Add Cursor Below',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 18 /* DownArrow */,
linux: {
primary: 1024 /* Shift */ | 512 /* Alt */ | 18 /* DownArrow */,
secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 18 /* DownArrow */]
},
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarSelectionMenu,
group: '3_multi',
title: nls.localize(5, null),
order: 3
}
});
}
run(accessor, editor, args) {
if (!editor.hasModel()) {
return;
}
const useLogicalLine = (args && args.logicalLine === true);
const viewModel = editor._getViewModel();
if (viewModel.cursorConfig.readOnly) {
return;
}
viewModel.pushStackElement();
const previousCursorState = viewModel.getCursorStates();
viewModel.setCursorStates(args.source, 3 /* 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(6, null),
alias: 'Add Cursors to Line Ends',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 1024 /* Shift */ | 512 /* Alt */ | 39 /* KEY_I */,
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarSelectionMenu,
group: '3_multi',
title: nls.localize(7, null),
order: 4
}
});
}
getCursorsForSelection(selection, model, result) {
if (selection.isEmpty()) {
return;
}
for (let i = selection.startLineNumber; i < selection.endLineNumber; i++) {
let 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();
let 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(8, null),
alias: 'Add Cursors To Bottom',
precondition: undefined
});
}
run(accessor, editor) {
if (!editor.hasModel()) {
return;
}
const selections = editor.getSelections();
const lineCount = editor.getModel().getLineCount();
let 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(9, null),
alias: 'Add Cursors To Top',
precondition: undefined
});
}
run(accessor, editor) {
if (!editor.hasModel()) {
return;
}
const selections = editor.getSelections();
let 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 {
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;
}
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);
}
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 /* 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 /* 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(115 /* 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 /* 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 /* 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(115 /* 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() {
if (!this._editor.hasModel()) {
return [];
}
this.findController.highlightFindOptions();
return this._editor.getModel().findMatches(this.searchText, true, false, this.matchCase, this.wholeWord ? this._editor.getOption(115 /* wordSeparators */) : null, false, 1073741824 /* MAX_SAFE_SMALL_INTEGER */);
}
}
exports.MultiCursorSession = MultiCursorSession;
class MultiCursorSelectionController extends lifecycle_1.Disposable {
constructor(editor) {
super();
this._sessionDispose = this._register(new lifecycle_1.DisposableStore());
this._editor = editor;
this._ignoreSelectionChange = false;
this._session = null;
}
static get(editor) {
return editor.getContribution(MultiCursorSelectionController.ID);
}
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 /* True */;
newState.matchCaseOverride = 1 /* True */;
newState.isRegexOverride = 2 /* 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 /* NotSet */,
matchCaseOverride: 0 /* NotSet */,
isRegexOverride: 0 /* 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();
let 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) {
matches = this._editor.getModel().findMatches(findState.searchString, true, findState.isRegex, findState.matchCase, findState.wholeWord ? this._editor.getOption(115 /* wordSeparators */) : null, false, 1073741824 /* MAX_SAFE_SMALL_INTEGER */);
}
else {
this._beginSessionIfNeeded(findController);
if (!this._session) {
return;
}
matches = this._session.selectAll();
}
if (findState.searchScope) {
const states = findState.searchScope;
let inSelection = [];
matches.forEach((match) => {
states.forEach((state) => {
if (match.range.endLineNumber <= state.endLineNumber && match.range.startLineNumber >= state.startLineNumber) {
inSelection.push(match);
}
});
});
matches = inSelection;
}
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;
MultiCursorSelectionController.ID = 'editor.contrib.multiCursorController';
class MultiCursorSelectionControllerAction extends editorExtensions_1.EditorAction {
run(accessor, editor) {
const multiCursorController = MultiCursorSelectionController.get(editor);
if (!multiCursorController) {
return;
}
const findController = findController_1.CommonFindController.get(editor);
if (!findController) {
return;
}
const viewModel = editor._getViewModel();
if (viewModel) {
const previousCursorState = viewModel.getCursorStates();
this._run(multiCursorController, findController);
announceCursorChange(previousCursorState, viewModel.getCursorStates());
}
}
}
exports.MultiCursorSelectionControllerAction = MultiCursorSelectionControllerAction;
class AddSelectionToNextFindMatchAction extends MultiCursorSelectionControllerAction {
constructor() {
super({
id: 'editor.action.addSelectionToNextFindMatch',
label: nls.localize(10, null),
alias: 'Add Selection To Next Find Match',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 2048 /* CtrlCmd */ | 34 /* KEY_D */,
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarSelectionMenu,
group: '3_multi',
title: nls.localize(11, null),
order: 5
}
});
}
_run(multiCursorController, findController) {
multiCursorController.addSelectionToNextFindMatch(findController);
}
}
exports.AddSelectionToNextFindMatchAction = AddSelectionToNextFindMatchAction;
class AddSelectionToPreviousFindMatchAction extends MultiCursorSelectionControllerAction {
constructor() {
super({
id: 'editor.action.addSelectionToPreviousFindMatch',
label: nls.localize(12, null),
alias: 'Add Selection To Previous Find Match',
precondition: undefined,
menuOpts: {
menuId: actions_1.MenuId.MenubarSelectionMenu,
group: '3_multi',
title: nls.localize(13, null),
order: 6
}
});
}
_run(multiCursorController, findController) {
multiCursorController.addSelectionToPreviousFindMatch(findController);
}
}
exports.AddSelectionToPreviousFindMatchAction = AddSelectionToPreviousFindMatchAction;
class MoveSelectionToNextFindMatchAction extends MultiCursorSelectionControllerAction {
constructor() {
super({
id: 'editor.action.moveSelectionToNextFindMatch',
label: nls.localize(14, null),
alias: 'Move Last Selection To Next Find Match',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 34 /* KEY_D */),
weight: 100 /* EditorContrib */
}
});
}
_run(multiCursorController, findController) {
multiCursorController.moveSelectionToNextFindMatch(findController);
}
}
exports.MoveSelectionToNextFindMatchAction = MoveSelectionToNextFindMatchAction;
class MoveSelectionToPreviousFindMatchAction extends MultiCursorSelectionControllerAction {
constructor() {
super({
id: 'editor.action.moveSelectionToPreviousFindMatch',
label: nls.localize(15, null),
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(16, null),
alias: 'Select All Occurrences of Find Match',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.focus,
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 42 /* KEY_L */,
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarSelectionMenu,
group: '3_multi',
title: nls.localize(17, null),
order: 7
}
});
}
_run(multiCursorController, findController) {
multiCursorController.selectAll(findController);
}
}
exports.SelectHighlightsAction = SelectHighlightsAction;
class CompatChangeAll extends MultiCursorSelectionControllerAction {
constructor() {
super({
id: 'editor.action.changeAll',
label: nls.localize(18, null),
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 /* CtrlCmd */ | 60 /* F2 */,
weight: 100 /* EditorContrib */
},
contextMenuOpts: {
group: '1_modification',
order: 1.2
}
});
}
_run(multiCursorController, findController) {
multiCursorController.selectAll(findController);
}
}
exports.CompatChangeAll = CompatChangeAll;
class SelectionHighlighterState {
constructor(searchText, matchCase, wordSeparators, modelVersionId) {
this.searchText = searchText;
this.matchCase = matchCase;
this.wordSeparators = wordSeparators;
this.modelVersionId = modelVersionId;
}
/**
* Everything equals except for `lastWordUnderCursor`
*/
static softEquals(a, b) {
if (!a && !b) {
return true;
}
if (!a || !b) {
return false;
}
return (a.searchText === b.searchText
&& a.matchCase === b.matchCase
&& a.wordSeparators === b.wordSeparators
&& a.modelVersionId === b.modelVersionId);
}
}
class SelectionHighlighter extends lifecycle_1.Disposable {
constructor(editor) {
super();
this.editor = editor;
this._isEnabled = editor.getOption(96 /* selectionHighlight */);
this.decorations = [];
this.updateSoon = this._register(new async_1.RunOnceScheduler(() => this._update(), 300));
this.state = null;
this._register(editor.onDidChangeConfiguration((e) => {
this._isEnabled = editor.getOption(96 /* 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 /* 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();
}
}));
this._register(findController_1.CommonFindController.get(editor).getState().onFindReplaceStateChange((e) => {
this._update();
}));
}
_update() {
this._setState(SelectionHighlighter._createState(this._isEnabled, this.editor));
}
static _createState(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(r.searchText, r.matchCase, r.wholeWord ? editor.getOption(115 /* wordSeparators */) : null, editor.getModel().getVersionId());
}
_setState(state) {
if (SelectionHighlighterState.softEquals(this.state, state)) {
this.state = state;
return;
}
this.state = state;
if (!this.state) {
this.decorations = this.editor.deltaDecorations(this.decorations, []);
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 takes is blocking the UI.
return;
}
const hasFindOccurrences = modes_1.DocumentHighlightProviderRegistry.has(model) && this.editor.getOption(70 /* occurrencesHighlight */);
let allMatches = model.findMatches(this.state.searchText, true, false, this.state.matchCase, this.state.wordSeparators, false).map(m => m.range);
allMatches.sort(range_1.Range.compareRangesUsingStarts);
let selections = this.editor.getSelections();
selections.sort(range_1.Range.compareRangesUsingStarts);
// do not overlap with selection (issue #64 and #512)
let 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 decorations = matches.map(r => {
return {
range: r,
// Show in overviewRuler only if model has no semantic highlighting
options: (hasFindOccurrences ? SelectionHighlighter._SELECTION_HIGHLIGHT : SelectionHighlighter._SELECTION_HIGHLIGHT_OVERVIEW)
};
});
this.decorations = this.editor.deltaDecorations(this.decorations, decorations);
}
dispose() {
this._setState(null);
super.dispose();
}
}
exports.SelectionHighlighter = SelectionHighlighter;
SelectionHighlighter.ID = 'editor.contrib.selectionHighlighter';
SelectionHighlighter._SELECTION_HIGHLIGHT_OVERVIEW = textModel_1.ModelDecorationOptions.register({
description: 'selection-highlight-overview',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
className: 'selectionHighlight',
overviewRuler: {
color: (0, themeService_1.themeColorFromId)(colorRegistry_1.overviewRulerSelectionHighlightForeground),
position: model_1.OverviewRulerLane.Center
}
});
SelectionHighlighter._SELECTION_HIGHLIGHT = textModel_1.ModelDecorationOptions.register({
description: 'selection-highlight',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
className: 'selectionHighlight',
});
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);
}
(0, editorExtensions_1.registerEditorContribution)(MultiCursorSelectionController.ID, MultiCursorSelectionController);
(0, editorExtensions_1.registerEditorContribution)(SelectionHighlighter.ID, SelectionHighlighter);
(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);
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/parameterHints/parameterHintsWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,44/*vs/base/browser/ui/aria/aria*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,57/*vs/editor/common/services/modeService*/,145/*vs/editor/browser/core/markdownRenderer*/,188/*vs/editor/contrib/parameterHints/provideSignatureHelp*/,511/*vs/nls!vs/editor/contrib/parameterHints/parameterHintsWidget*/,16/*vs/platform/contextkey/common/contextkey*/,58/*vs/platform/opener/common/opener*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,561/*vs/editor/contrib/parameterHints/parameterHintsModel*/,8/*vs/base/common/strings*/,27/*vs/base/common/codicons*/,20/*vs/base/common/types*/,100/*vs/platform/theme/common/theme*/,79/*vs/platform/theme/common/iconRegistry*/,357/*vs/css!vs/editor/contrib/parameterHints/parameterHints*/]), function (require, exports, dom, aria, scrollableElement_1, event_1, lifecycle_1, modeService_1, markdownRenderer_1, provideSignatureHelp_1, nls, contextkey_1, opener_1, colorRegistry_1, themeService_1, parameterHintsModel_1, strings_1, codicons_1, types_1, theme_1, iconRegistry_1) {
"use strict";
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(0, null));
const parameterHintsPreviousIcon = (0, iconRegistry_1.registerIcon)('parameter-hints-previous', codicons_1.Codicon.chevronUp, nls.localize(1, null));
let ParameterHintsWidget = class ParameterHintsWidget extends lifecycle_1.Disposable {
constructor(editor, contextKeyService, openerService, modeService) {
super();
this.editor = editor;
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 }, modeService, openerService));
this.model = this._register(new parameterHintsModel_1.ParameterHintsModel(editor));
this.keyVisible = provideSignatureHelp_1.Context.Visible.bindTo(contextKeyService);
this.keyMultipleSignatures = provideSignatureHelp_1.Context.MultipleSignatures.bindTo(contextKeyService);
this._register(this.model.onChangedHints(newParameterHints => {
if (newParameterHints) {
this.show();
this.render(newParameterHints);
}
else {
this.hide();
}
}));
}
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' + themeService_1.ThemeIcon.asCSSSelector(parameterHintsPreviousIcon)));
const overloads = dom.append(controls, $('.overloads'));
const next = dom.append(controls, $('.button' + themeService_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, {});
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(41 /* fontInfo */);
this.domNodes.element.style.fontSize = `${fontInfo.fontSize}px`;
};
updateFont();
this._register(event_1.Event.chain(this.editor.onDidChangeConfiguration.bind(this.editor))
.filter(e => e.hasChanged(41 /* fontInfo */))
.on(updateFont, null));
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(() => {
if (this.domNodes) {
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;
if (this.domNodes) {
this.domNodes.element.classList.remove('visible');
}
this.editor.layoutContentWidget(this);
}
getPosition() {
if (this.visible) {
return {
position: this.editor.getPosition(),
preference: [1 /* ABOVE */, 2 /* BELOW */]
};
}
return null;
}
render(hints) {
var _a;
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 fontInfo = this.editor.getOption(41 /* fontInfo */);
code.style.fontSize = `${fontInfo.fontSize}px`;
code.style.fontFamily = fontInfo.fontFamily;
const hasParameters = signature.parameters.length > 0;
const activeParameterIndex = (_a = signature.activeParameter) !== null && _a !== void 0 ? _a : 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 === null || activeParameter === void 0 ? void 0 : 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) {
const labelToAnnounce = this.getParameterLabel(signature, activeParameterIndex);
// 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(2, null, labelToAnnounce));
this.announcedLabel = labelToAnnounce;
}
}
this.editor.layoutContentWidget(this);
this.domNodes.scrollbar.scanDomNode();
}
renderMarkdownDocs(markdown) {
const renderedContents = this.renderDisposeables.add(this.markdownRenderer.render(markdown, {
asyncRenderCallback: () => {
var _a;
(_a = this.domNodes) === null || _a === void 0 ? void 0 : _a.scrollbar.scanDomNode();
}
}));
renderedContents.element.classList.add('markdown-docs');
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);
}
getParameterLabel(signature, paramIdx) {
const param = signature.parameters[paramIdx];
if (Array.isArray(param.label)) {
return signature.label.substring(param.label[0], param.label[1]);
}
else {
return param.label;
}
}
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();
}
cancel() {
this.model.cancel();
}
getDomNode() {
if (!this.domNodes) {
this.createParameterHintDOMNodes();
}
return this.domNodes.element;
}
getId() {
return ParameterHintsWidget.ID;
}
trigger(context) {
this.model.trigger(context, 0);
}
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;
}
}
};
ParameterHintsWidget.ID = 'editor.widget.parameterHintsWidget';
ParameterHintsWidget = __decorate([
__param(1, contextkey_1.IContextKeyService),
__param(2, opener_1.IOpenerService),
__param(3, modeService_1.IModeService)
], ParameterHintsWidget);
exports.ParameterHintsWidget = ParameterHintsWidget;
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const border = theme.getColor(colorRegistry_1.editorHoverBorder);
if (border) {
const borderWidth = theme.type === theme_1.ColorScheme.HIGH_CONTRAST ? 2 : 1;
collector.addRule(`.monaco-editor .parameter-hints-widget { border: ${borderWidth}px solid ${border}; }`);
collector.addRule(`.monaco-editor .parameter-hints-widget.multiple .body { border-left: 1px solid ${border.transparent(0.5)}; }`);
collector.addRule(`.monaco-editor .parameter-hints-widget .signature.has-docs { border-bottom: 1px solid ${border.transparent(0.5)}; }`);
}
const background = theme.getColor(colorRegistry_1.editorHoverBackground);
if (background) {
collector.addRule(`.monaco-editor .parameter-hints-widget { background-color: ${background}; }`);
}
const link = theme.getColor(colorRegistry_1.textLinkForeground);
if (link) {
collector.addRule(`.monaco-editor .parameter-hints-widget a { color: ${link}; }`);
}
const foreground = theme.getColor(colorRegistry_1.editorHoverForeground);
if (foreground) {
collector.addRule(`.monaco-editor .parameter-hints-widget { color: ${foreground}; }`);
}
const codeBackground = theme.getColor(colorRegistry_1.textCodeBlockBackground);
if (codeBackground) {
collector.addRule(`.monaco-editor .parameter-hints-widget code { background-color: ${codeBackground}; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/parameterHints/parameterHints*/], __M([0/*require*/,1/*exports*/,510/*vs/nls!vs/editor/contrib/parameterHints/parameterHints*/,2/*vs/base/common/lifecycle*/,9/*vs/platform/instantiation/common/instantiation*/,25/*vs/editor/common/editorContextKeys*/,16/*vs/platform/contextkey/common/contextkey*/,14/*vs/editor/browser/editorExtensions*/,677/*vs/editor/contrib/parameterHints/parameterHintsWidget*/,188/*vs/editor/contrib/parameterHints/provideSignatureHelp*/,18/*vs/editor/common/modes*/]), function (require, exports, nls, lifecycle_1, instantiation_1, editorContextKeys_1, contextkey_1, editorExtensions_1, parameterHintsWidget_1, provideSignatureHelp_1, modes) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TriggerParameterHintsAction = void 0;
let ParameterHintsController = class ParameterHintsController extends lifecycle_1.Disposable {
constructor(editor, instantiationService) {
super();
this.editor = editor;
this.widget = this._register(instantiationService.createInstance(parameterHintsWidget_1.ParameterHintsWidget, this.editor));
}
static get(editor) {
return editor.getContribution(ParameterHintsController.ID);
}
cancel() {
this.widget.cancel();
}
previous() {
this.widget.previous();
}
next() {
this.widget.next();
}
trigger(context) {
this.widget.trigger(context);
}
};
ParameterHintsController.ID = 'editor.controller.parameterHints';
ParameterHintsController = __decorate([
__param(1, instantiation_1.IInstantiationService)
], ParameterHintsController);
class TriggerParameterHintsAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.triggerParameterHints',
label: nls.localize(0, null),
alias: 'Trigger Parameter Hints',
precondition: editorContextKeys_1.EditorContextKeys.hasSignatureHelpProvider,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 10 /* Space */,
weight: 100 /* EditorContrib */
}
});
}
run(accessor, editor) {
const controller = ParameterHintsController.get(editor);
if (controller) {
controller.trigger({
triggerKind: modes.SignatureHelpTriggerKind.Invoke
});
}
}
}
exports.TriggerParameterHintsAction = TriggerParameterHintsAction;
(0, editorExtensions_1.registerEditorContribution)(ParameterHintsController.ID, ParameterHintsController);
(0, editorExtensions_1.registerEditorAction)(TriggerParameterHintsAction);
const weight = 100 /* 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 /* Escape */,
secondary: [1024 /* Shift */ | 9 /* 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 /* UpArrow */,
secondary: [512 /* Alt */ | 16 /* UpArrow */],
mac: { primary: 16 /* UpArrow */, secondary: [512 /* Alt */ | 16 /* UpArrow */, 256 /* WinCtrl */ | 46 /* KEY_P */] }
}
}));
(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 /* DownArrow */,
secondary: [512 /* Alt */ | 18 /* DownArrow */],
mac: { primary: 18 /* DownArrow */, secondary: [512 /* Alt */ | 18 /* DownArrow */, 256 /* WinCtrl */ | 44 /* KEY_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[679/*vs/editor/contrib/suggest/suggestWidgetRenderer*/], __M([0/*require*/,1/*exports*/,524/*vs/nls!vs/editor/contrib/suggest/suggestWidgetRenderer*/,67/*vs/base/common/filters*/,2/*vs/base/common/lifecycle*/,7/*vs/base/browser/dom*/,11/*vs/platform/theme/common/themeService*/,57/*vs/editor/common/services/modeService*/,18/*vs/editor/common/modes*/,179/*vs/base/browser/ui/iconLabel/iconLabel*/,576/*vs/editor/common/services/getIconClasses*/,36/*vs/editor/common/services/modelService*/,24/*vs/base/common/uri*/,240/*vs/platform/files/common/files*/,19/*vs/base/common/arrays*/,257/*vs/editor/contrib/suggest/suggestWidgetDetails*/,27/*vs/base/common/codicons*/,6/*vs/base/common/event*/,79/*vs/platform/theme/common/iconRegistry*/]), function (require, exports, nls, filters_1, lifecycle_1, dom_1, themeService_1, modeService_1, modes_1, iconLabel_1, getIconClasses_1, modelService_1, uri_1, files_1, arrays_1, suggestWidgetDetails_1, codicons_1, event_1, iconRegistry_1) {
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ItemRenderer = exports.suggestMoreInfoIcon = exports.getAriaId = void 0;
function getAriaId(index) {
return `suggest-aria-id:${index}`;
}
exports.getAriaId = getAriaId;
exports.suggestMoreInfoIcon = (0, iconRegistry_1.registerIcon)('suggest-more-info', codicons_1.Codicon.chevronRight, nls.localize(0, null));
const _completionItemColor = new (_a = class ColorExtractor {
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 (typeof item.completion.documentation === 'string') {
const match = ColorExtractor._regexRelaxed.exec(item.completion.documentation);
if (match && (match.index === 0 || match.index + match[0].length === item.completion.documentation.length)) {
out[0] = match[0];
return true;
}
}
return false;
}
},
_a._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*\))/,
_a._regexStrict = new RegExp(`^${_a._regexRelaxed.source}$`, 'i'),
_a);
let ItemRenderer = class ItemRenderer {
constructor(_editor, _modelService, _modeService, _themeService) {
this._editor = _editor;
this._modelService = _modelService;
this._modeService = _modeService;
this._themeService = _themeService;
this._onDidToggleDetails = new event_1.Emitter();
this.onDidToggleDetails = this._onDidToggleDetails.event;
this.templateId = 'suggestion';
}
dispose() {
this._onDidToggleDetails.dispose();
}
renderTemplate(container) {
const data = Object.create(null);
data.disposables = new lifecycle_1.DisposableStore();
data.root = container;
data.root.classList.add('show-file-icons');
data.icon = (0, dom_1.append)(container, (0, dom_1.$)('.icon'));
data.colorspan = (0, dom_1.append)(data.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'));
data.iconContainer = (0, dom_1.append)(main, (0, dom_1.$)('.icon-label.codicon'));
data.left = (0, dom_1.append)(main, (0, dom_1.$)('span.left'));
data.right = (0, dom_1.append)(main, (0, dom_1.$)('span.right'));
data.iconLabel = new iconLabel_1.IconLabel(data.left, { supportHighlights: true, supportIcons: true });
data.disposables.add(data.iconLabel);
data.parametersLabel = (0, dom_1.append)(data.left, (0, dom_1.$)('span.signature-label'));
data.qualifierLabel = (0, dom_1.append)(data.left, (0, dom_1.$)('span.qualifier-label'));
data.detailsLabel = (0, dom_1.append)(data.right, (0, dom_1.$)('span.details-label'));
data.readMore = (0, dom_1.append)(data.right, (0, dom_1.$)('span.readMore' + themeService_1.ThemeIcon.asCSSSelector(exports.suggestMoreInfoIcon)));
data.readMore.title = nls.localize(1, null);
const configureFont = () => {
const options = this._editor.getOptions();
const fontInfo = options.get(41 /* fontInfo */);
const fontFamily = fontInfo.fontFamily;
const fontFeatureSettings = fontInfo.fontFeatureSettings;
const fontSize = options.get(106 /* suggestFontSize */) || fontInfo.fontSize;
const lineHeight = options.get(107 /* suggestLineHeight */) || fontInfo.lineHeight;
const fontWeight = fontInfo.fontWeight;
const fontSizePx = `${fontSize}px`;
const lineHeightPx = `${lineHeight}px`;
data.root.style.fontSize = fontSizePx;
data.root.style.fontWeight = fontWeight;
main.style.fontFamily = fontFamily;
main.style.fontFeatureSettings = fontFeatureSettings;
main.style.lineHeight = lineHeightPx;
data.icon.style.height = lineHeightPx;
data.icon.style.width = lineHeightPx;
data.readMore.style.height = lineHeightPx;
data.readMore.style.width = lineHeightPx;
};
configureFont();
data.disposables.add(this._editor.onDidChangeConfiguration(e => {
if (e.hasChanged(41 /* fontInfo */) || e.hasChanged(106 /* suggestFontSize */) || e.hasChanged(107 /* suggestLineHeight */)) {
configureFont();
}
}));
return data;
}
renderElement(element, index, data) {
const { completion } = element;
data.root.id = getAriaId(index);
data.colorspan.style.backgroundColor = '';
const labelOptions = {
labelEscapeNewLines: true,
matches: (0, filters_1.createMatches)(element.score)
};
let color = [];
if (completion.kind === 19 /* 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 /* 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._modeService, uri_1.URI.from({ scheme: 'fake', path: element.textLabel }), files_1.FileKind.FILE);
const detailClasses = (0, getIconClasses_1.getIconClasses)(this._modelService, this._modeService, 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 /* Folder */ && this._themeService.getFileIconTheme().hasFolderIcons) {
// special logic for 'folder' completion items
data.icon.className = 'icon hide';
data.iconContainer.className = 'icon hide';
labelOptions.extraClasses = (0, arrays_1.flatten)([
(0, getIconClasses_1.getIconClasses)(this._modelService, this._modeService, uri_1.URI.from({ scheme: 'fake', path: element.textLabel }), files_1.FileKind.FOLDER),
(0, getIconClasses_1.getIconClasses)(this._modelService, this._modeService, uri_1.URI.from({ scheme: 'fake', path: completion.detail }), files_1.FileKind.FOLDER)
]);
}
else {
// normal icon
data.icon.className = 'icon hide';
data.iconContainer.className = '';
data.iconContainer.classList.add('suggest-icon', ...(0, modes_1.completionKindToCssClass)(completion.kind).split(' '));
}
if (completion.tags && completion.tags.indexOf(1 /* 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(105 /* 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();
}
};
ItemRenderer = __decorate([
__param(1, modelService_1.IModelService),
__param(2, modeService_1.IModeService),
__param(3, themeService_1.IThemeService)
], ItemRenderer);
exports.ItemRenderer = 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[680/*vs/editor/contrib/suggest/suggestWidget*/], __M([0/*require*/,1/*exports*/,522/*vs/nls!vs/editor/contrib/suggest/suggestWidget*/,8/*vs/base/common/strings*/,7/*vs/base/browser/dom*/,6/*vs/base/common/event*/,12/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,108/*vs/base/browser/ui/list/listWidget*/,16/*vs/platform/contextkey/common/contextkey*/,123/*vs/editor/contrib/suggest/suggest*/,122/*vs/platform/theme/common/styler*/,11/*vs/platform/theme/common/themeService*/,22/*vs/platform/theme/common/colorRegistry*/,71/*vs/platform/storage/common/storage*/,15/*vs/base/common/async*/,9/*vs/platform/instantiation/common/instantiation*/,257/*vs/editor/contrib/suggest/suggestWidgetDetails*/,664/*vs/editor/contrib/suggest/suggestWidgetStatus*/,679/*vs/editor/contrib/suggest/suggestWidgetRenderer*/,235/*vs/editor/contrib/suggest/resizable*/,150/*vs/editor/browser/widget/embeddedCodeEditorWidget*/,102/*vs/base/common/numbers*/,361/*vs/css!vs/editor/contrib/suggest/media/suggest*/,130/*vs/base/browser/ui/codicons/codiconStyles*/,262/*vs/editor/contrib/symbolIcons/symbolIcons*/]), function (require, exports, nls, strings, dom, event_1, errors_1, lifecycle_1, listWidget_1, contextkey_1, suggest_1, styler_1, themeService_1, colorRegistry_1, storage_1, async_1, instantiation_1, suggestWidgetDetails_1, suggestWidgetStatus_1, suggestWidgetRenderer_1, resizable_1, embeddedCodeEditorWidget_1, numbers_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SuggestContentWidget = exports.SuggestWidget = exports.editorSuggestWidgetHighlightFocusForeground = exports.editorSuggestWidgetHighlightForeground = exports.editorSuggestWidgetSelectedBackground = exports.editorSuggestWidgetSelectedIconForeground = exports.editorSuggestWidgetSelectedForeground = exports.editorSuggestWidgetForeground = exports.editorSuggestWidgetBorder = exports.editorSuggestWidgetBackground = void 0;
/**
* Suggest widget colors
*/
exports.editorSuggestWidgetBackground = (0, colorRegistry_1.registerColor)('editorSuggestWidget.background', { dark: colorRegistry_1.editorWidgetBackground, light: colorRegistry_1.editorWidgetBackground, hc: colorRegistry_1.editorWidgetBackground }, nls.localize(0, null));
exports.editorSuggestWidgetBorder = (0, colorRegistry_1.registerColor)('editorSuggestWidget.border', { dark: colorRegistry_1.editorWidgetBorder, light: colorRegistry_1.editorWidgetBorder, hc: colorRegistry_1.editorWidgetBorder }, nls.localize(1, null));
exports.editorSuggestWidgetForeground = (0, colorRegistry_1.registerColor)('editorSuggestWidget.foreground', { dark: colorRegistry_1.editorForeground, light: colorRegistry_1.editorForeground, hc: colorRegistry_1.editorForeground }, nls.localize(2, null));
exports.editorSuggestWidgetSelectedForeground = (0, colorRegistry_1.registerColor)('editorSuggestWidget.selectedForeground', { dark: colorRegistry_1.quickInputListFocusForeground, light: colorRegistry_1.quickInputListFocusForeground, hc: colorRegistry_1.quickInputListFocusForeground }, nls.localize(3, null));
exports.editorSuggestWidgetSelectedIconForeground = (0, colorRegistry_1.registerColor)('editorSuggestWidget.selectedIconForeground', { dark: colorRegistry_1.quickInputListFocusIconForeground, light: colorRegistry_1.quickInputListFocusIconForeground, hc: colorRegistry_1.quickInputListFocusIconForeground }, nls.localize(4, null));
exports.editorSuggestWidgetSelectedBackground = (0, colorRegistry_1.registerColor)('editorSuggestWidget.selectedBackground', { dark: colorRegistry_1.quickInputListFocusBackground, light: colorRegistry_1.quickInputListFocusBackground, hc: colorRegistry_1.quickInputListFocusBackground }, nls.localize(5, null));
exports.editorSuggestWidgetHighlightForeground = (0, colorRegistry_1.registerColor)('editorSuggestWidget.highlightForeground', { dark: colorRegistry_1.listHighlightForeground, light: colorRegistry_1.listHighlightForeground, hc: colorRegistry_1.listHighlightForeground }, nls.localize(6, null));
exports.editorSuggestWidgetHighlightFocusForeground = (0, colorRegistry_1.registerColor)('editorSuggestWidget.focusHighlightForeground', { dark: colorRegistry_1.listFocusHighlightForeground, light: colorRegistry_1.listFocusHighlightForeground, hc: colorRegistry_1.listFocusHighlightForeground }, nls.localize(7, null));
class PersistedWidgetSize {
constructor(_service, editor) {
this._service = _service;
this._key = `suggestWidget.size/${editor.getEditorType()}/${editor instanceof embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget}`;
}
restore() {
var _a;
const raw = (_a = this._service.get(this._key, 0 /* GLOBAL */)) !== null && _a !== void 0 ? _a : '';
try {
const obj = JSON.parse(raw);
if (dom.Dimension.is(obj)) {
return dom.Dimension.lift(obj);
}
}
catch (_b) {
// ignore
}
return undefined;
}
store(size) {
this._service.store(this._key, JSON.stringify(size), 0 /* GLOBAL */, 1 /* MACHINE */);
}
reset() {
this._service.remove(this._key, 0 /* GLOBAL */);
}
}
let SuggestWidget = class SuggestWidget {
constructor(editor, _storageService, _contextKeyService, _themeService, instantiationService) {
this.editor = editor;
this._storageService = _storageService;
this._state = 0 /* Hidden */;
this._isAuto = false;
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.Emitter();
this._onDidFocus = new event_1.Emitter();
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 => {
var _a, _b, _c, _d;
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 = (_b = (_a = state.persistedSize) === null || _a === void 0 ? void 0 : _a.height) !== null && _b !== void 0 ? _b : defaultSize.height;
}
if (!state.persistWidth || Math.abs(state.currentSize.width - width) <= threshold) {
width = (_d = (_c = state.persistedSize) === null || _c === void 0 ? void 0 : _c.width) !== null && _d !== void 0 ? _d : 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 = 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(105 /* 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,
accessibilityProvider: {
getRole: () => 'option',
getAriaLabel: (item) => {
if (item.isResolved && this._isDetailsVisible()) {
const { documentation, detail } = item.completion;
const docs = strings.format('{0}{1}', detail || '', documentation ? (typeof documentation === 'string' ? documentation : documentation.value) : '');
return nls.localize(10, null, item.textLabel, docs);
}
else {
return item.textLabel;
}
},
getWidgetAriaLabel: () => nls.localize(11, null),
getWidgetRole: () => 'listbox'
}
});
this._status = instantiationService.createInstance(suggestWidgetStatus_1.SuggestWidgetStatus, this.element.domNode);
const applyStatusBarStyle = () => this.element.domNode.classList.toggle('with-status-bar', this.editor.getOption(105 /* suggest */).showStatusBar);
applyStatusBarStyle();
this._disposables.add((0, styler_1.attachListStyler)(this._list, _themeService, {
listInactiveFocusBackground: exports.editorSuggestWidgetSelectedBackground,
listInactiveFocusOutline: colorRegistry_1.activeContrastBorder
}));
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(105 /* suggest */)) {
applyStatusBarStyle();
applyIconStyle();
}
}));
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._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() {
var _a;
this._details.widget.dispose();
this._details.dispose();
this._list.dispose();
this._status.dispose();
this._disposables.dispose();
(_a = this._loadingTimeout) === null || _a === void 0 ? void 0 : _a.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 /* 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) {
const backgroundColor = theme.getColor(exports.editorSuggestWidgetBackground);
if (backgroundColor) {
this.element.domNode.style.backgroundColor = backgroundColor.toString();
this._messageElement.style.backgroundColor = backgroundColor.toString();
this._details.widget.domNode.style.backgroundColor = backgroundColor.toString();
}
const borderColor = theme.getColor(exports.editorSuggestWidgetBorder);
if (borderColor) {
this.element.domNode.style.borderColor = borderColor.toString();
this._messageElement.style.borderColor = borderColor.toString();
this._status.element.style.borderTopColor = borderColor.toString();
this._details.widget.domNode.style.borderColor = borderColor.toString();
this._detailsBorderColor = borderColor.toString();
}
const focusBorderColor = theme.getColor(colorRegistry_1.focusBorder);
if (focusBorderColor) {
this._detailsFocusBorderColor = focusBorderColor.toString();
}
this._details.widget.borderWidth = theme.type === 'hc' ? 2 : 1;
}
_onListFocus(e) {
var _a;
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 });
return;
}
if (!this._completionModel) {
return;
}
const item = e.elements[0];
const index = e.indexes[0];
if (item !== this._focusedItem) {
(_a = this._currentSuggestionDetails) === null || _a === void 0 ? void 0 : _a.cancel();
this._currentSuggestionDetails = undefined;
this._focusedItem = item;
this._list.reveal(index);
this._currentSuggestionDetails = (0, async_1.createCancelablePromise)((token) => __awaiter(this, void 0, void 0, function* () {
const loading = (0, async_1.disposableTimeout)(() => {
if (this._isDetailsVisible()) {
this.showDetails(true);
}
}, 250);
token.onCancellationRequested(() => loading.dispose());
const result = yield item.resolve(token);
loading.dispose();
return result;
}));
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 /* Frozen */);
this.element.domNode.classList.remove('message');
switch (state) {
case 0 /* 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._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 /* Loading */:
this.element.domNode.classList.add('message');
this._messageElement.textContent = SuggestWidget.LOADING_MESSAGE;
dom.hide(this._listElement, this._status.element);
dom.show(this._messageElement);
this._details.hide();
this._show();
this._focusedItem = undefined;
break;
case 2 /* Empty */:
this.element.domNode.classList.add('message');
this._messageElement.textContent = SuggestWidget.NO_SUGGESTIONS_MESSAGE;
dom.hide(this._listElement, this._status.element);
dom.show(this._messageElement);
this._details.hide();
this._show();
this._focusedItem = undefined;
break;
case 3 /* Open */:
dom.hide(this._messageElement);
dom.show(this._listElement, this._status.element);
this._show();
break;
case 4 /* Frozen */:
dom.hide(this._messageElement);
dom.show(this._listElement, this._status.element);
this._show();
break;
case 5 /* 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 /* Hidden */) {
return;
}
this._contentWidget.setPosition(this.editor.getPosition());
this._isAuto = !!auto;
if (!this._isAuto) {
this._loadingTimeout = (0, async_1.disposableTimeout)(() => this._setState(1 /* Loading */), delay);
}
}
showSuggestions(completionModel, selectionIndex, isFrozen, isAuto) {
var _a, _b;
this._contentWidget.setPosition(this.editor.getPosition());
(_a = this._loadingTimeout) === null || _a === void 0 ? void 0 : _a.dispose();
(_b = this._currentSuggestionDetails) === null || _b === void 0 ? void 0 : _b.cancel();
this._currentSuggestionDetails = undefined;
if (this._completionModel !== completionModel) {
this._completionModel = completionModel;
}
if (isFrozen && this._state !== 2 /* Empty */ && this._state !== 0 /* Hidden */) {
this._setState(4 /* Frozen */);
return;
}
const visibleCount = this._completionModel.items.length;
const isEmpty = visibleCount === 0;
this._ctxSuggestWidgetMultipleSuggestions.set(visibleCount > 1);
if (isEmpty) {
this._setState(isAuto ? 0 /* Hidden */ : 2 /* Empty */);
this._completionModel = undefined;
return;
}
this._focusedItem = undefined;
this._list.splice(0, this._list.length, this._completionModel.items);
this._setState(isFrozen ? 4 /* Frozen */ : 3 /* Open */);
this._list.reveal(selectionIndex, 0);
this._list.setFocus([selectionIndex]);
this._layout(this.element.size);
// Reset focus border
if (this._detailsBorderColor) {
this._details.widget.domNode.style.borderColor = this._detailsBorderColor;
}
}
selectNextPage() {
switch (this._state) {
case 0 /* Hidden */:
return false;
case 5 /* Details */:
this._details.widget.pageDown();
return true;
case 1 /* Loading */:
return !this._isAuto;
default:
this._list.focusNextPage();
return true;
}
}
selectNext() {
switch (this._state) {
case 0 /* Hidden */:
return false;
case 1 /* Loading */:
return !this._isAuto;
default:
this._list.focusNext(1, true);
return true;
}
}
selectLast() {
switch (this._state) {
case 0 /* Hidden */:
return false;
case 5 /* Details */:
this._details.widget.scrollBottom();
return true;
case 1 /* Loading */:
return !this._isAuto;
default:
this._list.focusLast();
return true;
}
}
selectPreviousPage() {
switch (this._state) {
case 0 /* Hidden */:
return false;
case 5 /* Details */:
this._details.widget.pageUp();
return true;
case 1 /* Loading */:
return !this._isAuto;
default:
this._list.focusPreviousPage();
return true;
}
}
selectPrevious() {
switch (this._state) {
case 0 /* Hidden */:
return false;
case 1 /* Loading */:
return !this._isAuto;
default:
this._list.focusPrevious(1, true);
return false;
}
}
selectFirst() {
switch (this._state) {
case 0 /* Hidden */:
return false;
case 5 /* Details */:
this._details.widget.scrollTop();
return true;
case 1 /* Loading */:
return !this._isAuto;
default:
this._list.focusFirst();
return true;
}
}
getFocusedItem() {
if (this._state !== 0 /* Hidden */
&& this._state !== 2 /* Empty */
&& this._state !== 1 /* Loading */
&& this._completionModel) {
return {
item: this._list.getFocusedElements()[0],
index: this._list.getFocus()[0],
model: this._completionModel
};
}
return undefined;
}
toggleDetailsFocus() {
if (this._state === 5 /* Details */) {
this._setState(3 /* Open */);
if (this._detailsBorderColor) {
this._details.widget.domNode.style.borderColor = this._detailsBorderColor;
}
}
else if (this._state === 3 /* Open */ && this._isDetailsVisible()) {
this._setState(5 /* Details */);
if (this._detailsFocusBorderColor) {
this._details.widget.domNode.style.borderColor = this._detailsFocusBorderColor;
}
}
}
toggleDetails() {
if (this._isDetailsVisible()) {
// hide details widget
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 /* Open */ || this._state === 5 /* Details */ || this._state === 4 /* Frozen */)) {
// show details widget (iff possible)
this._ctxSuggestWidgetDetailsVisible.set(true);
this._setDetailsVisible(true);
this.showDetails(false);
}
}
showDetails(loading) {
this._details.show();
if (loading) {
this._details.widget.renderLoading();
}
else {
this._details.widget.renderItem(this._list.getFocusedElements()[0], this._explainMode);
}
this._positionDetails();
this.editor.focus();
this.element.domNode.classList.add('shows-details');
}
toggleExplainMode() {
if (this._list.getFocusedElements()[0]) {
this._explainMode = !this._explainMode;
if (!this._isDetailsVisible()) {
this.toggleDetails();
}
else {
this.showDetails(false);
}
}
}
resetPersistedSize() {
this._persistedSize.reset();
}
hideWidget() {
var _a;
(_a = this._loadingTimeout) === null || _a === void 0 ? void 0 : _a.dispose();
this._setState(0 /* 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 /* Frozen */;
}
_afterRender(position) {
if (position === null) {
if (this._isDetailsVisible()) {
this._details.hide(); //todo@jrieken soft-hide
}
return;
}
if (this._state === 2 /* Empty */ || this._state === 1 /* Loading */) {
// no special positioning when widget isn't showing list
return;
}
if (this._isDetailsVisible()) {
this._details.show();
}
this._positionDetails();
}
_layout(size) {
var _a, _b, _c;
if (!this.editor.hasModel()) {
return;
}
if (!this.editor.getDomNode()) {
// happens when running tests
return;
}
const bodyBox = dom.getClientArea(document.body);
const info = this.getLayoutInfo();
if (!size) {
size = info.defaultSize;
}
let height = size.height;
let width = size.width;
// status bar
this._status.element.style.lineHeight = `${info.itemHeight}px`;
if (this._state === 2 /* Empty */ || this._state === 1 /* 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 /* 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 maxHeightAbove = Math.min(editorBox.top + cursorBox.top - info.verticalPadding, fullHeight);
let maxHeight = Math.min(Math.max(maxHeightAbove, maxHeightBelow) + info.borderHeight, fullHeight);
if (height === ((_a = this._cappedHeight) === null || _a === void 0 ? void 0 : _a.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 = 100;
if (height > maxHeightBelow || (this._forceRenderingAbove && maxHeightAbove > forceRenderingAboveRequiredSpace)) {
this._contentWidget.setPreference(1 /* ABOVE */);
this.element.enableSashes(true, true, false, false);
maxHeight = maxHeightAbove;
}
else {
this._contentWidget.setPreference(2 /* 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: (_c = (_b = this._cappedHeight) === null || _b === void 0 ? void 0 : _b.wanted) !== null && _c !== void 0 ? _c : 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);
}
}
getLayoutInfo() {
const fontInfo = this.editor.getOption(41 /* fontInfo */);
const itemHeight = (0, numbers_1.clamp)(this.editor.getOption(107 /* suggestLineHeight */) || fontInfo.lineHeight, 8, 1000);
const statusBarHeight = !this.editor.getOption(105 /* suggest */).showStatusBar || this._state === 2 /* Empty */ || this._state === 1 /* 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 /* GLOBAL */, false);
}
_setDetailsVisible(value) {
this._storageService.store('expandSuggestionDocs', value, 0 /* GLOBAL */, 0 /* USER */);
}
forceRenderingAbove() {
if (!this._forceRenderingAbove) {
this._forceRenderingAbove = true;
this._layout(this._persistedSize.restore());
}
}
stopForceRenderingAbove() {
this._forceRenderingAbove = false;
}
};
SuggestWidget.LOADING_MESSAGE = nls.localize(8, null);
SuggestWidget.NO_SUGGESTIONS_MESSAGE = nls.localize(9, null);
SuggestWidget = __decorate([
__param(1, storage_1.IStorageService),
__param(2, contextkey_1.IContextKeyService),
__param(3, themeService_1.IThemeService),
__param(4, instantiation_1.IInstantiationService)
], SuggestWidget);
exports.SuggestWidget = 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;
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const matchHighlight = theme.getColor(exports.editorSuggestWidgetHighlightForeground);
if (matchHighlight) {
collector.addRule(`.monaco-editor .suggest-widget .monaco-list .monaco-list-row .monaco-highlighted-label .highlight { color: ${matchHighlight}; }`);
}
const matchHighlightFocus = theme.getColor(exports.editorSuggestWidgetHighlightFocusForeground);
if (matchHighlight) {
collector.addRule(`.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused .monaco-highlighted-label .highlight { color: ${matchHighlightFocus}; }`);
}
const foreground = theme.getColor(exports.editorSuggestWidgetForeground);
if (foreground) {
collector.addRule(`.monaco-editor .suggest-widget, .monaco-editor .suggest-details { color: ${foreground}; }`);
}
const selectedForeground = theme.getColor(exports.editorSuggestWidgetSelectedForeground);
if (selectedForeground) {
collector.addRule(`.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused { color: ${selectedForeground}; }`);
}
const selectedIconForeground = theme.getColor(exports.editorSuggestWidgetSelectedIconForeground);
if (selectedIconForeground) {
collector.addRule(`.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused .codicon { color: ${selectedIconForeground}; }`);
}
const link = theme.getColor(colorRegistry_1.textLinkForeground);
if (link) {
collector.addRule(`.monaco-editor .suggest-details a { color: ${link}; }`);
}
const codeBackground = theme.getColor(colorRegistry_1.textCodeBlockBackground);
if (codeBackground) {
collector.addRule(`.monaco-editor .suggest-details code { background-color: ${codeBackground}; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/platform/theme/browser/iconsStyleSheet*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/theme/common/themeService*/,79/*vs/platform/theme/common/iconRegistry*/,7/*vs/base/browser/dom*/,6/*vs/base/common/event*/]), function (require, exports, themeService_1, iconRegistry_1, dom_1, event_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getIconsStyleSheet = void 0;
function getIconsStyleSheet() {
const onDidChangeEmmiter = new event_1.Emitter();
const iconRegistry = (0, iconRegistry_1.getIconRegistry)();
iconRegistry.onDidChange(() => onDidChangeEmmiter.fire());
return {
onDidChange: onDidChangeEmmiter.event,
getCSS() {
const usedFontIds = {};
const formatIconRule = (contribution) => {
let definition = contribution.defaults;
while (themeService_1.ThemeIcon.isThemeIcon(definition)) {
const c = iconRegistry.getIcon(definition.id);
if (!c) {
return undefined;
}
definition = c.defaults;
}
const fontId = definition.fontId;
if (fontId) {
const fontContribution = iconRegistry.getIconFont(fontId);
if (fontContribution) {
usedFontIds[fontId] = fontContribution;
return `.codicon-${contribution.id}:before { content: '${definition.fontCharacter}'; font-family: ${(0, dom_1.asCSSPropertyValue)(fontId)}; }`;
}
}
return `.codicon-${contribution.id}:before { content: '${definition.fontCharacter}'; }`;
};
const rules = [];
for (let contribution of iconRegistry.getIcons()) {
const rule = formatIconRule(contribution);
if (rule) {
rules.push(rule);
}
}
for (let id in usedFontIds) {
const fontContribution = usedFontIds[id];
const src = fontContribution.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)}; }`);
}
return rules.join('\n');
}
};
}
exports.getIconsStyleSheet = getIconsStyleSheet;
});
/*---------------------------------------------------------------------------------------------
* 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/standaloneThemeServiceImpl*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,29/*vs/base/common/color*/,6/*vs/base/common/event*/,18/*vs/editor/common/modes*/,389/*vs/editor/common/modes/supports/tokenization*/,620/*vs/editor/standalone/common/themes*/,32/*vs/platform/registry/common/platform*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,2/*vs/base/common/lifecycle*/,100/*vs/platform/theme/common/theme*/,681/*vs/platform/theme/browser/iconsStyleSheet*/]), function (require, exports, dom, color_1, event_1, modes_1, tokenization_1, themes_1, platform_1, colorRegistry_1, themeService_1, lifecycle_1, theme_1, iconsStyleSheet_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StandaloneThemeServiceImpl = void 0;
const VS_THEME_NAME = 'vs';
const VS_DARK_THEME_NAME = 'vs-dark';
const HC_BLACK_THEME_NAME = 'hc-black';
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;
let 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 (let id in this.themeData.colors) {
colors.set(id, color_1.Color.fromHex(this.themeData.colors[id]));
}
if (this.themeData.inherit) {
let baseData = getBuiltinRules(this.themeData.base);
for (let 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 Object.prototype.hasOwnProperty.call(this.getColors(), colorId);
}
get type() {
switch (this.base) {
case VS_THEME_NAME: return theme_1.ColorScheme.LIGHT;
case HC_BLACK_THEME_NAME: return theme_1.ColorScheme.HIGH_CONTRAST;
default: return theme_1.ColorScheme.DARK;
}
}
get tokenTheme() {
if (!this._tokenTheme) {
let rules = [];
let encodedTokensColors = [];
if (this.themeData.inherit) {
let baseData = getBuiltinRules(this.themeData.base);
rules = baseData.rules;
if (baseData.encodedTokensColors) {
encodedTokensColors = baseData.encodedTokensColors;
}
}
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 = modes_1.TokenMetadata.getForeground(metadata);
const fontStyle = modes_1.TokenMetadata.getFontStyle(metadata);
return {
foreground: foreground,
italic: Boolean(fontStyle & 1 /* Italic */),
bold: Boolean(fontStyle & 2 /* Bold */),
underline: Boolean(fontStyle & 4 /* Underline */)
};
}
}
function isBuiltinTheme(themeName) {
return (themeName === VS_THEME_NAME
|| themeName === VS_DARK_THEME_NAME
|| themeName === HC_BLACK_THEME_NAME);
}
function getBuiltinRules(builtinTheme) {
switch (builtinTheme) {
case VS_THEME_NAME:
return themes_1.vs;
case VS_DARK_THEME_NAME:
return themes_1.vs_dark;
case HC_BLACK_THEME_NAME:
return themes_1.hc_black;
}
}
function newBuiltInTheme(builtinTheme) {
let themeData = getBuiltinRules(builtinTheme);
return new StandaloneTheme(builtinTheme, themeData);
}
class StandaloneThemeServiceImpl extends lifecycle_1.Disposable {
constructor() {
super();
this._onColorThemeChange = this._register(new event_1.Emitter());
this.onDidColorThemeChange = this._onColorThemeChange.event;
this._environment = Object.create(null);
this._autoDetectHighContrast = true;
this._knownThemes = new Map();
this._knownThemes.set(VS_THEME_NAME, newBuiltInTheme(VS_THEME_NAME));
this._knownThemes.set(VS_DARK_THEME_NAME, newBuiltInTheme(VS_DARK_THEME_NAME));
this._knownThemes.set(HC_BLACK_THEME_NAME, newBuiltInTheme(HC_BLACK_THEME_NAME));
const iconsStyleSheet = (0, iconsStyleSheet_1.getIconsStyleSheet)();
this._codiconCSS = iconsStyleSheet.getCSS();
this._themeCSS = '';
this._allCSS = `${this._codiconCSS}\n${this._themeCSS}`;
this._globalStyleElement = null;
this._styleElements = [];
this._colorMapOverride = null;
this.setTheme(VS_THEME_NAME);
iconsStyleSheet.onDidChange(() => {
this._codiconCSS = iconsStyleSheet.getCSS();
this._updateCSS();
});
dom.addMatchMediaChangeListener('(forced-colors: active)', () => {
this._updateActualTheme();
});
}
registerEditorContainer(domNode) {
if (dom.isInShadowDOM(domNode)) {
return this._registerShadowDomContainer(domNode);
}
return this._registerRegularEditorContainer();
}
_registerRegularEditorContainer() {
if (!this._globalStyleElement) {
this._globalStyleElement = dom.createStyleSheet();
this._globalStyleElement.className = 'monaco-colors';
this._globalStyleElement.textContent = this._allCSS;
this._styleElements.push(this._globalStyleElement);
}
return lifecycle_1.Disposable.None;
}
_registerShadowDomContainer(domNode) {
const styleElement = dom.createStyleSheet(domNode);
styleElement.className = 'monaco-colors';
styleElement.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(VS_THEME_NAME);
}
this._desiredTheme = theme;
this._updateActualTheme();
}
_updateActualTheme() {
const theme = (this._autoDetectHighContrast && window.matchMedia(`(forced-colors: active)`).matches
? this._knownThemes.get(HC_BLACK_THEME_NAME)
: this._desiredTheme);
if (this._theme === theme) {
// Nothing to do
return;
}
this._theme = theme;
this._updateThemeOrColorMap();
}
setAutoDetectHighContrast(autoDetectHighContrast) {
this._autoDetectHighContrast = autoDetectHighContrast;
this._updateActualTheme();
}
_updateThemeOrColorMap() {
let cssRules = [];
let hasRule = {};
let ruleCollector = {
addRule: (rule) => {
if (!hasRule[rule]) {
cssRules.push(rule);
hasRule[rule] = true;
}
}
};
themingRegistry.getThemingParticipants().forEach(p => p(this._theme, ruleCollector, this._environment));
const colorMap = this._colorMapOverride || this._theme.tokenTheme.getColorMap();
ruleCollector.addRule((0, tokenization_1.generateTokensCSSForColorMap)(colorMap));
this._themeCSS = cssRules.join('\n');
this._updateCSS();
modes_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
};
}
}
exports.StandaloneThemeServiceImpl = StandaloneThemeServiceImpl;
});
/*---------------------------------------------------------------------------------------------
* 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/undoRedo/common/undoRedo*/], __M([0/*require*/,1/*exports*/,9/*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 {
constructor() {
this.id = UndoRedoGroup._ID++;
this.order = 1;
}
nextOrder() {
if (this.id === 0) {
return 0;
}
return this.order++;
}
}
exports.UndoRedoGroup = UndoRedoGroup;
UndoRedoGroup._ID = 0;
UndoRedoGroup.None = new UndoRedoGroup();
class UndoRedoSource {
constructor() {
this.id = UndoRedoSource._ID++;
this.order = 1;
}
nextOrder() {
if (this.id === 0) {
return 0;
}
return this.order++;
}
}
exports.UndoRedoSource = UndoRedoSource;
UndoRedoSource._ID = 0;
UndoRedoSource.None = new 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[274/*vs/editor/common/services/modelServiceImpl*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,12/*vs/base/common/errors*/,35/*vs/editor/common/config/editorOptions*/,31/*vs/editor/common/model/textModel*/,18/*vs/editor/common/modes*/,146/*vs/editor/common/modes/modesRegistry*/,142/*vs/editor/common/services/textResourceConfigurationService*/,38/*vs/platform/configuration/common/configuration*/,15/*vs/base/common/async*/,23/*vs/base/common/cancellation*/,11/*vs/platform/theme/common/themeService*/,70/*vs/platform/log/common/log*/,154/*vs/platform/undoRedo/common/undoRedo*/,92/*vs/base/common/hash*/,239/*vs/editor/common/model/editStack*/,46/*vs/base/common/network*/,256/*vs/editor/common/services/semanticTokensProviderStyling*/,250/*vs/editor/common/services/getSemanticTokens*/]), function (require, exports, event_1, lifecycle_1, platform, errors, editorOptions_1, textModel_1, modes_1, modesRegistry_1, textResourceConfigurationService_1, configuration_1, async_1, cancellation_1, themeService_1, log_1, undoRedo_1, hash_1, editStack_1, network_1, semanticTokensProviderStyling_1, getSemanticTokens_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModelSemanticColoring = exports.isSemanticColoringEnabled = exports.SEMANTIC_HIGHLIGHTING_SETTING_ID = exports.ModelServiceImpl = void 0;
function MODEL_ID(resource) {
return resource.toString();
}
function computeModelSha1(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();
}
class ModelData {
constructor(model, onWillDispose, onDidChangeLanguage) {
this._modelEventListeners = new lifecycle_1.DisposableStore();
this.model = model;
this._languageSelection = null;
this._languageSelectionListener = null;
this._modelEventListeners.add(model.onWillDispose(() => onWillDispose(model)));
this._modelEventListeners.add(model.onDidChangeLanguage((e) => onDidChangeLanguage(model, e)));
}
_disposeLanguageSelection() {
if (this._languageSelectionListener) {
this._languageSelectionListener.dispose();
this._languageSelectionListener = null;
}
}
dispose() {
this._modelEventListeners.dispose();
this._disposeLanguageSelection();
}
setLanguage(languageSelection) {
this._disposeLanguageSelection();
this._languageSelection = languageSelection;
this._languageSelectionListener = this._languageSelection.onDidChange(() => this.model.setMode(languageSelection.languageIdentifier));
this.model.setMode(languageSelection.languageIdentifier);
}
}
const DEFAULT_EOL = (platform.isLinux || platform.isMacintosh) ? 1 /* LF */ : 2 /* 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;
}
}
function schemaShouldMaintainUndoRedoElements(resource) {
return (resource.scheme === network_1.Schemas.file
|| resource.scheme === network_1.Schemas.vscodeRemote
|| resource.scheme === network_1.Schemas.userData
|| resource.scheme === 'fake-fs' // for tests
);
}
let ModelServiceImpl = class ModelServiceImpl extends lifecycle_1.Disposable {
constructor(_configurationService, _resourcePropertiesService, _themeService, _logService, _undoRedoService) {
super();
this._configurationService = _configurationService;
this._resourcePropertiesService = _resourcePropertiesService;
this._themeService = _themeService;
this._logService = _logService;
this._undoRedoService = _undoRedoService;
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.onModelModeChanged = this._onModelModeChanged.event;
this._modelCreationOptionsByLanguageAndResource = Object.create(null);
this._models = {};
this._disposedModels = new Map();
this._disposedModelsHeapSize = 0;
this._semanticStyling = this._register(new SemanticStyling(this._themeService, this._logService));
this._register(this._configurationService.onDidChangeConfiguration(() => this._updateModelOptions()));
this._updateModelOptions();
this._register(new SemanticColoringFeature(this, this._themeService, this._configurationService, this._semanticStyling));
}
static _readModelOptions(config, isForSimpleWidget) {
let tabSize = editorOptions_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 = parsedIndentSize;
}
if (indentSize < 1) {
indentSize = 1;
}
}
let insertSpaces = editorOptions_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 /* CRLF */;
}
else if (eol === '\n') {
newDefaultEOL = 1 /* LF */;
}
let trimAutoWhitespace = editorOptions_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 = editorOptions_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 = editorOptions_1.EDITOR_MODEL_DEFAULTS.largeFileOptimizations;
if (config.editor && typeof config.editor.largeFileOptimizations !== 'undefined') {
largeFileOptimizations = (config.editor.largeFileOptimizations === 'false' ? false : Boolean(config.editor.largeFileOptimizations));
}
return {
isForSimpleWidget: isForSimpleWidget,
tabSize: tabSize,
indentSize: indentSize,
insertSpaces: insertSpaces,
detectIndentation: detectIndentation,
defaultEOL: newDefaultEOL,
trimAutoWhitespace: trimAutoWhitespace,
largeFileOptimizations: largeFileOptimizations
};
}
_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 /* Linux */ || platform.OS === 2 /* Macintosh */ ? '\n' : '\r\n';
}
_shouldRestoreUndoStack() {
const result = this._configurationService.getValue('files.restoreUndoStack');
if (typeof result === 'boolean') {
return result;
}
return true;
}
getCreationOptions(language, resource, isForSimpleWidget) {
let creationOptions = this._modelCreationOptionsByLanguageAndResource[language + resource];
if (!creationOptions) {
const editor = this._configurationService.getValue('editor', { overrideIdentifier: language, resource });
const eol = this._getEOL(resource, language);
creationOptions = ModelServiceImpl._readModelOptions({ editor, eol }, isForSimpleWidget);
this._modelCreationOptionsByLanguageAndResource[language + resource] = creationOptions;
}
return creationOptions;
}
_updateModelOptions() {
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.getLanguageIdentifier().language;
const uri = modelData.model.uri;
const oldOptions = oldOptionsByLanguageAndResource[language + uri];
const newOptions = this.getCreationOptions(language, uri, modelData.model.isForSimpleWidget);
ModelServiceImpl._setModelOptionsForModel(modelData.model, newOptions, oldOptions);
}
}
static _setModelOptionsForModel(model, newOptions, currentOptions) {
if (currentOptions && currentOptions.defaultEOL !== newOptions.defaultEOL && model.getLineCount() === 1) {
model.setEOL(newOptions.defaultEOL === 1 /* LF */ ? 0 /* LF */ : 1 /* CRLF */);
}
if (currentOptions
&& (currentOptions.detectIndentation === newOptions.detectIndentation)
&& (currentOptions.insertSpaces === newOptions.insertSpaces)
&& (currentOptions.tabSize === newOptions.tabSize)
&& (currentOptions.indentSize === newOptions.indentSize)
&& (currentOptions.trimAutoWhitespace === newOptions.trimAutoWhitespace)) {
// Same indent opts, no need to touch the model
return;
}
if (newOptions.detectIndentation) {
model.detectIndentation(newOptions.insertSpaces, newOptions.tabSize);
model.updateOptions({
trimAutoWhitespace: newOptions.trimAutoWhitespace
});
}
else {
model.updateOptions({
insertSpaces: newOptions.insertSpaces,
tabSize: newOptions.tabSize,
indentSize: newOptions.indentSize,
trimAutoWhitespace: newOptions.trimAutoWhitespace
});
}
}
// --- 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, languageIdentifier, resource, isForSimpleWidget) {
// create & save the model
const options = this.getCreationOptions(languageIdentifier.language, resource, isForSimpleWidget);
const model = new textModel_1.TextModel(value, options, languageIdentifier, resource, this._undoRedoService);
if (resource && this._disposedModels.has(MODEL_ID(resource))) {
const disposedModelData = this._removeDisposedModel(resource);
const elements = this._undoRedoService.getElements(resource);
const sha1IsEqual = (computeModelSha1(model) === disposedModelData.sha1);
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.languageIdentifier, resource, isForSimpleWidget);
this.setMode(modelData.model, languageSelection);
}
else {
modelData = this._createModelData(value, modesRegistry_1.PLAINTEXT_LANGUAGE_IDENTIFIER, resource, isForSimpleWidget);
}
this._onModelAdded.fire(modelData.model);
return modelData.model;
}
setMode(model, languageSelection) {
if (!languageSelection) {
return;
}
const modelData = this._models[MODEL_ID(model.uri)];
if (!modelData) {
return;
}
modelData.setLanguage(languageSelection);
}
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;
}
getSemanticTokensProviderStyling(provider) {
return this._semanticStyling.get(provider);
}
// --- end IModelService
_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() && 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 = ModelServiceImpl.MAX_MEMORY_FOR_CLOSED_FILES_UNDO_STACK;
if (!maintainUndoRedoStack) {
if (!sharesUndoRedoStack) {
const initialUndoRedoSnapshot = modelData.model.getInitialUndoRedoSnapshot();
if (initialUndoRedoSnapshot !== null) {
this._undoRedoService.restoreSnapshot(initialUndoRedoSnapshot);
}
}
}
else if (!sharesUndoRedoStack && heapSize > maxMemory) {
// the undo stack for this file would never fit in the configured memory, 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, computeModelSha1(model), model.getVersionId(), model.getAlternativeVersionId()));
}
delete this._models[modelId];
modelData.dispose();
// clean up cache
delete this._modelCreationOptionsByLanguageAndResource[model.getLanguageIdentifier().language + model.uri];
this._onModelRemoved.fire(model);
}
_onDidChangeLanguage(model, e) {
const oldModeId = e.oldLanguage;
const newModeId = model.getLanguageIdentifier().language;
const oldOptions = this.getCreationOptions(oldModeId, model.uri, model.isForSimpleWidget);
const newOptions = this.getCreationOptions(newModeId, model.uri, model.isForSimpleWidget);
ModelServiceImpl._setModelOptionsForModel(model, newOptions, oldOptions);
this._onModelModeChanged.fire({ model, oldModeId });
}
};
ModelServiceImpl.MAX_MEMORY_FOR_CLOSED_FILES_UNDO_STACK = 20 * 1024 * 1024;
ModelServiceImpl = __decorate([
__param(0, configuration_1.IConfigurationService),
__param(1, textResourceConfigurationService_1.ITextResourcePropertiesService),
__param(2, themeService_1.IThemeService),
__param(3, log_1.ILogService),
__param(4, undoRedo_1.IUndoRedoService)
], ModelServiceImpl);
exports.ModelServiceImpl = ModelServiceImpl;
exports.SEMANTIC_HIGHLIGHTING_SETTING_ID = 'editor.semanticHighlighting';
function isSemanticColoringEnabled(model, themeService, configurationService) {
var _a;
const setting = (_a = configurationService.getValue(exports.SEMANTIC_HIGHLIGHTING_SETTING_ID, { overrideIdentifier: model.getLanguageIdentifier().language, resource: model.uri })) === null || _a === void 0 ? void 0 : _a.enabled;
if (typeof setting === 'boolean') {
return setting;
}
return themeService.getColorTheme().semanticHighlighting;
}
exports.isSemanticColoringEnabled = isSemanticColoringEnabled;
class SemanticColoringFeature extends lifecycle_1.Disposable {
constructor(modelService, themeService, configurationService, semanticStyling) {
super();
this._watchers = Object.create(null);
this._semanticStyling = semanticStyling;
const register = (model) => {
this._watchers[model.uri.toString()] = new ModelSemanticColoring(model, themeService, this._semanticStyling);
};
const deregister = (model, modelSemanticColoring) => {
modelSemanticColoring.dispose();
delete this._watchers[model.uri.toString()];
};
const handleSettingOrThemeChange = () => {
for (let model of modelService.getModels()) {
const curr = this._watchers[model.uri.toString()];
if (isSemanticColoringEnabled(model, themeService, configurationService)) {
if (!curr) {
register(model);
}
}
else {
if (curr) {
deregister(model, curr);
}
}
}
};
this._register(modelService.onModelAdded((model) => {
if (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(exports.SEMANTIC_HIGHLIGHTING_SETTING_ID)) {
handleSettingOrThemeChange();
}
}));
this._register(themeService.onDidColorThemeChange(handleSettingOrThemeChange));
}
}
class SemanticStyling extends lifecycle_1.Disposable {
constructor(_themeService, _logService) {
super();
this._themeService = _themeService;
this._logService = _logService;
this._caches = new WeakMap();
this._register(this._themeService.onDidColorThemeChange(() => {
this._caches = new WeakMap();
}));
}
get(provider) {
if (!this._caches.has(provider)) {
this._caches.set(provider, new semanticTokensProviderStyling_1.SemanticTokensProviderStyling(provider.getLegend(), this._themeService, this._logService));
}
return this._caches.get(provider);
}
}
class SemanticTokensResponse {
constructor(_provider, resultId, data) {
this._provider = _provider;
this.resultId = resultId;
this.data = data;
}
dispose() {
this._provider.releaseDocumentSemanticTokens(this.resultId);
}
}
class ModelSemanticColoring extends lifecycle_1.Disposable {
constructor(model, themeService, stylingProvider) {
super();
this._isDisposed = false;
this._model = model;
this._semanticStyling = stylingProvider;
this._fetchDocumentSemanticTokens = this._register(new async_1.RunOnceScheduler(() => this._fetchDocumentSemanticTokensNow(), ModelSemanticColoring.FETCH_DOCUMENT_SEMANTIC_TOKENS_DELAY));
this._currentDocumentResponse = null;
this._currentDocumentRequestCancellationTokenSource = null;
this._documentProvidersChangeListeners = [];
this._register(this._model.onDidChangeContent(() => {
if (!this._fetchDocumentSemanticTokens.isScheduled()) {
this._fetchDocumentSemanticTokens.schedule();
}
}));
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 modes_1.DocumentSemanticTokensProviderRegistry.all(model)) {
if (typeof provider.onDidChange === 'function') {
this._documentProvidersChangeListeners.push(provider.onDidChange(() => this._fetchDocumentSemanticTokens.schedule(0)));
}
}
};
bindDocumentChangeListeners();
this._register(modes_1.DocumentSemanticTokensProviderRegistry.onDidChange(() => {
bindDocumentChangeListeners();
this._fetchDocumentSemanticTokens.schedule();
}));
this._register(themeService.onDidColorThemeChange(_ => {
// clear out existing tokens
this._setDocumentSemanticTokens(null, null, null, []);
this._fetchDocumentSemanticTokens.schedule();
}));
this._fetchDocumentSemanticTokens.schedule(0);
}
dispose() {
if (this._currentDocumentResponse) {
this._currentDocumentResponse.dispose();
this._currentDocumentResponse = null;
}
if (this._currentDocumentRequestCancellationTokenSource) {
this._currentDocumentRequestCancellationTokenSource.cancel();
this._currentDocumentRequestCancellationTokenSource = null;
}
this._setDocumentSemanticTokens(null, null, null, []);
this._isDisposed = true;
super.dispose();
}
_fetchDocumentSemanticTokensNow() {
if (this._currentDocumentRequestCancellationTokenSource) {
// there is already a request running, let it finish...
return;
}
const cancellationTokenSource = new cancellation_1.CancellationTokenSource();
const lastResultId = this._currentDocumentResponse ? this._currentDocumentResponse.resultId || null : null;
const r = (0, getSemanticTokens_1.getDocumentSemanticTokens)(this._model, lastResultId, cancellationTokenSource.token);
if (!r) {
// there is no provider
if (this._currentDocumentResponse) {
// there are semantic tokens set
this._model.setSemanticTokens(null, false);
}
return;
}
const { provider, request } = r;
this._currentDocumentRequestCancellationTokenSource = cancellationTokenSource;
const pendingChanges = [];
const contentChangeListener = this._model.onDidChangeContent((e) => {
pendingChanges.push(e);
});
const styling = this._semanticStyling.get(provider);
request.then((res) => {
this._currentDocumentRequestCancellationTokenSource = null;
contentChangeListener.dispose();
this._setDocumentSemanticTokens(provider, res || null, styling, pendingChanges);
}, (err) => {
const isExpectedError = err && (errors.isPromiseCanceledError(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) {
// More changes occurred while the request was running
if (!this._fetchDocumentSemanticTokens.isScheduled()) {
this._fetchDocumentSemanticTokens.schedule();
}
}
});
}
static _copy(src, srcOffset, dest, destOffset, length) {
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._fetchDocumentSemanticTokens.isScheduled()) {
this._fetchDocumentSemanticTokens.schedule();
}
};
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.setSemanticTokens(null, false);
return;
}
if (!tokens) {
this._model.setSemanticTokens(null, true);
rescheduleIfNeeded();
return;
}
if ((0, getSemanticTokens_1.isSemanticTokensEdits)(tokens)) {
if (!currentResponse) {
// not possible!
this._model.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];
const copyCount = srcLastStart - (edit.start + edit.deleteCount);
if (copyCount > 0) {
ModelSemanticColoring._copy(srcData, srcLastStart - copyCount, destData, destLastStart - copyCount, copyCount);
destLastStart -= copyCount;
}
if (edit.data) {
ModelSemanticColoring._copy(edit.data, 0, destData, destLastStart - edit.data.length, edit.data.length);
destLastStart -= edit.data.length;
}
srcLastStart = edit.start;
}
if (srcLastStart > 0) {
ModelSemanticColoring._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.getLanguageIdentifier());
// 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.setSemanticTokens(result, true);
}
else {
this._model.setSemanticTokens(null, true);
}
rescheduleIfNeeded();
}
}
exports.ModelSemanticColoring = ModelSemanticColoring;
ModelSemanticColoring.FETCH_DOCUMENT_SEMANTIC_TOKENS_DELAY = 300;
});
/*---------------------------------------------------------------------------------------------
* 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/gotoSymbol/peek/referencesWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,29/*vs/base/common/color*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,46/*vs/base/common/network*/,43/*vs/base/common/resources*/,150/*vs/editor/browser/widget/embeddedCodeEditorWidget*/,3/*vs/editor/common/core/range*/,31/*vs/editor/common/model/textModel*/,68/*vs/editor/common/services/resolverService*/,615/*vs/editor/contrib/gotoSymbol/peek/referencesTree*/,495/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesWidget*/,9/*vs/platform/instantiation/common/instantiation*/,121/*vs/platform/label/common/label*/,153/*vs/platform/list/browser/listService*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,124/*vs/editor/contrib/peekView/peekView*/,118/*vs/editor/contrib/gotoSymbol/referencesModel*/,212/*vs/base/browser/ui/splitview/splitview*/,154/*vs/platform/undoRedo/common/undoRedo*/,37/*vs/platform/keybinding/common/keybinding*/,353/*vs/css!vs/editor/contrib/gotoSymbol/peek/referencesWidget*/]), function (require, exports, dom, color_1, event_1, lifecycle_1, network_1, resources_1, embeddedCodeEditorWidget_1, range_1, textModel_1, resolverService_1, referencesTree_1, nls, instantiation_1, label_1, listService_1, colorRegistry_1, themeService_1, peekView, referencesModel_1, splitview_1, undoRedo_1, keybinding_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReferenceWidget = exports.LayoutData = void 0;
class DecorationsManager {
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 (let 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++) {
let 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);
}
const decorations = this._editor.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 (let [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.deltaDecorations(toRemove, []);
}
removeDecorations() {
this._editor.deltaDecorations([...this._decorations.keys()], []);
this._decorations.clear();
}
}
DecorationsManager.DecorationOptions = textModel_1.ModelDecorationOptions.register({
description: 'reference-decoration',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
className: 'reference-decoration'
});
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 (_a) {
//
}
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, _undoRedoService, _keybindingService) {
super(editor, { showFrame: false, showArrow: true, isResizeable: true, isAccessible: true }, _instantiationService);
this._defaultTreeKeyboardSupport = _defaultTreeKeyboardSupport;
this.layoutData = layoutData;
this._textModelResolverService = _textModelResolverService;
this._instantiationService = _instantiationService;
this._peekViewService = _peekViewService;
this._uriLabel = _uriLabel;
this._undoRedoService = _undoRedoService;
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._applyTheme(themeService.getColorTheme());
this._callOnDispose.add(themeService.onDidColorThemeChange(this._applyTheme.bind(this)));
this._peekViewService.addExclusiveWidget(editor, this);
this.create();
}
dispose() {
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) {
this.editor.revealRangeInCenterIfOutsideViewport(where, 0 /* Smooth */);
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 /* HORIZONTAL */ });
// editor
this._previewContainer = dom.append(containerElement, dom.$('div.preview.inline'));
let options = {
scrollBeyondLastLine: false,
scrollbar: {
verticalScrollbarSize: 14,
horizontal: 'auto',
useShadows: true,
verticalHasArrows: false,
horizontalHasArrows: false,
alwaysConsumeMouseWheel: false
},
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 = new textModel_1.TextModel(nls.localize(0, null), textModel_1.TextModel.DEFAULT_CREATION_OPTIONS, null, null, this._undoRedoService);
// 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 /* 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
let onEvent = (element, kind) => {
if (element instanceof referencesModel_1.OneReference) {
if (kind === 'show') {
this._revealReference(element, false);
}
this._onDidSelectReference.fire({ element, kind, source: 'tree' });
}
};
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(1, null);
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;
}
revealReference(reference) {
return __awaiter(this, void 0, void 0, function* () {
yield this._revealReference(reference, false);
this._onDidSelectReference.fire({ element: reference, kind: 'goto', source: 'tree' });
});
}
_revealReference(reference, revealParent) {
return __awaiter(this, void 0, void 0, function* () {
// 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(2, null));
}
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);
}
yield this._tree.expand(reference.parent);
this._tree.reveal(reference);
}
const ref = yield 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 /* Smooth */ : 1 /* 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();
}
});
}
};
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, undoRedo_1.IUndoRedoService),
__param(9, keybinding_1.IKeybindingService)
], ReferenceWidget);
exports.ReferenceWidget = ReferenceWidget;
// theming
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const findMatchHighlightColor = theme.getColor(peekView.peekViewResultsMatchHighlight);
if (findMatchHighlightColor) {
collector.addRule(`.monaco-editor .reference-zone-widget .ref-tree .referenceMatch .highlight { background-color: ${findMatchHighlightColor}; }`);
}
const referenceHighlightColor = theme.getColor(peekView.peekViewEditorMatchHighlight);
if (referenceHighlightColor) {
collector.addRule(`.monaco-editor .reference-zone-widget .preview .reference-decoration { background-color: ${referenceHighlightColor}; }`);
}
const referenceHighlightBorder = theme.getColor(peekView.peekViewEditorMatchHighlightBorder);
if (referenceHighlightBorder) {
collector.addRule(`.monaco-editor .reference-zone-widget .preview .reference-decoration { border: 2px solid ${referenceHighlightBorder}; box-sizing: border-box; }`);
}
const hcOutline = theme.getColor(colorRegistry_1.activeContrastBorder);
if (hcOutline) {
collector.addRule(`.monaco-editor .reference-zone-widget .ref-tree .referenceMatch .highlight { border: 1px dotted ${hcOutline}; box-sizing: border-box; }`);
}
const resultsBackground = theme.getColor(peekView.peekViewResultsBackground);
if (resultsBackground) {
collector.addRule(`.monaco-editor .reference-zone-widget .ref-tree { background-color: ${resultsBackground}; }`);
}
const resultsMatchForeground = theme.getColor(peekView.peekViewResultsMatchForeground);
if (resultsMatchForeground) {
collector.addRule(`.monaco-editor .reference-zone-widget .ref-tree { color: ${resultsMatchForeground}; }`);
}
const resultsFileForeground = theme.getColor(peekView.peekViewResultsFileForeground);
if (resultsFileForeground) {
collector.addRule(`.monaco-editor .reference-zone-widget .ref-tree .reference-file { color: ${resultsFileForeground}; }`);
}
const resultsSelectedBackground = theme.getColor(peekView.peekViewResultsSelectionBackground);
if (resultsSelectedBackground) {
collector.addRule(`.monaco-editor .reference-zone-widget .ref-tree .monaco-list:focus .monaco-list-rows > .monaco-list-row.selected:not(.highlighted) { background-color: ${resultsSelectedBackground}; }`);
}
const resultsSelectedForeground = theme.getColor(peekView.peekViewResultsSelectionForeground);
if (resultsSelectedForeground) {
collector.addRule(`.monaco-editor .reference-zone-widget .ref-tree .monaco-list:focus .monaco-list-rows > .monaco-list-row.selected:not(.highlighted) { color: ${resultsSelectedForeground} !important; }`);
}
const editorBackground = theme.getColor(peekView.peekViewEditorBackground);
if (editorBackground) {
collector.addRule(`.monaco-editor .reference-zone-widget .preview .monaco-editor .monaco-editor-background,` +
`.monaco-editor .reference-zone-widget .preview .monaco-editor .inputarea.ime-input {` +
` background-color: ${editorBackground};` +
`}`);
}
const editorGutterBackground = theme.getColor(peekView.peekViewEditorGutterBackground);
if (editorGutterBackground) {
collector.addRule(`.monaco-editor .reference-zone-widget .preview .monaco-editor .margin {` +
` background-color: ${editorGutterBackground};` +
`}`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/gotoSymbol/peek/referencesController*/], __M([0/*require*/,1/*exports*/,493/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesController*/,12/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,28/*vs/editor/browser/services/codeEditorService*/,9/*vs/platform/instantiation/common/instantiation*/,16/*vs/platform/contextkey/common/contextkey*/,38/*vs/platform/configuration/common/configuration*/,71/*vs/platform/storage/common/storage*/,118/*vs/editor/contrib/gotoSymbol/referencesModel*/,683/*vs/editor/contrib/gotoSymbol/peek/referencesWidget*/,3/*vs/editor/common/core/range*/,13/*vs/editor/common/core/position*/,34/*vs/platform/notification/common/notification*/,15/*vs/base/common/async*/,124/*vs/editor/contrib/peekView/peekView*/,153/*vs/platform/list/browser/listService*/,88/*vs/platform/keybinding/common/keybindingsRegistry*/,41/*vs/base/common/keyCodes*/,26/*vs/platform/commands/common/commands*/]), function (require, exports, nls, errors_1, lifecycle_1, codeEditorService_1, instantiation_1, contextkey_1, configuration_1, storage_1, referencesModel_1, referencesWidget_1, range_1, position_1, notification_1, async_1, peekView_1, listService_1, keybindingsRegistry_1, keyCodes_1, commands_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReferencesController = exports.ctxReferenceSearchVisible = void 0;
exports.ctxReferenceSearchVisible = new contextkey_1.RawContextKey('referenceSearchVisible', false, nls.localize(0, null));
let ReferencesController = class ReferencesController {
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);
}
static get(editor) {
return editor.getContribution(ReferencesController.ID);
}
dispose() {
var _a, _b;
this._referenceSearchVisible.reset();
this._disposables.dispose();
(_a = this._widget) === null || _a === void 0 ? void 0 : _a.dispose();
(_b = this._model) === null || _b === void 0 ? void 0 : _b.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 /* GLOBAL */, '{}'));
this._widget = this._instantiationService.createInstance(referencesWidget_1.ReferenceWidget, this._editor, this._defaultTreeKeyboardSupport, data);
this._widget.setTitle(nls.localize(1, null));
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 /* GLOBAL */, 1 /* MACHINE */);
this._widget = undefined;
}
this.closeWidget();
}));
this._disposables.add(this._widget.onDidSelectReference(event => {
let { 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);
}
else {
this.openReference(element, false, true);
}
break;
}
}));
const requestId = ++this._requestIdPool;
modelPromise.then(model => {
var _a;
// still current request? widget still open?
if (requestId !== this._requestIdPool || !this._widget) {
model.dispose();
return undefined;
}
(_a = this._model) === null || _a === void 0 ? void 0 : _a.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(2, null, this._model.title, this._model.references.length));
}
else {
this._widget.setMetaTitle('');
}
// set 'best' selection
let uri = this._editor.getModel().uri;
let pos = new position_1.Position(range.startLineNumber, range.startColumn);
let selection = this._model.nearestReference(uri, pos);
if (selection) {
return this._widget.setSelection(selection).then(() => {
if (this._widget && this._editor.getOption(75 /* 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();
}
}
goToNextOrPreviousReference(fwd) {
return __awaiter(this, void 0, void 0, function* () {
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();
yield this._widget.setSelection(target);
yield this._gotoReference(target);
if (editorFocus) {
this._editor.focus();
}
else if (this._widget && previewEditorFocus) {
this._widget.focusOnPreviewEditor();
}
});
}
revealReference(reference) {
return __awaiter(this, void 0, void 0, function* () {
if (!this._editor.hasModel() || !this._model || !this._widget) {
// can be called while still resolving...
return;
}
yield this._widget.revealReference(reference);
});
}
closeWidget(focusEditor = true) {
var _a, _b;
(_a = this._widget) === null || _a === void 0 ? void 0 : _a.dispose();
(_b = this._model) === null || _b === void 0 ? void 0 : _b.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) {
if (this._widget) {
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 }
}, this._editor).then(openedEditor => {
var _a;
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.get(openedEditor);
const model = this._model.clone();
this.closeWidget();
openedEditor.focus();
other.toggleWidget(range, (0, async_1.createCancelablePromise)(_ => Promise.resolve(model)), (_a = this._peekMode) !== null && _a !== void 0 ? _a : 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, pinned }
}, this._editor, sideBySide);
}
};
ReferencesController.ID = 'editor.contrib.referencesController';
ReferencesController = __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);
exports.ReferencesController = ReferencesController;
function withController(accessor, fn) {
const outerEditor = (0, peekView_1.getOuterEditor)(accessor);
if (!outerEditor) {
return;
}
let controller = ReferencesController.get(outerEditor);
if (controller) {
fn(controller);
}
}
keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'togglePeekWidgetFocus',
weight: 100 /* EditorContrib */,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 60 /* 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 /* EditorContrib */ - 10,
primary: 62 /* F4 */,
secondary: [70 /* 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 /* EditorContrib */ - 10,
primary: 1024 /* Shift */ | 62 /* F4 */,
secondary: [1024 /* Shift */ | 70 /* 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 /* EditorContrib */ - 101,
primary: 9 /* Escape */,
secondary: [1024 /* Shift */ | 9 /* 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 /* WorkbenchContrib */ + 50,
primary: 9 /* Escape */,
secondary: [1024 /* Shift */ | 9 /* Escape */],
when: contextkey_1.ContextKeyExpr.and(exports.ctxReferenceSearchVisible, contextkey_1.ContextKeyExpr.not('config.editor.stablePeek'))
});
keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'revealReference',
weight: 200 /* WorkbenchContrib */,
primary: 3 /* Enter */,
mac: {
primary: 3 /* Enter */,
secondary: [2048 /* CtrlCmd */ | 18 /* DownArrow */]
},
when: contextkey_1.ContextKeyExpr.and(exports.ctxReferenceSearchVisible, listService_1.WorkbenchListFocusContextKey),
handler(accessor) {
var _a;
const listService = accessor.get(listService_1.IListService);
const focus = (_a = listService.lastFocusedList) === null || _a === void 0 ? void 0 : _a.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 /* EditorContrib */,
primary: 2048 /* CtrlCmd */ | 3 /* Enter */,
mac: {
primary: 256 /* WinCtrl */ | 3 /* Enter */
},
when: contextkey_1.ContextKeyExpr.and(exports.ctxReferenceSearchVisible, listService_1.WorkbenchListFocusContextKey),
handler(accessor) {
var _a;
const listService = accessor.get(listService_1.IListService);
const focus = (_a = listService.lastFocusedList) === null || _a === void 0 ? void 0 : _a.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) => {
var _a;
const listService = accessor.get(listService_1.IListService);
const focus = (_a = listService.lastFocusedList) === null || _a === void 0 ? void 0 : _a.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[276/*vs/editor/contrib/gotoSymbol/goToCommands*/], __M([0/*require*/,1/*exports*/,44/*vs/base/browser/ui/aria/aria*/,15/*vs/base/common/async*/,41/*vs/base/common/keyCodes*/,17/*vs/base/common/platform*/,111/*vs/editor/browser/editorBrowser*/,14/*vs/editor/browser/editorExtensions*/,28/*vs/editor/browser/services/codeEditorService*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,25/*vs/editor/common/editorContextKeys*/,18/*vs/editor/common/modes*/,152/*vs/editor/contrib/message/messageController*/,124/*vs/editor/contrib/peekView/peekView*/,275/*vs/editor/contrib/gotoSymbol/peek/referencesController*/,118/*vs/editor/contrib/gotoSymbol/referencesModel*/,491/*vs/nls!vs/editor/contrib/gotoSymbol/goToCommands*/,33/*vs/platform/actions/common/actions*/,16/*vs/platform/contextkey/common/contextkey*/,34/*vs/platform/notification/common/notification*/,59/*vs/platform/progress/common/progress*/,266/*vs/editor/contrib/gotoSymbol/goToSymbol*/,26/*vs/platform/commands/common/commands*/,66/*vs/editor/browser/core/editorState*/,639/*vs/editor/contrib/gotoSymbol/symbolNavigation*/,39/*vs/base/browser/browser*/,24/*vs/base/common/uri*/,9/*vs/platform/instantiation/common/instantiation*/,20/*vs/base/common/types*/,150/*vs/editor/browser/widget/embeddedCodeEditorWidget*/]), function (require, exports, aria_1, async_1, keyCodes_1, platform_1, editorBrowser_1, editorExtensions_1, codeEditorService_1, corePosition, range_1, editorContextKeys_1, modes_1, messageController_1, peekView_1, referencesController_1, referencesModel_1, nls, actions_1, contextkey_1, notification_1, progress_1, goToSymbol_1, commands_1, editorState_1, symbolNavigation_1, browser_1, uri_1, instantiation_1, types_1, embeddedCodeEditorWidget_1) {
"use strict";
var _a, _b, _c, _d, _e, _f, _g, _h;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefinitionAction = void 0;
actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.EditorContext, {
submenu: actions_1.MenuId.EditorContextPeek,
title: nls.localize(0, null),
group: 'navigation',
order: 100
});
const _goToActionIds = new Set();
function registerGoToAction(ctor) {
const result = new ctor();
(0, editorExtensions_1.registerInstantiatedEditorAction)(result);
_goToActionIds.add(result.id);
return result;
}
class SymbolNavigationAction extends editorExtensions_1.EditorAction {
constructor(configuration, opts) {
super(opts);
this._configuration = configuration;
}
run(accessor, editor) {
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 model = editor.getModel();
const pos = editor.getPosition();
const cts = new editorState_1.EditorStateCancellationTokenSource(editor, 1 /* Value */ | 4 /* Position */);
const promise = (0, async_1.raceCancellation)(this._getLocationModel(model, pos, cts.token), cts.token).then((references) => __awaiter(this, void 0, void 0, function* () {
if (!references || cts.token.isCancellationRequested) {
return;
}
(0, aria_1.alert)(references.ariaMessage);
let altAction;
if (references.referenceAt(model.uri, pos)) {
const altActionId = this._getAlternativeCommand(editor);
if (altActionId !== this.id && _goToActionIds.has(altActionId)) {
altAction = editor.getAction(altActionId);
}
}
const referenceCount = references.references.length;
if (referenceCount === 0) {
// no result -> show message
if (!this._configuration.muteMessage) {
const info = model.getWordAtPosition(pos);
messageController_1.MessageController.get(editor).showMessage(this._getNoResultFoundMessage(info), pos);
}
}
else if (referenceCount === 1 && altAction) {
// already at the only result, run alternative
altAction.run();
}
else {
// normal results handling
return this._onResult(editorService, symbolNavService, editor, references);
}
}), (err) => {
// report an error
notificationService.error(err);
}).finally(() => {
cts.dispose();
});
progressService.showWhile(promise, 250);
return promise;
}
_onResult(editorService, symbolNavService, editor, model) {
return __awaiter(this, void 0, void 0, function* () {
const gotoLocation = this._getGoToPreference(editor);
if (!(editor instanceof embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget) && (this._configuration.openInPeek || (gotoLocation === 'peek' && model.references.length > 1))) {
this._openInPeek(editor, model);
}
else {
const next = model.firstReference();
const peek = model.references.length > 1 && gotoLocation === 'gotoAndPeek';
const targetEditor = yield this._openReference(editor, editorService, next, this._configuration.openToSide, !peek);
if (peek && targetEditor) {
this._openInPeek(targetEditor, model);
}
else {
model.dispose();
}
// keep remaining locations around when using
// 'goto'-mode
if (gotoLocation === 'goto') {
symbolNavService.put(next);
}
}
});
}
_openReference(editor, editorService, reference, sideBySide, highlight) {
return __awaiter(this, void 0, void 0, function* () {
// range is the target-selection-range when we have one
// and the fallback is the 'full' range
let range = undefined;
if ((0, modes_1.isLocationLink)(reference)) {
range = reference.targetSelectionRange;
}
if (!range) {
range = reference.range;
}
if (!range) {
return undefined;
}
const targetEditor = yield editorService.openCodeEditor({
resource: reference.uri,
options: {
selection: range_1.Range.collapseToStart(range),
selectionRevealType: 3 /* NearTopIfOutsideViewport */
}
}, editor, sideBySide);
if (!targetEditor) {
return undefined;
}
if (highlight) {
const modelNow = targetEditor.getModel();
const ids = targetEditor.deltaDecorations([], [{ range, options: { description: 'symbol-navigate-action-highlight', className: 'symbolHighlight' } }]);
setTimeout(() => {
if (targetEditor.getModel() === modelNow) {
targetEditor.deltaDecorations(ids, []);
}
}, 350);
}
return targetEditor;
});
}
_openInPeek(target, model) {
let controller = referencesController_1.ReferencesController.get(target);
if (controller && target.hasModel()) {
controller.toggleWidget(target.getSelection(), (0, async_1.createCancelablePromise)(_ => Promise.resolve(model)), this._configuration.openInPeek);
}
else {
model.dispose();
}
}
}
//#region --- DEFINITION
class DefinitionAction extends SymbolNavigationAction {
_getLocationModel(model, position, token) {
return __awaiter(this, void 0, void 0, function* () {
return new referencesModel_1.ReferencesModel(yield (0, goToSymbol_1.getDefinitionsAtPosition)(model, position, token), nls.localize(1, null));
});
}
_getNoResultFoundMessage(info) {
return info && info.word
? nls.localize(2, null, info.word)
: nls.localize(3, null);
}
_getAlternativeCommand(editor) {
return editor.getOption(48 /* gotoLocation */).alternativeDefinitionCommand;
}
_getGoToPreference(editor) {
return editor.getOption(48 /* gotoLocation */).multipleDefinitions;
}
}
exports.DefinitionAction = DefinitionAction;
const goToDefinitionKb = platform_1.isWeb && !browser_1.isStandalone
? 2048 /* CtrlCmd */ | 70 /* F12 */
: 70 /* F12 */;
registerGoToAction((_a = class GoToDefinitionAction extends DefinitionAction {
constructor() {
super({
openToSide: false,
openInPeek: false,
muteMessage: false
}, {
id: GoToDefinitionAction.id,
label: nls.localize(4, null),
alias: 'Go to Definition',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDefinitionProvider, editorContextKeys_1.EditorContextKeys.isInWalkThroughSnippet.toNegated()),
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: goToDefinitionKb,
weight: 100 /* EditorContrib */
},
contextMenuOpts: {
group: 'navigation',
order: 1.1
},
menuOpts: {
menuId: actions_1.MenuId.MenubarGoMenu,
group: '4_symbol_nav',
order: 2,
title: nls.localize(5, null)
}
});
commands_1.CommandsRegistry.registerCommandAlias('editor.action.goToDeclaration', GoToDefinitionAction.id);
}
},
_a.id = 'editor.action.revealDefinition',
_a));
registerGoToAction((_b = class OpenDefinitionToSideAction extends DefinitionAction {
constructor() {
super({
openToSide: true,
openInPeek: false,
muteMessage: false
}, {
id: OpenDefinitionToSideAction.id,
label: nls.localize(6, null),
alias: 'Open Definition to the Side',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDefinitionProvider, editorContextKeys_1.EditorContextKeys.isInWalkThroughSnippet.toNegated()),
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, goToDefinitionKb),
weight: 100 /* EditorContrib */
}
});
commands_1.CommandsRegistry.registerCommandAlias('editor.action.openDeclarationToTheSide', OpenDefinitionToSideAction.id);
}
},
_b.id = 'editor.action.revealDefinitionAside',
_b));
registerGoToAction((_c = class PeekDefinitionAction extends DefinitionAction {
constructor() {
super({
openToSide: false,
openInPeek: true,
muteMessage: false
}, {
id: PeekDefinitionAction.id,
label: nls.localize(7, null),
alias: 'Peek Definition',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDefinitionProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInWalkThroughSnippet.toNegated()),
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 512 /* Alt */ | 70 /* F12 */,
linux: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 68 /* F10 */ },
weight: 100 /* EditorContrib */
},
contextMenuOpts: {
menuId: actions_1.MenuId.EditorContextPeek,
group: 'peek',
order: 2
}
});
commands_1.CommandsRegistry.registerCommandAlias('editor.action.previewDeclaration', PeekDefinitionAction.id);
}
},
_c.id = 'editor.action.peekDefinition',
_c));
//#endregion
//#region --- DECLARATION
class DeclarationAction extends SymbolNavigationAction {
_getLocationModel(model, position, token) {
return __awaiter(this, void 0, void 0, function* () {
return new referencesModel_1.ReferencesModel(yield (0, goToSymbol_1.getDeclarationsAtPosition)(model, position, token), nls.localize(8, null));
});
}
_getNoResultFoundMessage(info) {
return info && info.word
? nls.localize(9, null, info.word)
: nls.localize(10, null);
}
_getAlternativeCommand(editor) {
return editor.getOption(48 /* gotoLocation */).alternativeDeclarationCommand;
}
_getGoToPreference(editor) {
return editor.getOption(48 /* gotoLocation */).multipleDeclarations;
}
}
registerGoToAction((_d = class GoToDeclarationAction extends DeclarationAction {
constructor() {
super({
openToSide: false,
openInPeek: false,
muteMessage: false
}, {
id: GoToDeclarationAction.id,
label: nls.localize(11, null),
alias: 'Go to Declaration',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDeclarationProvider, editorContextKeys_1.EditorContextKeys.isInWalkThroughSnippet.toNegated()),
contextMenuOpts: {
group: 'navigation',
order: 1.3
},
menuOpts: {
menuId: actions_1.MenuId.MenubarGoMenu,
group: '4_symbol_nav',
order: 3,
title: nls.localize(12, null)
},
});
}
_getNoResultFoundMessage(info) {
return info && info.word
? nls.localize(13, null, info.word)
: nls.localize(14, null);
}
},
_d.id = 'editor.action.revealDeclaration',
_d));
registerGoToAction(class PeekDeclarationAction extends DeclarationAction {
constructor() {
super({
openToSide: false,
openInPeek: true,
muteMessage: false
}, {
id: 'editor.action.peekDeclaration',
label: nls.localize(15, null),
alias: 'Peek Declaration',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDeclarationProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInWalkThroughSnippet.toNegated()),
contextMenuOpts: {
menuId: actions_1.MenuId.EditorContextPeek,
group: 'peek',
order: 3
}
});
}
});
//#endregion
//#region --- TYPE DEFINITION
class TypeDefinitionAction extends SymbolNavigationAction {
_getLocationModel(model, position, token) {
return __awaiter(this, void 0, void 0, function* () {
return new referencesModel_1.ReferencesModel(yield (0, goToSymbol_1.getTypeDefinitionsAtPosition)(model, position, token), nls.localize(16, null));
});
}
_getNoResultFoundMessage(info) {
return info && info.word
? nls.localize(17, null, info.word)
: nls.localize(18, null);
}
_getAlternativeCommand(editor) {
return editor.getOption(48 /* gotoLocation */).alternativeTypeDefinitionCommand;
}
_getGoToPreference(editor) {
return editor.getOption(48 /* gotoLocation */).multipleTypeDefinitions;
}
}
registerGoToAction((_e = class GoToTypeDefinitionAction extends TypeDefinitionAction {
constructor() {
super({
openToSide: false,
openInPeek: false,
muteMessage: false
}, {
id: GoToTypeDefinitionAction.ID,
label: nls.localize(19, null),
alias: 'Go to Type Definition',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasTypeDefinitionProvider, editorContextKeys_1.EditorContextKeys.isInWalkThroughSnippet.toNegated()),
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 0,
weight: 100 /* EditorContrib */
},
contextMenuOpts: {
group: 'navigation',
order: 1.4
},
menuOpts: {
menuId: actions_1.MenuId.MenubarGoMenu,
group: '4_symbol_nav',
order: 3,
title: nls.localize(20, null)
}
});
}
},
_e.ID = 'editor.action.goToTypeDefinition',
_e));
registerGoToAction((_f = class PeekTypeDefinitionAction extends TypeDefinitionAction {
constructor() {
super({
openToSide: false,
openInPeek: true,
muteMessage: false
}, {
id: PeekTypeDefinitionAction.ID,
label: nls.localize(21, null),
alias: 'Peek Type Definition',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasTypeDefinitionProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInWalkThroughSnippet.toNegated()),
contextMenuOpts: {
menuId: actions_1.MenuId.EditorContextPeek,
group: 'peek',
order: 4
}
});
}
},
_f.ID = 'editor.action.peekTypeDefinition',
_f));
//#endregion
//#region --- IMPLEMENTATION
class ImplementationAction extends SymbolNavigationAction {
_getLocationModel(model, position, token) {
return __awaiter(this, void 0, void 0, function* () {
return new referencesModel_1.ReferencesModel(yield (0, goToSymbol_1.getImplementationsAtPosition)(model, position, token), nls.localize(22, null));
});
}
_getNoResultFoundMessage(info) {
return info && info.word
? nls.localize(23, null, info.word)
: nls.localize(24, null);
}
_getAlternativeCommand(editor) {
return editor.getOption(48 /* gotoLocation */).alternativeImplementationCommand;
}
_getGoToPreference(editor) {
return editor.getOption(48 /* gotoLocation */).multipleImplementations;
}
}
registerGoToAction((_g = class GoToImplementationAction extends ImplementationAction {
constructor() {
super({
openToSide: false,
openInPeek: false,
muteMessage: false
}, {
id: GoToImplementationAction.ID,
label: nls.localize(25, null),
alias: 'Go to Implementations',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasImplementationProvider, editorContextKeys_1.EditorContextKeys.isInWalkThroughSnippet.toNegated()),
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 70 /* F12 */,
weight: 100 /* EditorContrib */
},
menuOpts: {
menuId: actions_1.MenuId.MenubarGoMenu,
group: '4_symbol_nav',
order: 4,
title: nls.localize(26, null)
},
contextMenuOpts: {
group: 'navigation',
order: 1.45
}
});
}
},
_g.ID = 'editor.action.goToImplementation',
_g));
registerGoToAction((_h = class PeekImplementationAction extends ImplementationAction {
constructor() {
super({
openToSide: false,
openInPeek: true,
muteMessage: false
}, {
id: PeekImplementationAction.ID,
label: nls.localize(27, null),
alias: 'Peek Implementations',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasImplementationProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInWalkThroughSnippet.toNegated()),
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 70 /* F12 */,
weight: 100 /* EditorContrib */
},
contextMenuOpts: {
menuId: actions_1.MenuId.EditorContextPeek,
group: 'peek',
order: 5
}
});
}
},
_h.ID = 'editor.action.peekImplementation',
_h));
//#endregion
//#region --- REFERENCES
class ReferencesAction extends SymbolNavigationAction {
_getNoResultFoundMessage(info) {
return info
? nls.localize(28, null, info.word)
: nls.localize(29, null);
}
_getAlternativeCommand(editor) {
return editor.getOption(48 /* gotoLocation */).alternativeReferenceCommand;
}
_getGoToPreference(editor) {
return editor.getOption(48 /* gotoLocation */).multipleReferences;
}
}
registerGoToAction(class GoToReferencesAction extends ReferencesAction {
constructor() {
super({
openToSide: false,
openInPeek: false,
muteMessage: false
}, {
id: 'editor.action.goToReferences',
label: nls.localize(30, null),
alias: 'Go to References',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasReferenceProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInWalkThroughSnippet.toNegated()),
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 1024 /* Shift */ | 70 /* F12 */,
weight: 100 /* EditorContrib */
},
contextMenuOpts: {
group: 'navigation',
order: 1.45
},
menuOpts: {
menuId: actions_1.MenuId.MenubarGoMenu,
group: '4_symbol_nav',
order: 5,
title: nls.localize(31, null)
},
});
}
_getLocationModel(model, position, token) {
return __awaiter(this, void 0, void 0, function* () {
return new referencesModel_1.ReferencesModel(yield (0, goToSymbol_1.getReferencesAtPosition)(model, position, true, token), nls.localize(32, null));
});
}
});
registerGoToAction(class PeekReferencesAction extends ReferencesAction {
constructor() {
super({
openToSide: false,
openInPeek: true,
muteMessage: false
}, {
id: 'editor.action.referenceSearch.trigger',
label: nls.localize(33, null),
alias: 'Peek References',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasReferenceProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInWalkThroughSnippet.toNegated()),
contextMenuOpts: {
menuId: actions_1.MenuId.EditorContextPeek,
group: 'peek',
order: 6
}
});
}
_getLocationModel(model, position, token) {
return __awaiter(this, void 0, void 0, function* () {
return new referencesModel_1.ReferencesModel(yield (0, goToSymbol_1.getReferencesAtPosition)(model, position, false, token), nls.localize(34, null));
});
}
});
//#endregion
//#region --- GENERIC goto symbols command
class GenericGoToLocationAction extends SymbolNavigationAction {
constructor(config, _references, _gotoMultipleBehaviour) {
super(config, {
id: 'editor.action.goToLocation',
label: nls.localize(35, null),
alias: 'Go To Any Symbol',
precondition: contextkey_1.ContextKeyExpr.and(peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInWalkThroughSnippet.toNegated()),
});
this._references = _references;
this._gotoMultipleBehaviour = _gotoMultipleBehaviour;
}
_getLocationModel(_model, _position, _token) {
return __awaiter(this, void 0, void 0, function* () {
return new referencesModel_1.ReferencesModel(this._references, nls.localize(36, null));
});
}
_getNoResultFoundMessage(info) {
return info && nls.localize(37, null, info.word) || '';
}
_getGoToPreference(editor) {
var _a;
return (_a = this._gotoMultipleBehaviour) !== null && _a !== void 0 ? _a : editor.getOption(48 /* gotoLocation */).multipleReferences;
}
_getAlternativeCommand() { return ''; }
}
commands_1.CommandsRegistry.registerCommand({
id: 'editor.action.goToLocations',
description: {
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: (accessor, resource, position, references, multiple, noResultsMessage, openInPeek) => __awaiter(void 0, void 0, void 0, function* () {
(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 = yield editorService.openCodeEditor({ resource }, editorService.getFocusedCodeEditor());
if ((0, editorBrowser_1.isCodeEditor)(editor)) {
editor.setPosition(position);
editor.revealPositionInCenterIfOutsideViewport(position, 0 /* 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',
description: {
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: (accessor, resource, position, references, multiple) => __awaiter(void 0, void 0, void 0, function* () {
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 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)(control.getModel(), corePosition.Position.lift(position), false, token).then(references => new referencesModel_1.ReferencesModel(references, nls.localize(38, null))));
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[277/*vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/], __M([0/*require*/,1/*exports*/,492/*vs/nls!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/,15/*vs/base/common/async*/,12/*vs/base/common/errors*/,82/*vs/base/common/htmlContent*/,57/*vs/editor/common/services/modeService*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/modes*/,14/*vs/editor/browser/editorExtensions*/,266/*vs/editor/contrib/gotoSymbol/goToSymbol*/,2/*vs/base/common/lifecycle*/,68/*vs/editor/common/services/resolverService*/,11/*vs/platform/theme/common/themeService*/,22/*vs/platform/theme/common/colorRegistry*/,66/*vs/editor/browser/core/editorState*/,276/*vs/editor/contrib/gotoSymbol/goToCommands*/,229/*vs/editor/contrib/gotoSymbol/link/clickLinkGesture*/,13/*vs/editor/common/core/position*/,20/*vs/base/common/types*/,124/*vs/editor/contrib/peekView/peekView*/,16/*vs/platform/contextkey/common/contextkey*/,352/*vs/css!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/]), function (require, exports, nls, async_1, errors_1, htmlContent_1, modeService_1, range_1, modes_1, editorExtensions_1, goToSymbol_1, lifecycle_1, resolverService_1, themeService_1, colorRegistry_1, editorState_1, goToCommands_1, clickLinkGesture_1, position_1, types_1, peekView_1, contextkey_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GotoDefinitionAtPositionEditorContribution = void 0;
let GotoDefinitionAtPositionEditorContribution = class GotoDefinitionAtPositionEditorContribution {
constructor(editor, textModelResolverService, modeService) {
this.textModelResolverService = textModelResolverService;
this.modeService = modeService;
this.toUnhook = new lifecycle_1.DisposableStore();
this.toUnhookForKeyboard = new lifecycle_1.DisposableStore();
this.linkDecorations = [];
this.currentWordAtPosition = null;
this.previousPromise = null;
this.editor = editor;
let linkGesture = new clickLinkGesture_1.ClickLinkGesture(editor);
this.toUnhook.add(linkGesture);
this.toUnhook.add(linkGesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
this.startFindDefinitionFromMouse(mouseEvent, (0, types_1.withNullAsUndefined)(keyboardEvent));
}));
this.toUnhook.add(linkGesture.onExecute((mouseEvent) => {
if (this.isEnabled(mouseEvent)) {
this.gotoDefinition(mouseEvent.target.position, mouseEvent.hasSideBySideModifier).then(() => {
this.removeLinkDecorations();
}, (error) => {
this.removeLinkDecorations();
(0, errors_1.onUnexpectedError)(error);
});
}
}));
this.toUnhook.add(linkGesture.onCancel(() => {
this.removeLinkDecorations();
this.currentWordAtPosition = null;
}));
}
static get(editor) {
return editor.getContribution(GotoDefinitionAtPositionEditorContribution.ID);
}
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
return this.startFindDefinition(position).then(() => {
// 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 /* 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);
}
startFindDefinition(position) {
var _a;
// Dispose listeners for updating decorations when using keyboard to show definition hover
this.toUnhookForKeyboard.clear();
// Find word at mouse position
const word = position ? (_a = this.editor.getModel()) === null || _a === void 0 ? void 0 : _a.getWordAtPosition(position) : null;
if (!word) {
this.currentWordAtPosition = null;
this.removeLinkDecorations();
return Promise.resolve(0);
}
// 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 Promise.resolve(0);
}
this.currentWordAtPosition = word;
// Find definition and decorate word if found
let state = new editorState_1.EditorState(this.editor, 4 /* Position */ | 1 /* Value */ | 2 /* Selection */ | 8 /* Scroll */);
if (this.previousPromise) {
this.previousPromise.cancel();
this.previousPromise = null;
}
this.previousPromise = (0, async_1.createCancelablePromise)(token => this.findDefinition(position, token));
return this.previousPromise.then(results => {
if (!results || !results.length || !state.validate(this.editor)) {
this.removeLinkDecorations();
return;
}
// Multiple results
if (results.length > 1) {
this.addDecoration(new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn), new htmlContent_1.MarkdownString().appendText(nls.localize(0, null, results.length)));
}
// Single result
else {
let 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);
let wordRange;
if (result.originSelectionRange) {
wordRange = range_1.Range.lift(result.originSelectionRange);
}
else {
wordRange = new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
}
const modeId = this.modeService.getModeIdByFilepathOrFirstLine(textEditorModel.uri);
this.addDecoration(wordRange, new htmlContent_1.MarkdownString().appendCodeblock(modeId ? modeId : '', previewValue));
ref.dispose();
});
}
}).then(undefined, errors_1.onUnexpectedError);
}
getPreviewValue(textEditorModel, startLineNumber, result) {
let rangeToUse = result.targetSelectionRange ? result.range : this.getPreviewRangeBasedOnBrackets(textEditorModel, startLineNumber);
const numberOfLinesInRange = rangeToUse.endLineNumber - rangeToUse.startLineNumber;
if (numberOfLinesInRange >= GotoDefinitionAtPositionEditorContribution.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.MAX_SOURCE_PREVIEW_LINES);
let endLineNumber = startLineNumber + 1;
for (; endLineNumber < maxLineNumber; endLineNumber++) {
let endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber);
if (startIndent === endIndent) {
break;
}
}
return new range_1.Range(startLineNumber, 1, endLineNumber + 1, 1);
}
getPreviewRangeBasedOnBrackets(textEditorModel, startLineNumber) {
const maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + GotoDefinitionAtPositionEditorContribution.MAX_SOURCE_PREVIEW_LINES);
const brackets = [];
let ignoreFirstEmpty = true;
let currentBracket = textEditorModel.findNextBracket(new position_1.Position(startLineNumber, 1));
while (currentBracket !== null) {
if (brackets.length === 0) {
brackets.push(currentBracket);
}
else {
const lastBracket = brackets[brackets.length - 1];
if (lastBracket.open[0] === currentBracket.open[0] && lastBracket.isOpen && !currentBracket.isOpen) {
brackets.pop();
}
else {
brackets.push(currentBracket);
}
if (brackets.length === 0) {
if (ignoreFirstEmpty) {
ignoreFirstEmpty = false;
}
else {
return new range_1.Range(startLineNumber, 1, currentBracket.range.endLineNumber + 1, 1);
}
}
}
const maxColumn = textEditorModel.getLineMaxColumn(startLineNumber);
let nextLineNumber = currentBracket.range.endLineNumber;
let nextColumn = currentBracket.range.endColumn;
if (maxColumn === currentBracket.range.endColumn) {
nextLineNumber++;
nextColumn = 1;
}
if (nextLineNumber > maxLineNumber) {
return new range_1.Range(startLineNumber, 1, maxLineNumber + 1, 1);
}
currentBracket = textEditorModel.findNextBracket(new position_1.Position(nextLineNumber, nextColumn));
}
return new range_1.Range(startLineNumber, 1, maxLineNumber + 1, 1);
}
addDecoration(range, hoverMessage) {
const newDecorations = {
range: range,
options: {
description: 'goto-definition-link',
inlineClassName: 'goto-definition-link',
hoverMessage
}
};
this.linkDecorations = this.editor.deltaDecorations(this.linkDecorations, [newDecorations]);
}
removeLinkDecorations() {
if (this.linkDecorations.length > 0) {
this.linkDecorations = this.editor.deltaDecorations(this.linkDecorations, []);
}
}
isEnabled(mouseEvent, withKey) {
return this.editor.hasModel() &&
mouseEvent.isNoneOrSingleMouseDown &&
(mouseEvent.target.type === 6 /* CONTENT_TEXT */) &&
(mouseEvent.hasTriggerModifier || (withKey ? withKey.keyCodeIsTriggerKey : false)) &&
modes_1.DefinitionProviderRegistry.has(this.editor.getModel());
}
findDefinition(position, token) {
const model = this.editor.getModel();
if (!model) {
return Promise.resolve(null);
}
return (0, goToSymbol_1.getDefinitionsAtPosition)(model, position, token);
}
gotoDefinition(position, openToSide) {
this.editor.setPosition(position);
return this.editor.invokeWithinContext((accessor) => {
const canPeek = !openToSide && this.editor.getOption(76 /* definitionLinkOpensInPeek */) && !this.isInPeekEditor(accessor);
const action = new goToCommands_1.DefinitionAction({ openToSide, openInPeek: canPeek, muteMessage: true }, { alias: '', label: '', id: '', precondition: undefined });
return action.run(accessor, this.editor);
});
}
isInPeekEditor(accessor) {
const contextKeyService = accessor.get(contextkey_1.IContextKeyService);
return peekView_1.PeekContext.inPeekEditor.getValue(contextKeyService);
}
dispose() {
this.toUnhook.dispose();
}
};
GotoDefinitionAtPositionEditorContribution.ID = 'editor.contrib.gotodefinitionatposition';
GotoDefinitionAtPositionEditorContribution.MAX_SOURCE_PREVIEW_LINES = 8;
GotoDefinitionAtPositionEditorContribution = __decorate([
__param(1, resolverService_1.ITextModelService),
__param(2, modeService_1.IModeService)
], GotoDefinitionAtPositionEditorContribution);
exports.GotoDefinitionAtPositionEditorContribution = GotoDefinitionAtPositionEditorContribution;
(0, editorExtensions_1.registerEditorContribution)(GotoDefinitionAtPositionEditorContribution.ID, GotoDefinitionAtPositionEditorContribution);
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const activeLinkForeground = theme.getColor(colorRegistry_1.editorActiveLinkForeground);
if (activeLinkForeground) {
collector.addRule(`.monaco-editor .goto-definition-link { color: ${activeLinkForeground} !important; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/viewportSemanticTokens/viewportSemanticTokens*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,18/*vs/editor/common/modes*/,36/*vs/editor/common/services/modelService*/,256/*vs/editor/common/services/semanticTokensProviderStyling*/,11/*vs/platform/theme/common/themeService*/,38/*vs/platform/configuration/common/configuration*/,274/*vs/editor/common/services/modelServiceImpl*/,250/*vs/editor/common/services/getSemanticTokens*/]), function (require, exports, async_1, lifecycle_1, editorExtensions_1, modes_1, modelService_1, semanticTokensProviderStyling_1, themeService_1, configuration_1, modelServiceImpl_1, getSemanticTokens_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let ViewportSemanticTokensContribution = class ViewportSemanticTokensContribution extends lifecycle_1.Disposable {
constructor(editor, _modelService, _themeService, _configurationService) {
super();
this._modelService = _modelService;
this._themeService = _themeService;
this._configurationService = _configurationService;
this._editor = editor;
this._tokenizeViewport = new async_1.RunOnceScheduler(() => this._tokenizeViewportNow(), 100);
this._outstandingRequests = [];
this._register(this._editor.onDidScrollChange(() => {
this._tokenizeViewport.schedule();
}));
this._register(this._editor.onDidChangeModel(() => {
this._cancelAll();
this._tokenizeViewport.schedule();
}));
this._register(this._editor.onDidChangeModelContent((e) => {
this._cancelAll();
this._tokenizeViewport.schedule();
}));
this._register(modes_1.DocumentRangeSemanticTokensProviderRegistry.onDidChange(() => {
this._cancelAll();
this._tokenizeViewport.schedule();
}));
this._register(this._configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(modelServiceImpl_1.SEMANTIC_HIGHLIGHTING_SETTING_ID)) {
this._cancelAll();
this._tokenizeViewport.schedule();
}
}));
this._register(this._themeService.onDidColorThemeChange(() => {
this._cancelAll();
this._tokenizeViewport.schedule();
}));
}
_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.hasCompleteSemanticTokens()) {
return;
}
if (!(0, modelServiceImpl_1.isSemanticColoringEnabled)(model, this._themeService, this._configurationService)) {
if (model.hasSomeSemanticTokens()) {
model.setSemanticTokens(null, false);
}
return;
}
const provider = (0, getSemanticTokens_1.getDocumentRangeSemanticTokensProvider)(model);
if (!provider) {
if (model.hasSomeSemanticTokens()) {
model.setSemanticTokens(null, false);
}
return;
}
const styling = this._modelService.getSemanticTokensProviderStyling(provider);
const visibleRanges = this._editor.getVisibleRangesPlusViewportAboveBelow();
this._outstandingRequests = this._outstandingRequests.concat(visibleRanges.map(range => this._requestRange(model, range, provider, styling)));
}
_requestRange(model, range, provider, styling) {
const requestVersionId = model.getVersionId();
const request = (0, async_1.createCancelablePromise)(token => Promise.resolve(provider.provideDocumentRangeSemanticTokens(model, range, token)));
request.then((r) => {
if (!r || model.isDisposed() || model.getVersionId() !== requestVersionId) {
return;
}
model.setPartialSemanticTokens(range, (0, semanticTokensProviderStyling_1.toMultilineTokens2)(r, styling, model.getLanguageIdentifier()));
}).then(() => this._removeOutstandingRequest(request), () => this._removeOutstandingRequest(request));
return request;
}
};
ViewportSemanticTokensContribution.ID = 'editor.contrib.viewportSemanticTokens';
ViewportSemanticTokensContribution = __decorate([
__param(1, modelService_1.IModelService),
__param(2, themeService_1.IThemeService),
__param(3, configuration_1.IConfigurationService)
], ViewportSemanticTokensContribution);
(0, editorExtensions_1.registerEditorContribution)(ViewportSemanticTokensContribution.ID, ViewportSemanticTokensContribution);
});
/*---------------------------------------------------------------------------------------------
* 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/standalone/browser/referenceSearch/standaloneReferenceSearch*/], __M([0/*require*/,1/*exports*/,14/*vs/editor/browser/editorExtensions*/,28/*vs/editor/browser/services/codeEditorService*/,275/*vs/editor/contrib/gotoSymbol/peek/referencesController*/,38/*vs/platform/configuration/common/configuration*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/,34/*vs/platform/notification/common/notification*/,71/*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);
}
};
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);
exports.StandaloneReferencesController = StandaloneReferencesController;
(0, editorExtensions_1.registerEditorContribution)(referencesController_1.ReferencesController.ID, StandaloneReferencesController);
});
/*---------------------------------------------------------------------------------------------
* 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/platform/undoRedo/common/undoRedoService*/], __M([0/*require*/,1/*exports*/,543/*vs/nls!vs/platform/undoRedo/common/undoRedoService*/,154/*vs/platform/undoRedo/common/undoRedo*/,12/*vs/base/common/errors*/,75/*vs/platform/instantiation/common/extensions*/,120/*vs/platform/dialogs/common/dialogs*/,74/*vs/base/common/severity*/,46/*vs/base/common/network*/,34/*vs/platform/notification/common/notification*/,2/*vs/base/common/lifecycle*/]), function (require, exports, nls, undoRedo_1, errors_1, extensions_1, dialogs_1, severity_1, network_1, notification_1, lifecycle_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 /* 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 /* ExternalRemoval */
? externalRemoval
: noParallelUniverses);
dest.push(element.resourceLabel);
}
let messages = [];
if (externalRemoval.length > 0) {
messages.push(nls.localize(0, null, externalRemoval.join(', ')));
}
if (noParallelUniverses.length > 0) {
messages.push(nls.localize(1, null, 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 /* 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 /* 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 /* Workspace */) {
element.removeResource(this.resourceLabel, this.strResource, 0 /* ExternalRemoval */);
}
}
for (const element of this._future) {
if (element.type === 1 /* Workspace */) {
element.removeResource(this.resourceLabel, this.strResource, 0 /* ExternalRemoval */);
}
}
this.versionId++;
}
toString() {
let 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 /* 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 /* Workspace */) {
futureElement.removeResource(this.resourceLabel, this.strResource, 1 /* 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 /* Workspace */) {
element.removeResource(this.resourceLabel, this.strResource, 0 /* 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 /* Workspace */) {
element.removeResource(this.resourceLabel, this.strResource, 0 /* 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}: `);
let 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 /* 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();
}
}
_invokeWorkspacePrepare(element) {
return __awaiter(this, void 0, void 0, function* () {
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 /* 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(2, null, element.label, element.removedResources.createMessage()));
}
if (checkInvalidatedResources && element.invalidatedResources) {
return this._tryToSplitAndUndo(strResource, element, element.invalidatedResources, nls.localize(3, null, 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(4, null, 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(5, null, 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(6, null, 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;
}
_confirmAndExecuteWorkspaceUndo(strResource, element, editStackSnapshot, undoConfirmed) {
return __awaiter(this, void 0, void 0, function* () {
if (element.canSplit() && !this._isPartOfUndoGroup(element)) {
// this element can be split
const result = yield this._dialogService.show(severity_1.default.Info, nls.localize(7, null, element.label), [
nls.localize(8, null, editStackSnapshot.editStacks.length),
nls.localize(9, null),
nls.localize(10, null),
], {
cancelId: 2
});
if (result.choice === 2) {
// choice: cancel
return;
}
if (result.choice === 1) {
// 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 = yield 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(11, null, 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 /* Workspace */) {
return this._workspaceUndo(strResource, element, undoConfirmed);
}
else {
return this._resourceUndo(editStack, element, undoConfirmed);
}
}
finally {
if (DEBUG) {
this._print('undo');
}
}
}
_confirmAndContinueUndo(strResource, sourceId, element) {
return __awaiter(this, void 0, void 0, function* () {
const result = yield this._dialogService.show(severity_1.default.Info, nls.localize(12, null, element.label), [
nls.localize(13, null),
nls.localize(14, null),
], {
cancelId: 1
});
if (result.choice === 1) {
// choice: cancel
return;
}
// choice: undo
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(15, null, element.label, element.removedResources.createMessage()));
}
if (checkInvalidatedResources && element.invalidatedResources) {
return this._tryToSplitAndRedo(strResource, element, element.invalidatedResources, nls.localize(16, null, 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(17, null, 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(18, null, 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(19, null, 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);
}
_executeWorkspaceRedo(strResource, element, editStackSnapshot) {
return __awaiter(this, void 0, void 0, function* () {
// prepare
let cleanup;
try {
cleanup = yield 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(20, null, 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 /* Workspace */) {
return this._workspaceRedo(strResource, element);
}
else {
return this._resourceRedo(editStack, element);
}
}
finally {
if (DEBUG) {
this._print('redo');
}
}
}
};
UndoRedoService = __decorate([
__param(0, dialogs_1.IDialogService),
__param(1, notification_1.INotificationService)
], UndoRedoService);
exports.UndoRedoService = UndoRedoService;
class WorkspaceVerificationError {
constructor(returnValue) {
this.returnValue = returnValue;
}
}
(0, extensions_1.registerSingleton)(undoRedo_1.IUndoRedoService, UndoRedoService);
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[193/*vs/platform/workspace/common/workspace*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,49/*vs/base/common/map*/]), function (require, exports, instantiation_1, map_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkspaceFolder = exports.Workspace = exports.IWorkspaceContextService = void 0;
exports.IWorkspaceContextService = (0, instantiation_1.createDecorator)('contextService');
class Workspace {
constructor(_id, folders, _configuration, _ignorePathCasing) {
this._id = _id;
this._configuration = _configuration;
this._ignorePathCasing = _ignorePathCasing;
this._foldersMap = map_1.TernarySearchTree.forUris(this._ignorePathCasing);
this.folders = folders;
}
get folders() {
return this._folders;
}
set folders(folders) {
this._folders = folders;
this.updateFoldersMap();
}
get id() {
return this._id;
}
get configuration() {
return this._configuration;
}
set configuration(configuration) {
this._configuration = configuration;
}
getFolder(resource) {
if (!resource) {
return null;
}
return this._foldersMap.findSubstr(resource.with({
scheme: resource.scheme,
authority: resource.authority,
path: resource.path
})) || null;
}
updateFoldersMap() {
this._foldersMap = map_1.TernarySearchTree.forUris(this._ignorePathCasing);
for (const folder of this.folders) {
this._foldersMap.set(folder.uri, folder);
}
}
toJSON() {
return { id: this.id, folders: this.folders, configuration: this.configuration };
}
}
exports.Workspace = Workspace;
class WorkspaceFolder {
constructor(data, 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;
});
/*---------------------------------------------------------------------------------------------
* 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/editor/standalone/browser/simpleServices*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,7/*vs/base/browser/dom*/,51/*vs/base/browser/keyboardEvent*/,6/*vs/base/common/event*/,41/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,74/*vs/base/common/severity*/,24/*vs/base/common/uri*/,111/*vs/editor/browser/editorBrowser*/,138/*vs/editor/browser/services/bulkEditService*/,190/*vs/editor/common/config/commonEditorConfig*/,56/*vs/editor/common/core/editOperation*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,36/*vs/editor/common/services/modelService*/,26/*vs/platform/commands/common/commands*/,38/*vs/platform/configuration/common/configuration*/,583/*vs/platform/configuration/common/configurationModels*/,565/*vs/platform/keybinding/common/abstractKeybindingService*/,254/*vs/platform/keybinding/common/keybindingResolver*/,88/*vs/platform/keybinding/common/keybindingsRegistry*/,567/*vs/platform/keybinding/common/resolvedKeybindingItem*/,568/*vs/platform/keybinding/common/usLayoutResolvedKeybinding*/,34/*vs/platform/notification/common/notification*/,193/*vs/platform/workspace/common/workspace*/,63/*vs/editor/common/standaloneStrings*/]), function (require, exports, strings, dom, keyboardEvent_1, event_1, keyCodes_1, lifecycle_1, platform_1, severity_1, uri_1, editorBrowser_1, bulkEditService_1, commonEditorConfig_1, editOperation_1, position_1, range_1, modelService_1, commands_1, configuration_1, configurationModels_1, abstractKeybindingService_1, keybindingResolver_1, keybindingsRegistry_1, resolvedKeybindingItem_1, usLayoutResolvedKeybinding_1, notification_1, workspace_1, standaloneStrings_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleLayoutService = exports.SimpleUriLabelService = exports.SimpleBulkEditService = exports.updateConfigurationService = exports.SimpleWorkspaceContextService = exports.StandaloneTelemetryService = exports.SimpleResourcePropertiesService = exports.SimpleResourceConfigurationService = exports.SimpleConfigurationService = exports.StandaloneKeybindingService = exports.StandaloneCommandService = exports.SimpleNotificationService = exports.SimpleDialogService = exports.SimpleEditorProgressService = exports.SimpleEditorModelResolverService = exports.SimpleModel = void 0;
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();
}
}
exports.SimpleModel = SimpleModel;
function withTypedEditor(widget, codeEditorCallback, diffEditorCallback) {
if ((0, editorBrowser_1.isCodeEditor)(widget)) {
// Single Editor
return codeEditorCallback(widget);
}
else {
// Diff Editor
return diffEditorCallback(widget);
}
}
let SimpleEditorModelResolverService = class SimpleEditorModelResolverService {
constructor(modelService) {
this.modelService = modelService;
}
setEditor(editor) {
this.editor = editor;
}
createModelReference(resource) {
let model = null;
if (this.editor) {
model = withTypedEditor(this.editor, (editor) => this.findModel(editor, resource), (diffEditor) => this.findModel(diffEditor.getOriginalEditor(), resource) || this.findModel(diffEditor.getModifiedEditor(), resource));
}
if (!model) {
return Promise.reject(new Error(`Model not found`));
}
return Promise.resolve(new lifecycle_1.ImmortalReference(new SimpleModel(model)));
}
findModel(editor, resource) {
let model = this.modelService.getModel(resource);
if (model && model.uri.toString() !== resource.toString()) {
return null;
}
return model;
}
};
SimpleEditorModelResolverService = __decorate([
__param(0, modelService_1.IModelService)
], SimpleEditorModelResolverService);
exports.SimpleEditorModelResolverService = SimpleEditorModelResolverService;
class SimpleEditorProgressService {
show() {
return SimpleEditorProgressService.NULL_PROGRESS_RUNNER;
}
showWhile(promise, delay) {
return __awaiter(this, void 0, void 0, function* () {
yield promise;
});
}
}
exports.SimpleEditorProgressService = SimpleEditorProgressService;
SimpleEditorProgressService.NULL_PROGRESS_RUNNER = {
done: () => { },
total: () => { },
worked: () => { }
};
class SimpleDialogService {
confirm(confirmation) {
return this.doConfirm(confirmation).then(confirmed => {
return {
confirmed,
checkboxChecked: false // unsupported
};
});
}
doConfirm(confirmation) {
let messageText = confirmation.message;
if (confirmation.detail) {
messageText = messageText + '\n\n' + confirmation.detail;
}
return Promise.resolve(window.confirm(messageText));
}
show(severity, message, buttons, options) {
return Promise.resolve({ choice: 0 });
}
}
exports.SimpleDialogService = SimpleDialogService;
class SimpleNotificationService {
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 SimpleNotificationService.NO_OP;
}
status(message, options) {
return lifecycle_1.Disposable.None;
}
}
exports.SimpleNotificationService = SimpleNotificationService;
SimpleNotificationService.NO_OP = new notification_1.NoOpNotification();
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;
class StandaloneKeybindingService extends abstractKeybindingService_1.AbstractKeybindingService {
constructor(contextKeyService, commandService, telemetryService, notificationService, logService, domNode) {
super(contextKeyService, commandService, telemetryService, notificationService, logService);
this._cachedResolver = null;
this._dynamicKeybindings = [];
// for standard keybindings
this._register(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)
this._register(dom.addDisposableListener(window, dom.EventType.KEY_UP, (e) => {
const keyEvent = new keyboardEvent_1.StandardKeyboardEvent(e);
const shouldPreventDefault = this._singleModifierDispatch(keyEvent, keyEvent.target);
if (shouldPreventDefault) {
keyEvent.preventDefault();
}
}));
}
addDynamicKeybinding(commandId, _keybinding, handler, when) {
const keybinding = (0, keyCodes_1.createKeybinding)(_keybinding, platform_1.OS);
const toDispose = new lifecycle_1.DisposableStore();
if (keybinding) {
this._dynamicKeybindings.push({
keybinding: keybinding,
command: commandId,
when: when,
weight1: 1000,
weight2: 0,
extensionId: null,
isBuiltinExtension: false
});
toDispose.add((0, lifecycle_1.toDisposable)(() => {
for (let i = 0; i < this._dynamicKeybindings.length; i++) {
let kb = this._dynamicKeybindings[i];
if (kb.command === commandId) {
this._dynamicKeybindings.splice(i, 1);
this.updateResolver({ source: 1 /* Default */ });
return;
}
}
}));
}
toDispose.add(commands_1.CommandsRegistry.registerCommand(commandId, handler));
this.updateResolver({ source: 1 /* Default */ });
return toDispose;
}
updateResolver(event) {
this._cachedResolver = null;
this._onDidUpdateKeybindings.fire(event);
}
_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 document.hasFocus();
}
_toNormalizedKeybindingItems(items, isDefault) {
let result = [], 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 = this.resolveKeybinding(keybinding);
for (const resolvedKeybinding of resolvedKeybindings) {
result[resultLen++] = new resolvedKeybindingItem_1.ResolvedKeybindingItem(resolvedKeybinding, item.command, item.commandArgs, when, isDefault, null, false);
}
}
}
return result;
}
resolveKeybinding(keybinding) {
return [new usLayoutResolvedKeybinding_1.USLayoutResolvedKeybinding(keybinding, platform_1.OS)];
}
resolveKeyboardEvent(keyboardEvent) {
let keybinding = new keyCodes_1.SimpleKeybinding(keyboardEvent.ctrlKey, keyboardEvent.shiftKey, keyboardEvent.altKey, keyboardEvent.metaKey, keyboardEvent.keyCode).toChord();
return new usLayoutResolvedKeybinding_1.USLayoutResolvedKeybinding(keybinding, platform_1.OS);
}
}
exports.StandaloneKeybindingService = StandaloneKeybindingService;
function isConfigurationOverrides(thing) {
return thing
&& typeof thing === 'object'
&& (!thing.overrideIdentifier || typeof thing.overrideIdentifier === 'string')
&& (!thing.resource || thing.resource instanceof uri_1.URI);
}
class SimpleConfigurationService {
constructor() {
this._onDidChangeConfiguration = new event_1.Emitter();
this.onDidChangeConfiguration = this._onDidChangeConfiguration.event;
this._configuration = new configurationModels_1.Configuration(new configurationModels_1.DefaultConfigurationModel(), new configurationModels_1.ConfigurationModel());
}
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() };
let 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);
configurationChangeEvent.source = 7 /* MEMORY */;
configurationChangeEvent.sourceConfig = null;
this._onDidChangeConfiguration.fire(configurationChangeEvent);
}
return Promise.resolve();
}
}
exports.SimpleConfigurationService = SimpleConfigurationService;
class SimpleResourceConfigurationService {
constructor(configurationService) {
this.configurationService = configurationService;
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);
if (typeof section === 'undefined') {
return this.configurationService.getValue();
}
return this.configurationService.getValue(section);
}
}
exports.SimpleResourceConfigurationService = SimpleResourceConfigurationService;
let SimpleResourcePropertiesService = class SimpleResourcePropertiesService {
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';
}
};
SimpleResourcePropertiesService = __decorate([
__param(0, configuration_1.IConfigurationService)
], SimpleResourcePropertiesService);
exports.SimpleResourcePropertiesService = SimpleResourcePropertiesService;
class StandaloneTelemetryService {
publicLog(eventName, data) {
return Promise.resolve(undefined);
}
publicLog2(eventName, data) {
return this.publicLog(eventName, data);
}
}
exports.StandaloneTelemetryService = StandaloneTelemetryService;
class SimpleWorkspaceContextService {
constructor() {
const resource = uri_1.URI.from({ scheme: SimpleWorkspaceContextService.SCHEME, authority: 'model', path: '/' });
this.workspace = { id: '4064f6ec-cb38-4ad0-af64-ee6467e63c82', folders: [new workspace_1.WorkspaceFolder({ uri: resource, name: '', index: 0 })] };
}
getWorkspace() {
return this.workspace;
}
}
exports.SimpleWorkspaceContextService = SimpleWorkspaceContextService;
SimpleWorkspaceContextService.SCHEME = 'inmemory';
function updateConfigurationService(configurationService, source, isDiffEditor) {
if (!source) {
return;
}
if (!(configurationService instanceof SimpleConfigurationService)) {
return;
}
let toUpdate = [];
Object.keys(source).forEach((key) => {
if ((0, commonEditorConfig_1.isEditorConfigurationKey)(key)) {
toUpdate.push([`editor.${key}`, source[key]]);
}
if (isDiffEditor && (0, commonEditorConfig_1.isDiffEditorConfigurationKey)(key)) {
toUpdate.push([`diffEditor.${key}`, source[key]]);
}
});
if (toUpdate.length > 0) {
configurationService.updateValues(toUpdate);
}
}
exports.updateConfigurationService = updateConfigurationService;
class SimpleBulkEditService {
constructor(_modelService) {
this._modelService = _modelService;
//
}
hasPreviewHandler() {
return false;
}
apply(edits, _options) {
return __awaiter(this, void 0, void 0, function* () {
const textEdits = new Map();
for (let 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.SimpleServicesNLS.bulkEditServiceSummary, totalEdits, totalFiles)
};
});
}
}
exports.SimpleBulkEditService = SimpleBulkEditService;
class SimpleUriLabelService {
getUriLabel(resource, options) {
if (resource.scheme === 'file') {
return resource.fsPath;
}
return resource.path;
}
}
exports.SimpleUriLabelService = SimpleUriLabelService;
class SimpleLayoutService {
constructor(_codeEditorService, _container) {
this._codeEditorService = _codeEditorService;
this._container = _container;
this.onDidLayout = event_1.Event.None;
}
get dimension() {
if (!this._dimension) {
this._dimension = dom.getClientArea(window.document.body);
}
return this._dimension;
}
get container() {
return this._container;
}
focus() {
var _a;
(_a = this._codeEditorService.getFocusedCodeEditor()) === null || _a === void 0 ? void 0 : _a.focus();
}
}
exports.SimpleLayoutService = SimpleLayoutService;
});
/*---------------------------------------------------------------------------------------------
* 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/editor/standalone/browser/standaloneCodeEditor*/], __M([0/*require*/,1/*exports*/,44/*vs/base/browser/ui/aria/aria*/,2/*vs/base/common/lifecycle*/,28/*vs/editor/browser/services/codeEditorService*/,149/*vs/editor/browser/widget/codeEditorWidget*/,271/*vs/editor/browser/widget/diffEditorWidget*/,219/*vs/editor/common/editorAction*/,76/*vs/editor/common/services/editorWorkerService*/,194/*vs/editor/standalone/browser/simpleServices*/,119/*vs/editor/standalone/common/standaloneThemeService*/,33/*vs/platform/actions/common/actions*/,26/*vs/platform/commands/common/commands*/,38/*vs/platform/configuration/common/configuration*/,16/*vs/platform/contextkey/common/contextkey*/,69/*vs/platform/contextview/browser/contextView*/,9/*vs/platform/instantiation/common/instantiation*/,37/*vs/platform/keybinding/common/keybinding*/,34/*vs/platform/notification/common/notification*/,11/*vs/platform/theme/common/themeService*/,64/*vs/platform/accessibility/common/accessibility*/,63/*vs/editor/common/standaloneStrings*/,86/*vs/platform/clipboard/common/clipboardService*/,59/*vs/platform/progress/common/progress*/,36/*vs/editor/common/services/modelService*/,57/*vs/editor/common/services/modeService*/,263/*vs/editor/standalone/browser/standaloneCodeServiceImpl*/,106/*vs/base/common/mime*/]), function (require, exports, aria, lifecycle_1, codeEditorService_1, codeEditorWidget_1, diffEditorWidget_1, editorAction_1, editorWorkerService_1, simpleServices_1, standaloneThemeService_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, modelService_1, modeService_1, standaloneCodeServiceImpl_1, mime_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTextModel = exports.StandaloneDiffEditor = exports.StandaloneEditor = exports.StandaloneCodeEditor = void 0;
let LAST_GENERATED_COMMAND_ID = 0;
let ariaDomNodeCreated = false;
function createAriaDomNode() {
if (ariaDomNodeCreated) {
return;
}
ariaDomNodeCreated = true;
aria.setARIAContainer(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, keybindingService, themeService, notificationService, accessibilityService) {
const options = Object.assign({}, _options);
options.ariaLabel = options.ariaLabel || standaloneStrings_1.StandaloneCodeEditorNLS.editorViewAccessibleLabel;
options.ariaLabel = options.ariaLabel + ';' + (standaloneStrings_1.StandaloneCodeEditorNLS.accessibilityHelpMessage);
super(domElement, options, {}, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService);
if (keybindingService instanceof simpleServices_1.StandaloneKeybindingService) {
this._standaloneKeybindingService = keybindingService;
}
else {
this._standaloneKeybindingService = null;
}
// Create the ARIA dom node as soon as the first editor is instantiated
createAriaDomNode();
}
addCommand(keybinding, handler, context) {
if (!this._standaloneKeybindingService) {
console.warn('Cannot add command because the editor is configured with an unrecognized KeybindingService');
return null;
}
let commandId = 'DYNAMIC_' + (++LAST_GENERATED_COMMAND_ID);
let 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) {
let 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
let internalAction = new editorAction_1.InternalEditorAction(uniqueId, label, label, precondition, run, this._contextKeyService);
// Store it under the original id, such that trigger with the original id will work
this._actions[id] = internalAction;
toDispose.add((0, lifecycle_1.toDisposable)(() => {
delete this._actions[id];
}));
return toDispose;
}
_triggerCommand(handlerId, payload) {
if (this._codeEditorService instanceof standaloneCodeServiceImpl_1.StandaloneCodeEditorServiceImpl) {
// 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);
}
}
};
StandaloneCodeEditor = __decorate([
__param(2, instantiation_1.IInstantiationService),
__param(3, codeEditorService_1.ICodeEditorService),
__param(4, commands_1.ICommandService),
__param(5, contextkey_1.IContextKeyService),
__param(6, keybinding_1.IKeybindingService),
__param(7, themeService_1.IThemeService),
__param(8, notification_1.INotificationService),
__param(9, accessibility_1.IAccessibilityService)
], StandaloneCodeEditor);
exports.StandaloneCodeEditor = StandaloneCodeEditor;
let StandaloneEditor = class StandaloneEditor extends StandaloneCodeEditor {
constructor(domElement, _options, toDispose, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, contextViewService, themeService, notificationService, configurationService, accessibilityService, modelService, modeService) {
const options = Object.assign({}, _options);
(0, simpleServices_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));
}
let _model = options.model;
delete options.model;
super(domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, themeService, notificationService, accessibilityService);
this._contextViewService = contextViewService;
this._configurationService = configurationService;
this._standaloneThemeService = themeService;
this._register(toDispose);
this._register(themeDomRegistration);
let model;
if (typeof _model === 'undefined') {
model = createTextModel(modelService, modeService, options.value || '', options.language || mime_1.Mimes.text, undefined);
this._ownsModel = true;
}
else {
model = _model;
this._ownsModel = false;
}
this._attachModel(model);
if (model) {
let e = {
oldModelUrl: null,
newModelUrl: model.uri
};
this._onDidChangeModel.fire(e);
}
}
dispose() {
super.dispose();
}
updateOptions(newOptions) {
(0, simpleServices_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);
}
_attachModel(model) {
super._attachModel(model);
if (this._modelData) {
this._contextViewService.setContainer(this._modelData.view.domNode.domNode);
}
}
_postDetachModelCleanup(detachedModel) {
super._postDetachModelCleanup(detachedModel);
if (detachedModel && this._ownsModel) {
detachedModel.dispose();
this._ownsModel = false;
}
}
};
StandaloneEditor = __decorate([
__param(3, instantiation_1.IInstantiationService),
__param(4, codeEditorService_1.ICodeEditorService),
__param(5, commands_1.ICommandService),
__param(6, contextkey_1.IContextKeyService),
__param(7, keybinding_1.IKeybindingService),
__param(8, contextView_1.IContextViewService),
__param(9, standaloneThemeService_1.IStandaloneThemeService),
__param(10, notification_1.INotificationService),
__param(11, configuration_1.IConfigurationService),
__param(12, accessibility_1.IAccessibilityService),
__param(13, modelService_1.IModelService),
__param(14, modeService_1.IModeService)
], StandaloneEditor);
exports.StandaloneEditor = StandaloneEditor;
let StandaloneDiffEditor = class StandaloneDiffEditor extends diffEditorWidget_1.DiffEditorWidget {
constructor(domElement, _options, toDispose, instantiationService, contextKeyService, keybindingService, contextViewService, editorWorkerService, codeEditorService, themeService, notificationService, configurationService, contextMenuService, editorProgressService, clipboardService) {
const options = Object.assign({}, _options);
(0, simpleServices_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, {}, clipboardService, editorWorkerService, contextKeyService, instantiationService, codeEditorService, themeService, notificationService, contextMenuService, editorProgressService);
this._contextViewService = contextViewService;
this._configurationService = configurationService;
this._standaloneThemeService = themeService;
this._register(toDispose);
this._register(themeDomRegistration);
this._contextViewService.setContainer(this._containerDomElement);
}
dispose() {
super.dispose();
}
updateOptions(newOptions) {
(0, simpleServices_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);
}
};
StandaloneDiffEditor = __decorate([
__param(3, instantiation_1.IInstantiationService),
__param(4, contextkey_1.IContextKeyService),
__param(5, keybinding_1.IKeybindingService),
__param(6, contextView_1.IContextViewService),
__param(7, editorWorkerService_1.IEditorWorkerService),
__param(8, codeEditorService_1.ICodeEditorService),
__param(9, standaloneThemeService_1.IStandaloneThemeService),
__param(10, notification_1.INotificationService),
__param(11, configuration_1.IConfigurationService),
__param(12, contextView_1.IContextMenuService),
__param(13, progress_1.IEditorProgressService),
__param(14, clipboardService_1.IClipboardService)
], StandaloneDiffEditor);
exports.StandaloneDiffEditor = StandaloneDiffEditor;
/**
* @internal
*/
function createTextModel(modelService, modeService, value, language, uri) {
value = value || '';
if (!language) {
const firstLF = value.indexOf('\n');
let firstLine = value;
if (firstLF !== -1) {
firstLine = value.substring(0, firstLF);
}
return doCreateModel(modelService, value, modeService.createByFilepathOrFirstLine(uri || null, firstLine), uri);
}
return doCreateModel(modelService, value, modeService.create(language), uri);
}
exports.createTextModel = createTextModel;
/**
* @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[278/*vs/editor/standalone/browser/standaloneServices*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,138/*vs/editor/browser/services/bulkEditService*/,28/*vs/editor/browser/services/codeEditorService*/,76/*vs/editor/common/services/editorWorkerService*/,255/*vs/editor/common/services/editorWorkerServiceImpl*/,57/*vs/editor/common/services/modeService*/,581/*vs/editor/common/services/modeServiceImpl*/,36/*vs/editor/common/services/modelService*/,274/*vs/editor/common/services/modelServiceImpl*/,142/*vs/editor/common/services/textResourceConfigurationService*/,194/*vs/editor/standalone/browser/simpleServices*/,263/*vs/editor/standalone/browser/standaloneCodeServiceImpl*/,682/*vs/editor/standalone/browser/standaloneThemeServiceImpl*/,119/*vs/editor/standalone/common/standaloneThemeService*/,33/*vs/platform/actions/common/actions*/,26/*vs/platform/commands/common/commands*/,38/*vs/platform/configuration/common/configuration*/,584/*vs/platform/contextkey/browser/contextKeyService*/,16/*vs/platform/contextkey/common/contextkey*/,666/*vs/platform/contextview/browser/contextMenuService*/,69/*vs/platform/contextview/browser/contextView*/,569/*vs/platform/contextview/browser/contextViewService*/,120/*vs/platform/dialogs/common/dialogs*/,9/*vs/platform/instantiation/common/instantiation*/,564/*vs/platform/instantiation/common/instantiationService*/,143/*vs/platform/instantiation/common/serviceCollection*/,37/*vs/platform/keybinding/common/keybinding*/,121/*vs/platform/label/common/label*/,153/*vs/platform/list/browser/listService*/,70/*vs/platform/log/common/log*/,572/*vs/platform/markers/common/markerService*/,87/*vs/platform/markers/common/markers*/,34/*vs/platform/notification/common/notification*/,59/*vs/platform/progress/common/progress*/,71/*vs/platform/storage/common/storage*/,89/*vs/platform/telemetry/common/telemetry*/,11/*vs/platform/theme/common/themeService*/,193/*vs/platform/workspace/common/workspace*/,665/*vs/platform/actions/common/menuService*/,183/*vs/editor/common/services/markersDecorationService*/,608/*vs/editor/common/services/markerDecorationsServiceImpl*/,64/*vs/platform/accessibility/common/accessibility*/,144/*vs/platform/layout/browser/layoutService*/,75/*vs/platform/instantiation/common/extensions*/,582/*vs/platform/accessibility/common/accessibilityService*/,86/*vs/platform/clipboard/common/clipboardService*/,544/*vs/platform/clipboard/browser/clipboardService*/,154/*vs/platform/undoRedo/common/undoRedo*/,686/*vs/platform/undoRedo/common/undoRedoService*/,668/*vs/editor/standalone/browser/quickInput/standaloneQuickInputServiceImpl*/,78/*vs/platform/quickinput/common/quickInput*/]), function (require, exports, lifecycle_1, bulkEditService_1, codeEditorService_1, editorWorkerService_1, editorWorkerServiceImpl_1, modeService_1, modeServiceImpl_1, modelService_1, modelServiceImpl_1, textResourceConfigurationService_1, simpleServices_1, standaloneCodeServiceImpl_1, standaloneThemeServiceImpl_1, standaloneThemeService_1, actions_1, commands_1, configuration_1, contextKeyService_1, contextkey_1, contextMenuService_1, contextView_1, contextViewService_1, dialogs_1, instantiation_1, instantiationService_1, serviceCollection_1, keybinding_1, label_1, listService_1, log_1, markerService_1, markers_1, notification_1, progress_1, storage_1, telemetry_1, themeService_1, workspace_1, menuService_1, markersDecorationService_1, markerDecorationsServiceImpl_1, accessibility_1, layoutService_1, extensions_1, accessibilityService_1, clipboardService_1, clipboardService_2, undoRedo_1, undoRedoService_1, standaloneQuickInputServiceImpl_1, quickInput_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DynamicStandaloneServices = exports.StaticServices = void 0;
var StaticServices;
(function (StaticServices) {
const _serviceCollection = new serviceCollection_1.ServiceCollection();
class LazyStaticService {
constructor(serviceId, factory) {
this._serviceId = serviceId;
this._factory = factory;
this._value = null;
}
get id() { return this._serviceId; }
get(overrides) {
if (!this._value) {
if (overrides) {
this._value = overrides[this._serviceId.toString()];
}
if (!this._value) {
this._value = this._factory(overrides);
}
if (!this._value) {
throw new Error('Service ' + this._serviceId + ' is missing!');
}
_serviceCollection.set(this._serviceId, this._value);
}
return this._value;
}
}
StaticServices.LazyStaticService = LazyStaticService;
let _all = [];
function define(serviceId, factory) {
let r = new LazyStaticService(serviceId, factory);
_all.push(r);
return r;
}
function init(overrides) {
// Create a fresh service collection
let result = new serviceCollection_1.ServiceCollection();
// make sure to add all services that use `registerSingleton`
for (const [id, descriptor] of (0, extensions_1.getSingletonServiceDescriptors)()) {
result.set(id, descriptor);
}
// Initialize the service collection with the overrides
for (let serviceId in overrides) {
if (overrides.hasOwnProperty(serviceId)) {
result.set((0, instantiation_1.createDecorator)(serviceId), overrides[serviceId]);
}
}
// Make sure the same static services are present in all service collections
_all.forEach(service => result.set(service.id, service.get(overrides)));
// Ensure the collection gets the correct instantiation service
let instantiationService = new instantiationService_1.InstantiationService(result, true);
result.set(instantiation_1.IInstantiationService, instantiationService);
return [result, instantiationService];
}
StaticServices.init = init;
StaticServices.instantiationService = define(instantiation_1.IInstantiationService, () => new instantiationService_1.InstantiationService(_serviceCollection, true));
const configurationServiceImpl = new simpleServices_1.SimpleConfigurationService();
StaticServices.configurationService = define(configuration_1.IConfigurationService, () => configurationServiceImpl);
StaticServices.resourceConfigurationService = define(textResourceConfigurationService_1.ITextResourceConfigurationService, () => new simpleServices_1.SimpleResourceConfigurationService(configurationServiceImpl));
StaticServices.resourcePropertiesService = define(textResourceConfigurationService_1.ITextResourcePropertiesService, () => new simpleServices_1.SimpleResourcePropertiesService(configurationServiceImpl));
StaticServices.contextService = define(workspace_1.IWorkspaceContextService, () => new simpleServices_1.SimpleWorkspaceContextService());
StaticServices.labelService = define(label_1.ILabelService, () => new simpleServices_1.SimpleUriLabelService());
StaticServices.telemetryService = define(telemetry_1.ITelemetryService, () => new simpleServices_1.StandaloneTelemetryService());
StaticServices.dialogService = define(dialogs_1.IDialogService, () => new simpleServices_1.SimpleDialogService());
StaticServices.notificationService = define(notification_1.INotificationService, () => new simpleServices_1.SimpleNotificationService());
StaticServices.markerService = define(markers_1.IMarkerService, () => new markerService_1.MarkerService());
StaticServices.modeService = define(modeService_1.IModeService, (o) => new modeServiceImpl_1.ModeServiceImpl());
StaticServices.standaloneThemeService = define(standaloneThemeService_1.IStandaloneThemeService, () => new standaloneThemeServiceImpl_1.StandaloneThemeServiceImpl());
StaticServices.logService = define(log_1.ILogService, () => new log_1.LogService(new log_1.ConsoleLogger()));
StaticServices.undoRedoService = define(undoRedo_1.IUndoRedoService, (o) => new undoRedoService_1.UndoRedoService(StaticServices.dialogService.get(o), StaticServices.notificationService.get(o)));
StaticServices.modelService = define(modelService_1.IModelService, (o) => new modelServiceImpl_1.ModelServiceImpl(StaticServices.configurationService.get(o), StaticServices.resourcePropertiesService.get(o), StaticServices.standaloneThemeService.get(o), StaticServices.logService.get(o), StaticServices.undoRedoService.get(o)));
StaticServices.markerDecorationsService = define(markersDecorationService_1.IMarkerDecorationsService, (o) => new markerDecorationsServiceImpl_1.MarkerDecorationsService(StaticServices.modelService.get(o), StaticServices.markerService.get(o)));
StaticServices.contextKeyService = define(contextkey_1.IContextKeyService, (o) => new contextKeyService_1.ContextKeyService(StaticServices.configurationService.get(o)));
StaticServices.codeEditorService = define(codeEditorService_1.ICodeEditorService, (o) => new standaloneCodeServiceImpl_1.StandaloneCodeEditorServiceImpl(null, StaticServices.contextKeyService.get(o), StaticServices.standaloneThemeService.get(o)));
StaticServices.editorProgressService = define(progress_1.IEditorProgressService, () => new simpleServices_1.SimpleEditorProgressService());
StaticServices.storageService = define(storage_1.IStorageService, () => new storage_1.InMemoryStorageService());
StaticServices.editorWorkerService = define(editorWorkerService_1.IEditorWorkerService, (o) => new editorWorkerServiceImpl_1.EditorWorkerServiceImpl(StaticServices.modelService.get(o), StaticServices.resourceConfigurationService.get(o), StaticServices.logService.get(o)));
})(StaticServices = exports.StaticServices || (exports.StaticServices = {}));
class DynamicStandaloneServices extends lifecycle_1.Disposable {
constructor(domElement, overrides) {
super();
const [_serviceCollection, _instantiationService] = StaticServices.init(overrides);
this._serviceCollection = _serviceCollection;
this._instantiationService = _instantiationService;
const configurationService = this.get(configuration_1.IConfigurationService);
const notificationService = this.get(notification_1.INotificationService);
const telemetryService = this.get(telemetry_1.ITelemetryService);
const themeService = this.get(themeService_1.IThemeService);
const logService = this.get(log_1.ILogService);
const contextKeyService = this.get(contextkey_1.IContextKeyService);
let ensure = (serviceId, factory) => {
let value = null;
if (overrides) {
value = overrides[serviceId.toString()];
}
if (!value) {
value = factory();
}
this._serviceCollection.set(serviceId, value);
return value;
};
ensure(accessibility_1.IAccessibilityService, () => new accessibilityService_1.AccessibilityService(contextKeyService, configurationService));
ensure(listService_1.IListService, () => new listService_1.ListService(themeService));
let commandService = ensure(commands_1.ICommandService, () => new simpleServices_1.StandaloneCommandService(this._instantiationService));
let keybindingService = ensure(keybinding_1.IKeybindingService, () => this._register(new simpleServices_1.StandaloneKeybindingService(contextKeyService, commandService, telemetryService, notificationService, logService, domElement)));
let layoutService = ensure(layoutService_1.ILayoutService, () => new simpleServices_1.SimpleLayoutService(StaticServices.codeEditorService.get(codeEditorService_1.ICodeEditorService), domElement));
ensure(quickInput_1.IQuickInputService, () => new standaloneQuickInputServiceImpl_1.StandaloneQuickInputServiceImpl(_instantiationService, StaticServices.codeEditorService.get(codeEditorService_1.ICodeEditorService)));
let contextViewService = ensure(contextView_1.IContextViewService, () => this._register(new contextViewService_1.ContextViewService(layoutService)));
ensure(clipboardService_1.IClipboardService, () => new clipboardService_2.BrowserClipboardService());
ensure(contextView_1.IContextMenuService, () => {
const contextMenuService = new contextMenuService_1.ContextMenuService(telemetryService, notificationService, contextViewService, keybindingService, themeService);
contextMenuService.configure({ blockMouse: false }); // we do not want that in the standalone editor
return this._register(contextMenuService);
});
ensure(actions_1.IMenuService, () => new menuService_1.MenuService(commandService));
ensure(bulkEditService_1.IBulkEditService, () => new simpleServices_1.SimpleBulkEditService(StaticServices.modelService.get(modelService_1.IModelService)));
}
get(serviceId) {
let r = this._serviceCollection.get(serviceId);
if (!r) {
throw new Error('Missing service ' + serviceId);
}
return r;
}
set(serviceId, instance) {
this._serviceCollection.set(serviceId, instance);
}
has(serviceId) {
return this._serviceCollection.has(serviceId);
}
}
exports.DynamicStandaloneServices = DynamicStandaloneServices;
});
/*---------------------------------------------------------------------------------------------
* 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/editor/standalone/browser/standaloneEditor*/], __M([0/*require*/,1/*exports*/,28/*vs/editor/browser/services/codeEditorService*/,573/*vs/editor/browser/services/openerService*/,217/*vs/editor/browser/widget/diffNavigator*/,35/*vs/editor/common/config/editorOptions*/,168/*vs/editor/common/config/fontInfo*/,110/*vs/editor/common/editorCommon*/,53/*vs/editor/common/model*/,18/*vs/editor/common/modes*/,77/*vs/editor/common/modes/nullMode*/,76/*vs/editor/common/services/editorWorkerService*/,57/*vs/editor/common/services/modeService*/,68/*vs/editor/common/services/resolverService*/,570/*vs/editor/common/services/webWorker*/,174/*vs/editor/common/standalone/standaloneEnums*/,558/*vs/editor/standalone/browser/colorizer*/,194/*vs/editor/standalone/browser/simpleServices*/,687/*vs/editor/standalone/browser/standaloneCodeEditor*/,278/*vs/editor/standalone/browser/standaloneServices*/,119/*vs/editor/standalone/common/standaloneThemeService*/,26/*vs/platform/commands/common/commands*/,38/*vs/platform/configuration/common/configuration*/,16/*vs/platform/contextkey/common/contextkey*/,69/*vs/platform/contextview/browser/contextView*/,9/*vs/platform/instantiation/common/instantiation*/,37/*vs/platform/keybinding/common/keybinding*/,34/*vs/platform/notification/common/notification*/,58/*vs/platform/opener/common/opener*/,64/*vs/platform/accessibility/common/accessibility*/,65/*vs/editor/browser/config/configuration*/,59/*vs/platform/progress/common/progress*/,86/*vs/platform/clipboard/common/clipboardService*/,8/*vs/base/common/strings*/,36/*vs/editor/common/services/modelService*/,367/*vs/css!vs/editor/standalone/browser/standalone-tokens*/]), function (require, exports, codeEditorService_1, openerService_1, diffNavigator_1, editorOptions_1, fontInfo_1, editorCommon_1, model_1, modes, nullMode_1, editorWorkerService_1, modeService_1, resolverService_1, webWorker_1, standaloneEnums, colorizer_1, simpleServices_1, standaloneCodeEditor_1, standaloneServices_1, standaloneThemeService_1, commands_1, configuration_1, contextkey_1, contextView_1, instantiation_1, keybinding_1, notification_1, opener_1, accessibility_1, configuration_2, progress_1, clipboardService_1, strings_1, modelService_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMonacoEditorAPI = exports.registerCommand = exports.remeasureFonts = exports.setTheme = exports.defineTheme = exports.tokenize = exports.colorizeModelLine = exports.colorize = exports.colorizeElement = exports.createWebWorker = exports.onDidChangeModelLanguage = exports.onWillDisposeModel = exports.onDidCreateModel = exports.getModels = exports.getModel = exports.onDidChangeMarkers = exports.getModelMarkers = exports.setModelMarkers = exports.setModelLanguage = exports.createModel = exports.createDiffNavigator = exports.createDiffEditor = exports.onDidCreateEditor = exports.create = void 0;
function withAllStandaloneServices(domElement, override, callback) {
let services = new standaloneServices_1.DynamicStandaloneServices(domElement, override);
let simpleEditorModelResolverService = null;
if (!services.has(resolverService_1.ITextModelService)) {
simpleEditorModelResolverService = new simpleServices_1.SimpleEditorModelResolverService(standaloneServices_1.StaticServices.modelService.get());
services.set(resolverService_1.ITextModelService, simpleEditorModelResolverService);
}
if (!services.has(opener_1.IOpenerService)) {
services.set(opener_1.IOpenerService, new openerService_1.OpenerService(services.get(codeEditorService_1.ICodeEditorService), services.get(commands_1.ICommandService)));
}
let result = callback(services);
if (simpleEditorModelResolverService) {
simpleEditorModelResolverService.setEditor(result);
}
return result;
}
/**
* 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) {
return withAllStandaloneServices(domElement, override || {}, (services) => {
return new standaloneCodeEditor_1.StandaloneEditor(domElement, options, services, services.get(instantiation_1.IInstantiationService), services.get(codeEditorService_1.ICodeEditorService), services.get(commands_1.ICommandService), services.get(contextkey_1.IContextKeyService), services.get(keybinding_1.IKeybindingService), services.get(contextView_1.IContextViewService), services.get(standaloneThemeService_1.IStandaloneThemeService), services.get(notification_1.INotificationService), services.get(configuration_1.IConfigurationService), services.get(accessibility_1.IAccessibilityService), services.get(modelService_1.IModelService), services.get(modeService_1.IModeService));
});
}
exports.create = create;
/**
* 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) {
return standaloneServices_1.StaticServices.codeEditorService.get().onCodeEditorAdd((editor) => {
listener(editor);
});
}
exports.onDidCreateEditor = onDidCreateEditor;
/**
* 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) {
return withAllStandaloneServices(domElement, override || {}, (services) => {
return new standaloneCodeEditor_1.StandaloneDiffEditor(domElement, options, services, services.get(instantiation_1.IInstantiationService), services.get(contextkey_1.IContextKeyService), services.get(keybinding_1.IKeybindingService), services.get(contextView_1.IContextViewService), services.get(editorWorkerService_1.IEditorWorkerService), services.get(codeEditorService_1.ICodeEditorService), services.get(standaloneThemeService_1.IStandaloneThemeService), services.get(notification_1.INotificationService), services.get(configuration_1.IConfigurationService), services.get(contextView_1.IContextMenuService), services.get(progress_1.IEditorProgressService), services.get(clipboardService_1.IClipboardService));
});
}
exports.createDiffEditor = createDiffEditor;
function createDiffNavigator(diffEditor, opts) {
return new diffNavigator_1.DiffNavigator(diffEditor, opts);
}
exports.createDiffNavigator = createDiffNavigator;
/**
* 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) {
return (0, standaloneCodeEditor_1.createTextModel)(standaloneServices_1.StaticServices.modelService.get(), standaloneServices_1.StaticServices.modeService.get(), value, language, uri);
}
exports.createModel = createModel;
/**
* Change the language for a model.
*/
function setModelLanguage(model, languageId) {
standaloneServices_1.StaticServices.modelService.get().setMode(model, standaloneServices_1.StaticServices.modeService.get().create(languageId));
}
exports.setModelLanguage = setModelLanguage;
/**
* Set the markers for a model.
*/
function setModelMarkers(model, owner, markers) {
if (model) {
standaloneServices_1.StaticServices.markerService.get().changeOne(owner, model.uri, markers);
}
}
exports.setModelMarkers = setModelMarkers;
/**
* Get markers for owner and/or resource
*
* @returns list of markers
*/
function getModelMarkers(filter) {
return standaloneServices_1.StaticServices.markerService.get().read(filter);
}
exports.getModelMarkers = getModelMarkers;
/**
* Emitted when markers change for a model.
* @event
*/
function onDidChangeMarkers(listener) {
return standaloneServices_1.StaticServices.markerService.get().onMarkerChanged(listener);
}
exports.onDidChangeMarkers = onDidChangeMarkers;
/**
* Get the model that has `uri` if it exists.
*/
function getModel(uri) {
return standaloneServices_1.StaticServices.modelService.get().getModel(uri);
}
exports.getModel = getModel;
/**
* Get all the created models.
*/
function getModels() {
return standaloneServices_1.StaticServices.modelService.get().getModels();
}
exports.getModels = getModels;
/**
* Emitted when a model is created.
* @event
*/
function onDidCreateModel(listener) {
return standaloneServices_1.StaticServices.modelService.get().onModelAdded(listener);
}
exports.onDidCreateModel = onDidCreateModel;
/**
* Emitted right before a model is disposed.
* @event
*/
function onWillDisposeModel(listener) {
return standaloneServices_1.StaticServices.modelService.get().onModelRemoved(listener);
}
exports.onWillDisposeModel = onWillDisposeModel;
/**
* Emitted when a different language is set to a model.
* @event
*/
function onDidChangeModelLanguage(listener) {
return standaloneServices_1.StaticServices.modelService.get().onModelModeChanged((e) => {
listener({
model: e.model,
oldLanguage: e.oldModeId
});
});
}
exports.onDidChangeModelLanguage = onDidChangeModelLanguage;
/**
* 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, webWorker_1.createWebWorker)(standaloneServices_1.StaticServices.modelService.get(), opts);
}
exports.createWebWorker = createWebWorker;
/**
* Colorize the contents of `domNode` using attribute `data-lang`.
*/
function colorizeElement(domNode, options) {
const themeService = standaloneServices_1.StaticServices.standaloneThemeService.get();
themeService.registerEditorContainer(domNode);
return colorizer_1.Colorizer.colorizeElement(themeService, standaloneServices_1.StaticServices.modeService.get(), domNode, options);
}
exports.colorizeElement = colorizeElement;
/**
* Colorize `text` using language `languageId`.
*/
function colorize(text, languageId, options) {
const themeService = standaloneServices_1.StaticServices.standaloneThemeService.get();
themeService.registerEditorContainer(document.body);
return colorizer_1.Colorizer.colorize(standaloneServices_1.StaticServices.modeService.get(), text, languageId, options);
}
exports.colorize = colorize;
/**
* Colorize a line in a model.
*/
function colorizeModelLine(model, lineNumber, tabSize = 4) {
const themeService = standaloneServices_1.StaticServices.standaloneThemeService.get();
themeService.registerEditorContainer(document.body);
return colorizer_1.Colorizer.colorizeModelLine(model, lineNumber, tabSize);
}
exports.colorizeModelLine = colorizeModelLine;
/**
* @internal
*/
function getSafeTokenizationSupport(language) {
let tokenizationSupport = modes.TokenizationRegistry.get(language);
if (tokenizationSupport) {
return tokenizationSupport;
}
return {
getInitialState: () => nullMode_1.NULL_STATE,
tokenize: (line, hasEOL, state, deltaOffset) => (0, nullMode_1.nullTokenize)(language, line, state, deltaOffset)
};
}
/**
* Tokenize `text` using language `languageId`
*/
function tokenize(text, languageId) {
let modeService = standaloneServices_1.StaticServices.modeService.get();
// Needed in order to get the mode registered for subsequent look-ups
modeService.triggerMode(languageId);
let tokenizationSupport = getSafeTokenizationSupport(languageId);
let lines = (0, strings_1.splitLines)(text);
let result = [];
let state = tokenizationSupport.getInitialState();
for (let i = 0, len = lines.length; i < len; i++) {
let line = lines[i];
let tokenizationResult = tokenizationSupport.tokenize(line, true, state, 0);
result[i] = tokenizationResult.tokens;
state = tokenizationResult.endState;
}
return result;
}
exports.tokenize = tokenize;
/**
* Define a new theme or update an existing theme.
*/
function defineTheme(themeName, themeData) {
standaloneServices_1.StaticServices.standaloneThemeService.get().defineTheme(themeName, themeData);
}
exports.defineTheme = defineTheme;
/**
* Switches to a theme.
*/
function setTheme(themeName) {
standaloneServices_1.StaticServices.standaloneThemeService.get().setTheme(themeName);
}
exports.setTheme = setTheme;
/**
* Clears all cached font measurements and triggers re-measurement.
*/
function remeasureFonts() {
(0, configuration_2.clearAllFontInfos)();
}
exports.remeasureFonts = remeasureFonts;
/**
* Register a command.
*/
function registerCommand(id, handler) {
return commands_1.CommandsRegistry.registerCommand({ id, handler });
}
exports.registerCommand = registerCommand;
/**
* @internal
*/
function createMonacoEditorAPI() {
return {
// methods
create: create,
onDidCreateEditor: onDidCreateEditor,
createDiffEditor: createDiffEditor,
createDiffNavigator: createDiffNavigator,
createModel: createModel,
setModelLanguage: setModelLanguage,
setModelMarkers: setModelMarkers,
getModelMarkers: getModelMarkers,
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,
// 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,
MouseTargetType: standaloneEnums.MouseTargetType,
OverlayWidgetPositionPreference: standaloneEnums.OverlayWidgetPositionPreference,
OverviewRulerLane: standaloneEnums.OverviewRulerLane,
RenderLineNumbersType: standaloneEnums.RenderLineNumbersType,
RenderMinimap: standaloneEnums.RenderMinimap,
ScrollbarVisibility: standaloneEnums.ScrollbarVisibility,
ScrollType: standaloneEnums.ScrollType,
TextEditorCursorBlinkingStyle: standaloneEnums.TextEditorCursorBlinkingStyle,
TextEditorCursorStyle: standaloneEnums.TextEditorCursorStyle,
TrackedRangeStickiness: standaloneEnums.TrackedRangeStickiness,
WrappingIndent: standaloneEnums.WrappingIndent,
// classes
ConfigurationChangedEvent: editorOptions_1.ConfigurationChangedEvent,
BareFontInfo: fontInfo_1.BareFontInfo,
FontInfo: fontInfo_1.FontInfo,
TextModelResolvedOptions: model_1.TextModelResolvedOptions,
FindMatch: model_1.FindMatch,
// vars
EditorType: editorCommon_1.EditorType,
EditorOptions: editorOptions_1.EditorOptions
};
}
exports.createMonacoEditorAPI = createMonacoEditorAPI;
});
/*---------------------------------------------------------------------------------------------
* 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/editor/standalone/browser/standaloneLanguages*/], __M([0/*require*/,1/*exports*/,29/*vs/base/common/color*/,3/*vs/editor/common/core/range*/,134/*vs/editor/common/core/token*/,18/*vs/editor/common/modes*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/,146/*vs/editor/common/modes/modesRegistry*/,174/*vs/editor/common/standalone/standaloneEnums*/,278/*vs/editor/standalone/browser/standaloneServices*/,426/*vs/editor/standalone/common/monarch/monarchCompile*/,249/*vs/editor/standalone/common/monarch/monarchLexer*/]), function (require, exports, color_1, range_1, token_1, modes, languageConfigurationRegistry_1, modesRegistry_1, standaloneEnums, standaloneServices_1, monarchCompile_1, monarchLexer_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMonacoLanguagesAPI = exports.registerInlayHintsProvider = exports.registerInlineCompletionsProvider = exports.registerDocumentRangeSemanticTokensProvider = exports.registerDocumentSemanticTokensProvider = exports.registerSelectionRangeProvider = exports.registerDeclarationProvider = exports.registerFoldingRangeProvider = exports.registerColorProvider = exports.registerCompletionItemProvider = exports.registerLinkProvider = exports.registerOnTypeFormattingEditProvider = exports.registerDocumentRangeFormattingEditProvider = exports.registerDocumentFormattingEditProvider = exports.registerCodeActionProvider = exports.registerCodeLensProvider = exports.registerTypeDefinitionProvider = exports.registerImplementationProvider = exports.registerDefinitionProvider = exports.registerLinkedEditingRangeProvider = exports.registerDocumentHighlightProvider = exports.registerDocumentSymbolProvider = exports.registerHoverProvider = exports.registerSignatureHelpProvider = exports.registerRenameProvider = exports.registerReferenceProvider = exports.setMonarchTokensProvider = exports.setTokensProvider = exports.setColorMap = exports.TokenizationSupport2Adapter = exports.EncodedTokenizationSupport2Adapter = exports.setLanguageConfiguration = exports.onLanguage = exports.getEncodedLanguageId = exports.getLanguages = exports.register = void 0;
/**
* Register information about a new language.
*/
function register(language) {
modesRegistry_1.ModesRegistry.registerLanguage(language);
}
exports.register = register;
/**
* Get the information of all the registered languages.
*/
function getLanguages() {
let result = [];
result = result.concat(modesRegistry_1.ModesRegistry.getLanguages());
return result;
}
exports.getLanguages = getLanguages;
function getEncodedLanguageId(languageId) {
let lid = standaloneServices_1.StaticServices.modeService.get().getLanguageIdentifier(languageId);
return lid ? lid.id : 0;
}
exports.getEncodedLanguageId = getEncodedLanguageId;
/**
* An event emitted when a language is first time needed (e.g. a model has it set).
* @event
*/
function onLanguage(languageId, callback) {
let disposable = standaloneServices_1.StaticServices.modeService.get().onDidCreateMode((mode) => {
if (mode.getId() === languageId) {
// stop listening
disposable.dispose();
// invoke actual listener
callback();
}
});
return disposable;
}
exports.onLanguage = onLanguage;
/**
* Set the editing configuration for a language.
*/
function setLanguageConfiguration(languageId, configuration) {
let languageIdentifier = standaloneServices_1.StaticServices.modeService.get().getLanguageIdentifier(languageId);
if (!languageIdentifier) {
throw new Error(`Cannot set configuration for unknown language ${languageId}`);
}
return languageConfigurationRegistry_1.LanguageConfigurationRegistry.register(languageIdentifier, configuration, 100);
}
exports.setLanguageConfiguration = setLanguageConfiguration;
/**
* @internal
*/
class EncodedTokenizationSupport2Adapter {
constructor(languageIdentifier, actual) {
this._languageIdentifier = languageIdentifier;
this._actual = actual;
}
getInitialState() {
return this._actual.getInitialState();
}
tokenize(line, hasEOL, state, offsetDelta) {
if (typeof this._actual.tokenize === 'function') {
return TokenizationSupport2Adapter.adaptTokenize(this._languageIdentifier.language, this._actual, line, state, offsetDelta);
}
throw new Error('Not supported!');
}
tokenize2(line, hasEOL, state) {
let result = this._actual.tokenizeEncoded(line, state);
return new token_1.TokenizationResult2(result.tokens, result.endState);
}
}
exports.EncodedTokenizationSupport2Adapter = EncodedTokenizationSupport2Adapter;
/**
* @internal
*/
class TokenizationSupport2Adapter {
constructor(standaloneThemeService, languageIdentifier, actual) {
this._standaloneThemeService = standaloneThemeService;
this._languageIdentifier = languageIdentifier;
this._actual = actual;
}
getInitialState() {
return this._actual.getInitialState();
}
static _toClassicTokens(tokens, language, offsetDelta) {
let 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 token_1.Token(startIndex + offsetDelta, t.scopes, language);
previousStartIndex = startIndex;
}
return result;
}
static adaptTokenize(language, actual, line, state, offsetDelta) {
let actualResult = actual.tokenize(line, state);
let tokens = TokenizationSupport2Adapter._toClassicTokens(actualResult.tokens, language, offsetDelta);
let endState;
// try to save an object if possible
if (actualResult.endState.equals(state)) {
endState = state;
}
else {
endState = actualResult.endState;
}
return new token_1.TokenizationResult(tokens, endState);
}
tokenize(line, hasEOL, state, offsetDelta) {
return TokenizationSupport2Adapter.adaptTokenize(this._languageIdentifier.language, this._actual, line, state, offsetDelta);
}
_toBinaryTokens(tokens, offsetDelta) {
const languageId = this._languageIdentifier.id;
const tokenTheme = this._standaloneThemeService.getColorTheme().tokenTheme;
let result = [], 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);
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 + offsetDelta;
result[resultLen++] = metadata;
previousStartIndex = startIndex;
}
let actualResult = new Uint32Array(resultLen);
for (let i = 0; i < resultLen; i++) {
actualResult[i] = result[i];
}
return actualResult;
}
tokenize2(line, hasEOL, state, offsetDelta) {
let actualResult = this._actual.tokenize(line, state);
let tokens = this._toBinaryTokens(actualResult.tokens, offsetDelta);
let endState;
// try to save an object if possible
if (actualResult.endState.equals(state)) {
endState = state;
}
else {
endState = actualResult.endState;
}
return new token_1.TokenizationResult2(tokens, endState);
}
}
exports.TokenizationSupport2Adapter = TokenizationSupport2Adapter;
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) {
if (colorMap) {
const result = [null];
for (let i = 1, len = colorMap.length; i < len; i++) {
result[i] = color_1.Color.fromHex(colorMap[i]);
}
standaloneServices_1.StaticServices.standaloneThemeService.get().setColorMapOverride(result);
}
else {
standaloneServices_1.StaticServices.standaloneThemeService.get().setColorMapOverride(null);
}
}
exports.setColorMap = setColorMap;
/**
* Set the tokens provider for a language (manual implementation).
*/
function setTokensProvider(languageId, provider) {
let languageIdentifier = standaloneServices_1.StaticServices.modeService.get().getLanguageIdentifier(languageId);
if (!languageIdentifier) {
throw new Error(`Cannot set tokens provider for unknown language ${languageId}`);
}
const create = (provider) => {
if (isEncodedTokensProvider(provider)) {
return new EncodedTokenizationSupport2Adapter(languageIdentifier, provider);
}
else {
return new TokenizationSupport2Adapter(standaloneServices_1.StaticServices.standaloneThemeService.get(), languageIdentifier, provider);
}
};
if (isThenable(provider)) {
return modes.TokenizationRegistry.registerPromise(languageId, provider.then(provider => create(provider)));
}
return modes.TokenizationRegistry.register(languageId, create(provider));
}
exports.setTokensProvider = setTokensProvider;
/**
* Set the tokens provider for a language (monarch implementation).
*/
function setMonarchTokensProvider(languageId, languageDef) {
const create = (languageDef) => {
return (0, monarchLexer_1.createTokenizationSupport)(standaloneServices_1.StaticServices.modeService.get(), standaloneServices_1.StaticServices.standaloneThemeService.get(), languageId, (0, monarchCompile_1.compile)(languageId, languageDef));
};
if (isThenable(languageDef)) {
return modes.TokenizationRegistry.registerPromise(languageId, languageDef.then(languageDef => create(languageDef)));
}
return modes.TokenizationRegistry.register(languageId, create(languageDef));
}
exports.setMonarchTokensProvider = setMonarchTokensProvider;
/**
* Register a reference provider (used by e.g. reference search).
*/
function registerReferenceProvider(languageId, provider) {
return modes.ReferenceProviderRegistry.register(languageId, provider);
}
exports.registerReferenceProvider = registerReferenceProvider;
/**
* Register a rename provider (used by e.g. rename symbol).
*/
function registerRenameProvider(languageId, provider) {
return modes.RenameProviderRegistry.register(languageId, provider);
}
exports.registerRenameProvider = registerRenameProvider;
/**
* Register a signature help provider (used by e.g. parameter hints).
*/
function registerSignatureHelpProvider(languageId, provider) {
return modes.SignatureHelpProviderRegistry.register(languageId, provider);
}
exports.registerSignatureHelpProvider = registerSignatureHelpProvider;
/**
* Register a hover provider (used by e.g. editor hover).
*/
function registerHoverProvider(languageId, provider) {
return modes.HoverProviderRegistry.register(languageId, {
provideHover: (model, position, token) => {
let word = model.getWordAtPosition(position);
return Promise.resolve(provider.provideHover(model, position, token)).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;
});
}
});
}
exports.registerHoverProvider = registerHoverProvider;
/**
* Register a document symbol provider (used by e.g. outline).
*/
function registerDocumentSymbolProvider(languageId, provider) {
return modes.DocumentSymbolProviderRegistry.register(languageId, provider);
}
exports.registerDocumentSymbolProvider = registerDocumentSymbolProvider;
/**
* Register a document highlight provider (used by e.g. highlight occurrences).
*/
function registerDocumentHighlightProvider(languageId, provider) {
return modes.DocumentHighlightProviderRegistry.register(languageId, provider);
}
exports.registerDocumentHighlightProvider = registerDocumentHighlightProvider;
/**
* Register an linked editing range provider.
*/
function registerLinkedEditingRangeProvider(languageId, provider) {
return modes.LinkedEditingRangeProviderRegistry.register(languageId, provider);
}
exports.registerLinkedEditingRangeProvider = registerLinkedEditingRangeProvider;
/**
* Register a definition provider (used by e.g. go to definition).
*/
function registerDefinitionProvider(languageId, provider) {
return modes.DefinitionProviderRegistry.register(languageId, provider);
}
exports.registerDefinitionProvider = registerDefinitionProvider;
/**
* Register a implementation provider (used by e.g. go to implementation).
*/
function registerImplementationProvider(languageId, provider) {
return modes.ImplementationProviderRegistry.register(languageId, provider);
}
exports.registerImplementationProvider = registerImplementationProvider;
/**
* Register a type definition provider (used by e.g. go to type definition).
*/
function registerTypeDefinitionProvider(languageId, provider) {
return modes.TypeDefinitionProviderRegistry.register(languageId, provider);
}
exports.registerTypeDefinitionProvider = registerTypeDefinitionProvider;
/**
* Register a code lens provider (used by e.g. inline code lenses).
*/
function registerCodeLensProvider(languageId, provider) {
return modes.CodeLensProviderRegistry.register(languageId, provider);
}
exports.registerCodeLensProvider = registerCodeLensProvider;
/**
* Register a code action provider (used by e.g. quick fix).
*/
function registerCodeActionProvider(languageId, provider) {
return modes.CodeActionProviderRegistry.register(languageId, {
provideCodeActions: (model, range, context, token) => {
let markers = standaloneServices_1.StaticServices.markerService.get().read({ resource: model.uri }).filter(m => {
return range_1.Range.areIntersectingOrTouching(m, range);
});
return provider.provideCodeActions(model, range, { markers, only: context.only }, token);
}
});
}
exports.registerCodeActionProvider = registerCodeActionProvider;
/**
* Register a formatter that can handle only entire models.
*/
function registerDocumentFormattingEditProvider(languageId, provider) {
return modes.DocumentFormattingEditProviderRegistry.register(languageId, provider);
}
exports.registerDocumentFormattingEditProvider = registerDocumentFormattingEditProvider;
/**
* Register a formatter that can handle a range inside a model.
*/
function registerDocumentRangeFormattingEditProvider(languageId, provider) {
return modes.DocumentRangeFormattingEditProviderRegistry.register(languageId, provider);
}
exports.registerDocumentRangeFormattingEditProvider = registerDocumentRangeFormattingEditProvider;
/**
* Register a formatter than can do formatting as the user types.
*/
function registerOnTypeFormattingEditProvider(languageId, provider) {
return modes.OnTypeFormattingEditProviderRegistry.register(languageId, provider);
}
exports.registerOnTypeFormattingEditProvider = registerOnTypeFormattingEditProvider;
/**
* Register a link provider that can find links in text.
*/
function registerLinkProvider(languageId, provider) {
return modes.LinkProviderRegistry.register(languageId, provider);
}
exports.registerLinkProvider = registerLinkProvider;
/**
* Register a completion item provider (use by e.g. suggestions).
*/
function registerCompletionItemProvider(languageId, provider) {
return modes.CompletionProviderRegistry.register(languageId, provider);
}
exports.registerCompletionItemProvider = registerCompletionItemProvider;
/**
* Register a document color provider (used by Color Picker, Color Decorator).
*/
function registerColorProvider(languageId, provider) {
return modes.ColorProviderRegistry.register(languageId, provider);
}
exports.registerColorProvider = registerColorProvider;
/**
* Register a folding range provider
*/
function registerFoldingRangeProvider(languageId, provider) {
return modes.FoldingRangeProviderRegistry.register(languageId, provider);
}
exports.registerFoldingRangeProvider = registerFoldingRangeProvider;
/**
* Register a declaration provider
*/
function registerDeclarationProvider(languageId, provider) {
return modes.DeclarationProviderRegistry.register(languageId, provider);
}
exports.registerDeclarationProvider = registerDeclarationProvider;
/**
* Register a selection range provider
*/
function registerSelectionRangeProvider(languageId, provider) {
return modes.SelectionRangeRegistry.register(languageId, provider);
}
exports.registerSelectionRangeProvider = registerSelectionRangeProvider;
/**
* Register a document semantic tokens provider
*/
function registerDocumentSemanticTokensProvider(languageId, provider) {
return modes.DocumentSemanticTokensProviderRegistry.register(languageId, provider);
}
exports.registerDocumentSemanticTokensProvider = registerDocumentSemanticTokensProvider;
/**
* Register a document range semantic tokens provider
*/
function registerDocumentRangeSemanticTokensProvider(languageId, provider) {
return modes.DocumentRangeSemanticTokensProviderRegistry.register(languageId, provider);
}
exports.registerDocumentRangeSemanticTokensProvider = registerDocumentRangeSemanticTokensProvider;
/**
* Register an inline completions provider.
*/
function registerInlineCompletionsProvider(languageId, provider) {
return modes.InlineCompletionsProviderRegistry.register(languageId, provider);
}
exports.registerInlineCompletionsProvider = registerInlineCompletionsProvider;
/**
* Register an inlay hints provider.
*/
function registerInlayHintsProvider(languageId, provider) {
return modes.InlayHintsProviderRegistry.register(languageId, provider);
}
exports.registerInlayHintsProvider = registerInlayHintsProvider;
/**
* @internal
*/
function createMonacoLanguagesAPI() {
return {
register: register,
getLanguages: getLanguages,
onLanguage: onLanguage,
getEncodedLanguageId: getEncodedLanguageId,
// provider methods
setLanguageConfiguration: setLanguageConfiguration,
setColorMap: setColorMap,
setTokensProvider: setTokensProvider,
setMonarchTokensProvider: setMonarchTokensProvider,
registerReferenceProvider: registerReferenceProvider,
registerRenameProvider: registerRenameProvider,
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,
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,
// classes
FoldingRangeKind: modes.FoldingRangeKind,
};
}
exports.createMonacoLanguagesAPI = createMonacoLanguagesAPI;
});
/*---------------------------------------------------------------------------------------------
* 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/editor.api*/], __M([0/*require*/,1/*exports*/,35/*vs/editor/common/config/editorOptions*/,222/*vs/editor/common/standalone/standaloneBase*/,688/*vs/editor/standalone/browser/standaloneEditor*/,689/*vs/editor/standalone/browser/standaloneLanguages*/,17/*vs/base/common/platform*/,265/*vs/editor/contrib/format/format*/]), function (require, exports, editorOptions_1, standaloneBase_1, standaloneEditor_1, standaloneLanguages_1, platform_1, format_1) {
"use strict";
var _a;
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 /* None */;
editorOptions_1.EditorOptions.glyphMargin.defaultValue = false;
editorOptions_1.EditorOptions.autoIndent.defaultValue = 3 /* 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, standaloneBase_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;
if (((_a = platform_1.globals.MonacoEnvironment) === null || _a === void 0 ? void 0 : _a.globalAPI) || (typeof define === 'function' && define.amd)) {
self.monaco = api;
}
if (typeof self.require !== 'undefined' && typeof self.require.config === 'function') {
self.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'
]
});
}
});
define(__m[691/*vs/platform/workspaces/common/workspaces*/], __M([0/*require*/,1/*exports*/,24/*vs/base/common/uri*/]), function (require, exports, uri_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toWorkspaceIdentifier = exports.isSingleFolderWorkspaceIdentifier = exports.WORKSPACE_EXTENSION = void 0;
exports.WORKSPACE_EXTENSION = 'code-workspace';
function isSingleFolderWorkspaceIdentifier(obj) {
const singleFolderIdentifier = obj;
return typeof (singleFolderIdentifier === null || singleFolderIdentifier === void 0 ? void 0 : singleFolderIdentifier.id) === 'string' && uri_1.URI.isUri(singleFolderIdentifier.uri);
}
exports.isSingleFolderWorkspaceIdentifier = isSingleFolderWorkspaceIdentifier;
function toWorkspaceIdentifier(workspace) {
// Multi root
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 workspace
return undefined;
}
exports.toWorkspaceIdentifier = toWorkspaceIdentifier;
});
//#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[692/*vs/editor/contrib/snippet/snippetVariables*/], __M([0/*require*/,1/*exports*/,519/*vs/nls!vs/editor/contrib/snippet/snippetVariables*/,73/*vs/base/common/path*/,43/*vs/base/common/resources*/,116/*vs/editor/contrib/snippet/snippetParser*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/,8/*vs/base/common/strings*/,691/*vs/platform/workspaces/common/workspaces*/,163/*vs/base/common/labels*/,299/*vs/base/common/uuid*/]), function (require, exports, nls, path, resources_1, snippetParser_1, languageConfigurationRegistry_1, strings_1, workspaces_1, labels_1, uuid_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 = void 0;
class CompositeSnippetVariableResolver {
constructor(_delegates) {
this._delegates = _delegates;
//
}
resolve(variable) {
for (const delegate of this._delegates) {
let 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);
}
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' && this._labelService) {
if (path.dirname(this._model.uri.fsPath) === '.') {
return '';
}
return this._labelService.getUriLabel((0, resources_1.dirname)(this._model.uri));
}
else if (name === 'TM_FILEPATH' && this._labelService) {
return this._labelService.getUriLabel(this._model.uri);
}
else if (name === 'RELATIVE_FILEPATH' && this._labelService) {
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;
class CommentBasedVariableResolver {
constructor(_model, _selection) {
this._model = _model;
this._selection = _selection;
//
}
resolve(variable) {
const { name } = variable;
const langId = this._model.getLanguageIdAtPosition(this._selection.selectionStartLineNumber, this._selection.selectionStartColumn);
const config = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getComments(langId);
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;
class TimeBasedVariableResolver {
constructor() {
this._date = new Date();
}
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));
}
return undefined;
}
}
exports.TimeBasedVariableResolver = TimeBasedVariableResolver;
TimeBasedVariableResolver.dayNames = [nls.localize(0, null), nls.localize(1, null), nls.localize(2, null), nls.localize(3, null), nls.localize(4, null), nls.localize(5, null), nls.localize(6, null)];
TimeBasedVariableResolver.dayNamesShort = [nls.localize(7, null), nls.localize(8, null), nls.localize(9, null), nls.localize(10, null), nls.localize(11, null), nls.localize(12, null), nls.localize(13, null)];
TimeBasedVariableResolver.monthNames = [nls.localize(14, null), nls.localize(15, null), nls.localize(16, null), nls.localize(17, null), nls.localize(18, null), nls.localize(19, null), nls.localize(20, null), nls.localize(21, null), nls.localize(22, null), nls.localize(23, null), nls.localize(24, null), nls.localize(25, null)];
TimeBasedVariableResolver.monthNamesShort = [nls.localize(26, null), nls.localize(27, null), nls.localize(28, null), nls.localize(29, null), nls.localize(30, null), nls.localize(31, null), nls.localize(32, null), nls.localize(33, null), nls.localize(34, null), nls.localize(35, null), nls.localize(36, null), nls.localize(37, null)];
class WorkspaceBasedVariableResolver {
constructor(_workspaceService) {
this._workspaceService = _workspaceService;
//
}
resolve(variable) {
if (!this._workspaceService) {
return undefined;
}
const workspaceIdentifier = (0, workspaces_1.toWorkspaceIdentifier)(this._workspaceService.getWorkspace());
if (!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, workspaces_1.isSingleFolderWorkspaceIdentifier)(workspaceIdentifier)) {
return path.basename(workspaceIdentifier.uri.path);
}
let filename = path.basename(workspaceIdentifier.configPath.path);
if (filename.endsWith(workspaces_1.WORKSPACE_EXTENSION)) {
filename = filename.substr(0, filename.length - workspaces_1.WORKSPACE_EXTENSION.length - 1);
}
return filename;
}
_resoveWorkspacePath(workspaceIdentifier) {
if ((0, workspaces_1.isSingleFolderWorkspaceIdentifier)(workspaceIdentifier)) {
return (0, labels_1.normalizeDriveLetter)(workspaceIdentifier.uri.fsPath);
}
let 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[279/*vs/editor/contrib/snippet/snippetSession*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,56/*vs/editor/common/core/editOperation*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,31/*vs/editor/common/model/textModel*/,193/*vs/platform/workspace/common/workspace*/,9/*vs/platform/instantiation/common/instantiation*/,116/*vs/editor/contrib/snippet/snippetParser*/,692/*vs/editor/contrib/snippet/snippetVariables*/,11/*vs/platform/theme/common/themeService*/,22/*vs/platform/theme/common/colorRegistry*/,121/*vs/platform/label/common/label*/,360/*vs/css!vs/editor/contrib/snippet/snippetSession*/]), function (require, exports, arrays_1, lifecycle_1, strings_1, editOperation_1, range_1, selection_1, textModel_1, workspace_1, instantiation_1, snippetParser_1, snippetVariables_1, themeService_1, colors, label_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SnippetSession = exports.OneSnippet = void 0;
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
function getColorGraceful(name) {
const color = theme.getColor(name);
return color ? color.toString() : 'transparent';
}
collector.addRule(`.monaco-editor .snippet-placeholder { background-color: ${getColorGraceful(colors.snippetTabstopHighlightBackground)}; outline-color: ${getColorGraceful(colors.snippetTabstopHighlightBorder)}; }`);
collector.addRule(`.monaco-editor .finish-snippet-placeholder { background-color: ${getColorGraceful(colors.snippetFinalTabstopHighlightBackground)}; outline-color: ${getColorGraceful(colors.snippetFinalTabstopHighlightBorder)}; }`);
});
class OneSnippet {
constructor(_editor, _snippet, _offset, _snippetLineLeadingWhitespace) {
this._editor = _editor;
this._snippet = _snippet;
this._offset = _offset;
this._snippetLineLeadingWhitespace = _snippetLineLeadingWhitespace;
this._nestingLevel = 1;
this._placeholderGroups = (0, arrays_1.groupBy)(_snippet.placeholders, snippetParser_1.Placeholder.compareByIndex);
this._placeholderGroupsIdx = -1;
}
dispose() {
if (this._placeholderDecorations) {
this._editor.deltaDecorations([...this._placeholderDecorations.values()], []);
}
this._placeholderGroups.length = 0;
}
_initDecorations() {
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) {
let 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 !== null && newSelections !== void 0 ? 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;
}
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 choice() {
return this._placeholderGroups[this._placeholderGroupsIdx][0].choice;
}
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._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;
OneSnippet._decor = {
active: textModel_1.ModelDecorationOptions.register({ description: 'snippet-placeholder-1', stickiness: 0 /* AlwaysGrowsWhenTypingAtEdges */, className: 'snippet-placeholder' }),
inactive: textModel_1.ModelDecorationOptions.register({ description: 'snippet-placeholder-2', stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'snippet-placeholder' }),
activeFinal: textModel_1.ModelDecorationOptions.register({ description: 'snippet-placeholder-3', stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'finish-snippet-placeholder' }),
inactiveFinal: textModel_1.ModelDecorationOptions.register({ description: 'snippet-placeholder-4', stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'finish-snippet-placeholder' }),
};
const _defaultOptions = {
overwriteBefore: 0,
overwriteAfter: 0,
adjustWhitespace: true,
clipboardText: undefined,
overtypingCapturer: undefined
};
class SnippetSession {
constructor(editor, template, options = _defaultOptions) {
this._templateMerges = [];
this._snippets = [];
this._editor = editor;
this._template = template;
this._options = options;
}
static adjustWhitespace(model, position, snippet, adjustIndentation, adjustNewlines) {
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;
}
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 !== null && snippetTextString !== void 0 ? snippetTextString : snippet.toString();
let prevChar = snippetTextString.charCodeAt(offset - 1);
if (prevChar === 10 /* LineFeed */ || prevChar === 13 /* 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 createEditsAndSnippets(editor, template, overwriteBefore, overwriteAfter, enforceFinalTabstop, adjustWhitespace, clipboardText, overtypingCapturer) {
const edits = [];
const snippets = [];
if (!editor.hasModel()) {
return { edits, snippets };
}
const model = editor.getModel();
const workspaceService = editor.invokeWithinContext(accessor => accessor.get(workspace_1.IWorkspaceContextService, instantiation_1.optional));
const modelBasedVariableResolver = editor.invokeWithinContext(accessor => new snippetVariables_1.ModelBasedVariableResolver(accessor.get(label_1.ILabelService, instantiation_1.optional), model));
const readClipboardText = () => clipboardText;
let delta = 0;
// 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
let firstBeforeText = model.getValueInRange(SnippetSession.adjustSelection(model, editor.getSelection(), overwriteBefore, 0));
let firstAfterText = model.getValueInRange(SnippetSession.adjustSelection(model, editor.getSelection(), 0, overwriteAfter));
// remember the first non-whitespace column to decide if
// `keepWhitespace` should be overruled for secondary selections
let 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.adjustSelection(model, selection, overwriteBefore, 0);
let extensionAfter = SnippetSession.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.adjustWhitespace(model, start, snippet, adjustWhitespace || (idx > 0 && firstLineFirstNonWhitespace !== model.getLineFirstNonWhitespaceColumn(selection.positionLineNumber)), true);
snippet.resolveVariables(new snippetVariables_1.CompositeSnippetVariableResolver([
modelBasedVariableResolver,
new snippetVariables_1.ClipboardBasedVariableResolver(readClipboardText, idx, indexedSelections.length, editor.getOption(69 /* multiCursorPaste */) === 'spread'),
new snippetVariables_1.SelectionBasedVariableResolver(model, selection, idx, overtypingCapturer),
new snippetVariables_1.CommentBasedVariableResolver(model, selection),
new snippetVariables_1.TimeBasedVariableResolver,
new snippetVariables_1.WorkspaceBasedVariableResolver(workspaceService),
new snippetVariables_1.RandomBasedVariableResolver,
]));
const offset = model.getOffsetAt(start) + delta;
delta += snippet.toString().length - model.getValueLengthInRange(snippetSelection);
// 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
snippets[idx] = new OneSnippet(editor, snippet, offset, snippetLineLeadingWhitespace);
}
return { edits, 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 } = SnippetSession.createEditsAndSnippets(this._editor, this._template, this._options.overwriteBefore, this._options.overwriteAfter, false, this._options.adjustWhitespace, this._options.clipboardText, this._options.overtypingCapturer);
this._snippets = snippets;
this._editor.executeEdits('snippet', edits, undoEdits => {
if (this._snippets[0].hasPlaceholder) {
return this._move(true);
}
else {
return undoEdits
.filter(edit => !!edit.identifier) // only use our undo edits
.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.createEditsAndSnippets(this._editor, template, options.overwriteBefore, options.overwriteAfter, true, options.adjustWhitespace, options.clipboardText, options.overtypingCapturer);
this._editor.executeEdits('snippet', edits, undoEdits => {
for (const snippet of this._snippets) {
snippet.merge(snippets);
}
console.assert(snippets.length === 0);
if (this._snippets[0].hasPlaceholder) {
return this._move(undefined);
}
else {
return (undoEdits
.filter(edit => !!edit.identifier) // only use our undo edits
.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 choice() {
return this._snippets[0].choice;
}
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;
}
let 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 (let [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;
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/snippet/snippetController2*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,25/*vs/editor/common/editorContextKeys*/,123/*vs/editor/contrib/suggest/suggest*/,16/*vs/platform/contextkey/common/contextkey*/,70/*vs/platform/log/common/log*/,279/*vs/editor/contrib/snippet/snippetSession*/,518/*vs/nls!vs/editor/contrib/snippet/snippetController2*/]), function (require, exports, lifecycle_1, editorExtensions_1, range_1, selection_1, editorContextKeys_1, suggest_1, contextkey_1, log_1, snippetSession_1, nls_1) {
"use strict";
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 {
constructor(_editor, _logService, contextKeyService) {
this._editor = _editor;
this._logService = _logService;
this._snippetListener = new lifecycle_1.DisposableStore();
this._modelVersionId = -1;
this._inSnippet = SnippetController2.InSnippetMode.bindTo(contextKeyService);
this._hasNextTabstop = SnippetController2.HasNextTabstop.bindTo(contextKeyService);
this._hasPrevTabstop = SnippetController2.HasPrevTabstop.bindTo(contextKeyService);
}
static get(editor) {
return editor.getContribution(SnippetController2.ID);
}
dispose() {
var _a;
this._inSnippet.reset();
this._hasPrevTabstop.reset();
this._hasNextTabstop.reset();
(_a = this._session) === null || _a === void 0 ? void 0 : _a.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 : Object.assign(Object.assign({}, _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();
}
if (!this._session) {
this._modelVersionId = this._editor.getModel().getAlternativeVersionId();
this._session = new snippetSession_1.SnippetSession(this._editor, template, opts);
this._session.insert();
}
else {
this._session.merge(template, opts);
}
if (opts.undoStopAfter) {
this._editor.getModel().pushStackElement();
}
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()) {
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 { choice } = this._session;
if (!choice) {
this._currentChoice = undefined;
return;
}
if (this._currentChoice !== choice) {
this._currentChoice = choice;
this._editor.setSelections(this._editor.getSelections()
.map(s => selection_1.Selection.fromPositions(s.getStartPosition())));
const [first] = choice.options;
(0, suggest_1.showSimpleSuggestions)(this._editor, choice.options.map((option, i) => {
// let before = choice.options.slice(0, i);
// let after = choice.options.slice(i);
return {
kind: 13 /* Value */,
label: option.value,
insertText: option.value,
// insertText: `\${1|${after.concat(before).join(',')}|}$0`,
// snippetType: 'textmate',
sortText: 'a'.repeat(i + 1),
range: range_1.Range.fromPositions(this._editor.getPosition(), this._editor.getPosition().delta(0, first.value.length))
};
}));
}
}
finish() {
while (this._inSnippet.get()) {
this.next();
}
}
cancel(resetSelection = false) {
var _a;
this._inSnippet.reset();
this._hasPrevTabstop.reset();
this._hasNextTabstop.reset();
this._snippetListener.clear();
(_a = this._session) === null || _a === void 0 ? void 0 : _a.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() {
if (this._session) {
this._session.prev();
}
this._updateState();
}
next() {
if (this._session) {
this._session.next();
}
this._updateState();
}
isInSnippet() {
return Boolean(this._inSnippet.get());
}
};
SnippetController2.ID = 'snippetController2';
SnippetController2.InSnippetMode = new contextkey_1.RawContextKey('inSnippetMode', false, (0, nls_1.localize)(0, null));
SnippetController2.HasNextTabstop = new contextkey_1.RawContextKey('hasNextTabstop', false, (0, nls_1.localize)(1, null));
SnippetController2.HasPrevTabstop = new contextkey_1.RawContextKey('hasPrevTabstop', false, (0, nls_1.localize)(2, null));
SnippetController2 = __decorate([
__param(1, log_1.ILogService),
__param(2, contextkey_1.IContextKeyService)
], SnippetController2);
exports.SnippetController2 = SnippetController2;
(0, editorExtensions_1.registerEditorContribution)(SnippetController2.ID, SnippetController2);
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 /* EditorContrib */ + 30,
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 2 /* 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 /* EditorContrib */ + 30,
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 1024 /* Shift */ | 2 /* Tab */
}
}));
(0, editorExtensions_1.registerEditorCommand)(new CommandCtor({
id: 'leaveSnippet',
precondition: SnippetController2.InSnippetMode,
handler: ctrl => ctrl.cancel(true),
kbOpts: {
weight: 100 /* EditorContrib */ + 30,
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: 9 /* Escape */,
secondary: [1024 /* Shift */ | 9 /* 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[693/*vs/editor/contrib/suggest/suggestModel*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,12/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,21/*vs/editor/common/core/selection*/,18/*vs/editor/common/modes*/,422/*vs/editor/contrib/suggest/completionModel*/,123/*vs/editor/contrib/suggest/suggest*/,195/*vs/editor/contrib/snippet/snippetController2*/,23/*vs/base/common/cancellation*/,76/*vs/editor/common/services/editorWorkerService*/,425/*vs/editor/contrib/suggest/wordDistance*/,8/*vs/base/common/strings*/,86/*vs/platform/clipboard/common/clipboardService*/,89/*vs/platform/telemetry/common/telemetry*/,70/*vs/platform/log/common/log*/,16/*vs/platform/contextkey/common/contextkey*/,38/*vs/platform/configuration/common/configuration*/]), function (require, exports, async_1, errors_1, event_1, lifecycle_1, selection_1, modes_1, completionModel_1, suggest_1, snippetController2_1, cancellation_1, editorWorkerService_1, wordDistance_1, strings_1, clipboardService_1, telemetry_1, log_1, contextkey_1, configuration_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SuggestModel = exports.LineContext = void 0;
class LineContext {
constructor(model, position, auto, shy) {
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.auto = auto;
this.shy = shy;
}
static shouldAutoTrigger(editor) {
if (!editor.hasModel()) {
return false;
}
const model = editor.getModel();
const pos = editor.getPosition();
model.tokenizeIfCheap(pos.lineNumber);
const word = model.getWordAtPosition(pos);
if (!word) {
return false;
}
if (word.endColumn !== pos.column) {
return false;
}
if (!isNaN(Number(word.word))) {
return false;
}
return true;
}
}
exports.LineContext = LineContext;
function shouldPreventQuickSuggest(contextKeyService, configurationService) {
return (Boolean(contextKeyService.getContextKeyValue('inlineSuggestionVisible'))
&& !Boolean(configurationService.getValue('editor.inlineSuggest.allowQuickSuggestions')));
}
function shouldPreventSuggestOnTriggerCharacters(contextKeyService, configurationService) {
return (Boolean(contextKeyService.getContextKeyValue('inlineSuggestionVisible'))
&& !Boolean(configurationService.getValue('editor.inlineSuggest.allowSuggestOnTriggerCharacters')));
}
let SuggestModel = class SuggestModel {
constructor(_editor, _editorWorkerService, _clipboardService, _telemetryService, _logService, _contextKeyService, _configurationService) {
this._editor = _editor;
this._editorWorkerService = _editorWorkerService;
this._clipboardService = _clipboardService;
this._telemetryService = _telemetryService;
this._logService = _logService;
this._contextKeyService = _contextKeyService;
this._configurationService = _configurationService;
this._toDispose = new lifecycle_1.DisposableStore();
this._quickSuggestDelay = 10;
this._triggerCharacterListener = new lifecycle_1.DisposableStore();
this._triggerQuickSuggest = new async_1.TimeoutTimer();
this._state = 0 /* Idle */;
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._updateQuickSuggest();
}));
this._toDispose.add(modes_1.CompletionProviderRegistry.onDidChange(() => {
this._updateTriggerCharacters();
this._updateActiveSuggestSession();
}));
this._toDispose.add(this._editor.onDidChangeCursorSelection(e => {
this._onCursorChange(e);
}));
let editorIsComposing = false;
this._toDispose.add(this._editor.onDidCompositionStart(() => {
editorIsComposing = true;
}));
this._toDispose.add(this._editor.onDidCompositionEnd(() => {
// refilter when composition ends
editorIsComposing = false;
this._refilterCompletionItems();
}));
this._toDispose.add(this._editor.onDidChangeModelContent(() => {
// only filter completions when the editor isn't
// composing a character, e.g. ¨ + u makes ü but just
// ¨ cannot be used for filtering
if (!editorIsComposing) {
this._refilterCompletionItems();
}
}));
this._updateTriggerCharacters();
this._updateQuickSuggest();
}
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();
}
// --- handle configuration & precondition changes
_updateQuickSuggest() {
this._quickSuggestDelay = this._editor.getOption(78 /* quickSuggestionsDelay */);
if (isNaN(this._quickSuggestDelay) || (!this._quickSuggestDelay && this._quickSuggestDelay !== 0) || this._quickSuggestDelay < 0) {
this._quickSuggestDelay = 10;
}
}
_updateTriggerCharacters() {
this._triggerCharacterListener.clear();
if (this._editor.getOption(79 /* readOnly */)
|| !this._editor.hasModel()
|| !this._editor.getOption(108 /* suggestOnTriggerCharacters */)) {
return;
}
const supportsByTriggerCharacter = new Map();
for (const support of modes_1.CompletionProviderRegistry.all(this._editor.getModel())) {
for (const ch of support.triggerCharacters || []) {
let set = supportsByTriggerCharacter.get(ch);
if (!set) {
set = new Set();
set.add((0, suggest_1.getSnippetSuggestSupport)());
supportsByTriggerCharacter.set(ch, set);
}
set.add(support);
}
}
const checkTriggerCharacter = (text) => {
if (shouldPreventSuggestOnTriggerCharacters(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 existing = this._completionModel
? { items: this._completionModel.adopt(supports), clipboardText: this._completionModel.clipboardText }
: undefined;
this.trigger({ auto: true, shy: false, triggerCharacter: lastChar }, Boolean(this._completionModel), supports, existing);
}
};
this._triggerCharacterListener.add(this._editor.onDidType(checkTriggerCharacter));
this._triggerCharacterListener.add(this._editor.onDidCompositionEnd(checkTriggerCharacter));
}
// --- trigger/retrigger/cancel suggest
get state() {
return this._state;
}
cancel(retrigger = false) {
var _a;
if (this._state !== 0 /* Idle */) {
this._triggerQuickSuggest.cancel();
(_a = this._requestToken) === null || _a === void 0 ? void 0 : _a.cancel();
this._requestToken = undefined;
this._state = 0 /* Idle */;
this._completionModel = undefined;
this._context = undefined;
this._onDidCancel.fire({ retrigger });
}
}
clear() {
this._completionDisposables.clear();
}
_updateActiveSuggestSession() {
if (this._state !== 0 /* Idle */) {
if (!this._editor.hasModel() || !modes_1.CompletionProviderRegistry.has(this._editor.getModel())) {
this.cancel();
}
else {
this.trigger({ auto: this._state === 2 /* Auto */, shy: false }, true);
}
}
}
_onCursorChange(e) {
if (!this._editor.hasModel()) {
return;
}
const model = this._editor.getModel();
const prevSelection = this._currentSelection;
this._currentSelection = this._editor.getSelection();
if (!e.selection.isEmpty()
|| (e.reason !== 0 /* NotSet */ && e.reason !== 3 /* 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 (!modes_1.CompletionProviderRegistry.has(model)) {
return;
}
if (this._state === 0 /* Idle */ && e.reason === 0 /* NotSet */) {
if (this._editor.getOption(77 /* quickSuggestions */) === false) {
// not enabled
return;
}
if (!prevSelection.containsRange(this._currentSelection) && !prevSelection.getEndPosition().isBeforeOrEqual(this._currentSelection.getPosition())) {
// cursor didn't move RIGHT
return;
}
if (this._editor.getOption(105 /* suggest */).snippetsPreventQuickSuggestions && snippetController2_1.SnippetController2.get(this._editor).isInSnippet()) {
// no quick suggestion when in snippet mode
return;
}
this.cancel();
this._triggerQuickSuggest.cancelAndSet(() => {
if (this._state !== 0 /* Idle */) {
return;
}
if (!LineContext.shouldAutoTrigger(this._editor)) {
return;
}
if (!this._editor.hasModel()) {
return;
}
const model = this._editor.getModel();
const pos = this._editor.getPosition();
// validate enabled now
const quickSuggestions = this._editor.getOption(77 /* quickSuggestions */);
if (quickSuggestions === false) {
return;
}
else if (quickSuggestions === true) {
// all good
}
else {
// Check the type of the token that triggered this
model.tokenizeIfCheap(pos.lineNumber);
const lineTokens = model.getLineTokens(pos.lineNumber);
const tokenType = lineTokens.getStandardTokenType(lineTokens.findTokenIndexAtOffset(Math.max(pos.column - 1 - 1, 0)));
const inValidScope = quickSuggestions.other && tokenType === 0 /* Other */
|| quickSuggestions.comments && tokenType === 1 /* Comment */
|| quickSuggestions.strings && tokenType === 2 /* String */;
if (!inValidScope) {
return;
}
}
if (shouldPreventQuickSuggest(this._contextKeyService, this._configurationService)) {
// do not trigger quick suggestions if inline suggestions are shown
return;
}
// we made it till here -> trigger now
this.trigger({ auto: true, shy: false });
}, this._quickSuggestDelay);
}
else if (this._state !== 0 /* Idle */ && e.reason === 3 /* 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();
}
}
_refilterCompletionItems() {
// Re-filter suggestions. This MUST run async because filtering/scoring
// uses the model content AND the cursor position. The latter is NOT
// updated when the document has changed (the event which drives this method)
// and therefore a little pause (next mirco task) is needed. See:
// https://stackoverflow.com/questions/25915634/difference-between-microtask-and-macrotask-within-an-event-loop-context#25933985
Promise.resolve().then(() => {
if (this._state === 0 /* Idle */) {
return;
}
if (!this._editor.hasModel()) {
return;
}
const model = this._editor.getModel();
const position = this._editor.getPosition();
const ctx = new LineContext(model, position, this._state === 2 /* Auto */, false);
this._onNewContext(ctx);
});
}
trigger(context, retrigger = false, onlyFrom, existing) {
var _a;
if (!this._editor.hasModel()) {
return;
}
const model = this._editor.getModel();
const auto = context.auto;
const ctx = new LineContext(model, this._editor.getPosition(), auto, context.shy);
// Cancel previous requests, change state & update UI
this.cancel(retrigger);
this._state = auto ? 2 /* Auto */ : 1 /* Manual */;
this._onDidTrigger.fire({ auto, shy: context.shy, position: this._editor.getPosition() });
// Capture context when request was sent
this._context = ctx;
// Build context for request
let suggestCtx = { triggerKind: (_a = context.triggerKind) !== null && _a !== void 0 ? _a : 0 /* Invoke */ };
if (context.triggerCharacter) {
suggestCtx = {
triggerKind: 1 /* TriggerCharacter */,
triggerCharacter: context.triggerCharacter
};
}
this._requestToken = new cancellation_1.CancellationTokenSource();
// kind filter and snippet sort rules
const snippetSuggestions = this._editor.getOption(100 /* snippetSuggestions */);
let snippetSortOrder = 1 /* Inline */;
switch (snippetSuggestions) {
case 'top':
snippetSortOrder = 0 /* Top */;
break;
// ↓ that's the default anyways...
// case 'inline':
// snippetSortOrder = SnippetSortOrder.Inline;
// break;
case 'bottom':
snippetSortOrder = 2 /* Bottom */;
break;
}
const { itemKind: itemKindFilter, showDeprecated } = SuggestModel._createSuggestFilter(this._editor);
const wordDistance = wordDistance_1.WordDistance.create(this._editorWorkerService, this._editor);
const completions = (0, suggest_1.provideSuggestionItems)(model, this._editor.getPosition(), new suggest_1.CompletionOptions(snippetSortOrder, itemKindFilter, onlyFrom, showDeprecated), suggestCtx, this._requestToken.token);
Promise.all([completions, wordDistance]).then(([completions, wordDistance]) => __awaiter(this, void 0, void 0, function* () {
var _b;
(_b = this._requestToken) === null || _b === void 0 ? void 0 : _b.dispose();
if (!this._editor.hasModel()) {
return;
}
let clipboardText = existing === null || existing === void 0 ? void 0 : existing.clipboardText;
if (!clipboardText && completions.needsClipboard) {
clipboardText = yield this._clipboardService.readText();
}
if (this._state === 0 /* Idle */) {
return;
}
const model = this._editor.getModel();
let items = completions.items;
if (existing) {
const cmpFn = (0, suggest_1.getSuggestionComparator)(snippetSortOrder);
items = items.concat(existing.items).sort(cmpFn);
}
const ctx = new LineContext(model, this._editor.getPosition(), auto, context.shy);
this._completionModel = new completionModel_1.CompletionModel(items, this._context.column, {
leadingLineContent: ctx.leadingLineContent,
characterCountDelta: ctx.column - this._context.column
}, wordDistance, this._editor.getOption(105 /* suggest */), this._editor.getOption(100 /* snippetSuggestions */), 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);
})).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(100 /* snippetSuggestions */);
if (snippetSuggestions === 'none') {
result.add(27 /* Snippet */);
}
// type setting
const suggestOptions = editor.getOption(105 /* suggest */);
if (!suggestOptions.showMethods) {
result.add(0 /* Method */);
}
if (!suggestOptions.showFunctions) {
result.add(1 /* Function */);
}
if (!suggestOptions.showConstructors) {
result.add(2 /* Constructor */);
}
if (!suggestOptions.showFields) {
result.add(3 /* Field */);
}
if (!suggestOptions.showVariables) {
result.add(4 /* Variable */);
}
if (!suggestOptions.showClasses) {
result.add(5 /* Class */);
}
if (!suggestOptions.showStructs) {
result.add(6 /* Struct */);
}
if (!suggestOptions.showInterfaces) {
result.add(7 /* Interface */);
}
if (!suggestOptions.showModules) {
result.add(8 /* Module */);
}
if (!suggestOptions.showProperties) {
result.add(9 /* Property */);
}
if (!suggestOptions.showEvents) {
result.add(10 /* Event */);
}
if (!suggestOptions.showOperators) {
result.add(11 /* Operator */);
}
if (!suggestOptions.showUnits) {
result.add(12 /* Unit */);
}
if (!suggestOptions.showValues) {
result.add(13 /* Value */);
}
if (!suggestOptions.showConstants) {
result.add(14 /* Constant */);
}
if (!suggestOptions.showEnums) {
result.add(15 /* Enum */);
}
if (!suggestOptions.showEnumMembers) {
result.add(16 /* EnumMember */);
}
if (!suggestOptions.showKeywords) {
result.add(17 /* Keyword */);
}
if (!suggestOptions.showWords) {
result.add(18 /* Text */);
}
if (!suggestOptions.showColors) {
result.add(19 /* Color */);
}
if (!suggestOptions.showFiles) {
result.add(20 /* File */);
}
if (!suggestOptions.showReferences) {
result.add(21 /* Reference */);
}
if (!suggestOptions.showColors) {
result.add(22 /* Customcolor */);
}
if (!suggestOptions.showFolders) {
result.add(23 /* Folder */);
}
if (!suggestOptions.showTypeParameters) {
result.add(24 /* TypeParameter */);
}
if (!suggestOptions.showSnippets) {
result.add(27 /* Snippet */);
}
if (!suggestOptions.showUsers) {
result.add(25 /* User */);
}
if (!suggestOptions.showIssues) {
result.add(26 /* 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.auto, shy: false }, 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
// Select those providers have not contributed to this completion model and re-trigger completions for
// them. Also adopt the existing items and merge them into the new completion model
const inactiveProvider = new Set(modes_1.CompletionProviderRegistry.all(this._editor.getModel()));
for (let provider of this._completionModel.allProvider) {
inactiveProvider.delete(provider);
}
const items = this._completionModel.adopt(new Set());
this.trigger({ auto: this._context.auto, shy: false }, true, inactiveProvider, { items, clipboardText: this._completionModel.clipboardText });
return;
}
if (ctx.column > this._context.column && this._completionModel.incomplete.size > 0 && ctx.leadingWord.word.length !== 0) {
// typed -> moved cursor RIGHT & incomple model & still on a word -> retrigger
const { incomplete } = this._completionModel;
const items = this._completionModel.adopt(incomplete);
this.trigger({ auto: this._state === 2 /* Auto */, shy: false, triggerKind: 2 /* TriggerForIncompleteCompletions */ }, true, incomplete, { items, clipboardText: this._completionModel.clipboardText });
}
else {
// typed -> moved cursor RIGHT -> update UI
let 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) {
if (LineContext.shouldAutoTrigger(this._editor) && this._context.leadingWord.endColumn < ctx.leadingWord.startColumn) {
// retrigger when heading into a new word
this.trigger({ auto: this._context.auto, shy: false }, true);
return;
}
if (!this._context.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,
auto: this._context.auto,
shy: this._context.shy,
isFrozen,
});
}
}
};
SuggestModel = __decorate([
__param(1, editorWorkerService_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)
], SuggestModel);
exports.SuggestModel = 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[280/*vs/editor/contrib/suggest/suggestController*/], __M([0/*require*/,1/*exports*/,44/*vs/base/browser/ui/aria/aria*/,19/*vs/base/common/arrays*/,12/*vs/base/common/errors*/,41/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,66/*vs/editor/browser/core/editorState*/,14/*vs/editor/browser/editorExtensions*/,56/*vs/editor/common/core/editOperation*/,3/*vs/editor/common/core/range*/,25/*vs/editor/common/editorContextKeys*/,195/*vs/editor/contrib/snippet/snippetController2*/,116/*vs/editor/contrib/snippet/snippetParser*/,590/*vs/editor/contrib/suggest/suggestMemory*/,521/*vs/nls!vs/editor/contrib/suggest/suggestController*/,26/*vs/platform/commands/common/commands*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/,88/*vs/platform/keybinding/common/keybindingsRegistry*/,123/*vs/editor/contrib/suggest/suggest*/,562/*vs/editor/contrib/suggest/suggestAlternatives*/,693/*vs/editor/contrib/suggest/suggestModel*/,680/*vs/editor/contrib/suggest/suggestWidget*/,563/*vs/editor/contrib/suggest/wordContextKey*/,6/*vs/base/common/event*/,15/*vs/base/common/async*/,20/*vs/base/common/types*/,423/*vs/editor/contrib/suggest/suggestCommitCharacters*/,424/*vs/editor/contrib/suggest/suggestOvertypingCapturer*/,13/*vs/editor/common/core/position*/,17/*vs/base/common/platform*/,33/*vs/platform/actions/common/actions*/,23/*vs/base/common/cancellation*/,70/*vs/platform/log/common/log*/,81/*vs/base/common/stopwatch*/]), function (require, exports, aria_1, arrays_1, errors_1, keyCodes_1, lifecycle_1, editorState_1, editorExtensions_1, editOperation_1, range_1, editorContextKeys_1, snippetController2_1, snippetParser_1, suggestMemory_1, nls, commands_1, contextkey_1, instantiation_1, keybindingsRegistry_1, suggest_1, suggestAlternatives_1, suggestModel_1, suggestWidget_1, wordContextKey_1, event_1, async_1, types_1, suggestCommitCharacters_1, suggestOvertypingCapturer_1, position_1, platform, actions_1, cancellation_1, log_1, stopwatch_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TriggerSuggestAction = exports.SuggestController = void 0;
// sticky suggest widget which doesn't disappear on focus out and such
let _sticky = false;
// _sticky = Boolean("true"); // done "weirdly" so that a lint warning prevents you from pushing this
class LineSuffix {
constructor(_model, _position) {
this._model = _model;
this._position = _position;
// 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);
this._marker = _model.deltaDecorations([], [{
range: range_1.Range.fromPositions(_position, end),
options: { description: 'suggest-line-suffix', stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ }
}]);
}
}
dispose() {
if (this._marker && !this._model.isDisposed()) {
this._model.deltaDecorations(this._marker, []);
}
}
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[0]);
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 {
constructor(editor, _memoryService, _commandService, _contextKeyService, _instantiationService, _logService) {
this._memoryService = _memoryService;
this._commandService = _commandService;
this._contextKeyService = _contextKeyService;
this._instantiationService = _instantiationService;
this._logService = _logService;
this._lineSuffix = new lifecycle_1.MutableDisposable();
this._toDispose = new lifecycle_1.DisposableStore();
this.editor = editor;
this.model = _instantiationService.createInstance(suggestModel_1.SuggestModel, this.editor);
// context key: update insert/replace mode
const ctxInsertMode = suggest_1.Context.InsertMode.bindTo(_contextKeyService);
ctxInsertMode.set(editor.getOption(105 /* suggest */).insertMode);
this.model.onDidTrigger(() => ctxInsertMode.set(editor.getOption(105 /* suggest */).insertMode));
this.widget = this._toDispose.add(new async_1.IdleValue(() => {
const widget = this._instantiationService.createInstance(suggestWidget_1.SuggestWidget, this.editor);
this._toDispose.add(widget);
this._toDispose.add(widget.onDidSelect(item => this._insertSuggestion(item, 0), this));
// Wire up logic to accept a suggestion on certain characters
const commitCharacterController = new suggestCommitCharacters_1.CommitCharacterController(this.editor, widget, item => this._insertSuggestion(item, 2 /* NoAfterUndoStop */));
this._toDispose.add(commitCharacterController);
this._toDispose.add(this.model.onDidSuggest(e => {
if (e.completionModel.items.length === 0) {
commitCharacterController.reset();
}
}));
// 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 /* acceptSuggestionOnEnter */) === 'smart'
&& this.model.state === 2 /* Auto */
&& !item.completion.command
&& !item.completion.additionalTextEdits
&& !(item.completion.insertTextRules & 4 /* 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.toKeybinding().equals(new keyCodes_1.SimpleKeybinding(true, false, false, false, 33 /* KEY_C */)) ||
(platform.isMacintosh && e.toKeybinding().equals(new keyCodes_1.SimpleKeybinding(false, false, false, true, 33 /* KEY_C */)))) {
e.stopPropagation();
return;
}
if (!e.toKeybinding().isModifierKey()) {
this.editor.focus();
}
}));
return widget;
}));
// Wire up text overtyping capture
this._overtypingCapturer = this._toDispose.add(new async_1.IdleValue(() => {
return this._toDispose.add(new suggestOvertypingCapturer_1.OvertypingCapturer(this.editor, this.model));
}));
this._alternatives = this._toDispose.add(new async_1.IdleValue(() => {
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.shy) {
let index = this._memoryService.select(this.editor.getModel(), this.editor.getPosition(), e.completionModel.items);
this.widget.value.showSuggestions(e.completionModel, index, e.isFrozen, e.auto);
}
}));
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
let acceptSuggestionsOnEnter = suggest_1.Context.AcceptSuggestionsOnEnter.bindTo(_contextKeyService);
let updateFromConfig = () => {
const acceptSuggestionOnEnter = this.editor.getOption(1 /* acceptSuggestionOnEnter */);
acceptSuggestionsOnEnter.set(acceptSuggestionOnEnter === 'on' || acceptSuggestionOnEnter === 'smart');
};
this._toDispose.add(this.editor.onDidChangeConfiguration(() => updateFromConfig()));
updateFromConfig();
}
static get(editor) {
return editor.getContribution(SuggestController.ID);
}
dispose() {
this._alternatives.dispose();
this._toDispose.dispose();
this.widget.dispose();
this.model.dispose();
this._lineSuffix.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 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 /* NoBeforeUndoStop */)) {
this.editor.pushUndoStop();
}
// compute overwrite[Before|After] deltas BEFORE applying extra edits
const info = this.getOverwriteInfo(item, Boolean(flags & 8 /* AlternativeOverwriteConfig */));
// keep item in memory
this._memoryService.memorize(model, this.editor.getPosition(), item);
if (Array.isArray(item.completion.additionalTextEdits)) {
// sync additional edits
const scrollState = editorState_1.StableEditorScrollState.capture(this.editor);
this.editor.executeEdits('suggestController.additionalTextEdits.sync', item.completion.additionalTextEdits.map(edit => editOperation_1.EditOperation.replace(range_1.Range.lift(edit.range), edit.text)));
scrollState.restoreRelativeVerticalPositionOfCursor(this.editor);
}
else if (!item.isResolved) {
// async additional edits
const sw = new stopwatch_1.StopWatch(true);
let position;
const docListener = model.onDidChangeContent(e => {
if (e.isFlush) {
cts.cancel();
docListener.dispose();
return;
}
for (let change of e.changes) {
const thisPosition = range_1.Range.getEndPosition(change.range);
if (!position || position_1.Position.isBefore(thisPosition, position)) {
position = thisPosition;
}
}
});
let oldFlags = flags;
flags |= 2 /* NoAfterUndoStop */;
let didType = false;
let typeListener = this.editor.onWillType(() => {
typeListener.dispose();
didType = true;
if (!(oldFlags & 2 /* NoAfterUndoStop */)) {
this.editor.pushUndoStop();
}
});
tasks.push(item.resolve(cts.token).then(() => {
if (!item.completion.additionalTextEdits || cts.token.isCancellationRequested) {
return false;
}
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 = editorState_1.StableEditorScrollState.capture(this.editor);
this.editor.executeEdits('suggestController.additionalTextEdits.async', item.completion.additionalTextEdits.map(edit => editOperation_1.EditOperation.replace(range_1.Range.lift(edit.range), edit.text)));
scrollState.restoreRelativeVerticalPositionOfCursor(this.editor);
if (didType || !(oldFlags & 2 /* NoAfterUndoStop */)) {
this.editor.pushUndoStop();
}
return true;
}).then(applied => {
this._logService.trace('[suggest] async resolving of edits DONE (ms, applied?)', sw.elapsed(), applied);
docListener.dispose();
typeListener.dispose();
}));
}
let { insertText } = item.completion;
if (!(item.completion.insertTextRules & 4 /* InsertAsSnippet */)) {
insertText = snippetParser_1.SnippetParser.escape(insertText);
}
snippetController2_1.SnippetController2.get(this.editor).insert(insertText, {
overwriteBefore: info.overwriteBefore,
overwriteAfter: info.overwriteAfter,
undoStopBefore: false,
undoStopAfter: false,
adjustWhitespace: !(item.completion.insertTextRules & 1 /* KeepWhitespace */),
clipboardText: event.model.clipboardText,
overtypingCapturer: this._overtypingCapturer.value
});
if (!(flags & 2 /* NoAfterUndoStop */)) {
this.editor.pushUndoStop();
}
if (!item.completion.command) {
// done
this.model.cancel();
}
else if (item.completion.command.id === TriggerSuggestAction.id) {
// retigger
this.model.trigger({ auto: true, shy: false }, true);
}
else {
// exec command, done
tasks.push(this._commandService.executeCommand(item.completion.command.id, ...(item.completion.command.arguments ? [...item.completion.command.arguments] : [])).catch(errors_1.onUnexpectedError));
this.model.cancel();
}
if (flags & 4 /* 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 /* NoBeforeUndoStop */ | 2 /* NoAfterUndoStop */ | (flags & 8 /* AlternativeOverwriteConfig */ ? 8 /* AlternativeOverwriteConfig */ : 0));
break;
}
});
}
this._alertCompletionItem(item);
// clear only now - after all tasks are done
Promise.all(tasks).finally(() => {
this.model.clear();
cts.dispose();
});
}
getOverwriteInfo(item, toggleMode) {
(0, types_1.assertType)(this.editor.hasModel());
let replace = this.editor.getOption(105 /* 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)) {
let msg = nls.localize(0, null, item.textLabel, item.completion.additionalTextEdits.length);
(0, aria_1.alert)(msg);
}
}
triggerSuggest(onlyFrom) {
if (this.editor.hasModel()) {
this.model.trigger({ auto: false, shy: false }, false, onlyFrom);
this.editor.revealLine(this.editor.getPosition().lineNumber, 0 /* 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 /* 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
let 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 /* KeepAlternativeSuggestions */ | 1 /* NoBeforeUndoStop */ | 2 /* NoAfterUndoStop */);
}, undefined, listener);
});
this.model.trigger({ auto: false, shy: true });
this.editor.revealLine(positionNow.lineNumber, 0 /* Smooth */);
this.editor.focus();
}
acceptSelectedSuggestion(keepAlternativeSuggestions, alternativeOverwriteConfig) {
const item = this.widget.value.getFocusedItem();
let flags = 0;
if (keepAlternativeSuggestions) {
flags |= 4 /* KeepAlternativeSuggestions */;
}
if (alternativeOverwriteConfig) {
flags |= 8 /* 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();
}
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() {
this.widget.value.stopForceRenderingAbove();
}
};
SuggestController.ID = 'editor.contrib.suggestController';
SuggestController = __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)
], SuggestController);
exports.SuggestController = SuggestController;
class TriggerSuggestAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: TriggerSuggestAction.id,
label: nls.localize(1, null),
alias: 'Trigger Suggest',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasCompletionItemProvider),
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 2048 /* CtrlCmd */ | 10 /* Space */,
secondary: [2048 /* CtrlCmd */ | 39 /* KEY_I */],
mac: { primary: 256 /* WinCtrl */ | 10 /* Space */, secondary: [512 /* Alt */ | 9 /* Escape */, 2048 /* CtrlCmd */ | 39 /* KEY_I */] },
weight: 100 /* EditorContrib */
}
});
}
run(accessor, editor) {
const controller = SuggestController.get(editor);
if (!controller) {
return;
}
controller.triggerSuggest();
}
}
exports.TriggerSuggestAction = TriggerSuggestAction;
TriggerSuggestAction.id = 'editor.action.triggerSuggest';
(0, editorExtensions_1.registerEditorContribution)(SuggestController.ID, SuggestController);
(0, editorExtensions_1.registerEditorAction)(TriggerSuggestAction);
const weight = 100 /* EditorContrib */ + 90;
const SuggestCommand = editorExtensions_1.EditorCommand.bindToContribution(SuggestController.get);
(0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
id: 'acceptSelectedSuggestion',
precondition: suggest_1.Context.Visible,
handler(x) {
x.acceptSelectedSuggestion(true, false);
}
}));
// normal tab
keybindingsRegistry_1.KeybindingsRegistry.registerKeybindingRule({
id: 'acceptSelectedSuggestion',
when: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, editorContextKeys_1.EditorContextKeys.textInputFocus),
primary: 2 /* Tab */,
weight
});
// accept on enter has special rules
keybindingsRegistry_1.KeybindingsRegistry.registerKeybindingRule({
id: 'acceptSelectedSuggestion',
when: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, editorContextKeys_1.EditorContextKeys.textInputFocus, suggest_1.Context.AcceptSuggestionsOnEnter, suggest_1.Context.MakesTextEdit),
primary: 3 /* Enter */,
weight,
});
actions_1.MenuRegistry.appendMenuItem(suggest_1.suggestWidgetStatusbarMenu, {
command: { id: 'acceptSelectedSuggestion', title: nls.localize(2, null) },
group: 'left',
order: 1,
when: suggest_1.Context.HasInsertAndReplaceRange.toNegated()
});
actions_1.MenuRegistry.appendMenuItem(suggest_1.suggestWidgetStatusbarMenu, {
command: { id: 'acceptSelectedSuggestion', title: nls.localize(3, null) },
group: 'left',
order: 1,
when: contextkey_1.ContextKeyExpr.and(suggest_1.Context.HasInsertAndReplaceRange, suggest_1.Context.InsertMode.isEqualTo('insert'))
});
actions_1.MenuRegistry.appendMenuItem(suggest_1.suggestWidgetStatusbarMenu, {
command: { id: 'acceptSelectedSuggestion', title: nls.localize(4, null) },
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),
kbOpts: {
weight: weight,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 1024 /* Shift */ | 3 /* Enter */,
secondary: [1024 /* Shift */ | 2 /* 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(5, null)
}, {
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(6, null)
}]
}));
// 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 /* Escape */,
secondary: [1024 /* Shift */ | 9 /* Escape */]
}
}));
(0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
id: 'selectNextSuggestion',
precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.MultipleSuggestions),
handler: c => c.selectNextSuggestion(),
kbOpts: {
weight: weight,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 18 /* DownArrow */,
secondary: [2048 /* CtrlCmd */ | 18 /* DownArrow */],
mac: { primary: 18 /* DownArrow */, secondary: [2048 /* CtrlCmd */ | 18 /* DownArrow */, 256 /* WinCtrl */ | 44 /* KEY_N */] }
}
}));
(0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
id: 'selectNextPageSuggestion',
precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.MultipleSuggestions),
handler: c => c.selectNextPageSuggestion(),
kbOpts: {
weight: weight,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 12 /* PageDown */,
secondary: [2048 /* CtrlCmd */ | 12 /* PageDown */]
}
}));
(0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
id: 'selectLastSuggestion',
precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.MultipleSuggestions),
handler: c => c.selectLastSuggestion()
}));
(0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
id: 'selectPrevSuggestion',
precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.MultipleSuggestions),
handler: c => c.selectPrevSuggestion(),
kbOpts: {
weight: weight,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 16 /* UpArrow */,
secondary: [2048 /* CtrlCmd */ | 16 /* UpArrow */],
mac: { primary: 16 /* UpArrow */, secondary: [2048 /* CtrlCmd */ | 16 /* UpArrow */, 256 /* WinCtrl */ | 46 /* KEY_P */] }
}
}));
(0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
id: 'selectPrevPageSuggestion',
precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.MultipleSuggestions),
handler: c => c.selectPrevPageSuggestion(),
kbOpts: {
weight: weight,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 11 /* PageUp */,
secondary: [2048 /* CtrlCmd */ | 11 /* PageUp */]
}
}));
(0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
id: 'selectFirstSuggestion',
precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.MultipleSuggestions),
handler: c => c.selectFirstSuggestion()
}));
(0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
id: 'toggleSuggestionDetails',
precondition: suggest_1.Context.Visible,
handler: x => x.toggleSuggestionDetails(),
kbOpts: {
weight: weight,
kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
primary: 2048 /* CtrlCmd */ | 10 /* Space */,
mac: { primary: 256 /* WinCtrl */ | 10 /* Space */ }
},
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(7, null)
}, {
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(8, null)
}]
}));
(0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
id: 'toggleExplainMode',
precondition: suggest_1.Context.Visible,
handler: x => x.toggleExplainMode(),
kbOpts: {
weight: 100 /* EditorContrib */,
primary: 2048 /* CtrlCmd */ | 85 /* US_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 /* CtrlCmd */ | 512 /* Alt */ | 10 /* Space */,
mac: { primary: 256 /* WinCtrl */ | 512 /* Alt */ | 10 /* 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) ? Object.assign({ fallback: 'tab' }, arg) : { fallback: 'tab' });
},
kbOpts: {
weight,
primary: 2 /* 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 /* 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 /* Shift */ | 2 /* Tab */
}
}));
(0, editorExtensions_1.registerEditorAction)(class extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.resetSuggestSize',
label: nls.localize(9, null),
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[694/*vs/editor/contrib/inlineCompletions/suggestWidgetAdapterModel*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/,233/*vs/editor/contrib/inlineCompletions/ghostText*/,267/*vs/editor/contrib/inlineCompletions/inlineCompletionsModel*/,116/*vs/editor/contrib/snippet/snippetParser*/,279/*vs/editor/contrib/snippet/snippetSession*/,280/*vs/editor/contrib/suggest/suggestController*/]), function (require, exports, async_1, event_1, lifecycle_1, range_1, ghostText_1, inlineCompletionsModel_1, snippetParser_1, snippetSession_1, suggestController_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SuggestWidgetAdapterModel = void 0;
class SuggestWidgetAdapterModel extends ghostText_1.BaseGhostTextWidgetModel {
constructor(editor) {
super(editor);
this.isSuggestWidgetVisible = false;
this.currentGhostText = undefined;
this._isActive = false;
this.isShiftKeyPressed = false;
this.minReservedLineCount = 0;
// This delay fixes an suggest widget issue when typing "." immediately restarts the suggestion session.
this.setInactiveDelayed = this._register(new async_1.RunOnceScheduler(() => {
if (!this.isSuggestWidgetVisible) {
if (this.isActive) {
this._isActive = false;
this.onDidChangeEmitter.fire();
}
}
}, 100));
const suggestController = suggestController_1.SuggestController.get(this.editor);
if (suggestController) {
let isBoundToSuggestWidget = false;
const bindToSuggestWidget = () => {
if (isBoundToSuggestWidget) {
return;
}
isBoundToSuggestWidget = true;
this._register(suggestController.widget.value.onDidShow(() => {
this.isSuggestWidgetVisible = true;
this._isActive = true;
this.updateFromSuggestion();
}));
this._register(suggestController.widget.value.onDidHide(() => {
this.isSuggestWidgetVisible = false;
this.setInactiveDelayed.schedule();
this.minReservedLineCount = 0;
this.updateFromSuggestion();
}));
this._register(suggestController.widget.value.onDidFocus(() => {
this.isSuggestWidgetVisible = true;
this._isActive = true;
this.updateFromSuggestion();
}));
};
this._register(event_1.Event.once(suggestController.model.onDidTrigger)(e => {
bindToSuggestWidget();
}));
}
this.updateFromSuggestion();
this._register(this.editor.onDidChangeCursorPosition((e) => {
if (this.isSuggestionPreviewEnabled()) {
this.update();
}
}));
this._register((0, lifecycle_1.toDisposable)(() => {
const suggestController = suggestController_1.SuggestController.get(this.editor);
if (suggestController) {
suggestController.stopForceRenderingAbove();
}
}));
// See the command acceptAlternativeSelectedSuggestion that is bound to shift+tab
this._register(editor.onKeyDown(e => {
if (e.shiftKey && !this.isShiftKeyPressed) {
this.isShiftKeyPressed = true;
this.updateFromSuggestion();
}
}));
this._register(editor.onKeyUp(e => {
if (e.shiftKey && this.isShiftKeyPressed) {
this.isShiftKeyPressed = false;
this.updateFromSuggestion();
}
}));
}
get isActive() { return this._isActive; }
setExpanded(expanded) {
super.setExpanded(expanded);
this.updateFromSuggestion();
}
isSuggestionPreviewEnabled() {
const suggestOptions = this.editor.getOption(105 /* suggest */);
return suggestOptions.preview;
}
updateFromSuggestion() {
const suggestController = suggestController_1.SuggestController.get(this.editor);
if (!suggestController) {
this.setCurrentInlineCompletion(undefined);
return;
}
if (!this.isSuggestWidgetVisible) {
this.setCurrentInlineCompletion(undefined);
return;
}
const focusedItem = suggestController.widget.value.getFocusedItem();
if (!focusedItem) {
this.setCurrentInlineCompletion(undefined);
return;
}
// TODO: item.isResolved
this.setCurrentInlineCompletion(getInlineCompletion(suggestController, this.editor.getPosition(), focusedItem, this.isShiftKeyPressed));
}
setCurrentInlineCompletion(completion) {
this.currentCompletion = completion;
this.update();
}
update() {
const completion = this.currentCompletion;
const mode = this.editor.getOptions().get(105 /* suggest */).previewMode;
this.setGhostText(completion
? ((0, inlineCompletionsModel_1.inlineCompletionToGhostText)(completion, this.editor.getModel(), mode, this.editor.getPosition()) ||
// Show an invisible ghost text to reserve space
new ghostText_1.GhostText(completion.range.endLineNumber, [], this.minReservedLineCount))
: undefined);
}
setGhostText(newGhostText) {
if (ghostText_1.GhostText.equals(this.currentGhostText, newGhostText)) {
return;
}
this.currentGhostText = newGhostText;
if (this.currentGhostText && this.expanded) {
this.minReservedLineCount = Math.max(this.minReservedLineCount, ...this.currentGhostText.parts.map(p => p.lines.length - 1));
}
const suggestController = suggestController_1.SuggestController.get(this.editor);
if (suggestController) {
if (this.minReservedLineCount >= 1 && this.isSuggestionPreviewEnabled()) {
suggestController.forceRenderingAbove();
}
else {
suggestController.stopForceRenderingAbove();
}
}
this.onDidChangeEmitter.fire();
}
get ghostText() {
return this.isSuggestionPreviewEnabled()
? this.currentGhostText
: undefined;
}
}
exports.SuggestWidgetAdapterModel = SuggestWidgetAdapterModel;
function getInlineCompletion(suggestController, position, suggestion, toggleMode) {
const item = suggestion.item;
if (Array.isArray(item.completion.additionalTextEdits)) {
// cannot represent additional text edits
return {
text: '',
range: range_1.Range.fromPositions(position, position),
};
}
let { insertText } = item.completion;
if (item.completion.insertTextRules & 4 /* InsertAsSnippet */) {
const snippet = new snippetParser_1.SnippetParser().parse(insertText);
const model = suggestController.editor.getModel();
snippetSession_1.SnippetSession.adjustWhitespace(model, position, snippet, true, true);
insertText = snippet.toString();
}
const info = suggestController.getOverwriteInfo(item, toggleMode);
return {
text: insertText,
range: range_1.Range.fromPositions(position.delta(0, -info.overwriteBefore), position.delta(0, Math.max(info.overwriteAfter, 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[695/*vs/editor/contrib/inlineCompletions/ghostTextModel*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,267/*vs/editor/contrib/inlineCompletions/inlineCompletionsModel*/,694/*vs/editor/contrib/inlineCompletions/suggestWidgetAdapterModel*/,26/*vs/platform/commands/common/commands*/,6/*vs/base/common/event*/,13/*vs/editor/common/core/position*/,418/*vs/editor/contrib/inlineCompletions/utils*/]), function (require, exports, lifecycle_1, inlineCompletionsModel_1, suggestWidgetAdapterModel_1, commands_1, event_1, position_1, utils_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GhostTextModel = exports.DelegatingModel = void 0;
class DelegatingModel extends lifecycle_1.Disposable {
constructor() {
super(...arguments);
this.onDidChangeEmitter = new event_1.Emitter();
this.onDidChange = this.onDidChangeEmitter.event;
this.hasCachedGhostText = false;
this.currentModelRef = this._register(new lifecycle_1.MutableDisposable());
}
get targetModel() {
var _a;
return (_a = this.currentModelRef.value) === null || _a === void 0 ? void 0 : _a.object;
}
setTargetModel(model) {
var _a;
if (((_a = this.currentModelRef.value) === null || _a === void 0 ? void 0 : _a.object) === model) {
return;
}
this.currentModelRef.clear();
this.currentModelRef.value = model ? (0, utils_1.createDisposableRef)(model, model.onDidChange(() => {
this.hasCachedGhostText = false;
this.onDidChangeEmitter.fire();
})) : undefined;
this.hasCachedGhostText = false;
this.onDidChangeEmitter.fire();
}
get ghostText() {
var _a, _b;
if (!this.hasCachedGhostText) {
this.cachedGhostText = (_b = (_a = this.currentModelRef.value) === null || _a === void 0 ? void 0 : _a.object) === null || _b === void 0 ? void 0 : _b.ghostText;
this.hasCachedGhostText = true;
}
return this.cachedGhostText;
}
setExpanded(expanded) {
var _a;
(_a = this.targetModel) === null || _a === void 0 ? void 0 : _a.setExpanded(expanded);
}
get expanded() {
return this.targetModel ? this.targetModel.expanded : false;
}
get minReservedLineCount() {
return this.targetModel ? this.targetModel.minReservedLineCount : 0;
}
}
exports.DelegatingModel = DelegatingModel;
/**
* A ghost text model that is both driven by inline completions and the suggest widget.
*/
let GhostTextModel = class GhostTextModel extends DelegatingModel {
constructor(editor, commandService) {
super();
this.editor = editor;
this.commandService = commandService;
this.suggestWidgetAdapterModel = this._register(new suggestWidgetAdapterModel_1.SuggestWidgetAdapterModel(this.editor));
this.inlineCompletionsModel = this._register(new inlineCompletionsModel_1.InlineCompletionsModel(this.editor, this.commandService));
this._register(this.suggestWidgetAdapterModel.onDidChange(() => {
this.updateModel();
}));
this.updateModel();
}
get activeInlineCompletionsModel() {
if (this.targetModel === this.inlineCompletionsModel) {
return this.inlineCompletionsModel;
}
return undefined;
}
updateModel() {
this.setTargetModel(this.suggestWidgetAdapterModel.isActive
? this.suggestWidgetAdapterModel
: this.inlineCompletionsModel);
this.inlineCompletionsModel.setActive(this.targetModel === this.inlineCompletionsModel);
}
shouldShowHoverAt(hoverRange) {
var _a;
const ghostText = (_a = this.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.ghostText;
if (ghostText) {
return ghostText.parts.some(p => hoverRange.containsPosition(new position_1.Position(ghostText.lineNumber, p.column)));
}
return false;
}
triggerInlineCompletion() {
var _a;
(_a = this.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.trigger();
}
commitInlineCompletion() {
var _a;
(_a = this.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.commitCurrentSuggestion();
}
hideInlineCompletion() {
var _a;
(_a = this.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.hide();
}
showNextInlineCompletion() {
var _a;
(_a = this.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.showNext();
}
showPreviousInlineCompletion() {
var _a;
(_a = this.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.showPrevious();
}
hasMultipleInlineCompletions() {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const result = yield ((_a = this.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.hasMultipleInlineCompletions());
return result !== undefined ? result : false;
});
}
};
GhostTextModel = __decorate([
__param(1, commands_1.ICommandService)
], GhostTextModel);
exports.GhostTextModel = GhostTextModel;
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/inlineCompletions/ghostTextController*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,25/*vs/editor/common/editorContextKeys*/,616/*vs/editor/contrib/inlineCompletions/ghostTextWidget*/,503/*vs/nls!vs/editor/contrib/inlineCompletions/ghostTextController*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/,695/*vs/editor/contrib/inlineCompletions/ghostTextModel*/]), function (require, exports, lifecycle_1, editorExtensions_1, editorContextKeys_1, ghostTextWidget_1, nls, contextkey_1, instantiation_1, ghostTextModel_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TriggerInlineSuggestionAction = exports.ShowPreviousInlineSuggestionAction = exports.ShowNextInlineSuggestionAction = exports.commitInlineSuggestionAction = exports.ActiveGhostTextController = exports.GhostTextController = void 0;
let GhostTextController = class GhostTextController extends lifecycle_1.Disposable {
constructor(editor, instantiationService) {
super();
this.editor = editor;
this.instantiationService = instantiationService;
this.triggeredExplicitly = false;
this.activeController = this._register(new lifecycle_1.MutableDisposable());
this._register(this.editor.onDidChangeModel(() => {
this.updateModelController();
}));
this._register(this.editor.onDidChangeConfiguration((e) => {
if (e.hasChanged(105 /* suggest */)) {
this.updateModelController();
}
if (e.hasChanged(53 /* inlineSuggest */)) {
this.updateModelController();
}
}));
this.updateModelController();
}
static get(editor) {
return editor.getContribution(GhostTextController.ID);
}
get activeModel() {
var _a;
return (_a = this.activeController.value) === null || _a === void 0 ? void 0 : _a.model;
}
// Don't call this method when not neccessary. It will recreate the activeController.
updateModelController() {
const suggestOptions = this.editor.getOption(105 /* suggest */);
const inlineSuggestOptions = this.editor.getOption(53 /* inlineSuggest */);
this.activeController.value = undefined;
// ActiveGhostTextController is only created if one of those settings is set or if the inline completions are triggered explicitly.
this.activeController.value =
this.editor.hasModel() && (suggestOptions.preview || inlineSuggestOptions.enabled || this.triggeredExplicitly)
? this.instantiationService.createInstance(ActiveGhostTextController, this.editor)
: undefined;
}
shouldShowHoverAt(hoverRange) {
var _a;
return ((_a = this.activeModel) === null || _a === void 0 ? void 0 : _a.shouldShowHoverAt(hoverRange)) || false;
}
shouldShowHoverAtViewZone(viewZoneId) {
var _a, _b;
return ((_b = (_a = this.activeController.value) === null || _a === void 0 ? void 0 : _a.widget) === null || _b === void 0 ? void 0 : _b.shouldShowHoverAtViewZone(viewZoneId)) || false;
}
trigger() {
var _a;
this.triggeredExplicitly = true;
if (!this.activeController.value) {
this.updateModelController();
}
(_a = this.activeModel) === null || _a === void 0 ? void 0 : _a.triggerInlineCompletion();
}
commit() {
var _a;
(_a = this.activeModel) === null || _a === void 0 ? void 0 : _a.commitInlineCompletion();
}
hide() {
var _a;
(_a = this.activeModel) === null || _a === void 0 ? void 0 : _a.hideInlineCompletion();
}
showNextInlineCompletion() {
var _a;
(_a = this.activeModel) === null || _a === void 0 ? void 0 : _a.showNextInlineCompletion();
}
showPreviousInlineCompletion() {
var _a;
(_a = this.activeModel) === null || _a === void 0 ? void 0 : _a.showPreviousInlineCompletion();
}
hasMultipleInlineCompletions() {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const result = yield ((_a = this.activeModel) === null || _a === void 0 ? void 0 : _a.hasMultipleInlineCompletions());
return result !== undefined ? result : false;
});
}
};
GhostTextController.inlineSuggestionVisible = new contextkey_1.RawContextKey('inlineSuggestionVisible', false, nls.localize(0, null));
GhostTextController.inlineSuggestionHasIndentation = new contextkey_1.RawContextKey('inlineSuggestionHasIndentation', false, nls.localize(1, null));
GhostTextController.ID = 'editor.contrib.ghostTextController';
GhostTextController = __decorate([
__param(1, instantiation_1.IInstantiationService)
], GhostTextController);
exports.GhostTextController = GhostTextController;
class GhostTextContextKeys {
constructor(contextKeyService) {
this.contextKeyService = contextKeyService;
this.inlineCompletionVisible = GhostTextController.inlineSuggestionVisible.bindTo(this.contextKeyService);
this.inlineCompletionSuggestsIndentation = GhostTextController.inlineSuggestionHasIndentation.bindTo(this.contextKeyService);
}
}
/**
* The controller for a text editor with an initialized text model.
* Must be disposed as soon as the model detaches from the editor.
*/
let ActiveGhostTextController = class ActiveGhostTextController extends lifecycle_1.Disposable {
constructor(editor, instantiationService, contextKeyService) {
super();
this.editor = editor;
this.instantiationService = instantiationService;
this.contextKeyService = contextKeyService;
this.contextKeys = new GhostTextContextKeys(this.contextKeyService);
this.model = this._register(this.instantiationService.createInstance(ghostTextModel_1.GhostTextModel, this.editor));
this.widget = this._register(this.instantiationService.createInstance(ghostTextWidget_1.GhostTextWidget, this.editor, this.model));
this._register((0, lifecycle_1.toDisposable)(() => {
this.contextKeys.inlineCompletionVisible.set(false);
this.contextKeys.inlineCompletionSuggestsIndentation.set(false);
}));
this._register(this.model.onDidChange(() => {
this.updateContextKeys();
}));
this.updateContextKeys();
}
updateContextKeys() {
var _a;
this.contextKeys.inlineCompletionVisible.set(((_a = this.model.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.ghostText) !== undefined);
const ghostText = this.model.inlineCompletionsModel.ghostText;
if (ghostText && ghostText.parts.length > 0) {
const { column, lines } = ghostText.parts[0];
const suggestionStartsWithWs = lines[0].startsWith(' ') || lines[0].startsWith('\t');
const indentationEndColumn = this.editor.getModel().getLineIndentColumn(ghostText.lineNumber);
const inIndentation = column <= indentationEndColumn;
this.contextKeys.inlineCompletionSuggestsIndentation.set(!!this.model.activeInlineCompletionsModel
&& suggestionStartsWithWs && inIndentation);
}
else {
this.contextKeys.inlineCompletionSuggestsIndentation.set(false);
}
}
};
ActiveGhostTextController = __decorate([
__param(1, instantiation_1.IInstantiationService),
__param(2, contextkey_1.IContextKeyService)
], ActiveGhostTextController);
exports.ActiveGhostTextController = ActiveGhostTextController;
const GhostTextCommand = editorExtensions_1.EditorCommand.bindToContribution(GhostTextController.get);
exports.commitInlineSuggestionAction = new GhostTextCommand({
id: 'editor.action.inlineSuggest.commit',
precondition: contextkey_1.ContextKeyExpr.and(GhostTextController.inlineSuggestionVisible, GhostTextController.inlineSuggestionHasIndentation.toNegated(), editorContextKeys_1.EditorContextKeys.tabMovesFocus.toNegated()),
kbOpts: {
weight: 200,
primary: 2 /* Tab */,
},
handler(x) {
x.commit();
x.editor.focus();
}
});
(0, editorExtensions_1.registerEditorCommand)(exports.commitInlineSuggestionAction);
(0, editorExtensions_1.registerEditorCommand)(new GhostTextCommand({
id: 'editor.action.inlineSuggest.hide',
precondition: GhostTextController.inlineSuggestionVisible,
kbOpts: {
weight: 100,
primary: 9 /* Escape */,
},
handler(x) {
x.hide();
}
}));
class ShowNextInlineSuggestionAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: ShowNextInlineSuggestionAction.ID,
label: nls.localize(2, null),
alias: 'Show Next Inline Suggestion',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, GhostTextController.inlineSuggestionVisible),
kbOpts: {
weight: 100,
primary: 512 /* Alt */ | 89 /* US_CLOSE_SQUARE_BRACKET */,
},
});
}
run(accessor, editor) {
return __awaiter(this, void 0, void 0, function* () {
const controller = GhostTextController.get(editor);
if (controller) {
controller.showNextInlineCompletion();
editor.focus();
}
});
}
}
exports.ShowNextInlineSuggestionAction = ShowNextInlineSuggestionAction;
ShowNextInlineSuggestionAction.ID = 'editor.action.inlineSuggest.showNext';
class ShowPreviousInlineSuggestionAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: ShowPreviousInlineSuggestionAction.ID,
label: nls.localize(3, null),
alias: 'Show Previous Inline Suggestion',
precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, GhostTextController.inlineSuggestionVisible),
kbOpts: {
weight: 100,
primary: 512 /* Alt */ | 87 /* US_OPEN_SQUARE_BRACKET */,
},
});
}
run(accessor, editor) {
return __awaiter(this, void 0, void 0, function* () {
const controller = GhostTextController.get(editor);
if (controller) {
controller.showPreviousInlineCompletion();
editor.focus();
}
});
}
}
exports.ShowPreviousInlineSuggestionAction = ShowPreviousInlineSuggestionAction;
ShowPreviousInlineSuggestionAction.ID = 'editor.action.inlineSuggest.showPrevious';
class TriggerInlineSuggestionAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.inlineSuggest.trigger',
label: nls.localize(4, null),
alias: 'Trigger Inline Suggestion',
precondition: editorContextKeys_1.EditorContextKeys.writable
});
}
run(accessor, editor) {
return __awaiter(this, void 0, void 0, function* () {
const controller = GhostTextController.get(editor);
if (controller) {
controller.trigger();
}
});
}
}
exports.TriggerInlineSuggestionAction = TriggerInlineSuggestionAction;
(0, editorExtensions_1.registerEditorContribution)(GhostTextController.ID, GhostTextController);
(0, editorExtensions_1.registerEditorAction)(TriggerInlineSuggestionAction);
(0, editorExtensions_1.registerEditorAction)(ShowNextInlineSuggestionAction);
(0, editorExtensions_1.registerEditorAction)(ShowPreviousInlineSuggestionAction);
});
/*---------------------------------------------------------------------------------------------
* 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/editor/contrib/inlineCompletions/inlineCompletionsHoverParticipant*/], __M([0/*require*/,1/*exports*/,504/*vs/nls!vs/editor/contrib/inlineCompletions/inlineCompletionsHoverParticipant*/,231/*vs/editor/contrib/hover/hoverTypes*/,3/*vs/editor/common/core/range*/,2/*vs/base/common/lifecycle*/,281/*vs/editor/contrib/inlineCompletions/ghostTextController*/,26/*vs/platform/commands/common/commands*/,33/*vs/platform/actions/common/actions*/,16/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, nls, hoverTypes_1, range_1, lifecycle_1, ghostTextController_1, commands_1, actions_1, contextkey_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 /* Range */
&& this.range.startColumn <= anchor.range.startColumn
&& this.range.endColumn >= anchor.range.endColumn);
}
hasMultipleSuggestions() {
return this.controller.hasMultipleInlineCompletions();
}
}
exports.InlineCompletionsHover = InlineCompletionsHover;
let InlineCompletionsHoverParticipant = class InlineCompletionsHoverParticipant {
constructor(_editor, hover, _commandService, _menuService, _contextKeyService) {
this._editor = _editor;
this._commandService = _commandService;
this._menuService = _menuService;
this._contextKeyService = _contextKeyService;
}
suggestHoverAnchor(mouseEvent) {
const controller = ghostTextController_1.GhostTextController.get(this._editor);
if (!controller) {
return null;
}
if (mouseEvent.target.type === 8 /* CONTENT_VIEW_ZONE */) {
// handle the case where the mouse is over the view zone
const viewZoneData = mouseEvent.target.detail;
if (controller.shouldShowHoverAtViewZone(viewZoneData.viewZoneId)) {
return new hoverTypes_1.HoverForeignElementAnchor(1000, this, range_1.Range.fromPositions(viewZoneData.positionBefore || viewZoneData.position, viewZoneData.positionBefore || viewZoneData.position));
}
}
if (mouseEvent.target.type === 7 /* CONTENT_EMPTY */ && mouseEvent.target.range) {
// handle the case where the mouse is over the empty portion of a line following ghost text
if (controller.shouldShowHoverAt(mouseEvent.target.range)) {
return new hoverTypes_1.HoverForeignElementAnchor(1000, this, mouseEvent.target.range);
}
}
if (mouseEvent.target.type === 6 /* CONTENT_TEXT */ && mouseEvent.target.range && mouseEvent.target.detail) {
// handle the case where the mouse is directly over ghost text
const mightBeForeignElement = mouseEvent.target.detail.mightBeForeignElement;
if (mightBeForeignElement && controller.shouldShowHoverAt(mouseEvent.target.range)) {
return new hoverTypes_1.HoverForeignElementAnchor(1000, this, mouseEvent.target.range);
}
}
return null;
}
computeSync(anchor, lineDecorations) {
const controller = ghostTextController_1.GhostTextController.get(this._editor);
if (controller && controller.shouldShowHoverAt(anchor.range)) {
return [new InlineCompletionsHover(this, anchor.range, controller)];
}
return [];
}
renderHoverParts(hoverParts, fragment, statusBar) {
const disposableStore = new lifecycle_1.DisposableStore();
const menu = disposableStore.add(this._menuService.createMenu(actions_1.MenuId.InlineCompletionsActions, this._contextKeyService));
const previousAction = statusBar.addAction({
label: nls.localize(0, null),
commandId: ghostTextController_1.ShowNextInlineSuggestionAction.ID,
run: () => this._commandService.executeCommand(ghostTextController_1.ShowNextInlineSuggestionAction.ID)
});
const nextAction = statusBar.addAction({
label: nls.localize(1, null),
commandId: ghostTextController_1.ShowPreviousInlineSuggestionAction.ID,
run: () => this._commandService.executeCommand(ghostTextController_1.ShowPreviousInlineSuggestionAction.ID)
});
statusBar.addAction({
label: nls.localize(2, null),
commandId: ghostTextController_1.commitInlineSuggestionAction.id,
run: () => this._commandService.executeCommand(ghostTextController_1.commitInlineSuggestionAction.id)
});
const actions = [previousAction, nextAction];
for (const action of actions) {
action.setEnabled(false);
}
hoverParts[0].hasMultipleSuggestions().then(hasMore => {
for (const action of actions) {
action.setEnabled(hasMore);
}
});
for (const [_, group] of menu.getActions()) {
for (const action of group) {
if (action instanceof actions_1.MenuItemAction) {
statusBar.addAction({
label: action.label,
commandId: action.item.id,
run: () => this._commandService.executeCommand(action.item.id)
});
}
}
}
return disposableStore;
}
};
InlineCompletionsHoverParticipant = __decorate([
__param(2, commands_1.ICommandService),
__param(3, actions_1.IMenuService),
__param(4, contextkey_1.IContextKeyService)
], InlineCompletionsHoverParticipant);
exports.InlineCompletionsHoverParticipant = 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[697/*vs/editor/contrib/hover/modesContentHover*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,31/*vs/editor/common/model/textModel*/,18/*vs/editor/common/modes*/,230/*vs/editor/contrib/hover/hoverOperation*/,19/*vs/base/common/arrays*/,52/*vs/base/browser/ui/widget*/,319/*vs/base/browser/ui/hover/hoverWidget*/,675/*vs/editor/contrib/hover/markerHoverParticipant*/,9/*vs/platform/instantiation/common/instantiation*/,642/*vs/editor/contrib/hover/markdownHoverParticipant*/,696/*vs/editor/contrib/inlineCompletions/inlineCompletionsHoverParticipant*/,640/*vs/editor/contrib/hover/colorHoverParticipant*/,37/*vs/platform/keybinding/common/keybinding*/,231/*vs/editor/contrib/hover/hoverTypes*/]), function (require, exports, dom, lifecycle_1, position_1, range_1, textModel_1, modes_1, hoverOperation_1, arrays_1, widget_1, hoverWidget_1, markerHoverParticipant_1, instantiation_1, markdownHoverParticipant_1, inlineCompletionsHoverParticipant_1, colorHoverParticipant_1, keybinding_1, hoverTypes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModesContentHoverWidget = void 0;
const $ = dom.$;
let EditorHoverStatusBar = class EditorHoverStatusBar extends lifecycle_1.Disposable {
constructor(_keybindingService) {
super();
this._keybindingService = _keybindingService;
this._hasContent = false;
this.hoverElement = $('div.hover-row.status-bar');
this.actionsElement = dom.append(this.hoverElement, $('div.actions'));
}
get hasContent() {
return this._hasContent;
}
addAction(actionOptions) {
const keybinding = this._keybindingService.lookupKeybinding(actionOptions.commandId);
const keybindingLabel = keybinding ? keybinding.getLabel() : null;
this._hasContent = true;
return this._register(hoverWidget_1.HoverAction.render(this.actionsElement, actionOptions, keybindingLabel));
}
append(element) {
const result = dom.append(this.actionsElement, element);
this._hasContent = true;
return result;
}
};
EditorHoverStatusBar = __decorate([
__param(0, keybinding_1.IKeybindingService)
], EditorHoverStatusBar);
class ModesContentComputer {
constructor(editor, _participants) {
this._participants = _participants;
this._editor = editor;
this._result = [];
this._anchor = null;
}
setAnchor(anchor) {
this._anchor = anchor;
this._result = [];
}
clearResult() {
this._result = [];
}
static _getLineDecorations(editor, anchor) {
if (anchor.type !== 1 /* Range */) {
return [];
}
const model = editor.getModel();
const lineNumber = anchor.range.startLineNumber;
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 (startColumn > anchor.range.startColumn || anchor.range.endColumn > endColumn) {
return false;
}
return true;
});
}
computeAsync(token) {
return __awaiter(this, void 0, void 0, function* () {
const anchor = this._anchor;
if (!this._editor.hasModel() || !anchor) {
return Promise.resolve([]);
}
const lineDecorations = ModesContentComputer._getLineDecorations(this._editor, anchor);
const allResults = yield Promise.all(this._participants.map(p => this._computeAsync(p, lineDecorations, anchor, token)));
return (0, arrays_1.flatten)(allResults);
});
}
_computeAsync(participant, lineDecorations, anchor, token) {
return __awaiter(this, void 0, void 0, function* () {
if (!participant.computeAsync) {
return [];
}
return participant.computeAsync(anchor, lineDecorations, token);
});
}
computeSync() {
if (!this._editor.hasModel() || !this._anchor) {
return [];
}
const lineDecorations = ModesContentComputer._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);
}
onResult(result, isFromSynchronousComputation) {
// Always put synchronous messages before asynchronous ones
if (isFromSynchronousComputation) {
this._result = result.concat(this._result);
}
else {
this._result = this._result.concat(result);
}
}
getResult() {
return this._result.slice(0);
}
getResultWithLoadingMessage() {
if (this._anchor) {
for (const participant of this._participants) {
if (participant.createLoadingMessage) {
const loadingMessage = participant.createLoadingMessage(this._anchor);
if (loadingMessage) {
return this._result.slice(0).concat([loadingMessage]);
}
}
}
}
return this._result.slice(0);
}
}
let ModesContentHoverWidget = class ModesContentHoverWidget extends widget_1.Widget {
constructor(editor, _hoverVisibleKey, instantiationService, _keybindingService) {
super();
this._hoverVisibleKey = _hoverVisibleKey;
this._keybindingService = _keybindingService;
// IContentWidget.allowEditorOverflow
this.allowEditorOverflow = true;
this._participants = [
instantiationService.createInstance(colorHoverParticipant_1.ColorHoverParticipant, editor, this),
instantiationService.createInstance(markdownHoverParticipant_1.MarkdownHoverParticipant, editor, this),
instantiationService.createInstance(inlineCompletionsHoverParticipant_1.InlineCompletionsHoverParticipant, editor, this),
instantiationService.createInstance(markerHoverParticipant_1.MarkerHoverParticipant, editor, this),
];
this._hover = this._register(new hoverWidget_1.HoverWidget());
this._id = ModesContentHoverWidget.ID;
this._editor = editor;
this._isVisible = false;
this._stoleFocus = false;
this._renderDisposable = null;
this.onkeydown(this._hover.containerDomNode, (e) => {
if (e.equals(9 /* Escape */)) {
this.hide();
}
});
this._register(this._editor.onDidChangeConfiguration((e) => {
if (e.hasChanged(41 /* fontInfo */)) {
this._updateFont();
}
}));
this._editor.onDidLayoutChange(() => this.layout());
this.layout();
this._editor.addContentWidget(this);
this._showAtPosition = null;
this._showAtRange = null;
this._stoleFocus = false;
this._messages = [];
this._lastAnchor = null;
this._computer = new ModesContentComputer(this._editor, this._participants);
this._highlightDecorations = [];
this._isChangingDecorations = false;
this._shouldFocus = false;
this._colorPicker = null;
this._hoverOperation = new hoverOperation_1.HoverOperation(this._computer, result => this._withResult(result, true), null, result => this._withResult(result, false), this._editor.getOption(51 /* hover */).delay);
this._register(dom.addStandardDisposableListener(this.getDomNode(), dom.EventType.FOCUS, () => {
if (this._colorPicker) {
this.getDomNode().classList.add('colorpicker-hover');
}
}));
this._register(dom.addStandardDisposableListener(this.getDomNode(), dom.EventType.BLUR, () => {
this.getDomNode().classList.remove('colorpicker-hover');
}));
this._register(editor.onDidChangeConfiguration(() => {
this._hoverOperation.setHoverTime(this._editor.getOption(51 /* hover */).delay);
}));
this._register(modes_1.TokenizationRegistry.onDidChange(() => {
if (this._isVisible && this._lastAnchor && this._messages.length > 0) {
this._hover.contentsDomNode.textContent = '';
this._renderMessages(this._lastAnchor, this._messages);
}
}));
}
dispose() {
this._hoverOperation.cancel();
this._editor.removeContentWidget(this);
super.dispose();
}
getId() {
return this._id;
}
getDomNode() {
return this._hover.containerDomNode;
}
_shouldShowAt(mouseEvent) {
const targetType = mouseEvent.target.type;
if (targetType === 6 /* CONTENT_TEXT */) {
return true;
}
if (targetType === 7 /* CONTENT_EMPTY */) {
const epsilon = this._editor.getOption(41 /* fontInfo */).typicalHalfwidthCharacterWidth / 2;
const data = mouseEvent.target.detail;
if (data && !data.isAfterLines && typeof data.horizontalDistanceToText === 'number' && data.horizontalDistanceToText < epsilon) {
// Let hover kick in even when the mouse is technically in the empty area after a line, given the distance is small enough
return true;
}
}
return false;
}
maybeShowAt(mouseEvent) {
var _a;
const anchorCandidates = [];
for (const participant of this._participants) {
if (typeof participant.suggestHoverAnchor === 'function') {
const anchor = participant.suggestHoverAnchor(mouseEvent);
if (anchor) {
anchorCandidates.push(anchor);
}
}
}
if (this._shouldShowAt(mouseEvent) && mouseEvent.target.range) {
// TODO@rebornix. This should be removed if we move Color Picker out of Hover component.
// Check if mouse is hovering on color decorator
const hoverOnColorDecorator = [...((_a = mouseEvent.target.element) === null || _a === void 0 ? void 0 : _a.classList.values()) || []].find(className => className.startsWith('ced-colorBox'))
&& mouseEvent.target.range.endColumn - mouseEvent.target.range.startColumn === 1;
const showAtRange = (hoverOnColorDecorator // shift the mouse focus by one as color decorator is a `before` decoration of next character.
? new range_1.Range(mouseEvent.target.range.startLineNumber, mouseEvent.target.range.startColumn + 1, mouseEvent.target.range.endLineNumber, mouseEvent.target.range.endColumn + 1)
: mouseEvent.target.range);
anchorCandidates.push(new hoverTypes_1.HoverRangeAnchor(0, showAtRange));
}
if (anchorCandidates.length === 0) {
return false;
}
anchorCandidates.sort((a, b) => b.priority - a.priority);
this._startShowingAt(anchorCandidates[0], 0 /* Delayed */, false);
return true;
}
_showAt(position, range, focus) {
// Position has changed
this._showAtPosition = position;
this._showAtRange = range;
this._hoverVisibleKey.set(true);
this._isVisible = true;
this._hover.containerDomNode.classList.toggle('hidden', !this._isVisible);
this._editor.layoutContentWidget(this);
// Simply force a synchronous render on the editor
// such that the widget does not really render with left = '0px'
this._editor.render();
this._stoleFocus = focus;
if (focus) {
this._hover.containerDomNode.focus();
}
}
getPosition() {
if (this._isVisible) {
return {
position: this._showAtPosition,
range: this._showAtRange,
preference: [
1 /* ABOVE */,
2 /* BELOW */
]
};
}
return null;
}
_updateFont() {
const codeClasses = Array.prototype.slice.call(this._hover.contentsDomNode.getElementsByClassName('code'));
codeClasses.forEach(node => this._editor.applyFontInfo(node));
}
_updateContents(node) {
this._hover.contentsDomNode.textContent = '';
this._hover.contentsDomNode.appendChild(node);
this._updateFont();
this._editor.layoutContentWidget(this);
this._hover.onContentsChanged();
}
layout() {
const height = Math.max(this._editor.getLayoutInfo().height / 4, 250);
const { fontSize, lineHeight } = this._editor.getOption(41 /* fontInfo */);
this._hover.contentsDomNode.style.fontSize = `${fontSize}px`;
this._hover.contentsDomNode.style.lineHeight = `${lineHeight}px`;
this._hover.contentsDomNode.style.maxHeight = `${height}px`;
this._hover.contentsDomNode.style.maxWidth = `${Math.max(this._editor.getLayoutInfo().width * 0.66, 500)}px`;
}
onModelDecorationsChanged() {
if (this._isChangingDecorations) {
return;
}
if (this._isVisible) {
// The decorations have changed and the hover is visible,
// we need to recompute the displayed text
this._hoverOperation.cancel();
this._computer.clearResult();
if (!this._colorPicker) { // TODO@Michel ensure that displayed text for other decorations is computed even if color picker is in place
this._hoverOperation.start(0 /* Delayed */);
}
}
}
startShowingAtRange(range, mode, focus) {
this._startShowingAt(new hoverTypes_1.HoverRangeAnchor(0, range), mode, focus);
}
_startShowingAt(anchor, mode, focus) {
if (this._lastAnchor && this._lastAnchor.equals(anchor)) {
// We have to show the widget at the exact same range as before, so no work is needed
return;
}
this._hoverOperation.cancel();
if (this._isVisible) {
// The range might have changed, but the hover is visible
// Instead of hiding it completely, filter out messages that are still in the new range and
// kick off a new computation
if (!this._showAtPosition || !this._lastAnchor || !anchor.canAdoptVisibleHover(this._lastAnchor, this._showAtPosition)) {
this.hide();
}
else {
const filteredMessages = this._messages.filter((m) => m.isValidForHoverAnchor(anchor));
if (filteredMessages.length === 0) {
this.hide();
}
else if (filteredMessages.length === this._messages.length) {
// no change
return;
}
else {
this._renderMessages(anchor, filteredMessages);
}
}
}
this._lastAnchor = anchor;
this._computer.setAnchor(anchor);
this._shouldFocus = focus;
this._hoverOperation.start(mode);
}
hide() {
this._lastAnchor = null;
this._hoverOperation.cancel();
if (this._isVisible) {
setTimeout(() => {
// Give commands a chance to see the key
if (!this._isVisible) {
this._hoverVisibleKey.set(false);
}
}, 0);
this._isVisible = false;
this._hover.containerDomNode.classList.toggle('hidden', !this._isVisible);
this._editor.layoutContentWidget(this);
if (this._stoleFocus) {
this._editor.focus();
}
}
this._isChangingDecorations = true;
this._highlightDecorations = this._editor.deltaDecorations(this._highlightDecorations, []);
this._isChangingDecorations = false;
if (this._renderDisposable) {
this._renderDisposable.dispose();
this._renderDisposable = null;
}
this._colorPicker = null;
}
isColorPickerVisible() {
return !!this._colorPicker;
}
setColorPicker(widget) {
this._colorPicker = widget;
}
onContentsChanged() {
this._hover.onContentsChanged();
}
_withResult(result, complete) {
this._messages = result;
if (this._lastAnchor && this._messages.length > 0) {
this._renderMessages(this._lastAnchor, this._messages);
}
else if (complete) {
this.hide();
}
}
_renderMessages(anchor, messages) {
if (this._renderDisposable) {
this._renderDisposable.dispose();
this._renderDisposable = null;
}
this._colorPicker = null; // TODO: TypeScript thinks this is always null
// update column from which to show
let renderColumn = 1073741824 /* MAX_SAFE_SMALL_INTEGER */;
let highlightRange = messages[0].range;
let forceShowAtRange = null;
let fragment = document.createDocumentFragment();
const disposables = new lifecycle_1.DisposableStore();
const hoverParts = new Map();
for (const msg of messages) {
renderColumn = Math.min(renderColumn, msg.range.startColumn);
highlightRange = range_1.Range.plusRange(highlightRange, msg.range);
if (msg.forceShowAtRange) {
forceShowAtRange = msg.range;
}
if (!hoverParts.has(msg.owner)) {
hoverParts.set(msg.owner, []);
}
const dest = hoverParts.get(msg.owner);
dest.push(msg);
}
const statusBar = disposables.add(new EditorHoverStatusBar(this._keybindingService));
for (const [participant, participantHoverParts] of hoverParts) {
disposables.add(participant.renderHoverParts(participantHoverParts, fragment, statusBar));
}
if (statusBar.hasContent) {
fragment.appendChild(statusBar.hoverElement);
}
this._renderDisposable = disposables;
// show
if (fragment.hasChildNodes()) {
if (forceShowAtRange) {
this._showAt(forceShowAtRange.getStartPosition(), forceShowAtRange, this._shouldFocus);
}
else {
this._showAt(new position_1.Position(anchor.range.startLineNumber, renderColumn), highlightRange, this._shouldFocus);
}
this._updateContents(fragment);
}
if (this._colorPicker) {
this._colorPicker.layout();
}
this._isChangingDecorations = true;
this._highlightDecorations = this._editor.deltaDecorations(this._highlightDecorations, highlightRange ? [{
range: highlightRange,
options: ModesContentHoverWidget._DECORATION_OPTIONS
}] : []);
this._isChangingDecorations = false;
}
};
ModesContentHoverWidget.ID = 'editor.contrib.modesContentHoverWidget';
ModesContentHoverWidget._DECORATION_OPTIONS = textModel_1.ModelDecorationOptions.register({
description: 'content-hover-highlight',
className: 'hoverHighlight'
});
ModesContentHoverWidget = __decorate([
__param(2, instantiation_1.IInstantiationService),
__param(3, keybinding_1.IKeybindingService)
], ModesContentHoverWidget);
exports.ModesContentHoverWidget = ModesContentHoverWidget;
});
/*---------------------------------------------------------------------------------------------
* 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/contrib/hover/hover*/], __M([0/*require*/,1/*exports*/,498/*vs/nls!vs/editor/contrib/hover/hover*/,41/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,25/*vs/editor/common/editorContextKeys*/,57/*vs/editor/common/services/modeService*/,697/*vs/editor/contrib/hover/modesContentHover*/,574/*vs/editor/contrib/hover/modesGlyphHover*/,58/*vs/platform/opener/common/opener*/,22/*vs/platform/theme/common/colorRegistry*/,11/*vs/platform/theme/common/themeService*/,277/*vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, nls, keyCodes_1, lifecycle_1, editorExtensions_1, range_1, editorContextKeys_1, modeService_1, modesContentHover_1, modesGlyphHover_1, opener_1, colorRegistry_1, themeService_1, goToDefinitionAtPosition_1, contextkey_1, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModesHoverController = void 0;
let ModesHoverController = class ModesHoverController {
constructor(_editor, _instantiationService, _openerService, _modeService, _contextKeyService) {
this._editor = _editor;
this._instantiationService = _instantiationService;
this._openerService = _openerService;
this._modeService = _modeService;
this._toUnhook = new lifecycle_1.DisposableStore();
this._isMouseDown = false;
this._hoverClicked = false;
this._contentWidget = null;
this._glyphWidget = null;
this._hookEvents();
this._didChangeConfigurationHandler = this._editor.onDidChangeConfiguration((e) => {
if (e.hasChanged(51 /* hover */)) {
this._unhookEvents();
this._hookEvents();
}
});
this._hoverVisibleKey = editorContextKeys_1.EditorContextKeys.hoverVisible.bindTo(_contextKeyService);
}
static get(editor) {
return editor.getContribution(ModesHoverController.ID);
}
_hookEvents() {
const hideWidgetsEventHandler = () => this._hideWidgets();
const hoverOpts = this._editor.getOption(51 /* hover */);
this._isHoverEnabled = hoverOpts.enabled;
this._isHoverSticky = hoverOpts.sticky;
if (this._isHoverEnabled) {
this._toUnhook.add(this._editor.onMouseDown((e) => this._onEditorMouseDown(e)));
this._toUnhook.add(this._editor.onMouseUp((e) => this._onEditorMouseUp(e)));
this._toUnhook.add(this._editor.onMouseMove((e) => this._onEditorMouseMove(e)));
this._toUnhook.add(this._editor.onKeyDown((e) => this._onKeyDown(e)));
this._toUnhook.add(this._editor.onDidChangeModelDecorations(() => this._onModelDecorationsChanged()));
}
else {
this._toUnhook.add(this._editor.onMouseMove((e) => this._onEditorMouseMove(e)));
this._toUnhook.add(this._editor.onKeyDown((e) => this._onKeyDown(e)));
}
this._toUnhook.add(this._editor.onMouseLeave(hideWidgetsEventHandler));
this._toUnhook.add(this._editor.onDidChangeModel(hideWidgetsEventHandler));
this._toUnhook.add(this._editor.onDidScrollChange((e) => this._onEditorScrollChanged(e)));
}
_unhookEvents() {
this._toUnhook.clear();
}
_onModelDecorationsChanged() {
var _a, _b;
(_a = this._contentWidget) === null || _a === void 0 ? void 0 : _a.onModelDecorationsChanged();
(_b = this._glyphWidget) === null || _b === void 0 ? void 0 : _b.onModelDecorationsChanged();
}
_onEditorScrollChanged(e) {
if (e.scrollTopChanged || e.scrollLeftChanged) {
this._hideWidgets();
}
}
_onEditorMouseDown(mouseEvent) {
this._isMouseDown = true;
const targetType = mouseEvent.target.type;
if (targetType === 9 /* CONTENT_WIDGET */ && mouseEvent.target.detail === modesContentHover_1.ModesContentHoverWidget.ID) {
this._hoverClicked = true;
// mouse down on top of content hover widget
return;
}
if (targetType === 12 /* OVERLAY_WIDGET */ && mouseEvent.target.detail === modesGlyphHover_1.ModesGlyphHoverWidget.ID) {
// mouse down on top of overlay hover widget
return;
}
if (targetType !== 12 /* OVERLAY_WIDGET */ && mouseEvent.target.detail !== modesGlyphHover_1.ModesGlyphHoverWidget.ID) {
this._hoverClicked = false;
}
this._hideWidgets();
}
_onEditorMouseUp(mouseEvent) {
this._isMouseDown = false;
}
_onEditorMouseMove(mouseEvent) {
var _a, _b, _c, _d, _e;
let targetType = mouseEvent.target.type;
if (this._isMouseDown && this._hoverClicked) {
return;
}
if (this._isHoverSticky && targetType === 9 /* CONTENT_WIDGET */ && mouseEvent.target.detail === modesContentHover_1.ModesContentHoverWidget.ID) {
// mouse moved on top of content hover widget
return;
}
if (this._isHoverSticky && !((_b = (_a = mouseEvent.event.browserEvent.view) === null || _a === void 0 ? void 0 : _a.getSelection()) === null || _b === void 0 ? void 0 : _b.isCollapsed)) {
// selected text within content hover widget
return;
}
if (!this._isHoverSticky && targetType === 9 /* CONTENT_WIDGET */ && mouseEvent.target.detail === modesContentHover_1.ModesContentHoverWidget.ID
&& ((_c = this._contentWidget) === null || _c === void 0 ? void 0 : _c.isColorPickerVisible())) {
// though the hover is not sticky, the color picker needs to.
return;
}
if (this._isHoverSticky && targetType === 12 /* OVERLAY_WIDGET */ && mouseEvent.target.detail === modesGlyphHover_1.ModesGlyphHoverWidget.ID) {
// mouse moved on top of overlay hover widget
return;
}
if (!this._isHoverEnabled) {
this._hideWidgets();
return;
}
const contentWidget = this._getOrCreateContentWidget();
if (contentWidget.maybeShowAt(mouseEvent)) {
(_d = this._glyphWidget) === null || _d === void 0 ? void 0 : _d.hide();
return;
}
if (targetType === 2 /* GUTTER_GLYPH_MARGIN */ && mouseEvent.target.position) {
(_e = this._contentWidget) === null || _e === void 0 ? void 0 : _e.hide();
if (!this._glyphWidget) {
this._glyphWidget = new modesGlyphHover_1.ModesGlyphHoverWidget(this._editor, this._modeService, this._openerService);
}
this._glyphWidget.startShowingAt(mouseEvent.target.position.lineNumber);
return;
}
this._hideWidgets();
}
_onKeyDown(e) {
if (e.keyCode !== 5 /* Ctrl */ && e.keyCode !== 6 /* Alt */ && e.keyCode !== 57 /* Meta */ && e.keyCode !== 4 /* Shift */) {
// Do not hide hover when a modifier key is pressed
this._hideWidgets();
}
}
_hideWidgets() {
var _a, _b, _c;
if ((this._isMouseDown && this._hoverClicked && ((_a = this._contentWidget) === null || _a === void 0 ? void 0 : _a.isColorPickerVisible()))) {
return;
}
this._hoverClicked = false;
(_b = this._glyphWidget) === null || _b === void 0 ? void 0 : _b.hide();
(_c = this._contentWidget) === null || _c === void 0 ? void 0 : _c.hide();
}
_getOrCreateContentWidget() {
if (!this._contentWidget) {
this._contentWidget = this._instantiationService.createInstance(modesContentHover_1.ModesContentHoverWidget, this._editor, this._hoverVisibleKey);
}
return this._contentWidget;
}
isColorPickerVisible() {
var _a;
return ((_a = this._contentWidget) === null || _a === void 0 ? void 0 : _a.isColorPickerVisible()) || false;
}
showContentHover(range, mode, focus) {
this._getOrCreateContentWidget().startShowingAtRange(range, mode, focus);
}
dispose() {
var _a, _b;
this._unhookEvents();
this._toUnhook.dispose();
this._didChangeConfigurationHandler.dispose();
(_a = this._glyphWidget) === null || _a === void 0 ? void 0 : _a.dispose();
(_b = this._contentWidget) === null || _b === void 0 ? void 0 : _b.dispose();
}
};
ModesHoverController.ID = 'editor.contrib.hover';
ModesHoverController = __decorate([
__param(1, instantiation_1.IInstantiationService),
__param(2, opener_1.IOpenerService),
__param(3, modeService_1.IModeService),
__param(4, contextkey_1.IContextKeyService)
], ModesHoverController);
exports.ModesHoverController = ModesHoverController;
class ShowHoverAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.showHover',
label: nls.localize(0, null),
alias: 'Show Hover',
precondition: undefined,
kbOpts: {
kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
primary: (0, keyCodes_1.KeyChord)(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 39 /* KEY_I */),
weight: 100 /* EditorContrib */
}
});
}
run(accessor, editor) {
if (!editor.hasModel()) {
return;
}
let controller = ModesHoverController.get(editor);
if (!controller) {
return;
}
const position = editor.getPosition();
const range = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column);
const focus = editor.getOption(2 /* accessibilitySupport */) === 2 /* Enabled */;
controller.showContentHover(range, 1 /* Immediate */, focus);
}
}
class ShowDefinitionPreviewHoverAction extends editorExtensions_1.EditorAction {
constructor() {
super({
id: 'editor.action.showDefinitionPreviewHover',
label: nls.localize(1, null),
alias: 'Show Definition Preview Hover',
precondition: undefined
});
}
run(accessor, editor) {
let controller = ModesHoverController.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);
const promise = goto.startFindDefinitionFromCursor(position);
promise.then(() => {
controller.showContentHover(range, 1 /* Immediate */, true);
});
}
}
(0, editorExtensions_1.registerEditorContribution)(ModesHoverController.ID, ModesHoverController);
(0, editorExtensions_1.registerEditorAction)(ShowHoverAction);
(0, editorExtensions_1.registerEditorAction)(ShowDefinitionPreviewHoverAction);
// theming
(0, themeService_1.registerThemingParticipant)((theme, collector) => {
const editorHoverHighlightColor = theme.getColor(colorRegistry_1.editorHoverHighlight);
if (editorHoverHighlightColor) {
collector.addRule(`.monaco-editor .hoverHighlight { background-color: ${editorHoverHighlightColor}; }`);
}
const hoverBackground = theme.getColor(colorRegistry_1.editorHoverBackground);
if (hoverBackground) {
collector.addRule(`.monaco-editor .monaco-hover { background-color: ${hoverBackground}; }`);
}
const hoverBorder = theme.getColor(colorRegistry_1.editorHoverBorder);
if (hoverBorder) {
collector.addRule(`.monaco-editor .monaco-hover { border: 1px solid ${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)}; }`);
}
const link = theme.getColor(colorRegistry_1.textLinkForeground);
if (link) {
collector.addRule(`.monaco-editor .monaco-hover a { color: ${link}; }`);
}
const linkHover = theme.getColor(colorRegistry_1.textLinkActiveForeground);
if (linkHover) {
collector.addRule(`.monaco-editor .monaco-hover a:hover { color: ${linkHover}; }`);
}
const hoverForeground = theme.getColor(colorRegistry_1.editorHoverForeground);
if (hoverForeground) {
collector.addRule(`.monaco-editor .monaco-hover { color: ${hoverForeground}; }`);
}
const actionsBackground = theme.getColor(colorRegistry_1.editorHoverStatusBarBackground);
if (actionsBackground) {
collector.addRule(`.monaco-editor .monaco-hover .hover-row .actions { background-color: ${actionsBackground}; }`);
}
const codeBackground = theme.getColor(colorRegistry_1.textCodeBlockBackground);
if (codeBackground) {
collector.addRule(`.monaco-editor .monaco-hover code { background-color: ${codeBackground}; }`);
}
});
});
/*---------------------------------------------------------------------------------------------
* 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/colorPicker/colorContributions*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,14/*vs/editor/browser/editorExtensions*/,282/*vs/editor/contrib/hover/hover*/,3/*vs/editor/common/core/range*/,264/*vs/editor/contrib/colorPicker/colorDetector*/]), function (require, exports, lifecycle_1, editorExtensions_1, hover_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ColorContribution = void 0;
class ColorContribution extends lifecycle_1.Disposable {
constructor(_editor) {
super();
this._editor = _editor;
this._register(_editor.onMouseDown((e) => this.onMouseDown(e)));
}
dispose() {
super.dispose();
}
onMouseDown(mouseEvent) {
var _a;
const targetType = mouseEvent.target.type;
if (targetType !== 6 /* CONTENT_TEXT */) {
return;
}
const hoverOnColorDecorator = [...((_a = mouseEvent.target.element) === null || _a === void 0 ? void 0 : _a.classList.values()) || []].find(className => className.startsWith('ced-colorBox'));
if (!hoverOnColorDecorator) {
return;
}
if (!mouseEvent.target.range) {
return;
}
const hoverController = this._editor.getContribution(hover_1.ModesHoverController.ID);
if (!hoverController.isColorPickerVisible()) {
const range = new range_1.Range(mouseEvent.target.range.startLineNumber, mouseEvent.target.range.startColumn + 1, mouseEvent.target.range.endLineNumber, mouseEvent.target.range.endColumn + 1);
hoverController.showContentHover(range, 0 /* Delayed */, false);
}
}
}
exports.ColorContribution = ColorContribution;
ColorContribution.ID = 'editor.contrib.colorContribution'; // ms
(0, editorExtensions_1.registerEditorContribution)(ColorContribution.ID, ColorContribution);
});
/*---------------------------------------------------------------------------------------------
* 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/editor/editor.all*/], __M([0/*require*/,1/*exports*/,148/*vs/editor/browser/controller/coreCommands*/,149/*vs/editor/browser/widget/codeEditorWidget*/,271/*vs/editor/browser/widget/diffEditorWidget*/,217/*vs/editor/browser/widget/diffNavigator*/,625/*vs/editor/contrib/anchorSelect/anchorSelect*/,626/*vs/editor/contrib/bracketMatching/bracketMatching*/,627/*vs/editor/contrib/caretOperations/caretOperations*/,628/*vs/editor/contrib/caretOperations/transpose*/,629/*vs/editor/contrib/clipboard/clipboard*/,650/*vs/editor/contrib/codeAction/codeActionContributions*/,632/*vs/editor/contrib/codelens/codelensController*/,698/*vs/editor/contrib/colorPicker/colorContributions*/,633/*vs/editor/contrib/comment/comment*/,634/*vs/editor/contrib/contextmenu/contextmenu*/,635/*vs/editor/contrib/cursorUndo/cursorUndo*/,636/*vs/editor/contrib/dnd/dnd*/,272/*vs/editor/contrib/find/findController*/,674/*vs/editor/contrib/folding/folding*/,637/*vs/editor/contrib/fontZoom/fontZoom*/,638/*vs/editor/contrib/format/formatActions*/,559/*vs/editor/contrib/documentSymbols/documentSymbols*/,281/*vs/editor/contrib/inlineCompletions/ghostTextController*/,276/*vs/editor/contrib/gotoSymbol/goToCommands*/,277/*vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/,273/*vs/editor/contrib/gotoError/gotoError*/,282/*vs/editor/contrib/hover/hover*/,644/*vs/editor/contrib/indentation/indentation*/,645/*vs/editor/contrib/inlayHints/inlayHintsController*/,643/*vs/editor/contrib/inPlaceReplace/inPlaceReplace*/,646/*vs/editor/contrib/linesOperations/linesOperations*/,647/*vs/editor/contrib/linkedEditing/linkedEditing*/,648/*vs/editor/contrib/links/links*/,676/*vs/editor/contrib/multicursor/multicursor*/,678/*vs/editor/contrib/parameterHints/parameterHints*/,651/*vs/editor/contrib/rename/rename*/,652/*vs/editor/contrib/smartSelect/smartSelect*/,195/*vs/editor/contrib/snippet/snippetController2*/,280/*vs/editor/contrib/suggest/suggestController*/,653/*vs/editor/contrib/tokenization/tokenization*/,269/*vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/,654/*vs/editor/contrib/unusualLineTerminators/unusualLineTerminators*/,684/*vs/editor/contrib/viewportSemanticTokens/viewportSemanticTokens*/,655/*vs/editor/contrib/wordHighlighter/wordHighlighter*/,270/*vs/editor/contrib/wordOperations/wordOperations*/,656/*vs/editor/contrib/wordPartOperations/wordPartOperations*/,63/*vs/editor/common/standaloneStrings*/,130/*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.
*--------------------------------------------------------------------------------------------*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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[702/*vs/editor/editor.main*/], __M([0/*require*/,1/*exports*/,690/*vs/editor/editor.api*/,699/*vs/editor/editor.all*/,657/*vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/,658/*vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/,659/*vs/editor/standalone/browser/inspectTokens/inspectTokens*/,587/*vs/editor/standalone/browser/quickAccess/standaloneHelpQuickAccess*/,661/*vs/editor/standalone/browser/quickAccess/standaloneGotoLineQuickAccess*/,662/*vs/editor/standalone/browser/quickAccess/standaloneGotoSymbolQuickAccess*/,660/*vs/editor/standalone/browser/quickAccess/standaloneCommandsQuickAccess*/,685/*vs/editor/standalone/browser/referenceSearch/standaloneReferenceSearch*/,663/*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);
//
// **NOTE**: Do not edit directly! This file is generated using `npm run import-typescript`
//
define('vs/language/typescript/lib/typescriptServicesMetadata',["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.typescriptVersion = void 0;
exports.typescriptVersion = "4.3.2";
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/language/typescript/fillers/monaco-editor-core',['vs/editor/editor.api'], function () {
return self.monaco;
});
define('vs/language/typescript/monaco.contribution',["require", "exports", "./lib/typescriptServicesMetadata", "./fillers/monaco-editor-core"], function (require, exports, typescriptServicesMetadata_1, monaco_editor_core_1) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.getJavaScriptWorker = exports.getTypeScriptWorker = exports.javascriptDefaults = exports.typescriptDefaults = exports.typescriptVersion = exports.ModuleResolutionKind = exports.ScriptTarget = exports.NewLineKind = exports.JsxEmit = exports.ModuleKind = void 0;
//#region enums copied from typescript to prevent loading the entire typescriptServices ---
var ModuleKind;
(function (ModuleKind) {
ModuleKind[ModuleKind["None"] = 0] = "None";
ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS";
ModuleKind[ModuleKind["AMD"] = 2] = "AMD";
ModuleKind[ModuleKind["UMD"] = 3] = "UMD";
ModuleKind[ModuleKind["System"] = 4] = "System";
ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext";
})(ModuleKind = exports.ModuleKind || (exports.ModuleKind = {}));
var JsxEmit;
(function (JsxEmit) {
JsxEmit[JsxEmit["None"] = 0] = "None";
JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
JsxEmit[JsxEmit["React"] = 2] = "React";
JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
JsxEmit[JsxEmit["ReactJSX"] = 4] = "ReactJSX";
JsxEmit[JsxEmit["ReactJSXDev"] = 5] = "ReactJSXDev";
})(JsxEmit = exports.JsxEmit || (exports.JsxEmit = {}));
var NewLineKind;
(function (NewLineKind) {
NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
})(NewLineKind = exports.NewLineKind || (exports.NewLineKind = {}));
var ScriptTarget;
(function (ScriptTarget) {
ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020";
ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext";
ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest";
})(ScriptTarget = exports.ScriptTarget || (exports.ScriptTarget = {}));
var ModuleResolutionKind;
(function (ModuleResolutionKind) {
ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs";
})(ModuleResolutionKind = exports.ModuleResolutionKind || (exports.ModuleResolutionKind = {}));
// --- TypeScript configuration and defaults ---------
var LanguageServiceDefaultsImpl = /** @class */ (function () {
function LanguageServiceDefaultsImpl(compilerOptions, diagnosticsOptions, workerOptions) {
this._onDidChange = new monaco_editor_core_1.Emitter();
this._onDidExtraLibsChange = new monaco_editor_core_1.Emitter();
this._extraLibs = Object.create(null);
this._removedExtraLibs = Object.create(null);
this._eagerModelSync = false;
this.setCompilerOptions(compilerOptions);
this.setDiagnosticsOptions(diagnosticsOptions);
this.setWorkerOptions(workerOptions);
this._onDidExtraLibsChangeTimeout = -1;
}
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "onDidChange", {
get: function () {
return this._onDidChange.event;
},
enumerable: false,
configurable: true
});
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "onDidExtraLibsChange", {
get: function () {
return this._onDidExtraLibsChange.event;
},
enumerable: false,
configurable: true
});
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "workerOptions", {
get: function () {
return this._workerOptions;
},
enumerable: false,
configurable: true
});
LanguageServiceDefaultsImpl.prototype.getExtraLibs = function () {
return this._extraLibs;
};
LanguageServiceDefaultsImpl.prototype.addExtraLib = function (content, _filePath) {
var _this = this;
var 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) {
// no-op, there already exists an extra lib with this content
return {
dispose: function () { }
};
}
var 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: content,
version: myVersion
};
this._fireOnDidExtraLibsChangeSoon();
return {
dispose: function () {
var extraLib = _this._extraLibs[filePath];
if (!extraLib) {
return;
}
if (extraLib.version !== myVersion) {
return;
}
delete _this._extraLibs[filePath];
_this._removedExtraLibs[filePath] = myVersion;
_this._fireOnDidExtraLibsChangeSoon();
}
};
};
LanguageServiceDefaultsImpl.prototype.setExtraLibs = function (libs) {
for (var filePath in this._extraLibs) {
this._removedExtraLibs[filePath] = this._extraLibs[filePath].version;
}
// clear out everything
this._extraLibs = Object.create(null);
if (libs && libs.length > 0) {
for (var _i = 0, libs_1 = libs; _i < libs_1.length; _i++) {
var lib = libs_1[_i];
var filePath = lib.filePath || "ts:extralib-" + Math.random().toString(36).substring(2, 15);
var content = lib.content;
var myVersion = 1;
if (this._removedExtraLibs[filePath]) {
myVersion = this._removedExtraLibs[filePath] + 1;
}
this._extraLibs[filePath] = {
content: content,
version: myVersion
};
}
}
this._fireOnDidExtraLibsChangeSoon();
};
LanguageServiceDefaultsImpl.prototype._fireOnDidExtraLibsChangeSoon = function () {
var _this = this;
if (this._onDidExtraLibsChangeTimeout !== -1) {
// already scheduled
return;
}
this._onDidExtraLibsChangeTimeout = setTimeout(function () {
_this._onDidExtraLibsChangeTimeout = -1;
_this._onDidExtraLibsChange.fire(undefined);
}, 0);
};
LanguageServiceDefaultsImpl.prototype.getCompilerOptions = function () {
return this._compilerOptions;
};
LanguageServiceDefaultsImpl.prototype.setCompilerOptions = function (options) {
this._compilerOptions = options || Object.create(null);
this._onDidChange.fire(undefined);
};
LanguageServiceDefaultsImpl.prototype.getDiagnosticsOptions = function () {
return this._diagnosticsOptions;
};
LanguageServiceDefaultsImpl.prototype.setDiagnosticsOptions = function (options) {
this._diagnosticsOptions = options || Object.create(null);
this._onDidChange.fire(undefined);
};
LanguageServiceDefaultsImpl.prototype.setWorkerOptions = function (options) {
this._workerOptions = options || Object.create(null);
this._onDidChange.fire(undefined);
};
LanguageServiceDefaultsImpl.prototype.setMaximumWorkerIdleTime = function (value) { };
LanguageServiceDefaultsImpl.prototype.setEagerModelSync = function (value) {
// doesn't fire an event since no
// worker restart is required here
this._eagerModelSync = value;
};
LanguageServiceDefaultsImpl.prototype.getEagerModelSync = function () {
return this._eagerModelSync;
};
return LanguageServiceDefaultsImpl;
}());
exports.typescriptVersion = typescriptServicesMetadata_1.typescriptVersion;
exports.typescriptDefaults = new LanguageServiceDefaultsImpl({ allowNonTsExtensions: true, target: ScriptTarget.Latest }, { noSemanticValidation: false, noSyntaxValidation: false, onlyVisible: false }, {});
exports.javascriptDefaults = new LanguageServiceDefaultsImpl({ allowNonTsExtensions: true, allowJs: true, target: ScriptTarget.Latest }, { noSemanticValidation: true, noSyntaxValidation: false, onlyVisible: false }, {});
var getTypeScriptWorker = function () {
return getMode().then(function (mode) { return mode.getTypeScriptWorker(); });
};
exports.getTypeScriptWorker = getTypeScriptWorker;
var getJavaScriptWorker = function () {
return getMode().then(function (mode) { return mode.getJavaScriptWorker(); });
};
exports.getJavaScriptWorker = getJavaScriptWorker;
// export to the global based API
monaco_editor_core_1.languages.typescript = {
ModuleKind: ModuleKind,
JsxEmit: JsxEmit,
NewLineKind: NewLineKind,
ScriptTarget: ScriptTarget,
ModuleResolutionKind: ModuleResolutionKind,
typescriptVersion: exports.typescriptVersion,
typescriptDefaults: exports.typescriptDefaults,
javascriptDefaults: exports.javascriptDefaults,
getTypeScriptWorker: exports.getTypeScriptWorker,
getJavaScriptWorker: exports.getJavaScriptWorker
};
// --- Registration to monaco editor ---
function getMode() {
return new Promise(function (resolve_1, reject_1) { require(['./tsMode'], resolve_1, reject_1); });
}
monaco_editor_core_1.languages.onLanguage('typescript', function () {
return getMode().then(function (mode) { return mode.setupTypeScript(exports.typescriptDefaults); });
});
monaco_editor_core_1.languages.onLanguage('javascript', function () {
return getMode().then(function (mode) { return mode.setupJavaScript(exports.javascriptDefaults); });
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/language/css/fillers/monaco-editor-core',['vs/editor/editor.api'], function () {
return self.monaco;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/language/css/monaco.contribution',["require", "exports", "./fillers/monaco-editor-core"], function (require, exports, monaco_editor_core_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.lessDefaults = exports.scssDefaults = exports.cssDefaults = void 0;
// --- CSS configuration and defaults ---------
var LanguageServiceDefaultsImpl = /** @class */ (function () {
function LanguageServiceDefaultsImpl(languageId, options, modeConfiguration) {
this._onDidChange = new monaco_editor_core_1.Emitter();
this._languageId = languageId;
this.setOptions(options);
this.setModeConfiguration(modeConfiguration);
}
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "onDidChange", {
get: function () {
return this._onDidChange.event;
},
enumerable: false,
configurable: true
});
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "languageId", {
get: function () {
return this._languageId;
},
enumerable: false,
configurable: true
});
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "modeConfiguration", {
get: function () {
return this._modeConfiguration;
},
enumerable: false,
configurable: true
});
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "diagnosticsOptions", {
get: function () {
return this.options;
},
enumerable: false,
configurable: true
});
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "options", {
get: function () {
return this._options;
},
enumerable: false,
configurable: true
});
LanguageServiceDefaultsImpl.prototype.setOptions = function (options) {
this._options = options || Object.create(null);
this._onDidChange.fire(this);
};
LanguageServiceDefaultsImpl.prototype.setDiagnosticsOptions = function (options) {
this.setOptions(options);
};
LanguageServiceDefaultsImpl.prototype.setModeConfiguration = function (modeConfiguration) {
this._modeConfiguration = modeConfiguration || Object.create(null);
this._onDidChange.fire(this);
};
return LanguageServiceDefaultsImpl;
}());
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 }
};
var modeConfigurationDefault = {
completionItems: true,
hovers: true,
documentSymbols: true,
definitions: true,
references: true,
documentHighlights: true,
rename: true,
colors: true,
foldingRanges: true,
diagnostics: true,
selectionRanges: true
};
exports.cssDefaults = new LanguageServiceDefaultsImpl('css', optionsDefault, modeConfigurationDefault);
exports.scssDefaults = new LanguageServiceDefaultsImpl('scss', optionsDefault, modeConfigurationDefault);
exports.lessDefaults = new LanguageServiceDefaultsImpl('less', optionsDefault, modeConfigurationDefault);
// export to the global based API
monaco_editor_core_1.languages.css = { cssDefaults: exports.cssDefaults, lessDefaults: exports.lessDefaults, scssDefaults: exports.scssDefaults };
// --- Registration to monaco editor ---
function getMode() {
return new Promise(function (resolve_1, reject_1) { require(['./cssMode'], resolve_1, reject_1); });
}
monaco_editor_core_1.languages.onLanguage('less', function () {
getMode().then(function (mode) { return mode.setupMode(exports.lessDefaults); });
});
monaco_editor_core_1.languages.onLanguage('scss', function () {
getMode().then(function (mode) { return mode.setupMode(exports.scssDefaults); });
});
monaco_editor_core_1.languages.onLanguage('css', function () {
getMode().then(function (mode) { return mode.setupMode(exports.cssDefaults); });
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/language/json/fillers/monaco-editor-core',['vs/editor/editor.api'], function () {
return self.monaco;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/language/json/monaco.contribution',["require", "exports", "./fillers/monaco-editor-core"], function (require, exports, monaco_editor_core_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.jsonDefaults = void 0;
var LanguageServiceDefaultsImpl = /** @class */ (function () {
function LanguageServiceDefaultsImpl(languageId, diagnosticsOptions, modeConfiguration) {
this._onDidChange = new monaco_editor_core_1.Emitter();
this._languageId = languageId;
this.setDiagnosticsOptions(diagnosticsOptions);
this.setModeConfiguration(modeConfiguration);
}
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "onDidChange", {
get: function () {
return this._onDidChange.event;
},
enumerable: false,
configurable: true
});
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "languageId", {
get: function () {
return this._languageId;
},
enumerable: false,
configurable: true
});
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "modeConfiguration", {
get: function () {
return this._modeConfiguration;
},
enumerable: false,
configurable: true
});
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "diagnosticsOptions", {
get: function () {
return this._diagnosticsOptions;
},
enumerable: false,
configurable: true
});
LanguageServiceDefaultsImpl.prototype.setDiagnosticsOptions = function (options) {
this._diagnosticsOptions = options || Object.create(null);
this._onDidChange.fire(this);
};
LanguageServiceDefaultsImpl.prototype.setModeConfiguration = function (modeConfiguration) {
this._modeConfiguration = modeConfiguration || Object.create(null);
this._onDidChange.fire(this);
};
return LanguageServiceDefaultsImpl;
}());
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
};
exports.jsonDefaults = new LanguageServiceDefaultsImpl('json', diagnosticDefault, modeConfigurationDefault);
// export to the global based API
monaco_editor_core_1.languages.json = { jsonDefaults: exports.jsonDefaults };
// --- Registration to monaco editor ---
function getMode() {
return new Promise(function (resolve_1, reject_1) { require(['./jsonMode'], resolve_1, reject_1); });
}
monaco_editor_core_1.languages.register({
id: 'json',
extensions: ['.json', '.bowerrc', '.jshintrc', '.jscsrc', '.eslintrc', '.babelrc', '.har'],
aliases: ['JSON', 'json'],
mimetypes: ['application/json']
});
monaco_editor_core_1.languages.onLanguage('json', function () {
getMode().then(function (mode) { return mode.setupMode(exports.jsonDefaults); });
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/language/html/fillers/monaco-editor-core',['vs/editor/editor.api'], function () {
return self.monaco;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
define('vs/language/html/monaco.contribution',["require", "exports", "./fillers/monaco-editor-core"], function (require, exports, monaco_editor_core_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerHTMLLanguageService = exports.razorDefaults = exports.razorLanguageService = exports.handlebarDefaults = exports.handlebarLanguageService = exports.htmlDefaults = exports.htmlLanguageService = void 0;
// --- HTML configuration and defaults ---------
var LanguageServiceDefaultsImpl = /** @class */ (function () {
function LanguageServiceDefaultsImpl(languageId, options, modeConfiguration) {
this._onDidChange = new monaco_editor_core_1.Emitter();
this._languageId = languageId;
this.setOptions(options);
this.setModeConfiguration(modeConfiguration);
}
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "onDidChange", {
get: function () {
return this._onDidChange.event;
},
enumerable: false,
configurable: true
});
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "languageId", {
get: function () {
return this._languageId;
},
enumerable: false,
configurable: true
});
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "options", {
get: function () {
return this._options;
},
enumerable: false,
configurable: true
});
Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "modeConfiguration", {
get: function () {
return this._modeConfiguration;
},
enumerable: false,
configurable: true
});
LanguageServiceDefaultsImpl.prototype.setOptions = function (options) {
this._options = options || Object.create(null);
this._onDidChange.fire(this);
};
LanguageServiceDefaultsImpl.prototype.setModeConfiguration = function (modeConfiguration) {
this._modeConfiguration = modeConfiguration || Object.create(null);
this._onDidChange.fire(this);
};
return LanguageServiceDefaultsImpl;
}());
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: null,
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,
documentFormattingEdits: languageId === htmlLanguageId,
documentRangeFormattingEdits: languageId === htmlLanguageId // turned off for Razor and Handlebar
};
}
var htmlLanguageId = 'html';
var handlebarsLanguageId = 'handlebars';
var razorLanguageId = 'razor';
exports.htmlLanguageService = registerHTMLLanguageService(htmlLanguageId, optionsDefault, getConfigurationDefault(htmlLanguageId));
exports.htmlDefaults = exports.htmlLanguageService.defaults;
exports.handlebarLanguageService = registerHTMLLanguageService(handlebarsLanguageId, optionsDefault, getConfigurationDefault(handlebarsLanguageId));
exports.handlebarDefaults = exports.handlebarLanguageService.defaults;
exports.razorLanguageService = registerHTMLLanguageService(razorLanguageId, optionsDefault, getConfigurationDefault(razorLanguageId));
exports.razorDefaults = exports.razorLanguageService.defaults;
// export to the global based API
monaco_editor_core_1.languages.html = { htmlDefaults: exports.htmlDefaults, razorDefaults: exports.razorDefaults, handlebarDefaults: exports.handlebarDefaults, htmlLanguageService: exports.htmlLanguageService, handlebarLanguageService: exports.handlebarLanguageService, razorLanguageService: exports.razorLanguageService, registerHTMLLanguageService: registerHTMLLanguageService };
// --- Registration to monaco editor ---
function getMode() {
return new Promise(function (resolve_1, reject_1) { require(['./htmlMode'], resolve_1, reject_1); });
}
/**
* Registers a new HTML language service for the languageId.
* Note: 'html', 'handlebar' and 'razor' are registered by default.
*
* Use this method to register additional language ids with a HTML service.
* The language server has to be registered before an editor model is opened.
*/
function registerHTMLLanguageService(languageId, options, modeConfiguration) {
var _this = this;
if (options === void 0) { options = optionsDefault; }
if (modeConfiguration === void 0) { modeConfiguration = getConfigurationDefault(languageId); }
var defaults = new LanguageServiceDefaultsImpl(languageId, options, modeConfiguration);
var mode;
// delay the initalization of the mode until the language is accessed the first time
var onLanguageListener = monaco_editor_core_1.languages.onLanguage(languageId, function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, getMode()];
case 1:
mode = (_a.sent()).setupMode(defaults);
return [2 /*return*/];
}
});
}); });
return {
defaults: defaults,
dispose: function () {
onLanguageListener.dispose();
mode === null || mode === void 0 ? void 0 : mode.dispose();
mode = undefined;
}
};
}
exports.registerHTMLLanguageService = registerHTMLLanguageService;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/fillers/monaco-editor-core',['vs/editor/editor.api'], function () {
return self.monaco;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/_.contribution',["require", "exports", "./fillers/monaco-editor-core"], function (require, exports, monaco_editor_core_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerLanguage = exports.loadLanguage = void 0;
var languageDefinitions = {};
var lazyLanguageLoaders = {};
var LazyLanguageLoader = /** @class */ (function () {
function LazyLanguageLoader(languageId) {
var _this = this;
this._languageId = languageId;
this._loadingTriggered = false;
this._lazyLoadPromise = new Promise(function (resolve, reject) {
_this._lazyLoadPromiseResolve = resolve;
_this._lazyLoadPromiseReject = reject;
});
}
LazyLanguageLoader.getOrCreate = function (languageId) {
if (!lazyLanguageLoaders[languageId]) {
lazyLanguageLoaders[languageId] = new LazyLanguageLoader(languageId);
}
return lazyLanguageLoaders[languageId];
};
LazyLanguageLoader.prototype.whenLoaded = function () {
return this._lazyLoadPromise;
};
LazyLanguageLoader.prototype.load = function () {
var _this = this;
if (!this._loadingTriggered) {
this._loadingTriggered = true;
languageDefinitions[this._languageId].loader().then(function (mod) { return _this._lazyLoadPromiseResolve(mod); }, function (err) { return _this._lazyLoadPromiseReject(err); });
}
return this._lazyLoadPromise;
};
return LazyLanguageLoader;
}());
function loadLanguage(languageId) {
return LazyLanguageLoader.getOrCreate(languageId).load();
}
exports.loadLanguage = loadLanguage;
function registerLanguage(def) {
var languageId = def.id;
languageDefinitions[languageId] = def;
monaco_editor_core_1.languages.register(def);
var lazyLanguageLoader = LazyLanguageLoader.getOrCreate(languageId);
monaco_editor_core_1.languages.setMonarchTokensProvider(languageId, lazyLanguageLoader.whenLoaded().then(function (mod) { return mod.language; }));
monaco_editor_core_1.languages.onLanguage(languageId, function () {
lazyLanguageLoader.load().then(function (mod) {
monaco_editor_core_1.languages.setLanguageConfiguration(languageId, mod.conf);
});
});
}
exports.registerLanguage = registerLanguage;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/abap/abap.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'abap',
extensions: ['.abap'],
aliases: ['abap', 'ABAP'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./abap'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/apex/apex.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'apex',
extensions: ['.cls'],
aliases: ['Apex', 'apex'],
mimetypes: ['text/x-apex-source', 'text/x-apex'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./apex'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/azcli/azcli.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'azcli',
extensions: ['.azcli'],
aliases: ['Azure CLI', 'azcli'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./azcli'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/bat/bat.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'bat',
extensions: ['.bat', '.cmd'],
aliases: ['Batch', 'bat'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./bat'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/bicep/bicep.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'bicep',
extensions: ['.bicep'],
aliases: ['Bicep'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./bicep'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/cameligo/cameligo.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'cameligo',
extensions: ['.mligo'],
aliases: ['Cameligo'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./cameligo'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/clojure/clojure.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'clojure',
extensions: ['.clj', '.cljs', '.cljc', '.edn'],
aliases: ['clojure', 'Clojure'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./clojure'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/coffee/coffee.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'coffeescript',
extensions: ['.coffee'],
aliases: ['CoffeeScript', 'coffeescript', 'coffee'],
mimetypes: ['text/x-coffeescript', 'text/coffeescript'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./coffee'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/cpp/cpp.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'c',
extensions: ['.c', '.h'],
aliases: ['C', 'c'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./cpp'], resolve_1, reject_1); }); }
});
__contribution_1.registerLanguage({
id: 'cpp',
extensions: ['.cpp', '.cc', '.cxx', '.hpp', '.hh', '.hxx'],
aliases: ['C++', 'Cpp', 'cpp'],
loader: function () { return new Promise(function (resolve_2, reject_2) { require(['./cpp'], resolve_2, reject_2); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/csharp/csharp.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'csharp',
extensions: ['.cs', '.csx', '.cake'],
aliases: ['C#', 'csharp'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./csharp'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/csp/csp.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'csp',
extensions: [],
aliases: ['CSP', 'csp'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./csp'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/css/css.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'css',
extensions: ['.css'],
aliases: ['CSS', 'css'],
mimetypes: ['text/css'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./css'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/dart/dart.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'dart',
extensions: ['.dart'],
aliases: ['Dart', 'dart'],
mimetypes: ['text/x-dart-source', 'text/x-dart'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./dart'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/dockerfile/dockerfile.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'dockerfile',
extensions: ['.dockerfile'],
filenames: ['Dockerfile'],
aliases: ['Dockerfile'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./dockerfile'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/ecl/ecl.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'ecl',
extensions: ['.ecl'],
aliases: ['ECL', 'Ecl', 'ecl'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./ecl'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/elixir/elixir.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'elixir',
extensions: ['.ex', '.exs'],
aliases: ['Elixir', 'elixir', 'ex'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./elixir'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/fsharp/fsharp.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'fsharp',
extensions: ['.fs', '.fsi', '.ml', '.mli', '.fsx', '.fsscript'],
aliases: ['F#', 'FSharp', 'fsharp'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./fsharp'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/go/go.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'go',
extensions: ['.go'],
aliases: ['Go'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./go'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/graphql/graphql.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'graphql',
extensions: ['.graphql', '.gql'],
aliases: ['GraphQL', 'graphql', 'gql'],
mimetypes: ['application/graphql'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./graphql'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/handlebars/handlebars.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'handlebars',
extensions: ['.handlebars', '.hbs'],
aliases: ['Handlebars', 'handlebars', 'hbs'],
mimetypes: ['text/x-handlebars-template'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./handlebars'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/hcl/hcl.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'hcl',
extensions: ['.tf', '.tfvars', '.hcl'],
aliases: ['Terraform', 'tf', 'HCL', 'hcl'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./hcl'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/html/html.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.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: function () { return new Promise(function (resolve_1, reject_1) { require(['./html'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/ini/ini.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'ini',
extensions: ['.ini', '.properties', '.gitconfig'],
filenames: ['config', '.gitattributes', '.gitconfig', '.editorconfig'],
aliases: ['Ini', 'ini'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./ini'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/java/java.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'java',
extensions: ['.java', '.jav'],
aliases: ['Java', 'java'],
mimetypes: ['text/x-java-source', 'text/x-java'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./java'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/javascript/javascript.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'javascript',
extensions: ['.js', '.es6', '.jsx', '.mjs'],
firstLine: '^#!.*\\bnode',
filenames: ['jakefile'],
aliases: ['JavaScript', 'javascript', 'js'],
mimetypes: ['text/javascript'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./javascript'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/julia/julia.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'julia',
extensions: ['.jl'],
aliases: ['julia', 'Julia'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./julia'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/kotlin/kotlin.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'kotlin',
extensions: ['.kt'],
aliases: ['Kotlin', 'kotlin'],
mimetypes: ['text/x-kotlin-source', 'text/x-kotlin'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./kotlin'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/less/less.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'less',
extensions: ['.less'],
aliases: ['Less', 'less'],
mimetypes: ['text/x-less', 'text/less'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./less'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/lexon/lexon.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'lexon',
extensions: ['.lex'],
aliases: ['Lexon'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./lexon'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/lua/lua.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'lua',
extensions: ['.lua'],
aliases: ['Lua', 'lua'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./lua'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/liquid/liquid.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'liquid',
extensions: ['.liquid', '.html.liquid'],
aliases: ['Liquid', 'liquid'],
mimetypes: ['application/liquid'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./liquid'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/m3/m3.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'm3',
extensions: ['.m3', '.i3', '.mg', '.ig'],
aliases: ['Modula-3', 'Modula3', 'modula3', 'm3'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./m3'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/markdown/markdown.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'markdown',
extensions: ['.md', '.markdown', '.mdown', '.mkdn', '.mkd', '.mdwn', '.mdtxt', '.mdtext'],
aliases: ['Markdown', 'markdown'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./markdown'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/mips/mips.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'mips',
extensions: ['.s'],
aliases: ['MIPS', 'MIPS-V'],
mimetypes: ['text/x-mips', 'text/mips', 'text/plaintext'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./mips'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/msdax/msdax.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'msdax',
extensions: ['.dax', '.msdax'],
aliases: ['DAX', 'MSDAX'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./msdax'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/mysql/mysql.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'mysql',
extensions: [],
aliases: ['MySQL', 'mysql'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./mysql'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/objective-c/objective-c.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'objective-c',
extensions: ['.m'],
aliases: ['Objective-C'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./objective-c'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/pascal/pascal.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'pascal',
extensions: ['.pas', '.p', '.pp'],
aliases: ['Pascal', 'pas'],
mimetypes: ['text/x-pascal-source', 'text/x-pascal'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./pascal'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/pascaligo/pascaligo.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'pascaligo',
extensions: ['.ligo'],
aliases: ['Pascaligo', 'ligo'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./pascaligo'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/perl/perl.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'perl',
extensions: ['.pl'],
aliases: ['Perl', 'pl'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./perl'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/pgsql/pgsql.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'pgsql',
extensions: [],
aliases: ['PostgreSQL', 'postgres', 'pg', 'postgre'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./pgsql'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/php/php.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'php',
extensions: ['.php', '.php4', '.php5', '.phtml', '.ctp'],
aliases: ['PHP', 'php'],
mimetypes: ['application/x-php'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./php'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/postiats/postiats.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'postiats',
extensions: ['.dats', '.sats', '.hats'],
aliases: ['ATS', 'ATS/Postiats'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./postiats'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/powerquery/powerquery.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'powerquery',
extensions: ['.pq', '.pqm'],
aliases: ['PQ', 'M', 'Power Query', 'Power Query M'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./powerquery'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/powershell/powershell.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'powershell',
extensions: ['.ps1', '.psm1', '.psd1'],
aliases: ['PowerShell', 'powershell', 'ps', 'ps1'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./powershell'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/pug/pug.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'pug',
extensions: ['.jade', '.pug'],
aliases: ['Pug', 'Jade', 'jade'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./pug'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/python/python.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'python',
extensions: ['.py', '.rpy', '.pyw', '.cpy', '.gyp', '.gypi'],
aliases: ['Python', 'py'],
firstLine: '^#!/.*\\bpython[0-9.-]*\\b',
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./python'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/qsharp/qsharp.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'qsharp',
extensions: ['.qs'],
aliases: ['Q#', 'qsharp'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./qsharp'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/r/r.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'r',
extensions: ['.r', '.rhistory', '.rmd', '.rprofile', '.rt'],
aliases: ['R', 'r'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./r'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/razor/razor.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'razor',
extensions: ['.cshtml'],
aliases: ['Razor', 'razor'],
mimetypes: ['text/x-cshtml'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./razor'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/redis/redis.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'redis',
extensions: ['.redis'],
aliases: ['redis'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./redis'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/redshift/redshift.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'redshift',
extensions: [],
aliases: ['Redshift', 'redshift'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./redshift'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/restructuredtext/restructuredtext.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'restructuredtext',
extensions: ['.rst'],
aliases: ['reStructuredText', 'restructuredtext'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./restructuredtext'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/ruby/ruby.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'ruby',
extensions: ['.rb', '.rbx', '.rjs', '.gemspec', '.pp'],
filenames: ['rakefile', 'Gemfile'],
aliases: ['Ruby', 'rb'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./ruby'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/rust/rust.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'rust',
extensions: ['.rs', '.rlib'],
aliases: ['Rust', 'rust'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./rust'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/sb/sb.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'sb',
extensions: ['.sb'],
aliases: ['Small Basic', 'sb'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./sb'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/scala/scala.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.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: function () { return new Promise(function (resolve_1, reject_1) { require(['./scala'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/scheme/scheme.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'scheme',
extensions: ['.scm', '.ss', '.sch', '.rkt'],
aliases: ['scheme', 'Scheme'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./scheme'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/scss/scss.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'scss',
extensions: ['.scss'],
aliases: ['Sass', 'sass', 'scss'],
mimetypes: ['text/x-scss', 'text/scss'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./scss'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/shell/shell.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'shell',
extensions: ['.sh', '.bash'],
aliases: ['Shell', 'sh'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./shell'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/solidity/solidity.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'sol',
extensions: ['.sol'],
aliases: ['sol', 'solidity', 'Solidity'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./solidity'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/sophia/sophia.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'aes',
extensions: ['.aes'],
aliases: ['aes', 'sophia', 'Sophia'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./sophia'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/sparql/sparql.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'sparql',
extensions: ['.rq'],
aliases: ['sparql', 'SPARQL'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./sparql'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/sql/sql.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'sql',
extensions: ['.sql'],
aliases: ['SQL'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./sql'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/st/st.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'st',
extensions: ['.st', '.iecst', '.iecplc', '.lc3lib'],
aliases: ['StructuredText', 'scl', 'stl'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./st'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/swift/swift.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'swift',
aliases: ['Swift', 'swift'],
extensions: ['.swift'],
mimetypes: ['text/swift'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./swift'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/systemverilog/systemverilog.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'systemverilog',
extensions: ['.sv', '.svh'],
aliases: ['SV', 'sv', 'SystemVerilog', 'systemverilog'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./systemverilog'], resolve_1, reject_1); }); }
});
__contribution_1.registerLanguage({
id: 'verilog',
extensions: ['.v', '.vh'],
aliases: ['V', 'v', 'Verilog', 'verilog'],
loader: function () { return new Promise(function (resolve_2, reject_2) { require(['./systemverilog'], resolve_2, reject_2); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/tcl/tcl.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'tcl',
extensions: ['.tcl'],
aliases: ['tcl', 'Tcl', 'tcltk', 'TclTk', 'tcl/tk', 'Tcl/Tk'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./tcl'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/twig/twig.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'twig',
extensions: ['.twig'],
aliases: ['Twig', 'twig'],
mimetypes: ['text/x-twig'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./twig'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/typescript/typescript.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'typescript',
extensions: ['.ts', '.tsx'],
aliases: ['TypeScript', 'ts', 'typescript'],
mimetypes: ['text/typescript'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./typescript'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/vb/vb.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'vb',
extensions: ['.vb'],
aliases: ['Visual Basic', 'vb'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./vb'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/xml/xml.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'xml',
extensions: [
'.xml',
'.dtd',
'.ascx',
'.csproj',
'.config',
'.wxi',
'.wxl',
'.wxs',
'.xaml',
'.svg',
'.svgz',
'.opf',
'.xsl'
],
firstLine: '(\\<\\?xml.*)|(\\<svg)|(\\<\\!doctype\\s+svg)',
aliases: ['XML', 'xml'],
mimetypes: ['text/xml', 'application/xml', 'application/xaml+xml', 'application/xml-dtd'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./xml'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/yaml/yaml.contribution',["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__contribution_1.registerLanguage({
id: 'yaml',
extensions: ['.yaml', '.yml'],
aliases: ['YAML', 'yaml', 'YML', 'yml'],
mimetypes: ['application/x-yaml', 'text/x-yaml'],
loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./yaml'], resolve_1, reject_1); }); }
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define('vs/basic-languages/monaco.contribution',["require", "exports", "./abap/abap.contribution", "./apex/apex.contribution", "./azcli/azcli.contribution", "./bat/bat.contribution", "./bicep/bicep.contribution", "./cameligo/cameligo.contribution", "./clojure/clojure.contribution", "./coffee/coffee.contribution", "./cpp/cpp.contribution", "./csharp/csharp.contribution", "./csp/csp.contribution", "./css/css.contribution", "./dart/dart.contribution", "./dockerfile/dockerfile.contribution", "./ecl/ecl.contribution", "./elixir/elixir.contribution", "./fsharp/fsharp.contribution", "./go/go.contribution", "./graphql/graphql.contribution", "./handlebars/handlebars.contribution", "./hcl/hcl.contribution", "./html/html.contribution", "./ini/ini.contribution", "./java/java.contribution", "./javascript/javascript.contribution", "./julia/julia.contribution", "./kotlin/kotlin.contribution", "./less/less.contribution", "./lexon/lexon.contribution", "./lua/lua.contribution", "./liquid/liquid.contribution", "./m3/m3.contribution", "./markdown/markdown.contribution", "./mips/mips.contribution", "./msdax/msdax.contribution", "./mysql/mysql.contribution", "./objective-c/objective-c.contribution", "./pascal/pascal.contribution", "./pascaligo/pascaligo.contribution", "./perl/perl.contribution", "./pgsql/pgsql.contribution", "./php/php.contribution", "./postiats/postiats.contribution", "./powerquery/powerquery.contribution", "./powershell/powershell.contribution", "./pug/pug.contribution", "./python/python.contribution", "./qsharp/qsharp.contribution", "./r/r.contribution", "./razor/razor.contribution", "./redis/redis.contribution", "./redshift/redshift.contribution", "./restructuredtext/restructuredtext.contribution", "./ruby/ruby.contribution", "./rust/rust.contribution", "./sb/sb.contribution", "./scala/scala.contribution", "./scheme/scheme.contribution", "./scss/scss.contribution", "./shell/shell.contribution", "./solidity/solidity.contribution", "./sophia/sophia.contribution", "./sparql/sparql.contribution", "./sql/sql.contribution", "./st/st.contribution", "./swift/swift.contribution", "./systemverilog/systemverilog.contribution", "./tcl/tcl.contribution", "./twig/twig.contribution", "./typescript/typescript.contribution", "./vb/vb.contribution", "./xml/xml.contribution", "./yaml/yaml.contribution"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
});
define("vs/editor/editor.main", ["vs/editor/edcore.main","vs/language/typescript/monaco.contribution","vs/language/css/monaco.contribution","vs/language/json/monaco.contribution","vs/language/html/monaco.contribution","vs/basic-languages/monaco.contribution"], function(api) { return api; });
//# sourceMappingURL=editor.main.js.map