/*!----------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Version: 0.32.1(8ad5e3bceab16a4d0856c43a374b511dffb1e795) * Released under the MIT license * https://github.com/microsoft/vscode/blob/main/LICENSE.txt *-----------------------------------------------------------*/ (function() { var __m = ["exports","require","vs/base/common/lifecycle","vs/editor/common/core/range","vs/base/common/event","vs/nls","vs/nls!vs/editor/editor.main","vs/base/browser/dom","vs/base/common/strings","vs/platform/instantiation/common/instantiation","vs/base/common/async","vs/editor/common/core/position","vs/css!vs/editor/editor.main","vs/base/common/errors","vs/platform/theme/common/themeService","vs/editor/browser/editorExtensions","vs/platform/contextkey/common/contextkey","vs/base/common/platform","vs/editor/common/languages","vs/base/common/arrays","vs/base/common/types","vs/base/common/cancellation","vs/editor/common/core/selection","vs/platform/theme/common/colorRegistry","vs/editor/common/editorContextKeys","vs/base/common/uri","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/config/editorOptions","vs/editor/common/languages/languageConfigurationRegistry","vs/editor/common/model/textModel","vs/base/browser/browser","vs/editor/common/services/language","vs/platform/registry/common/platform","vs/platform/actions/common/actions","vs/platform/notification/common/notification","vs/base/common/objects","vs/platform/configuration/common/configuration","vs/base/common/resources","vs/platform/keybinding/common/keybinding","vs/base/browser/ui/aria/aria","vs/base/common/actions","vs/editor/common/services/model","vs/base/browser/keyboardEvent","vs/base/common/map","vs/base/common/network","vs/editor/common/model","vs/editor/browser/view/viewPart","vs/platform/opener/common/opener","vs/editor/common/core/editorColorRegistry","vs/platform/instantiation/common/extensions","vs/base/common/iterator","vs/base/common/keyCodes","vs/base/browser/mouseEvent","vs/base/browser/touch","vs/editor/common/services/resolverService","vs/editor/common/cursor/cursorCommon","vs/base/browser/ui/widget","vs/editor/common/core/editOperation","vs/editor/browser/config/domFontInfo","vs/platform/accessibility/common/accessibility","vs/platform/log/common/log","vs/base/common/stopwatch","vs/base/common/htmlContent","vs/base/browser/ui/scrollbar/scrollableElement","vs/editor/common/core/cursorColumns","vs/editor/common/viewModel/viewModel","vs/editor/common/standaloneStrings","vs/platform/progress/common/progress","vs/platform/theme/common/iconRegistry","vs/base/common/filters","vs/base/common/severity","vs/editor/common/tokens/lineTokens","vs/platform/contextview/browser/contextView","vs/platform/markers/common/markers","vs/platform/quickinput/common/quickInput","vs/editor/common/languages/modesRegistry","vs/platform/storage/common/storage","vs/base/common/linkedList","vs/base/common/path","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length","vs/base/browser/ui/actionbar/actionbar","vs/editor/common/services/editorWorker","vs/platform/keybinding/common/keybindingsRegistry","vs/platform/telemetry/common/telemetry","vs/base/common/functional","vs/base/browser/event","vs/editor/common/core/stringBuilder","vs/editor/common/textModelEvents","vs/editor/common/services/languageFeatureDebounce","vs/base/common/decorators","vs/base/common/keybindings","vs/base/common/iconLabels","vs/base/browser/globalMouseMoveMonitor","vs/editor/common/core/characterClassifier","vs/editor/common/commands/replaceCommand","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet","vs/editor/browser/view/dynamicViewOverlay","vs/editor/standalone/common/standaloneTheme","vs/platform/clipboard/common/clipboardService","vs/platform/configuration/common/configurationRegistry","vs/editor/contrib/markdownRenderer/browser/markdownRenderer","vs/platform/quickinput/common/quickAccess","vs/editor/contrib/editorState/browser/editorState","vs/editor/contrib/suggest/browser/suggest","vs/editor/contrib/peekView/browser/peekView","vs/base/browser/ui/tree/tree","vs/base/common/buffer","vs/base/common/numbers","vs/base/common/hash","vs/base/browser/ui/iconLabel/iconLabels","vs/base/browser/ui/sash/sash","vs/base/browser/ui/list/listWidget","vs/editor/browser/view/renderingContext","vs/editor/common/core/eolCounter","vs/editor/common/core/wordCharacterClassifier","vs/editor/common/languages/languageConfiguration","vs/editor/common/languages/supports","vs/editor/common/languages/nullMode","vs/editor/common/viewLayout/viewLineRenderer","vs/editor/common/viewModel/viewEventHandler","vs/editor/contrib/snippet/browser/snippetParser","vs/base/browser/ui/actionbar/actionViewItems","vs/editor/contrib/gotoSymbol/browser/referencesModel","vs/platform/dialogs/common/dialogs","vs/platform/label/common/label","vs/platform/layout/browser/layoutService","vs/editor/browser/editorDom","vs/platform/theme/common/styler","vs/platform/theme/common/theme","vs/base/common/idGenerator","vs/base/common/lazy","vs/base/common/mime","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/browser/stableEditorScroll","vs/editor/common/config/editorZoom","vs/editor/common/core/textModelDefaults","vs/editor/common/core/wordHelper","vs/editor/common/editorCommon","vs/editor/browser/editorBrowser","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/ast","vs/editor/common/model/textModelSearch","vs/editor/common/viewLayout/lineDecorations","vs/editor/contrib/codeAction/browser/types","vs/editor/common/services/textResourceConfiguration","vs/platform/instantiation/common/serviceCollection","vs/editor/contrib/codeAction/browser/codeAction","vs/editor/contrib/message/browser/messageController","vs/platform/list/browser/listService","vs/platform/undoRedo/common/undoRedo","vs/editor/common/cursor/cursorWordOperations","vs/editor/browser/controller/coreCommands","vs/editor/browser/widget/codeEditorWidget","vs/editor/browser/widget/embeddedCodeEditorWidget","vs/editor/contrib/find/browser/findModel","vs/base/browser/dnd","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/scrollbar/scrollbarArrow","vs/base/common/labels","vs/base/browser/ui/checkbox/checkbox","vs/base/browser/ui/list/listView","vs/editor/common/config/fontInfo","vs/editor/browser/controller/textAreaInput","vs/editor/browser/view/viewLayer","vs/editor/common/languages/supports/richEditBrackets","vs/editor/common/model/utils","vs/editor/common/standalone/standaloneEnums","vs/editor/common/textModelGuides","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/tokenizer","vs/editor/browser/viewParts/glyphMargin/glyphMargin","vs/editor/common/viewModel/viewEvents","vs/editor/common/viewModel/viewModelEventDispatcher","vs/editor/contrib/folding/browser/foldingRanges","vs/editor/contrib/gotoSymbol/browser/link/clickLinkGesture","vs/editor/contrib/hover/browser/hoverTypes","vs/editor/contrib/inlineCompletions/browser/ghostText","vs/editor/contrib/inlineCompletions/browser/inlineCompletionToGhostText","vs/base/browser/ui/iconLabel/iconLabel","vs/base/browser/ui/tree/abstractTree","vs/base/browser/ui/inputbox/inputBox","vs/base/common/keybindingLabels","vs/platform/instantiation/common/descriptors","vs/editor/browser/services/bulkEditService","vs/editor/common/services/markerDecorations","vs/editor/common/commands/shiftCommand","vs/editor/contrib/parameterHints/browser/provideSignatureHelp","vs/editor/contrib/documentSymbols/browser/outlineModel","vs/platform/jsonschemas/common/jsonContributionRegistry","vs/editor/contrib/hover/browser/markdownHoverParticipant","vs/platform/actions/browser/menuEntryActionViewItem","vs/editor/common/cursor/cursorMoveOperations","vs/editor/common/cursor/cursorDeleteOperations","vs/editor/common/cursor/cursorTypeOperations","vs/editor/common/cursor/cursorMoveCommands","vs/editor/contrib/inlineCompletions/browser/inlineCompletionsModel","vs/editor/contrib/gotoSymbol/browser/goToCommands","vs/editor/standalone/browser/standaloneServices","vs/editor/contrib/snippet/browser/snippetController2","vs/base/browser/iframe","vs/base/browser/ui/scrollbar/scrollbarState","vs/base/common/assert","vs/base/common/collections","vs/base/common/glob","vs/base/common/marshalling","vs/base/browser/ui/highlightedlabel/highlightedLabel","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/hover/hoverWidget","vs/base/browser/ui/splitview/splitview","vs/base/parts/quickinput/browser/quickInputUtils","vs/editor/browser/config/elementSizeObserver","vs/editor/browser/config/tabFocus","vs/editor/browser/view/viewUserInputEvents","vs/editor/browser/viewParts/minimap/minimapCharSheet","vs/editor/browser/controller/textAreaState","vs/editor/browser/widget/diffNavigator","vs/editor/common/core/rgba","vs/editor/common/core/textChange","vs/editor/common/cursor/cursorAtomicMoveOperations","vs/editor/common/editorAction","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/beforeEditPositionMapper","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/parser","vs/editor/common/model/prefixSumComputer","vs/editor/common/languages/unicodeTextModelHighlighter","vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase","vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer","vs/editor/common/model/guidesTextModelPart","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/brackets","vs/editor/common/services/editorBaseApi","vs/editor/common/languages/textToHtmlTokenizer","vs/editor/common/viewModel/minimapTokensColorTracker","vs/editor/common/viewModel/modelLineProjectionData","vs/editor/common/viewModel/overviewZoneManager","vs/editor/browser/viewParts/margin/margin","vs/editor/contrib/comment/browser/blockCommentCommand","vs/editor/contrib/folding/browser/syntaxRangeProvider","vs/editor/contrib/format/browser/formattingEdit","vs/editor/contrib/hover/browser/hoverOperation","vs/editor/contrib/indentation/browser/indentUtils","vs/editor/contrib/inlineCompletions/browser/consts","vs/editor/contrib/smartSelect/browser/bracketSelections","vs/editor/contrib/suggest/browser/resizable","vs/editor/standalone/common/monarch/monarchCommon","vs/editor/standalone/common/monarch/monarchLexer","vs/base/browser/ui/findinput/findInputCheckboxes","vs/base/browser/ui/tree/objectTree","vs/editor/browser/config/fontMeasurements","vs/editor/common/viewModel/viewModelDecorations","vs/editor/common/model/editStack","vs/platform/files/common/files","vs/editor/common/services/getSemanticTokens","vs/editor/contrib/codelens/browser/codelens","vs/editor/contrib/colorPicker/browser/color","vs/platform/contextkey/common/contextkeys","vs/platform/keybinding/common/resolvedKeybindingItem","vs/editor/standalone/browser/standaloneLayoutService","vs/editor/browser/services/editorWorkerService","vs/editor/contrib/suggest/browser/suggestWidgetDetails","vs/editor/browser/viewParts/lines/viewLine","vs/editor/browser/controller/mouseTarget","vs/editor/browser/viewParts/lineNumbers/lineNumbers","vs/editor/common/services/semanticTokensProviderStyling","vs/editor/contrib/quickAccess/browser/editorNavigationQuickAccess","vs/editor/contrib/symbolIcons/browser/symbolIcons","vs/editor/standalone/browser/standaloneCodeEditorService","vs/editor/contrib/format/browser/format","vs/editor/contrib/gotoSymbol/browser/goToSymbol","vs/editor/contrib/hover/browser/getHover","vs/editor/contrib/codeAction/browser/codeActionCommands","vs/editor/contrib/toggleTabFocusMode/browser/toggleTabFocusMode","vs/editor/common/cursor/cursor","vs/editor/common/services/modelService","vs/editor/browser/widget/diffEditorWidget","vs/editor/contrib/colorPicker/browser/colorDetector","vs/editor/contrib/find/browser/findController","vs/editor/contrib/wordOperations/browser/wordOperations","vs/editor/contrib/gotoError/browser/gotoError","vs/editor/contrib/gotoSymbol/browser/peek/referencesController","vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition","vs/editor/contrib/inlayHints/browser/inlayHintsController","vs/platform/workspace/common/workspace","vs/platform/workspace/common/workspaceTrust","vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter","vs/editor/contrib/snippet/browser/snippetSession","vs/editor/contrib/suggest/browser/suggestController","vs/editor/contrib/inlineCompletions/browser/ghostTextController","vs/editor/contrib/hover/browser/hover","vs/base/browser/ui/list/list","vs/base/browser/ui/list/splice","vs/base/common/cache","vs/base/common/diff/diffChange","vs/base/common/marked/marked","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/fuzzyScorer","vs/base/common/search","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/browser/defaultWorkerFactory","vs/base/parts/storage/common/storage","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/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/browser/anchorSelect","vs/css!vs/editor/contrib/bracketMatching/browser/bracketMatching","vs/css!vs/editor/contrib/codeAction/browser/lightBulbWidget","vs/css!vs/editor/contrib/codelens/browser/codelensWidget","vs/css!vs/editor/contrib/colorPicker/browser/colorPicker","vs/css!vs/editor/contrib/dnd/browser/dnd","vs/css!vs/editor/contrib/find/browser/findWidget","vs/css!vs/editor/contrib/folding/browser/folding","vs/css!vs/editor/contrib/gotoError/browser/media/gotoErrorWidget","vs/css!vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition","vs/css!vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget","vs/css!vs/editor/contrib/inlineCompletions/browser/ghostText","vs/css!vs/editor/contrib/links/browser/links","vs/css!vs/editor/contrib/message/browser/messageController","vs/css!vs/editor/contrib/parameterHints/browser/parameterHints","vs/css!vs/editor/contrib/peekView/browser/media/peekViewWidget","vs/css!vs/editor/contrib/rename/browser/renameInputField","vs/css!vs/editor/contrib/snippet/browser/snippetSession","vs/css!vs/editor/contrib/suggest/browser/media/suggest","vs/css!vs/editor/contrib/unicodeHighlighter/browser/bannerController","vs/css!vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter","vs/css!vs/editor/contrib/zoneWidget/browser/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/migrateOptions","vs/editor/browser/viewParts/lines/rangeUtil","vs/editor/browser/viewParts/minimap/minimapCharRenderer","vs/editor/browser/viewParts/minimap/minimapPreBaked","vs/editor/browser/viewParts/minimap/minimapCharRendererFactory","vs/editor/common/commands/trimTrailingWhitespaceCommand","vs/editor/common/commands/surroundSelectionCommand","vs/editor/common/diff/diffComputer","vs/editor/common/languageSelector","vs/editor/common/languages/linkComputer","vs/editor/common/languages/supports/characterPair","vs/editor/common/languages/supports/indentRules","vs/editor/common/languages/supports/inplaceReplaceSupport","vs/editor/common/languages/supports/onEnter","vs/editor/common/languages/supports/electricCharacter","vs/editor/common/languages/supports/tokenization","vs/editor/common/languageFeatureRegistry","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/nodeReader","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/concat23Trees","vs/editor/common/model/indentationGuesser","vs/editor/common/model/intervalTree","vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase","vs/editor/common/model/mirrorTextModel","vs/editor/common/model/textModelPart","vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder","vs/editor/common/services/languagesAssociations","vs/editor/common/services/semanticTokensDto","vs/editor/common/textModelBracketPairs","vs/editor/common/tokenizationRegistry","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/bracketPairsTree","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsImpl","vs/editor/common/model/bracketPairsTextModelPart/fixBrackets","vs/editor/common/services/editorSimpleWorker","vs/editor/common/tokens/contiguousMultilineTokens","vs/editor/common/tokens/contiguousMultilineTokensBuilder","vs/editor/common/model/textModelTokens","vs/editor/common/tokens/contiguousTokensEditing","vs/editor/common/tokens/contiguousTokensStore","vs/editor/common/tokens/sparseMultilineTokens","vs/editor/common/tokens/sparseTokensStore","vs/editor/common/viewLayout/linesLayout","vs/editor/common/viewLayout/viewLinesViewportData","vs/editor/common/viewModel/monospaceLineBreaksComputer","vs/editor/common/viewModel/viewContext","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/modelLineProjection","vs/editor/common/viewLayout/viewLayout","vs/editor/contrib/caretOperations/browser/moveCaretCommand","vs/editor/contrib/colorPicker/browser/colorPickerModel","vs/editor/contrib/dnd/browser/dragAndDropCommand","vs/editor/contrib/find/browser/replaceAllCommand","vs/editor/contrib/find/browser/replacePattern","vs/editor/contrib/folding/browser/foldingModel","vs/editor/contrib/folding/browser/hiddenRangeModel","vs/editor/contrib/folding/browser/indentRangeProvider","vs/editor/contrib/folding/browser/intializingRangeProvider","vs/editor/contrib/inPlaceReplace/browser/inPlaceReplaceCommand","vs/editor/contrib/inlayHints/browser/inlayHints","vs/editor/contrib/inlineCompletions/browser/utils","vs/editor/contrib/linesOperations/browser/copyLinesCommand","vs/editor/contrib/linesOperations/browser/sortLinesCommand","vs/editor/contrib/smartSelect/browser/wordSelections","vs/editor/contrib/suggest/browser/completionModel","vs/editor/contrib/suggest/browser/suggestCommitCharacters","vs/editor/contrib/suggest/browser/suggestOvertypingCapturer","vs/editor/contrib/suggest/browser/wordDistance","vs/editor/standalone/common/monarch/monarchCompile","vs/editor/standalone/browser/colorizer","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/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/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/editorConfigurationSchema","vs/nls!vs/editor/common/config/editorOptions","vs/editor/browser/config/charWidthReader","vs/editor/browser/view/domLineBreaksComputer","vs/editor/browser/view/viewOverlays","vs/editor/browser/viewParts/viewCursors/viewCursor","vs/nls!vs/editor/common/core/editorColorRegistry","vs/nls!vs/editor/common/editorContextKeys","vs/nls!vs/editor/common/languages/modesRegistry","vs/nls!vs/editor/common/model/editStack","vs/nls!vs/editor/common/standaloneStrings","vs/nls!vs/editor/contrib/anchorSelect/browser/anchorSelect","vs/nls!vs/editor/contrib/bracketMatching/browser/bracketMatching","vs/nls!vs/editor/contrib/caretOperations/browser/caretOperations","vs/nls!vs/editor/contrib/caretOperations/browser/transpose","vs/nls!vs/editor/contrib/clipboard/browser/clipboard","vs/nls!vs/editor/contrib/codeAction/browser/codeActionCommands","vs/nls!vs/editor/contrib/codeAction/browser/lightBulbWidget","vs/nls!vs/editor/contrib/codelens/browser/codelensController","vs/nls!vs/editor/contrib/colorPicker/browser/colorPickerWidget","vs/nls!vs/editor/contrib/comment/browser/comment","vs/nls!vs/editor/contrib/contextmenu/browser/contextmenu","vs/nls!vs/editor/contrib/cursorUndo/browser/cursorUndo","vs/nls!vs/editor/contrib/editorState/browser/keybindingCancellation","vs/nls!vs/editor/contrib/find/browser/findController","vs/nls!vs/editor/contrib/find/browser/findWidget","vs/nls!vs/editor/contrib/folding/browser/folding","vs/nls!vs/editor/contrib/folding/browser/foldingDecorations","vs/nls!vs/editor/contrib/fontZoom/browser/fontZoom","vs/nls!vs/editor/contrib/format/browser/format","vs/nls!vs/editor/contrib/format/browser/formatActions","vs/nls!vs/editor/contrib/gotoError/browser/gotoError","vs/nls!vs/editor/contrib/gotoError/browser/gotoErrorWidget","vs/nls!vs/editor/contrib/gotoSymbol/browser/goToCommands","vs/nls!vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition","vs/nls!vs/editor/contrib/gotoSymbol/browser/peek/referencesController","vs/nls!vs/editor/contrib/gotoSymbol/browser/peek/referencesTree","vs/nls!vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget","vs/nls!vs/editor/contrib/gotoSymbol/browser/referencesModel","vs/nls!vs/editor/contrib/gotoSymbol/browser/symbolNavigation","vs/nls!vs/editor/contrib/hover/browser/hover","vs/nls!vs/editor/contrib/hover/browser/markdownHoverParticipant","vs/nls!vs/editor/contrib/hover/browser/markerHoverParticipant","vs/nls!vs/editor/contrib/inPlaceReplace/browser/inPlaceReplace","vs/nls!vs/editor/contrib/indentation/browser/indentation","vs/nls!vs/editor/contrib/inlineCompletions/browser/ghostTextController","vs/nls!vs/editor/contrib/inlineCompletions/browser/inlineCompletionsHoverParticipant","vs/nls!vs/editor/contrib/lineSelection/browser/lineSelection","vs/nls!vs/editor/contrib/linesOperations/browser/linesOperations","vs/nls!vs/editor/contrib/linkedEditing/browser/linkedEditing","vs/nls!vs/editor/contrib/links/browser/links","vs/nls!vs/editor/contrib/message/browser/messageController","vs/nls!vs/editor/contrib/multicursor/browser/multicursor","vs/nls!vs/editor/contrib/parameterHints/browser/parameterHints","vs/nls!vs/editor/contrib/parameterHints/browser/parameterHintsWidget","vs/nls!vs/editor/contrib/peekView/browser/peekView","vs/nls!vs/editor/contrib/quickAccess/browser/gotoLineQuickAccess","vs/nls!vs/editor/contrib/quickAccess/browser/gotoSymbolQuickAccess","vs/nls!vs/editor/contrib/rename/browser/rename","vs/nls!vs/editor/contrib/rename/browser/renameInputField","vs/nls!vs/editor/contrib/smartSelect/browser/smartSelect","vs/nls!vs/editor/contrib/snippet/browser/snippetController2","vs/nls!vs/editor/contrib/snippet/browser/snippetVariables","vs/nls!vs/editor/contrib/suggest/browser/suggest","vs/nls!vs/editor/contrib/suggest/browser/suggestController","vs/nls!vs/editor/contrib/suggest/browser/suggestWidget","vs/nls!vs/editor/contrib/suggest/browser/suggestWidgetDetails","vs/nls!vs/editor/contrib/suggest/browser/suggestWidgetRenderer","vs/nls!vs/editor/contrib/suggest/browser/suggestWidgetStatus","vs/nls!vs/editor/contrib/symbolIcons/browser/symbolIcons","vs/nls!vs/editor/contrib/toggleTabFocusMode/browser/toggleTabFocusMode","vs/nls!vs/editor/contrib/tokenization/browser/tokenization","vs/nls!vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter","vs/nls!vs/editor/contrib/unusualLineTerminators/browser/unusualLineTerminators","vs/nls!vs/editor/contrib/wordHighlighter/browser/wordHighlighter","vs/nls!vs/editor/contrib/wordOperations/browser/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/nls!vs/platform/workspaces/common/workspaces","vs/platform/editor/common/editor","vs/platform/extensions/common/extensions","vs/platform/history/browser/historyWidgetKeybindingHint","vs/platform/instantiation/common/graph","vs/editor/contrib/links/browser/getLinks","vs/editor/contrib/comment/browser/lineCommentCommand","vs/editor/contrib/linesOperations/browser/moveLinesCommand","vs/editor/contrib/parameterHints/browser/parameterHintsModel","vs/editor/contrib/suggest/browser/suggestAlternatives","vs/editor/contrib/suggest/browser/wordContextKey","vs/editor/browser/config/editorConfiguration","vs/platform/accessibility/browser/accessibilityService","vs/platform/contextkey/browser/contextKeyService","vs/platform/instantiation/common/instantiationService","vs/platform/keybinding/common/abstractKeybindingService","vs/platform/keybinding/common/baseResolvedKeybinding","vs/platform/keybinding/common/keybindingResolver","vs/platform/keybinding/common/usLayoutResolvedKeybinding","vs/platform/contextview/browser/contextViewService","vs/editor/browser/services/webWorker","vs/editor/contrib/documentSymbols/browser/documentSymbols","vs/platform/clipboard/browser/clipboardService","vs/editor/contrib/gotoError/browser/markerNavigationService","vs/platform/markers/common/markerService","vs/editor/browser/services/openerService","vs/platform/quickinput/browser/pickerQuickAccess","vs/editor/common/config/editorConfigurationSchema","vs/editor/common/services/getIconClasses","vs/editor/common/services/languagesRegistry","vs/editor/common/services/languageService","vs/editor/contrib/hover/browser/marginHover","vs/platform/configuration/common/configurationModels","vs/platform/history/browser/contextScopedHistoryWidget","vs/platform/quickinput/browser/helpQuickAccess","vs/editor/standalone/browser/quickAccess/standaloneHelpQuickAccess","vs/platform/quickinput/browser/quickAccess","vs/editor/contrib/codelens/browser/codeLensCache","vs/editor/contrib/suggest/browser/suggestMemory","vs/platform/quickinput/browser/commandsQuickAccess","vs/editor/contrib/quickAccess/browser/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/abstractCodeEditorService","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/model/bracketPairsTextModelPart/colorizedBracketPairsDecorationProvider","vs/editor/common/services/markerDecorationsService","vs/editor/contrib/codeAction/browser/lightBulbWidget","vs/editor/contrib/colorPicker/browser/colorPickerWidget","vs/editor/contrib/gotoSymbol/browser/peek/referencesTree","vs/editor/contrib/inlineCompletions/browser/ghostTextWidget","vs/editor/contrib/quickAccess/browser/gotoLineQuickAccess","vs/editor/contrib/quickAccess/browser/gotoSymbolQuickAccess","vs/editor/contrib/rename/browser/renameInputField","vs/editor/standalone/common/themes","vs/editor/browser/services/markerDecorations","vs/editor/contrib/anchorSelect/browser/anchorSelect","vs/editor/contrib/caretOperations/browser/caretOperations","vs/editor/contrib/clipboard/browser/clipboard","vs/editor/contrib/comment/browser/comment","vs/editor/contrib/contextmenu/browser/contextmenu","vs/editor/contrib/cursorUndo/browser/cursorUndo","vs/editor/contrib/editorState/browser/keybindingCancellation","vs/editor/contrib/codeAction/browser/codeActionMenu","vs/editor/contrib/codeAction/browser/codeActionModel","vs/editor/contrib/fontZoom/browser/fontZoom","vs/editor/contrib/format/browser/formatActions","vs/editor/contrib/gotoSymbol/browser/symbolNavigation","vs/editor/contrib/codeAction/browser/codeActionUi","vs/editor/contrib/codeAction/browser/codeActionContributions","vs/editor/contrib/rename/browser/rename","vs/editor/contrib/smartSelect/browser/smartSelect","vs/editor/contrib/tokenization/browser/tokenization","vs/editor/contrib/unusualLineTerminators/browser/unusualLineTerminators","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/browser/suggestWidgetStatus","vs/platform/actions/common/menuService","vs/platform/contextview/browser/contextMenuService","vs/platform/opener/browser/link","vs/platform/quickinput/browser/quickInput","vs/editor/standalone/browser/quickInput/standaloneQuickInputService","vs/platform/severityIcon/common/severityIcon","vs/editor/browser/widget/diffReview","vs/editor/contrib/parameterHints/browser/parameterHintsWidget","vs/editor/contrib/parameterHints/browser/parameterHints","vs/editor/contrib/suggest/browser/suggestWidgetRenderer","vs/editor/contrib/unicodeHighlighter/browser/bannerController","vs/platform/theme/browser/iconsStyleSheet","vs/editor/standalone/browser/standaloneThemeService","vs/editor/common/cursor/cursorColumnSelection","vs/editor/browser/view/viewController","vs/editor/browser/view/view","vs/editor/common/cursor/oneCursor","vs/editor/common/cursor/cursorCollection","vs/editor/common/viewModel/viewModelLines","vs/editor/common/viewModel/viewModelImpl","vs/editor/contrib/bracketMatching/browser/bracketMatching","vs/editor/contrib/caretOperations/browser/transpose","vs/editor/contrib/codelens/browser/codelensWidget","vs/editor/contrib/codelens/browser/codelensController","vs/editor/contrib/dnd/browser/dnd","vs/editor/contrib/find/browser/findDecorations","vs/editor/contrib/find/browser/findOptionsWidget","vs/editor/contrib/find/browser/findState","vs/editor/contrib/find/browser/findWidget","vs/editor/contrib/folding/browser/foldingDecorations","vs/editor/contrib/folding/browser/folding","vs/editor/contrib/hover/browser/colorHoverParticipant","vs/editor/contrib/inPlaceReplace/browser/inPlaceReplace","vs/editor/contrib/indentation/browser/indentation","vs/editor/contrib/lineSelection/browser/lineSelection","vs/editor/contrib/linesOperations/browser/linesOperations","vs/editor/contrib/linkedEditing/browser/linkedEditing","vs/editor/contrib/links/browser/links","vs/editor/contrib/multicursor/browser/multicursor","vs/editor/contrib/suggest/browser/suggestWidget","vs/editor/contrib/viewportSemanticTokens/browser/viewportSemanticTokens","vs/editor/contrib/wordHighlighter/browser/wordHighlighter","vs/editor/contrib/wordPartOperations/browser/wordPartOperations","vs/editor/contrib/zoneWidget/browser/zoneWidget","vs/editor/contrib/gotoError/browser/gotoErrorWidget","vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget","vs/editor/contrib/hover/browser/markerHoverParticipant","vs/editor/contrib/inlayHints/browser/inlayHintsLocations","vs/editor/contrib/inlayHints/browser/inlayHintsHover","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/browser/snippetVariables","vs/editor/contrib/suggest/browser/suggestModel","vs/editor/contrib/inlineCompletions/browser/suggestWidgetInlineCompletionProvider","vs/editor/contrib/inlineCompletions/browser/suggestWidgetPreviewModel","vs/editor/contrib/inlineCompletions/browser/ghostTextModel","vs/editor/contrib/inlineCompletions/browser/inlineCompletionsHoverParticipant","vs/editor/contrib/hover/browser/contentHover","vs/editor/contrib/colorPicker/browser/colorContributions","vs/editor/editor.all","vs/base/browser/dompurify/dompurify","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]; 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: false, 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 = {})); /*! @license DOMPurify 2.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.3.1/LICENSE */ function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var hasOwnProperty = Object.hasOwnProperty, setPrototypeOf = Object.setPrototypeOf, isFrozen = Object.isFrozen, getPrototypeOf = Object.getPrototypeOf, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var freeze = Object.freeze, seal = Object.seal, create = Object.create; // eslint-disable-line import/no-mutable-exports var _ref = typeof Reflect !== 'undefined' && Reflect, apply = _ref.apply, construct = _ref.construct; if (!apply) { apply = function apply(fun, thisValue, args) { return fun.apply(thisValue, args); }; } if (!freeze) { freeze = function freeze(x) { return x; }; } if (!seal) { seal = function seal(x) { return x; }; } if (!construct) { construct = function construct(Func, args) { return new (Function.prototype.bind.apply(Func, [null].concat(_toConsumableArray(args))))(); }; } var arrayForEach = unapply(Array.prototype.forEach); var arrayPop = unapply(Array.prototype.pop); var arrayPush = unapply(Array.prototype.push); var stringToLowerCase = unapply(String.prototype.toLowerCase); var stringMatch = unapply(String.prototype.match); var stringReplace = unapply(String.prototype.replace); var stringIndexOf = unapply(String.prototype.indexOf); var stringTrim = unapply(String.prototype.trim); var regExpTest = unapply(RegExp.prototype.test); var typeErrorCreate = unconstruct(TypeError); function unapply(func) { return function (thisArg) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return apply(func, thisArg, args); }; } function unconstruct(func) { return function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return construct(func, args); }; } /* Add properties to a lookup table */ function addToSet(set, array) { if (setPrototypeOf) { // Make 'in' and truthy checks like Boolean(set.constructor) // independent of any properties defined on Object.prototype. // Prevent prototype setters from intercepting set as a this value. setPrototypeOf(set, null); } var l = array.length; while (l--) { var element = array[l]; if (typeof element === 'string') { var lcElement = stringToLowerCase(element); if (lcElement !== element) { // Config presets (e.g. tags.js, attrs.js) are immutable. if (!isFrozen(array)) { array[l] = lcElement; } element = lcElement; } } set[element] = true; } return set; } /* Shallow clone an object */ function clone(object) { var newObject = create(null); var property = void 0; for (property in object) { if (apply(hasOwnProperty, object, [property])) { newObject[property] = object[property]; } } return newObject; } /* IE10 doesn't support __lookupGetter__ so lets' * simulate it. It also automatically checks * if the prop is function or getter and behaves * accordingly. */ function lookupGetter(object, prop) { while (object !== null) { var desc = getOwnPropertyDescriptor(object, prop); if (desc) { if (desc.get) { return unapply(desc.get); } if (typeof desc.value === 'function') { return unapply(desc.value); } } object = getPrototypeOf(object); } function fallbackValue(element) { console.warn('fallback value for', element); return null; } return fallbackValue; } var html = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); // SVG var svg = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']); var svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); // List of SVG elements that are disallowed by default. // We still need to know them so that we can do namespace // checks properly in case one wants to add them to // allow-list. var svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'fedropshadow', 'feimage', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']); var mathMl = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover']); // Similarly to SVG, we want to know all MathML elements, // even those that we disallow by default. var mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']); var text = freeze(['#text']); var html$1 = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']); var svg$1 = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'targetx', 'targety', 'transform', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']); var mathMl$1 = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']); var xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']); // eslint-disable-next-line unicorn/better-regex var MUSTACHE_EXPR = seal(/\{\{[\s\S]*|[\s\S]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode var ERB_EXPR = seal(/<%[\s\S]*|[\s\S]*%>/gm); var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape var ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape ); var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex ); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function _toConsumableArray$1(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var getGlobal = function getGlobal() { return typeof window === 'undefined' ? null : window; }; /** * Creates a no-op policy for internal use only. * Don't export this function outside this module! * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory. * @param {Document} document The document object (to determine policy name suffix) * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types * are not supported). */ var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) { if ((typeof trustedTypes === 'undefined' ? 'undefined' : _typeof(trustedTypes)) !== 'object' || typeof trustedTypes.createPolicy !== 'function') { return null; } // Allow the callers to control the unique policy name // by adding a data-tt-policy-suffix to the script element with the DOMPurify. // Policy creation with duplicate names throws in Trusted Types. var suffix = null; var ATTR_NAME = 'data-tt-policy-suffix'; if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) { suffix = document.currentScript.getAttribute(ATTR_NAME); } var policyName = 'dompurify' + (suffix ? '#' + suffix : ''); try { return trustedTypes.createPolicy(policyName, { createHTML: function createHTML(html$$1) { return html$$1; } }); } catch (_) { // Policy creation failed (most likely another DOMPurify script has // already run). Skip creating the policy, as this will only cause errors // if TT are enforced. console.warn('TrustedTypes policy ' + policyName + ' could not be created.'); return null; } }; function createDOMPurify() { var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal(); var DOMPurify = function DOMPurify(root) { return createDOMPurify(root); }; /** * Version label, exposed for easier checks * if DOMPurify is up to date or not */ DOMPurify.version = '2.3.1'; /** * Array of elements that DOMPurify removed during sanitation. * Empty if nothing was removed. */ DOMPurify.removed = []; if (!window || !window.document || window.document.nodeType !== 9) { // Not running in a browser, provide a factory function // so that you can pass your own Window DOMPurify.isSupported = false; return DOMPurify; } var originalDocument = window.document; var document = window.document; var DocumentFragment = window.DocumentFragment, HTMLTemplateElement = window.HTMLTemplateElement, Node = window.Node, Element = window.Element, NodeFilter = window.NodeFilter, _window$NamedNodeMap = window.NamedNodeMap, NamedNodeMap = _window$NamedNodeMap === undefined ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap, Text = window.Text, Comment = window.Comment, DOMParser = window.DOMParser, trustedTypes = window.trustedTypes; var ElementPrototype = Element.prototype; var cloneNode = lookupGetter(ElementPrototype, 'cloneNode'); var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling'); var getChildNodes = lookupGetter(ElementPrototype, 'childNodes'); var getParentNode = lookupGetter(ElementPrototype, 'parentNode'); // As per issue #47, the web-components registry is inherited by a // new document created via createHTMLDocument. As per the spec // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries) // a new empty registry is used when creating a template contents owner // document, so we use that as our parent document to ensure nothing // is inherited. if (typeof HTMLTemplateElement === 'function') { var template = document.createElement('template'); if (template.content && template.content.ownerDocument) { document = template.content.ownerDocument; } } var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument); var emptyHTML = trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML('') : ''; var _document = document, implementation = _document.implementation, createNodeIterator = _document.createNodeIterator, createDocumentFragment = _document.createDocumentFragment, getElementsByTagName = _document.getElementsByTagName; var importNode = originalDocument.importNode; var documentMode = {}; try { documentMode = clone(document).documentMode ? document.documentMode : {}; } catch (_) {} var hooks = {}; /** * Expose whether this browser supports running the full DOMPurify. */ DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9; var MUSTACHE_EXPR$$1 = MUSTACHE_EXPR, ERB_EXPR$$1 = ERB_EXPR, DATA_ATTR$$1 = DATA_ATTR, ARIA_ATTR$$1 = ARIA_ATTR, IS_SCRIPT_OR_DATA$$1 = IS_SCRIPT_OR_DATA, ATTR_WHITESPACE$$1 = ATTR_WHITESPACE; var IS_ALLOWED_URI$$1 = IS_ALLOWED_URI; /** * We consider the elements and attributes below to be safe. Ideally * don't add any new ones but feel free to remove unwanted ones. */ /* allowed element names */ var ALLOWED_TAGS = null; var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(html), _toConsumableArray$1(svg), _toConsumableArray$1(svgFilters), _toConsumableArray$1(mathMl), _toConsumableArray$1(text))); /* Allowed attribute names */ var ALLOWED_ATTR = null; var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray$1(html$1), _toConsumableArray$1(svg$1), _toConsumableArray$1(mathMl$1), _toConsumableArray$1(xml))); /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */ var FORBID_TAGS = null; /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */ var FORBID_ATTR = null; /* Decide if ARIA attributes are okay */ var ALLOW_ARIA_ATTR = true; /* Decide if custom data attributes are okay */ var ALLOW_DATA_ATTR = true; /* Decide if unknown protocols are okay */ var ALLOW_UNKNOWN_PROTOCOLS = false; /* Output should be safe for common template engines. * This means, DOMPurify removes data attributes, mustaches and ERB */ var SAFE_FOR_TEMPLATES = false; /* Decide if document with ... should be returned */ var WHOLE_DOCUMENT = false; /* Track whether config is already set on this instance of DOMPurify. */ var SET_CONFIG = false; /* Decide if all elements (e.g. style, script) must be children of * document.body. By default, browsers might move them to document.head */ var FORCE_BODY = false; /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html * string (or a TrustedHTML object if Trusted Types are supported). * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead */ var RETURN_DOM = false; /* Decide if a DOM `DocumentFragment` should be returned, instead of a html * string (or a TrustedHTML object if Trusted Types are supported) */ var RETURN_DOM_FRAGMENT = false; /* If `RETURN_DOM` or `RETURN_DOM_FRAGMENT` is enabled, decide if the returned DOM * `Node` is imported into the current `Document`. If this flag is not enabled the * `Node` will belong (its ownerDocument) to a fresh `HTMLDocument`, created by * DOMPurify. * * This defaults to `true` starting DOMPurify 2.2.0. Note that setting it to `false` * might cause XSS from attacks hidden in closed shadowroots in case the browser * supports Declarative Shadow: DOM https://web.dev/declarative-shadow-dom/ */ var RETURN_DOM_IMPORT = true; /* Try to return a Trusted Type object instead of a string, return a string in * case Trusted Types are not supported */ var RETURN_TRUSTED_TYPE = false; /* Output should be free from DOM clobbering attacks? */ var SANITIZE_DOM = true; /* Keep element content when removing element? */ var KEEP_CONTENT = true; /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead * of importing it into a new Document and returning a sanitized copy */ var IN_PLACE = false; /* Allow usage of profiles like html, svg and mathMl */ var USE_PROFILES = {}; /* Tags to ignore content of when KEEP_CONTENT is true */ var FORBID_CONTENTS = null; var DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']); /* Tags that are safe for data: URIs */ var DATA_URI_TAGS = null; var DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']); /* Attributes safe for values like "javascript:" */ var URI_SAFE_ATTRIBUTES = null; var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']); var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; /* Document namespace */ var NAMESPACE = HTML_NAMESPACE; var IS_EMPTY_INPUT = false; /* Keep a reference to config to pass to hooks */ var CONFIG = null; /* Ideally, do not touch anything below this line */ /* ______________________________________________ */ var formElement = document.createElement('form'); /** * _parseConfig * * @param {Object} cfg optional config literal */ // eslint-disable-next-line complexity var _parseConfig = function _parseConfig(cfg) { if (CONFIG && CONFIG === cfg) { return; } /* Shield configuration object from tampering */ if (!cfg || (typeof cfg === 'undefined' ? 'undefined' : _typeof(cfg)) !== 'object') { cfg = {}; } /* Shield configuration object from prototype pollution */ cfg = clone(cfg); /* Set configuration parameters */ ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS; ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR; URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES; DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS; FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS) : DEFAULT_FORBID_CONTENTS; FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS) : {}; FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR) : {}; USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false; ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false RETURN_DOM = cfg.RETURN_DOM || false; // Default false RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false RETURN_DOM_IMPORT = cfg.RETURN_DOM_IMPORT !== false; // Default true RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false FORCE_BODY = cfg.FORCE_BODY || false; // Default false SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true IN_PLACE = cfg.IN_PLACE || false; // Default false IS_ALLOWED_URI$$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$$1; NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE; if (SAFE_FOR_TEMPLATES) { ALLOW_DATA_ATTR = false; } if (RETURN_DOM_FRAGMENT) { RETURN_DOM = true; } /* Parse profile info */ if (USE_PROFILES) { ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(text))); ALLOWED_ATTR = []; if (USE_PROFILES.html === true) { addToSet(ALLOWED_TAGS, html); addToSet(ALLOWED_ATTR, html$1); } if (USE_PROFILES.svg === true) { addToSet(ALLOWED_TAGS, svg); addToSet(ALLOWED_ATTR, svg$1); addToSet(ALLOWED_ATTR, xml); } if (USE_PROFILES.svgFilters === true) { addToSet(ALLOWED_TAGS, svgFilters); addToSet(ALLOWED_ATTR, svg$1); addToSet(ALLOWED_ATTR, xml); } if (USE_PROFILES.mathMl === true) { addToSet(ALLOWED_TAGS, mathMl); addToSet(ALLOWED_ATTR, mathMl$1); addToSet(ALLOWED_ATTR, xml); } } /* Merge configuration parameters */ if (cfg.ADD_TAGS) { if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { ALLOWED_TAGS = clone(ALLOWED_TAGS); } addToSet(ALLOWED_TAGS, cfg.ADD_TAGS); } if (cfg.ADD_ATTR) { if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { ALLOWED_ATTR = clone(ALLOWED_ATTR); } addToSet(ALLOWED_ATTR, cfg.ADD_ATTR); } if (cfg.ADD_URI_SAFE_ATTR) { addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR); } if (cfg.FORBID_CONTENTS) { if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { FORBID_CONTENTS = clone(FORBID_CONTENTS); } addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS); } /* Add #text in case KEEP_CONTENT is set to true */ if (KEEP_CONTENT) { ALLOWED_TAGS['#text'] = true; } /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */ if (WHOLE_DOCUMENT) { addToSet(ALLOWED_TAGS, ['html', 'head', 'body']); } /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */ if (ALLOWED_TAGS.table) { addToSet(ALLOWED_TAGS, ['tbody']); delete FORBID_TAGS.tbody; } // Prevent further manipulation of configuration. // Not available in IE8, Safari 5, etc. if (freeze) { freeze(cfg); } CONFIG = cfg; }; var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); var HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']); /* Keep track of all possible SVG and MathML tags * so that we can perform the namespace checks * correctly. */ var ALL_SVG_TAGS = addToSet({}, svg); addToSet(ALL_SVG_TAGS, svgFilters); addToSet(ALL_SVG_TAGS, svgDisallowed); var ALL_MATHML_TAGS = addToSet({}, mathMl); addToSet(ALL_MATHML_TAGS, mathMlDisallowed); /** * * * @param {Element} element a DOM element whose namespace is being checked * @returns {boolean} Return false if the element has a * namespace that a spec-compliant parser would never * return. Return true otherwise. */ var _checkValidNamespace = function _checkValidNamespace(element) { var parent = getParentNode(element); // In JSDOM, if we're inside shadow DOM, then parentNode // can be null. We just simulate parent in this case. if (!parent || !parent.tagName) { parent = { namespaceURI: HTML_NAMESPACE, tagName: 'template' }; } var tagName = stringToLowerCase(element.tagName); var parentTagName = stringToLowerCase(parent.tagName); if (element.namespaceURI === SVG_NAMESPACE) { // The only way to switch from HTML namespace to SVG // is via . If it happens via any other tag, then // it should be killed. if (parent.namespaceURI === HTML_NAMESPACE) { return tagName === 'svg'; } // The only way to switch from MathML to SVG is via // svg if parent is either or MathML // text integration points. if (parent.namespaceURI === MATHML_NAMESPACE) { return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); } // We only allow elements that are defined in SVG // spec. All others are disallowed in SVG namespace. return Boolean(ALL_SVG_TAGS[tagName]); } if (element.namespaceURI === MATHML_NAMESPACE) { // The only way to switch from HTML namespace to MathML // is via . If it happens via any other tag, then // it should be killed. if (parent.namespaceURI === HTML_NAMESPACE) { return tagName === 'math'; } // The only way to switch from SVG to MathML is via // and HTML integration points if (parent.namespaceURI === SVG_NAMESPACE) { return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName]; } // We only allow elements that are defined in MathML // spec. All others are disallowed in MathML namespace. return Boolean(ALL_MATHML_TAGS[tagName]); } if (element.namespaceURI === HTML_NAMESPACE) { // The only way to switch from SVG to HTML is via // HTML integration points, and from MathML to HTML // is via MathML text integration points if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) { return false; } if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) { return false; } // Certain elements are allowed in both SVG and HTML // namespace. We need to specify them explicitly // so that they don't get erronously deleted from // HTML namespace. var commonSvgAndHTMLElements = addToSet({}, ['title', 'style', 'font', 'a', 'script']); // We disallow tags that are specific for MathML // or SVG and should never appear in HTML namespace return !ALL_MATHML_TAGS[tagName] && (commonSvgAndHTMLElements[tagName] || !ALL_SVG_TAGS[tagName]); } // The code should never reach this place (this means // that the element somehow got namespace that is not // HTML, SVG or MathML). Return false just in case. return false; }; /** * _forceRemove * * @param {Node} node a DOM node */ var _forceRemove = function _forceRemove(node) { arrayPush(DOMPurify.removed, { element: node }); try { // eslint-disable-next-line unicorn/prefer-dom-node-remove node.parentNode.removeChild(node); } catch (_) { try { node.outerHTML = emptyHTML; } catch (_) { node.remove(); } } }; /** * _removeAttribute * * @param {String} name an Attribute name * @param {Node} node a DOM node */ var _removeAttribute = function _removeAttribute(name, node) { try { arrayPush(DOMPurify.removed, { attribute: node.getAttributeNode(name), from: node }); } catch (_) { arrayPush(DOMPurify.removed, { attribute: null, from: node }); } node.removeAttribute(name); // We void attribute values for unremovable "is"" attributes if (name === 'is' && !ALLOWED_ATTR[name]) { if (RETURN_DOM || RETURN_DOM_FRAGMENT) { try { _forceRemove(node); } catch (_) {} } else { try { node.setAttribute(name, ''); } catch (_) {} } } }; /** * _initDocument * * @param {String} dirty a string of dirty markup * @return {Document} a DOM, filled with the dirty markup */ var _initDocument = function _initDocument(dirty) { /* Create a HTML document */ var doc = void 0; var leadingWhitespace = void 0; if (FORCE_BODY) { dirty = '' + dirty; } else { /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */ var matches = stringMatch(dirty, /^[\r\n\t ]+/); leadingWhitespace = matches && matches[0]; } var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty; /* * Use the DOMParser API by default, fallback later if needs be * DOMParser not work for svg when has multiple root element. */ if (NAMESPACE === HTML_NAMESPACE) { try { doc = new DOMParser().parseFromString(dirtyPayload, 'text/html'); } catch (_) {} } /* Use createHTMLDocument in case DOMParser is not available */ if (!doc || !doc.documentElement) { doc = implementation.createDocument(NAMESPACE, 'template', null); try { doc.documentElement.innerHTML = IS_EMPTY_INPUT ? '' : dirtyPayload; } catch (_) { // Syntax error if dirtyPayload is invalid xml } } var body = doc.body || doc.documentElement; if (dirty && leadingWhitespace) { body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null); } /* Work on whole document or just its body */ if (NAMESPACE === HTML_NAMESPACE) { return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0]; } return WHOLE_DOCUMENT ? doc.documentElement : body; }; /** * _createIterator * * @param {Document} root document/fragment to create iterator for * @return {Iterator} iterator instance */ var _createIterator = function _createIterator(root) { return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false); }; /** * _isClobbered * * @param {Node} elm element to check for clobbering attacks * @return {Boolean} true if clobbered, false if safe */ var _isClobbered = function _isClobbered(elm) { if (elm instanceof Text || elm instanceof Comment) { return false; } if (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function') { return true; } return false; }; /** * _isNode * * @param {Node} obj object to check whether it's a DOM node * @return {Boolean} true is object is a DOM node */ var _isNode = function _isNode(object) { return (typeof Node === 'undefined' ? 'undefined' : _typeof(Node)) === 'object' ? object instanceof Node : object && (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string'; }; /** * _executeHook * Execute user configurable hooks * * @param {String} entryPoint Name of the hook's entry point * @param {Node} currentNode node to work on with the hook * @param {Object} data additional hook parameters */ var _executeHook = function _executeHook(entryPoint, currentNode, data) { if (!hooks[entryPoint]) { return; } arrayForEach(hooks[entryPoint], function (hook) { hook.call(DOMPurify, currentNode, data, CONFIG); }); }; /** * _sanitizeElements * * @protect nodeName * @protect textContent * @protect removeChild * * @param {Node} currentNode to check for permission to exist * @return {Boolean} true if node was killed, false if left alive */ var _sanitizeElements = function _sanitizeElements(currentNode) { var content = void 0; /* Execute a hook if present */ _executeHook('beforeSanitizeElements', currentNode, null); /* Check if element is clobbered or can clobber */ if (_isClobbered(currentNode)) { _forceRemove(currentNode); return true; } /* Check if tagname contains Unicode */ if (stringMatch(currentNode.nodeName, /[\u0080-\uFFFF]/)) { _forceRemove(currentNode); return true; } /* Now let's check the element's type and name */ var tagName = stringToLowerCase(currentNode.nodeName); /* Execute a hook if present */ _executeHook('uponSanitizeElement', currentNode, { tagName: tagName, allowedTags: ALLOWED_TAGS }); /* Detect mXSS attempts abusing namespace confusion */ if (!_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) { _forceRemove(currentNode); return true; } /* Mitigate a problem with templates inside select */ if (tagName === 'select' && regExpTest(/
' + (escaped ? _code : escape(_code, true)) + '
\n'; } return '
' + (escaped ? _code : escape(_code, true)) + '
\n'; }; _proto.blockquote = function blockquote(quote) { return '
\n' + quote + '
\n'; }; _proto.html = function html(_html) { return _html; }; _proto.heading = function heading(text, level, raw, slugger) { if (this.options.headerIds) { return '' + text + '\n'; } // ignore IDs return '' + text + '\n'; }; _proto.hr = function hr() { return this.options.xhtml ? '
\n' : '
\n'; }; _proto.list = function list(body, ordered, start) { var type = ordered ? 'ol' : 'ul', startatt = ordered && start !== 1 ? ' start="' + start + '"' : ''; return '<' + type + startatt + '>\n' + body + '\n'; }; _proto.listitem = function listitem(text) { return '
  • ' + text + '
  • \n'; }; _proto.checkbox = function checkbox(checked) { return ' '; }; _proto.paragraph = function paragraph(text) { return '

    ' + text + '

    \n'; }; _proto.table = function table(header, body) { if (body) body = '' + body + ''; return '\n' + '\n' + header + '\n' + body + '
    \n'; }; _proto.tablerow = function tablerow(content) { return '\n' + content + '\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 + '\n'; } // span level renderer ; _proto.strong = function strong(text) { return '' + text + ''; }; _proto.em = function em(text) { return '' + text + ''; }; _proto.codespan = function codespan(text) { return '' + text + ''; }; _proto.br = function br() { return this.options.xhtml ? '
    ' : '
    '; }; _proto.del = function del(text) { return '' + text + ''; }; _proto.link = function link(href, title, text) { href = cleanUrl(this.options.sanitize, this.options.baseUrl, href); if (href === null) { return text; } var out = ''; return out; }; _proto.image = function image(href, title, text) { href = cleanUrl(this.options.sanitize, this.options.baseUrl, href); if (href === null) { return text; } var out = '' + text + '' : '>'; return out; }; _proto.text = function text(_text) { return _text; }; return Renderer; }(); /** * TextRenderer * returns only the textual part of the token */ var TextRenderer = /*#__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 = /*#__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; }(); /** * Parsing & Compiling */ var Parser = /*#__PURE__*/function () { function Parser(options) { this.options = options || exports.defaults; this.options.renderer = this.options.renderer || new Renderer(); this.renderer = this.options.renderer; this.renderer.options = this.options; this.textRenderer = new TextRenderer(); this.slugger = new Slugger(); } /** * 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, ret; var l = tokens.length; for (i = 0; i < l; i++) { token = tokens[i]; // Run any renderer extensions if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) { ret = this.options.extensions.renderers[token.type].call({ parser: this }, token); if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'paragraph', 'text'].includes(token.type)) { out += ret || ''; continue; } } 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(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.header[j].tokens), { header: true, align: token.align[j] }); } header += this.renderer.tablerow(cell); body = ''; l2 = token.rows.length; for (j = 0; j < l2; j++) { row = token.rows[j]; cell = ''; l3 = row.length; for (k = 0; k < l3; k++) { cell += this.renderer.tablecell(this.parseInline(row[k].tokens), { 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 === 'paragraph') { item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text; } } else { item.tokens.unshift({ type: 'text', 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, ret; var l = tokens.length; for (i = 0; i < l; i++) { token = tokens[i]; // Run any renderer extensions if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) { ret = this.options.extensions.renderers[token.type].call({ parser: this }, token); if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(token.type)) { out += ret || ''; continue; } } 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; }(); /** * 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({}, marked.defaults, opt || {}); checkSanitizeDeprecation(opt); if (callback) { var highlight = opt.highlight; var tokens; try { tokens = Lexer.lex(src, opt); } catch (e) { return callback(e); } var done = function done(err) { var out; if (!err) { try { if (opt.walkTokens) { marked.walkTokens(tokens, opt.walkTokens); } out = Parser.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.lex(src, opt); if (opt.walkTokens) { marked.walkTokens(_tokens, opt.walkTokens); } return Parser.parse(_tokens, opt); } catch (e) { e.message += '\nPlease report this to https://github.com/markedjs/marked.'; if (opt.silent) { return '

    An error occurred:

    ' + escape(e.message + '', true) + '
    '; } throw e; } } /** * Options */ marked.options = marked.setOptions = function (opt) { merge(marked.defaults, opt); changeDefaults(marked.defaults); return marked; }; marked.getDefaults = getDefaults; marked.defaults = exports.defaults; /** * Use Extension */ marked.use = function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var opts = merge.apply(void 0, [{}].concat(args)); var extensions = marked.defaults.extensions || { renderers: {}, childTokens: {} }; var hasExtensions; args.forEach(function (pack) { // ==-- Parse "addon" extensions --== // if (pack.extensions) { hasExtensions = true; pack.extensions.forEach(function (ext) { if (!ext.name) { throw new Error('extension name required'); } if (ext.renderer) { // Renderer extensions var prevRenderer = extensions.renderers ? extensions.renderers[ext.name] : null; if (prevRenderer) { // Replace extension with func to run new extension but fall back if false extensions.renderers[ext.name] = function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } var ret = ext.renderer.apply(this, args); if (ret === false) { ret = prevRenderer.apply(this, args); } return ret; }; } else { extensions.renderers[ext.name] = ext.renderer; } } if (ext.tokenizer) { // Tokenizer Extensions if (!ext.level || ext.level !== 'block' && ext.level !== 'inline') { throw new Error("extension level must be 'block' or 'inline'"); } if (extensions[ext.level]) { extensions[ext.level].unshift(ext.tokenizer); } else { extensions[ext.level] = [ext.tokenizer]; } if (ext.start) { // Function to check for start of token if (ext.level === 'block') { if (extensions.startBlock) { extensions.startBlock.push(ext.start); } else { extensions.startBlock = [ext.start]; } } else if (ext.level === 'inline') { if (extensions.startInline) { extensions.startInline.push(ext.start); } else { extensions.startInline = [ext.start]; } } } } if (ext.childTokens) { // Child tokens to be visited by walkTokens extensions.childTokens[ext.name] = ext.childTokens; } }); } // ==-- Parse "overwrite" extensions --== // if (pack.renderer) { (function () { var renderer = marked.defaults.renderer || new Renderer(); var _loop = function _loop(prop) { var prevRenderer = renderer[prop]; // Replace renderer with func to run extension, but fall back if false renderer[prop] = function () { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } var ret = pack.renderer[prop].apply(renderer, args); if (ret === false) { ret = prevRenderer.apply(renderer, args); } return ret; }; }; for (var prop in pack.renderer) { _loop(prop); } opts.renderer = renderer; })(); } if (pack.tokenizer) { (function () { var tokenizer = marked.defaults.tokenizer || new Tokenizer(); var _loop2 = function _loop2(prop) { var prevTokenizer = tokenizer[prop]; // Replace tokenizer with func to run extension, but fall back if false tokenizer[prop] = function () { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } var ret = pack.tokenizer[prop].apply(tokenizer, args); if (ret === false) { ret = prevTokenizer.apply(tokenizer, args); } return ret; }; }; for (var prop in pack.tokenizer) { _loop2(prop); } opts.tokenizer = tokenizer; })(); } // ==-- Parse WalkTokens extensions --== // if (pack.walkTokens) { var _walkTokens = marked.defaults.walkTokens; opts.walkTokens = function (token) { pack.walkTokens.call(this, token); if (_walkTokens) { _walkTokens.call(this, token); } }; } if (hasExtensions) { opts.extensions = extensions; } marked.setOptions(opts); }); }; /** * Run callback for every token */ marked.walkTokens = function (tokens, callback) { var _loop3 = function _loop3() { var token = _step.value; callback.call(marked, token); switch (token.type) { case 'table': { for (var _iterator2 = _createForOfIteratorHelperLoose(token.header), _step2; !(_step2 = _iterator2()).done;) { var cell = _step2.value; marked.walkTokens(cell.tokens, callback); } for (var _iterator3 = _createForOfIteratorHelperLoose(token.rows), _step3; !(_step3 = _iterator3()).done;) { var row = _step3.value; for (var _iterator4 = _createForOfIteratorHelperLoose(row), _step4; !(_step4 = _iterator4()).done;) { var _cell = _step4.value; marked.walkTokens(_cell.tokens, callback); } } break; } case 'list': { marked.walkTokens(token.items, callback); break; } default: { if (marked.defaults.extensions && marked.defaults.extensions.childTokens && marked.defaults.extensions.childTokens[token.type]) { // Walk any extensions marked.defaults.extensions.childTokens[token.type].forEach(function (childTokens) { marked.walkTokens(token[childTokens], callback); }); } else if (token.tokens) { marked.walkTokens(token.tokens, callback); } } } }; for (var _iterator = _createForOfIteratorHelperLoose(tokens), _step; !(_step = _iterator()).done;) { _loop3(); } }; /** * 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({}, marked.defaults, opt || {}); checkSanitizeDeprecation(opt); try { var tokens = Lexer.lexInline(src, opt); if (opt.walkTokens) { marked.walkTokens(tokens, opt.walkTokens); } return Parser.parseInline(tokens, opt); } catch (e) { e.message += '\nPlease report this to https://github.com/markedjs/marked.'; if (opt.silent) { return '

    An error occurred:

    ' + escape(e.message + '', true) + '
    '; } throw e; } }; /** * Expose */ marked.Parser = Parser; marked.parser = Parser.parse; marked.Renderer = Renderer; marked.TextRenderer = TextRenderer; marked.Lexer = Lexer; marked.lexer = Lexer.lex; marked.Tokenizer = Tokenizer; marked.Slugger = Slugger; marked.parse = marked; var options = marked.options; var setOptions = marked.setOptions; var use = marked.use; var walkTokens = marked.walkTokens; var parseInline = marked.parseInline; var parse = marked; var parser = Parser.parse; var lexer = Lexer.lex; exports.Lexer = Lexer; exports.Parser = Parser; exports.Renderer = Renderer; exports.Slugger = Slugger; exports.TextRenderer = TextRenderer; exports.Tokenizer = Tokenizer; exports.getDefaults = getDefaults; exports.lexer = lexer; exports.marked = marked; exports.options = options; exports.parse = parse; exports.parseInline = parseInline; exports.parser = parser; exports.setOptions = setOptions; exports.use = use; exports.walkTokens = walkTokens; Object.defineProperty(exports, '__esModule', { value: true }); })); // ESM-uncomment-begin // })(); // export var marked = (__marked_exports || exports); // ESM-uncomment-end define(__m[135/*vs/base/common/mime*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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.latex = 'text/latex'; })(Mimes = exports.Mimes || (exports.Mimes = {})); }); define(__m[164/*vs/base/browser/dnd*/], __M([1/*require*/,0/*exports*/,135/*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 }; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[312/*vs/base/common/navigator*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ArrayNavigator = void 0; class ArrayNavigator { constructor(items, start = 0, end = items.length, index = start - 1) { this.items = items; this.start = start; this.end = end; this.index = index; } current() { if (this.index === this.start - 1 || this.index === this.end) { return null; } return this.items[this.index]; } next() { this.index = Math.min(this.index + 1, this.end); return this.current(); } previous() { this.index = Math.max(this.index - 1, this.start - 1); return this.current(); } first() { this.index = this.start; return this.current(); } last() { this.index = this.end - 1; return this.current(); } } exports.ArrayNavigator = ArrayNavigator; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[313/*vs/base/common/history*/], __M([1/*require*/,0/*exports*/,312/*vs/base/common/navigator*/]), function (require, exports, navigator_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HistoryNavigator = void 0; class HistoryNavigator { constructor(history = [], limit = 10) { this._initialize(history); this._limit = limit; this._onChange(); } getHistory() { return this._elements; } add(t) { this._history.delete(t); this._history.add(t); this._onChange(); } next() { 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[111/*vs/base/common/numbers*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SlidingWindowAverage = 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._val; } get value() { return this._val; } } exports.MovingAverage = MovingAverage; class SlidingWindowAverage { constructor(size) { this._n = 0; this._val = 0; this._values = []; this._index = 0; this._sum = 0; this._values = new Array(size); this._values.fill(0, 0, size); } update(value) { const oldValue = this._values[this._index]; this._values[this._index] = value; this._index = (this._index + 1) % this._values.length; this._sum -= oldValue; this._sum += value; if (this._n < this._values.length) { this._n += 1; } this._val = this._sum / this._n; return this._val; } get value() { return this._val; } } exports.SlidingWindowAverage = SlidingWindowAverage; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[17/*vs/base/common/platform*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; var _a; Object.defineProperty(exports, "__esModule", { value: true }); exports.isAndroid = exports.isEdge = exports.isSafari = exports.isFirefox = exports.isChrome = exports.isLittleEndian = exports.OS = exports.setTimeout0 = exports.language = exports.userAgent = exports.isIOS = exports.isWeb = exports.isNative = exports.isLinux = exports.isMacintosh = exports.isWindows = 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 _isElectron = 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 isElectronProcess = typeof ((_a = nodeProcess === null || nodeProcess === void 0 ? void 0 : nodeProcess.versions) === null || _a === void 0 ? void 0 : _a.electron) === 'string'; const isElectronRenderer = isElectronProcess && (nodeProcess === null || nodeProcess === void 0 ? void 0 : nodeProcess.type) === 'renderer'; // 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']; _isElectron = isElectronProcess; _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; /** * The language used for the user interface. The format of * the string is all lower case (e.g. zh-tw for Traditional * Chinese) */ exports.language = _language; /** * See https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#:~:text=than%204%2C%20then-,set%20timeout%20to%204,-. * * Works similarly to `setTimeout(0)` but doesn't suffer from the 4ms artificial delay * that browsers set when the nesting level is > 5. */ exports.setTimeout0 = (() => { if (typeof exports.globals.postMessage === 'function' && !exports.globals.importScripts) { let pending = []; exports.globals.addEventListener('message', (e) => { if (e.data && e.data.vscodeScheduleAsyncWork) { for (let i = 0, len = pending.length; i < len; i++) { const candidate = pending[i]; if (candidate.id === e.data.vscodeScheduleAsyncWork) { pending.splice(i, 1); candidate.callback(); return; } } } }); let lastId = 0; return (callback) => { const myId = ++lastId; pending.push({ id: myId, callback: callback }); exports.globals.postMessage({ vscodeScheduleAsyncWork: myId }, '*'); }; } return (callback) => setTimeout(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; exports.isChrome = !!(exports.userAgent && exports.userAgent.indexOf('Chrome') >= 0); exports.isFirefox = !!(exports.userAgent && exports.userAgent.indexOf('Firefox') >= 0); exports.isSafari = !!(!exports.isChrome && (exports.userAgent && exports.userAgent.indexOf('Safari') >= 0)); exports.isEdge = !!(exports.userAgent && exports.userAgent.indexOf('Edg/') >= 0); exports.isAndroid = !!(exports.userAgent && exports.userAgent.indexOf('Android') >= 0); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[314/*vs/base/common/process*/], __M([1/*require*/,0/*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 arch() { return sandboxProcess.arch; }, get env() { return sandboxProcess.env; }, cwd() { return sandboxProcess.cwd(); } }; } // Native node.js environment else if (typeof process !== 'undefined') { safeProcess = { get platform() { return process.platform; }, get arch() { return process.arch; }, get env() { return process.env; }, cwd() { return process.env['VSCODE_CWD'] || process.cwd(); } }; } // Web environment else { safeProcess = { // Supported get platform() { return platform_1.isWindows ? 'win32' : platform_1.isMacintosh ? 'darwin' : 'linux'; }, get arch() { return undefined; /* arch is undefined in web */ }, // Unsupported get env() { return {}; }, cwd() { return '/'; } }; } /** * Provides safe access to the `cwd` property in node.js, sandboxed or web * environments. * * Note: in web, this property is hardcoded to be `/`. */ 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[82/*vs/base/common/path*/], __M([1/*require*/,0/*exports*/,314/*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 a UNC path then. // // This step is skipped when it is very clear that the user actually // intended to point at a UNC path. This is assumed when the first // non-empty string arguments starts with exactly two slashes followed by // at least one more non-slash character. // // Note that for normalize() to treat a path as a UNC path it needs to // have at least 2 components, so we don't filter for that here. // This means that the user can use join to construct UNC paths from // a server name and a share name; for example: // path.join('//server', 'share') -> '\\\\server\\share\\') let needsReplace = true; let slashCount = 0; if (typeof firstPart === 'string' && isPathSeparator(firstPart.charCodeAt(0))) { ++slashCount; const firstLen = firstPart.length; if (firstLen > 1 && isPathSeparator(firstPart.charCodeAt(1))) { ++slashCount; if (firstLen > 2) { if (isPathSeparator(firstPart.charCodeAt(2))) { ++slashCount; } else { // We matched a UNC path in the first part needsReplace = false; } } } } if (needsReplace) { // Find any more consecutive slashes we need to replace while (slashCount < joined.length && isPathSeparator(joined.charCodeAt(slashCount))) { slashCount++; } // Replace the slashes if needed if (slashCount >= 2) { joined = `\\${joined.slice(slashCount)}`; } } return exports.win32.normalize(joined); }, // It will solve the relative path from `from` to `to`, for instance: // from = 'C:\\orandea\\test\\aaa' // to = 'C:\\orandea\\impl\\bbb' // The output of the function should be: '..\\..\\impl\\bbb' relative(from, to) { validateString(from, 'from'); validateString(to, 'to'); if (from === to) { return ''; } const fromOrig = exports.win32.resolve(from); const toOrig = exports.win32.resolve(to); if (fromOrig === toOrig) { return ''; } from = fromOrig.toLowerCase(); to = toOrig.toLowerCase(); if (from === to) { return ''; } // Trim any leading backslashes let fromStart = 0; while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) { fromStart++; } // Trim trailing backslashes (applicable to UNC paths only) let fromEnd = from.length; while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) { fromEnd--; } const fromLen = fromEnd - fromStart; // Trim any leading backslashes let toStart = 0; while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) { toStart++; } // Trim trailing backslashes (applicable to UNC paths only) let toEnd = to.length; while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) { toEnd--; } const toLen = toEnd - toStart; // Compare paths to find the longest common path from root const length = fromLen < toLen ? fromLen : toLen; let lastCommonSep = -1; let i = 0; for (; i < length; i++) { const fromCode = from.charCodeAt(fromStart + i); if (fromCode !== to.charCodeAt(toStart + i)) { break; } else if (fromCode === CHAR_BACKWARD_SLASH) { lastCommonSep = i; } } // We found a mismatch before the first common path separator was seen, so // return the original `to`. if (i !== length) { if (lastCommonSep === -1) { return toOrig; } } else { if (toLen > length) { if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) { // We get here if `from` is the exact base path for `to`. // For example: from='C:\\foo\\bar'; to='C:\\foo\\bar\\baz' return toOrig.slice(toStart + i + 1); } if (i === 2) { // We get here if `from` is the device root. // For example: from='C:\\'; to='C:\\foo' return toOrig.slice(toStart + i); } } if (fromLen > length) { if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) { // We get here if `to` is the exact base path for `from`. // For example: from='C:\\foo\\bar'; to='C:\\foo' lastCommonSep = i; } else if (i === 2) { // We get here if `to` is the device root. // For example: from='C:\\foo\\bar'; to='C:\\' lastCommonSep = 3; } } if (lastCommonSep === -1) { lastCommonSep = 0; } } let out = ''; // Generate the relative path based on the path difference between `to` and // `from` for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) { out += out.length === 0 ? '..' : '\\..'; } } toStart += lastCommonSep; // Lastly, append the rest of the destination (`to`) path that comes after // the common path parts if (out.length > 0) { return `${out}${toOrig.slice(toStart, toEnd)}`; } if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) { ++toStart; } return toOrig.slice(toStart, toEnd); }, toNamespacedPath(path) { // Note: this will *probably* throw somewhere. if (typeof path !== 'string') { 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[136/*vs/base/common/range*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Range = void 0; var Range; (function (Range) { /** * Returns the intersection between two ranges as a range itself. * Returns `{ start: 0, end: 0 }` if the intersection is empty. */ function intersect(one, other) { if (one.start >= other.end || other.start >= one.end) { return { start: 0, end: 0 }; } const start = Math.max(one.start, other.start); const end = Math.min(one.end, other.end); if (end - start <= 0) { return { start: 0, end: 0 }; } return { start, end }; } Range.intersect = intersect; function isEmpty(range) { return range.end - range.start <= 0; } Range.isEmpty = isEmpty; function intersects(one, other) { return !isEmpty(intersect(one, other)); } Range.intersects = intersects; function relativeComplement(one, other) { const result = []; const first = { start: one.start, end: Math.min(other.start, one.end) }; const second = { start: Math.max(other.end, one.start), end: one.end }; if (!isEmpty(first)) { result.push(first); } if (!isEmpty(second)) { result.push(second); } return result; } Range.relativeComplement = relativeComplement; })(Range = exports.Range || (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[315/*vs/base/browser/ui/list/rangeMap*/], __M([1/*require*/,0/*exports*/,136/*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[65/*vs/base/common/stopwatch*/], __M([1/*require*/,0/*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[4/*vs/base/common/event*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,81/*vs/base/common/linkedList*/,65/*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`. */ 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; } function debouncedListener(event, listener, merge, delay = 100, leading = false) { let output = undefined; let handle = undefined; let numDebouncedCalls = 0; return event(cur => { numDebouncedCalls++; output = merge(output, cur); if (leading && !handle) { listener(output); output = undefined; } clearTimeout(handle); handle = setTimeout(() => { const _output = output; output = undefined; handle = undefined; if (!leading || numDebouncedCalls > 1) { listener(_output); } numDebouncedCalls = 0; }, delay); }); } Event.debouncedListener = debouncedListener; /** * @deprecated this leaks memory, {@link debouncedListener} or {@link DebounceEmitter} instead */ 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, flushAfterTimeout = 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 (flushAfterTimeout) { 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; function runAndSubscribe(event, handler) { handler(undefined); return event(e => handler(e)); } Event.runAndSubscribe = runAndSubscribe; function runAndSubscribeWithStore(event, handler) { let store = null; function run(e) { store === null || store === void 0 ? void 0 : store.dispose(); store = new lifecycle_1.DisposableStore(); handler(e, store); } run(undefined); const disposable = event(e => run(e)); return (0, lifecycle_1.toDisposable)(() => { disposable.dispose(); store === null || store === void 0 ? void 0 : store.dispose(); }); } Event.runAndSubscribeWithStore = runAndSubscribeWithStore; })(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[34/*vs/base/browser/browser*/], __M([1/*require*/,0/*exports*/,4/*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.isStandalone = exports.isAndroid = exports.isElectron = exports.isEdgeLegacyWebView = exports.isWebkitWebView = exports.isSafari = exports.isChrome = exports.isWebKit = exports.isFirefox = exports.getZoomFactor = exports.PixelRatio = void 0; class WindowManager { constructor() { // --- Zoom Factor this._zoomFactor = 1; } getZoomFactor() { return this._zoomFactor; } } WindowManager.INSTANCE = new WindowManager(); class PixelRatioImpl extends lifecycle_1.Disposable { constructor() { super(); this._onDidChange = this._register(new event_1.Emitter()); this.onDidChange = this._onDidChange.event; this._value = this._getPixelRatio(); this._removeListener = this._installResolutionListener(); } get value() { return this._value; } dispose() { this._removeListener(); super.dispose(); } _installResolutionListener() { // See https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#monitoring_screen_resolution_or_zoom_level_changes const mediaQueryList = matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`); const listener = () => this._updateValue(); mediaQueryList.addEventListener('change', listener); return () => { mediaQueryList.removeEventListener('change', listener); }; } _updateValue() { this._value = this._getPixelRatio(); this._onDidChange.fire(this._value); this._removeListener = this._installResolutionListener(); } _getPixelRatio() { const ctx = document.createElement('canvas').getContext('2d'); const dpr = window.devicePixelRatio || 1; const bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1; return dpr / bsr; } } class PixelRatioFacade { constructor() { this._pixelRatioMonitor = null; } _getOrCreatePixelRatioMonitor() { if (!this._pixelRatioMonitor) { this._pixelRatioMonitor = new PixelRatioImpl(); } return this._pixelRatioMonitor; } /** * Get the current value. */ get value() { return this._getOrCreatePixelRatioMonitor().value; } /** * Listen for changes. */ get onDidChange() { return this._getOrCreatePixelRatioMonitor().onDidChange; } } /** * Returns the pixel ratio. * * This is useful for rendering elements at native screen resolution or for being used as * a cache key when storing font measurements. Fonts might render differently depending on resolution * and any measurements need to be discarded for example when a window is moved from a monitor to another. */ exports.PixelRatio = new PixelRatioFacade(); /** The zoom scale for an index, e.g. 1, 1.2, 1.4 */ function getZoomFactor() { return WindowManager.INSTANCE.getZoomFactor(); } exports.getZoomFactor = getZoomFactor; 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.isEdgeLegacyWebView = (userAgent.indexOf('Edge/') >= 0) && (userAgent.indexOf('WebView/') >= 0); exports.isElectron = (userAgent.indexOf('Electron/') >= 0); 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[165/*vs/base/browser/canIUse*/], __M([1/*require*/,0/*exports*/,34/*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[89/*vs/base/browser/event*/], __M([1/*require*/,0/*exports*/,4/*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[46/*vs/base/browser/keyboardEvent*/], __M([1/*require*/,0/*exports*/,34/*vs/base/browser/browser*/,55/*vs/base/common/keyCodes*/,94/*vs/base/common/keybindings*/,17/*vs/base/common/platform*/]), function (require, exports, browser, keyCodes_1, keybindings_1, platform) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.StandardKeyboardEvent = void 0; function extractKeyCode(e) { if (e.charCode) { // "keypress" events mostly let char = String.fromCharCode(e.charCode).toUpperCase(); return keyCodes_1.KeyCodeUtils.fromString(char); } const keyCode = e.keyCode; // browser quirks if (keyCode === 3) { return 7 /* PauseBreak */; } else if (browser.isFirefox) { if (keyCode === 59) { return 80 /* Semicolon */; } else if (keyCode === 107) { return 81 /* Equal */; } else if (keyCode === 109) { return 83 /* Minus */; } else if (platform.isMacintosh && keyCode === 224) { return 57 /* Meta */; } } else if (browser.isWebKit) { if (keyCode === 91) { return 57 /* Meta */; } else if (platform.isMacintosh && keyCode === 93) { // the two meta keys in the Mac have different key codes (91 and 93) return 57 /* Meta */; } else if (!platform.isMacintosh && keyCode === 92) { return 57 /* Meta */; } } // cross browser keycodes: return keyCodes_1.EVENT_KEY_CODE_MAP[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 keybindings_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[56/*vs/base/browser/mouseEvent*/], __M([1/*require*/,0/*exports*/,34/*vs/base/browser/browser*/,211/*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[21/*vs/base/common/cancellation*/], __M([1/*require*/,0/*exports*/,4/*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()); }); }; var __asyncValues = (this && this.__asyncValues) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } }; define(__m[10/*vs/base/common/async*/], __M([1/*require*/,0/*exports*/,21/*vs/base/common/cancellation*/,13/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/]), function (require, exports, cancellation_1, errors_1, event_1, lifecycle_1, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createCancelableAsyncIterable = exports.CancelableAsyncIterableObject = exports.AsyncIterableObject = exports.Promises = exports.DeferredPromise = exports.IdleValue = exports.runWhenIdle = exports.RunOnceScheduler = exports.IntervalTimer = exports.TimeoutTimer = exports.first = exports.disposableTimeout = exports.timeout = exports.ThrottledDelayer = exports.Delayer = exports.MicrotaskDelay = 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(new errors_1.CancellationError()); }); Promise.resolve(thenable).then(value => { subscription.dispose(); source.dispose(); resolve(value); }, err => { subscription.dispose(); source.dispose(); reject(err); }); }); return new class { cancel() { source.cancel(); } 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 new Promise((resolve, reject) => { const ref = token.onCancellationRequested(() => { ref.dispose(); resolve(defaultValue); }); promise.then(resolve, reject).finally(() => ref.dispose()); }); } 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; const timeoutDeferred = (timeout, fn) => { let scheduled = true; const handle = setTimeout(() => { scheduled = false; fn(); }, timeout); return { isTriggered: () => scheduled, dispose: () => { clearTimeout(handle); scheduled = false; }, }; }; const microtaskDeferred = (fn) => { let scheduled = true; queueMicrotask(() => { if (scheduled) { scheduled = false; fn(); } }); return { isTriggered: () => scheduled, dispose: () => { scheduled = false; }, }; }; /** Can be passed into the Delayed to defer using a microtask */ exports.MicrotaskDelay = Symbol('MicrotaskDelay'); /** * A helper to delay (debounce) execution of a task that is being requested often. * * Following the throttler, now imagine the mail man wants to optimize the number of * trips proactively. The trip itself can be long, so he decides not to make the trip * as soon as a letter is submitted. Instead he waits a while, in case more * letters are submitted. After said waiting period, if no letters were submitted, he * decides to make the trip. Imagine that N more letters were submitted after the first * one, all within a short period of time between each other. Even though N+1 * submissions occurred, only 1 delivery was made. * * The delayer offers this behavior via the trigger() method, into which both the task * to be executed and the waiting period (delay) must be passed in as arguments. Following * the example: * * const delayer = new Delayer(WAITING_PERIOD); * const letters = []; * * function letterReceived(l) { * letters.push(l); * delayer.trigger(() => { return makeTheTrip(); }); * } */ class Delayer { constructor(defaultDelay) { this.defaultDelay = defaultDelay; this.deferred = null; this.completionPromise = null; this.doResolve = null; this.doReject = null; this.task = null; } trigger(task, delay = this.defaultDelay) { this.task = task; this.cancelTimeout(); if (!this.completionPromise) { this.completionPromise = new Promise((resolve, reject) => { this.doResolve = resolve; this.doReject = reject; }).then(() => { this.completionPromise = null; this.doResolve = null; if (this.task) { const task = this.task; this.task = null; return task(); } return undefined; }); } const fn = () => { var _a; this.deferred = null; (_a = this.doResolve) === null || _a === void 0 ? void 0 : _a.call(this, null); }; this.deferred = delay === exports.MicrotaskDelay ? microtaskDeferred(fn) : timeoutDeferred(delay, fn); return this.completionPromise; } isTriggered() { var _a; return !!((_a = this.deferred) === null || _a === void 0 ? void 0 : _a.isTriggered()); } cancel() { this.cancelTimeout(); if (this.completionPromise) { if (this.doReject) { this.doReject(new errors_1.CancellationError()); } this.completionPromise = null; } } cancelTimeout() { var _a; (_a = this.deferred) === null || _a === void 0 ? void 0 : _a.dispose(); this.deferred = null; } dispose() { this.cancel(); } } exports.Delayer = Delayer; /** * A helper to delay execution of a task that is being requested often, while * preventing accumulation of consecutive executions, while the task runs. * * The mail man is clever and waits for a certain amount of time, before going * out to deliver letters. While the mail man is going out, more letters arrive * and can only be delivered once he is back. Once he is back the mail man will * do one more trip to deliver the letters that have accumulated while he was out. */ class ThrottledDelayer { constructor(defaultDelay) { this.delayer = new Delayer(defaultDelay); this.throttler = new Throttler(); } trigger(promiseFactory, delay) { return this.delayer.trigger(() => this.throttler.queue(promiseFactory), delay); } 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(new errors_1.CancellationError()); }); }); } 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') { exports.runWhenIdle = (runner) => { (0, platform_1.setTimeout0)(() => { if (disposed) { return; } const end = Date.now() + 15; // one frame at 64fps runner(Object.freeze({ didTimeout: true, timeRemaining() { return Math.max(0, end - Date.now()); } })); }); let disposed = false; return { dispose() { if (disposed) { return; } disposed = true; } }; }; } 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; } get isInitialized() { return this._didRun; } } exports.IdleValue = IdleValue; /** * Creates a promise whose resolution or rejection can be controlled imperatively. */ class DeferredPromise { constructor() { this.rejected = false; this.resolved = false; this.p = new Promise((c, e) => { this.completeCallback = c; this.errorCallback = e; }); } get isRejected() { return this.rejected; } get isSettled() { return this.rejected || this.resolved; } complete(value) { return new Promise(resolve => { this.completeCallback(value); this.resolved = true; resolve(); }); } cancel() { new Promise(resolve => { this.errorCallback(new errors_1.CancellationError()); this.rejected = true; resolve(); }); } } exports.DeferredPromise = DeferredPromise; //#endregion //#region Promises var Promises; (function (Promises) { /** * A drop-in replacement for `Promise.all` with the only difference * that the method awaits every promise to either fulfill or reject. * * Similar to `Promise.all`, only the first error will be returned * if any. */ 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; /** * A helper to create a new `Promise` with a body that is a promise * itself. By default, an error that raises from the async body will * end up as a unhandled rejection, so this utility properly awaits the * body and rejects the promise as a normal promise does without async * body. * * This method should only be used in rare cases where otherwise `async` * cannot be used (e.g. when callbacks are involved that require this). */ function withAsyncBody(bodyFn) { // eslint-disable-next-line no-async-promise-executor return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { try { yield bodyFn(resolve, reject); } catch (error) { reject(error); } })); } Promises.withAsyncBody = withAsyncBody; })(Promises = exports.Promises || (exports.Promises = {})); /** * A rich implementation for an `AsyncIterable`. */ class AsyncIterableObject { constructor(executor) { this._state = 0 /* Initial */; this._results = []; this._error = null; this._onStateChanged = new event_1.Emitter(); queueMicrotask(() => __awaiter(this, void 0, void 0, function* () { const writer = { emitOne: (item) => this.emitOne(item), emitMany: (items) => this.emitMany(items), reject: (error) => this.reject(error) }; try { yield Promise.resolve(executor(writer)); this.resolve(); } catch (err) { this.reject(err); } finally { writer.emitOne = undefined; writer.emitMany = undefined; writer.reject = undefined; } })); } static fromArray(items) { return new AsyncIterableObject((writer) => { writer.emitMany(items); }); } static fromPromise(promise) { return new AsyncIterableObject((emitter) => __awaiter(this, void 0, void 0, function* () { emitter.emitMany(yield promise); })); } static fromPromises(promises) { return new AsyncIterableObject((emitter) => __awaiter(this, void 0, void 0, function* () { yield Promise.all(promises.map((p) => __awaiter(this, void 0, void 0, function* () { return emitter.emitOne(yield p); }))); })); } static merge(iterables) { return new AsyncIterableObject((emitter) => __awaiter(this, void 0, void 0, function* () { yield Promise.all(iterables.map((iterable) => { var iterable_1, iterable_1_1; return __awaiter(this, void 0, void 0, function* () { var e_1, _a; try { for (iterable_1 = __asyncValues(iterable); iterable_1_1 = yield iterable_1.next(), !iterable_1_1.done;) { const item = iterable_1_1.value; emitter.emitOne(item); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) yield _a.call(iterable_1); } finally { if (e_1) throw e_1.error; } } }); })); })); } [Symbol.asyncIterator]() { let i = 0; return { next: () => __awaiter(this, void 0, void 0, function* () { do { if (this._state === 2 /* DoneError */) { throw this._error; } if (i < this._results.length) { return { done: false, value: this._results[i++] }; } if (this._state === 1 /* DoneOK */) { return { done: true, value: undefined }; } yield event_1.Event.toPromise(this._onStateChanged.event); } while (true); }) }; } static map(iterable, mapFn) { return new AsyncIterableObject((emitter) => __awaiter(this, void 0, void 0, function* () { var e_2, _a; try { for (var iterable_2 = __asyncValues(iterable), iterable_2_1; iterable_2_1 = yield iterable_2.next(), !iterable_2_1.done;) { const item = iterable_2_1.value; emitter.emitOne(mapFn(item)); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (iterable_2_1 && !iterable_2_1.done && (_a = iterable_2.return)) yield _a.call(iterable_2); } finally { if (e_2) throw e_2.error; } } })); } map(mapFn) { return AsyncIterableObject.map(this, mapFn); } static filter(iterable, filterFn) { return new AsyncIterableObject((emitter) => __awaiter(this, void 0, void 0, function* () { var e_3, _a; try { for (var iterable_3 = __asyncValues(iterable), iterable_3_1; iterable_3_1 = yield iterable_3.next(), !iterable_3_1.done;) { const item = iterable_3_1.value; if (filterFn(item)) { emitter.emitOne(item); } } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (iterable_3_1 && !iterable_3_1.done && (_a = iterable_3.return)) yield _a.call(iterable_3); } finally { if (e_3) throw e_3.error; } } })); } filter(filterFn) { return AsyncIterableObject.filter(this, filterFn); } static coalesce(iterable) { return AsyncIterableObject.filter(iterable, item => !!item); } coalesce() { return AsyncIterableObject.coalesce(this); } static toPromise(iterable) { var iterable_4, iterable_4_1; var e_4, _a; return __awaiter(this, void 0, void 0, function* () { const result = []; try { for (iterable_4 = __asyncValues(iterable); iterable_4_1 = yield iterable_4.next(), !iterable_4_1.done;) { const item = iterable_4_1.value; result.push(item); } } catch (e_4_1) { e_4 = { error: e_4_1 }; } finally { try { if (iterable_4_1 && !iterable_4_1.done && (_a = iterable_4.return)) yield _a.call(iterable_4); } finally { if (e_4) throw e_4.error; } } return result; }); } toPromise() { return AsyncIterableObject.toPromise(this); } /** * The value will be appended at the end. * * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect. */ emitOne(value) { if (this._state !== 0 /* Initial */) { return; } // it is important to add new values at the end, // as we may have iterators already running on the array this._results.push(value); this._onStateChanged.fire(); } /** * The values will be appended at the end. * * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect. */ emitMany(values) { if (this._state !== 0 /* Initial */) { return; } // it is important to add new values at the end, // as we may have iterators already running on the array this._results = this._results.concat(values); this._onStateChanged.fire(); } /** * Calling `resolve()` will mark the result array as complete. * * **NOTE** `resolve()` must be called, otherwise all consumers of this iterable will hang indefinitely, similar to a non-resolved promise. * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect. */ resolve() { if (this._state !== 0 /* Initial */) { return; } this._state = 1 /* DoneOK */; this._onStateChanged.fire(); } /** * Writing an error will permanently invalidate this iterable. * The current users will receive an error thrown, as will all future users. * * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect. */ reject(error) { if (this._state !== 0 /* Initial */) { return; } this._state = 2 /* DoneError */; this._error = error; this._onStateChanged.fire(); } } exports.AsyncIterableObject = AsyncIterableObject; AsyncIterableObject.EMPTY = AsyncIterableObject.fromArray([]); class CancelableAsyncIterableObject extends AsyncIterableObject { constructor(_source, executor) { super(executor); this._source = _source; } cancel() { this._source.cancel(); } } exports.CancelableAsyncIterableObject = CancelableAsyncIterableObject; function createCancelableAsyncIterable(callback) { const source = new cancellation_1.CancellationTokenSource(); const innerIterable = callback(source.token); return new CancelableAsyncIterableObject(source, (emitter) => __awaiter(this, void 0, void 0, function* () { var e_5, _a; const subscription = source.token.onCancellationRequested(() => { subscription.dispose(); source.dispose(); emitter.reject(new errors_1.CancellationError()); }); try { try { for (var innerIterable_1 = __asyncValues(innerIterable), innerIterable_1_1; innerIterable_1_1 = yield innerIterable_1.next(), !innerIterable_1_1.done;) { const item = innerIterable_1_1.value; if (source.token.isCancellationRequested) { // canceled in the meantime return; } emitter.emitOne(item); } } catch (e_5_1) { e_5 = { error: e_5_1 }; } finally { try { if (innerIterable_1_1 && !innerIterable_1_1.done && (_a = innerIterable_1.return)) yield _a.call(innerIterable_1); } finally { if (e_5) throw e_5.error; } } subscription.dispose(); source.dispose(); } catch (err) { subscription.dispose(); source.dispose(); emitter.reject(err); } })); } exports.createCancelableAsyncIterable = createCancelableAsyncIterable; }); //#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[316/*vs/base/browser/ui/scrollbar/scrollbarVisibilityController*/], __M([1/*require*/,0/*exports*/,10/*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[317/*vs/base/common/comparers*/], __M([1/*require*/,0/*exports*/,10/*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 }; }); // A collator with numeric sorting enabled. const intlFileNameCollatorNumeric = new async_1.IdleValue(() => { const collator = new Intl.Collator(undefined, { numeric: true }); return { collator: collator }; }); // A collator with numeric sorting enabled, and sensitivity to accents and diacritics but not case. const intlFileNameCollatorNumericCaseInsensitive = new async_1.IdleValue(() => { const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'accent' }); return { collator: collator }; }); /** Compares filenames without distinguishing the name from the extension. Disambiguates by unicode comparison. */ function compareFileNames(one, other, caseSensitive = false) { const a = one || ''; const b = other || ''; const result = intlFileNameCollatorBaseNumeric.value.collator.compare(a, b); // Using the numeric option will make compare(`foo1`, `foo01`) === 0. Disambiguate. if (intlFileNameCollatorBaseNumeric.value.collatorIsNumeric && result === 0 && a !== b) { return a < b ? -1 : 1; } return result; } 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[137/*vs/base/common/scrollable*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SmoothScrollingOperation = exports.SmoothScrollingUpdate = exports.Scrollable = exports.ScrollState = void 0; class ScrollState { constructor(_forceIntegerValues, width, scrollWidth, scrollLeft, height, scrollHeight, scrollTop) { this._forceIntegerValues = _forceIntegerValues; this._scrollStateBrand = undefined; if (this._forceIntegerValues) { width = width | 0; scrollWidth = scrollWidth | 0; scrollLeft = scrollLeft | 0; height = height | 0; scrollHeight = scrollHeight | 0; scrollTop = scrollTop | 0; } this.rawScrollLeft = scrollLeft; // before validation this.rawScrollTop = scrollTop; // before validation if (width < 0) { width = 0; } if (scrollLeft + width > scrollWidth) { scrollLeft = scrollWidth - width; } if (scrollLeft < 0) { scrollLeft = 0; } if (height < 0) { height = 0; } if (scrollTop + height > scrollHeight) { scrollTop = scrollHeight - height; } if (scrollTop < 0) { scrollTop = 0; } this.width = width; this.scrollWidth = scrollWidth; this.scrollLeft = scrollLeft; this.height = height; this.scrollHeight = scrollHeight; this.scrollTop = scrollTop; } equals(other) { return (this.rawScrollLeft === other.rawScrollLeft && this.rawScrollTop === other.rawScrollTop && this.width === other.width && this.scrollWidth === other.scrollWidth && this.scrollLeft === other.scrollLeft && this.height === other.height && this.scrollHeight === other.scrollHeight && this.scrollTop === other.scrollTop); } withScrollDimensions(update, useRawScrollPositions) { return new ScrollState(this._forceIntegerValues, (typeof update.width !== 'undefined' ? update.width : this.width), (typeof update.scrollWidth !== 'undefined' ? update.scrollWidth : this.scrollWidth), useRawScrollPositions ? this.rawScrollLeft : this.scrollLeft, (typeof update.height !== 'undefined' ? update.height : this.height), (typeof update.scrollHeight !== 'undefined' ? update.scrollHeight : this.scrollHeight), useRawScrollPositions ? this.rawScrollTop : this.scrollTop); } withScrollPosition(update) { return new ScrollState(this._forceIntegerValues, this.width, this.scrollWidth, (typeof update.scrollLeft !== 'undefined' ? update.scrollLeft : this.rawScrollLeft), this.height, this.scrollHeight, (typeof update.scrollTop !== 'undefined' ? update.scrollTop : this.rawScrollTop)); } createScrollEvent(previous, inSmoothScrolling) { const widthChanged = (this.width !== previous.width); const scrollWidthChanged = (this.scrollWidth !== previous.scrollWidth); const scrollLeftChanged = (this.scrollLeft !== previous.scrollLeft); const heightChanged = (this.height !== previous.height); const scrollHeightChanged = (this.scrollHeight !== previous.scrollHeight); const scrollTopChanged = (this.scrollTop !== previous.scrollTop); return { inSmoothScrolling: inSmoothScrolling, oldWidth: previous.width, oldScrollWidth: previous.scrollWidth, oldScrollLeft: previous.scrollLeft, width: this.width, scrollWidth: this.scrollWidth, scrollLeft: this.scrollLeft, oldHeight: previous.height, oldScrollHeight: previous.scrollHeight, oldScrollTop: previous.scrollTop, height: this.height, scrollHeight: this.scrollHeight, scrollTop: this.scrollTop, widthChanged: widthChanged, scrollWidthChanged: scrollWidthChanged, scrollLeftChanged: scrollLeftChanged, heightChanged: heightChanged, scrollHeightChanged: scrollHeightChanged, scrollTopChanged: scrollTopChanged, }; } } exports.ScrollState = ScrollState; class Scrollable extends lifecycle_1.Disposable { constructor(options) { super(); this._scrollableBrand = undefined; this._onScroll = this._register(new event_1.Emitter()); this.onScroll = this._onScroll.event; this._smoothScrollDuration = options.smoothScrollDuration; this._scheduleAtNextAnimationFrame = options.scheduleAtNextAnimationFrame; this._state = new ScrollState(options.forceIntegerValues, 0, 0, 0, 0, 0, 0); this._smoothScrolling = null; } dispose() { if (this._smoothScrolling) { this._smoothScrolling.dispose(); this._smoothScrolling = null; } super.dispose(); } setSmoothScrollDuration(smoothScrollDuration) { this._smoothScrollDuration = smoothScrollDuration; } validateScrollPosition(scrollPosition) { return this._state.withScrollPosition(scrollPosition); } getScrollDimensions() { return this._state; } setScrollDimensions(dimensions, useRawScrollPositions) { const newState = this._state.withScrollDimensions(dimensions, useRawScrollPositions); this._setState(newState, Boolean(this._smoothScrolling)); // Validate outstanding animated scroll position target 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([1/*require*/,0/*exports*/,309/*vs/base/common/cache*/,134/*vs/base/common/lazy*/]), function (require, exports, cache_1, lazy_1) { "use strict"; var _a; Object.defineProperty(exports, "__esModule", { value: true }); exports.InvisibleCharacters = exports.AmbiguousCharacters = exports.noBreakWhitespace = exports.getLeftDeleteOffset = exports.singleLetterHash = exports.containsUppercaseCharacter = exports.startsWithUTF8BOM = exports.UTF8_BOM_CHARACTER = exports.isEmojiImprecise = exports.isFullWidthCharacter = exports.containsUnusualLineTerminators = exports.UNUSUAL_LINE_TERMINATORS = exports.isBasicASCII = exports.containsRTL = exports.getCharContainingOffset = exports.prevCharLength = exports.nextCharLength = exports.GraphemeIterator = exports.CodePointIterator = 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 '<'; case '>': return '>'; case '&': return '&'; 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; } if (codeA >= 128 || codeB >= 128) { // not ASCII letters -> fallback to lower-casing strings return compareSubstring(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd); } // mapper lower-case ascii letter onto upper-case varinats // [97-122] (lower ascii) --> [65-90] (upper ascii) if (isLowerAsciiLetter(codeA)) { codeA -= 32; } if (isLowerAsciiLetter(codeB)) { codeB -= 32; } // compare both code points const diff = codeA - codeB; if (diff === 0) { continue; } return diff; } const aLen = aEnd - aStart; const bLen = bEnd - bStart; if (aLen < bLen) { return -1; } else if (aLen > bLen) { return 1; } return 0; } 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 equalsIgnoreCase(a, b) { return a.length === b.length && compareSubstringIgnoreCase(a, b) === 0; } exports.equalsIgnoreCase = equalsIgnoreCase; function startsWithIgnoreCase(str, candidate) { const candidateLength = candidate.length; if (candidate.length > str.length) { return false; } return compareSubstringIgnoreCase(str, candidate, 0, candidateLength) === 0; } 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; } class CodePointIterator { constructor(str, offset = 0) { this._str = str; this._len = str.length; this._offset = offset; } get offset() { return this._offset; } setOffset(offset) { this._offset = offset; } prevCodePoint() { const codePoint = getPrevCodePoint(this._str, this._offset); this._offset -= (codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); return codePoint; } nextCodePoint() { const codePoint = getNextCodePoint(this._str, this._len, this._offset); this._offset += (codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); return codePoint; } eol() { return (this._offset >= this._len); } } exports.CodePointIterator = CodePointIterator; class GraphemeIterator { constructor(str, offset = 0) { this._iterator = new CodePointIterator(str, offset); } get offset() { return this._iterator.offset; } nextGraphemeLength() { const graphemeBreakTree = GraphemeBreakTree.getInstance(); const iterator = this._iterator; const initialOffset = iterator.offset; let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.nextCodePoint()); while (!iterator.eol()) { const offset = iterator.offset; const nextGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.nextCodePoint()); if (breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) { // move iterator back iterator.setOffset(offset); break; } graphemeBreakType = nextGraphemeBreakType; } return (iterator.offset - initialOffset); } prevGraphemeLength() { const graphemeBreakTree = GraphemeBreakTree.getInstance(); const iterator = this._iterator; const initialOffset = iterator.offset; let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.prevCodePoint()); while (iterator.offset > 0) { const offset = iterator.offset; const prevGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.prevCodePoint()); if (breakBetweenGraphemeBreakType(prevGraphemeBreakType, graphemeBreakType)) { // move iterator back iterator.setOffset(offset); break; } graphemeBreakType = prevGraphemeBreakType; } return (initialOffset - iterator.offset); } eol() { return this._iterator.eol(); } } exports.GraphemeIterator = GraphemeIterator; function nextCharLength(str, initialOffset) { const iterator = new GraphemeIterator(str, initialOffset); return iterator.nextGraphemeLength(); } exports.nextCharLength = nextCharLength; function prevCharLength(str, initialOffset) { const iterator = new GraphemeIterator(str, initialOffset); return iterator.prevGraphemeLength(); } exports.prevCharLength = prevCharLength; function getCharContainingOffset(str, offset) { if (offset > 0 && isLowSurrogate(str.charCodeAt(offset))) { offset--; } const endOffset = offset + nextCharLength(str, offset); const startOffset = endOffset - prevCharLength(str, endOffset); return [startOffset, endOffset]; } exports.getCharContainingOffset = getCharContainingOffset; /** * Generated using https://github.com/alexdima/unicode-utils/blob/main/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\u07FE-\u0815\u081A\u0824\u0828\u0830-\u0858\u085E-\u088E\u08A0-\u08C9\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFD3D\uFD50-\uFDC7\uFDF0-\uFDFC\uFE70-\uFEFC]|\uD802[\uDC00-\uDD1B\uDD20-\uDE00\uDE10-\uDE35\uDE40-\uDEE4\uDEEB-\uDF35\uDF40-\uDFFF]|\uD803[\uDC00-\uDD23\uDE80-\uDEA9\uDEAD-\uDF45\uDF51-\uDF81\uDF86-\uDFF6]|\uD83A[\uDC00-\uDCCF\uDD00-\uDD43\uDD4B-\uDFFF]|\uD83B[\uDC00-\uDEBB])/; /** * Returns true if `str` contains any Unicode character that is classified as "R" or "AL". */ function containsRTL(str) { return CONTAINS_RTL.test(str); } exports.containsRTL = containsRTL; 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 isFullWidthCharacter(charCode) { // Do a cheap trick to better support wrapping of wide characters, treat them as 2 columns // http://jrgraphix.net/research/unicode_blocks.php // 2E80 - 2EFF CJK Radicals Supplement // 2F00 - 2FDF Kangxi Radicals // 2FF0 - 2FFF Ideographic Description Characters // 3000 - 303F CJK Symbols and Punctuation // 3040 - 309F Hiragana // 30A0 - 30FF Katakana // 3100 - 312F Bopomofo // 3130 - 318F Hangul Compatibility Jamo // 3190 - 319F Kanbun // 31A0 - 31BF Bopomofo Extended // 31F0 - 31FF Katakana Phonetic Extensions // 3200 - 32FF Enclosed CJK Letters and Months // 3300 - 33FF CJK Compatibility // 3400 - 4DBF CJK Unified Ideographs Extension A // 4DC0 - 4DFF Yijing Hexagram Symbols // 4E00 - 9FFF CJK Unified Ideographs // A000 - A48F Yi Syllables // A490 - A4CF Yi Radicals // AC00 - D7AF Hangul Syllables // [IGNORE] D800 - DB7F High Surrogates // [IGNORE] DB80 - DBFF High Private Use Surrogates // [IGNORE] DC00 - DFFF Low Surrogates // [IGNORE] E000 - F8FF Private Use Area // F900 - FAFF CJK Compatibility Ideographs // [IGNORE] FB00 - FB4F Alphabetic Presentation Forms // [IGNORE] FB50 - FDFF Arabic Presentation Forms-A // [IGNORE] FE00 - FE0F Variation Selectors // [IGNORE] FE20 - FE2F Combining Half Marks // [IGNORE] FE30 - FE4F CJK Compatibility Forms // [IGNORE] FE50 - FE6F Small Form Variants // [IGNORE] FE70 - FEFF Arabic Presentation Forms-B // FF00 - FFEF Halfwidth and Fullwidth Forms // [https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms] // of which FF01 - FF5E fullwidth ASCII of 21 to 7E // [IGNORE] and FF65 - FFDC halfwidth of Katakana and Hangul // [IGNORE] FFF0 - FFFF Specials return ((charCode >= 0x2E80 && charCode <= 0xD7AF) || (charCode >= 0xF900 && charCode <= 0xFAFF) || (charCode >= 0xFF01 && charCode <= 0xFF5E)); } exports.isFullWidthCharacter = isFullWidthCharacter; /** * A fast function (therefore imprecise) to check if code points are emojis. * Generated using https://github.com/alexdima/unicode-utils/blob/main/emoji-test.js */ function isEmojiImprecise(x) { return ((x >= 0x1F1E6 && x <= 0x1F1FF) || (x === 8986) || (x === 8987) || (x === 9200) || (x === 9203) || (x >= 9728 && x <= 10175) || (x === 11088) || (x === 11093) || (x >= 127744 && x <= 128591) || (x >= 128640 && x <= 128764) || (x >= 128992 && x <= 129008) || (x >= 129280 && x <= 129535) || (x >= 129648 && x <= 129782)); } 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; 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; } 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/main/grapheme-break.js return JSON.parse('[0,0,0,51229,51255,12,44061,44087,12,127462,127487,6,7083,7085,5,47645,47671,12,54813,54839,12,128678,128678,14,3270,3270,5,9919,9923,14,45853,45879,12,49437,49463,12,53021,53047,12,71216,71218,7,128398,128399,14,129360,129374,14,2519,2519,5,4448,4519,9,9742,9742,14,12336,12336,14,44957,44983,12,46749,46775,12,48541,48567,12,50333,50359,12,52125,52151,12,53917,53943,12,69888,69890,5,73018,73018,5,127990,127990,14,128558,128559,14,128759,128760,14,129653,129655,14,2027,2035,5,2891,2892,7,3761,3761,5,6683,6683,5,8293,8293,4,9825,9826,14,9999,9999,14,43452,43453,5,44509,44535,12,45405,45431,12,46301,46327,12,47197,47223,12,48093,48119,12,48989,49015,12,49885,49911,12,50781,50807,12,51677,51703,12,52573,52599,12,53469,53495,12,54365,54391,12,65279,65279,4,70471,70472,7,72145,72147,7,119173,119179,5,127799,127818,14,128240,128244,14,128512,128512,14,128652,128652,14,128721,128722,14,129292,129292,14,129445,129450,14,129734,129743,14,1476,1477,5,2366,2368,7,2750,2752,7,3076,3076,5,3415,3415,5,4141,4144,5,6109,6109,5,6964,6964,5,7394,7400,5,9197,9198,14,9770,9770,14,9877,9877,14,9968,9969,14,10084,10084,14,43052,43052,5,43713,43713,5,44285,44311,12,44733,44759,12,45181,45207,12,45629,45655,12,46077,46103,12,46525,46551,12,46973,46999,12,47421,47447,12,47869,47895,12,48317,48343,12,48765,48791,12,49213,49239,12,49661,49687,12,50109,50135,12,50557,50583,12,51005,51031,12,51453,51479,12,51901,51927,12,52349,52375,12,52797,52823,12,53245,53271,12,53693,53719,12,54141,54167,12,54589,54615,12,55037,55063,12,69506,69509,5,70191,70193,5,70841,70841,7,71463,71467,5,72330,72342,5,94031,94031,5,123628,123631,5,127763,127765,14,127941,127941,14,128043,128062,14,128302,128317,14,128465,128467,14,128539,128539,14,128640,128640,14,128662,128662,14,128703,128703,14,128745,128745,14,129004,129007,14,129329,129330,14,129402,129402,14,129483,129483,14,129686,129704,14,130048,131069,14,173,173,4,1757,1757,1,2200,2207,5,2434,2435,7,2631,2632,5,2817,2817,5,3008,3008,5,3201,3201,5,3387,3388,5,3542,3542,5,3902,3903,7,4190,4192,5,6002,6003,5,6439,6440,5,6765,6770,7,7019,7027,5,7154,7155,7,8205,8205,13,8505,8505,14,9654,9654,14,9757,9757,14,9792,9792,14,9852,9853,14,9890,9894,14,9937,9937,14,9981,9981,14,10035,10036,14,11035,11036,14,42654,42655,5,43346,43347,7,43587,43587,5,44006,44007,7,44173,44199,12,44397,44423,12,44621,44647,12,44845,44871,12,45069,45095,12,45293,45319,12,45517,45543,12,45741,45767,12,45965,45991,12,46189,46215,12,46413,46439,12,46637,46663,12,46861,46887,12,47085,47111,12,47309,47335,12,47533,47559,12,47757,47783,12,47981,48007,12,48205,48231,12,48429,48455,12,48653,48679,12,48877,48903,12,49101,49127,12,49325,49351,12,49549,49575,12,49773,49799,12,49997,50023,12,50221,50247,12,50445,50471,12,50669,50695,12,50893,50919,12,51117,51143,12,51341,51367,12,51565,51591,12,51789,51815,12,52013,52039,12,52237,52263,12,52461,52487,12,52685,52711,12,52909,52935,12,53133,53159,12,53357,53383,12,53581,53607,12,53805,53831,12,54029,54055,12,54253,54279,12,54477,54503,12,54701,54727,12,54925,54951,12,55149,55175,12,68101,68102,5,69762,69762,7,70067,70069,7,70371,70378,5,70720,70721,7,71087,71087,5,71341,71341,5,71995,71996,5,72249,72249,7,72850,72871,5,73109,73109,5,118576,118598,5,121505,121519,5,127245,127247,14,127568,127569,14,127777,127777,14,127872,127891,14,127956,127967,14,128015,128016,14,128110,128172,14,128259,128259,14,128367,128368,14,128424,128424,14,128488,128488,14,128530,128532,14,128550,128551,14,128566,128566,14,128647,128647,14,128656,128656,14,128667,128673,14,128691,128693,14,128715,128715,14,128728,128732,14,128752,128752,14,128765,128767,14,129096,129103,14,129311,129311,14,129344,129349,14,129394,129394,14,129413,129425,14,129466,129471,14,129511,129535,14,129664,129666,14,129719,129722,14,129760,129767,14,917536,917631,5,13,13,2,1160,1161,5,1564,1564,4,1807,1807,1,2085,2087,5,2307,2307,7,2382,2383,7,2497,2500,5,2563,2563,7,2677,2677,5,2763,2764,7,2879,2879,5,2914,2915,5,3021,3021,5,3142,3144,5,3263,3263,5,3285,3286,5,3398,3400,7,3530,3530,5,3633,3633,5,3864,3865,5,3974,3975,5,4155,4156,7,4229,4230,5,5909,5909,7,6078,6085,7,6277,6278,5,6451,6456,7,6744,6750,5,6846,6846,5,6972,6972,5,7074,7077,5,7146,7148,7,7222,7223,5,7416,7417,5,8234,8238,4,8417,8417,5,9000,9000,14,9203,9203,14,9730,9731,14,9748,9749,14,9762,9763,14,9776,9783,14,9800,9811,14,9831,9831,14,9872,9873,14,9882,9882,14,9900,9903,14,9929,9933,14,9941,9960,14,9974,9974,14,9989,9989,14,10006,10006,14,10062,10062,14,10160,10160,14,11647,11647,5,12953,12953,14,43019,43019,5,43232,43249,5,43443,43443,5,43567,43568,7,43696,43696,5,43765,43765,7,44013,44013,5,44117,44143,12,44229,44255,12,44341,44367,12,44453,44479,12,44565,44591,12,44677,44703,12,44789,44815,12,44901,44927,12,45013,45039,12,45125,45151,12,45237,45263,12,45349,45375,12,45461,45487,12,45573,45599,12,45685,45711,12,45797,45823,12,45909,45935,12,46021,46047,12,46133,46159,12,46245,46271,12,46357,46383,12,46469,46495,12,46581,46607,12,46693,46719,12,46805,46831,12,46917,46943,12,47029,47055,12,47141,47167,12,47253,47279,12,47365,47391,12,47477,47503,12,47589,47615,12,47701,47727,12,47813,47839,12,47925,47951,12,48037,48063,12,48149,48175,12,48261,48287,12,48373,48399,12,48485,48511,12,48597,48623,12,48709,48735,12,48821,48847,12,48933,48959,12,49045,49071,12,49157,49183,12,49269,49295,12,49381,49407,12,49493,49519,12,49605,49631,12,49717,49743,12,49829,49855,12,49941,49967,12,50053,50079,12,50165,50191,12,50277,50303,12,50389,50415,12,50501,50527,12,50613,50639,12,50725,50751,12,50837,50863,12,50949,50975,12,51061,51087,12,51173,51199,12,51285,51311,12,51397,51423,12,51509,51535,12,51621,51647,12,51733,51759,12,51845,51871,12,51957,51983,12,52069,52095,12,52181,52207,12,52293,52319,12,52405,52431,12,52517,52543,12,52629,52655,12,52741,52767,12,52853,52879,12,52965,52991,12,53077,53103,12,53189,53215,12,53301,53327,12,53413,53439,12,53525,53551,12,53637,53663,12,53749,53775,12,53861,53887,12,53973,53999,12,54085,54111,12,54197,54223,12,54309,54335,12,54421,54447,12,54533,54559,12,54645,54671,12,54757,54783,12,54869,54895,12,54981,55007,12,55093,55119,12,55243,55291,10,66045,66045,5,68325,68326,5,69688,69702,5,69817,69818,5,69957,69958,7,70089,70092,5,70198,70199,5,70462,70462,5,70502,70508,5,70750,70750,5,70846,70846,7,71100,71101,5,71230,71230,7,71351,71351,5,71737,71738,5,72000,72000,7,72160,72160,5,72273,72278,5,72752,72758,5,72882,72883,5,73031,73031,5,73461,73462,7,94192,94193,7,119149,119149,7,121403,121452,5,122915,122916,5,126980,126980,14,127358,127359,14,127535,127535,14,127759,127759,14,127771,127771,14,127792,127793,14,127825,127867,14,127897,127899,14,127945,127945,14,127985,127986,14,128000,128007,14,128021,128021,14,128066,128100,14,128184,128235,14,128249,128252,14,128266,128276,14,128335,128335,14,128379,128390,14,128407,128419,14,128444,128444,14,128481,128481,14,128499,128499,14,128526,128526,14,128536,128536,14,128543,128543,14,128556,128556,14,128564,128564,14,128577,128580,14,128643,128645,14,128649,128649,14,128654,128654,14,128660,128660,14,128664,128664,14,128675,128675,14,128686,128689,14,128695,128696,14,128705,128709,14,128717,128719,14,128725,128725,14,128736,128741,14,128747,128748,14,128755,128755,14,128762,128762,14,128981,128991,14,129009,129023,14,129160,129167,14,129296,129304,14,129320,129327,14,129340,129342,14,129356,129356,14,129388,129392,14,129399,129400,14,129404,129407,14,129432,129442,14,129454,129455,14,129473,129474,14,129485,129487,14,129648,129651,14,129659,129660,14,129671,129679,14,129709,129711,14,129728,129730,14,129751,129753,14,129776,129782,14,917505,917505,4,917760,917999,5,10,10,3,127,159,4,768,879,5,1471,1471,5,1536,1541,1,1648,1648,5,1767,1768,5,1840,1866,5,2070,2073,5,2137,2139,5,2274,2274,1,2363,2363,7,2377,2380,7,2402,2403,5,2494,2494,5,2507,2508,7,2558,2558,5,2622,2624,7,2641,2641,5,2691,2691,7,2759,2760,5,2786,2787,5,2876,2876,5,2881,2884,5,2901,2902,5,3006,3006,5,3014,3016,7,3072,3072,5,3134,3136,5,3157,3158,5,3260,3260,5,3266,3266,5,3274,3275,7,3328,3329,5,3391,3392,7,3405,3405,5,3457,3457,5,3536,3537,7,3551,3551,5,3636,3642,5,3764,3772,5,3895,3895,5,3967,3967,7,3993,4028,5,4146,4151,5,4182,4183,7,4226,4226,5,4253,4253,5,4957,4959,5,5940,5940,7,6070,6070,7,6087,6088,7,6158,6158,4,6432,6434,5,6448,6449,7,6679,6680,5,6742,6742,5,6754,6754,5,6783,6783,5,6912,6915,5,6966,6970,5,6978,6978,5,7042,7042,7,7080,7081,5,7143,7143,7,7150,7150,7,7212,7219,5,7380,7392,5,7412,7412,5,8203,8203,4,8232,8232,4,8265,8265,14,8400,8412,5,8421,8432,5,8617,8618,14,9167,9167,14,9200,9200,14,9410,9410,14,9723,9726,14,9733,9733,14,9745,9745,14,9752,9752,14,9760,9760,14,9766,9766,14,9774,9774,14,9786,9786,14,9794,9794,14,9823,9823,14,9828,9828,14,9833,9850,14,9855,9855,14,9875,9875,14,9880,9880,14,9885,9887,14,9896,9897,14,9906,9916,14,9926,9927,14,9935,9935,14,9939,9939,14,9962,9962,14,9972,9972,14,9978,9978,14,9986,9986,14,9997,9997,14,10002,10002,14,10017,10017,14,10055,10055,14,10071,10071,14,10133,10135,14,10548,10549,14,11093,11093,14,12330,12333,5,12441,12442,5,42608,42610,5,43010,43010,5,43045,43046,5,43188,43203,7,43302,43309,5,43392,43394,5,43446,43449,5,43493,43493,5,43571,43572,7,43597,43597,7,43703,43704,5,43756,43757,5,44003,44004,7,44009,44010,7,44033,44059,12,44089,44115,12,44145,44171,12,44201,44227,12,44257,44283,12,44313,44339,12,44369,44395,12,44425,44451,12,44481,44507,12,44537,44563,12,44593,44619,12,44649,44675,12,44705,44731,12,44761,44787,12,44817,44843,12,44873,44899,12,44929,44955,12,44985,45011,12,45041,45067,12,45097,45123,12,45153,45179,12,45209,45235,12,45265,45291,12,45321,45347,12,45377,45403,12,45433,45459,12,45489,45515,12,45545,45571,12,45601,45627,12,45657,45683,12,45713,45739,12,45769,45795,12,45825,45851,12,45881,45907,12,45937,45963,12,45993,46019,12,46049,46075,12,46105,46131,12,46161,46187,12,46217,46243,12,46273,46299,12,46329,46355,12,46385,46411,12,46441,46467,12,46497,46523,12,46553,46579,12,46609,46635,12,46665,46691,12,46721,46747,12,46777,46803,12,46833,46859,12,46889,46915,12,46945,46971,12,47001,47027,12,47057,47083,12,47113,47139,12,47169,47195,12,47225,47251,12,47281,47307,12,47337,47363,12,47393,47419,12,47449,47475,12,47505,47531,12,47561,47587,12,47617,47643,12,47673,47699,12,47729,47755,12,47785,47811,12,47841,47867,12,47897,47923,12,47953,47979,12,48009,48035,12,48065,48091,12,48121,48147,12,48177,48203,12,48233,48259,12,48289,48315,12,48345,48371,12,48401,48427,12,48457,48483,12,48513,48539,12,48569,48595,12,48625,48651,12,48681,48707,12,48737,48763,12,48793,48819,12,48849,48875,12,48905,48931,12,48961,48987,12,49017,49043,12,49073,49099,12,49129,49155,12,49185,49211,12,49241,49267,12,49297,49323,12,49353,49379,12,49409,49435,12,49465,49491,12,49521,49547,12,49577,49603,12,49633,49659,12,49689,49715,12,49745,49771,12,49801,49827,12,49857,49883,12,49913,49939,12,49969,49995,12,50025,50051,12,50081,50107,12,50137,50163,12,50193,50219,12,50249,50275,12,50305,50331,12,50361,50387,12,50417,50443,12,50473,50499,12,50529,50555,12,50585,50611,12,50641,50667,12,50697,50723,12,50753,50779,12,50809,50835,12,50865,50891,12,50921,50947,12,50977,51003,12,51033,51059,12,51089,51115,12,51145,51171,12,51201,51227,12,51257,51283,12,51313,51339,12,51369,51395,12,51425,51451,12,51481,51507,12,51537,51563,12,51593,51619,12,51649,51675,12,51705,51731,12,51761,51787,12,51817,51843,12,51873,51899,12,51929,51955,12,51985,52011,12,52041,52067,12,52097,52123,12,52153,52179,12,52209,52235,12,52265,52291,12,52321,52347,12,52377,52403,12,52433,52459,12,52489,52515,12,52545,52571,12,52601,52627,12,52657,52683,12,52713,52739,12,52769,52795,12,52825,52851,12,52881,52907,12,52937,52963,12,52993,53019,12,53049,53075,12,53105,53131,12,53161,53187,12,53217,53243,12,53273,53299,12,53329,53355,12,53385,53411,12,53441,53467,12,53497,53523,12,53553,53579,12,53609,53635,12,53665,53691,12,53721,53747,12,53777,53803,12,53833,53859,12,53889,53915,12,53945,53971,12,54001,54027,12,54057,54083,12,54113,54139,12,54169,54195,12,54225,54251,12,54281,54307,12,54337,54363,12,54393,54419,12,54449,54475,12,54505,54531,12,54561,54587,12,54617,54643,12,54673,54699,12,54729,54755,12,54785,54811,12,54841,54867,12,54897,54923,12,54953,54979,12,55009,55035,12,55065,55091,12,55121,55147,12,55177,55203,12,65024,65039,5,65520,65528,4,66422,66426,5,68152,68154,5,69291,69292,5,69633,69633,5,69747,69748,5,69811,69814,5,69826,69826,5,69932,69932,7,70016,70017,5,70079,70080,7,70095,70095,5,70196,70196,5,70367,70367,5,70402,70403,7,70464,70464,5,70487,70487,5,70709,70711,7,70725,70725,7,70833,70834,7,70843,70844,7,70849,70849,7,71090,71093,5,71103,71104,5,71227,71228,7,71339,71339,5,71344,71349,5,71458,71461,5,71727,71735,5,71985,71989,7,71998,71998,5,72002,72002,7,72154,72155,5,72193,72202,5,72251,72254,5,72281,72283,5,72344,72345,5,72766,72766,7,72874,72880,5,72885,72886,5,73023,73029,5,73104,73105,5,73111,73111,5,92912,92916,5,94095,94098,5,113824,113827,4,119142,119142,7,119155,119162,4,119362,119364,5,121476,121476,5,122888,122904,5,123184,123190,5,125252,125258,5,127183,127183,14,127340,127343,14,127377,127386,14,127491,127503,14,127548,127551,14,127744,127756,14,127761,127761,14,127769,127769,14,127773,127774,14,127780,127788,14,127796,127797,14,127820,127823,14,127869,127869,14,127894,127895,14,127902,127903,14,127943,127943,14,127947,127950,14,127972,127972,14,127988,127988,14,127992,127994,14,128009,128011,14,128019,128019,14,128023,128041,14,128064,128064,14,128102,128107,14,128174,128181,14,128238,128238,14,128246,128247,14,128254,128254,14,128264,128264,14,128278,128299,14,128329,128330,14,128348,128359,14,128371,128377,14,128392,128393,14,128401,128404,14,128421,128421,14,128433,128434,14,128450,128452,14,128476,128478,14,128483,128483,14,128495,128495,14,128506,128506,14,128519,128520,14,128528,128528,14,128534,128534,14,128538,128538,14,128540,128542,14,128544,128549,14,128552,128555,14,128557,128557,14,128560,128563,14,128565,128565,14,128567,128576,14,128581,128591,14,128641,128642,14,128646,128646,14,128648,128648,14,128650,128651,14,128653,128653,14,128655,128655,14,128657,128659,14,128661,128661,14,128663,128663,14,128665,128666,14,128674,128674,14,128676,128677,14,128679,128685,14,128690,128690,14,128694,128694,14,128697,128702,14,128704,128704,14,128710,128714,14,128716,128716,14,128720,128720,14,128723,128724,14,128726,128727,14,128733,128735,14,128742,128744,14,128746,128746,14,128749,128751,14,128753,128754,14,128756,128758,14,128761,128761,14,128763,128764,14,128884,128895,14,128992,129003,14,129008,129008,14,129036,129039,14,129114,129119,14,129198,129279,14,129293,129295,14,129305,129310,14,129312,129319,14,129328,129328,14,129331,129338,14,129343,129343,14,129351,129355,14,129357,129359,14,129375,129387,14,129393,129393,14,129395,129398,14,129401,129401,14,129403,129403,14,129408,129412,14,129426,129431,14,129443,129444,14,129451,129453,14,129456,129465,14,129472,129472,14,129475,129482,14,129484,129484,14,129488,129510,14,129536,129647,14,129652,129652,14,129656,129658,14,129661,129663,14,129667,129670,14,129680,129685,14,129705,129708,14,129712,129718,14,129723,129727,14,129731,129733,14,129744,129750,14,129754,129759,14,129768,129775,14,129783,129791,14,917504,917504,4,917506,917535,4,917632,917759,4,918000,921599,4,0,9,4,11,12,4,14,31,4,169,169,14,174,174,14,1155,1159,5,1425,1469,5,1473,1474,5,1479,1479,5,1552,1562,5,1611,1631,5,1750,1756,5,1759,1764,5,1770,1773,5,1809,1809,5,1958,1968,5,2045,2045,5,2075,2083,5,2089,2093,5,2192,2193,1,2250,2273,5,2275,2306,5,2362,2362,5,2364,2364,5,2369,2376,5,2381,2381,5,2385,2391,5,2433,2433,5,2492,2492,5,2495,2496,7,2503,2504,7,2509,2509,5,2530,2531,5,2561,2562,5,2620,2620,5,2625,2626,5,2635,2637,5,2672,2673,5,2689,2690,5,2748,2748,5,2753,2757,5,2761,2761,7,2765,2765,5,2810,2815,5,2818,2819,7,2878,2878,5,2880,2880,7,2887,2888,7,2893,2893,5,2903,2903,5,2946,2946,5,3007,3007,7,3009,3010,7,3018,3020,7,3031,3031,5,3073,3075,7,3132,3132,5,3137,3140,7,3146,3149,5,3170,3171,5,3202,3203,7,3262,3262,7,3264,3265,7,3267,3268,7,3271,3272,7,3276,3277,5,3298,3299,5,3330,3331,7,3390,3390,5,3393,3396,5,3402,3404,7,3406,3406,1,3426,3427,5,3458,3459,7,3535,3535,5,3538,3540,5,3544,3550,7,3570,3571,7,3635,3635,7,3655,3662,5,3763,3763,7,3784,3789,5,3893,3893,5,3897,3897,5,3953,3966,5,3968,3972,5,3981,3991,5,4038,4038,5,4145,4145,7,4153,4154,5,4157,4158,5,4184,4185,5,4209,4212,5,4228,4228,7,4237,4237,5,4352,4447,8,4520,4607,10,5906,5908,5,5938,5939,5,5970,5971,5,6068,6069,5,6071,6077,5,6086,6086,5,6089,6099,5,6155,6157,5,6159,6159,5,6313,6313,5,6435,6438,7,6441,6443,7,6450,6450,5,6457,6459,5,6681,6682,7,6741,6741,7,6743,6743,7,6752,6752,5,6757,6764,5,6771,6780,5,6832,6845,5,6847,6862,5,6916,6916,7,6965,6965,5,6971,6971,7,6973,6977,7,6979,6980,7,7040,7041,5,7073,7073,7,7078,7079,7,7082,7082,7,7142,7142,5,7144,7145,5,7149,7149,5,7151,7153,5,7204,7211,7,7220,7221,7,7376,7378,5,7393,7393,7,7405,7405,5,7415,7415,7,7616,7679,5,8204,8204,5,8206,8207,4,8233,8233,4,8252,8252,14,8288,8292,4,8294,8303,4,8413,8416,5,8418,8420,5,8482,8482,14,8596,8601,14,8986,8987,14,9096,9096,14,9193,9196,14,9199,9199,14,9201,9202,14,9208,9210,14,9642,9643,14,9664,9664,14,9728,9729,14,9732,9732,14,9735,9741,14,9743,9744,14,9746,9746,14,9750,9751,14,9753,9756,14,9758,9759,14,9761,9761,14,9764,9765,14,9767,9769,14,9771,9773,14,9775,9775,14,9784,9785,14,9787,9791,14,9793,9793,14,9795,9799,14,9812,9822,14,9824,9824,14,9827,9827,14,9829,9830,14,9832,9832,14,9851,9851,14,9854,9854,14,9856,9861,14,9874,9874,14,9876,9876,14,9878,9879,14,9881,9881,14,9883,9884,14,9888,9889,14,9895,9895,14,9898,9899,14,9904,9905,14,9917,9918,14,9924,9925,14,9928,9928,14,9934,9934,14,9936,9936,14,9938,9938,14,9940,9940,14,9961,9961,14,9963,9967,14,9970,9971,14,9973,9973,14,9975,9977,14,9979,9980,14,9982,9985,14,9987,9988,14,9992,9996,14,9998,9998,14,10000,10001,14,10004,10004,14,10013,10013,14,10024,10024,14,10052,10052,14,10060,10060,14,10067,10069,14,10083,10083,14,10085,10087,14,10145,10145,14,10175,10175,14,11013,11015,14,11088,11088,14,11503,11505,5,11744,11775,5,12334,12335,5,12349,12349,14,12951,12951,14,42607,42607,5,42612,42621,5,42736,42737,5,43014,43014,5,43043,43044,7,43047,43047,7,43136,43137,7,43204,43205,5,43263,43263,5,43335,43345,5,43360,43388,8,43395,43395,7,43444,43445,7,43450,43451,7,43454,43456,7,43561,43566,5,43569,43570,5,43573,43574,5,43596,43596,5,43644,43644,5,43698,43700,5,43710,43711,5,43755,43755,7,43758,43759,7,43766,43766,5,44005,44005,5,44008,44008,5,44012,44012,7,44032,44032,11,44060,44060,11,44088,44088,11,44116,44116,11,44144,44144,11,44172,44172,11,44200,44200,11,44228,44228,11,44256,44256,11,44284,44284,11,44312,44312,11,44340,44340,11,44368,44368,11,44396,44396,11,44424,44424,11,44452,44452,11,44480,44480,11,44508,44508,11,44536,44536,11,44564,44564,11,44592,44592,11,44620,44620,11,44648,44648,11,44676,44676,11,44704,44704,11,44732,44732,11,44760,44760,11,44788,44788,11,44816,44816,11,44844,44844,11,44872,44872,11,44900,44900,11,44928,44928,11,44956,44956,11,44984,44984,11,45012,45012,11,45040,45040,11,45068,45068,11,45096,45096,11,45124,45124,11,45152,45152,11,45180,45180,11,45208,45208,11,45236,45236,11,45264,45264,11,45292,45292,11,45320,45320,11,45348,45348,11,45376,45376,11,45404,45404,11,45432,45432,11,45460,45460,11,45488,45488,11,45516,45516,11,45544,45544,11,45572,45572,11,45600,45600,11,45628,45628,11,45656,45656,11,45684,45684,11,45712,45712,11,45740,45740,11,45768,45768,11,45796,45796,11,45824,45824,11,45852,45852,11,45880,45880,11,45908,45908,11,45936,45936,11,45964,45964,11,45992,45992,11,46020,46020,11,46048,46048,11,46076,46076,11,46104,46104,11,46132,46132,11,46160,46160,11,46188,46188,11,46216,46216,11,46244,46244,11,46272,46272,11,46300,46300,11,46328,46328,11,46356,46356,11,46384,46384,11,46412,46412,11,46440,46440,11,46468,46468,11,46496,46496,11,46524,46524,11,46552,46552,11,46580,46580,11,46608,46608,11,46636,46636,11,46664,46664,11,46692,46692,11,46720,46720,11,46748,46748,11,46776,46776,11,46804,46804,11,46832,46832,11,46860,46860,11,46888,46888,11,46916,46916,11,46944,46944,11,46972,46972,11,47000,47000,11,47028,47028,11,47056,47056,11,47084,47084,11,47112,47112,11,47140,47140,11,47168,47168,11,47196,47196,11,47224,47224,11,47252,47252,11,47280,47280,11,47308,47308,11,47336,47336,11,47364,47364,11,47392,47392,11,47420,47420,11,47448,47448,11,47476,47476,11,47504,47504,11,47532,47532,11,47560,47560,11,47588,47588,11,47616,47616,11,47644,47644,11,47672,47672,11,47700,47700,11,47728,47728,11,47756,47756,11,47784,47784,11,47812,47812,11,47840,47840,11,47868,47868,11,47896,47896,11,47924,47924,11,47952,47952,11,47980,47980,11,48008,48008,11,48036,48036,11,48064,48064,11,48092,48092,11,48120,48120,11,48148,48148,11,48176,48176,11,48204,48204,11,48232,48232,11,48260,48260,11,48288,48288,11,48316,48316,11,48344,48344,11,48372,48372,11,48400,48400,11,48428,48428,11,48456,48456,11,48484,48484,11,48512,48512,11,48540,48540,11,48568,48568,11,48596,48596,11,48624,48624,11,48652,48652,11,48680,48680,11,48708,48708,11,48736,48736,11,48764,48764,11,48792,48792,11,48820,48820,11,48848,48848,11,48876,48876,11,48904,48904,11,48932,48932,11,48960,48960,11,48988,48988,11,49016,49016,11,49044,49044,11,49072,49072,11,49100,49100,11,49128,49128,11,49156,49156,11,49184,49184,11,49212,49212,11,49240,49240,11,49268,49268,11,49296,49296,11,49324,49324,11,49352,49352,11,49380,49380,11,49408,49408,11,49436,49436,11,49464,49464,11,49492,49492,11,49520,49520,11,49548,49548,11,49576,49576,11,49604,49604,11,49632,49632,11,49660,49660,11,49688,49688,11,49716,49716,11,49744,49744,11,49772,49772,11,49800,49800,11,49828,49828,11,49856,49856,11,49884,49884,11,49912,49912,11,49940,49940,11,49968,49968,11,49996,49996,11,50024,50024,11,50052,50052,11,50080,50080,11,50108,50108,11,50136,50136,11,50164,50164,11,50192,50192,11,50220,50220,11,50248,50248,11,50276,50276,11,50304,50304,11,50332,50332,11,50360,50360,11,50388,50388,11,50416,50416,11,50444,50444,11,50472,50472,11,50500,50500,11,50528,50528,11,50556,50556,11,50584,50584,11,50612,50612,11,50640,50640,11,50668,50668,11,50696,50696,11,50724,50724,11,50752,50752,11,50780,50780,11,50808,50808,11,50836,50836,11,50864,50864,11,50892,50892,11,50920,50920,11,50948,50948,11,50976,50976,11,51004,51004,11,51032,51032,11,51060,51060,11,51088,51088,11,51116,51116,11,51144,51144,11,51172,51172,11,51200,51200,11,51228,51228,11,51256,51256,11,51284,51284,11,51312,51312,11,51340,51340,11,51368,51368,11,51396,51396,11,51424,51424,11,51452,51452,11,51480,51480,11,51508,51508,11,51536,51536,11,51564,51564,11,51592,51592,11,51620,51620,11,51648,51648,11,51676,51676,11,51704,51704,11,51732,51732,11,51760,51760,11,51788,51788,11,51816,51816,11,51844,51844,11,51872,51872,11,51900,51900,11,51928,51928,11,51956,51956,11,51984,51984,11,52012,52012,11,52040,52040,11,52068,52068,11,52096,52096,11,52124,52124,11,52152,52152,11,52180,52180,11,52208,52208,11,52236,52236,11,52264,52264,11,52292,52292,11,52320,52320,11,52348,52348,11,52376,52376,11,52404,52404,11,52432,52432,11,52460,52460,11,52488,52488,11,52516,52516,11,52544,52544,11,52572,52572,11,52600,52600,11,52628,52628,11,52656,52656,11,52684,52684,11,52712,52712,11,52740,52740,11,52768,52768,11,52796,52796,11,52824,52824,11,52852,52852,11,52880,52880,11,52908,52908,11,52936,52936,11,52964,52964,11,52992,52992,11,53020,53020,11,53048,53048,11,53076,53076,11,53104,53104,11,53132,53132,11,53160,53160,11,53188,53188,11,53216,53216,11,53244,53244,11,53272,53272,11,53300,53300,11,53328,53328,11,53356,53356,11,53384,53384,11,53412,53412,11,53440,53440,11,53468,53468,11,53496,53496,11,53524,53524,11,53552,53552,11,53580,53580,11,53608,53608,11,53636,53636,11,53664,53664,11,53692,53692,11,53720,53720,11,53748,53748,11,53776,53776,11,53804,53804,11,53832,53832,11,53860,53860,11,53888,53888,11,53916,53916,11,53944,53944,11,53972,53972,11,54000,54000,11,54028,54028,11,54056,54056,11,54084,54084,11,54112,54112,11,54140,54140,11,54168,54168,11,54196,54196,11,54224,54224,11,54252,54252,11,54280,54280,11,54308,54308,11,54336,54336,11,54364,54364,11,54392,54392,11,54420,54420,11,54448,54448,11,54476,54476,11,54504,54504,11,54532,54532,11,54560,54560,11,54588,54588,11,54616,54616,11,54644,54644,11,54672,54672,11,54700,54700,11,54728,54728,11,54756,54756,11,54784,54784,11,54812,54812,11,54840,54840,11,54868,54868,11,54896,54896,11,54924,54924,11,54952,54952,11,54980,54980,11,55008,55008,11,55036,55036,11,55064,55064,11,55092,55092,11,55120,55120,11,55148,55148,11,55176,55176,11,55216,55238,9,64286,64286,5,65056,65071,5,65438,65439,5,65529,65531,4,66272,66272,5,68097,68099,5,68108,68111,5,68159,68159,5,68900,68903,5,69446,69456,5,69632,69632,7,69634,69634,7,69744,69744,5,69759,69761,5,69808,69810,7,69815,69816,7,69821,69821,1,69837,69837,1,69927,69931,5,69933,69940,5,70003,70003,5,70018,70018,7,70070,70078,5,70082,70083,1,70094,70094,7,70188,70190,7,70194,70195,7,70197,70197,7,70206,70206,5,70368,70370,7,70400,70401,5,70459,70460,5,70463,70463,7,70465,70468,7,70475,70477,7,70498,70499,7,70512,70516,5,70712,70719,5,70722,70724,5,70726,70726,5,70832,70832,5,70835,70840,5,70842,70842,5,70845,70845,5,70847,70848,5,70850,70851,5,71088,71089,7,71096,71099,7,71102,71102,7,71132,71133,5,71219,71226,5,71229,71229,5,71231,71232,5,71340,71340,7,71342,71343,7,71350,71350,7,71453,71455,5,71462,71462,7,71724,71726,7,71736,71736,7,71984,71984,5,71991,71992,7,71997,71997,7,71999,71999,1,72001,72001,1,72003,72003,5,72148,72151,5,72156,72159,7,72164,72164,7,72243,72248,5,72250,72250,1,72263,72263,5,72279,72280,7,72324,72329,1,72343,72343,7,72751,72751,7,72760,72765,5,72767,72767,5,72873,72873,7,72881,72881,7,72884,72884,7,73009,73014,5,73020,73021,5,73030,73030,1,73098,73102,7,73107,73108,7,73110,73110,7,73459,73460,5,78896,78904,4,92976,92982,5,94033,94087,7,94180,94180,5,113821,113822,5,118528,118573,5,119141,119141,5,119143,119145,5,119150,119154,5,119163,119170,5,119210,119213,5,121344,121398,5,121461,121461,5,121499,121503,5,122880,122886,5,122907,122913,5,122918,122922,5,123566,123566,5,125136,125142,5,126976,126979,14,126981,127182,14,127184,127231,14,127279,127279,14,127344,127345,14,127374,127374,14,127405,127461,14,127489,127490,14,127514,127514,14,127538,127546,14,127561,127567,14,127570,127743,14,127757,127758,14,127760,127760,14,127762,127762,14,127766,127768,14,127770,127770,14,127772,127772,14,127775,127776,14,127778,127779,14,127789,127791,14,127794,127795,14,127798,127798,14,127819,127819,14,127824,127824,14,127868,127868,14,127870,127871,14,127892,127893,14,127896,127896,14,127900,127901,14,127904,127940,14,127942,127942,14,127944,127944,14,127946,127946,14,127951,127955,14,127968,127971,14,127973,127984,14,127987,127987,14,127989,127989,14,127991,127991,14,127995,127999,5,128008,128008,14,128012,128014,14,128017,128018,14,128020,128020,14,128022,128022,14,128042,128042,14,128063,128063,14,128065,128065,14,128101,128101,14,128108,128109,14,128173,128173,14,128182,128183,14,128236,128237,14,128239,128239,14,128245,128245,14,128248,128248,14,128253,128253,14,128255,128258,14,128260,128263,14,128265,128265,14,128277,128277,14,128300,128301,14,128326,128328,14,128331,128334,14,128336,128347,14,128360,128366,14,128369,128370,14,128378,128378,14,128391,128391,14,128394,128397,14,128400,128400,14,128405,128406,14,128420,128420,14,128422,128423,14,128425,128432,14,128435,128443,14,128445,128449,14,128453,128464,14,128468,128475,14,128479,128480,14,128482,128482,14,128484,128487,14,128489,128494,14,128496,128498,14,128500,128505,14,128507,128511,14,128513,128518,14,128521,128525,14,128527,128527,14,128529,128529,14,128533,128533,14,128535,128535,14,128537,128537,14]'); } //#endregion /** * Computes the offset after performing a left delete on the given string, * while considering unicode grapheme/emoji rules. */ function getLeftDeleteOffset(offset, str) { if (offset === 0) { return 0; } // Try to delete emoji part. const emojiOffset = getOffsetBeforeLastEmojiComponent(offset, str); if (emojiOffset !== undefined) { return emojiOffset; } // Otherwise, just skip a single code point. const iterator = new CodePointIterator(str, offset); iterator.prevCodePoint(); return iterator.offset; } exports.getLeftDeleteOffset = getLeftDeleteOffset; function getOffsetBeforeLastEmojiComponent(initialOffset, str) { // See https://www.unicode.org/reports/tr51/tr51-14.html#EBNF_and_Regex for the // structure of emojis. const iterator = new CodePointIterator(str, initialOffset); let codePoint = iterator.prevCodePoint(); // Skip modifiers while ((isEmojiModifier(codePoint) || codePoint === 65039 /* emojiVariantSelector */ || codePoint === 8419 /* enclosingKeyCap */)) { if (iterator.offset === 0) { // Cannot skip modifier, no preceding emoji base. return undefined; } codePoint = iterator.prevCodePoint(); } // Expect base emoji if (!isEmojiImprecise(codePoint)) { // Unexpected code point, not a valid emoji. return undefined; } let resultOffset = iterator.offset; if (resultOffset > 0) { // Skip optional ZWJ code points that combine multiple emojis. // In theory, we should check if that ZWJ actually combines multiple emojis // to prevent deleting ZWJs in situations we didn't account for. const optionalZwjCodePoint = iterator.prevCodePoint(); if (optionalZwjCodePoint === 8205 /* zwj */) { resultOffset = iterator.offset; } } return resultOffset; } function isEmojiModifier(codePoint) { return 0x1F3FB <= codePoint && codePoint <= 0x1F3FF; } exports.noBreakWhitespace = '\xa0'; class AmbiguousCharacters { constructor(confusableDictionary) { this.confusableDictionary = confusableDictionary; } static getInstance(locales) { return AmbiguousCharacters.cache.get(Array.from(locales)); } static getLocales() { return AmbiguousCharacters._locales.getValue(); } isAmbiguous(codePoint) { return this.confusableDictionary.has(codePoint); } /** * Returns the non basic ASCII code point that the given code point can be confused, * or undefined if such code point does note exist. */ getPrimaryConfusable(codePoint) { return this.confusableDictionary.get(codePoint); } getConfusableCodePoints() { return new Set(this.confusableDictionary.keys()); } } exports.AmbiguousCharacters = AmbiguousCharacters; _a = AmbiguousCharacters; AmbiguousCharacters.ambiguousCharacterData = new lazy_1.Lazy(() => { // Generated using https://github.com/hediet/vscode-unicode-data // Stored as key1, value1, key2, value2, ... return JSON.parse('{\"_common\":[8232,32,8233,32,5760,32,8192,32,8193,32,8194,32,8195,32,8196,32,8197,32,8198,32,8200,32,8201,32,8202,32,8287,32,8199,32,8239,32,2042,95,65101,95,65102,95,65103,95,8208,45,8209,45,8210,45,65112,45,1748,45,8259,45,727,45,8722,45,10134,45,11450,45,1549,44,1643,44,8218,44,184,44,42233,44,894,59,2307,58,2691,58,1417,58,1795,58,1796,58,5868,58,65072,58,6147,58,6153,58,8282,58,1475,58,760,58,42889,58,8758,58,720,58,42237,58,451,33,11601,33,660,63,577,63,2429,63,5038,63,42731,63,119149,46,8228,46,1793,46,1794,46,42510,46,68176,46,1632,46,1776,46,42232,46,1373,96,65287,96,8219,96,8242,96,1370,96,1523,96,8175,96,65344,96,900,96,8189,96,8125,96,8127,96,8190,96,697,96,884,96,712,96,714,96,715,96,756,96,699,96,701,96,700,96,702,96,42892,96,1497,96,2036,96,2037,96,5194,96,5836,96,94033,96,94034,96,65339,91,10088,40,10098,40,12308,40,64830,40,65341,93,10089,41,10099,41,12309,41,64831,41,10100,123,119060,123,10101,125,65342,94,8270,42,1645,42,8727,42,66335,42,5941,47,8257,47,8725,47,8260,47,9585,47,10187,47,10744,47,119354,47,12755,47,12339,47,11462,47,20031,47,12035,47,65340,92,65128,92,8726,92,10189,92,10741,92,10745,92,119311,92,119355,92,12756,92,20022,92,12034,92,42872,38,708,94,710,94,5869,43,10133,43,66203,43,8249,60,10094,60,706,60,119350,60,5176,60,5810,60,5120,61,11840,61,12448,61,42239,61,8250,62,10095,62,707,62,119351,62,5171,62,94015,62,8275,126,732,126,8128,126,8764,126,65372,124,65293,45,120784,50,120794,50,120804,50,120814,50,120824,50,130034,50,42842,50,423,50,1000,50,42564,50,5311,50,42735,50,119302,51,120785,51,120795,51,120805,51,120815,51,120825,51,130035,51,42923,51,540,51,439,51,42858,51,11468,51,1248,51,94011,51,71882,51,120786,52,120796,52,120806,52,120816,52,120826,52,130036,52,5070,52,71855,52,120787,53,120797,53,120807,53,120817,53,120827,53,130037,53,444,53,71867,53,120788,54,120798,54,120808,54,120818,54,120828,54,130038,54,11474,54,5102,54,71893,54,119314,55,120789,55,120799,55,120809,55,120819,55,120829,55,130039,55,66770,55,71878,55,2819,56,2538,56,2666,56,125131,56,120790,56,120800,56,120810,56,120820,56,120830,56,130040,56,547,56,546,56,66330,56,2663,57,2920,57,2541,57,3437,57,120791,57,120801,57,120811,57,120821,57,120831,57,130041,57,42862,57,11466,57,71884,57,71852,57,71894,57,9082,97,65345,97,119834,97,119886,97,119938,97,119990,97,120042,97,120094,97,120146,97,120198,97,120250,97,120302,97,120354,97,120406,97,120458,97,593,97,945,97,120514,97,120572,97,120630,97,120688,97,120746,97,65313,65,119808,65,119860,65,119912,65,119964,65,120016,65,120068,65,120120,65,120172,65,120224,65,120276,65,120328,65,120380,65,120432,65,913,65,120488,65,120546,65,120604,65,120662,65,120720,65,5034,65,5573,65,42222,65,94016,65,66208,65,119835,98,119887,98,119939,98,119991,98,120043,98,120095,98,120147,98,120199,98,120251,98,120303,98,120355,98,120407,98,120459,98,388,98,5071,98,5234,98,5551,98,65314,66,8492,66,119809,66,119861,66,119913,66,120017,66,120069,66,120121,66,120173,66,120225,66,120277,66,120329,66,120381,66,120433,66,42932,66,914,66,120489,66,120547,66,120605,66,120663,66,120721,66,5108,66,5623,66,42192,66,66178,66,66209,66,66305,66,65347,99,8573,99,119836,99,119888,99,119940,99,119992,99,120044,99,120096,99,120148,99,120200,99,120252,99,120304,99,120356,99,120408,99,120460,99,7428,99,1010,99,11429,99,43951,99,66621,99,128844,67,71922,67,71913,67,65315,67,8557,67,8450,67,8493,67,119810,67,119862,67,119914,67,119966,67,120018,67,120174,67,120226,67,120278,67,120330,67,120382,67,120434,67,1017,67,11428,67,5087,67,42202,67,66210,67,66306,67,66581,67,66844,67,8574,100,8518,100,119837,100,119889,100,119941,100,119993,100,120045,100,120097,100,120149,100,120201,100,120253,100,120305,100,120357,100,120409,100,120461,100,1281,100,5095,100,5231,100,42194,100,8558,68,8517,68,119811,68,119863,68,119915,68,119967,68,120019,68,120071,68,120123,68,120175,68,120227,68,120279,68,120331,68,120383,68,120435,68,5024,68,5598,68,5610,68,42195,68,8494,101,65349,101,8495,101,8519,101,119838,101,119890,101,119942,101,120046,101,120098,101,120150,101,120202,101,120254,101,120306,101,120358,101,120410,101,120462,101,43826,101,1213,101,8959,69,65317,69,8496,69,119812,69,119864,69,119916,69,120020,69,120072,69,120124,69,120176,69,120228,69,120280,69,120332,69,120384,69,120436,69,917,69,120492,69,120550,69,120608,69,120666,69,120724,69,11577,69,5036,69,42224,69,71846,69,71854,69,66182,69,119839,102,119891,102,119943,102,119995,102,120047,102,120099,102,120151,102,120203,102,120255,102,120307,102,120359,102,120411,102,120463,102,43829,102,42905,102,383,102,7837,102,1412,102,119315,70,8497,70,119813,70,119865,70,119917,70,120021,70,120073,70,120125,70,120177,70,120229,70,120281,70,120333,70,120385,70,120437,70,42904,70,988,70,120778,70,5556,70,42205,70,71874,70,71842,70,66183,70,66213,70,66853,70,65351,103,8458,103,119840,103,119892,103,119944,103,120048,103,120100,103,120152,103,120204,103,120256,103,120308,103,120360,103,120412,103,120464,103,609,103,7555,103,397,103,1409,103,119814,71,119866,71,119918,71,119970,71,120022,71,120074,71,120126,71,120178,71,120230,71,120282,71,120334,71,120386,71,120438,71,1292,71,5056,71,5107,71,42198,71,65352,104,8462,104,119841,104,119945,104,119997,104,120049,104,120101,104,120153,104,120205,104,120257,104,120309,104,120361,104,120413,104,120465,104,1211,104,1392,104,5058,104,65320,72,8459,72,8460,72,8461,72,119815,72,119867,72,119919,72,120023,72,120179,72,120231,72,120283,72,120335,72,120387,72,120439,72,919,72,120494,72,120552,72,120610,72,120668,72,120726,72,11406,72,5051,72,5500,72,42215,72,66255,72,731,105,9075,105,65353,105,8560,105,8505,105,8520,105,119842,105,119894,105,119946,105,119998,105,120050,105,120102,105,120154,105,120206,105,120258,105,120310,105,120362,105,120414,105,120466,105,120484,105,618,105,617,105,953,105,8126,105,890,105,120522,105,120580,105,120638,105,120696,105,120754,105,1110,105,42567,105,1231,105,43893,105,5029,105,71875,105,65354,106,8521,106,119843,106,119895,106,119947,106,119999,106,120051,106,120103,106,120155,106,120207,106,120259,106,120311,106,120363,106,120415,106,120467,106,1011,106,1112,106,65322,74,119817,74,119869,74,119921,74,119973,74,120025,74,120077,74,120129,74,120181,74,120233,74,120285,74,120337,74,120389,74,120441,74,42930,74,895,74,1032,74,5035,74,5261,74,42201,74,119844,107,119896,107,119948,107,120000,107,120052,107,120104,107,120156,107,120208,107,120260,107,120312,107,120364,107,120416,107,120468,107,8490,75,65323,75,119818,75,119870,75,119922,75,119974,75,120026,75,120078,75,120130,75,120182,75,120234,75,120286,75,120338,75,120390,75,120442,75,922,75,120497,75,120555,75,120613,75,120671,75,120729,75,11412,75,5094,75,5845,75,42199,75,66840,75,1472,108,8739,73,9213,73,65512,73,1633,108,1777,73,66336,108,125127,108,120783,73,120793,73,120803,73,120813,73,120823,73,130033,73,65321,73,8544,73,8464,73,8465,73,119816,73,119868,73,119920,73,120024,73,120128,73,120180,73,120232,73,120284,73,120336,73,120388,73,120440,73,65356,108,8572,73,8467,108,119845,108,119897,108,119949,108,120001,108,120053,108,120105,73,120157,73,120209,73,120261,73,120313,73,120365,73,120417,73,120469,73,448,73,120496,73,120554,73,120612,73,120670,73,120728,73,11410,73,1030,73,1216,73,1493,108,1503,108,1575,108,126464,108,126592,108,65166,108,65165,108,1994,108,11599,73,5825,73,42226,73,93992,73,66186,124,66313,124,119338,76,8556,76,8466,76,119819,76,119871,76,119923,76,120027,76,120079,76,120131,76,120183,76,120235,76,120287,76,120339,76,120391,76,120443,76,11472,76,5086,76,5290,76,42209,76,93974,76,71843,76,71858,76,66587,76,66854,76,65325,77,8559,77,8499,77,119820,77,119872,77,119924,77,120028,77,120080,77,120132,77,120184,77,120236,77,120288,77,120340,77,120392,77,120444,77,924,77,120499,77,120557,77,120615,77,120673,77,120731,77,1018,77,11416,77,5047,77,5616,77,5846,77,42207,77,66224,77,66321,77,119847,110,119899,110,119951,110,120003,110,120055,110,120107,110,120159,110,120211,110,120263,110,120315,110,120367,110,120419,110,120471,110,1400,110,1404,110,65326,78,8469,78,119821,78,119873,78,119925,78,119977,78,120029,78,120081,78,120185,78,120237,78,120289,78,120341,78,120393,78,120445,78,925,78,120500,78,120558,78,120616,78,120674,78,120732,78,11418,78,42208,78,66835,78,3074,111,3202,111,3330,111,3458,111,2406,111,2662,111,2790,111,3046,111,3174,111,3302,111,3430,111,3664,111,3792,111,4160,111,1637,111,1781,111,65359,111,8500,111,119848,111,119900,111,119952,111,120056,111,120108,111,120160,111,120212,111,120264,111,120316,111,120368,111,120420,111,120472,111,7439,111,7441,111,43837,111,959,111,120528,111,120586,111,120644,111,120702,111,120760,111,963,111,120532,111,120590,111,120648,111,120706,111,120764,111,11423,111,4351,111,1413,111,1505,111,1607,111,126500,111,126564,111,126596,111,65259,111,65260,111,65258,111,65257,111,1726,111,64428,111,64429,111,64427,111,64426,111,1729,111,64424,111,64425,111,64423,111,64422,111,1749,111,3360,111,4125,111,66794,111,71880,111,71895,111,66604,111,1984,79,2534,79,2918,79,12295,79,70864,79,71904,79,120782,79,120792,79,120802,79,120812,79,120822,79,130032,79,65327,79,119822,79,119874,79,119926,79,119978,79,120030,79,120082,79,120134,79,120186,79,120238,79,120290,79,120342,79,120394,79,120446,79,927,79,120502,79,120560,79,120618,79,120676,79,120734,79,11422,79,1365,79,11604,79,4816,79,2848,79,66754,79,42227,79,71861,79,66194,79,66219,79,66564,79,66838,79,9076,112,65360,112,119849,112,119901,112,119953,112,120005,112,120057,112,120109,112,120161,112,120213,112,120265,112,120317,112,120369,112,120421,112,120473,112,961,112,120530,112,120544,112,120588,112,120602,112,120646,112,120660,112,120704,112,120718,112,120762,112,120776,112,11427,112,65328,80,8473,80,119823,80,119875,80,119927,80,119979,80,120031,80,120083,80,120187,80,120239,80,120291,80,120343,80,120395,80,120447,80,929,80,120504,80,120562,80,120620,80,120678,80,120736,80,11426,80,5090,80,5229,80,42193,80,66197,80,119850,113,119902,113,119954,113,120006,113,120058,113,120110,113,120162,113,120214,113,120266,113,120318,113,120370,113,120422,113,120474,113,1307,113,1379,113,1382,113,8474,81,119824,81,119876,81,119928,81,119980,81,120032,81,120084,81,120188,81,120240,81,120292,81,120344,81,120396,81,120448,81,11605,81,119851,114,119903,114,119955,114,120007,114,120059,114,120111,114,120163,114,120215,114,120267,114,120319,114,120371,114,120423,114,120475,114,43847,114,43848,114,7462,114,11397,114,43905,114,119318,82,8475,82,8476,82,8477,82,119825,82,119877,82,119929,82,120033,82,120189,82,120241,82,120293,82,120345,82,120397,82,120449,82,422,82,5025,82,5074,82,66740,82,5511,82,42211,82,94005,82,65363,115,119852,115,119904,115,119956,115,120008,115,120060,115,120112,115,120164,115,120216,115,120268,115,120320,115,120372,115,120424,115,120476,115,42801,115,445,115,1109,115,43946,115,71873,115,66632,115,65331,83,119826,83,119878,83,119930,83,119982,83,120034,83,120086,83,120138,83,120190,83,120242,83,120294,83,120346,83,120398,83,120450,83,1029,83,1359,83,5077,83,5082,83,42210,83,94010,83,66198,83,66592,83,119853,116,119905,116,119957,116,120009,116,120061,116,120113,116,120165,116,120217,116,120269,116,120321,116,120373,116,120425,116,120477,116,8868,84,10201,84,128872,84,65332,84,119827,84,119879,84,119931,84,119983,84,120035,84,120087,84,120139,84,120191,84,120243,84,120295,84,120347,84,120399,84,120451,84,932,84,120507,84,120565,84,120623,84,120681,84,120739,84,11430,84,5026,84,42196,84,93962,84,71868,84,66199,84,66225,84,66325,84,119854,117,119906,117,119958,117,120010,117,120062,117,120114,117,120166,117,120218,117,120270,117,120322,117,120374,117,120426,117,120478,117,42911,117,7452,117,43854,117,43858,117,651,117,965,117,120534,117,120592,117,120650,117,120708,117,120766,117,1405,117,66806,117,71896,117,8746,85,8899,85,119828,85,119880,85,119932,85,119984,85,120036,85,120088,85,120140,85,120192,85,120244,85,120296,85,120348,85,120400,85,120452,85,1357,85,4608,85,66766,85,5196,85,42228,85,94018,85,71864,85,8744,118,8897,118,65366,118,8564,118,119855,118,119907,118,119959,118,120011,118,120063,118,120115,118,120167,118,120219,118,120271,118,120323,118,120375,118,120427,118,120479,118,7456,118,957,118,120526,118,120584,118,120642,118,120700,118,120758,118,1141,118,1496,118,71430,118,43945,118,71872,118,119309,86,1639,86,1783,86,8548,86,119829,86,119881,86,119933,86,119985,86,120037,86,120089,86,120141,86,120193,86,120245,86,120297,86,120349,86,120401,86,120453,86,1140,86,11576,86,5081,86,5167,86,42719,86,42214,86,93960,86,71840,86,66845,86,623,119,119856,119,119908,119,119960,119,120012,119,120064,119,120116,119,120168,119,120220,119,120272,119,120324,119,120376,119,120428,119,120480,119,7457,119,1121,119,1309,119,1377,119,71434,119,71438,119,71439,119,43907,119,71919,87,71910,87,119830,87,119882,87,119934,87,119986,87,120038,87,120090,87,120142,87,120194,87,120246,87,120298,87,120350,87,120402,87,120454,87,1308,87,5043,87,5076,87,42218,87,5742,120,10539,120,10540,120,10799,120,65368,120,8569,120,119857,120,119909,120,119961,120,120013,120,120065,120,120117,120,120169,120,120221,120,120273,120,120325,120,120377,120,120429,120,120481,120,5441,120,5501,120,5741,88,9587,88,66338,88,71916,88,65336,88,8553,88,119831,88,119883,88,119935,88,119987,88,120039,88,120091,88,120143,88,120195,88,120247,88,120299,88,120351,88,120403,88,120455,88,42931,88,935,88,120510,88,120568,88,120626,88,120684,88,120742,88,11436,88,11613,88,5815,88,42219,88,66192,88,66228,88,66327,88,66855,88,611,121,7564,121,65369,121,119858,121,119910,121,119962,121,120014,121,120066,121,120118,121,120170,121,120222,121,120274,121,120326,121,120378,121,120430,121,120482,121,655,121,7935,121,43866,121,947,121,8509,121,120516,121,120574,121,120632,121,120690,121,120748,121,1199,121,4327,121,71900,121,65337,89,119832,89,119884,89,119936,89,119988,89,120040,89,120092,89,120144,89,120196,89,120248,89,120300,89,120352,89,120404,89,120456,89,933,89,978,89,120508,89,120566,89,120624,89,120682,89,120740,89,11432,89,1198,89,5033,89,5053,89,42220,89,94019,89,71844,89,66226,89,119859,122,119911,122,119963,122,120015,122,120067,122,120119,122,120171,122,120223,122,120275,122,120327,122,120379,122,120431,122,120483,122,7458,122,43923,122,71876,122,66293,90,71909,90,65338,90,8484,90,8488,90,119833,90,119885,90,119937,90,119989,90,120041,90,120197,90,120249,90,120301,90,120353,90,120405,90,120457,90,918,90,120493,90,120551,90,120609,90,120667,90,120725,90,5059,90,42204,90,71849,90,65282,34,65284,36,65285,37,65286,38,65290,42,65291,43,65294,46,65295,47,65296,48,65297,49,65298,50,65299,51,65300,52,65301,53,65302,54,65303,55,65304,56,65305,57,65308,60,65309,61,65310,62,65312,64,65316,68,65318,70,65319,71,65324,76,65329,81,65330,82,65333,85,65334,86,65335,87,65343,95,65346,98,65348,100,65350,102,65355,107,65357,109,65358,110,65361,113,65362,114,65364,116,65365,117,65367,119,65370,122,65371,123,65373,125],\"_default\":[160,32,8211,45,65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"cs\":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"de\":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"es\":[8211,45,65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"fr\":[65374,126,65306,58,65281,33,8216,96,8245,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"it\":[160,32,8211,45,65374,126,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"ja\":[8211,45,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65292,44,65307,59],\"ko\":[8211,45,65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"pl\":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"pt-BR\":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"qps-ploc\":[160,32,8211,45,65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"ru\":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,305,105,921,73,1009,112,215,120,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"tr\":[160,32,8211,45,65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"zh-hans\":[65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41],\"zh-hant\":[8211,45,65374,126,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65307,59]}'); }); AmbiguousCharacters.cache = new cache_1.LRUCachedComputed((locales) => { function arrayToMap(arr) { const result = new Map(); for (let i = 0; i < arr.length; i += 2) { result.set(arr[i], arr[i + 1]); } return result; } function mergeMaps(map1, map2) { const result = new Map(map1); for (const [key, value] of map2) { result.set(key, value); } return result; } function intersectMaps(map1, map2) { if (!map1) { return map2; } const result = new Map(); for (const [key, value] of map1) { if (map2.has(key)) { result.set(key, value); } } return result; } const data = _a.ambiguousCharacterData.getValue(); let filteredLocales = locales.filter((l) => !l.startsWith('_') && l in data); if (filteredLocales.length === 0) { filteredLocales = ['_default']; } let languageSpecificMap = undefined; for (const locale of filteredLocales) { const map = arrayToMap(data[locale]); languageSpecificMap = intersectMaps(languageSpecificMap, map); } const commonMap = arrayToMap(data['_common']); const map = mergeMaps(commonMap, languageSpecificMap); return new AmbiguousCharacters(map); }); AmbiguousCharacters._locales = new lazy_1.Lazy(() => Object.keys(AmbiguousCharacters.ambiguousCharacterData.getValue()).filter((k) => !k.startsWith('_'))); class InvisibleCharacters { static getRawData() { // Generated using https://github.com/hediet/vscode-unicode-data return JSON.parse('[9,10,11,12,13,32,127,160,173,847,1564,4447,4448,6068,6069,6155,6156,6157,6158,7355,7356,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8203,8204,8205,8206,8207,8234,8235,8236,8237,8238,8239,8287,8288,8289,8290,8291,8292,8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,10240,12288,12644,65024,65025,65026,65027,65028,65029,65030,65031,65032,65033,65034,65035,65036,65037,65038,65039,65279,65440,65520,65521,65522,65523,65524,65525,65526,65527,65528,65532,78844,119155,119156,119157,119158,119159,119160,119161,119162,917504,917505,917506,917507,917508,917509,917510,917511,917512,917513,917514,917515,917516,917517,917518,917519,917520,917521,917522,917523,917524,917525,917526,917527,917528,917529,917530,917531,917532,917533,917534,917535,917536,917537,917538,917539,917540,917541,917542,917543,917544,917545,917546,917547,917548,917549,917550,917551,917552,917553,917554,917555,917556,917557,917558,917559,917560,917561,917562,917563,917564,917565,917566,917567,917568,917569,917570,917571,917572,917573,917574,917575,917576,917577,917578,917579,917580,917581,917582,917583,917584,917585,917586,917587,917588,917589,917590,917591,917592,917593,917594,917595,917596,917597,917598,917599,917600,917601,917602,917603,917604,917605,917606,917607,917608,917609,917610,917611,917612,917613,917614,917615,917616,917617,917618,917619,917620,917621,917622,917623,917624,917625,917626,917627,917628,917629,917630,917631,917760,917761,917762,917763,917764,917765,917766,917767,917768,917769,917770,917771,917772,917773,917774,917775,917776,917777,917778,917779,917780,917781,917782,917783,917784,917785,917786,917787,917788,917789,917790,917791,917792,917793,917794,917795,917796,917797,917798,917799,917800,917801,917802,917803,917804,917805,917806,917807,917808,917809,917810,917811,917812,917813,917814,917815,917816,917817,917818,917819,917820,917821,917822,917823,917824,917825,917826,917827,917828,917829,917830,917831,917832,917833,917834,917835,917836,917837,917838,917839,917840,917841,917842,917843,917844,917845,917846,917847,917848,917849,917850,917851,917852,917853,917854,917855,917856,917857,917858,917859,917860,917861,917862,917863,917864,917865,917866,917867,917868,917869,917870,917871,917872,917873,917874,917875,917876,917877,917878,917879,917880,917881,917882,917883,917884,917885,917886,917887,917888,917889,917890,917891,917892,917893,917894,917895,917896,917897,917898,917899,917900,917901,917902,917903,917904,917905,917906,917907,917908,917909,917910,917911,917912,917913,917914,917915,917916,917917,917918,917919,917920,917921,917922,917923,917924,917925,917926,917927,917928,917929,917930,917931,917932,917933,917934,917935,917936,917937,917938,917939,917940,917941,917942,917943,917944,917945,917946,917947,917948,917949,917950,917951,917952,917953,917954,917955,917956,917957,917958,917959,917960,917961,917962,917963,917964,917965,917966,917967,917968,917969,917970,917971,917972,917973,917974,917975,917976,917977,917978,917979,917980,917981,917982,917983,917984,917985,917986,917987,917988,917989,917990,917991,917992,917993,917994,917995,917996,917997,917998,917999]'); } static getData() { if (!this._data) { this._data = new Set(InvisibleCharacters.getRawData()); } return this._data; } static isInvisibleCharacter(codePoint) { return InvisibleCharacters.getData().has(codePoint); } static get codePoints() { return InvisibleCharacters.getData(); } } exports.InvisibleCharacters = InvisibleCharacters; InvisibleCharacters._data = undefined; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[166/*vs/base/common/extpath*/], __M([1/*require*/,0/*exports*/,82/*vs/base/common/path*/,17/*vs/base/common/platform*/,8/*vs/base/common/strings*/]), function (require, exports, path_1, platform_1, strings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.hasDriveLetter = exports.isRootOrDriveLetter = exports.isWindowsDriveLetter = exports.isEqualOrParent = exports.getRoot = exports.toPosixPath = exports.toSlashes = exports.isPathSeparator = void 0; function isPathSeparator(code) { return code === 47 /* Slash */ || code === 92 /* Backslash */; } exports.isPathSeparator = isPathSeparator; /** * 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; /** * Computes the _root_ this path, like `getRoot('c:\files') === c:\`, * `getRoot('files:///files/path') === files:///`, * or `getRoot('\\server\shares\path') === \\server\shares\` */ function getRoot(path, sep = path_1.posix.sep) { if (!path) { return ''; } const len = path.length; const firstLetter = path.charCodeAt(0); if (isPathSeparator(firstLetter)) { if (isPathSeparator(path.charCodeAt(1))) { // UNC candidate \\localhost\shares\ddd // ^^^^^^^^^^^^^^^^^^^ if (!isPathSeparator(path.charCodeAt(2))) { let pos = 3; const start = pos; for (; pos < len; pos++) { if (isPathSeparator(path.charCodeAt(pos))) { break; } } if (start !== pos && !isPathSeparator(path.charCodeAt(pos + 1))) { pos += 1; for (; pos < len; pos++) { if (isPathSeparator(path.charCodeAt(pos))) { return path.slice(0, pos + 1) // consume this separator .replace(/[\\/]/g, sep); } } } } } // /user/far // ^ return sep; } else if (isWindowsDriveLetter(firstLetter)) { // check for windows drive letter c:\ or c: if (path.charCodeAt(1) === 58 /* Colon */) { if (isPathSeparator(path.charCodeAt(2))) { // C:\fff // ^^^ return path.slice(0, 2) + sep; } else { // C: // ^^ return path.slice(0, 2); } } } // check for URI // scheme://authority/path // ^^^^^^^^^^^^^^^^^^^ let pos = path.indexOf('://'); if (pos !== -1) { pos += 3; // 3 -> "://".length for (; pos < len; pos++) { if (isPathSeparator(path.charCodeAt(pos))) { return path.slice(0, pos + 1); // consume this separator } } } return ''; } exports.getRoot = getRoot; /** * @deprecated please use `IUriIdentityService.extUri.isEqualOrParent` instead. If * you are in a context without services, consider to pass down the `extUri` from the * outside, or use `extUriBiasedIgnorePathCase` if you know what you are doing. */ function isEqualOrParent(base, parentCandidate, ignoreCase, separator = path_1.sep) { if (base === parentCandidate) { return true; } if (!base || !parentCandidate) { return false; } if (parentCandidate.length > base.length) { return false; } if (ignoreCase) { const beginsWith = (0, strings_1.startsWithIgnoreCase)(base, parentCandidate); if (!beginsWith) { return false; } if (parentCandidate.length === base.length) { return true; // same path, different casing } let sepOffset = parentCandidate.length; if (parentCandidate.charAt(parentCandidate.length - 1) === separator) { sepOffset--; // adjust the expected sep offset in case our candidate already ends in separator character } return base.charAt(sepOffset) === separator; } if (parentCandidate.charAt(parentCandidate.length - 1) !== separator) { parentCandidate += separator; } return base.indexOf(parentCandidate) === 0; } 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, continueAsWindows) { const isWindowsPath = ((continueAsWindows !== undefined) ? continueAsWindows : platform_1.isWindows); if (isWindowsPath) { 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[112/*vs/base/common/hash*/], __M([1/*require*/,0/*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.numberHash = 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 } exports.numberHash = numberHash; 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[138/*vs/base/common/diff/diff*/], __M([1/*require*/,0/*exports*/,310/*vs/base/common/diff/diffChange*/,112/*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 * MarkNextChange() method can be called to mark the separation between * distinct changes. At the end, the Changes property can be called to retrieve * the constructed changes. */ class DiffChangeHelper { /** * Constructs a new DiffChangeHelper for the given DiffSequences. */ constructor() { this.m_changes = []; this.m_originalStart = 1073741824 /* 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 didn't have time to finish the first half, so we don't have time to compute this half. // Consider the entire rest of the sequence different. rightChanges = [ new diffChange_1.DiffChange(midOriginal + 1, originalEnd - (midOriginal + 1) + 1, midModified + 1, modifiedEnd - (midModified + 1) + 1) ]; } return this.ConcatenateChanges(leftChanges, rightChanges); } // If we hit here, we quit early, and so can't return anything meaningful return [ new diffChange_1.DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1) ]; } WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr) { let forwardChanges = null; let reverseChanges = null; // First, walk backward through the forward diagonals history let changeHelper = new DiffChangeHelper(); let diagonalMin = diagonalForwardStart; let diagonalMax = diagonalForwardEnd; let diagonalRelative = (midOriginalArr[0] - midModifiedArr[0]) - diagonalForwardOffset; let lastOriginalIndex = -1073741824 /* 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 quitting the diff early, we need to shift back the originalStart and modified start //back into the boundary limits since we decremented their value above beyond the boundary limit. originalStart++; modifiedStart++; return [ new diffChange_1.DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1) ]; } } // Run the algorithm in the reverse direction diagonalReverseStart = this.ClipDiagonalBound(diagonalReverseBase - numDifferences, numDifferences, diagonalReverseBase, numDiagonals); diagonalReverseEnd = this.ClipDiagonalBound(diagonalReverseBase + numDifferences, numDifferences, diagonalReverseBase, numDiagonals); for (let diagonal = diagonalReverseStart; diagonal <= diagonalReverseEnd; diagonal += 2) { // STEP 1: We extend the furthest reaching point in the present diagonal // by looking at the diagonals above and below and picking the one whose point // is further away from the start point (originalEnd, modifiedEnd) if (diagonal === diagonalReverseStart || (diagonal < diagonalReverseEnd && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1])) { originalIndex = reversePoints[diagonal + 1] - 1; } else { originalIndex = reversePoints[diagonal - 1]; } modifiedIndex = originalIndex - (diagonal - diagonalReverseBase) - diagonalReverseOffset; // Save the current originalIndex so we can test for false overlap const tempOriginalIndex = originalIndex; // STEP 2: We can continue to extend the furthest reaching point in the present diagonal // as long as the elements are equal. while (originalIndex > originalStart && modifiedIndex > modifiedStart && this.ElementsAreEqual(originalIndex, modifiedIndex)) { originalIndex--; modifiedIndex--; } reversePoints[diagonal] = originalIndex; // STEP 4: If delta is even (overlap first happens on reverse when delta is even) // and diagonal is in the range of forward diagonals computed for numDifferences // then check for overlap. if (deltaIsEven && Math.abs(diagonal - diagonalForwardBase) <= numDifferences) { if (originalIndex <= forwardPoints[diagonal]) { midOriginalArr[0] = originalIndex; midModifiedArr[0] = modifiedIndex; if (tempOriginalIndex >= forwardPoints[diagonal] && 1447 /* 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[167/*vs/base/browser/ui/tree/indexTreeModel*/], __M([1/*require*/,0/*exports*/,109/*vs/base/browser/ui/tree/tree*/,19/*vs/base/common/arrays*/,10/*vs/base/common/async*/,138/*vs/base/common/diff/diff*/,4/*vs/base/common/event*/,54/*vs/base/common/iterator*/]), function (require, exports, tree_1, arrays_1, async_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.refilterDelayer = new async_1.Delayer(async_1.MicrotaskDelay); 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); if (!parentNode.lastDiffIds) { return this.spliceSimple(location, deleteCount, toInsertIterable, options); } const toInsert = [...toInsertIterable]; const index = location[location.length - 1]; const diff = new diff_1.LcsDiff({ getElements: () => parentNode.lastDiffIds }, { getElements: () => [ ...parentNode.children.slice(0, index), ...toInsert, ...parentNode.children.slice(index + deleteCount), ].map(e => identity.getId(e.element).toString()) }).ComputeDiff(false); // if we were given a 'best effort' diff, use default behavior if (diff.quitEarly) { parentNode.lastDiffIds = undefined; return this.spliceSimple(location, deleteCount, toInsert, options); } const locationPrefix = location.slice(0, -1); const recurseSplice = (fromOriginal, fromModified, count) => { if (recurseLevels > 0) { for (let i = 0; i < count; i++) { fromOriginal--; fromModified--; this.spliceSmart(identity, [...locationPrefix, fromOriginal, 0], Number.MAX_SAFE_INTEGER, toInsert[fromModified].children, options, recurseLevels - 1); } } }; let lastStartO = Math.min(parentNode.children.length, index + deleteCount); let lastStartM = toInsert.length; for (const change of diff.changes.sort((a, b) => b.originalStart - a.originalStart)) { recurseSplice(lastStartO, lastStartM, lastStartO - (change.originalStart + change.originalLength)); lastStartO = change.originalStart; lastStartM = change.modifiedStart - index; this.spliceSimple([...locationPrefix, lastStartO], change.originalLength, iterator_1.Iterable.slice(toInsert, lastStartM, lastStartM + change.modifiedLength), options); } // at this point, startO === startM === count since any remaining prefix should match recurseSplice(lastStartO, lastStartM, lastStartO); } spliceSimple(location, deleteCount, toInsert = iterator_1.Iterable.empty(), { onDidCreateNode, onDidDeleteNode, diffIdentityProvider }) { const { parentNode, listIndex, revealed, visible } = this.getParentNodeWithListIndex(location); const treeListElementsToInsert = []; const nodesToInsertIterator = iterator_1.Iterable.map(toInsert, el => this.createTreeNode(el, parentNode, parentNode.visible ? 1 /* 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); if (!diffIdentityProvider) { parentNode.lastDiffIds = undefined; } else if (parentNode.lastDiffIds) { (0, arrays_1.splice)(parentNode.lastDiffIds, lastIndex, deleteCount, nodesToInsert.map(n => diffIdentityProvider.getId(n.element).toString())); } else { parentNode.lastDiffIds = parentNode.children.map(n => diffIdentityProvider.getId(n.element).toString()); } // figure out what is the count of deleted visible children let deletedVisibleChildrenCount = 0; for (const child of deletedNodes) { if (child.visible) { deletedVisibleChildrenCount++; } } // and adjust for all visible children after the splice point if (deletedVisibleChildrenCount !== 0) { for (let i = lastIndex + nodesToInsert.length; i < parentNode.children.length; i++) { const child = parentNode.children[i]; if (child.visible) { child.visibleChildIndex -= deletedVisibleChildrenCount; } } } // update parent's visible children count parentNode.visibleChildrenCount += insertedVisibleChildrenCount - deletedVisibleChildrenCount; if (revealed && visible) { const visibleDeleteCount = deletedNodes.reduce((r, node) => r + (node.visible ? node.renderNodeCount : 0), 0); this._updateAncestorsRenderNodeCount(parentNode, renderNodeCount - visibleDeleteCount); this.list.splice(listIndex, visibleDeleteCount, treeListElementsToInsert); } if (deletedNodes.length > 0 && onDidDeleteNode) { const visit = (node) => { onDidDeleteNode(node); node.children.forEach(visit); }; deletedNodes.forEach(visit); } 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 */) { // delayed to avoid excessive refiltering, see #135941 this.refilterDelayer.trigger(() => this.refilter()); break; } node = node.parent; } } rerender(location) { if (location.length === 0) { throw new tree_1.TreeError(this.user, 'Invalid tree location'); } const { node, listIndex, revealed } = this.getTreeNodeWithListIndex(location); if (node.visible && revealed) { this.list.splice(listIndex, 1, [node]); } } has(location) { return this.hasTreeNode(location); } getListIndex(location) { const { listIndex, visible, revealed } = this.getTreeNodeWithListIndex(location); return visible && revealed ? listIndex : -1; } getListRenderCount(location) { return this.getTreeNode(location).renderNodeCount; } isCollapsible(location) { return this.getTreeNode(location).collapsible; } setCollapsible(location, collapsible) { const node = this.getTreeNode(location); if (typeof collapsible === 'undefined') { collapsible = !node.collapsible; } const update = { collapsible }; return this.eventBufferer.bufferEvents(() => this._setCollapseState(location, update)); } isCollapsed(location) { return this.getTreeNode(location).collapsed; } setCollapsed(location, collapsed, recursive) { const node = this.getTreeNode(location); if (typeof collapsed === 'undefined') { collapsed = !node.collapsed; } const update = { collapsed, recursive: recursive || false }; return this.eventBufferer.bufferEvents(() => this._setCollapseState(location, update)); } _setCollapseState(location, update) { const { node, listIndex, revealed } = this.getTreeNodeWithListIndex(location); const result = this._setListNodeCollapseState(node, listIndex, revealed, update); if (node !== this.root && this.autoExpandSingleChildren && result && !isCollapsibleStateUpdate(update) && node.collapsible && !node.collapsed && !update.recursive) { let onlyVisibleChildIndex = -1; for (let i = 0; i < node.children.length; i++) { const child = node.children[i]; if (child.visible) { if (onlyVisibleChildIndex > -1) { onlyVisibleChildIndex = -1; break; } else { onlyVisibleChildIndex = i; } } } if (onlyVisibleChildIndex > -1) { this._setCollapseState([...location, onlyVisibleChildIndex], update); } } return result; } _setListNodeCollapseState(node, listIndex, revealed, update) { const result = this._setNodeCollapseState(node, update, false); if (!revealed || !node.visible || !result) { return result; } const previousRenderNodeCount = node.renderNodeCount; const toInsert = this.updateNodeAfterCollapseChange(node); const deleteCount = previousRenderNodeCount - (listIndex === -1 ? 0 : 1); this.list.splice(listIndex + 1, deleteCount, toInsert.slice(1)); return result; } _setNodeCollapseState(node, update, deep) { let result; if (node === this.root) { result = false; } else { if (isCollapsibleStateUpdate(update)) { result = node.collapsible !== update.collapsible; node.collapsible = update.collapsible; } else if (!node.collapsible) { result = false; } else { result = node.collapsed !== update.collapsed; node.collapsed = update.collapsed; } if (result) { this._onDidChangeCollapseState.fire({ node, deep }); } } if (!isCollapsibleStateUpdate(update) && update.recursive) { for (const child of node.children) { result = this._setNodeCollapseState(child, update, true) || result; } } return result; } expandTo(location) { this.eventBufferer.bufferEvents(() => { let node = this.getTreeNode(location); while (node.parent) { node = node.parent; location = location.slice(0, location.length - 1); if (node.collapsed) { this._setCollapseState(location, { collapsed: false, recursive: false }); } } }); } refilter() { const previousRenderNodeCount = this.root.renderNodeCount; const toInsert = this.updateNodeAfterFilterChange(this.root); this.list.splice(0, previousRenderNodeCount, toInsert); this.refilterDelayer.cancel(); } createTreeNode(treeElement, parent, parentVisibility, revealed, treeListElements, onDidCreateNode) { const node = { parent, element: treeElement.element, children: [], depth: parent.depth + 1, visibleChildrenCount: 0, visibleChildIndex: -1, collapsible: typeof treeElement.collapsible === 'boolean' ? treeElement.collapsible : (typeof treeElement.collapsed !== 'undefined'), collapsed: typeof treeElement.collapsed === 'undefined' ? this.collapseByDefault : treeElement.collapsed, renderNodeCount: 1, visibility: 1 /* 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 */); node.visibility = visibility; } if (!node.visible) { node.renderNodeCount = 0; if (revealed) { result.pop(); } } else if (!node.collapsed) { node.renderNodeCount += result.length - resultStartLength; } this._onDidChangeRenderNodeCount.fire(node); return node.visible; } _updateAncestorsRenderNodeCount(node, diff) { if (diff === 0) { return; } while (node) { node.renderNodeCount += diff; this._onDidChangeRenderNodeCount.fire(node); node = node.parent; } } _filterNode(node, parentVisibility) { const result = this.filter ? this.filter.filter(node.element, parentVisibility) : 1 /* 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]; } } getFirstElementChild(location) { const node = this.getTreeNode(location); if (node.children.length === 0) { return undefined; } return node.children[0].element; } } exports.IndexTreeModel = IndexTreeModel; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[168/*vs/base/browser/ui/tree/objectTreeModel*/], __M([1/*require*/,0/*exports*/,167/*vs/base/browser/ui/tree/indexTreeModel*/,109/*vs/base/browser/ui/tree/tree*/,54/*vs/base/common/iterator*/]), function (require, exports, indexTreeModel_1, tree_1, iterator_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ObjectTreeModel = void 0; class ObjectTreeModel { constructor(user, list, options = {}) { this.user = user; this.rootRef = null; this.nodes = new Map(); this.nodesByIdentity = new Map(); this.model = new indexTreeModel_1.IndexTreeModel(user, list, null, options); this.onDidSplice = this.model.onDidSplice; this.onDidChangeCollapseState = this.model.onDidChangeCollapseState; this.onDidChangeRenderNodeCount = this.model.onDidChangeRenderNodeCount; if (options.sorter) { this.sorter = { compare(a, b) { return options.sorter.compare(a.element, b.element); } }; } this.identityProvider = options.identityProvider; } setChildren(element, children = iterator_1.Iterable.empty(), options = {}) { const location = this.getElementLocation(element); this._setChildren(location, this.preserveCollapseState(children), options); } _setChildren(location, children = iterator_1.Iterable.empty(), options) { const insertedElements = new Set(); const insertedElementIds = new Set(); const onDidCreateNode = (node) => { 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); } getFirstElementChild(ref = null) { const location = this.getElementLocation(ref); return this.model.getFirstElementChild(location); } has(element) { return this.nodes.has(element); } getListIndex(element) { const location = this.getElementLocation(element); return this.model.getListIndex(location); } getListRenderCount(element) { const location = this.getElementLocation(element); return this.model.getListRenderCount(location); } isCollapsible(element) { const location = this.getElementLocation(element); return this.model.isCollapsible(location); } setCollapsible(element, collapsible) { const location = this.getElementLocation(element); return this.model.setCollapsible(location, collapsible); } isCollapsed(element) { const location = this.getElementLocation(element); return this.model.isCollapsed(location); } setCollapsed(element, collapsed, recursive) { const location = this.getElementLocation(element); return this.model.setCollapsed(location, collapsed, recursive); } expandTo(element) { const location = this.getElementLocation(element); this.model.expandTo(location); } refilter() { this.model.refilter(); } getNode(element = null) { if (element === null) { return this.model.getNode(this.model.rootRef); } const node = this.nodes.get(element); if (!node) { throw new tree_1.TreeError(this.user, `Tree element not found: ${element}`); } return node; } getNodeLocation(node) { return node.element; } getParentNodeLocation(element) { if (element === null) { throw new tree_1.TreeError(this.user, `Invalid getParentNodeLocation call`); } const node = this.nodes.get(element); if (!node) { throw new tree_1.TreeError(this.user, `Tree element not found: ${element}`); } const location = this.model.getNodeLocation(node); const parentLocation = this.model.getParentNodeLocation(location); const parent = this.model.getNode(parentLocation); return parent.element; } getElementLocation(element) { if (element === null) { return []; } const node = this.nodes.get(element); if (!node) { throw new tree_1.TreeError(this.user, `Tree element not found: ${element}`); } return this.model.getNodeLocation(node); } } exports.ObjectTreeModel = ObjectTreeModel; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[318/*vs/base/browser/ui/tree/compressedObjectTreeModel*/], __M([1/*require*/,0/*exports*/,168/*vs/base/browser/ui/tree/objectTreeModel*/,109/*vs/base/browser/ui/tree/tree*/,4/*vs/base/common/event*/,54/*vs/base/common/iterator*/]), function (require, exports, objectTreeModel_1, tree_1, event_1, iterator_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]; } getFirstElementChild(location) { const compressedNode = this.getCompressedNode(location); return this.model.getFirstElementChild(compressedNode); } isCollapsible(location) { const compressedNode = this.getCompressedNode(location); return this.model.isCollapsible(compressedNode); } setCollapsible(location, collapsible) { const compressedNode = this.getCompressedNode(location); return this.model.setCollapsible(compressedNode, collapsible); } isCollapsed(location) { const compressedNode = this.getCompressedNode(location); return this.model.isCollapsed(compressedNode); } setCollapsed(location, collapsed, recursive) { const compressedNode = this.getCompressedNode(location); return this.model.setCollapsed(compressedNode, collapsed, recursive); } expandTo(location) { const compressedNode = this.getCompressedNode(location); this.model.expandTo(compressedNode); } rerender(location) { const compressedNode = this.getCompressedNode(location); this.model.rerender(compressedNode); } refilter() { this.model.refilter(); } getCompressedNode(element) { if (element === null) { return null; } const node = this.nodes.get(element); if (!node) { throw new tree_1.TreeError(this.user, `Tree element not found: ${element}`); } return node; } } exports.CompressedObjectTreeModel = CompressedObjectTreeModel; const DefaultElementMapper = elements => elements[elements.length - 1]; exports.DefaultElementMapper = DefaultElementMapper; class CompressedTreeNodeWrapper { 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); } getFirstElementChild(location) { const result = this.model.getFirstElementChild(location); if (result === null || typeof result === 'undefined') { return result; } return this.elementMapper(result.elements); } isCollapsible(location) { return this.model.isCollapsible(location); } setCollapsible(location, collapsed) { return this.model.setCollapsible(location, collapsed); } isCollapsed(location) { return this.model.isCollapsed(location); } setCollapsed(location, collapsed, recursive) { return this.model.setCollapsed(location, collapsed, recursive); } expandTo(location) { return this.model.expandTo(location); } rerender(location) { return this.model.rerender(location); } refilter() { return this.model.refilter(); } getCompressedTreeNode(location = null) { return this.model.getNode(location); } } exports.CompressibleObjectTreeModel = CompressibleObjectTreeModel; }); define(__m[47/*vs/base/common/map*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/]), function (require, exports, 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._from = 0; this._to = 0; this._value = key; this._valueLen = key.length; for (let pos = key.length - 1; pos >= 0; pos--, this._valueLen--) { const ch = this._value.charCodeAt(pos); if (!(ch === 47 /* Slash */ || this._splitOnBackslash && ch === 92 /* Backslash */)) { break; } } return this.next(); } hasNext() { return this._to < this._valueLen; } next() { // this._data = key.split(/[\\/]/).filter(s => !!s); this._from = this._to; let justSeps = true; for (; this._to < this._valueLen; this._to++) { const ch = this._value.charCodeAt(this._to); if (ch === 47 /* 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 { constructor() { this.height = 1; } rotateLeft() { const tmp = this.right; this.right = tmp.left; tmp.left = this; this.updateHeight(); tmp.updateHeight(); return tmp; } rotateRight() { const tmp = this.left; this.left = tmp.right; tmp.right = this; this.updateHeight(); tmp.updateHeight(); return tmp; } updateHeight() { this.height = 1 + Math.max(this.heightLeft, this.heightRight); } balanceFactor() { return this.heightRight - this.heightLeft; } get heightLeft() { var _c, _d; return (_d = (_c = this.left) === null || _c === void 0 ? void 0 : _c.height) !== null && _d !== void 0 ? _d : 0; } get heightRight() { var _c, _d; return (_d = (_c = this.right) === null || _c === void 0 ? void 0 : _c.height) !== null && _d !== void 0 ? _d : 0; } } 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(); } const stack = []; // find insert_node node = this._root; while (true) { const val = iter.cmp(node.segment); if (val > 0) { // left if (!node.left) { node.left = new TernarySearchTreeNode(); node.left.segment = iter.value(); } stack.push([-1 /* Left */, node]); node = node.left; } else if (val < 0) { // right if (!node.right) { node.right = new TernarySearchTreeNode(); node.right.segment = iter.value(); } stack.push([1 /* Right */, node]); node = node.right; } else if (iter.hasNext()) { // mid iter.next(); if (!node.mid) { node.mid = new TernarySearchTreeNode(); node.mid.segment = iter.value(); } stack.push([0 /* Mid */, node]); node = node.mid; } else { break; } } // set value const oldElement = node.value; node.value = element; node.key = key; // balance for (let i = stack.length - 1; i >= 0; i--) { const node = stack[i][1]; node.updateHeight(); const bf = node.balanceFactor(); if (bf < -1 || bf > 1) { // needs rotate const d1 = stack[i][0]; const d2 = stack[i + 1][0]; if (d1 === 1 /* Right */ && d2 === 1 /* Right */) { //right, right -> rotate left stack[i][1] = node.rotateLeft(); } else if (d1 === -1 /* Left */ && d2 === -1 /* Left */) { // left, left -> rotate right stack[i][1] = node.rotateRight(); } else if (d1 === 1 /* Right */ && d2 === -1 /* Left */) { // right, left -> double rotate right, left node.right = stack[i + 1][1] = stack[i + 1][1].rotateRight(); stack[i][1] = node.rotateLeft(); } else if (d1 === -1 /* Left */ && d2 === 1 /* Right */) { // left, right -> double rotate left, right node.left = stack[i + 1][1] = stack[i + 1][1].rotateLeft(); stack[i][1] = node.rotateRight(); } else { throw new Error(); } // patch path to parent if (i > 0) { switch (stack[i - 1][0]) { case -1 /* Left */: stack[i - 1][1].left = stack[i][1]; break; case 1 /* Right */: stack[i - 1][1].right = stack[i][1]; break; case 0 /* Mid */: stack[i - 1][1].mid = stack[i][1]; break; } } else { this._root = stack[0][1]; } } } 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) { var _c; const iter = this._iter.reset(key); const stack = []; let node = this._root; // find node while (node) { const val = iter.cmp(node.segment); if (val > 0) { // left stack.push([-1 /* Left */, node]); node = node.left; } else if (val < 0) { // right stack.push([1 /* Right */, node]); node = node.right; } else if (iter.hasNext()) { // mid iter.next(); stack.push([0 /* Mid */, node]); node = node.mid; } else { break; } } if (!node) { // node not found return; } if (superStr) { // removing children, reset height node.left = undefined; node.mid = undefined; node.right = undefined; node.height = 1; } else { // removing element node.key = undefined; node.value = undefined; } // BST node removal if (!node.mid && !node.value) { if (node.left && node.right) { // full node const min = this._min(node.right); const { key, value, segment } = min; this._delete(min.key, false); node.key = key; node.value = value; node.segment = segment; } else { // empty or half empty const newChild = (_c = node.left) !== null && _c !== void 0 ? _c : node.right; if (stack.length > 0) { const [dir, parent] = stack[stack.length - 1]; switch (dir) { case -1 /* Left */: parent.left = newChild; break; case 0 /* Mid */: parent.mid = newChild; break; case 1 /* Right */: parent.right = newChild; break; } } else { this._root = newChild; } } } // AVL balance for (let i = stack.length - 1; i >= 0; i--) { const node = stack[i][1]; node.updateHeight(); const bf = node.balanceFactor(); if (bf > 1) { // right heavy if (node.right.balanceFactor() >= 0) { // right, right -> rotate left stack[i][1] = node.rotateLeft(); } else { // right, left -> double rotate node.right = node.right.rotateRight(); stack[i][1] = node.rotateLeft(); } } else if (bf < -1) { // left heavy if (node.left.balanceFactor() <= 0) { // left, left -> rotate right stack[i][1] = node.rotateRight(); } else { // left, right -> double rotate node.left = node.left.rotateLeft(); stack[i][1] = node.rotateRight(); } } // patch path to parent if (i > 0) { switch (stack[i - 1][0]) { case -1 /* Left */: stack[i - 1][1].left = stack[i][1]; break; case 1 /* Right */: stack[i - 1][1].right = stack[i][1]; break; case 0 /* Mid */: stack[i - 1][1].mid = stack[i][1]; break; } } else { this._root = stack[0][1]; } } } _min(node) { while (node.left) { node = node.left; } return node; } findSubstr(key) { const iter = this._iter.reset(key); let node = this._root; let candidate = undefined; while (node) { const val = iter.cmp(node.segment); if (val > 0) { // left node = node.left; } else if (val < 0) { // right node = node.right; } else if (iter.hasNext()) { // mid iter.next(); candidate = node.value || candidate; node = node.mid; } else { break; } } return node && node.value || candidate; } findSuperstr(key) { 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; } if (node.left) { yield* this._entries(node.left); } if (node.value) { yield [node.key, node.value]; } if (node.mid) { yield* this._entries(node.mid); } if (node.right) { yield* this._entries(node.right); } } } exports.TernarySearchTree = TernarySearchTree; class ResourceMapEntry { constructor(uri, value) { this.uri = uri; this.value = value; } } 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), new ResourceMapEntry(resource, value)); return this; } get(resource) { var _c; return (_c = this.map.get(this.toKey(resource))) === null || _c === void 0 ? void 0 : _c.value; } has(resource) { return this.map.has(this.toKey(resource)); } get size() { return this.map.size; } clear() { this.map.clear(); } delete(resource) { return this.map.delete(this.toKey(resource)); } forEach(clb, thisArg) { if (typeof thisArg !== 'undefined') { clb = clb.bind(thisArg); } for (let [_, entry] of this.map) { clb(entry.value, entry.uri, this); } } *values() { for (let entry of this.map.values()) { yield entry.value; } } *keys() { for (let entry of this.map.values()) { yield entry.uri; } } *entries() { for (let entry of this.map.values()) { yield [entry.uri, entry.value]; } } *[(_a = Symbol.toStringTag, Symbol.iterator)]() { for (let [, entry] of this.map) { yield [entry.uri, entry.value]; } } } 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[73/*vs/base/common/filters*/], __M([1/*require*/,0/*exports*/,47/*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.matchesStrictPrefix = 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; // Prefix exports.matchesStrictPrefix = _matchesPrefix.bind(undefined, false); exports.matchesPrefix = _matchesPrefix.bind(undefined, true); function _matchesPrefix(ignoreCase, word, wordToMatchAgainst) { if (!wordToMatchAgainst || wordToMatchAgainst.length < word.length) { return null; } let matches; if (ignoreCase) { matches = strings.startsWithIgnoreCase(wordToMatchAgainst, word); } else { matches = wordToMatchAgainst.indexOf(word) === 0; } if (!matches) { return null; } return word.length > 0 ? [{ start: 0, end: word.length }] : []; } // Contiguous Substring function matchesContiguousSubString(word, wordToMatchAgainst) { const index = wordToMatchAgainst.toLowerCase().indexOf(word.toLowerCase()); if (index === -1) { return null; } return [{ start: index, end: index + word.length }]; } 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(); // These are chosen as natural word separators based on writen text. // It is a subset of the word separators used by the monaco editor. '()[]{}<>`\'"-/;:,.?!' .split('') .forEach(s => wordSeparators.add(s.charCodeAt(0))); function isWordSeparator(code) { return isWhitespace(code) || wordSeparators.has(code); } function charactersMatch(codeA, codeB) { return (codeA === codeB) || (isWordSeparator(codeA) && isWordSeparator(codeB)); } 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 preferred gap location score += isGapLocation ? 0 : 1; } } if (wordPos + 1 === wordLen) { // we always penalize gaps, but this gives unfair advantages to a match that would match the last character in the word // so pretend there is a gap after the last character in the word to normalize things score -= isGapLocation ? 3 : 5; } return score; } //#endregion //#region --- graceful --- function fuzzyScoreGracefulAggressive(pattern, lowPattern, patternPos, word, lowWord, wordPos, 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[319/*vs/base/common/fuzzyScorer*/], __M([1/*require*/,0/*exports*/,73/*vs/base/common/filters*/,82/*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)]; } const NO_ITEM_SCORE = Object.freeze({ score: 0 }); function normalizeMatches(matches) { // sort matches by start to be able to normalize const sortedMatches = matches.sort((matchA, matchB) => { return matchA.start - matchB.start; }); // merge matches that overlap const normalizedMatches = []; let currentMatch = undefined; for (const match of sortedMatches) { // if we have no current match or the matches // do not overlap, we take it as is and remember // it for future merging if (!currentMatch || !matchOverlaps(currentMatch, match)) { currentMatch = match; normalizedMatches.push(match); } // otherwise we merge the matches else { currentMatch.start = Math.min(currentMatch.start, match.start); currentMatch.end = Math.max(currentMatch.end, match.end); } } return normalizedMatches; } function matchOverlaps(matchA, matchB) { if (matchA.end < matchB.start) { return false; // A ends before B starts } if (matchB.end < matchA.start) { return false; // B ends before A starts } return true; } /* * If a query is wrapped in quotes, the user does not want to * use fuzzy search for this query. */ function queryExpectsExactMatch(query) { return query.startsWith('"') && query.endsWith('"'); } /** * Helper function to prepare a search value for scoring by removing unwanted characters * and allowing to score on multiple pieces separated by whitespace character. */ const MULTIPLE_QUERY_VALUES_SEPARATOR = ' '; function prepareQuery(original) { if (typeof original !== 'string') { original = ''; } const originalLowercase = original.toLowerCase(); const { pathNormalized, normalized, normalizedLowercase } = normalizeQuery(original); const containsPathSeparator = pathNormalized.indexOf(path_1.sep) >= 0; const expectExactMatch = queryExpectsExactMatch(original); let values = undefined; const originalSplit = original.split(MULTIPLE_QUERY_VALUES_SEPARATOR); if (originalSplit.length > 1) { for (const originalPiece of originalSplit) { const expectExactMatchPiece = queryExpectsExactMatch(originalPiece); const { pathNormalized: pathNormalizedPiece, normalized: normalizedPiece, normalizedLowercase: normalizedLowercasePiece } = normalizeQuery(originalPiece); if (normalizedPiece) { if (!values) { values = []; } values.push({ original: originalPiece, originalLowercase: originalPiece.toLowerCase(), pathNormalized: pathNormalizedPiece, normalized: normalizedPiece, normalizedLowercase: normalizedLowercasePiece, expectContiguousMatch: expectExactMatchPiece }); } } } return { original, originalLowercase, pathNormalized, normalized, normalizedLowercase, values, containsPathSeparator, expectContiguousMatch: expectExactMatch }; } 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 } // we remove quotes here because quotes are used for exact match search const normalized = (0, strings_1.stripWildcards)(pathNormalized).replace(/\s|"/g, ''); return { pathNormalized, normalized, normalizedLowercase: normalized.toLowerCase() }; } function pieceToQuery(arg1) { if (Array.isArray(arg1)) { return prepareQuery(arg1.map(piece => piece.original).join(MULTIPLE_QUERY_VALUES_SEPARATOR)); } return prepareQuery(arg1.original); } 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[215/*vs/base/common/glob*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/async*/,166/*vs/base/common/extpath*/,47/*vs/base/common/map*/,82/*vs/base/common/path*/,17/*vs/base/common/platform*/,8/*vs/base/common/strings*/]), function (require, exports, async_1, extpath_1, map_1, path_1, platform_1, strings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isRelativePattern = exports.parse = exports.match = exports.splitGlobAware = exports.GLOB_SPLIT = exports.GLOBSTAR = void 0; exports.GLOBSTAR = '**'; exports.GLOB_SPLIT = '/'; const PATH_REGEX = '[/\\\\]'; // any slash or backslash const NO_PATH_REGEX = '[^/\\\\]'; // any non-slash and non-backslash const ALL_FORWARD_SLASHES = /\//g; function starsToRegExp(starCount) { 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, exports.GLOB_SPLIT); // Special case where we only have globstars if (segments.every(s => s === exports.GLOBSTAR)) { regEx = '.*'; } // Build regex over segments else { let previousSegmentWasGlobStar = false; segments.forEach((segment, index) => { // Globstar is special if (segment === exports.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 === exports.GLOB_SPLIT) { res = ''; } // anything else gets escaped else { res = (0, strings_1.escapeRegExpCharacters)(char); } bracketVal += res; continue; } switch (char) { case '{': inBraces = true; continue; case '[': inBrackets = true; continue; case '}': { const choices = splitGlobAware(braceVal, ','); // Converts {foo,bar} => [foo|bar] const braceRegExp = `(?:${choices.map(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 += (0, strings_1.escapeRegExpCharacters)(char); } } // Tail: Add the slash we had split on if there is more to come and the remaining pattern is not a globstar // For example if pattern: some/**/*.js we want the "/" after some to be included in the RegEx to prevent // a folder called "something" to match as well. // 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] !== exports.GLOBSTAR || index + 2 < segments.length)) { regEx += PATH_REGEX; } // reset state previousSegmentWasGlobStar = false; }); } return regEx; } // regexes to check for trivial glob patterns that just check for String#endsWith const T1 = /^\*\*\/\*\.[\w\.-]+$/; // **/*.something const T2 = /^\*\*\/([\w\.-]+)\/?$/; // **/something const T3 = /^{\*\*\/[\*\.]?[\w\.-]+\/?(,\*\*\/[\*\.]?[\w\.-]+\/?)*}$/; // {**/*.something,**/*.else} or {**/package.json,**/project.json} const T3_2 = /^{\*\*\/[\*\.]?[\w\.-]+(\/(\*\*)?)?(,\*\*\/[\*\.]?[\w\.-]+(\/(\*\*)?)?)*}$/; // Like T3, with optional trailing /** const T4 = /^\*\*((\/[\w\.-]+)+)\/?$/; // **/something/else const T5 = /^([\w\.-]+(\/[\w\.-]+)*)\/?$/; // something/else const CACHE = new map_1.LRUCache(10000); // bounded to 10000 elements const FALSE = function () { return false; }; const NULL = function () { return null; }; function parsePattern(arg1, options) { if (!arg1) { return NULL; } // Handle 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 Trivials 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 (!(0, extpath_1.isEqualOrParent)(path, arg2.base, !platform_1.isLinux)) { // skip glob matching if `base` is not a parent of `path` return null; } // Given we have checked `base` being a parent of `path`, // we can now remove the `base` portion of the `path` // and only match on the remaining path components return parsedPattern(path.substr(arg2.base.length + 1), 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 = path_1.sep === path_1.posix.sep; const nativePath = usingPosixSep ? targetPath : targetPath.replace(ALL_FORWARD_SLASHES, path_1.sep); const nativePathEnd = path_1.sep + nativePath; const targetPathEnd = path_1.posix.sep + targetPath; 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; if (!rp) { return false; } return 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, base, 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 (!base) { base = (0, path_1.basename)(path); } if (!name) { name = base.substr(0, base.length - (0, path_1.extname)(path).length); } } const result = parsedPattern(path, base, name, hasSibling); if (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 if (typeof value === 'boolean') { return parsedPattern; } // Expression Pattern is 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[95/*vs/base/common/iconLabels*/], __M([1/*require*/,0/*exports*/,27/*vs/base/common/codicons*/,73/*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 iconNameCharacterRegexp = new RegExp(codicons_1.CSSIcon.iconNameCharacter); 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 (iconNameCharacterRegexp.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[66/*vs/base/common/htmlContent*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/errors*/,95/*vs/base/common/iconLabels*/]), function (require, exports, errors_1, iconLabels_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, _c; this.value = value; if (typeof this.value !== 'string') { throw (0, errors_1.illegalArgument)('value'); } if (typeof isTrustedOrOptions === 'boolean') { this.isTrusted = isTrustedOrOptions; this.supportThemeIcons = false; this.supportHtml = false; } else { this.isTrusted = (_a = isTrustedOrOptions.isTrusted) !== null && _a !== void 0 ? _a : undefined; this.supportThemeIcons = (_b = isTrustedOrOptions.supportThemeIcons) !== null && _b !== void 0 ? _b : false; this.supportHtml = (_c = isTrustedOrOptions.supportHtml) !== null && _c !== void 0 ? _c : false; } } appendText(value, newlineStyle = 0 /* Paragraph */) { this.value += escapeMarkdownSyntaxTokens(this.supportThemeIcons ? (0, iconLabels_1.escapeIcons)(value) : value) .replace(/([ \t]+)/g, (_match, g1) => ' '.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[320/*vs/base/common/search*/], __M([1/*require*/,0/*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([1/*require*/,0/*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([1/*require*/,0/*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.isDefined = 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 defined. */ function isDefined(arg) { return !isUndefinedOrNull(arg); } exports.isDefined = isDefined; /** * @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[39/*vs/base/common/objects*/], __M([1/*require*/,0/*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[139/*vs/base/common/uint*/], __M([1/*require*/,0/*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[25/*vs/base/common/uri*/], __M([1/*require*/,0/*exports*/,82/*vs/base/common/path*/,17/*vs/base/common/platform*/]), function (require, exports, paths, platform_1) { "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.example.com/some/path`, * `file:///usr/home`, or `scheme:with/path`. * * @param value A string which represents an URI (see `URI#toString`). */ static parse(value, _strict = false) { const match = _regexp.exec(value); if (!match) { return new Uri(_empty, _empty, _empty, _empty, _empty); } return new Uri(match[2] || _empty, percentDecode(match[4] || _empty), percentDecode(match[5] || _empty), percentDecode(match[7] || _empty), percentDecode(match[9] || _empty), _strict); } /** * Creates a new URI from a file system path, e.g. `c:\my\files`, * `/usr/home`, or `\\server\share\some\path`. * * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as** * `URI.parse('file://' + path)` because the path might contain characters that are * interpreted (# and ?). See the following sample: * ```ts const good = URI.file('/coding/c#/project1'); good.scheme === 'file'; good.path === '/coding/c#/project1'; good.fragment === ''; const bad = URI.parse('file://' + '/coding/c#/project1'); bad.scheme === 'file'; bad.path === '/coding/c'; // path is now broken bad.fragment === '/project1'; ``` * * @param path A file system path (see `URI#fsPath`) */ static file(path) { let authority = _empty; // normalize to fwd-slashes on windows, // on other systems bwd-slashes are valid // filename character, eg /f\oo/ba\r.txt if (platform_1.isWindows) { path = path.replace(/\\/g, _slash); } // check for authority as used in UNC shares // or use the path as given if (path[0] === _slash && path[1] === _slash) { const idx = path.indexOf(_slash, 2); if (idx === -1) { authority = path.substring(2); path = _slash; } else { authority = path.substring(2, idx); path = path.substring(idx) || _slash; } } return new Uri('file', authority, path, _empty, _empty); } 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 compatible with vscode.Uri (API). class Uri extends URI { constructor() { super(...arguments); this._formatted = null; this._fsPath = null; } get fsPath() { if (!this._fsPath) { this._fsPath = uriToFsPath(this, false); } return this._fsPath; } toString(skipEncoding = false) { if (!skipEncoding) { if (!this._formatted) { this._formatted = _asFormatted(this, false); } return this._formatted; } else { // we don't cache that return _asFormatted(this, true); } } toJSON() { const res = { $mid: 1 /* 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) { // @ const userinfo = authority.substr(0, idx); authority = authority.substr(idx + 1); idx = userinfo.indexOf(':'); if (idx === -1) { res += encoder(userinfo, false); } else { // :@ 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 { // : 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[216/*vs/base/common/marshalling*/], __M([1/*require*/,0/*exports*/,110/*vs/base/common/buffer*/,25/*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); case 14 /* Date */: return new Date(obj.source); } if (obj instanceof buffer_1.VSBuffer || obj instanceof Uint8Array) { return obj; } if (Array.isArray(obj)) { for (let i = 0; i < obj.length; ++i) { obj[i] = revive(obj[i], depth + 1); } } else { // walk object for (const key in obj) { if (Object.hasOwnProperty.call(obj, key)) { obj[key] = revive(obj[key], depth + 1); } } } } return obj; } 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[48/*vs/base/common/network*/], __M([1/*require*/,0/*exports*/,17/*vs/base/common/platform*/,25/*vs/base/common/uri*/]), function (require, exports, platform, uri_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FileAccess = exports.RemoteAuthorities = exports.connectionTokenQueryName = 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'; /** * Scheme used internally for webviews that aren't linked to a resource (i.e. not custom editors) */ Schemas.webviewPanel = 'webview-panel'; /** * Scheme used for loading the wrapper html and script in webviews. */ Schemas.vscodeWebview = 'vscode-webview'; /** * Scheme used for extension pages */ Schemas.extension = 'extension'; /** * Scheme used as a replacement of `file` scheme to load * files with our custom protocol handler (desktop only). */ Schemas.vscodeFileResource = 'vscode-file'; /** * Scheme used for temporary resources */ Schemas.tmp = 'tmp'; /** * Scheme used vs live share */ Schemas.vsls = 'vsls'; })(Schemas = exports.Schemas || (exports.Schemas = {})); exports.connectionTokenQueryName = 'tkn'; class RemoteAuthoritiesImpl { constructor() { this._hosts = Object.create(null); this._ports = Object.create(null); this._connectionTokens = Object.create(null); this._preferredWebSchema = 'http'; this._delegate = null; } 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 += `&${exports.connectionTokenQueryName}=${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 { asBrowserUri(uriOrModule, moduleIdToUrl) { const uri = this.toUri(uriOrModule, moduleIdToUrl); // Handle remote URIs via `RemoteAuthorities` if (uri.scheme === Schemas.vscodeRemote) { return exports.RemoteAuthorities.rewrite(uri); } // Convert to `vscode-file` resource.. if ( // ...only ever for `file` resources uri.scheme === Schemas.file && ( // ...and we run in native environments platform.isNative || // ...or web worker extensions on desktop (typeof platform.globals.importScripts === 'function' && platform.globals.origin === `${Schemas.vscodeFileResource}://${FileAccessImpl.FALLBACK_AUTHORITY}`))) { return uri.with({ scheme: Schemas.vscodeFileResource, // We need to provide an authority here so that it can serve // as origin for network and loading matters in chromium. // If the URI is not coming with an authority already, we // add our own authority: uri.authority || FileAccessImpl.FALLBACK_AUTHORITY, query: null, fragment: null }); } return uri; } toUri(uriOrModule, moduleIdToUrl) { if (uri_1.URI.isUri(uriOrModule)) { return uriOrModule; } return uri_1.URI.parse(moduleIdToUrl.toUrl(uriOrModule)); } } FileAccessImpl.FALLBACK_AUTHORITY = 'vscode-app'; 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([1/*require*/,0/*exports*/,34/*vs/base/browser/browser*/,165/*vs/base/browser/canIUse*/,46/*vs/base/browser/keyboardEvent*/,56/*vs/base/browser/mouseEvent*/,10/*vs/base/common/async*/,13/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,48/*vs/base/common/network*/,17/*vs/base/common/platform*/]), function (require, exports, browser, canIUse_1, keyboardEvent_1, mouseEvent_1, async_1, errors_1, event_1, lifecycle_1, network_1, platform) { "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.createEventEmitter = exports.addDisposableNonBubblingPointerOutListener = exports.addDisposableNonBubblingMouseOutListener = exports.addDisposableGenericMouseUpListner = exports.addDisposableGenericMouseDownListner = exports.addStandardDisposableGenericMouseUpListner = 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; let addStandardDisposableGenericMouseUpListner = function addStandardDisposableListener(node, handler, useCapture) { let wrapHandler = _wrapAsStandardMouseEvent(handler); return addDisposableGenericMouseUpListner(node, wrapHandler, useCapture); }; exports.addStandardDisposableGenericMouseUpListner = addStandardDisposableGenericMouseUpListner; 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; function createEventEmitter(target, type, options) { let domListener = null; const handler = (e) => result.fire(e); const onFirstListenerAdd = () => { if (!domListener) { domListener = new DomListener(target, type, handler, options); } }; const onLastListenerRemove = () => { if (domListener) { domListener.dispose(); domListener = null; } }; const result = new event_1.Emitter({ onFirstListenerAdd, onLastListenerRemove }); return result; } exports.createEventEmitter = createEventEmitter; 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; Dimension.None = new Dimension(0, 0); 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', PAGE_SHOW: 'pageshow', PAGE_HIDE: 'pagehide', 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 = FocusTracker.hasFocusWithin(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 = FocusTracker.hasFocusWithin(element); if (currentNodeHasFocus !== hasFocus) { if (hasFocus) { onBlur(); } else { onFocus(); } } }; this._register(addDisposableListener(element, exports.EventType.FOCUS, onFocus, true)); this._register(addDisposableListener(element, exports.EventType.BLUR, onBlur, true)); this._register(addDisposableListener(element, exports.EventType.FOCUS_IN, () => this._refreshStateHandler())); this._register(addDisposableListener(element, exports.EventType.FOCUS_OUT, () => this._refreshStateHandler())); } static hasFocusWithin(element) { const shadowRoot = getShadowRoot(element); const activeElement = (shadowRoot ? shadowRoot.activeElement : document.activeElement); return isAncestor(activeElement, element); } } 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 browser's popup blocker. * If you want to tell if the browser blocked the new window, use {@link windowOpenWithSuccess}. * * See https://github.com/microsoft/monaco-editor/issues/601 * To protect against malicious code in the linked site, particularly phishing attempts, * the window.opener should be set to null to prevent the linked site from having access * to change the location of the current page. * See https://mathiasbynens.github.io/rel-noopener/ */ function windowOpenNoOpener(url) { // By using 'noopener' in the `windowFeatures` argument, the newly created window will // not be able to use `window.opener` to reach back to the current page. // See https://stackoverflow.com/a/46958731 // See https://developer.mozilla.org/en-US/docs/Web/API/Window/open#noopener // However, this also doesn't allow us to realize if the browser blocked // the creation of the window. window.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); mediaQueryList.addEventListener('change', 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[169/*vs/base/browser/formattedTextRenderer*/], __M([1/*require*/,0/*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.renderCodeSegments), options.actionHandler, options.renderCodeSegments); 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, renderCodeSegments) { 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 */ && renderCodeSegments) { child = document.createElement('code'); } else if (treeNode.type === 5 /* Action */ && actionHandler) { const a = document.createElement('a'); actionHandler.disposables.add(DOM.addStandardDisposableListener(a, 'click', (event) => { actionHandler.callback(String(treeNode.index), event); })); child = a; } else if (treeNode.type === 8 /* 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, renderCodeSegments); }); } } 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[96/*vs/base/browser/globalMouseMoveMonitor*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,211/*vs/base/browser/iframe*/,56/*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[57/*vs/base/browser/touch*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,19/*vs/base/common/arrays*/,93/*vs/base/common/decorators*/,2/*vs/base/common/lifecycle*/]), function (require, exports, DomUtils, arrays, decorators_1, lifecycle_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[113/*vs/base/browser/ui/iconLabel/iconLabels*/], __M([1/*require*/,0/*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[217/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,113/*vs/base/browser/ui/iconLabel/iconLabels*/,39/*vs/base/common/objects*/]), function (require, exports, dom, iconLabels_1, objects) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HighlightedLabel = void 0; /** * A widget which can render a label with substring highlights, often * originating from a filter function like the fuzzy matcher. */ class HighlightedLabel { /** * Create a new {@link HighlightedLabel}. * * @param container The parent container to append to. */ constructor(container, options) { var _a; this.text = ''; this.title = ''; this.highlights = []; this.didEverRender = false; this.supportIcons = (_a = options === null || options === void 0 ? void 0 : options.supportIcons) !== null && _a !== void 0 ? _a : false; this.domNode = dom.append(container, dom.$('span.monaco-highlighted-label')); } /** * The label's DOM node. */ get element() { return this.domNode; } /** * Set the label and highlights. * * @param text The label to display. * @param highlights The ranges to highlight. * @param title An optional title for the hover tooltip. * @param escapeNewLines Whether to escape new lines. * @returns */ set(text, highlights = [], title = '', escapeNewLines) { if (!text) { text = ''; } if (escapeNewLines) { // adjusts highlights inplace text = HighlightedLabel.escapeNewLines(text, highlights); } if (this.didEverRender && this.text === text && this.title === title && objects.equals(this.highlights, highlights)) { return; } this.text = text; this.title = title; this.highlights = highlights; this.render(); } render() { const children = []; let pos = 0; for (const highlight of this.highlights) { if (highlight.end === highlight.start) { continue; } if (pos < highlight.start) { const substring = this.text.substring(pos, highlight.start); 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[321/*vs/base/browser/ui/list/rowCache*/], __M([1/*require*/,0/*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[60/*vs/base/browser/ui/widget*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,46/*vs/base/browser/keyboardEvent*/,56/*vs/base/browser/mouseEvent*/,57/*vs/base/browser/touch*/,2/*vs/base/common/lifecycle*/]), function (require, exports, dom, keyboardEvent_1, mouseEvent_1, touch_1, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Widget = void 0; class Widget extends lifecycle_1.Disposable { onclick(domNode, listener) { this._register(dom.addDisposableListener(domNode, dom.EventType.CLICK, (e) => listener(new mouseEvent_1.StandardMouseEvent(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[170/*vs/base/browser/ui/scrollbar/scrollbarArrow*/], __M([1/*require*/,0/*exports*/,96/*vs/base/browser/globalMouseMoveMonitor*/,60/*vs/base/browser/ui/widget*/,10/*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[218/*vs/base/browser/ui/scrollbar/abstractScrollbar*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,96/*vs/base/browser/globalMouseMoveMonitor*/,170/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,316/*vs/base/browser/ui/scrollbar/scrollbarVisibilityController*/,60/*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[322/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/], __M([1/*require*/,0/*exports*/,56/*vs/base/browser/mouseEvent*/,218/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,170/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,212/*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; 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: codicons_1.Codicon.scrollbarButtonLeft, top: scrollbarDelta, left: arrowDelta, bottom: undefined, right: undefined, bgWidth: options.arrowSize, bgHeight: options.horizontalScrollbarSize, onActivate: () => this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, 1, 0)), }); this._createArrow({ className: 'scra', icon: codicons_1.Codicon.scrollbarButtonRight, top: scrollbarDelta, left: undefined, bottom: undefined, right: arrowDelta, bgWidth: options.arrowSize, bgHeight: options.horizontalScrollbarSize, onActivate: () => this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, -1, 0)), }); } this._createSlider(Math.floor((options.horizontalScrollbarSize - options.horizontalSliderSize) / 2), 0, undefined, options.horizontalSliderSize); } _updateSlider(sliderSize, sliderPosition) { this.slider.setWidth(sliderSize); this.slider.setLeft(sliderPosition); } _renderDomNode(largeSize, smallSize) { this.domNode.setWidth(largeSize); this.domNode.setHeight(smallSize); this.domNode.setLeft(0); this.domNode.setBottom(0); } onDidScroll(e) { this._shouldRender = this._onElementScrollSize(e.scrollWidth) || this._shouldRender; this._shouldRender = this._onElementScrollPosition(e.scrollLeft) || this._shouldRender; this._shouldRender = this._onElementSize(e.width) || this._shouldRender; return this._shouldRender; } _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[323/*vs/base/browser/ui/scrollbar/verticalScrollbar*/], __M([1/*require*/,0/*exports*/,56/*vs/base/browser/mouseEvent*/,218/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,170/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,212/*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; 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: codicons_1.Codicon.scrollbarButtonUp, top: arrowDelta, left: scrollbarDelta, bottom: undefined, right: undefined, bgWidth: options.verticalScrollbarSize, bgHeight: options.arrowSize, onActivate: () => this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, 0, 1)), }); this._createArrow({ className: 'scra', icon: codicons_1.Codicon.scrollbarButtonDown, top: undefined, left: scrollbarDelta, bottom: arrowDelta, right: undefined, bgWidth: options.verticalScrollbarSize, bgHeight: options.arrowSize, onActivate: () => this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, 0, -1)), }); } this._createSlider(0, Math.floor((options.verticalScrollbarSize - options.verticalSliderSize) / 2), options.verticalSliderSize, undefined); } _updateSlider(sliderSize, sliderPosition) { this.slider.setHeight(sliderSize); this.slider.setTop(sliderPosition); } _renderDomNode(largeSize, smallSize) { this.domNode.setWidth(smallSize); this.domNode.setHeight(largeSize); this.domNode.setRight(0); this.domNode.setTop(0); } onDidScroll(e) { this._shouldRender = this._onElementScrollSize(e.scrollHeight) || this._shouldRender; this._shouldRender = this._onElementScrollPosition(e.scrollTop) || this._shouldRender; this._shouldRender = this._onElementSize(e.height) || this._shouldRender; return this._shouldRender; } _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[41/*vs/base/common/resources*/], __M([1/*require*/,0/*exports*/,166/*vs/base/common/extpath*/,48/*vs/base/common/network*/,82/*vs/base/common/path*/,17/*vs/base/common/platform*/,8/*vs/base/common/strings*/,25/*vs/base/common/uri*/]), function (require, exports, extpath, network_1, paths, platform_1, strings_1, uri_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DataUri = exports.addTrailingPathSeparator = exports.removeTrailingPathSeparator = exports.hasTrailingPathSeparator = exports.isEqualAuthority = exports.isAbsolutePath = exports.resolvePath = exports.relativePath = exports.normalizePath = exports.joinPath = exports.dirname = exports.extname = exports.basename = exports.basenameOrAuthority = exports.getComparisonKey = exports.isEqualOrParent = exports.isEqual = exports.extUriIgnorePathCase = exports.extUriBiasedIgnorePathCase = exports.extUri = exports.ExtUri = 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(); } isEqualOrParent(base, parentCandidate, ignoreFragment = false) { if (base.scheme === parentCandidate.scheme) { if (base.scheme === network_1.Schemas.file) { return extpath.isEqualOrParent(originalFSPath(base), originalFSPath(parentCandidate), this._ignorePathCasing(base)) && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment); } if ((0, exports.isEqualAuthority)(base.authority, parentCandidate.authority)) { return extpath.isEqualOrParent(base.path, parentCandidate.path, this._ignorePathCasing(base), '/') && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment); } } return false; } // --- path math joinPath(resource, ...pathFragment) { return uri_1.URI.joinPath(resource, ...pathFragment); } basenameOrAuthority(resource) { return (0, exports.basename)(resource) || resource.authority; } basename(resource) { return paths.posix.basename(resource.path); } extname(resource) { return paths.posix.extname(resource.path); } dirname(resource) { if (resource.path.length === 0) { return resource; } let dirname; if (resource.scheme === network_1.Schemas.file) { dirname = uri_1.URI.file(paths.dirname(originalFSPath(resource))).path; } else { dirname = paths.posix.dirname(resource.path); if (resource.authority && dirname.length && dirname.charCodeAt(0) !== 47 /* Slash */) { console.error(`dirname("${resource.toString})) resulted in a relative path`); dirname = '/'; // If a URI contains an authority component, then the path component must either be empty or begin with a CharCode.Slash ("/") character } } return resource.with({ path: dirname }); } normalizePath(resource) { if (!resource.path.length) { return resource; } let normalizedPath; if (resource.scheme === network_1.Schemas.file) { normalizedPath = uri_1.URI.file(paths.normalize(originalFSPath(resource))).path; } else { normalizedPath = paths.posix.normalize(resource.path); } return resource.with({ path: normalizedPath }); } relativePath(from, to) { if (from.scheme !== to.scheme || !(0, exports.isEqualAuthority)(from.authority, to.authority)) { return undefined; } if (from.scheme === network_1.Schemas.file) { const relativePath = paths.relative(originalFSPath(from), originalFSPath(to)); return platform_1.isWindows ? extpath.toSlashes(relativePath) : relativePath; } let fromPath = from.path || '/', toPath = to.path || '/'; if (this._ignorePathCasing(from)) { // make casing of fromPath match toPath let i = 0; for (const len = Math.min(fromPath.length, toPath.length); i < len; i++) { if (fromPath.charCodeAt(i) !== toPath.charCodeAt(i)) { if (fromPath.charAt(i).toLowerCase() !== toPath.charAt(i).toLowerCase()) { break; } } } fromPath = toPath.substr(0, i) + fromPath.substr(i); } return paths.posix.relative(fromPath, toPath); } resolvePath(base, path) { if (base.scheme === network_1.Schemas.file) { const newURI = uri_1.URI.file(paths.resolve(originalFSPath(base), path)); return base.with({ authority: newURI.authority, path: newURI.path }); } path = extpath.toPosixPath(path); // we allow path to be a windows path return base.with({ path: paths.posix.resolve(base.path, path) }); } // --- misc isAbsolutePath(resource) { return !!resource.path && resource.path[0] === '/'; } isEqualAuthority(a1, a2) { return a1 === a2 || (a1 !== undefined && a2 !== undefined && (0, strings_1.equalsIgnoreCase)(a1, a2)); } hasTrailingPathSeparator(resource, sep = paths.sep) { if (resource.scheme === network_1.Schemas.file) { const fsp = originalFSPath(resource); return fsp.length > extpath.getRoot(fsp).length && fsp[fsp.length - 1] === sep; } else { const p = resource.path; return (p.length > 1 && p.charCodeAt(p.length - 1) === 47 /* Slash */) && !(/^[a-zA-Z]:(\/$|\\$)/.test(resource.fsPath)); // ignore the slash at offset 0 } } removeTrailingPathSeparator(resource, sep = paths.sep) { // Make sure that the path isn't a drive letter. A trailing separator there is not removable. if ((0, exports.hasTrailingPathSeparator)(resource, sep)) { return resource.with({ path: resource.path.substr(0, resource.path.length - 1) }); } return resource; } addTrailingPathSeparator(resource, sep = paths.sep) { let isRootSep = false; if (resource.scheme === network_1.Schemas.file) { const fsp = originalFSPath(resource); isRootSep = ((fsp !== undefined) && (fsp.length === extpath.getRoot(fsp).length) && (fsp[fsp.length - 1] === sep)); } else { sep = '/'; const p = resource.path; isRootSep = p.length === 1 && p.charCodeAt(p.length - 1) === 47 /* Slash */; } if (!isRootSep && !(0, exports.hasTrailingPathSeparator)(resource, sep)) { return resource.with({ path: resource.path + '/' }); } return resource; } } exports.ExtUri = ExtUri; /** * Unbiased utility that takes uris "as they are". This means it can be interchanged with * uri#toString() usages. The following is true * ``` * assertEqual(aUri.toString() === bUri.toString(), exturi.isEqual(aUri, bUri)) * ``` */ exports.extUri = new ExtUri(() => false); /** * BIASED utility that _mostly_ ignored the case of urs paths. ONLY use this util if you * understand what you are doing. * * This utility is INCOMPATIBLE with `uri.toString()`-usages and both CANNOT be used interchanged. * * When dealing with uris from files or documents, `extUri` (the unbiased friend)is sufficient * because those uris come from a "trustworthy source". When creating unknown uris it's always * better to use `IUriIdentityService` which exposes an `IExtUri`-instance which knows when path * casing matters. */ exports.extUriBiasedIgnorePathCase = new ExtUri(uri => { // A file scheme resource is in the same platform as code, so ignore case for non linux platforms // Resource can be from another platform. Lowering the case as an hack. Should come from File system provider return uri.scheme === network_1.Schemas.file ? !platform_1.isLinux : true; }); /** * BIASED utility that always ignores the casing of uris paths. ONLY use this util if you * understand what you are doing. * * This utility is INCOMPATIBLE with `uri.toString()`-usages and both CANNOT be used interchanged. * * When dealing with uris from files or documents, `extUri` (the unbiased friend)is sufficient * because those uris come from a "trustworthy source". When creating unknown uris it's always * better to use `IUriIdentityService` which exposes an `IExtUri`-instance which knows when path * casing matters. */ exports.extUriIgnorePathCase = new ExtUri(_ => true); exports.isEqual = exports.extUri.isEqual.bind(exports.extUri); exports.isEqualOrParent = exports.extUri.isEqualOrParent.bind(exports.extUri); exports.getComparisonKey = exports.extUri.getComparisonKey.bind(exports.extUri); exports.basenameOrAuthority = exports.extUri.basenameOrAuthority.bind(exports.extUri); exports.basename = exports.extUri.basename.bind(exports.extUri); exports.extname = exports.extUri.extname.bind(exports.extUri); exports.dirname = exports.extUri.dirname.bind(exports.extUri); exports.joinPath = exports.extUri.joinPath.bind(exports.extUri); exports.normalizePath = exports.extUri.normalizePath.bind(exports.extUri); exports.relativePath = exports.extUri.relativePath.bind(exports.extUri); exports.resolvePath = exports.extUri.resolvePath.bind(exports.extUri); exports.isAbsolutePath = exports.extUri.isAbsolutePath.bind(exports.extUri); exports.isEqualAuthority = exports.extUri.isEqualAuthority.bind(exports.extUri); exports.hasTrailingPathSeparator = exports.extUri.hasTrailingPathSeparator.bind(exports.extUri); exports.removeTrailingPathSeparator = exports.extUri.removeTrailingPathSeparator.bind(exports.extUri); exports.addTrailingPathSeparator = exports.extUri.addTrailingPathSeparator.bind(exports.extUri); /** * Data URI related helpers. */ var DataUri; (function (DataUri) { DataUri.META_DATA_LABEL = 'label'; DataUri.META_DATA_DESCRIPTION = 'description'; DataUri.META_DATA_SIZE = 'size'; DataUri.META_DATA_MIME = 'mime'; function parseMetaData(dataUri) { const metadata = new Map(); // Given a URI of: data:image/png;size:2313;label:SomeLabel;description:SomeDescription;base64,77+9UE5... // the metadata is: size:2313;label:SomeLabel;description:SomeDescription const meta = dataUri.path.substring(dataUri.path.indexOf(';') + 1, dataUri.path.lastIndexOf(';')); meta.split(';').forEach(property => { const [key, value] = property.split(':'); if (key && value) { metadata.set(key, value); } }); // Given a URI of: data:image/png;size:2313;label:SomeLabel;description:SomeDescription;base64,77+9UE5... // the mime is: image/png const mime = dataUri.path.substring(0, dataUri.path.indexOf(';')); if (mime) { metadata.set(DataUri.META_DATA_MIME, mime); } return metadata; } DataUri.parseMetaData = parseMetaData; })(DataUri = exports.DataUri || (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[324/*vs/base/browser/markdownRenderer*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,751/*vs/base/browser/dompurify/dompurify*/,89/*vs/base/browser/event*/,169/*vs/base/browser/formattedTextRenderer*/,56/*vs/base/browser/mouseEvent*/,113/*vs/base/browser/ui/iconLabel/iconLabels*/,10/*vs/base/common/async*/,21/*vs/base/common/cancellation*/,13/*vs/base/common/errors*/,4/*vs/base/common/event*/,66/*vs/base/common/htmlContent*/,95/*vs/base/common/iconLabels*/,133/*vs/base/common/idGenerator*/,2/*vs/base/common/lifecycle*/,311/*vs/base/common/marked/marked*/,216/*vs/base/common/marshalling*/,48/*vs/base/common/network*/,39/*vs/base/common/objects*/,41/*vs/base/common/resources*/,8/*vs/base/common/strings*/,25/*vs/base/common/uri*/]), function (require, exports, DOM, dompurify, event_1, formattedTextRenderer_1, mouseEvent_1, iconLabels_1, async_1, cancellation_1, errors_1, event_2, htmlContent_1, iconLabels_2, idGenerator_1, lifecycle_1, marked_1, marshalling_1, network_1, objects_1, resources_1, strings_1, uri_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.renderMarkdown = void 0; /** * 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 disposables = new lifecycle_1.DisposableStore(); let isDisposed = false; const cts = disposables.add(new cancellation_1.CancellationTokenSource()); const element = (0, formattedTextRenderer_1.createElement)(options); const _uriMassage = function (part) { let data; try { data = (0, marshalling_1.parse)(decodeURIComponent(part)); } catch (e) { // ignore } if (!data) { return part; } data = (0, objects_1.cloneAndChange)(data, value => { if (markdown.uris && markdown.uris[value]) { return uri_1.URI.revive(markdown.uris[value]); } else { return undefined; } }); return encodeURIComponent(JSON.stringify(data)); }; const _href = function (href, isDomUri) { const data = markdown.uris && markdown.uris[href]; let uri = uri_1.URI.revive(data); if (isDomUri) { if (href.startsWith(network_1.Schemas.data + ':')) { return href; } if (!uri) { uri = uri_1.URI.parse(href); } // this URI will end up as "src"-attribute of a dom node // and because of that special rewriting needs to be done // so that the URI uses a protocol that's understood by // browsers (like http or https) return network_1.FileAccess.asBrowserUri(uri).toString(true); } if (!uri) { return href; } if (uri_1.URI.parse(href).toString() === uri.toString()) { return href; // no transformation performed } if (uri.query) { uri = uri.with({ query: _uriMassage(uri.query) }); } return uri.toString(); }; // signal to code-block render that the // element has been created let signalInnerHTML; const withInnerHTML = new Promise(c => signalInnerHTML = c); const renderer = new marked_1.marked.Renderer(); renderer.image = (href, title, text) => { let dimensions = []; let attributes = []; if (href) { ({ href, dimensions } = (0, htmlContent_1.parseHrefAndDimensions)(href)); attributes.push(`src="${href}"`); } if (text) { attributes.push(`alt="${text}"`); } if (title) { attributes.push(`title="${title}"`); } if (dimensions.length) { attributes = attributes.concat(dimensions); } return ''; }; renderer.link = (href, title, text) => { if (typeof href !== 'string') { return ''; } // Remove markdown escapes. Workaround for https://github.com/chjj/marked/issues/829 if (href === text) { // raw link case text = (0, htmlContent_1.removeMarkdownEscapes)(text); } 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 = typeof title === 'string' ? (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, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); return `
    ${text}`; } }; renderer.paragraph = (text) => { return `

    ${text}

    `; }; if (options.codeBlockRenderer) { renderer.code = (code, lang) => { if (typeof lang !== 'string') { return ''; } 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(); (0, async_1.raceCancellation)(Promise.all([value, withInnerHTML]), cts.token).then(values => { var _a; if (!isDisposed && values) { const span = element.querySelector(`div[data-code="${id}"]`); if (span) { DOM.reset(span, values[0]); } (_a = options.asyncRenderCallback) === null || _a === void 0 ? void 0 : _a.call(options); } }).catch(() => { // ignore }); return `
    ${(0, strings_1.escape)(code)}
    `; }; } if (options.actionHandler) { const onClick = options.actionHandler.disposables.add(new event_1.DomEmitter(element, 'click')); const onAuxClick = options.actionHandler.disposables.add(new event_1.DomEmitter(element, 'auxclick')); options.actionHandler.disposables.add(event_2.Event.any(onClick.event, onAuxClick.event)(e => { const mouseEvent = new mouseEvent_1.StandardMouseEvent(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(); } })); } if (!markdown.supportHtml) { // TODO: Can we deprecated this in favor of 'supportHtml'? // 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 dompurify after this so that we don't rely on // marked for sanitization. markedOptions.sanitizer = (html) => { const match = markdown.isTrusted ? html.match(/^(]+>)|(<\/\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_2.markdownEscapeEscapedIcons)(value); } let renderedMarkdown = marked_1.marked.parse(value, markedOptions); // Rewrite theme icons if (markdown.supportThemeIcons) { const elements = (0, iconLabels_1.renderLabelWithIcons)(renderedMarkdown); renderedMarkdown = elements.map(e => typeof e === 'string' ? e : e.outerHTML).join(''); } const htmlParser = new DOMParser(); const markdownHtmlDoc = htmlParser.parseFromString(sanitizeRenderedMarkdown(markdown, renderedMarkdown), 'text/html'); markdownHtmlDoc.body.querySelectorAll('img') .forEach(img => { if (img.src) { let href = _href(img.src, 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) { } img.src = href; } }); element.innerHTML = sanitizeRenderedMarkdown(markdown, markdownHtmlDoc.body.innerHTML); // 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 = disposables.add(DOM.addDisposableListener(img, 'load', () => { listener.dispose(); options.asyncRenderCallback(); })); } } return { element, dispose: () => { isDisposed = true; cts.cancel(); disposables.dispose(); } }; } exports.renderMarkdown = renderMarkdown; function sanitizeRenderedMarkdown(options, renderedMarkdown) { const { config, allowedSchemes } = getSanitizerOptions(options); dompurify.addHook('uponSanitizeAttribute', (element, e) => { if (e.attrName === 'style' || e.attrName === 'class') { if (element.tagName === 'SPAN') { if (e.attrName === 'style') { e.keepAttr = /^(color\:#[0-9a-fA-F]+;)?(background-color\:#[0-9a-fA-F]+;)?$/.test(e.attrValue); return; } else if (e.attrName === 'class') { e.keepAttr = /^codicon codicon-[a-z\-]+( codicon-modifier-[a-z\-]+)?$/.test(e.attrValue); return; } } e.keepAttr = false; return; } }); // build an anchor to map URLs to const anchor = document.createElement('a'); // https://github.com/cure53/DOMPurify/blob/main/demos/hooks-scheme-allowlist.html dompurify.addHook('afterSanitizeAttributes', (node) => { // check all href/src attributes for validity for (const attr of ['href', 'src']) { if (node.hasAttribute(attr)) { anchor.href = node.getAttribute(attr); if (!allowedSchemes.includes(anchor.protocol.replace(/:$/, ''))) { node.removeAttribute(attr); } } } }); try { return dompurify.sanitize(renderedMarkdown, Object.assign(Object.assign({}, config), { RETURN_TRUSTED_TYPE: true })); } finally { dompurify.removeHook('uponSanitizeAttribute'); dompurify.removeHook('afterSanitizeAttributes'); } } function getSanitizerOptions(options) { const allowedSchemes = [ network_1.Schemas.http, network_1.Schemas.https, network_1.Schemas.mailto, network_1.Schemas.data, network_1.Schemas.file, network_1.Schemas.vscodeFileResource, network_1.Schemas.vscodeRemote, network_1.Schemas.vscodeRemoteResource, ]; if (options.isTrusted) { allowedSchemes.push(network_1.Schemas.command); } return { config: { // allowedTags should included everything that markdown renders to. // Since we have our own sanitize function for marked, it's possible we missed some tag so let dompurify make sure. // HTML tags that can result from markdown are from reading https://spec.commonmark.org/0.29/ // HTML table tags that can result from markdown are from https://github.github.com/gfm/#tables-extension- ALLOWED_TAGS: ['ul', 'li', 'p', 'b', 'i', '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'], ALLOWED_ATTR: ['href', 'data-href', 'target', 'title', 'src', 'alt', 'class', 'style', 'data-code', 'width', 'height', 'align'], ALLOW_UNKNOWN_PROTOCOLS: true, }, allowedSchemes }; } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[171/*vs/base/common/labels*/], __M([1/*require*/,0/*exports*/,166/*vs/base/common/extpath*/,48/*vs/base/common/network*/,17/*vs/base/common/platform*/,41/*vs/base/common/resources*/,25/*vs/base/common/uri*/]), function (require, exports, extpath_1, network_1, platform_1, resources_1, uri_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, continueAsWindows) { if ((0, extpath_1.hasDriveLetter)(path, continueAsWindows)) { return path.charAt(0).toUpperCase() + path.slice(1); } return path; } exports.normalizeDriveLetter = normalizeDriveLetter; let normalizedUserHomeCached = Object.create(null); }); define(__m[325/*vs/base/common/uuid*/], __M([1/*require*/,0/*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[219/*vs/base/common/worker/simpleWorker*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,20/*vs/base/common/types*/,8/*vs/base/common/strings*/]), function (require, exports, errors_1, event_1, lifecycle_1, platform_1, types, strings) { "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 RequestMessage { constructor(vsWorker, req, method, args) { this.vsWorker = vsWorker; this.req = req; this.method = method; this.args = args; this.type = 0 /* Request */; } } class ReplyMessage { constructor(vsWorker, seq, res, err) { this.vsWorker = vsWorker; this.seq = seq; this.res = res; this.err = err; this.type = 1 /* Reply */; } } class SubscribeEventMessage { constructor(vsWorker, req, eventName, arg) { this.vsWorker = vsWorker; this.req = req; this.eventName = eventName; this.arg = arg; this.type = 2 /* SubscribeEvent */; } } class EventMessage { constructor(vsWorker, req, event) { this.vsWorker = vsWorker; this.req = req; this.event = event; this.type = 3 /* Event */; } } class UnsubscribeEventMessage { constructor(vsWorker, req) { this.vsWorker = vsWorker; this.req = req; this.type = 4 /* UnsubscribeEvent */; } } class SimpleWorkerProtocol { constructor(handler) { this._workerId = -1; this._handler = handler; this._lastSentReq = 0; this._pendingReplies = Object.create(null); this._pendingEmitters = new Map(); this._pendingEvents = new Map(); } setWorkerId(workerId) { this._workerId = workerId; } sendMessage(method, args) { const req = String(++this._lastSentReq); return new Promise((resolve, reject) => { this._pendingReplies[req] = { resolve: resolve, reject: reject }; this._send(new RequestMessage(this._workerId, req, method, args)); }); } listen(eventName, arg) { let req = null; const emitter = new event_1.Emitter({ onFirstListenerAdd: () => { req = String(++this._lastSentReq); this._pendingEmitters.set(req, emitter); this._send(new SubscribeEventMessage(this._workerId, req, eventName, arg)); }, onLastListenerRemove: () => { this._pendingEmitters.delete(req); this._send(new UnsubscribeEventMessage(this._workerId, req)); req = null; } }); return emitter.event; } handleMessage(message) { if (!message || !message.vsWorker) { return; } if (this._workerId !== -1 && message.vsWorker !== this._workerId) { return; } this._handleMessage(message); } _handleMessage(msg) { switch (msg.type) { case 1 /* Reply */: return this._handleReplyMessage(msg); case 0 /* Request */: return this._handleRequestMessage(msg); case 2 /* SubscribeEvent */: return this._handleSubscribeEventMessage(msg); case 3 /* Event */: return this._handleEventMessage(msg); case 4 /* UnsubscribeEvent */: return this._handleUnsubscribeEventMessage(msg); } } _handleReplyMessage(replyMessage) { 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); } _handleRequestMessage(requestMessage) { let req = requestMessage.req; let result = this._handler.handleMessage(requestMessage.method, requestMessage.args); result.then((r) => { this._send(new ReplyMessage(this._workerId, req, r, undefined)); }, (e) => { if (e.detail instanceof Error) { // Loading errors have a detail property that points to the actual error e.detail = (0, errors_1.transformErrorForSerialization)(e.detail); } this._send(new ReplyMessage(this._workerId, req, undefined, (0, errors_1.transformErrorForSerialization)(e))); }); } _handleSubscribeEventMessage(msg) { const req = msg.req; const disposable = this._handler.handleEvent(msg.eventName, msg.arg)((event) => { this._send(new EventMessage(this._workerId, req, event)); }); this._pendingEvents.set(req, disposable); } _handleEventMessage(msg) { if (!this._pendingEmitters.has(msg.req)) { console.warn('Got event for unknown req'); return; } this._pendingEmitters.get(msg.req).fire(msg.event); } _handleUnsubscribeEventMessage(msg) { if (!this._pendingEvents.has(msg.req)) { console.warn('Got unsubscribe for unknown req'); return; } this._pendingEvents.get(msg.req).dispose(); this._pendingEvents.delete(msg.req); } _send(msg) { let transfer = []; if (msg.type === 0 /* Request */) { for (let i = 0; i < msg.args.length; i++) { if (msg.args[i] instanceof ArrayBuffer) { transfer.push(msg.args[i]); } } } else if (msg.type === 1 /* Reply */) { if (msg.res instanceof ArrayBuffer) { transfer.push(msg.res); } } this._handler.sendMessage(msg, transfer); } } /** * Main thread side */ class SimpleWorkerClient extends lifecycle_1.Disposable { constructor(workerFactory, 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); } }, handleEvent: (eventName, arg) => { if (propertyIsDynamicEvent(eventName)) { const event = host[eventName].call(host, arg); if (typeof event !== 'function') { throw new Error(`Missing dynamic event ${eventName} on main thread host.`); } return event; } if (propertyIsEvent(eventName)) { const event = host[eventName]; if (typeof event !== 'function') { throw new Error(`Missing event ${eventName} on main thread host.`); } return event; } throw new Error(`Malformed event name ${eventName}`); } }); this._protocol.setWorkerId(this._worker.getId()); // Gather loader configuration let loaderConfiguration = null; if (typeof platform_1.globals.require !== 'undefined' && typeof platform_1.globals.require.getConfig === 'function') { // Get the configuration from the Monaco AMD Loader loaderConfiguration = platform_1.globals.require.getConfig(); } else if (typeof platform_1.globals.requirejs !== 'undefined') { // Get the configuration from requirejs loaderConfiguration = platform_1.globals.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); }; const proxyListen = (eventName, arg) => { return this._protocol.listen(eventName, arg); }; this._lazyProxy = new Promise((resolve, reject) => { lazyProxyReject = reject; this._onModuleLoaded.then((availableMethods) => { resolve(createProxyObject(availableMethods, proxyMethodRequest, proxyListen)); }, (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; function propertyIsEvent(name) { // Assume a property is an event if it has a form of "onSomething" return name[0] === 'o' && name[1] === 'n' && strings.isUpperAsciiLetter(name.charCodeAt(2)); } function propertyIsDynamicEvent(name) { // Assume a property is a dynamic event (a method that returns an event) if it has a form of "onDynamicSomething" return /^onDynamic/.test(name) && strings.isUpperAsciiLetter(name.charCodeAt(9)); } function createProxyObject(methodNames, invoke, proxyListen) { const createProxyMethod = (method) => { return function () { const args = Array.prototype.slice.call(arguments, 0); return invoke(method, args); }; }; const createProxyDynamicEvent = (eventName) => { return function (arg) { return proxyListen(eventName, arg); }; }; let result = {}; for (const methodName of methodNames) { if (propertyIsDynamicEvent(methodName)) { result[methodName] = createProxyDynamicEvent(methodName); continue; } if (propertyIsEvent(methodName)) { result[methodName] = proxyListen(methodName, undefined); continue; } result[methodName] = createProxyMethod(methodName); } return result; } /** * 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), handleEvent: (eventName, arg) => this._handleEvent(eventName, arg) }); } 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); } } _handleEvent(eventName, arg) { if (!this._requestHandler) { throw new Error(`Missing requestHandler`); } if (propertyIsDynamicEvent(eventName)) { const event = this._requestHandler[eventName].call(this._requestHandler, arg); if (typeof event !== 'function') { throw new Error(`Missing dynamic event ${eventName} on request handler.`); } return event; } if (propertyIsEvent(eventName)) { const event = this._requestHandler[eventName]; if (typeof event !== 'function') { throw new Error(`Missing event ${eventName} on request handler.`); } return event; } throw new Error(`Malformed event name ${eventName}`); } initialize(workerId, loaderConfig, moduleId, hostMethods) { this._protocol.setWorkerId(workerId); const proxyMethodRequest = (method, args) => { return this._protocol.sendMessage(method, args); }; const proxyListen = (eventName, arg) => { return this._protocol.listen(eventName, arg); }; const hostProxy = createProxyObject(hostMethods, proxyMethodRequest, proxyListen); 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; platform_1.globals.require.config(loaderConfig); } return new Promise((resolve, reject) => { // Use the global require to be sure to get the global config // ESM-comment-begin const req = (platform_1.globals.require || require); // ESM-comment-end // ESM-uncomment-begin // const req = globals.require; // ESM-uncomment-end req([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[326/*vs/base/browser/defaultWorkerFactory*/], __M([1/*require*/,0/*exports*/,17/*vs/base/common/platform*/,219/*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(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('workerMain.js', label); } if (typeof platform_1.globals.MonacoEnvironment.getWorkerUrl === 'function') { const workerUrl = platform_1.globals.MonacoEnvironment.getWorkerUrl('workerMain.js', label); return new Worker(ttPolicy ? ttPolicy.createScriptURL(workerUrl) : workerUrl, { name: label }); } } // ESM-comment-begin if (typeof require === 'function') { // check if the JS lives on a different origin const workerMain = require.toUrl('vs/base/worker/workerMain.js'); // 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(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; }); /*--------------------------------------------------------------------------------------------- * 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/base/parts/quickinput/common/quickInput*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.quickPickItemScorerAccessor = exports.QuickPickItemScorerAccessor = 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 = {})); class QuickPickItemScorerAccessor { constructor(options) { this.options = options; } } exports.QuickPickItemScorerAccessor = QuickPickItemScorerAccessor; exports.quickPickItemScorerAccessor = new QuickPickItemScorerAccessor(); }); //#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[327/*vs/base/parts/storage/common/storage*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/async*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/]), function (require, exports, async_1, event_1, lifecycle_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.doFlush(); }); } 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.doFlush(); }); } 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(); } } }); }); } doFlush(delay) { return __awaiter(this, void 0, void 0, function* () { return this.flushDelayer.trigger(() => this.flushPending(), delay); }); } 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; }); define(__m[221/*vs/css!vs/base/browser/ui/actionbar/actionbar*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[328/*vs/css!vs/base/browser/ui/aria/aria*/], __M([12/*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[43/*vs/base/browser/ui/aria/aria*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,17/*vs/base/common/platform*/,328/*vs/css!vs/base/browser/ui/aria/aria*/]), function (require, exports, dom, platform_1) { "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[329/*vs/css!vs/base/browser/ui/button/button*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[330/*vs/base/browser/ui/button/button*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,46/*vs/base/browser/keyboardEvent*/,57/*vs/base/browser/touch*/,113/*vs/base/browser/ui/iconLabel/iconLabels*/,29/*vs/base/common/color*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,39/*vs/base/common/objects*/,329/*vs/css!vs/base/browser/ui/button/button*/]), function (require, exports, dom_1, keyboardEvent_1, touch_1, iconLabels_1, color_1, event_1, lifecycle_1, objects_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[331/*vs/css!vs/base/browser/ui/checkbox/checkbox*/], __M([12/*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[172/*vs/base/browser/ui/checkbox/checkbox*/], __M([1/*require*/,0/*exports*/,60/*vs/base/browser/ui/widget*/,27/*vs/base/common/codicons*/,29/*vs/base/common/color*/,4/*vs/base/common/event*/,331/*vs/css!vs/base/browser/ui/checkbox/checkbox*/]), function (require, exports, widget_1, codicons_1, color_1, event_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) => { if (this.enabled) { 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 /*margin left*/ + 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() : ''; 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() : ''; } } enable() { this.domNode.setAttribute('aria-disabled', String(false)); } disable() { this.domNode.setAttribute('aria-disabled', String(true)); } } exports.Checkbox = Checkbox; }); define(__m[332/*vs/css!vs/base/browser/ui/codicons/codicon/codicon*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[333/*vs/css!vs/base/browser/ui/codicons/codicon/codicon-modifiers*/], __M([12/*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[140/*vs/base/browser/ui/codicons/codiconStyles*/], __M([1/*require*/,0/*exports*/,27/*vs/base/common/codicons*/,332/*vs/css!vs/base/browser/ui/codicons/codicon/codicon*/,333/*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[334/*vs/css!vs/base/browser/ui/contextview/contextview*/], __M([12/*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[222/*vs/base/browser/ui/contextview/contextview*/], __M([1/*require*/,0/*exports*/,165/*vs/base/browser/canIUse*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,136/*vs/base/common/range*/,334/*vs/css!vs/base/browser/ui/contextview/contextview*/]), function (require, exports, canIUse_1, DOM, lifecycle_1, platform, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ContextView = exports.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"; font-display: block; 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[335/*vs/css!vs/base/browser/ui/countBadge/countBadge*/], __M([12/*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[223/*vs/base/browser/ui/countBadge/countBadge*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,29/*vs/base/common/color*/,39/*vs/base/common/objects*/,8/*vs/base/common/strings*/,335/*vs/css!vs/base/browser/ui/countBadge/countBadge*/]), function (require, exports, dom_1, color_1, objects_1, strings_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[224/*vs/css!vs/base/browser/ui/dropdown/dropdown*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[225/*vs/css!vs/base/browser/ui/findinput/findInput*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[336/*vs/css!vs/base/browser/ui/hover/hover*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[337/*vs/css!vs/base/browser/ui/iconLabel/iconlabel*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[338/*vs/css!vs/base/browser/ui/inputbox/inputBox*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[339/*vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[226/*vs/css!vs/base/browser/ui/list/list*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[340/*vs/css!vs/base/browser/ui/mouseCursor/mouseCursor*/], __M([12/*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[141/*vs/base/browser/ui/mouseCursor/mouseCursor*/], __M([1/*require*/,0/*exports*/,340/*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[341/*vs/css!vs/base/browser/ui/progressbar/progressbar*/], __M([12/*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[342/*vs/base/browser/ui/progressbar/progressbar*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,10/*vs/base/common/async*/,29/*vs/base/common/color*/,2/*vs/base/common/lifecycle*/,39/*vs/base/common/objects*/,341/*vs/css!vs/base/browser/ui/progressbar/progressbar*/]), function (require, exports, dom_1, async_1, color_1, lifecycle_1, objects_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ProgressBar = void 0; const CSS_DONE = 'done'; const CSS_ACTIVE = 'active'; const CSS_INFINITE = 'infinite'; const CSS_INFINITE_LONG_RUNNING = 'infinite-long-running'; const CSS_DISCRETE = 'discrete'; 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.showDelayedScheduler = this._register(new async_1.RunOnceScheduler(() => (0, dom_1.show)(this.element), 0)); this.longRunningScheduler = this._register(new async_1.RunOnceScheduler(() => this.infiniteLongRunning(), ProgressBar.LONG_RUNNING_INFINITE_THRESHOLD)); this.create(container); } 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_INFINITE_LONG_RUNNING, CSS_DISCRETE); this.workedVal = 0; this.totalWork = undefined; this.longRunningScheduler.cancel(); } /** * Stops the progressbar from showing any progress instantly without fading out. */ stop() { return this.doDone(false); } doDone(delayed) { this.element.classList.add(CSS_DONE); // discrete: let it grow to 100% width and hide afterwards if (!this.element.classList.contains(CSS_INFINITE)) { this.bit.style.width = 'inherit'; if (delayed) { setTimeout(() => this.off(), 200); } else { this.off(); } } // infinite: let it fade out and hide afterwards else { this.bit.style.opacity = '0'; if (delayed) { setTimeout(() => this.off(), 200); } else { this.off(); } } return this; } /** * Use this mode to indicate progress that has no total number of work units. */ infinite() { this.bit.style.width = '2%'; this.bit.style.opacity = '1'; this.element.classList.remove(CSS_DISCRETE, CSS_DONE, CSS_INFINITE_LONG_RUNNING); this.element.classList.add(CSS_ACTIVE, CSS_INFINITE); this.longRunningScheduler.schedule(); return this; } infiniteLongRunning() { this.element.classList.add(CSS_INFINITE_LONG_RUNNING); } getContainer() { return this.element; } 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; /** * After a certain time of showing the progress bar, switch * to long-running mode and throttle animations to reduce * the pressure on the GPU process. * * https://github.com/microsoft/vscode/issues/97900 * https://github.com/microsoft/vscode/issues/138396 */ ProgressBar.LONG_RUNNING_INFINITE_THRESHOLD = 10000; }); define(__m[343/*vs/css!vs/base/browser/ui/sash/sash*/], __M([12/*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[114/*vs/base/browser/ui/sash/sash*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,89/*vs/base/browser/event*/,57/*vs/base/browser/touch*/,10/*vs/base/common/async*/,93/*vs/base/common/decorators*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,343/*vs/css!vs/base/browser/ui/sash/sash*/]), function (require, exports, dom_1, event_1, touch_1, async_1, decorators_1, event_2, lifecycle_1, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Sash = exports.OrthogonalEdge = void 0; /** * Allow the sashes to be visible at runtime. * @remark Use for development purposes only. */ 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_2.Emitter(); let globalHoverDelay = 300; const onDidChangeHoverDelay = new event_2.Emitter(); class MouseEventFactory { constructor() { this.disposables = new lifecycle_1.DisposableStore(); } get onPointerMove() { return this.disposables.add(new event_1.DomEmitter(window, 'mousemove')).event; } get onPointerUp() { return this.disposables.add(new event_1.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_1.DomEmitter(this.el, touch_1.EventType.Change)).event; } get onPointerUp() { return this.disposables.add(new event_1.DomEmitter(this.el, touch_1.EventType.End)).event; } 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); const PointerEventsDisabledCssClass = 'pointer-events-disabled'; /** * The {@link Sash} is the UI component which allows the user to resize other * components. It's usually an invisible horizontal or vertical line which, when * hovered, becomes highlighted and can be dragged along the perpendicular dimension * to its direction. * * Features: * - Touch event handling * - Corner sash support * - Hover with different mouse cursor support * - Configurable hover size * - Linked sash support, for 2x2 corner sashes */ class Sash extends lifecycle_1.Disposable { 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_2.Emitter()); this._onDidStart = this._register(new event_2.Emitter()); this._onDidChange = this._register(new event_2.Emitter()); this._onDidReset = this._register(new event_2.Emitter()); this._onDidEnd = this._register(new event_2.Emitter()); this.orthogonalStartSashDisposables = this._register(new lifecycle_1.DisposableStore()); this.orthogonalStartDragHandleDisposables = this._register(new lifecycle_1.DisposableStore()); this.orthogonalEndSashDisposables = this._register(new lifecycle_1.DisposableStore()); this.orthogonalEndDragHandleDisposables = this._register(new lifecycle_1.DisposableStore()); /** * An event which fires whenever the user starts dragging this sash. */ this.onDidStart = this._onDidStart.event; /** * An event which fires whenever the user moves the mouse while * dragging this sash. */ this.onDidChange = this._onDidChange.event; /** * An event which fires whenever the user double clicks this sash. */ this.onDidReset = this._onDidReset.event; /** * An event which fires whenever the user stops dragging this sash. */ this.onDidEnd = this._onDidEnd.event; /** * A linked sash will be forwarded the same user interactions and events * so it moves exactly the same way as this sash. * * Useful in 2x2 grids. Not meant for widespread usage. */ this.linkedSash = undefined; this.el = (0, dom_1.append)(container, (0, dom_1.$)('.monaco-sash')); if (options.orthogonalEdge) { this.el.classList.add(`orthogonal-edge-${options.orthogonalEdge}`); } if (platform_1.isMacintosh) { this.el.classList.add('mac'); } const onMouseDown = this._register(new event_1.DomEmitter(this.el, 'mousedown')).event; this._register(onMouseDown(e => this.onPointerStart(e, new MouseEventFactory()), this)); const onMouseDoubleClick = this._register(new event_1.DomEmitter(this.el, 'dblclick')).event; this._register(onMouseDoubleClick(this.onPointerDoublePress, this)); const onMouseEnter = this._register(new event_1.DomEmitter(this.el, 'mouseenter')).event; this._register(onMouseEnter(() => Sash.onMouseEnter(this))); const onMouseLeave = this._register(new event_1.DomEmitter(this.el, 'mouseleave')).event; this._register(onMouseLeave(() => Sash.onMouseLeave(this))); this._register(touch_1.Gesture.addTarget(this.el)); const onTouchStart = event_2.Event.map(this._register(new event_1.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_1.DomEmitter(this.el, touch_1.EventType.Tap)).event; const onDoubleTap = event_2.Event.map(event_2.Event.filter(event_2.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.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; } get orthogonalStartSash() { return this._orthogonalStartSash; } get orthogonalEndSash() { return this._orthogonalEndSash; } /** * The state of a sash defines whether it can be interacted with by the user * as well as what mouse cursor to use, when hovered. */ set state(state) { if (this._state === state) { return; } this.el.classList.toggle('disabled', state === 0 /* Disabled */); this.el.classList.toggle('minimum', state === 1 /* AtMinimum */); this.el.classList.toggle('maximum', state === 2 /* AtMaximum */); this._state = state; this.onDidEnablementChange.fire(state); } /** * A reference to another sash, perpendicular to this one, which * aligns at the start of this one. A corner sash will be created * automatically at that location. * * The start of a horizontal sash is its left-most position. * The start of a vertical sash is its top-most position. */ set orthogonalStartSash(sash) { 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_1.DomEmitter(this._orthogonalStartDragHandle, 'mouseenter')).event(() => Sash.onMouseEnter(sash), undefined, this.orthogonalStartDragHandleDisposables); this.orthogonalStartDragHandleDisposables.add(new event_1.DomEmitter(this._orthogonalStartDragHandle, 'mouseleave')).event(() => Sash.onMouseLeave(sash), undefined, this.orthogonalStartDragHandleDisposables); } }; this.orthogonalStartSashDisposables.add(sash.onDidEnablementChange.event(onChange, this)); onChange(sash.state); } this._orthogonalStartSash = sash; } /** * A reference to another sash, perpendicular to this one, which * aligns at the end of this one. A corner sash will be created * automatically at that location. * * The end of a horizontal sash is its right-most position. * The end of a vertical sash is its bottom-most position. */ set orthogonalEndSash(sash) { 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_1.DomEmitter(this._orthogonalEndDragHandle, 'mouseenter')).event(() => Sash.onMouseEnter(sash), undefined, this.orthogonalEndDragHandleDisposables); this.orthogonalEndDragHandleDisposables.add(new event_1.DomEmitter(this._orthogonalEndDragHandle, 'mouseleave')).event(() => Sash.onMouseLeave(sash), undefined, this.orthogonalEndDragHandleDisposables); } }; this.orthogonalEndSashDisposables.add(sash.onDidEnablementChange.event(onChange, this)); onChange(sash.state); } this._orthogonalEndSash = sash; } 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.classList.add(PointerEventsDisabledCssClass); // disable mouse events on iframes as long as we drag the sash } const startX = event.pageX; const startY = event.pageY; const altKey = event.altKey; const startEvent = { startX, currentX: startX, startY, currentY: startY, altKey }; this.el.classList.add('active'); this._onDidStart.fire(startEvent); // fix https://github.com/microsoft/vscode/issues/21675 const style = (0, dom_1.createStyleSheet)(this.el); const updateStyle = () => { let cursor = ''; if (isMultisashResize) { cursor = 'all-scroll'; } else if (this.orientation === 1 /* HORIZONTAL */) { if (this.state === 1 /* AtMinimum */) { cursor = 's-resize'; } else if (this.state === 2 /* AtMaximum */) { cursor = 'n-resize'; } else { cursor = platform_1.isMacintosh ? 'row-resize' : 'ns-resize'; } } else { if (this.state === 1 /* AtMinimum */) { cursor = 'e-resize'; } else if (this.state === 2 /* AtMaximum */) { cursor = 'w-resize'; } else { cursor = platform_1.isMacintosh ? 'col-resize' : 'ew-resize'; } } style.textContent = `* { cursor: ${cursor} !important; }`; }; const disposables = new lifecycle_1.DisposableStore(); updateStyle(); if (!isMultisashResize) { this.onDidEnablementChange.event(updateStyle, null, disposables); } const onPointerMove = (e) => { dom_1.EventHelper.stop(e, false); const event = { startX, currentX: e.pageX, startY, currentY: e.pageY, altKey }; this._onDidChange.fire(event); }; const onPointerUp = (e) => { dom_1.EventHelper.stop(e, false); this.el.removeChild(style); this.el.classList.remove('active'); this._onDidEnd.fire(); disposables.dispose(); for (const iframe of iframes) { iframe.classList.remove(PointerEventsDisabledCssClass); } }; pointerEventFactory.onPointerMove(onPointerMove, null, disposables); pointerEventFactory.onPointerUp(onPointerUp, null, disposables); disposables.add(pointerEventFactory); } onPointerDoublePress(e) { const orthogonalSash = this.getOrthogonalSash(e); if (orthogonalSash) { orthogonalSash._onDidReset.fire(); } if (this.linkedSash) { this.linkedSash._onDidReset.fire(); } this._onDidReset.fire(); } static onMouseEnter(sash, fromLinkedSash = false) { if (sash.el.classList.contains('active')) { sash.hoverDelayer.cancel(); sash.el.classList.add('hover'); } else { sash.hoverDelayer.trigger(() => sash.el.classList.add('hover'), sash.hoverDelay).then(undefined, () => { }); } if (!fromLinkedSash && sash.linkedSash) { Sash.onMouseEnter(sash.linkedSash, true); } } static onMouseLeave(sash, fromLinkedSash = false) { sash.hoverDelayer.cancel(); sash.el.classList.remove('hover'); if (!fromLinkedSash && sash.linkedSash) { Sash.onMouseLeave(sash.linkedSash, true); } } /** * Forcefully stop any user interactions with this sash. * Useful when hiding a parent component, while the user is still * interacting with the sash. */ clearSashHoverState() { Sash.onMouseLeave(this); } /** * Layout the sash. The sash will size and position itself * based on its provided {@link ISashLayoutProvider layout provider}. */ layout() { if (this.orientation === 0 /* VERTICAL */) { const verticalProvider = this.layoutProvider; this.el.style.left = verticalProvider.getVerticalSashLeft(this) - (this.size / 2) + 'px'; if (verticalProvider.getVerticalSashTop) { this.el.style.top = verticalProvider.getVerticalSashTop(this) + 'px'; } if (verticalProvider.getVerticalSashHeight) { this.el.style.height = verticalProvider.getVerticalSashHeight(this) + 'px'; } } else { const horizontalProvider = this.layoutProvider; this.el.style.top = horizontalProvider.getHorizontalSashTop(this) - (this.size / 2) + 'px'; if (horizontalProvider.getHorizontalSashLeft) { this.el.style.left = horizontalProvider.getHorizontalSashLeft(this) + 'px'; } if (horizontalProvider.getHorizontalSashWidth) { this.el.style.width = horizontalProvider.getHorizontalSashWidth(this) + 'px'; } } } getOrthogonalSash(e) { 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[344/*vs/css!vs/base/browser/ui/scrollbar/media/scrollbars*/], __M([12/*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[67/*vs/base/browser/ui/scrollbar/scrollableElement*/], __M([1/*require*/,0/*exports*/,34/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,56/*vs/base/browser/mouseEvent*/,322/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/,323/*vs/base/browser/ui/scrollbar/verticalScrollbar*/,60/*vs/base/browser/ui/widget*/,10/*vs/base/common/async*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,137/*vs/base/common/scrollable*/,344/*vs/css!vs/base/browser/ui/scrollbar/media/scrollbars*/]), function (require, exports, browser_1, dom, fastDomNode_1, mouseEvent_1, horizontalScrollbar_1, verticalScrollbar_1, widget_1, async_1, event_1, lifecycle_1, platform, scrollable_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DomScrollableElement = exports.SmoothScrollableElement = exports.ScrollableElement = exports.AbstractScrollableElement = exports.MouseWheelClassifier = void 0; const HIDE_TIMEOUT = 500; const SCROLL_WHEEL_SENSITIVITY = 50; const SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED = true; class MouseWheelClassifierItem { constructor(timestamp, deltaX, deltaY) { this.timestamp = timestamp; this.deltaX = deltaX; this.deltaY = deltaY; this.score = 0; } } class MouseWheelClassifier { 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; } get options() { return this._options; } 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 deltaScrollTop = SCROLL_WHEEL_SENSITIVITY * deltaY; // Here we convert values such as -0.3 to -1 or 0.3 to 1, otherwise low speed scrolling will never scroll const desiredScrollTop = futureScrollPosition.scrollTop - (deltaScrollTop < 0 ? Math.floor(deltaScrollTop) : Math.ceil(deltaScrollTop)); this._verticalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollTop); } if (deltaX) { const deltaScrollLeft = SCROLL_WHEEL_SENSITIVITY * deltaX; // Here we convert values such as -0.3 to -1 or 0.3 to 1, otherwise low speed scrolling will never scroll const desiredScrollLeft = futureScrollPosition.scrollLeft - (deltaScrollLeft < 0 ? Math.floor(deltaScrollLeft) : Math.ceil(deltaScrollLeft)); this._horizontalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollLeft); } // Check that we are scrolling towards a location which is valid desiredScrollPosition = this._scrollable.validateScrollPosition(desiredScrollPosition); if (futureScrollPosition.scrollLeft !== desiredScrollPosition.scrollLeft || futureScrollPosition.scrollTop !== desiredScrollPosition.scrollTop) { const canPerformSmoothScroll = (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED && this._options.mouseWheelSmoothScroll && classifier.isPhysicalMouseWheel()); if (canPerformSmoothScroll) { this._scrollable.setScrollPositionSmooth(desiredScrollPosition); } else { this._scrollable.setScrollPositionNow(desiredScrollPosition); } didScroll = true; } } let consumeMouseWheel = didScroll; if (!consumeMouseWheel && this._options.alwaysConsumeMouseWheel) { consumeMouseWheel = true; } if (!consumeMouseWheel && this._options.consumeMouseWheelIfScrollbarIsNeeded && (this._verticalScrollbar.isNeeded() || this._horizontalScrollbar.isNeeded())) { consumeMouseWheel = true; } if (consumeMouseWheel) { e.preventDefault(); e.stopPropagation(); } } _onDidScroll(e) { this._shouldRender = this._horizontalScrollbar.onDidScroll(e) || this._shouldRender; this._shouldRender = this._verticalScrollbar.onDidScroll(e) || this._shouldRender; if (this._options.useShadows) { this._shouldRender = true; } if (this._revealOnScroll) { this._reveal(); } if (!this._options.lazyRender) { this._render(); } } /** * Render / mutate the DOM now. * Should be used together with the ctor option `lazyRender`. */ renderNow() { if (!this._options.lazyRender) { throw new Error('Please use `lazyRender` together with `renderNow`!'); } this._render(); } _render() { if (!this._shouldRender) { return; } this._shouldRender = false; this._horizontalScrollbar.render(); this._verticalScrollbar.render(); if (this._options.useShadows) { const scrollState = this._scrollable.getCurrentScrollPosition(); const enableTop = scrollState.scrollTop > 0; const enableLeft = scrollState.scrollLeft > 0; const leftClassName = (enableLeft ? ' left' : ''); const topClassName = (enableTop ? ' top' : ''); const topLeftClassName = (enableLeft || enableTop ? ' top-left-corner' : ''); this._leftShadowDomNode.setClassName(`shadow${leftClassName}`); this._topShadowDomNode.setClassName(`shadow${topClassName}`); this._topLeftShadowDomNode.setClassName(`shadow${topLeftClassName}${topClassName}${leftClassName}`); } } // -------------------- fade in / fade out -------------------- _onDragStart() { this._isDragging = true; this._reveal(); } _onDragEnd() { this._isDragging = false; this._hide(); } _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({ forceIntegerValues: true, smoothScrollDuration: 0, scheduleAtNextAnimationFrame: (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 AbstractScrollableElement { constructor(element, options) { options = options || {}; options.mouseWheelSmoothScroll = false; const scrollable = new scrollable_1.Scrollable({ forceIntegerValues: false, smoothScrollDuration: 0, scheduleAtNextAnimationFrame: (callback) => dom.scheduleAtNextAnimationFrame(callback) }); super(element, options, scrollable); this._register(scrollable); this._element = element; this.onScroll((e) => { if (e.scrollTopChanged) { this._element.scrollTop = e.scrollTop; } if (e.scrollLeftChanged) { this._element.scrollLeft = e.scrollLeft; } }); this.scanDomNode(); } setScrollPosition(update) { this._scrollable.setScrollPositionNow(update); } getScrollPosition() { return this._scrollable.getCurrentScrollPosition(); } scanDomNode() { // width, scrollLeft, scrollWidth, height, scrollTop, scrollHeight this.setScrollDimensions({ width: this._element.clientWidth, scrollWidth: this._element.scrollWidth, height: this._element.clientHeight, scrollHeight: this._element.scrollHeight }); this.setScrollPosition({ scrollLeft: this._element.scrollLeft, scrollTop: this._element.scrollTop, }); } } exports.DomScrollableElement = DomScrollableElement; function resolveOptions(opts) { const result = { lazyRender: (typeof opts.lazyRender !== 'undefined' ? opts.lazyRender : false), className: (typeof opts.className !== 'undefined' ? opts.className : ''), useShadows: (typeof opts.useShadows !== 'undefined' ? opts.useShadows : true), handleMouseWheel: (typeof opts.handleMouseWheel !== 'undefined' ? opts.handleMouseWheel : true), flipAxes: (typeof opts.flipAxes !== 'undefined' ? opts.flipAxes : false), consumeMouseWheelIfScrollbarIsNeeded: (typeof opts.consumeMouseWheelIfScrollbarIsNeeded !== 'undefined' ? opts.consumeMouseWheelIfScrollbarIsNeeded : false), alwaysConsumeMouseWheel: (typeof opts.alwaysConsumeMouseWheel !== 'undefined' ? opts.alwaysConsumeMouseWheel : false), scrollYToX: (typeof opts.scrollYToX !== 'undefined' ? opts.scrollYToX : false), mouseWheelScrollSensitivity: (typeof opts.mouseWheelScrollSensitivity !== 'undefined' ? opts.mouseWheelScrollSensitivity : 1), fastScrollSensitivity: (typeof opts.fastScrollSensitivity !== 'undefined' ? opts.fastScrollSensitivity : 5), scrollPredominantAxis: (typeof opts.scrollPredominantAxis !== 'undefined' ? opts.scrollPredominantAxis : true), mouseWheelSmoothScroll: (typeof opts.mouseWheelSmoothScroll !== 'undefined' ? opts.mouseWheelSmoothScroll : true), arrowSize: (typeof opts.arrowSize !== 'undefined' ? opts.arrowSize : 11), listenOnDomNode: (typeof opts.listenOnDomNode !== 'undefined' ? opts.listenOnDomNode : null), horizontal: (typeof opts.horizontal !== 'undefined' ? opts.horizontal : 1 /* 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[227/*vs/base/browser/ui/hover/hoverWidget*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,67/*vs/base/browser/ui/scrollbar/scrollableElement*/,2/*vs/base/common/lifecycle*/,336/*vs/css!vs/base/browser/ui/hover/hover*/]), function (require, exports, dom, scrollableElement_1, lifecycle_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('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.MOUSE_DOWN, 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[173/*vs/base/browser/ui/list/listView*/], __M([1/*require*/,0/*exports*/,34/*vs/base/browser/browser*/,164/*vs/base/browser/dnd*/,7/*vs/base/browser/dom*/,89/*vs/base/browser/event*/,57/*vs/base/browser/touch*/,67/*vs/base/browser/ui/scrollbar/scrollableElement*/,19/*vs/base/common/arrays*/,10/*vs/base/common/async*/,93/*vs/base/common/decorators*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,39/*vs/base/common/objects*/,136/*vs/base/common/range*/,137/*vs/base/common/scrollable*/,315/*vs/base/browser/ui/list/rangeMap*/,321/*vs/base/browser/ui/list/rowCache*/]), function (require, exports, browser_1, dnd_1, dom_1, event_1, touch_1, scrollableElement_1, arrays_1, async_1, decorators_1, event_2, lifecycle_1, objects_1, range_1, scrollable_1, rangeMap_1, rowCache_1) { "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; } } } /** * The {@link ListView} is a virtual scrolling engine. * * Given that it only renders elements within its viewport, it can hold large * collections of elements and stay very performant. The performance bottleneck * usually lies within the user's rendering code for each element. * * @remarks It is a low-level widget, not meant to be used directly. Refer to the * List widget instead. */ class ListView { constructor(container, virtualDelegate, renderers, options = DefaultOptions) { this.virtualDelegate = virtualDelegate; this.domId = `list_id_${++ListView.InstanceCount}`; this.renderers = new Map(); this.renderWidth = 0; this._scrollHeight = 0; this.scrollableElementUpdateDisposable = null; this.scrollableElementWidthDelayer = new async_1.Delayer(50); this.splicing = false; this.dragOverAnimationStopDisposable = lifecycle_1.Disposable.None; this.dragOverMouseY = 0; this.canDrop = false; this.currentDragFeedbackDisposable = lifecycle_1.Disposable.None; this.onDragLeaveTimeout = lifecycle_1.Disposable.None; this.disposables = new lifecycle_1.DisposableStore(); this._onDidChangeContentHeight = new event_2.Emitter(); this._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({ forceIntegerValues: true, smoothScrollDuration: (0, objects_1.getOrDefault)(options, o => o.smoothScrolling, false) ? 125 : 0, scheduleAtNextAnimationFrame: 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.end - 1; i >= removeRange.start; 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('data-parity', index % 2 === 0 ? 'even' : 'odd'); item.row.domNode.setAttribute('aria-setsize', String(this.accessibilityProvider.getSetSize(item.element, index, this.length))); item.row.domNode.setAttribute('aria-posinset', String(this.accessibilityProvider.getPosInSet(item.element, index))); item.row.domNode.setAttribute('id', this.getElementDomId(index)); item.row.domNode.classList.toggle('drop-target', item.dropTarget); } removeItemFromDOM(index) { const item = this.items[index]; item.dragStartDisposable.dispose(); 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_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, 'click')).event, e => this.toMouseEvent(e)); } get onMouseDblClick() { return event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, 'dblclick')).event, e => this.toMouseEvent(e)); } get onMouseMiddleClick() { return event_2.Event.filter(event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, 'auxclick')).event, e => this.toMouseEvent(e)), e => e.browserEvent.button === 1); } get onMouseDown() { return event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, 'mousedown')).event, e => this.toMouseEvent(e)); } get onContextMenu() { return event_2.Event.any(event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, 'contextmenu')).event, e => this.toMouseEvent(e)), event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, touch_1.EventType.Contextmenu)).event, e => this.toGestureEvent(e))); } get onTouchStart() { return event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, 'touchstart')).event, e => this.toTouchEvent(e)); } get onTap() { return event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.rowsContainer, touch_1.EventType.Tap)).event, e => this.toGestureEvent(e)); } 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 (!!this.virtualDelegate.getDynamicHeight) { const newSize = this.virtualDelegate.getDynamicHeight(item.element); if (newSize !== null) { const size = item.size; item.size = newSize; item.lastDynamicHeightWidth = this.renderWidth; return newSize - size; } } if (!item.hasDynamicHeight || item.lastDynamicHeightWidth === this.renderWidth) { return 0; } if (!!this.virtualDelegate.hasDynamicHeight && !this.virtualDelegate.hasDynamicHeight(item.element)) { return 0; } const size = item.size; if (!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[115/*vs/base/browser/ui/list/listWidget*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,89/*vs/base/browser/event*/,46/*vs/base/browser/keyboardEvent*/,57/*vs/base/browser/touch*/,43/*vs/base/browser/ui/aria/aria*/,308/*vs/base/browser/ui/list/splice*/,19/*vs/base/common/arrays*/,10/*vs/base/common/async*/,29/*vs/base/common/color*/,93/*vs/base/common/decorators*/,4/*vs/base/common/event*/,73/*vs/base/common/filters*/,2/*vs/base/common/lifecycle*/,111/*vs/base/common/numbers*/,39/*vs/base/common/objects*/,17/*vs/base/common/platform*/,20/*vs/base/common/types*/,307/*vs/base/browser/ui/list/list*/,173/*vs/base/browser/ui/list/listView*/,226/*vs/css!vs/base/browser/ui/list/list*/]), function (require, exports, dom_1, event_1, keyboardEvent_1, touch_1, aria_1, splice_1, arrays_1, async_1, color_1, decorators_1, event_2, filters_1, lifecycle_1, numbers_1, objects_1, platform, types_1, list_1, listView_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_2.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 /* KeyA */).on(this.onCtrlA, this, this.multipleSelectionDisposables); } } get onKeyDown() { return event_2.Event.chain(this.disposables.add(new event_1.DomEmitter(this.view.domNode, 'keydown')).event) .filter(e => !isInputElement(e.target)) .map(e => new keyboardEvent_1.StandardKeyboardEvent(e)); } 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 /* KeyA */).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); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } onDownArrow(e) { e.preventDefault(); e.stopPropagation(); this.list.focusNext(1, false, e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } onPageUpArrow(e) { e.preventDefault(); e.stopPropagation(); this.list.focusPreviousPage(e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } onPageDownArrow(e) { e.preventDefault(); e.stopPropagation(); this.list.focusNextPage(e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } onCtrlA(e) { e.preventDefault(); e.stopPropagation(); this.list.setSelection((0, arrays_1.range)(this.list.length), e.browserEvent); this.list.setAnchor(undefined); this.view.domNode.focus(); } onEscape(e) { if (this.list.getSelection().length) { e.preventDefault(); e.stopPropagation(); this.list.setSelection([], e.browserEvent); this.list.setAnchor(undefined); this.view.domNode.focus(); } } dispose() { this.disposables.dispose(); this.multipleSelectionDisposables.dispose(); } } __decorate([ decorators_1.memoize ], KeyboardController.prototype, "onKeyDown", null); var 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 /* KeyA */ && event.keyCode <= 56 /* KeyZ */) || (event.keyCode >= 21 /* Digit0 */ && event.keyCode <= 30 /* Digit9 */) || (event.keyCode >= 93 /* Numpad0 */ && event.keyCode <= 102 /* Numpad9 */) || (event.keyCode >= 80 /* Semicolon */ && event.keyCode <= 90 /* 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_2.Event.chain(this.enabledDisposables.add(new event_1.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.preventDefault()) .map(event => event.browserEvent.key) .event; const onClear = event_2.Event.debounce(onChar, () => null, 800); const onInput = event_2.Event.reduce(event_2.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-announce element on typing end since typed keys will interrupt aria label of focused element // Do not announce if there was a focus change at the end to prevent duplication https://github.com/microsoft/vscode/issues/95961 const ariaLabel = (_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_2.Event.chain(this.disposables.add(new event_1.DomEmitter(view.domNode, 'keydown')).event) .filter(e => !isInputElement(e.target)) .map(e => new keyboardEvent_1.StandardKeyboardEvent(e)); 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_2.Emitter(); this.onPointer = this._onPointer.event; if (list.options.multipleSelectionSupport !== false) { this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController; } this.mouseSupport = typeof list.options.mouseSupport === 'undefined' || !!list.options.mouseSupport; if (this.mouseSupport) { list.onMouseDown(this.onMouseDown, this, this.disposables); list.onContextMenu(this.onContextMenu, this, this.disposables); list.onMouseDblClick(this.onDoubleClick, this, this.disposables); list.onTouchStart(this.onMouseDown, this, this.disposables); this.disposables.add(touch_1.Gesture.addTarget(list.getHTMLElement())); } event_2.Event.any(list.onMouseClick, list.onMouseMiddleClick, list.onTap)(this.onViewPointer, this, this.disposables); } updateOptions(optionsUpdate) { if (optionsUpdate.multipleSelectionSupport !== undefined) { this.multipleSelectionController = undefined; if (optionsUpdate.multipleSelectionSupport) { this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController; } } } isSelectionSingleChangeEvent(event) { if (!this.multipleSelectionController) { return false; } return this.multipleSelectionController.isSelectionSingleChangeEvent(event); } isSelectionRangeChangeEvent(event) { if (!this.multipleSelectionController) { return false; } return this.multipleSelectionController.isSelectionRangeChangeEvent(event); } isSelectionChangeEvent(event) { return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event); } onMouseDown(e) { if (isMonacoEditor(e.browserEvent.target)) { return; } if (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; } .monaco-workbench.context-menu-visible .monaco-list${suffix}.last-focused .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}; }`); } if (styles.tableOddRowsBackgroundColor) { content.push(` .monaco-table .monaco-list-row[data-parity=odd]:not(.focused):not(.selected):not(:hover) .monaco-table-tr, .monaco-table .monaco-list:not(:focus) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr, .monaco-table .monaco-list:not(.focused) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr { background-color: ${styles.tableOddRowsBackgroundColor}; } `); } this.styleElement.textContent = content.join('\n'); } } exports.DefaultStyleController = DefaultStyleController; 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), tableOddRowsBackgroundColor: color_1.Color.fromHex('#cccccc').transparent(0.04) }; 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); } } /** * The {@link List} is a virtual scrolling widget, built on top of the {@link ListView} * widget. * * Features: * - Customizable keyboard and mouse support * - Element traits: focus, selection, achor * - Accessibility support * - Touch support * - Performant template-based rendering * - Horizontal scrolling * - Variable element height support * - Dynamic element height support * - Drag-and-drop support */ class List { 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_2.EventBufferer(); this._ariaLabel = ''; this.disposables = new lifecycle_1.DisposableStore(); this._onDidDispose = new event_2.Emitter(); this.onDidDispose = this._onDidDispose.event; const role = this._options.accessibilityProvider && this._options.accessibilityProvider.getWidgetRole ? (_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_2.Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), e => this.toListEvent(e)); } get onDidChangeSelection() { return event_2.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_2.Event.chain(this.disposables.add(new event_1.DomEmitter(this.view.domNode, 'keydown')).event) .map(e => new keyboardEvent_1.StandardKeyboardEvent(e)) .filter(e => didJustPressContextMenuKey = e.keyCode === 58 /* ContextMenu */ || (e.shiftKey && e.keyCode === 68 /* F10 */)) .map(event_1.stopEvent) .filter(() => false) .event; const fromKeyUp = event_2.Event.chain(this.disposables.add(new event_1.DomEmitter(this.view.domNode, 'keyup')).event) .forEach(() => didJustPressContextMenuKey = false) .map(e => new keyboardEvent_1.StandardKeyboardEvent(e)) .filter(e => e.keyCode === 58 /* ContextMenu */ || (e.shiftKey && e.keyCode === 68 /* F10 */)) .map(event_1.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_2.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_2.Event.any(fromKeyDown, fromKeyUp, fromMouse); } get onKeyDown() { return this.disposables.add(new event_1.DomEmitter(this.view.domNode, 'keydown')).event; } get onDidFocus() { return event_2.Event.signal(this.disposables.add(new event_1.DomEmitter(this.view.domNode, 'focus', true)).event); } 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[345/*vs/base/browser/ui/list/listPaging*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,21/*vs/base/common/cancellation*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,115/*vs/base/browser/ui/list/listWidget*/,226/*vs/css!vs/base/browser/ui/list/list*/]), function (require, exports, arrays_1, cancellation_1, event_1, lifecycle_1, listWidget_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PagedList = void 0; class PagedRenderer { 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[346/*vs/css!vs/base/browser/ui/splitview/splitview*/], __M([12/*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[228/*vs/base/browser/ui/splitview/splitview*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,114/*vs/base/browser/ui/sash/sash*/,67/*vs/base/browser/ui/scrollbar/scrollableElement*/,19/*vs/base/common/arrays*/,29/*vs/base/common/color*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,111/*vs/base/common/numbers*/,137/*vs/base/common/scrollable*/,20/*vs/base/common/types*/,346/*vs/css!vs/base/browser/ui/splitview/splitview*/]), function (require, exports, dom_1, sash_1, scrollableElement_1, arrays_1, color_1, event_1, lifecycle_1, numbers_1, scrollable_1, types) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SplitView = exports.Sizing = void 0; const defaultStyles = { separatorBorder: color_1.Color.transparent }; class ViewItem { 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) { /** * When adding or removing views, distribute the delta space among * all other views. */ Sizing.Distribute = { type: 'distribute' }; /** * When adding or removing views, split the delta space with another * specific view, indexed by the provided `index`. */ function Split(index) { return { type: 'split', index }; } Sizing.Split = Split; /** * When adding or removing views, assume the view is invisible. */ function Invisible(cachedVisibleSize) { return { type: 'invisible', cachedVisibleSize }; } Sizing.Invisible = Invisible; })(Sizing = exports.Sizing || (exports.Sizing = {})); /** * The {@link SplitView} is the UI component which implements a one dimensional * flex-like layout algorithm for a collection of {@link IView} instances, which * are essentially HTMLElement instances with the following size constraints: * * - {@link IView.minimumSize} * - {@link IView.maximumSize} * - {@link IView.priority} * - {@link IView.snap} * * In case the SplitView doesn't have enough size to fit all views, it will overflow * its content with a scrollbar. * * In between each pair of views there will be a {@link Sash} allowing the user * to resize the views, making sure the constraints are respected. * * An optional {@link TLayoutContext layout context type} may be used in order to * pass along layout contextual data from the {@link SplitView.layout} method down * to each view's {@link IView.layout} calls. * * Features: * - Flex-like layout algorithm * - Snap support * - Orthogonal sash support, for corner sashes * - View hide/show support * - View swap/move support * - Alt key modifier behavior, macOS style */ class SplitView extends lifecycle_1.Disposable { /** * Create a new {@link SplitView} instance. */ constructor(container, options = {}) { var _a, _b, _c, _d, _e; 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._onDidSashReset = this._register(new event_1.Emitter()); this._startSnappingEnabled = true; this._endSnappingEnabled = true; /** * Fires whenever the user resizes a {@link Sash sash}. */ this.onDidSashChange = this._onDidSashChange.event; /** * Fires whenever the user double clicks a {@link Sash sash}. */ this.onDidSashReset = this._onDidSashReset.event; this.orientation = (_a = options.orientation) !== null && _a !== void 0 ? _a : 0 /* VERTICAL */; this.inverseAltBehavior = (_b = options.inverseAltBehavior) !== null && _b !== void 0 ? _b : false; this.proportionalLayout = (_c = options.proportionalLayout) !== null && _c !== void 0 ? _c : true; 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({ forceIntegerValues: true, smoothScrollDuration: 125, scheduleAtNextAnimationFrame: dom_1.scheduleAtNextAnimationFrame }); this.scrollableElement = this._register(new scrollableElement_1.SmoothScrollableElement(this.viewContainer, { vertical: this.orientation === 0 /* VERTICAL */ ? ((_d = options.scrollbarVisibility) !== null && _d !== void 0 ? _d : 1 /* Auto */) : 2 /* Hidden */, horizontal: this.orientation === 1 /* HORIZONTAL */ ? ((_e = options.scrollbarVisibility) !== null && _e !== void 0 ? _e : 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; } get orthogonalEndSash() { return this._orthogonalEndSash; } get startSnappingEnabled() { return this._startSnappingEnabled; } get endSnappingEnabled() { return this._endSnappingEnabled; } /** * A reference to a sash, perpendicular to all sashes in this {@link SplitView}, * located at the left- or top-most side of the SplitView. * Corner sashes will be created automatically at the intersections. */ set orthogonalStartSash(sash) { for (const sashItem of this.sashItems) { sashItem.sash.orthogonalStartSash = sash; } this._orthogonalStartSash = sash; } /** * A reference to a sash, perpendicular to all sashes in this {@link SplitView}, * located at the right- or bottom-most side of the SplitView. * Corner sashes will be created automatically at the intersections. */ set orthogonalEndSash(sash) { for (const sashItem of this.sashItems) { sashItem.sash.orthogonalEndSash = sash; } this._orthogonalEndSash = sash; } /** * Enable/disable snapping at the beginning of this {@link SplitView}. */ set startSnappingEnabled(startSnappingEnabled) { if (this._startSnappingEnabled === startSnappingEnabled) { return; } this._startSnappingEnabled = startSnappingEnabled; this.updateSashEnablement(); } /** * Enable/disable snapping at the end of this {@link SplitView}. */ set endSnappingEnabled(endSnappingEnabled) { if (this._endSnappingEnabled === endSnappingEnabled) { return; } this._endSnappingEnabled = endSnappingEnabled; this.updateSashEnablement(); } style(styles) { if (styles.separatorBorder.isTransparent()) { this.el.classList.remove('separator-border'); this.el.style.removeProperty('--separator-border'); } else { this.el.classList.add('separator-border'); this.el.style.setProperty('--separator-border', styles.separatorBorder.toString()); } } /** * Add a {@link IView view} to this {@link SplitView}. * * @param view The view to add. * @param size Either a fixed size, or a dynamic {@link Sizing} strategy. * @param index The index to insert the view on. * @param skipLayout Whether layout should be skipped. */ addView(view, size, index = this.viewItems.length, skipLayout) { this.doAddView(view, size, index, skipLayout); } /** * Layout the {@link SplitView}. * * @param size The entire size of the {@link SplitView}. * @param layoutContext An optional layout context to pass along to {@link IView views}. */ layout(size, layoutContext) { const previousSize = Math.max(this.size, this.contentSize); this.size = size; this.layoutContext = layoutContext; if (!this.proportions) { const indexes = (0, arrays_1.range)(this.viewItems.length); const lowPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 1 /* 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); } } /** * Resize a {@link IView view} within the {@link SplitView}. * * @param index The {@link IView view} index. * @param size The {@link IView view} size. */ resizeView(index, size) { if (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; } /** * Distribute the entire {@link SplitView} size among all {@link IView views}. */ distributeViewSizes() { const flexibleViewItems = []; let flexibleSize = 0; for (const item of this.viewItems) { if (item.maximumSize - item.minimumSize > 0) { flexibleViewItems.push(item); flexibleSize += item.size; } } const size = Math.floor(flexibleSize / flexibleViewItems.length); for (const item of flexibleViewItems) { item.size = (0, numbers_1.clamp)(size, item.minimumSize, item.maximumSize); } const indexes = (0, arrays_1.range)(this.viewItems.length); const lowPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 1 /* Low */); const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* High */); this.relayout(lowPriorityIndexes, highPriorityIndexes); } /** * Returns the size of a {@link IView view}. */ getViewSize(index) { if (index < 0 || index >= this.viewItems.length) { return -1; } return this.viewItems[index].size; } doAddView(view, size, index = this.viewItems.length, skipLayout) { if (this.state !== State.Idle) { throw new Error('Cant modify splitview'); } this.state = State.Busy; // 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 /* AtMinimum */; } else if (snappedAfter && collapsesDown[index] && (position < this.contentSize || this.endSnappingEnabled)) { sash.state = 2 /* AtMaximum */; } else { sash.state = 0 /* Disabled */; } } else if (min && !max) { sash.state = 1 /* AtMinimum */; } else if (!min && max) { sash.state = 2 /* AtMaximum */; } 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[347/*vs/css!vs/base/browser/ui/table/table*/], __M([12/*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[348/*vs/base/browser/ui/table/tableWidget*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,115/*vs/base/browser/ui/list/listWidget*/,228/*vs/base/browser/ui/splitview/splitview*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,347/*vs/css!vs/base/browser/ui/table/table*/]), function (require, exports, dom_1, listWidget_1, splitview_1, event_1, lifecycle_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.disposables = new lifecycle_1.DisposableStore(); this.cachedWidth = 0; this.cachedHeight = 0; this.domNode = (0, dom_1.append)(container, (0, dom_1.$)(`.monaco-table.${this.domId}`)); const headers = columns.map((c, i) => new ColumnHeader(c, i)); const descriptor = { size: headers.reduce((a, b) => a + b.column.weight, 0), views: headers.map(view => ({ size: view.column.weight, view })) }; this.splitview = this.disposables.add(new splitview_1.SplitView(this.domNode, { orientation: 1 /* 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 = this.disposables.add(new listWidget_1.List(user, this.domNode, asListVirtualDelegate(virtualDelegate), [renderer], _options)); event_1.Event.any(...headers.map(h => h.onDidLayout))(([index, size]) => renderer.layoutColumn(index, size), null, this.disposables); this.splitview.onDidSashReset(index => { const totalWeight = columns.reduce((r, c) => r + c.weight, 0); const size = columns[index].weight / totalWeight * this.cachedWidth; this.splitview.resizeView(index, size); }, null, this.disposables); this.styleElement = (0, dom_1.createStyleSheet)(this.domNode); this.style({}); } 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.disposables.dispose(); } } exports.Table = Table; Table.InstanceCount = 0; }); define(__m[349/*vs/css!vs/base/browser/ui/tree/media/tree*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[142/*vs/css!vs/base/parts/quickinput/browser/media/quickInput*/], __M([12/*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[229/*vs/base/parts/quickinput/browser/quickInputUtils*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,133/*vs/base/common/idGenerator*/,142/*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[350/*vs/css!vs/editor/browser/controller/textAreaHandler*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[351/*vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[352/*vs/css!vs/editor/browser/viewParts/decorations/decorations*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[353/*vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[354/*vs/css!vs/editor/browser/viewParts/indentGuides/indentGuides*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[355/*vs/css!vs/editor/browser/viewParts/lineNumbers/lineNumbers*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[356/*vs/css!vs/editor/browser/viewParts/lines/viewLines*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[357/*vs/css!vs/editor/browser/viewParts/linesDecorations/linesDecorations*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[358/*vs/css!vs/editor/browser/viewParts/marginDecorations/marginDecorations*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[359/*vs/css!vs/editor/browser/viewParts/minimap/minimap*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[360/*vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[361/*vs/css!vs/editor/browser/viewParts/rulers/rulers*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[362/*vs/css!vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[363/*vs/css!vs/editor/browser/viewParts/selections/selections*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[364/*vs/css!vs/editor/browser/viewParts/viewCursors/viewCursors*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[365/*vs/css!vs/editor/browser/widget/media/diffEditor*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[366/*vs/css!vs/editor/browser/widget/media/diffReview*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[367/*vs/css!vs/editor/browser/widget/media/editor*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[368/*vs/css!vs/editor/contrib/anchorSelect/browser/anchorSelect*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[369/*vs/css!vs/editor/contrib/bracketMatching/browser/bracketMatching*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[370/*vs/css!vs/editor/contrib/codeAction/browser/lightBulbWidget*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[371/*vs/css!vs/editor/contrib/codelens/browser/codelensWidget*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[372/*vs/css!vs/editor/contrib/colorPicker/browser/colorPicker*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[373/*vs/css!vs/editor/contrib/dnd/browser/dnd*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[374/*vs/css!vs/editor/contrib/find/browser/findWidget*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[375/*vs/css!vs/editor/contrib/folding/browser/folding*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[376/*vs/css!vs/editor/contrib/gotoError/browser/media/gotoErrorWidget*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[377/*vs/css!vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[378/*vs/css!vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[379/*vs/css!vs/editor/contrib/inlineCompletions/browser/ghostText*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[380/*vs/css!vs/editor/contrib/links/browser/links*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[381/*vs/css!vs/editor/contrib/message/browser/messageController*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[382/*vs/css!vs/editor/contrib/parameterHints/browser/parameterHints*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[383/*vs/css!vs/editor/contrib/peekView/browser/media/peekViewWidget*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[384/*vs/css!vs/editor/contrib/rename/browser/renameInputField*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[385/*vs/css!vs/editor/contrib/snippet/browser/snippetSession*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[386/*vs/css!vs/editor/contrib/suggest/browser/media/suggest*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[387/*vs/css!vs/editor/contrib/unicodeHighlighter/browser/bannerController*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[388/*vs/css!vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[389/*vs/css!vs/editor/contrib/zoneWidget/browser/zoneWidget*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[390/*vs/css!vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[391/*vs/css!vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[392/*vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[393/*vs/css!vs/editor/standalone/browser/quickInput/standaloneQuickInput*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[394/*vs/css!vs/editor/standalone/browser/standalone-tokens*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[395/*vs/css!vs/platform/actions/browser/menuEntryActionViewItem*/], __M([12/*vs/css!vs/editor/editor.main*/]), {}); define(__m[396/*vs/css!vs/platform/contextview/browser/contextMenuHandler*/], __M([12/*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[230/*vs/editor/browser/config/elementSizeObserver*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,4/*vs/base/common/event*/]), function (require, exports, lifecycle_1, event_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ElementSizeObserver = void 0; class ElementSizeObserver extends lifecycle_1.Disposable { constructor(referenceDomElement, dimension) { super(); this._onDidChange = this._register(new event_1.Emitter()); this.onDidChange = this._onDidChange.event; this._referenceDomElement = referenceDomElement; this._width = -1; this._height = -1; this._resizeObserver = null; this.measureReferenceDomElement(false, dimension); } dispose() { this.stopObserving(); super.dispose(); } getWidth() { return this._width; } getHeight() { return this._height; } startObserving() { if (!this._resizeObserver && this._referenceDomElement) { 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); } } stopObserving() { if (this._resizeObserver) { this._resizeObserver.disconnect(); this._resizeObserver = null; } } observe(dimension) { this.measureReferenceDomElement(true, dimension); } measureReferenceDomElement(emitEvent, dimension) { let observedWidth = 0; let observedHeight = 0; if (dimension) { observedWidth = dimension.width; observedHeight = dimension.height; } else if (this._referenceDomElement) { observedWidth = this._referenceDomElement.clientWidth; observedHeight = this._referenceDomElement.clientHeight; } observedWidth = Math.max(5, observedWidth); observedHeight = Math.max(5, observedHeight); if (this._width !== observedWidth || this._height !== observedHeight) { this._width = observedWidth; this._height = observedHeight; if (emitEvent) { this._onDidChange.fire(); } } } } exports.ElementSizeObserver = ElementSizeObserver; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[397/*vs/editor/browser/config/migrateOptions*/], __M([1/*require*/,0/*exports*/,214/*vs/base/common/collections*/]), function (require, exports, collections_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.migrateOptions = void 0; /** * 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 (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'; } const { renderIndentGuides, highlightActiveIndentGuide } = options; if (!options.guides) { options.guides = {}; } if (renderIndentGuides !== undefined) { options.guides.indentation = !!renderIndentGuides; } if (highlightActiveIndentGuide !== undefined) { options.guides.highlightActiveIndentation = !!highlightActiveIndentGuide; } } exports.migrateOptions = migrateOptions; }); /*--------------------------------------------------------------------------------------------- * 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/browser/config/tabFocus*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/]), function (require, exports, event_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TabFocus = void 0; class TabFocusImpl { constructor() { this._tabFocus = false; this._onDidChangeTabFocus = new event_1.Emitter(); this.onDidChangeTabFocus = this._onDidChangeTabFocus.event; } getTabFocusMode() { return this._tabFocus; } setTabFocusMode(tabFocusMode) { if (this._tabFocus === tabFocusMode) { return; } this._tabFocus = tabFocusMode; this._onDidChangeTabFocus.fire(this._tabFocus); } } /** * Control what pressing Tab does. * If it is false, pressing Tab or Shift-Tab will be handled by the editor. * If it is true, pressing Tab or Shift-Tab will move the browser focus. * Defaults to false. */ exports.TabFocus = new TabFocusImpl(); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[143/*vs/editor/browser/stableEditorScroll*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.StableEditorScrollState = void 0; class StableEditorScrollState { 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[116/*vs/editor/browser/view/renderingContext*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.VisibleRanges = exports.HorizontalPosition = exports.FloatHorizontalRange = exports.HorizontalRange = exports.LineVisibleRanges = exports.RenderingContext = exports.RestrictedRenderingContext = void 0; class RestrictedRenderingContext { constructor(viewLayout, viewportData) { this._restrictedRenderingContextBrand = undefined; this._viewLayout = viewLayout; this.viewportData = viewportData; this.scrollWidth = this._viewLayout.getScrollWidth(); this.scrollHeight = this._viewLayout.getScrollHeight(); this.visibleRange = this.viewportData.visibleRange; this.bigNumbersDelta = this.viewportData.bigNumbersDelta; const vInfo = this._viewLayout.getCurrentViewport(); this.scrollTop = vInfo.top; this.scrollLeft = vInfo.left; this.viewportWidth = vInfo.width; this.viewportHeight = vInfo.height; } getScrolledTopFromAbsoluteTop(absoluteTop) { return absoluteTop - this.scrollTop; } getVerticalOffsetForLineNumber(lineNumber) { 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._horizontalRangeBrand = undefined; this.left = Math.round(left); this.width = Math.round(width); } static from(ranges) { const result = new Array(ranges.length); for (let i = 0, len = ranges.length; i < len; i++) { const range = ranges[i]; result[i] = new HorizontalRange(range.left, range.width); } return result; } toString() { return `[${this.left},${this.width}]`; } } exports.HorizontalRange = HorizontalRange; class FloatHorizontalRange { constructor(left, width) { this._floatHorizontalRangeBrand = undefined; this.left = left; this.width = width; } toString() { return `[${this.left},${this.width}]`; } static compare(a, b) { return a.left - b.left; } } exports.FloatHorizontalRange = FloatHorizontalRange; class HorizontalPosition { constructor(outsideRenderedLine, left) { this.outsideRenderedLine = outsideRenderedLine; this.originalLeft = left; this.left = Math.round(this.originalLeft); } } exports.HorizontalPosition = HorizontalPosition; class VisibleRanges { constructor(outsideRenderedLine, ranges) { this.outsideRenderedLine = outsideRenderedLine; this.ranges = ranges; } } exports.VisibleRanges = VisibleRanges; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[232/*vs/editor/browser/view/viewUserInputEvents*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "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) { const result = Object.assign({}, target); if (result.position) { result.position = coordinatesConverter.convertViewPositionToModelPosition(result.position); } if (result.range) { result.range = coordinatesConverter.convertViewRangeToModelRange(result.range); } return result; } } exports.ViewUserInputEvents = ViewUserInputEvents; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[398/*vs/editor/browser/viewParts/lines/rangeUtil*/], __M([1/*require*/,0/*exports*/,116/*vs/editor/browser/view/renderingContext*/]), function (require, exports, renderingContext_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RangeUtil = void 0; class RangeUtil { static _createRange() { if (!this._handyReadyRange) { this._handyReadyRange = document.createRange(); } return this._handyReadyRange; } static _detachRange(range, endNode) { // Move range out of the span node, IE doesn't like having many ranges in // the same spot and will act badly for lines containing dashes ('-') range.selectNodeContents(endNode); } static _readClientRects(startElement, startOffset, endElement, endOffset, endNode) { const range = this._createRange(); try { range.setStart(startElement, startOffset); range.setEnd(endElement, endOffset); return range.getClientRects(); } catch (e) { // This is life ... return null; } finally { this._detachRange(range, endNode); } } static _mergeAdjacentRanges(ranges) { if (ranges.length === 1) { // There is nothing to merge return ranges; } ranges.sort(renderingContext_1.FloatHorizontalRange.compare); const result = []; let resultLen = 0; let prev = ranges[0]; for (let i = 1, len = ranges.length; i < len; i++) { const range = ranges[i]; if (prev.left + prev.width + 0.9 /* account for browser's rounding errors*/ >= range.left) { prev.width = Math.max(prev.width, range.left + range.width - prev.left); } else { result[resultLen++] = prev; prev = range; } } result[resultLen++] = prev; return result; } static _createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft, clientRectScale) { if (!clientRects || clientRects.length === 0) { return null; } // We go through FloatHorizontalRange because it has been observed in bi-di text // that the clientRects are not coming in sorted from the browser const result = []; for (let i = 0, len = clientRects.length; i < len; i++) { const clientRect = clientRects[i]; result[i] = new renderingContext_1.FloatHorizontalRange(Math.max(0, (clientRect.left - clientRectDeltaLeft) / clientRectScale), clientRect.width / clientRectScale); } return this._mergeAdjacentRanges(result); } static readHorizontalRanges(domNode, startChildIndex, startOffset, endChildIndex, endOffset, clientRectDeltaLeft, clientRectScale, 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 // To cover cases of empty s, avoid using a range and use the 's bounding box const clientRects = domNode.children[startChildIndex].getClientRects(); return this._createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft, clientRectScale); } // If crossing over to a span only to select offset 0, then use the previous span's maximum offset // Chrome is buggy and doesn't handle 0 offsets well sometimes. if (startChildIndex !== endChildIndex) { if (endChildIndex > 0 && endOffset === 0) { endChildIndex--; endOffset = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; } } let startElement = domNode.children[startChildIndex].firstChild; let endElement = domNode.children[endChildIndex].firstChild; if (!startElement || !endElement) { // When having an empty (without any text content), try to move to the previous 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, clientRectScale); } } exports.RangeUtil = RangeUtil; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[233/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getCharIndex = exports.allCharCodes = void 0; exports.allCharCodes = (() => { const v = []; for (let i = 32 /* 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[399/*vs/editor/browser/viewParts/minimap/minimapCharRenderer*/], __M([1/*require*/,0/*exports*/,233/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/,139/*vs/base/common/uint*/]), function (require, exports, minimapCharSheet_1, uint_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MinimapCharRenderer = void 0; class MinimapCharRenderer { constructor(charData, scale) { this.scale = scale; this._minimapCharRendererBrand = undefined; this.charDataNormal = MinimapCharRenderer.soften(charData, 12 / 15); this.charDataLight = MinimapCharRenderer.soften(charData, 50 / 60); } static soften(input, ratio) { const result = new Uint8ClampedArray(input.length); for (let i = 0, len = input.length; i < len; i++) { result[i] = (0, uint_1.toUint8)(input[i] * ratio); } return result; } renderChar(target, dx, dy, chCode, color, foregroundAlpha, backgroundColor, backgroundAlpha, fontScale, useLighterFont, force1pxHeight) { const charWidth = 1 /* 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 destAlpha = Math.max(foregroundAlpha, backgroundAlpha); 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) * (foregroundAlpha / 255); dest[column++] = backgroundR + deltaR * c; dest[column++] = backgroundG + deltaG * c; dest[column++] = backgroundB + deltaB * c; dest[column++] = destAlpha; } row += destWidth; } } blockRenderChar(target, dx, dy, color, foregroundAlpha, backgroundColor, backgroundAlpha, force1pxHeight) { const charWidth = 1 /* 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 * (foregroundAlpha / 255); const backgroundR = backgroundColor.r; const backgroundG = backgroundColor.g; const backgroundB = backgroundColor.b; const deltaR = color.r - backgroundR; const deltaG = color.g - backgroundG; const deltaB = color.b - backgroundB; const colorR = backgroundR + deltaR * c; const colorG = backgroundG + deltaG * c; const colorB = backgroundB + deltaB * c; const destAlpha = Math.max(foregroundAlpha, backgroundAlpha); const dest = target.data; let row = dy * destWidth + dx * 4 /* RGBA_CHANNELS_CNT */; for (let y = 0; y < renderHeight; y++) { let column = row; for (let x = 0; x < charWidth; x++) { dest[column++] = colorR; dest[column++] = colorG; dest[column++] = colorB; dest[column++] = destAlpha; } row += destWidth; } } } exports.MinimapCharRenderer = MinimapCharRenderer; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[400/*vs/editor/browser/viewParts/minimap/minimapPreBaked*/], __M([1/*require*/,0/*exports*/,88/*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[401/*vs/editor/browser/viewParts/minimap/minimapCharRendererFactory*/], __M([1/*require*/,0/*exports*/,399/*vs/editor/browser/viewParts/minimap/minimapCharRenderer*/,233/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/,400/*vs/editor/browser/viewParts/minimap/minimapPreBaked*/,139/*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'); } const 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[144/*vs/editor/common/config/editorZoom*/], __M([1/*require*/,0/*exports*/,4/*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[174/*vs/editor/common/config/fontInfo*/], __M([1/*require*/,0/*exports*/,17/*vs/base/common/platform*/,144/*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.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, pixelRatio, ignoreEditorZoom) { const fontFamily = options.get(43 /* fontFamily */); const fontWeight = options.get(47 /* fontWeight */); const fontSize = options.get(46 /* fontSize */); const fontFeatureSettings = options.get(45 /* fontLigatures */); const lineHeight = options.get(59 /* lineHeight */); const letterSpacing = options.get(56 /* letterSpacing */); return BareFontInfo._create(fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom); } /** * @internal */ static _create(fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom) { if (lineHeight === 0) { lineHeight = GOLDEN_LINE_HEIGHT_RATIO * fontSize; } else if (lineHeight < MINIMUM_LINE_HEIGHT) { // Values too small to be line heights in pixels are in ems. lineHeight = lineHeight * fontSize; } // Enforce integer, minimum constraints lineHeight = Math.round(lineHeight); if (lineHeight < MINIMUM_LINE_HEIGHT) { lineHeight = MINIMUM_LINE_HEIGHT; } const editorZoomLevelMultiplier = 1 + (ignoreEditorZoom ? 0 : editorZoom_1.EditorZoom.getZoomLevel() * 0.1); fontSize *= editorZoomLevelMultiplier; lineHeight *= editorZoomLevelMultiplier; return new BareFontInfo({ pixelRatio: pixelRatio, fontFamily: fontFamily, fontWeight: fontWeight, fontSize: fontSize, fontFeatureSettings: fontFeatureSettings, lineHeight: lineHeight, letterSpacing: letterSpacing }); } /** * @internal */ getId() { return `${this.pixelRatio}-${this.fontFamily}-${this.fontWeight}-${this.fontSize}-${this.fontFeatureSettings}-${this.lineHeight}-${this.letterSpacing}`; } /** * @internal */ getMassagedFontFamily(fallbackFontFamily) { const fontFamily = BareFontInfo._wrapInQuotes(this.fontFamily); if (fallbackFontFamily && this.fontFamily !== fallbackFontFamily) { return `${fontFamily}, ${fallbackFontFamily}`; } return fontFamily; } static _wrapInQuotes(fontFamily) { if (/[,"']/.test(fontFamily)) { // Looks like the font family might be already escaped return fontFamily; } if (/[+ ]/.test(fontFamily)) { // Wrap a font family using + or with quotes return `"${fontFamily}"`; } return 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[97/*vs/editor/common/core/characterClassifier*/], __M([1/*require*/,0/*exports*/,139/*vs/base/common/uint*/]), function (require, exports, uint_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CharacterSet = exports.CharacterClassifier = void 0; /** * A fast character classifier that uses a compact array for ASCII values. */ class CharacterClassifier { constructor(_defaultValue) { const defaultValue = (0, uint_1.toUint8)(_defaultValue); this._defaultValue = defaultValue; this._asciiMap = CharacterClassifier._createAsciiMap(defaultValue); this._map = new Map(); } static _createAsciiMap(defaultValue) { const asciiMap = new Uint8Array(256); for (let i = 0; i < 256; i++) { asciiMap[i] = defaultValue; } return asciiMap; } set(charCode, _value) { const value = (0, uint_1.toUint8)(_value); if (charCode >= 0 && charCode < 256) { this._asciiMap[charCode] = value; } else { this._map.set(charCode, value); } } get(charCode) { if (charCode >= 0 && charCode < 256) { return this._asciiMap[charCode]; } else { return (this._map.get(charCode) || this._defaultValue); } } } 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[68/*vs/editor/common/core/cursorColumns*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/]), function (require, exports, strings) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CursorColumns = void 0; /** * A column in a position is the gap between two adjacent characters. The methods here * work with a concept called "visible column". A visible column is a very rough approximation * of the horizontal screen position of a column. For example, using a tab size of 4: * ```txt * |||T|ext * | | | \---- column = 4, visible column = 9 * | | \------ column = 3, visible column = 8 * | \------------ column = 2, visible column = 4 * \------------------ column = 1, visible column = 0 * ``` * * **NOTE**: Visual columns do not work well for RTL text or variable-width fonts or characters. * * **NOTE**: These methods work and make sense both on the model and on the view model. */ class CursorColumns { static _nextVisibleColumn(codePoint, visibleColumn, tabSize) { if (codePoint === 9 /* Tab */) { return CursorColumns.nextRenderTabStop(visibleColumn, tabSize); } if (strings.isFullWidthCharacter(codePoint) || strings.isEmojiImprecise(codePoint)) { return visibleColumn + 2; } return visibleColumn + 1; } /** * Returns a visible column from a column. * @see {@link CursorColumns} */ static visibleColumnFromColumn(lineContent, column, tabSize) { const textLen = Math.min(column - 1, lineContent.length); const text = lineContent.substring(0, textLen); const iterator = new strings.GraphemeIterator(text); let result = 0; while (!iterator.eol()) { const codePoint = strings.getNextCodePoint(text, textLen, iterator.offset); iterator.nextGraphemeLength(); result = this._nextVisibleColumn(codePoint, result, tabSize); } return result; } /** * Returns a column from a visible column. * @see {@link CursorColumns} */ static columnFromVisibleColumn(lineContent, visibleColumn, tabSize) { if (visibleColumn <= 0) { return 1; } const lineContentLength = lineContent.length; const iterator = new strings.GraphemeIterator(lineContent); let beforeVisibleColumn = 0; let beforeColumn = 1; while (!iterator.eol()) { const codePoint = strings.getNextCodePoint(lineContent, lineContentLength, iterator.offset); iterator.nextGraphemeLength(); const afterVisibleColumn = this._nextVisibleColumn(codePoint, beforeVisibleColumn, tabSize); const afterColumn = iterator.offset + 1; if (afterVisibleColumn >= visibleColumn) { const beforeDelta = visibleColumn - beforeVisibleColumn; const afterDelta = afterVisibleColumn - visibleColumn; if (afterDelta < beforeDelta) { return afterColumn; } else { return beforeColumn; } } beforeVisibleColumn = afterVisibleColumn; beforeColumn = afterColumn; } // walked the entire string return lineContentLength + 1; } /** * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns) * @see {@link CursorColumns} */ static nextRenderTabStop(visibleColumn, tabSize) { return visibleColumn + tabSize - visibleColumn % tabSize; } /** * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns) * @see {@link CursorColumns} */ static nextIndentTabStop(visibleColumn, indentSize) { return visibleColumn + indentSize - visibleColumn % indentSize; } /** * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns) * @see {@link CursorColumns} */ static prevRenderTabStop(column, tabSize) { return Math.max(0, column - 1 - (column - 1) % tabSize); } /** * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns) * @see {@link CursorColumns} */ static prevIndentTabStop(column, indentSize) { return Math.max(0, column - 1 - (column - 1) % indentSize); } } exports.CursorColumns = CursorColumns; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[117/*vs/editor/common/core/eolCounter*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }); /*--------------------------------------------------------------------------------------------- * 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/editor/common/core/position*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Position = void 0; /** * A position in the editor. */ class Position { constructor(lineNumber, column) { this.lineNumber = lineNumber; this.column = column; } /** * Create a new position from this position. * * @param newLineNumber new line number * @param newColumn new column */ with(newLineNumber = this.lineNumber, newColumn = this.column) { if (newLineNumber === this.lineNumber && newColumn === this.column) { return this; } else { return new Position(newLineNumber, newColumn); } } /** * Derive a new position from this position. * * @param deltaLineNumber line number delta * @param deltaColumn column delta */ delta(deltaLineNumber = 0, deltaColumn = 0) { return this.with(this.lineNumber + deltaLineNumber, this.column + deltaColumn); } /** * Test if this position equals other position */ equals(other) { return Position.equals(this, other); } /** * Test if position `a` equals position `b` */ static equals(a, b) { if (!a && !b) { return true; } return (!!a && !!b && a.lineNumber === b.lineNumber && a.column === b.column); } /** * Test if this position is before other position. * If the two positions are equal, the result will be false. */ isBefore(other) { return Position.isBefore(this, other); } /** * Test if position `a` is before position `b`. * If the two positions are equal, the result will be false. */ static isBefore(a, b) { if (a.lineNumber < b.lineNumber) { return true; } if (b.lineNumber < a.lineNumber) { return false; } return a.column < b.column; } /** * Test if this position is before other position. * If the two positions are equal, the result will be true. */ isBeforeOrEqual(other) { return Position.isBeforeOrEqual(this, other); } /** * Test if position `a` is before position `b`. * If the two positions are equal, the result will be true. */ static isBeforeOrEqual(a, b) { if (a.lineNumber < b.lineNumber) { return true; } if (b.lineNumber < a.lineNumber) { return false; } return a.column <= b.column; } /** * A function that compares positions, useful for sorting */ static compare(a, b) { const aLineNumber = a.lineNumber | 0; const bLineNumber = b.lineNumber | 0; if (aLineNumber === bLineNumber) { const aColumn = a.column | 0; const bColumn = b.column | 0; return aColumn - bColumn; } return aLineNumber - bLineNumber; } /** * Clone this position. */ clone() { return new Position(this.lineNumber, this.column); } /** * Convert to a human-readable representation. */ toString() { return '(' + this.lineNumber + ',' + this.column + ')'; } // --- /** * Create a `Position` from an `IPosition`. */ static lift(pos) { return new Position(pos.lineNumber, pos.column); } /** * Test if `obj` is an `IPosition`. */ static isIPosition(obj) { return (obj && (typeof obj.lineNumber === 'number') && (typeof obj.column === 'number')); } } 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([1/*require*/,0/*exports*/,11/*vs/editor/common/core/position*/]), function (require, exports, position_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Range = void 0; /** * A range in the editor. (startLineNumber,startColumn) is <= (endLineNumber,endColumn) */ class Range { constructor(startLineNumber, startColumn, endLineNumber, endColumn) { if ((startLineNumber > endLineNumber) || (startLineNumber === endLineNumber && startColumn > endColumn)) { this.startLineNumber = endLineNumber; this.startColumn = endColumn; this.endLineNumber = startLineNumber; this.endColumn = startColumn; } else { this.startLineNumber = startLineNumber; this.startColumn = startColumn; this.endLineNumber = endLineNumber; this.endColumn = endColumn; } } /** * Test if this range is empty. */ isEmpty() { return Range.isEmpty(this); } /** * Test if `range` is empty. */ static isEmpty(range) { return (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn); } /** * Test if position is in this range. If the position is at the edges, will return true. */ containsPosition(position) { return Range.containsPosition(this, position); } /** * Test if `position` is in `range`. If the position is at the edges, will return true. */ static containsPosition(range, position) { if (position.lineNumber < range.startLineNumber || position.lineNumber > range.endLineNumber) { return false; } if (position.lineNumber === range.startLineNumber && position.column < range.startColumn) { return false; } if (position.lineNumber === range.endLineNumber && position.column > range.endColumn) { return false; } return true; } /** * Test if `position` is in `range`. If the position is at the edges, will return false. * @internal */ static strictContainsPosition(range, position) { if (position.lineNumber < range.startLineNumber || position.lineNumber > range.endLineNumber) { return false; } if (position.lineNumber === range.startLineNumber && position.column <= range.startColumn) { return false; } if (position.lineNumber === range.endLineNumber && position.column >= range.endColumn) { return false; } return true; } /** * Test if range is in this range. If the range is equal to this range, will return true. */ containsRange(range) { return Range.containsRange(this, range); } /** * Test if `otherRange` is in `range`. If the ranges are equal, will return true. */ static containsRange(range, otherRange) { if (otherRange.startLineNumber < range.startLineNumber || otherRange.endLineNumber < range.startLineNumber) { return false; } if (otherRange.startLineNumber > range.endLineNumber || otherRange.endLineNumber > range.endLineNumber) { return false; } if (otherRange.startLineNumber === range.startLineNumber && otherRange.startColumn < range.startColumn) { return false; } if (otherRange.endLineNumber === range.endLineNumber && otherRange.endColumn > range.endColumn) { return false; } return true; } /** * Test if `range` is strictly in this range. `range` must start after and end before this range for the result to be true. */ strictContainsRange(range) { return Range.strictContainsRange(this, range); } /** * Test if `otherRange` is strictly in `range` (must start after, and end before). If the ranges are equal, will return false. */ static strictContainsRange(range, otherRange) { if (otherRange.startLineNumber < range.startLineNumber || otherRange.endLineNumber < range.startLineNumber) { return false; } if (otherRange.startLineNumber > range.endLineNumber || otherRange.endLineNumber > range.endLineNumber) { return false; } if (otherRange.startLineNumber === range.startLineNumber && otherRange.startColumn <= range.startColumn) { return false; } if (otherRange.endLineNumber === range.endLineNumber && otherRange.endColumn >= range.endColumn) { return false; } return true; } /** * A reunion of the two ranges. * The smallest position will be used as the start point, and the largest one as the end point. */ plusRange(range) { return Range.plusRange(this, range); } /** * A reunion of the two ranges. * The smallest position will be used as the start point, and the largest one as the end point. */ static plusRange(a, b) { let startLineNumber; let startColumn; let endLineNumber; let endColumn; if (b.startLineNumber < a.startLineNumber) { startLineNumber = b.startLineNumber; startColumn = b.startColumn; } else if (b.startLineNumber === a.startLineNumber) { startLineNumber = b.startLineNumber; startColumn = Math.min(b.startColumn, a.startColumn); } else { startLineNumber = a.startLineNumber; startColumn = a.startColumn; } if (b.endLineNumber > a.endLineNumber) { endLineNumber = b.endLineNumber; endColumn = b.endColumn; } else if (b.endLineNumber === a.endLineNumber) { endLineNumber = b.endLineNumber; endColumn = Math.max(b.endColumn, a.endColumn); } else { endLineNumber = a.endLineNumber; endColumn = a.endColumn; } return new Range(startLineNumber, startColumn, endLineNumber, endColumn); } /** * A intersection of the two ranges. */ intersectRanges(range) { return Range.intersectRanges(this, range); } /** * A intersection of the two ranges. */ static intersectRanges(a, b) { let resultStartLineNumber = a.startLineNumber; let resultStartColumn = a.startColumn; let resultEndLineNumber = a.endLineNumber; let resultEndColumn = a.endColumn; 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[234/*vs/editor/browser/controller/textAreaState*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,11/*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 deduceInput(previousState, currentState, couldBeEmojiInput) { if (!previousState) { // This is the EMPTY state return { text: '', replacePrevCharCnt: 0, replaceNextCharCnt: 0, positionDelta: 0 }; } if (exports._debugComposition) { console.log('------------------------deduceInput'); console.log(`PREVIOUS STATE: ${previousState.toString()}`); console.log(`CURRENT STATE: ${currentState.toString()}`); } const prefixLength = Math.min(strings.commonPrefixLength(previousState.value, currentState.value), previousState.selectionStart, currentState.selectionStart); const suffixLength = Math.min(strings.commonSuffixLength(previousState.value, currentState.value), previousState.value.length - previousState.selectionEnd, currentState.value.length - currentState.selectionEnd); const previousValue = previousState.value.substring(prefixLength, previousState.value.length - suffixLength); const currentValue = currentState.value.substring(prefixLength, currentState.value.length - suffixLength); const previousSelectionStart = previousState.selectionStart - prefixLength; const previousSelectionEnd = previousState.selectionEnd - prefixLength; const currentSelectionStart = currentState.selectionStart - prefixLength; const currentSelectionEnd = currentState.selectionEnd - prefixLength; if (exports._debugComposition) { console.log(`AFTER DIFFING PREVIOUS STATE: <${previousValue}>, selectionStart: ${previousSelectionStart}, selectionEnd: ${previousSelectionEnd}`); console.log(`AFTER DIFFING CURRENT STATE: <${currentValue}>, selectionStart: ${currentSelectionStart}, selectionEnd: ${currentSelectionEnd}`); } if (currentSelectionStart === currentSelectionEnd) { // no current selection const replacePreviousCharacters = (previousState.selectionStart - prefixLength); if (exports._debugComposition) { console.log(`REMOVE PREVIOUS: ${replacePreviousCharacters} chars`); } return { text: currentValue, replacePrevCharCnt: replacePreviousCharacters, replaceNextCharCnt: 0, positionDelta: 0 }; } // there is a current selection => composition case const replacePreviousCharacters = previousSelectionEnd - previousSelectionStart; return { text: currentValue, replacePrevCharCnt: replacePreviousCharacters, replaceNextCharCnt: 0, positionDelta: 0 }; } static deduceAndroidCompositionInput(previousState, currentState) { if (!previousState) { // This is the EMPTY state return { text: '', replacePrevCharCnt: 0, replaceNextCharCnt: 0, positionDelta: 0 }; } if (exports._debugComposition) { console.log('------------------------deduceAndroidCompositionInput'); console.log(`PREVIOUS STATE: ${previousState.toString()}`); console.log(`CURRENT STATE: ${currentState.toString()}`); } if (previousState.value === currentState.value) { return { text: '', replacePrevCharCnt: 0, replaceNextCharCnt: 0, positionDelta: currentState.selectionEnd - previousState.selectionEnd }; } const prefixLength = Math.min(strings.commonPrefixLength(previousState.value, currentState.value), previousState.selectionEnd); const suffixLength = Math.min(strings.commonSuffixLength(previousState.value, currentState.value), previousState.value.length - previousState.selectionEnd); const previousValue = previousState.value.substring(prefixLength, previousState.value.length - suffixLength); const currentValue = currentState.value.substring(prefixLength, currentState.value.length - suffixLength); const previousSelectionStart = previousState.selectionStart - prefixLength; const previousSelectionEnd = previousState.selectionEnd - prefixLength; const currentSelectionStart = currentState.selectionStart - prefixLength; const currentSelectionEnd = currentState.selectionEnd - prefixLength; if (exports._debugComposition) { console.log(`AFTER DIFFING PREVIOUS STATE: <${previousValue}>, selectionStart: ${previousSelectionStart}, selectionEnd: ${previousSelectionEnd}`); console.log(`AFTER DIFFING CURRENT STATE: <${currentValue}>, selectionStart: ${currentSelectionStart}, selectionEnd: ${currentSelectionEnd}`); } return { text: currentValue, replacePrevCharCnt: previousSelectionEnd, replaceNextCharCnt: previousValue.length - previousSelectionEnd, positionDelta: currentSelectionEnd - currentValue.length }; } } exports.TextAreaState = TextAreaState; 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[235/*vs/editor/browser/widget/diffNavigator*/], __M([1/*require*/,0/*exports*/,213/*vs/base/common/assert*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,39/*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() { const 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 { if (lineChange.modifiedEndLineNumber === 0) { // a deletion this.ranges.push({ rhs: true, range: new range_1.Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedStartLineNumber + 1, 1) }); } else { // an insertion or modification this.ranges.push({ rhs: true, range: new range_1.Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber + 1, 1) }); } } }); } // sort this.ranges.sort((left, right) => range_1.Range.compareRangesUsingStarts(left.range, right.range)); this._onDidUpdate.fire(this); } _initIdx(fwd) { let found = false; const position = this._editor.getPosition(); if (!position) { this.nextIdx = 0; return; } for (let i = 0, len = this.ranges.length; i < len && !found; i++) { const 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; } } const info = this.ranges[this.nextIdx]; this.ignoreSelectionChange = true; try { const pos = info.range.getStartPosition(); this._editor.setPosition(pos); this._editor.revealRangeInCenter(info.range, 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[61/*vs/editor/common/core/editOperation*/], __M([1/*require*/,0/*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[402/*vs/editor/common/commands/trimTrailingWhitespaceCommand*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,61/*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) { const ops = trimTrailingWhitespace(model, this._cursors); for (let i = 0, len = ops.length; i < len; i++) { const op = ops[i]; builder.addEditOperation(op.range, op.text); } this._selectionId = builder.trackSelection(this._selection); } computeCursorState(model, helper) { return helper.getTrackedSelection(this._selectionId); } } exports.TrimTrailingWhitespaceCommand = TrimTrailingWhitespaceCommand; /** * Generate commands for trimming trailing whitespace on a model and ignore lines on which cursors are sitting. */ function trimTrailingWhitespace(model, cursors) { // Sort cursors ascending cursors.sort((a, b) => { if (a.lineNumber === b.lineNumber) { return a.column - b.column; } return a.lineNumber - b.lineNumber; }); // Reduce multiple cursors on the same line and only keep the last one on the line for (let i = cursors.length - 2; i >= 0; i--) { if (cursors[i].lineNumber === cursors[i + 1].lineNumber) { // Remove cursor at `i` cursors.splice(i, 1); } } const r = []; let rLen = 0; let cursorIndex = 0; const cursorLen = cursors.length; for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) { const lineContent = model.getLineContent(lineNumber); const maxLineColumn = lineContent.length + 1; let minEditColumn = 0; if (cursorIndex < cursorLen && cursors[cursorIndex].lineNumber === lineNumber) { minEditColumn = cursors[cursorIndex].column; cursorIndex++; if (minEditColumn === maxLineColumn) { // The cursor is at the end of the line => no edits for sure on this line continue; } } if (lineContent.length === 0) { continue; } const lastNonWhitespaceIndex = strings.lastNonWhitespaceIndex(lineContent); let fromColumn = 0; if (lastNonWhitespaceIndex === -1) { // Entire line is whitespace fromColumn = 1; } else if (lastNonWhitespaceIndex !== lineContent.length - 1) { // There is trailing whitespace fromColumn = lastNonWhitespaceIndex + 2; } else { // There is no trailing whitespace continue; } 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[236/*vs/editor/common/core/rgba*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RGBA8 = void 0; /** * A very VM friendly rgba datastructure. * Please don't touch unless you take a look at the IR. */ class RGBA8 { 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[22/*vs/editor/common/core/selection*/], __M([1/*require*/,0/*exports*/,11/*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); } /** * Get the position at the start of the selection. */ getSelectionStart() { return new position_1.Position(this.selectionStartLineNumber, this.selectionStartColumn); } /** * Create a new selection with a different `selectionStartLineNumber` and `selectionStartColumn`. */ setStartPosition(startLineNumber, startColumn) { if (this.getDirection() === 0 /* LTR */) { return new Selection(startLineNumber, startColumn, this.endLineNumber, this.endColumn); } return new Selection(this.endLineNumber, this.endColumn, startLineNumber, startColumn); } // ---- /** * Create a `Selection` from one or two positions */ static fromPositions(start, end = start) { return new Selection(start.lineNumber, start.column, end.lineNumber, end.column); } /** * Creates a `Selection` from a range, given a direction. */ static fromRange(range, direction) { if (direction === 0 /* LTR */) { return new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn); } else { return new Selection(range.endLineNumber, range.endColumn, range.startLineNumber, range.startColumn); } } /** * Create a `Selection` from an `ISelection`. */ static liftSelection(sel) { return new Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn); } /** * `a` equals `b`. */ static selectionsArrEqual(a, b) { if (a && !b || !a && b) { return false; } if (!a && !b) { return true; } if (a.length !== b.length) { return false; } for (let i = 0, len = a.length; i < len; i++) { if (!this.selectionsEqual(a[i], b[i])) { return false; } } return true; } /** * Test if `obj` is an `ISelection`. */ static isISelection(obj) { return (obj && (typeof obj.selectionStartLineNumber === 'number') && (typeof obj.selectionStartColumn === 'number') && (typeof obj.positionLineNumber === 'number') && (typeof obj.positionColumn === 'number')); } /** * Create with a direction. */ static createWithDirection(startLineNumber, startColumn, endLineNumber, endColumn, direction) { if (direction === 0 /* 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[175/*vs/editor/browser/controller/textAreaInput*/], __M([1/*require*/,0/*exports*/,34/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,46/*vs/base/browser/keyboardEvent*/,10/*vs/base/common/async*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,135/*vs/base/common/mime*/,8/*vs/base/common/strings*/,234/*vs/editor/browser/controller/textAreaState*/,22/*vs/editor/common/core/selection*/]), function (require, exports, browser, dom, keyboardEvent_1, async_1, event_1, lifecycle_1, mime_1, strings, textAreaState_1, selection_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TextAreaWrapper = 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(); class CompositionContext { constructor() { this._lastTypeTextLength = 0; } handleCompositionUpdate(text) { text = text || ''; const typeInput = { text: text, replacePrevCharCnt: this._lastTypeTextLength, replaceNextCharCnt: 0, positionDelta: 0 }; this._lastTypeTextLength = text.length; return typeInput; } } /** * Writes screen reader content to the textarea and is able to analyze its input events to generate: * - onCut * - onPaste * - onType * * Composition events are generated for presentation purposes (composition input is reflected in onType). */ class TextAreaInput extends lifecycle_1.Disposable { constructor(_host, _textArea, _OS, _browser) { super(); this._host = _host; this._textArea = _textArea; this._OS = _OS; this._browser = _browser; 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._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._currentComposition = null; let lastKeyDown = null; this._register(this._textArea.onKeyDown((_e) => { const e = new keyboardEvent_1.StandardKeyboardEvent(_e); if (e.keyCode === 109 /* KEY_IN_COMPOSITION */ || (this._currentComposition && 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(this._textArea.onKeyUp((_e) => { const e = new keyboardEvent_1.StandardKeyboardEvent(_e); this._onKeyUp.fire(e); })); this._register(this._textArea.onCompositionStart((e) => { if (textAreaState_1._debugComposition) { console.log(`[compositionstart]`, e); } const currentComposition = new CompositionContext(); if (this._currentComposition) { // simply reset the composition context this._currentComposition = currentComposition; return; } this._currentComposition = currentComposition; if (this._OS === 2 /* Macintosh */ && lastKeyDown && lastKeyDown.equals(109 /* KEY_IN_COMPOSITION */) && this._textAreaState.selectionStart === this._textAreaState.selectionEnd && this._textAreaState.selectionStart > 0 && this._textAreaState.value.substr(this._textAreaState.selectionStart - 1, 1) === e.data && (lastKeyDown.code === 'ArrowRight' || lastKeyDown.code === 'ArrowLeft')) { // Handling long press case on Chromium/Safari macOS + arrow key => pretend the character was selected if (textAreaState_1._debugComposition) { console.log(`[compositionstart] Handling long press case on macOS + arrow key`, e); } // Pretend the previous character was composed (in order to get it removed by subsequent compositionupdate events) currentComposition.handleCompositionUpdate('x'); this._onCompositionStart.fire({ data: e.data }); return; } if (this._browser.isAndroid) { // when tapping on the editor, Android enters composition mode to edit the current word // so we cannot clear the textarea on Android and we must pretend the current word was selected this._onCompositionStart.fire({ data: e.data }); return; } this._onCompositionStart.fire({ data: e.data }); })); this._register(this._textArea.onCompositionUpdate((e) => { if (textAreaState_1._debugComposition) { console.log(`[compositionupdate]`, e); } const currentComposition = this._currentComposition; if (!currentComposition) { // should not be possible to receive a 'compositionupdate' without a 'compositionstart' return; } if (this._browser.isAndroid) { // On Android, the data sent with the composition update event is unusable. // For example, if the cursor is in the middle of a word like Mic|osoft // and Microsoft is chosen from the keyboard's suggestions, the e.data will contain "Microsoft". // This is not really usable because it doesn't tell us where the edit began and where it ended. const newState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea); const typeInput = textAreaState_1.TextAreaState.deduceAndroidCompositionInput(this._textAreaState, newState); this._textAreaState = newState; this._onType.fire(typeInput); this._onCompositionUpdate.fire(e); return; } const typeInput = currentComposition.handleCompositionUpdate(e.data); this._textAreaState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea); this._onType.fire(typeInput); this._onCompositionUpdate.fire(e); })); this._register(this._textArea.onCompositionEnd((e) => { if (textAreaState_1._debugComposition) { console.log(`[compositionend]`, e); } const currentComposition = this._currentComposition; if (!currentComposition) { // https://github.com/microsoft/monaco-editor/issues/1663 // On iOS 13.2, Chinese system IME randomly trigger an additional compositionend event with empty data return; } this._currentComposition = null; if (this._browser.isAndroid) { // On Android, the data sent with the composition update event is unusable. // For example, if the cursor is in the middle of a word like Mic|osoft // and Microsoft is chosen from the keyboard's suggestions, the e.data will contain "Microsoft". // This is not really usable because it doesn't tell us where the edit began and where it ended. const newState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea); const typeInput = textAreaState_1.TextAreaState.deduceAndroidCompositionInput(this._textAreaState, newState); this._textAreaState = newState; this._onType.fire(typeInput); this._onCompositionEnd.fire(); return; } const typeInput = currentComposition.handleCompositionUpdate(e.data); this._textAreaState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea); this._onType.fire(typeInput); this._onCompositionEnd.fire(); })); this._register(this._textArea.onInput((e) => { if (textAreaState_1._debugComposition) { console.log(`[input]`, e); } // Pretend here we touched the text area, as the `input` event will most likely // result in a `selectionchange` event which we want to ignore this._textArea.setIgnoreSelectionChangeTime('received input event'); if (this._currentComposition) { return; } const newState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea); const typeInput = textAreaState_1.TextAreaState.deduceInput(this._textAreaState, newState, /*couldBeEmojiInput*/ this._OS === 2 /* Macintosh */); 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 (typeInput.text !== '' || typeInput.replacePrevCharCnt !== 0 || typeInput.replaceNextCharCnt !== 0 || typeInput.positionDelta !== 0) { this._onType.fire(typeInput); } })); // --- Clipboard operations this._register(this._textArea.onCut((e) => { // Pretend here we touched the text area, as the `cut` event will most likely // result in a `selectionchange` event which we want to ignore this._textArea.setIgnoreSelectionChangeTime('received cut event'); this._ensureClipboardGetsEditorSelection(e); this._asyncTriggerCut.schedule(); })); this._register(this._textArea.onCopy((e) => { this._ensureClipboardGetsEditorSelection(e); })); this._register(this._textArea.onPaste((e) => { // Pretend here we touched the text area, as the `paste` event will most likely // result in a `selectionchange` event which we want to ignore this._textArea.setIgnoreSelectionChangeTime('received paste event'); e.preventDefault(); if (!e.clipboardData) { return; } let [text, metadata] = ClipboardEventUtils.getTextData(e.clipboardData); if (!text) { return; } // try the in-memory store metadata = metadata || InMemoryClipboardMetadataManager.INSTANCE.get(text); this._onPaste.fire({ text: text, metadata: metadata }); })); this._register(this._textArea.onFocus(() => { const hadFocus = this._hasFocus; this._setHasFocus(true); if (this._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(this._textArea.onBlur(() => { if (this._currentComposition) { // See https://github.com/microsoft/vscode/issues/112621 // where compositionend is not triggered when the editor // is taken off-dom during a composition // Clear the flag to be able to write to the textarea this._currentComposition = null; // Clear the textarea to avoid an unwanted cursor type this.writeScreenReaderContent('blurWithoutCompositionEnd'); // Fire artificial composition end this._onCompositionEnd.fire(); } this._setHasFocus(false); })); this._register(this._textArea.onSyntheticTap(() => { if (this._browser.isAndroid && this._currentComposition) { // on Android, tapping does not cancel the current composition, so the // textarea is stuck showing the old composition // Clear the flag to be able to write to the textarea this._currentComposition = null; // Clear the textarea to avoid an unwanted cursor type this.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._currentComposition) { return; } if (!this._browser.isChrome) { // Support only for Chrome until testing happens on other browsers return; } const now = Date.now(); const delta1 = now - previousSelectionChangeEventTime; previousSelectionChangeEventTime = now; if (delta1 < 5) { // received another `selectionchange` event within 5ms of the previous `selectionchange` event // => ignore it return; } const delta2 = now - this._textArea.getIgnoreSelectionChangeTime(); this._textArea.resetSelectionChangeTime(); if (delta2 < 100) { // received a `selectionchange` event within 100ms since we touched the textarea // => ignore it, since we caused it return; } if (!this._textAreaState.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() { this._setHasFocus(this._textArea.hasFocus()); } _setHasFocus(newHasFocus) { if (this._hasFocus === newHasFocus) { // no change return; } this._hasFocus = newHasFocus; if (this._selectionChangeListener) { this._selectionChangeListener.dispose(); this._selectionChangeListener = null; } if (this._hasFocus) { this._selectionChangeListener = this._installSelectionChangeListener(); } if (this._hasFocus) { this.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._currentComposition) { // 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(); const storedMetadata = { version: 1, isFromEmptySelection: dataToCopy.isFromEmptySelection, multicursorText: dataToCopy.multicursorText, mode: dataToCopy.mode }; InMemoryClipboardMetadataManager.INSTANCE.set( // When writing "LINE\r\n" to the clipboard and then pasting, // Firefox pastes "LINE\n", so let's work around this quirk (this._browser.isFirefox ? dataToCopy.text.replace(/\r\n/g, '\n') : dataToCopy.text), storedMetadata); e.preventDefault(); if (e.clipboardData) { ClipboardEventUtils.setTextData(e.clipboardData, dataToCopy.text, dataToCopy.html, storedMetadata); } } } exports.TextAreaInput = TextAreaInput; class ClipboardEventUtils { static getTextData(clipboardData) { const text = clipboardData.getData(mime_1.Mimes.text); let metadata = null; const rawmetadata = clipboardData.getData('vscode-editor-data'); if (typeof rawmetadata === 'string') { try { metadata = JSON.parse(rawmetadata); if (metadata.version !== 1) { metadata = null; } } catch (err) { // no problem! } } return [text, metadata]; } static setTextData(clipboardData, text, html, metadata) { clipboardData.setData(mime_1.Mimes.text, text); if (typeof html === 'string') { clipboardData.setData('text/html', html); } clipboardData.setData('vscode-editor-data', JSON.stringify(metadata)); } } class TextAreaWrapper extends lifecycle_1.Disposable { constructor(_actual) { super(); this._actual = _actual; this.onKeyDown = this._register(dom.createEventEmitter(this._actual, 'keydown')).event; this.onKeyUp = this._register(dom.createEventEmitter(this._actual, 'keyup')).event; this.onCompositionStart = this._register(dom.createEventEmitter(this._actual, 'compositionstart')).event; this.onCompositionUpdate = this._register(dom.createEventEmitter(this._actual, 'compositionupdate')).event; this.onCompositionEnd = this._register(dom.createEventEmitter(this._actual, 'compositionend')).event; this.onInput = this._register(dom.createEventEmitter(this._actual, 'input')).event; this.onCut = this._register(dom.createEventEmitter(this._actual, 'cut')).event; this.onCopy = this._register(dom.createEventEmitter(this._actual, 'copy')).event; this.onPaste = this._register(dom.createEventEmitter(this._actual, 'paste')).event; this.onFocus = this._register(dom.createEventEmitter(this._actual, 'focus')).event; this.onBlur = this._register(dom.createEventEmitter(this._actual, 'blur')).event; this._onSyntheticTap = this._register(new event_1.Emitter()); this.onSyntheticTap = this._onSyntheticTap.event; this._ignoreSelectionChangeTime = 0; this._register(dom.addDisposableListener(this._actual, TextAreaSyntethicEvents.Tap, () => this._onSyntheticTap.fire())); } hasFocus() { const shadowRoot = dom.getShadowRoot(this._actual); if (shadowRoot) { return shadowRoot.activeElement === this._actual; } else if (dom.isInDOM(this._actual)) { return document.activeElement === this._actual; } else { return false; } } setIgnoreSelectionChangeTime(reason) { this._ignoreSelectionChangeTime = Date.now(); } getIgnoreSelectionChangeTime() { return this._ignoreSelectionChangeTime; } resetSelectionChangeTime() { this._ignoreSelectionChangeTime = 0; } getValue() { // console.log('current value: ' + this._textArea.value); return this._actual.value; } setValue(reason, value) { const textArea = this._actual; if (textArea.value === value) { // No change return; } // console.log('reason: ' + reason + ', current value: ' + textArea.value + ' => new value: ' + value); this.setIgnoreSelectionChangeTime('setValue'); textArea.value = value; } getSelectionStart() { return this._actual.selectionDirection === 'backward' ? this._actual.selectionEnd : this._actual.selectionStart; } getSelectionEnd() { return this._actual.selectionDirection === 'backward' ? this._actual.selectionStart : this._actual.selectionEnd; } setSelectionRange(reason, selectionStart, selectionEnd) { const textArea = this._actual; let activeElement = null; const shadowRoot = dom.getShadowRoot(textArea); if (shadowRoot) { activeElement = shadowRoot.activeElement; } else { activeElement = 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) } } } exports.TextAreaWrapper = TextAreaWrapper; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[98/*vs/editor/common/commands/replaceCommand*/], __M([1/*require*/,0/*exports*/,22/*vs/editor/common/core/selection*/]), function (require, exports, selection_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ReplaceCommandThatPreservesSelection = exports.ReplaceCommandWithOffsetCursorState = exports.ReplaceCommandWithoutChangingPosition = exports.ReplaceCommandThatSelectsText = exports.ReplaceCommand = void 0; class ReplaceCommand { constructor(range, text, insertsAutoWhitespace = false) { this._range = range; this._text = text; this.insertsAutoWhitespace = insertsAutoWhitespace; } getEditOperations(model, builder) { builder.addTrackedEditOperation(this._range, this._text); } computeCursorState(model, helper) { const inverseEditOperations = helper.getInverseEditOperations(); const srcRange = inverseEditOperations[0].range; return selection_1.Selection.fromPositions(srcRange.getEndPosition()); } } exports.ReplaceCommand = ReplaceCommand; class ReplaceCommandThatSelectsText { constructor(range, text) { this._range = range; this._text = text; } getEditOperations(model, builder) { builder.addTrackedEditOperation(this._range, this._text); } computeCursorState(model, helper) { const inverseEditOperations = helper.getInverseEditOperations(); const srcRange = inverseEditOperations[0].range; return selection_1.Selection.fromRange(srcRange, 0 /* LTR */); } } exports.ReplaceCommandThatSelectsText = ReplaceCommandThatSelectsText; class ReplaceCommandWithoutChangingPosition { constructor(range, text, insertsAutoWhitespace = false) { this._range = range; this._text = text; this.insertsAutoWhitespace = insertsAutoWhitespace; } getEditOperations(model, builder) { builder.addTrackedEditOperation(this._range, this._text); } computeCursorState(model, helper) { const inverseEditOperations = helper.getInverseEditOperations(); const srcRange = inverseEditOperations[0].range; return selection_1.Selection.fromPositions(srcRange.getStartPosition()); } } exports.ReplaceCommandWithoutChangingPosition = ReplaceCommandWithoutChangingPosition; class ReplaceCommandWithOffsetCursorState { constructor(range, text, lineNumberDeltaOffset, columnDeltaOffset, insertsAutoWhitespace = false) { this._range = range; this._text = text; this._columnDeltaOffset = columnDeltaOffset; this._lineNumberDeltaOffset = lineNumberDeltaOffset; this.insertsAutoWhitespace = insertsAutoWhitespace; } getEditOperations(model, builder) { builder.addTrackedEditOperation(this._range, this._text); } computeCursorState(model, helper) { const inverseEditOperations = helper.getInverseEditOperations(); const srcRange = inverseEditOperations[0].range; return selection_1.Selection.fromPositions(srcRange.getEndPosition().delta(this._lineNumberDeltaOffset, this._columnDeltaOffset)); } } exports.ReplaceCommandWithOffsetCursorState = ReplaceCommandWithOffsetCursorState; class ReplaceCommandThatPreservesSelection { constructor(editRange, text, initialSelection, forceMoveMarkers = false) { this._range = editRange; this._text = text; this._initialSelection = initialSelection; this._forceMoveMarkers = forceMoveMarkers; this._selectionId = null; } getEditOperations(model, builder) { builder.addTrackedEditOperation(this._range, this._text, this._forceMoveMarkers); this._selectionId = builder.trackSelection(this._initialSelection); } computeCursorState(model, helper) { return helper.getTrackedSelection(this._selectionId); } } exports.ReplaceCommandThatPreservesSelection = ReplaceCommandThatPreservesSelection; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[403/*vs/editor/common/commands/surroundSelectionCommand*/], __M([1/*require*/,0/*exports*/,3/*vs/editor/common/core/range*/,22/*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) { const inverseEditOperations = helper.getInverseEditOperations(); const firstOperationRange = inverseEditOperations[0].range; const secondOperationRange = inverseEditOperations[1].range; return new selection_1.Selection(firstOperationRange.endLineNumber, firstOperationRange.endColumn, secondOperationRange.endLineNumber, secondOperationRange.endColumn - this._charAfterSelection.length); } } exports.SurroundSelectionCommand = SurroundSelectionCommand; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[90/*vs/editor/common/core/stringBuilder*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,17/*vs/base/common/platform*/,110/*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) { const result = []; let resultLen = 0; for (let i = 0; i < len; i++) { const charCode = buffer.readUInt16LE(source, offset); offset += 2; result[resultLen++] = String.fromCharCode(charCode); } return result.join(''); } class StringBuilder { constructor(capacity) { this._capacity = capacity | 0; this._buffer = new Uint16Array(this._capacity); this._completedStrings = null; this._bufferLength = 0; } reset() { this._completedStrings = null; this._bufferLength = 0; } build() { if (this._completedStrings !== null) { this._flushBuffer(); return this._completedStrings.join(''); } return this._buildBuffer(); } _buildBuffer() { if (this._bufferLength === 0) { return ''; } const view = new Uint16Array(this._buffer.buffer, 0, this._bufferLength); return getPlatformTextDecoder().decode(view); } _flushBuffer() { const bufferString = this._buildBuffer(); this._bufferLength = 0; if (this._completedStrings === null) { this._completedStrings = [bufferString]; } else { this._completedStrings[this._completedStrings.length] = bufferString; } } 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[176/*vs/editor/browser/view/viewLayer*/], __M([1/*require*/,0/*exports*/,30/*vs/base/browser/fastDomNode*/,90/*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(131 /* 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[237/*vs/editor/common/core/textChange*/], __M([1/*require*/,0/*exports*/,110/*vs/base/common/buffer*/,90/*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; } const result = []; let resultLen = 0; let prev = edits[0]; for (let i = 1; i < edits.length; i++) { const curr = edits[i]; if (prev.oldEnd === curr.oldPosition) { // Merge into `prev` prev = new TextChange(prev.oldPosition, prev.oldText + curr.oldText, prev.newPosition, prev.newText + curr.newText); } else { result[resultLen++] = prev; prev = curr; } } result[resultLen++] = prev; return result; } static _removeNoOps(edits) { if (edits.length === 0) { return edits; } const result = []; let resultLen = 0; for (let i = 0; i < edits.length; i++) { const edit = edits[i]; if (edit.oldText === edit.newText) { continue; } result[resultLen++] = edit; } return result; } } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[145/*vs/editor/common/core/textModelDefaults*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EDITOR_MODEL_DEFAULTS = void 0; exports.EDITOR_MODEL_DEFAULTS = { tabSize: 4, indentSize: 4, insertSpaces: true, detectIndentation: true, trimAutoWhitespace: true, largeFileOptimizations: true, bracketPairColorizationOptions: { enabled: 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[118/*vs/editor/common/core/wordCharacterClassifier*/], __M([1/*require*/,0/*exports*/,97/*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) { const 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[146/*vs/editor/common/core/wordHelper*/], __M([1/*require*/,0/*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) { const result = { word: match[0], startColumn: textOffset + 1 + match.index, endColumn: textOffset + 1 + match.index + match[0].length }; wordDefinition.lastIndex = 0; return result; } return null; } 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[238/*vs/editor/common/cursor/cursorAtomicMoveOperations*/], __M([1/*require*/,0/*exports*/,68/*vs/editor/common/core/cursorColumns*/]), function (require, exports, cursorColumns_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AtomicTabMoveOperations = void 0; class AtomicTabMoveOperations { /** * Get the visible column at the position. If we get to a non-whitespace character first * or past the end of string then return -1. * * **Note** `position` and the return value are 0-based. */ static whitespaceVisibleColumn(lineContent, position, tabSize) { const lineLength = lineContent.length; let visibleColumn = 0; let prevTabStopPosition = -1; let prevTabStopVisibleColumn = -1; for (let i = 0; i < lineLength; i++) { if (i === position) { return [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn]; } if (visibleColumn % tabSize === 0) { prevTabStopPosition = i; prevTabStopVisibleColumn = visibleColumn; } const chCode = lineContent.charCodeAt(i); switch (chCode) { case 32 /* Space */: visibleColumn += 1; break; case 9 /* Tab */: // Skip to the next multiple of tabSize. visibleColumn = cursorColumns_1.CursorColumns.nextRenderTabStop(visibleColumn, tabSize); break; default: return [-1, -1, -1]; } } if (position === lineLength) { return [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn]; } return [-1, -1, -1]; } /** * Return the position that should result from a move left, right or to the * nearest tab, if atomic tabs are enabled. Left and right are used for the * arrow key movements, nearest is used for mouse selection. It returns * -1 if atomic tabs are not relevant and you should fall back to normal * behaviour. * * **Note**: `position` and the return value are 0-based. */ static atomicPosition(lineContent, position, tabSize, direction) { const lineLength = lineContent.length; // Get the 0-based visible column corresponding to the position, or return // -1 if it is not in the initial whitespace. const [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn] = AtomicTabMoveOperations.whitespaceVisibleColumn(lineContent, position, tabSize); if (visibleColumn === -1) { return -1; } // Is the output left or right of the current position. The case for nearest // where it is the same as the current position is handled in the switch. let left; switch (direction) { case 0 /* 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 = cursorColumns_1.CursorColumns.nextRenderTabStop(currentVisibleColumn, tabSize); break; default: return -1; } } if (currentVisibleColumn === prevTabStopVisibleColumn + tabSize) { return prevTabStopPosition; } // It must have been a partial indentation. return -1; } // We are going right. const targetVisibleColumn = cursorColumns_1.CursorColumns.nextRenderTabStop(visibleColumn, tabSize); // We can just continue from where whitespaceVisibleColumn got to. let currentVisibleColumn = visibleColumn; for (let i = position; i < lineLength; i++) { if (currentVisibleColumn === targetVisibleColumn) { return i; } const chCode = lineContent.charCodeAt(i); switch (chCode) { case 32 /* Space */: currentVisibleColumn += 1; break; case 9 /* Tab */: currentVisibleColumn = cursorColumns_1.CursorColumns.nextRenderTabStop(currentVisibleColumn, tabSize); break; default: return -1; } } // This condition handles when the target column is at the end of the line. if (currentVisibleColumn === targetVisibleColumn) { return lineLength; } return -1; } } exports.AtomicTabMoveOperations = AtomicTabMoveOperations; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[404/*vs/editor/common/diff/diffComputer*/], __M([1/*require*/,0/*exports*/,138/*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[239/*vs/editor/common/editorAction*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.InternalEditorAction = void 0; class InternalEditorAction { constructor(id, label, alias, 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[147/*vs/editor/common/editorCommon*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EditorType = void 0; /** * The type of the `IEditor`. */ exports.EditorType = { ICodeEditor: 'vs.editor.ICodeEditor', IDiffEditor: 'vs.editor.IDiffEditor' }; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[148/*vs/editor/browser/editorBrowser*/], __M([1/*require*/,0/*exports*/,147/*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; }); /*--------------------------------------------------------------------------------------------- * 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/languageSelector*/], __M([1/*require*/,0/*exports*/,215/*vs/base/common/glob*/,82/*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[119/*vs/editor/common/languages/languageConfiguration*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AutoClosingPairs = exports.StandardAutoClosingPairConditional = exports.IndentAction = void 0; /** * Describes what to do with the indentation when pressing Enter. */ var IndentAction; (function (IndentAction) { /** * Insert new line and copy the previous line's indentation. */ IndentAction[IndentAction["None"] = 0] = "None"; /** * Insert new line and indent once (relative to the previous line's indentation). */ IndentAction[IndentAction["Indent"] = 1] = "Indent"; /** * Insert two new lines: * - the first one indented which will hold the cursor * - the second one at the same indentation level */ IndentAction[IndentAction["IndentOutdent"] = 2] = "IndentOutdent"; /** * Insert new line and outdent once (relative to the previous line's indentation). */ IndentAction[IndentAction["Outdent"] = 3] = "Outdent"; })(IndentAction = exports.IndentAction || (exports.IndentAction = {})); /** * @internal */ class StandardAutoClosingPairConditional { constructor(source) { this._neutralCharacter = null; this._neutralCharacterSearched = false; this.open = source.open; this.close = source.close; // initially allowed in all tokens this._inString = true; this._inComment = true; this._inRegEx = true; if (Array.isArray(source.notIn)) { for (let i = 0, len = source.notIn.length; i < len; i++) { const notIn = source.notIn[i]; switch (notIn) { case 'string': this._inString = false; break; case 'comment': this._inComment = false; break; case 'regex': this._inRegEx = false; break; } } } } isOK(standardToken) { switch (standardToken) { case 0 /* Other */: return true; case 1 /* Comment */: return this._inComment; case 2 /* String */: return this._inString; case 3 /* RegEx */: return this._inRegEx; } } shouldAutoClose(context, column) { // Always complete on empty line if (context.getTokenCount() === 0) { return true; } const tokenIndex = context.findTokenIndexAtOffset(column - 2); const standardTokenType = context.getStandardTokenType(tokenIndex); return this.isOK(standardTokenType); } _findNeutralCharacterInRange(fromCharCode, toCharCode) { for (let charCode = fromCharCode; charCode <= toCharCode; charCode++) { const character = String.fromCharCode(charCode); if (!this.open.includes(character) && !this.close.includes(character)) { return character; } } return null; } /** * Find a character in the range [0-9a-zA-Z] that does not appear in the open or close */ findNeutralCharacter() { if (!this._neutralCharacterSearched) { this._neutralCharacterSearched = true; if (!this._neutralCharacter) { this._neutralCharacter = this._findNeutralCharacterInRange(48 /* Digit0 */, 57 /* Digit9 */); } if (!this._neutralCharacter) { this._neutralCharacter = this._findNeutralCharacterInRange(97 /* a */, 122 /* z */); } if (!this._neutralCharacter) { this._neutralCharacter = this._findNeutralCharacterInRange(65 /* A */, 90 /* Z */); } } return this._neutralCharacter; } } exports.StandardAutoClosingPairConditional = StandardAutoClosingPairConditional; /** * @internal */ class AutoClosingPairs { constructor(autoClosingPairs) { this.autoClosingPairsOpenByStart = new Map(); this.autoClosingPairsOpenByEnd = new Map(); this.autoClosingPairsCloseByStart = new Map(); this.autoClosingPairsCloseByEnd = new Map(); this.autoClosingPairsCloseSingleChar = new Map(); for (const pair of autoClosingPairs) { appendEntry(this.autoClosingPairsOpenByStart, pair.open.charAt(0), pair); appendEntry(this.autoClosingPairsOpenByEnd, pair.open.charAt(pair.open.length - 1), pair); appendEntry(this.autoClosingPairsCloseByStart, pair.close.charAt(0), pair); appendEntry(this.autoClosingPairsCloseByEnd, pair.close.charAt(pair.close.length - 1), pair); if (pair.close.length === 1 && pair.open.length === 1) { appendEntry(this.autoClosingPairsCloseSingleChar, pair.close, pair); } } } } exports.AutoClosingPairs = AutoClosingPairs; function appendEntry(target, key, value) { if (target.has(key)) { target.get(key).push(value); } else { target.set(key, [value]); } } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[406/*vs/editor/common/languages/linkComputer*/], __M([1/*require*/,0/*exports*/,97/*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++) { const [from, chCode, to] = edges[i]; if (chCode > maxCharCode) { maxCharCode = chCode; } if (from > maxState) { maxState = from; } if (to > maxState) { maxState = to; } } maxCharCode++; maxState++; const states = new Uint8Matrix(maxState, maxCharCode, 0 /* Invalid */); for (let i = 0, len = edges.length; i < len; i++) { const [from, chCode, to] = edges[i]; states.set(from, chCode, to); } this._states = states; this._maxCharCode = maxCharCode; } nextState(currentState, chCode) { if (chCode < 0 || chCode >= this._maxCharCode) { return 0 /* 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 */); // allow-any-unicode-next-line const FORCE_TERMINATION_CHARACTERS = ' \t<>\'\"、。。、,.:;‘〈「『〔([{「」}])〕』」〉’`~…'; for (let i = 0; i < FORCE_TERMINATION_CHARACTERS.length; i++) { _classifier.set(FORCE_TERMINATION_CHARACTERS.charCodeAt(i), 1 /* 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(); const result = []; for (let i = 1, lineCount = model.getLineCount(); i <= lineCount; i++) { const line = model.getLineContent(i); const len = line.length; let j = 0; let linkBeginIndex = 0; let linkBeginChCode = 0; let state = 1 /* 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[120/*vs/editor/common/languages/supports*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ignoreBracketsInToken = exports.ScopedLineTokens = exports.createScopedLineTokens = void 0; function createScopedLineTokens(context, offset) { const tokenCount = context.getCount(); const tokenIndex = context.findTokenIndexAtOffset(offset); const desiredLanguageId = context.getLanguageId(tokenIndex); let lastTokenIndex = tokenIndex; while (lastTokenIndex + 1 < tokenCount && context.getLanguageId(lastTokenIndex + 1) === desiredLanguageId) { lastTokenIndex++; } let firstTokenIndex = tokenIndex; while (firstTokenIndex > 0 && context.getLanguageId(firstTokenIndex - 1) === desiredLanguageId) { firstTokenIndex--; } return new ScopedLineTokens(context, desiredLanguageId, firstTokenIndex, lastTokenIndex + 1, context.getStartOffset(firstTokenIndex), context.getEndOffset(lastTokenIndex)); } 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 & 3 /* 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[407/*vs/editor/common/languages/supports/characterPair*/], __M([1/*require*/,0/*exports*/,119/*vs/editor/common/languages/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.colorizedBracketPairs) { this._colorizedBracketPairs = filterValidBrackets(config.colorizedBracketPairs.map(b => [b[0], b[1]])); } else if (config.brackets) { this._colorizedBracketPairs = filterValidBrackets(config.brackets .map((b) => [b[0], b[1]]) // Many languages set < ... > as bracket pair, even though they also use it as comparison operator. // This leads to problems when colorizing this bracket, so we exclude it by default. // Languages can still override this by configuring `colorizedBracketPairs` // https://github.com/microsoft/vscode/issues/132476 .filter((p) => !(p[0] === '<' && p[1] === '>'))); } else { this._colorizedBracketPairs = []; } 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; } getSurroundingPairs() { return this._surroundingPairs; } getColorizedBrackets() { return this._colorizedBracketPairs; } } exports.CharacterPairSupport = CharacterPairSupport; CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED = ';:.,=}])> \n\t'; function filterValidBrackets(bracketPairs) { return bracketPairs.filter(([open, close]) => open !== '' && close !== ''); } }); /*--------------------------------------------------------------------------------------------- * 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/common/languages/supports/indentRules*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IndentRulesSupport = void 0; function resetGlobalRegex(reg) { if (reg.global) { reg.lastIndex = 0; } return true; } class IndentRulesSupport { constructor(indentationRules) { this._indentationRules = indentationRules; } shouldIncrease(text) { if (this._indentationRules) { if (this._indentationRules.increaseIndentPattern && resetGlobalRegex(this._indentationRules.increaseIndentPattern) && this._indentationRules.increaseIndentPattern.test(text)) { return true; } // if (this._indentationRules.indentNextLinePattern && this._indentationRules.indentNextLinePattern.test(text)) { // return true; // } } return false; } shouldDecrease(text) { if (this._indentationRules && this._indentationRules.decreaseIndentPattern && resetGlobalRegex(this._indentationRules.decreaseIndentPattern) && this._indentationRules.decreaseIndentPattern.test(text)) { return true; } return false; } shouldIndentNextLine(text) { if (this._indentationRules && this._indentationRules.indentNextLinePattern && resetGlobalRegex(this._indentationRules.indentNextLinePattern) && this._indentationRules.indentNextLinePattern.test(text)) { return true; } return false; } shouldIgnore(text) { // the text matches `unIndentedLinePattern` if (this._indentationRules && this._indentationRules.unIndentedLinePattern && resetGlobalRegex(this._indentationRules.unIndentedLinePattern) && this._indentationRules.unIndentedLinePattern.test(text)) { return true; } return false; } getIndentMetadata(text) { let ret = 0; if (this.shouldIncrease(text)) { ret += 1 /* 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[409/*vs/editor/common/languages/supports/inplaceReplaceSupport*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BasicInplaceReplace = void 0; class BasicInplaceReplace { constructor() { this._defaultValueSet = [ ['true', 'false'], ['True', 'False'], ['Private', 'Public', 'Friend', 'ReadOnly', 'Partial', 'Protected', 'WriteOnly'], ['public', 'protected', 'private'], ]; } navigateValueSet(range1, text1, range2, text2, up) { if (range1 && text1) { const result = this.doNavigateValueSet(text1, up); if (result) { return { range: range1, value: result }; } } if (range2 && text2) { const result = this.doNavigateValueSet(text2, up); if (result) { return { range: range2, value: result }; } } return null; } doNavigateValueSet(text, up) { const numberResult = this.numberReplace(text, up); if (numberResult !== null) { return numberResult; } return this.textReplace(text, up); } numberReplace(value, up) { const precision = Math.pow(10, value.length - (value.lastIndexOf('.') + 1)); let n1 = Number(value); 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[410/*vs/editor/common/languages/supports/onEnter*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/errors*/,8/*vs/base/common/strings*/,119/*vs/editor/common/languages/languageConfiguration*/]), function (require, exports, errors_1, strings, languageConfiguration_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OnEnterSupport = void 0; class OnEnterSupport { constructor(opts) { opts = opts || {}; opts.brackets = opts.brackets || [ ['(', ')'], ['{', '}'], ['[', ']'] ]; this._brackets = []; opts.brackets.forEach((bracket) => { const openRegExp = OnEnterSupport._createOpenBracketRegExp(bracket[0]); const closeRegExp = OnEnterSupport._createCloseBracketRegExp(bracket[1]); if (openRegExp && closeRegExp) { this._brackets.push({ open: bracket[0], openRegExp: openRegExp, close: bracket[1], closeRegExp: closeRegExp, }); } }); this._regExpRules = opts.onEnterRules || []; } onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText) { // (1): `regExpRules` if (autoIndent >= 3 /* Advanced */) { for (let i = 0, len = this._regExpRules.length; i < len; i++) { const rule = this._regExpRules[i]; const regResult = [{ reg: rule.beforeText, text: beforeEnterText }, { reg: rule.afterText, text: afterEnterText }, { reg: rule.previousLineText, text: previousLineText }].every((obj) => { if (!obj.reg) { return true; } obj.reg.lastIndex = 0; // To disable the effect of the "g" flag. return obj.reg.test(obj.text); }); if (regResult) { return rule.action; } } } // (2): Special indent-outdent if (autoIndent >= 2 /* Brackets */) { if (beforeEnterText.length > 0 && afterEnterText.length > 0) { for (let i = 0, len = this._brackets.length; i < len; i++) { const bracket = this._brackets[i]; if (bracket.openRegExp.test(beforeEnterText) && bracket.closeRegExp.test(afterEnterText)) { return { indentAction: languageConfiguration_1.IndentAction.IndentOutdent }; } } } } // (4): Open bracket based logic if (autoIndent >= 2 /* Brackets */) { if (beforeEnterText.length > 0) { for (let i = 0, len = this._brackets.length; i < len; i++) { const bracket = this._brackets[i]; if (bracket.openRegExp.test(beforeEnterText)) { return { indentAction: languageConfiguration_1.IndentAction.Indent }; } } } } return null; } static _createOpenBracketRegExp(bracket) { let str = strings.escapeRegExpCharacters(bracket); if (!/\B/.test(str.charAt(0))) { str = '\\b' + str; } str += '\\s*$'; return OnEnterSupport._safeRegExp(str); } static _createCloseBracketRegExp(bracket) { let str = strings.escapeRegExpCharacters(bracket); if (!/\B/.test(str.charAt(str.length - 1))) { str = str + '\\b'; } str = '^\\s*' + str; return OnEnterSupport._safeRegExp(str); } static _safeRegExp(def) { try { return new RegExp(def); } catch (err) { (0, errors_1.onUnexpectedError)(err); return null; } } } exports.OnEnterSupport = OnEnterSupport; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[177/*vs/editor/common/languages/supports/richEditBrackets*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,90/*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; /** * Represents a grouping of colliding bracket pairs. * * Most of the times this contains a single bracket pair, * but sometimes this contains multiple bracket pairs in cases * where the same string appears as a closing bracket for multiple * bracket pairs, or the same string appears an opening bracket for * multiple bracket pairs. * * e.g. of a group containing a single pair: * open: ['{'], close: ['}'] * * e.g. of a group containing multiple pairs: * open: ['if', 'for'], close: ['end', 'end'] */ class RichEditBracket { constructor(languageId, index, open, close, forwardRegex, reversedRegex) { this._richEditBracketBrand = undefined; this.languageId = languageId; this.index = index; this.open = open; this.close = close; this.forwardRegex = forwardRegex; this.reversedRegex = reversedRegex; this._openSet = RichEditBracket._toSet(this.open); this._closeSet = RichEditBracket._toSet(this.close); } /** * Check if the provided `text` is an open bracket in this group. */ isOpen(text) { return this._openSet.has(text); } /** * Check if the provided `text` is a close bracket in this group. */ isClose(text) { return this._closeSet.has(text); } static _toSet(arr) { const result = new Set(); for (const element of arr) { result.add(element); } return result; } } exports.RichEditBracket = RichEditBracket; /** * Groups together brackets that have equal open or close sequences. * * For example, if the following brackets are defined: * ['IF','END'] * ['for','end'] * ['{','}'] * * Then the grouped brackets would be: * { open: ['if', 'for'], close: ['end', 'end'] } * { open: ['{'], close: ['}'] } * */ function groupFuzzyBrackets(brackets) { const N = brackets.length; brackets = brackets.map(b => [b[0].toLowerCase(), b[1].toLowerCase()]); const group = []; for (let i = 0; i < N; i++) { group[i] = i; } const areOverlapping = (a, b) => { const [aOpen, aClose] = a; const [bOpen, bClose] = b; return (aOpen === bOpen || aOpen === bClose || aClose === bOpen || aClose === bClose); }; const mergeGroups = (g1, g2) => { const newG = Math.min(g1, g2); const oldG = Math.max(g1, g2); for (let i = 0; i < N; i++) { if (group[i] === oldG) { group[i] = newG; } } }; // group together brackets that have the same open or the same close sequence for (let i = 0; i < N; i++) { const a = brackets[i]; for (let j = i + 1; j < N; j++) { const b = brackets[j]; if (areOverlapping(a, b)) { mergeGroups(group[i], group[j]); } } } const result = []; for (let g = 0; g < N; g++) { const currentOpen = []; const currentClose = []; for (let i = 0; i < N; i++) { if (group[i] === g) { const [open, close] = brackets[i]; currentOpen.push(open); currentClose.push(close); } } if (currentOpen.length > 0) { result.push({ open: currentOpen, close: currentClose }); } } return result; } class RichEditBrackets { constructor(languageId, _brackets) { this._richEditBracketsBrand = undefined; const brackets = groupFuzzyBrackets(_brackets); this.brackets = brackets.map((b, index) => { return new RichEditBracket(languageId, index, b.open, b.close, getRegexForBracketPair(b.open, b.close, brackets, index), getReversedRegexForBracketPair(b.open, b.close, brackets, index)); }); this.forwardRegex = getRegexForBrackets(this.brackets); this.reversedRegex = getReversedRegexForBrackets(this.brackets); this.textIsBracket = {}; this.textIsOpenBracket = {}; this.maxBracketLength = 0; for (const bracket of this.brackets) { for (const open of bracket.open) { this.textIsBracket[open] = bracket; this.textIsOpenBracket[open] = true; this.maxBracketLength = Math.max(this.maxBracketLength, open.length); } for (const close of bracket.close) { this.textIsBracket[close] = bracket; this.textIsOpenBracket[close] = false; this.maxBracketLength = Math.max(this.maxBracketLength, close.length); } } } } exports.RichEditBrackets = RichEditBrackets; function collectSuperstrings(str, brackets, currentIndex, dest) { for (let i = 0, len = brackets.length; i < len; i++) { if (i === currentIndex) { continue; } const bracket = brackets[i]; for (const open of bracket.open) { if (open.indexOf(str) >= 0) { dest.push(open); } } for (const close of bracket.close) { if (close.indexOf(str) >= 0) { dest.push(close); } } } } function lengthcmp(a, b) { return a.length - b.length; } function unique(arr) { if (arr.length <= 1) { return arr; } const result = []; const seen = new Set(); for (const element of arr) { if (seen.has(element)) { continue; } result.push(element); seen.add(element); } return result; } /** * Create a regular expression that can be used to search forward in a piece of text * for a group of bracket pairs. But this regex must be built in a way in which * it is aware of the other bracket pairs defined for the language. * * For example, if a language contains the following bracket pairs: * ['begin', 'end'] * ['if', 'end if'] * The two bracket pairs do not collide because no open or close brackets are equal. * So the function getRegexForBracketPair is called twice, once with * the ['begin'], ['end'] group consisting of one bracket pair, and once with * the ['if'], ['end if'] group consiting of the other bracket pair. * * But there could be a situation where an occurrence of 'end if' is mistaken * for an occurrence of 'end'. * * Therefore, for the bracket pair ['begin', 'end'], the regex will also * target 'end if'. The regex will be something like: * /(\bend if\b)|(\bend\b)|(\bif\b)/ * * The regex also searches for "superstrings" (other brackets that might be mistaken with the current bracket). * */ function getRegexForBracketPair(open, close, brackets, currentIndex) { // search in all brackets for other brackets that are a superstring of these brackets let pieces = []; pieces = pieces.concat(open); pieces = pieces.concat(close); for (let i = 0, len = pieces.length; i < len; i++) { collectSuperstrings(pieces[i], brackets, currentIndex, pieces); } pieces = unique(pieces); pieces.sort(lengthcmp); pieces.reverse(); return createBracketOrRegExp(pieces); } /** * Matching a regular expression in JS can only be done "forwards". So JS offers natively only * methods to find the first match of a regex in a string. But sometimes, it is useful to * find the last match of a regex in a string. For such a situation, a nice solution is to * simply reverse the string and then search for a reversed regex. * * This function also has the fine details of `getRegexForBracketPair`. For the same example * given above, the regex produced here would look like: * /(\bfi dne\b)|(\bdne\b)|(\bfi\b)/ */ function getReversedRegexForBracketPair(open, close, brackets, currentIndex) { // search in all brackets for other brackets that are a superstring of these brackets let pieces = []; pieces = pieces.concat(open); pieces = pieces.concat(close); for (let i = 0, len = pieces.length; i < len; i++) { collectSuperstrings(pieces[i], brackets, currentIndex, pieces); } pieces = unique(pieces); pieces.sort(lengthcmp); pieces.reverse(); return createBracketOrRegExp(pieces.map(toReversedString)); } /** * Creates a regular expression that targets all bracket pairs. * * e.g. for the bracket pairs: * ['{','}'] * ['begin,'end'] * ['for','end'] * the regex would look like: * /(\{)|(\})|(\bbegin\b)|(\bend\b)|(\bfor\b)/ */ function getRegexForBrackets(brackets) { let pieces = []; for (const bracket of brackets) { for (const open of bracket.open) { pieces.push(open); } for (const close of bracket.close) { pieces.push(close); } } pieces = unique(pieces); return createBracketOrRegExp(pieces); } /** * Matching a regular expression in JS can only be done "forwards". So JS offers natively only * methods to find the first match of a regex in a string. But sometimes, it is useful to * find the last match of a regex in a string. For such a situation, a nice solution is to * simply reverse the string and then search for a reversed regex. * * e.g. for the bracket pairs: * ['{','}'] * ['begin,'end'] * ['for','end'] * the regex would look like: * /(\{)|(\})|(\bnigeb\b)|(\bdne\b)|(\brof\b)/ */ function getReversedRegexForBrackets(brackets) { let pieces = []; for (const bracket of brackets) { for (const open of bracket.open) { pieces.push(open); } for (const close of bracket.close) { pieces.push(close); } } pieces = unique(pieces); return createBracketOrRegExp(pieces.map(toReversedString)); } function prepareBracketForRegExp(str) { // This bracket pair uses letters like e.g. "begin" - "end" const insertWordBoundaries = (/^[\w ]+$/.test(str)); str = strings.escapeRegExpCharacters(str); return (insertWordBoundaries ? `\\b${str}\\b` : str); } function createBracketOrRegExp(pieces) { const 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 { const result = []; let 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) { const m = reversedText.match(reversedBracketRegex); if (!m) { return null; } const matchOffset = reversedText.length - (m.index || 0); const matchLength = m[0].length; const absoluteMatchOffset = offset + matchOffset; return new range_1.Range(lineNumber, absoluteMatchOffset - matchLength + 1, lineNumber, absoluteMatchOffset + 1); } static findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, startOffset, endOffset) { // Because JS does not support backwards regex search, we search forwards in a reversed string with a reversed regex ;) const reversedLineText = toReversedString(lineText); const reversedSubstr = reversedLineText.substring(lineText.length - endOffset, lineText.length - startOffset); return this._findPrevBracketInText(reversedBracketRegex, lineNumber, reversedSubstr, startOffset); } static findNextBracketInText(bracketRegex, lineNumber, text, offset) { const m = text.match(bracketRegex); if (!m) { return null; } const matchOffset = m.index || 0; const matchLength = m[0].length; if (matchLength === 0) { return null; } const absoluteMatchOffset = offset + matchOffset; return new range_1.Range(lineNumber, absoluteMatchOffset + 1, lineNumber, absoluteMatchOffset + 1 + matchLength); } static findNextBracketInRange(bracketRegex, lineNumber, lineText, startOffset, endOffset) { const substr = lineText.substring(startOffset, endOffset); return this.findNextBracketInText(bracketRegex, lineNumber, substr, startOffset); } } exports.BracketsUtils = BracketsUtils; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[411/*vs/editor/common/languages/supports/electricCharacter*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,120/*vs/editor/common/languages/supports*/,177/*vs/editor/common/languages/supports/richEditBrackets*/]), function (require, exports, arrays_1, supports_1, richEditBrackets_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BracketElectricCharacterSupport = void 0; class BracketElectricCharacterSupport { constructor(richEditBrackets) { this._richEditBrackets = richEditBrackets; } getElectricCharacters() { const result = []; if (this._richEditBrackets) { for (const bracket of this._richEditBrackets.brackets) { for (const close of bracket.close) { const lastChar = close.charAt(close.length - 1); result.push(lastChar); } } } return (0, arrays_1.distinct)(result); } onElectricCharacter(character, context, column) { if (!this._richEditBrackets || this._richEditBrackets.brackets.length === 0) { return null; } const tokenIndex = context.findTokenIndexAtOffset(column - 1); if ((0, supports_1.ignoreBracketsInToken)(context.getStandardTokenType(tokenIndex))) { return null; } const reversedBracketRegex = this._richEditBrackets.reversedRegex; const text = context.getLineContent().substring(0, column - 1) + character; const r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(reversedBracketRegex, 1, text, 0, text.length); if (!r) { return null; } const bracketText = text.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase(); const isOpen = this._richEditBrackets.textIsOpenBracket[bracketText]; if (isOpen) { return null; } const textBeforeBracket = context.getActualLineContentBefore(r.startColumn - 1); if (!/^\s*$/.test(textBeforeBracket)) { // There is other text on the line before the bracket return null; } return { matchOpenBracket: bracketText }; } } exports.BracketElectricCharacterSupport = BracketElectricCharacterSupport; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[412/*vs/editor/common/languages/supports/tokenization*/], __M([1/*require*/,0/*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 []; } const result = []; let resultLen = 0; for (let i = 0, len = source.length; i < len; i++) { const entry = source[i]; let fontStyle = -1 /* NotSet */; if (typeof entry.fontStyle === 'string') { fontStyle = 0 /* None */; const segments = entry.fontStyle.split(' '); for (let j = 0, lenJ = segments.length; j < lenJ; j++) { const segment = segments[j]; switch (segment) { case 'italic': fontStyle = fontStyle | 1 /* Italic */; break; case 'bold': fontStyle = fontStyle | 2 /* Bold */; break; case 'underline': fontStyle = fontStyle | 4 /* Underline */; break; case 'strikethrough': fontStyle = fontStyle | 8 /* Strikethrough */; break; } } } let foreground = null; if (typeof entry.foreground === 'string') { foreground = entry.foreground; } let background = null; if (typeof entry.background === 'string') { background = entry.background; } result[resultLen++] = new ParsedTokenThemeRule(entry.token || '', i, fontStyle, foreground, background); } return result; } 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) => { const 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 === '') { const 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; } } const colorMap = new ColorMap(); // start with token colors from custom token themes for (let color of customTokenColors) { colorMap.getId(color); } const foregroundColorId = colorMap.getId(defaultForeground); const backgroundColorId = colorMap.getId(defaultBackground); const defaults = new ThemeTrieElementRule(defaultFontStyle, foregroundColorId, backgroundColorId); const root = new ThemeTrieElement(defaults); for (let i = 0, len = parsedThemeRules.length; i < len; i++) { const rule = parsedThemeRules[i]; root.insert(rule.token, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background)); } return new TokenTheme(colorMap, root); } const colorRegExp = /^#?([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?$/; class ColorMap { constructor() { this._lastColorId = 0; this._id2color = []; this._color2id = new Map(); } getId(color) { if (color === null) { return 0; } const match = color.match(colorRegExp); if (!match) { throw new Error('Illegal value for token color: ' + color); } color = match[1].toUpperCase(); let value = this._color2id.get(color); if (value) { return value; } value = ++this._lastColorId; this._color2id.set(color, value); this._id2color[value] = color_1.Color.fromHex('#' + color); return value; } getColorMap() { return this._id2color.slice(0); } } exports.ColorMap = ColorMap; class TokenTheme { 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') { const rule = this._match(token); const 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) { const 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 3 /* RegEx */; case 'regexp': return 3 /* 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 << 10 /* 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 << 10 /* 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; } const dotIndex = token.indexOf('.'); let head; let tail; if (dotIndex === -1) { head = token; tail = ''; } else { head = token.substring(0, dotIndex); tail = token.substring(dotIndex + 1); } const child = this._children.get(head); if (typeof child !== 'undefined') { return child.match(tail); } return this._mainRule; } insert(token, fontStyle, foreground, background) { if (token === '') { // Merge into the main rule this._mainRule.acceptOverwrite(fontStyle, foreground, background); return; } const dotIndex = token.indexOf('.'); let head; let tail; if (dotIndex === -1) { head = token; tail = ''; } else { head = token.substring(0, dotIndex); tail = token.substring(dotIndex + 1); } let child = this._children.get(head); if (typeof child === 'undefined') { child = new ThemeTrieElement(this._mainRule.clone()); this._children.set(head, child); } child.insert(tail, fontStyle, foreground, background); } } exports.ThemeTrieElement = ThemeTrieElement; function generateTokensCSSForColorMap(colorMap) { const rules = []; for (let i = 1, len = colorMap.length; i < len; i++) { const color = colorMap[i]; rules[i] = `.mtk${i} { color: ${color}; }`; } rules.push('.mtki { font-style: italic; }'); rules.push('.mtkb { font-weight: bold; }'); rules.push('.mtku { text-decoration: underline; text-underline-position: under; }'); rules.push('.mtks { text-decoration: line-through; }'); rules.push('.mtks.mtku { text-decoration: underline line-through; text-underline-position: under; }'); return rules.join('\n'); } 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[49/*vs/editor/common/model*/], __M([1/*require*/,0/*exports*/,39/*vs/base/common/objects*/]), function (require, exports, objects_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.shouldSynchronizeModel = exports.ApplyEditsResult = exports.SearchData = exports.ValidAnnotatedEditOperation = exports.FindMatch = exports.TextModelResolvedOptions = exports.InjectedTextCursorStops = 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 = {})); var InjectedTextCursorStops; (function (InjectedTextCursorStops) { InjectedTextCursorStops[InjectedTextCursorStops["Both"] = 0] = "Both"; InjectedTextCursorStops[InjectedTextCursorStops["Right"] = 1] = "Right"; InjectedTextCursorStops[InjectedTextCursorStops["Left"] = 2] = "Left"; InjectedTextCursorStops[InjectedTextCursorStops["None"] = 3] = "None"; })(InjectedTextCursorStops = exports.InjectedTextCursorStops || (exports.InjectedTextCursorStops = {})); 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); this.bracketPairColorizationOptions = src.bracketPairColorizationOptions; } /** * @internal */ equals(other) { return (this.tabSize === other.tabSize && this.indentSize === other.indentSize && this.insertSpaces === other.insertSpaces && this.defaultEOL === other.defaultEOL && this.trimAutoWhitespace === other.trimAutoWhitespace && (0, objects_1.equals)(this.bracketPairColorizationOptions, other.bracketPairColorizationOptions)); } /** * @internal */ createChangeEvent(newOpts) { return { tabSize: this.tabSize !== newOpts.tabSize, indentSize: this.indentSize !== newOpts.indentSize, insertSpaces: this.insertSpaces !== newOpts.insertSpaces, trimAutoWhitespace: this.trimAutoWhitespace !== newOpts.trimAutoWhitespace, }; } } exports.TextModelResolvedOptions = TextModelResolvedOptions; class FindMatch { /** * @internal */ constructor(range, matches) { this._findMatchBrand = undefined; this.range = range; this.matches = matches; } } exports.FindMatch = FindMatch; /** * @internal */ class ValidAnnotatedEditOperation { constructor(identifier, range, text, forceMoveMarkers, isAutoWhitespaceEdit, _isTracked) { this.identifier = identifier; this.range = range; this.text = text; this.forceMoveMarkers = forceMoveMarkers; this.isAutoWhitespaceEdit = isAutoWhitespaceEdit; this._isTracked = _isTracked; } } exports.ValidAnnotatedEditOperation = ValidAnnotatedEditOperation; /** * @internal */ class SearchData { constructor(regex, wordSeparators, simpleSearch) { this.regex = regex; this.wordSeparators = wordSeparators; this.simpleSearch = simpleSearch; } } exports.SearchData = SearchData; /** * @internal */ class ApplyEditsResult { constructor(reverseEdits, changes, trimAutoWhitespaceLineNumbers) { this.reverseEdits = reverseEdits; this.changes = changes; this.trimAutoWhitespaceLineNumbers = trimAutoWhitespaceLineNumbers; } } exports.ApplyEditsResult = ApplyEditsResult; /** * @internal */ function shouldSynchronizeModel(model) { return (!model.isTooLargeForSyncing() && !model.isForSimpleWidget); } 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[413/*vs/editor/common/languageFeatureRegistry*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,49/*vs/editor/common/model*/,405/*vs/editor/common/languageSelector*/]), function (require, exports, event_1, lifecycle_1, model_1, languageSelector_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LanguageFeatureRegistry = void 0; function isExclusive(selector) { if (typeof selector === 'string') { return false; } else if (Array.isArray(selector)) { return selector.every(isExclusive); } else { return !!selector.exclusive; // TODO: microsoft/TypeScript#42768 } } class 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) { const idx = this._entries.indexOf(entry); if (idx >= 0) { this._entries.splice(idx, 1); this._lastCandidate = undefined; this._onDidChange.fire(this._entries.length); entry = undefined; } } }); } has(model) { return this.all(model).length > 0; } all(model) { if (!model) { return []; } this._updateScores(model); 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) { const candidate = { uri: model.uri.toString(), language: model.getLanguageId() }; 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.getLanguageId(), (0, model_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; }); /*--------------------------------------------------------------------------------------------- * 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/model/bracketPairsTextModelPart/bracketPairsTree/length*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings_1, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.lengthOfString = exports.lengthsToRange = exports.positionToLength = exports.lengthGreaterThanEqual = exports.lengthLessThanEqual = exports.lengthLessThan = exports.lengthDiffNonNegative = exports.lengthAdd = exports.lengthGetColumnCountIfZeroLineCount = exports.lengthGetLineCount = exports.lengthToObj = exports.toLength = exports.lengthIsZero = exports.lengthZero = exports.lengthDiff = exports.LengthObj = void 0; /** * Represents a non-negative length in terms of line and column count. * Prefer using {@link Length} for performance reasons. */ class LengthObj { constructor(lineCount, columnCount) { this.lineCount = lineCount; this.columnCount = columnCount; } toString() { return `${this.lineCount},${this.columnCount}`; } } exports.LengthObj = LengthObj; LengthObj.zero = new LengthObj(0, 0); /** * The end must be greater than or equal to the start. */ function lengthDiff(startLineCount, startColumnCount, endLineCount, endColumnCount) { return (startLineCount !== endLineCount) ? toLength(endLineCount - startLineCount, endColumnCount) : toLength(0, endColumnCount - startColumnCount); } exports.lengthDiff = lengthDiff; exports.lengthZero = 0; function lengthIsZero(length) { return length === 0; } exports.lengthIsZero = lengthIsZero; /* * We have 52 bits available in a JS number. * We use the upper 26 bits to store the line and the lower 26 bits to store the column. * * Set boolean to `true` when debugging, so that debugging is easier. */ const factor = /* is debug: */ false ? 100000 : Math.pow(2, 26); function toLength(lineCount, columnCount) { // llllllllllllllllllllllllllcccccccccccccccccccccccccc (52 bits) // line count (26 bits) column count (26 bits) // If there is no overflow (all values/sums below 2^26 = 67108864), // we have `toLength(lns1, cols1) + toLength(lns2, cols2) = toLength(lns1 + lns2, cols1 + cols2)`. return (lineCount * factor + columnCount); } exports.toLength = toLength; function lengthToObj(length) { const l = length; const lineCount = Math.floor(l / factor); const columnCount = l - lineCount * factor; return new LengthObj(lineCount, columnCount); } exports.lengthToObj = lengthToObj; function lengthGetLineCount(length) { return Math.floor(length / factor); } exports.lengthGetLineCount = lengthGetLineCount; /** * Returns the amount of columns of the given length, assuming that it does not span any line. */ function lengthGetColumnCountIfZeroLineCount(length) { return length; } exports.lengthGetColumnCountIfZeroLineCount = lengthGetColumnCountIfZeroLineCount; function lengthAdd(l1, l2) { return ((l2 < factor) ? (l1 + l2) // l2 is the amount of columns (zero line count). Keep the column count from l1. : (l1 - (l1 % factor) + l2)); // l1 - (l1 % factor) equals toLength(l1.lineCount, 0) } exports.lengthAdd = lengthAdd; /** * Returns a non negative length `result` such that `lengthAdd(length1, result) = length2`, or zero if such length does not exist. */ function lengthDiffNonNegative(length1, length2) { const l1 = length1; const l2 = length2; const diff = l2 - l1; if (diff <= 0) { // line-count of length1 is higher than line-count of length2 // or they are equal and column-count of length1 is higher than column-count of length2 return exports.lengthZero; } const lineCount1 = Math.floor(l1 / factor); const lineCount2 = Math.floor(l2 / factor); const colCount2 = l2 - lineCount2 * factor; if (lineCount1 === lineCount2) { const colCount1 = l1 - lineCount1 * factor; return toLength(0, colCount2 - colCount1); } else { return toLength(lineCount2 - lineCount1, colCount2); } } exports.lengthDiffNonNegative = lengthDiffNonNegative; function lengthLessThan(length1, length2) { // First, compare line counts, then column counts. return length1 < length2; } exports.lengthLessThan = lengthLessThan; function lengthLessThanEqual(length1, length2) { return length1 <= length2; } exports.lengthLessThanEqual = lengthLessThanEqual; function lengthGreaterThanEqual(length1, length2) { return length1 >= length2; } exports.lengthGreaterThanEqual = lengthGreaterThanEqual; function positionToLength(position) { return toLength(position.lineNumber - 1, position.column - 1); } exports.positionToLength = positionToLength; function lengthsToRange(lengthStart, lengthEnd) { const l = lengthStart; const lineCount = Math.floor(l / factor); const colCount = l - lineCount * factor; const l2 = lengthEnd; const lineCount2 = Math.floor(l2 / factor); const colCount2 = l2 - lineCount2 * factor; return new range_1.Range(lineCount + 1, colCount + 1, lineCount2 + 1, colCount2 + 1); } exports.lengthsToRange = lengthsToRange; function lengthOfString(str) { const lines = (0, strings_1.splitLines)(str); return toLength(lines.length - 1, lines[lines.length - 1].length); } exports.lengthOfString = lengthOfString; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[240/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/beforeEditPositionMapper*/], __M([1/*require*/,0/*exports*/,83/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/]), function (require, exports, length_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BeforeEditPositionMapper = exports.TextEditInfo = void 0; class TextEditInfo { constructor(startOffset, endOffset, newLength) { this.startOffset = startOffset; this.endOffset = endOffset; this.newLength = newLength; } } exports.TextEditInfo = TextEditInfo; class BeforeEditPositionMapper { /** * @param edits Must be sorted by offset in ascending order. */ constructor(edits, documentLength) { this.documentLength = documentLength; this.nextEditIdx = 0; this.deltaOldToNewLineCount = 0; this.deltaOldToNewColumnCount = 0; this.deltaLineIdxInOld = -1; this.edits = edits.map(edit => TextEditInfoCache.from(edit)); } /** * @param offset Must be equal to or greater than the last offset this method has been called with. */ getOffsetBeforeChange(offset) { this.adjustNextEdit(offset); return this.translateCurToOld(offset); } /** * @param offset Must be equal to or greater than the last offset this method has been called with. */ getDistanceToNextChange(offset) { this.adjustNextEdit(offset); const nextEdit = this.edits[this.nextEditIdx]; const nextChangeOffset = nextEdit ? this.translateOldToCur(nextEdit.offsetObj) : this.documentLength; return (0, length_1.lengthDiffNonNegative)(offset, nextChangeOffset); } translateOldToCur(oldOffsetObj) { if (oldOffsetObj.lineCount === this.deltaLineIdxInOld) { return (0, length_1.toLength)(oldOffsetObj.lineCount + this.deltaOldToNewLineCount, oldOffsetObj.columnCount + this.deltaOldToNewColumnCount); } else { return (0, length_1.toLength)(oldOffsetObj.lineCount + this.deltaOldToNewLineCount, oldOffsetObj.columnCount); } } translateCurToOld(newOffset) { const offsetObj = (0, length_1.lengthToObj)(newOffset); if (offsetObj.lineCount - this.deltaOldToNewLineCount === this.deltaLineIdxInOld) { return (0, length_1.toLength)(offsetObj.lineCount - this.deltaOldToNewLineCount, offsetObj.columnCount - this.deltaOldToNewColumnCount); } else { return (0, length_1.toLength)(offsetObj.lineCount - this.deltaOldToNewLineCount, offsetObj.columnCount); } } adjustNextEdit(offset) { while (this.nextEditIdx < this.edits.length) { const nextEdit = this.edits[this.nextEditIdx]; // After applying the edit, what is its end offset (considering all previous edits)? const nextEditEndOffsetInCur = this.translateOldToCur(nextEdit.endOffsetAfterObj); if ((0, length_1.lengthLessThanEqual)(nextEditEndOffsetInCur, offset)) { // We are after the edit, skip it this.nextEditIdx++; const nextEditEndOffsetInCurObj = (0, length_1.lengthToObj)(nextEditEndOffsetInCur); // Before applying the edit, what is its end offset (considering all previous edits)? const nextEditEndOffsetBeforeInCurObj = (0, length_1.lengthToObj)(this.translateOldToCur(nextEdit.endOffsetBeforeObj)); const lineDelta = nextEditEndOffsetInCurObj.lineCount - nextEditEndOffsetBeforeInCurObj.lineCount; this.deltaOldToNewLineCount += lineDelta; const previousColumnDelta = this.deltaLineIdxInOld === nextEdit.endOffsetBeforeObj.lineCount ? this.deltaOldToNewColumnCount : 0; const columnDelta = nextEditEndOffsetInCurObj.columnCount - nextEditEndOffsetBeforeInCurObj.columnCount; this.deltaOldToNewColumnCount = previousColumnDelta + columnDelta; this.deltaLineIdxInOld = nextEdit.endOffsetBeforeObj.lineCount; } else { // We are in or before the edit. break; } } } } exports.BeforeEditPositionMapper = BeforeEditPositionMapper; class TextEditInfoCache { constructor(startOffset, endOffset, textLength) { this.endOffsetBeforeObj = (0, length_1.lengthToObj)(endOffset); this.endOffsetAfterObj = (0, length_1.lengthToObj)((0, length_1.lengthAdd)(startOffset, textLength)); this.offsetObj = (0, length_1.lengthToObj)(startOffset); } static from(edit) { return new TextEditInfoCache(edit.startOffset, edit.endOffset, edit.newLength); } } }); /*--------------------------------------------------------------------------------------------- * 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/common/model/bracketPairsTextModelPart/bracketPairsTree/nodeReader*/], __M([1/*require*/,0/*exports*/,83/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/]), function (require, exports, length_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NodeReader = void 0; /** * Allows to efficiently find a longest child at a given offset in a fixed node. * The requested offsets must increase monotonously. */ class NodeReader { constructor(node) { this.lastOffset = length_1.lengthZero; this.nextNodes = [node]; this.offsets = [length_1.lengthZero]; this.idxs = []; } /** * Returns the longest node at `offset` that satisfies the predicate. * @param offset must be greater than or equal to the last offset this method has been called with! */ readLongestNodeAt(offset, predicate) { if ((0, length_1.lengthLessThan)(offset, this.lastOffset)) { throw new Error('Invalid offset'); } this.lastOffset = offset; // Find the longest node of all those that are closest to the current offset. while (true) { const curNode = lastOrUndefined(this.nextNodes); if (!curNode) { return undefined; } const curNodeOffset = lastOrUndefined(this.offsets); if ((0, length_1.lengthLessThan)(offset, curNodeOffset)) { // The next best node is not here yet. // The reader must advance before a cached node is hit. return undefined; } if ((0, length_1.lengthLessThan)(curNodeOffset, offset)) { // The reader is ahead of the current node. if ((0, length_1.lengthAdd)(curNodeOffset, curNode.length) <= offset) { // The reader is after the end of the current node. this.nextNodeAfterCurrent(); } else { // The reader is somewhere in the current node. const nextChildIdx = getNextChildIdx(curNode); if (nextChildIdx !== -1) { // Go to the first child and repeat. this.nextNodes.push(curNode.getChild(nextChildIdx)); this.offsets.push(curNodeOffset); this.idxs.push(nextChildIdx); } else { // We don't have children this.nextNodeAfterCurrent(); } } } else { // readerOffsetBeforeChange === curNodeOffset if (predicate(curNode)) { this.nextNodeAfterCurrent(); return curNode; } else { const nextChildIdx = getNextChildIdx(curNode); // look for shorter node if (nextChildIdx === -1) { // There is no shorter node. this.nextNodeAfterCurrent(); return undefined; } else { // Descend into first child & repeat. this.nextNodes.push(curNode.getChild(nextChildIdx)); this.offsets.push(curNodeOffset); this.idxs.push(nextChildIdx); } } } } } // Navigates to the longest node that continues after the current node. nextNodeAfterCurrent() { while (true) { const currentOffset = lastOrUndefined(this.offsets); const currentNode = lastOrUndefined(this.nextNodes); this.nextNodes.pop(); this.offsets.pop(); if (this.idxs.length === 0) { // We just popped the root node, there is no next node. break; } // Parent is not undefined, because idxs is not empty const parent = lastOrUndefined(this.nextNodes); const nextChildIdx = getNextChildIdx(parent, this.idxs[this.idxs.length - 1]); if (nextChildIdx !== -1) { this.nextNodes.push(parent.getChild(nextChildIdx)); this.offsets.push((0, length_1.lengthAdd)(currentOffset, currentNode.length)); this.idxs[this.idxs.length - 1] = nextChildIdx; break; } else { this.idxs.pop(); } // We fully consumed the parent. // Current node is now parent, so call nextNodeAfterCurrent again } } } exports.NodeReader = NodeReader; function getNextChildIdx(node, curIdx = -1) { while (true) { curIdx++; if (curIdx >= node.childrenLength) { return -1; } if (node.getChild(curIdx)) { return curIdx; } } } function lastOrUndefined(arr) { return arr.length > 0 ? arr[arr.length - 1] : undefined; } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[99/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DenseKeyProvider = exports.identityKeyProvider = exports.SmallImmutableSet = void 0; const emptyArr = new Array(); /** * Represents an immutable set that works best for a small number of elements (less than 32). * It uses bits to encode element membership efficiently. */ class SmallImmutableSet { constructor(items, additionalItems) { this.items = items; this.additionalItems = additionalItems; } static create(items, additionalItems) { if (items <= 128 && additionalItems.length === 0) { // We create a cache of 128=2^7 elements to cover all sets with up to 7 (dense) elements. let cached = SmallImmutableSet.cache[items]; if (!cached) { cached = new SmallImmutableSet(items, additionalItems); SmallImmutableSet.cache[items] = cached; } return cached; } return new SmallImmutableSet(items, additionalItems); } static getEmpty() { return this.empty; } add(value, keyProvider) { const key = keyProvider.getKey(value); let idx = key >> 5; // divided by 32 if (idx === 0) { // fast path const newItem = (1 << key) | this.items; if (newItem === this.items) { return this; } return SmallImmutableSet.create(newItem, this.additionalItems); } idx--; const newItems = this.additionalItems.slice(0); while (newItems.length < idx) { newItems.push(0); } newItems[idx] |= 1 << (key & 31); return SmallImmutableSet.create(this.items, newItems); } merge(other) { const merged = this.items | other.items; if (this.additionalItems === emptyArr && other.additionalItems === emptyArr) { // fast path if (merged === this.items) { return this; } if (merged === other.items) { return other; } return SmallImmutableSet.create(merged, emptyArr); } // This can be optimized, but it's not a common case const newItems = new Array(); for (let i = 0; i < Math.max(this.additionalItems.length, other.additionalItems.length); i++) { const item1 = this.additionalItems[i] || 0; const item2 = other.additionalItems[i] || 0; newItems.push(item1 | item2); } return SmallImmutableSet.create(merged, newItems); } intersects(other) { if ((this.items & other.items) !== 0) { return true; } for (let i = 0; i < Math.min(this.additionalItems.length, other.additionalItems.length); i++) { if ((this.additionalItems[i] & other.additionalItems[i]) !== 0) { return true; } } return false; } } exports.SmallImmutableSet = SmallImmutableSet; SmallImmutableSet.cache = new Array(129); SmallImmutableSet.empty = SmallImmutableSet.create(0, emptyArr); exports.identityKeyProvider = { getKey(value) { return value; } }; /** * Assigns values a unique incrementing key. */ class DenseKeyProvider { constructor() { this.items = new Map(); } getKey(value) { let existing = this.items.get(value); if (existing === undefined) { existing = this.items.size; this.items.set(value, existing); } return existing; } } exports.DenseKeyProvider = DenseKeyProvider; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[149/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/ast*/], __M([1/*require*/,0/*exports*/,68/*vs/editor/common/core/cursorColumns*/,83/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/,99/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet*/]), function (require, exports, cursorColumns_1, length_1, smallImmutableSet_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.InvalidBracketAstNode = exports.BracketAstNode = exports.TextAstNode = exports.ListAstNode = exports.PairAstNode = void 0; /** * The base implementation for all AST nodes. */ class BaseAstNode { constructor(length) { this._length = length; } /** * The length of the entire node, which should equal the sum of lengths of all children. */ get length() { return this._length; } } /** * Represents a bracket pair including its child (e.g. `{ ... }`). * Might be unclosed. * Immutable, if all children are immutable. */ class PairAstNode extends BaseAstNode { constructor(length, openingBracket, child, closingBracket, missingOpeningBracketIds) { super(length); this.openingBracket = openingBracket; this.child = child; this.closingBracket = closingBracket; this.missingOpeningBracketIds = missingOpeningBracketIds; } static create(openingBracket, child, closingBracket) { let length = openingBracket.length; if (child) { length = (0, length_1.lengthAdd)(length, child.length); } if (closingBracket) { length = (0, length_1.lengthAdd)(length, closingBracket.length); } return new PairAstNode(length, openingBracket, child, closingBracket, child ? child.missingOpeningBracketIds : smallImmutableSet_1.SmallImmutableSet.getEmpty()); } get kind() { return 2 /* Pair */; } get listHeight() { return 0; } get childrenLength() { return 3; } getChild(idx) { switch (idx) { case 0: return this.openingBracket; case 1: return this.child; case 2: return this.closingBracket; } throw new Error('Invalid child index'); } /** * Avoid using this property, it allocates an array! */ get children() { const result = new Array(); result.push(this.openingBracket); if (this.child) { result.push(this.child); } if (this.closingBracket) { result.push(this.closingBracket); } return result; } canBeReused(openBracketIds) { if (this.closingBracket === null) { // Unclosed pair ast nodes only // end at the end of the document // or when a parent node is closed. // This could be improved: // Only return false if some next token is neither "undefined" nor a bracket that closes a parent. return false; } if (openBracketIds.intersects(this.missingOpeningBracketIds)) { return false; } return true; } deepClone() { return new PairAstNode(this.length, this.openingBracket.deepClone(), this.child && this.child.deepClone(), this.closingBracket && this.closingBracket.deepClone(), this.missingOpeningBracketIds); } computeMinIndentation(offset, textModel) { return this.child ? this.child.computeMinIndentation((0, length_1.lengthAdd)(offset, this.openingBracket.length), textModel) : Number.MAX_SAFE_INTEGER; } } exports.PairAstNode = PairAstNode; class ListAstNode extends BaseAstNode { /** * Use ListAstNode.create. */ constructor(length, listHeight, _missingOpeningBracketIds) { super(length); this.listHeight = listHeight; this._missingOpeningBracketIds = _missingOpeningBracketIds; this.cachedMinIndentation = -1; } /** * This method uses more memory-efficient list nodes that can only store 2 or 3 children. */ static create23(item1, item2, item3, immutable = false) { let length = item1.length; let missingBracketIds = item1.missingOpeningBracketIds; if (item1.listHeight !== item2.listHeight) { throw new Error('Invalid list heights'); } length = (0, length_1.lengthAdd)(length, item2.length); missingBracketIds = missingBracketIds.merge(item2.missingOpeningBracketIds); if (item3) { if (item1.listHeight !== item3.listHeight) { throw new Error('Invalid list heights'); } length = (0, length_1.lengthAdd)(length, item3.length); missingBracketIds = missingBracketIds.merge(item3.missingOpeningBracketIds); } return immutable ? new Immutable23ListAstNode(length, item1.listHeight + 1, item1, item2, item3, missingBracketIds) : new TwoThreeListAstNode(length, item1.listHeight + 1, item1, item2, item3, missingBracketIds); } static getEmpty() { return new ImmutableArrayListAstNode(length_1.lengthZero, 0, [], smallImmutableSet_1.SmallImmutableSet.getEmpty()); } get kind() { return 4 /* List */; } get missingOpeningBracketIds() { return this._missingOpeningBracketIds; } throwIfImmutable() { // NOOP } makeLastElementMutable() { this.throwIfImmutable(); const childCount = this.childrenLength; if (childCount === 0) { return undefined; } const lastChild = this.getChild(childCount - 1); const mutable = lastChild.kind === 4 /* List */ ? lastChild.toMutable() : lastChild; if (lastChild !== mutable) { this.setChild(childCount - 1, mutable); } return mutable; } makeFirstElementMutable() { this.throwIfImmutable(); const childCount = this.childrenLength; if (childCount === 0) { return undefined; } const firstChild = this.getChild(0); const mutable = firstChild.kind === 4 /* List */ ? firstChild.toMutable() : firstChild; if (firstChild !== mutable) { this.setChild(0, mutable); } return mutable; } canBeReused(openBracketIds) { if (openBracketIds.intersects(this.missingOpeningBracketIds)) { return false; } let lastChild = this; let lastLength; while (lastChild.kind === 4 /* List */ && (lastLength = lastChild.childrenLength) > 0) { lastChild = lastChild.getChild(lastLength - 1); } return lastChild.canBeReused(openBracketIds); } handleChildrenChanged() { this.throwIfImmutable(); const count = this.childrenLength; let length = this.getChild(0).length; let unopenedBrackets = this.getChild(0).missingOpeningBracketIds; for (let i = 1; i < count; i++) { const child = this.getChild(i); length = (0, length_1.lengthAdd)(length, child.length); unopenedBrackets = unopenedBrackets.merge(child.missingOpeningBracketIds); } this._length = length; this._missingOpeningBracketIds = unopenedBrackets; this.cachedMinIndentation = -1; } computeMinIndentation(offset, textModel) { if (this.cachedMinIndentation !== -1) { return this.cachedMinIndentation; } let minIndentation = Number.MAX_SAFE_INTEGER; let childOffset = offset; for (let i = 0; i < this.childrenLength; i++) { const child = this.getChild(i); if (child) { minIndentation = Math.min(minIndentation, child.computeMinIndentation(childOffset, textModel)); childOffset = (0, length_1.lengthAdd)(childOffset, child.length); } } this.cachedMinIndentation = minIndentation; return minIndentation; } } exports.ListAstNode = ListAstNode; class TwoThreeListAstNode extends ListAstNode { constructor(length, listHeight, _item1, _item2, _item3, missingOpeningBracketIds) { super(length, listHeight, missingOpeningBracketIds); this._item1 = _item1; this._item2 = _item2; this._item3 = _item3; } get childrenLength() { return this._item3 !== null ? 3 : 2; } getChild(idx) { switch (idx) { case 0: return this._item1; case 1: return this._item2; case 2: return this._item3; } throw new Error('Invalid child index'); } setChild(idx, node) { switch (idx) { case 0: this._item1 = node; return; case 1: this._item2 = node; return; case 2: this._item3 = node; return; } throw new Error('Invalid child index'); } get children() { return this._item3 ? [this._item1, this._item2, this._item3] : [this._item1, this._item2]; } get item1() { return this._item1; } get item2() { return this._item2; } get item3() { return this._item3; } deepClone() { return new TwoThreeListAstNode(this.length, this.listHeight, this._item1.deepClone(), this._item2.deepClone(), this._item3 ? this._item3.deepClone() : null, this.missingOpeningBracketIds); } appendChildOfSameHeight(node) { if (this._item3) { throw new Error('Cannot append to a full (2,3) tree node'); } this.throwIfImmutable(); this._item3 = node; this.handleChildrenChanged(); } unappendChild() { if (!this._item3) { throw new Error('Cannot remove from a non-full (2,3) tree node'); } this.throwIfImmutable(); const result = this._item3; this._item3 = null; this.handleChildrenChanged(); return result; } prependChildOfSameHeight(node) { if (this._item3) { throw new Error('Cannot prepend to a full (2,3) tree node'); } this.throwIfImmutable(); this._item3 = this._item2; this._item2 = this._item1; this._item1 = node; this.handleChildrenChanged(); } unprependChild() { if (!this._item3) { throw new Error('Cannot remove from a non-full (2,3) tree node'); } this.throwIfImmutable(); const result = this._item1; this._item1 = this._item2; this._item2 = this._item3; this._item3 = null; this.handleChildrenChanged(); return result; } toMutable() { return this; } } /** * Immutable, if all children are immutable. */ class Immutable23ListAstNode extends TwoThreeListAstNode { toMutable() { return new TwoThreeListAstNode(this.length, this.listHeight, this.item1, this.item2, this.item3, this.missingOpeningBracketIds); } throwIfImmutable() { throw new Error('this instance is immutable'); } } /** * For debugging. */ class ArrayListAstNode extends ListAstNode { constructor(length, listHeight, _children, missingOpeningBracketIds) { super(length, listHeight, missingOpeningBracketIds); this._children = _children; } get childrenLength() { return this._children.length; } getChild(idx) { return this._children[idx]; } setChild(idx, child) { this._children[idx] = child; } get children() { return this._children; } deepClone() { const children = new Array(this._children.length); for (let i = 0; i < this._children.length; i++) { children[i] = this._children[i].deepClone(); } return new ArrayListAstNode(this.length, this.listHeight, children, this.missingOpeningBracketIds); } appendChildOfSameHeight(node) { this.throwIfImmutable(); this._children.push(node); this.handleChildrenChanged(); } unappendChild() { this.throwIfImmutable(); const item = this._children.pop(); this.handleChildrenChanged(); return item; } prependChildOfSameHeight(node) { this.throwIfImmutable(); this._children.unshift(node); this.handleChildrenChanged(); } unprependChild() { this.throwIfImmutable(); const item = this._children.shift(); this.handleChildrenChanged(); return item; } toMutable() { return this; } } /** * Immutable, if all children are immutable. */ class ImmutableArrayListAstNode extends ArrayListAstNode { toMutable() { return new ArrayListAstNode(this.length, this.listHeight, [...this.children], this.missingOpeningBracketIds); } throwIfImmutable() { throw new Error('this instance is immutable'); } } const emptyArray = []; class ImmutableLeafAstNode extends BaseAstNode { get listHeight() { return 0; } get childrenLength() { return 0; } getChild(idx) { return null; } get children() { return emptyArray; } deepClone() { return this; } } class TextAstNode extends ImmutableLeafAstNode { get kind() { return 0 /* Text */; } get missingOpeningBracketIds() { return smallImmutableSet_1.SmallImmutableSet.getEmpty(); } canBeReused(_openedBracketIds) { return true; } computeMinIndentation(offset, textModel) { const start = (0, length_1.lengthToObj)(offset); // Text ast nodes don't have partial indentation (ensured by the tokenizer). // Thus, if this text node does not start at column 0, the first line cannot have any indentation at all. const startLineNumber = (start.columnCount === 0 ? start.lineCount : start.lineCount + 1) + 1; const endLineNumber = (0, length_1.lengthGetLineCount)((0, length_1.lengthAdd)(offset, this.length)) + 1; let result = Number.MAX_SAFE_INTEGER; for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { const firstNonWsColumn = textModel.getLineFirstNonWhitespaceColumn(lineNumber); const lineContent = textModel.getLineContent(lineNumber); if (firstNonWsColumn === 0) { continue; } const visibleColumn = cursorColumns_1.CursorColumns.visibleColumnFromColumn(lineContent, firstNonWsColumn, textModel.getOptions().tabSize); result = Math.min(result, visibleColumn); } return result; } } exports.TextAstNode = TextAstNode; class BracketAstNode extends ImmutableLeafAstNode { constructor(length, languageId, /** * In case of a opening bracket, this is the id of the opening bracket. * In case of a closing bracket, this contains the ids of all opening brackets it can close. */ bracketIds) { super(length); this.languageId = languageId; this.bracketIds = bracketIds; } static create(length, languageId, bracketIds) { const node = new BracketAstNode(length, languageId, bracketIds); return node; } get kind() { return 1 /* Bracket */; } get missingOpeningBracketIds() { return smallImmutableSet_1.SmallImmutableSet.getEmpty(); } canBeReused(_openedBracketIds) { // These nodes could be reused, // but not in a general way. // Their parent may be reused. return false; } computeMinIndentation(offset, textModel) { return Number.MAX_SAFE_INTEGER; } } exports.BracketAstNode = BracketAstNode; class InvalidBracketAstNode extends ImmutableLeafAstNode { constructor(closingBrackets, length) { super(length); this.missingOpeningBracketIds = closingBrackets; } get kind() { return 3 /* UnexpectedClosingBracket */; } canBeReused(openedBracketIds) { return !openedBracketIds.intersects(this.missingOpeningBracketIds); } computeMinIndentation(offset, textModel) { return Number.MAX_SAFE_INTEGER; } } exports.InvalidBracketAstNode = InvalidBracketAstNode; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[415/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/concat23Trees*/], __M([1/*require*/,0/*exports*/,149/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/ast*/]), function (require, exports, ast_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.concat23TreesOfSameHeight = exports.concat23Trees = void 0; /** * Concatenates a list of (2,3) AstNode's into a single (2,3) AstNode. * This mutates the items of the input array! * If all items have the same height, this method has runtime O(items.length). * Otherwise, it has runtime O(items.length * max(log(items.length), items.max(i => i.height))). */ function concat23Trees(items) { if (items.length === 0) { return null; } if (items.length === 1) { return items[0]; } let i = 0; /** * Reads nodes of same height and concatenates them to a single node. */ function readNode() { if (i >= items.length) { return null; } const start = i; const height = items[start].listHeight; i++; while (i < items.length && items[i].listHeight === height) { i++; } if (i - start >= 2) { return concat23TreesOfSameHeight(start === 0 && i === items.length ? items : items.slice(start, i), false); } else { return items[start]; } } // The items might not have the same height. // We merge all items by using a binary concat operator. let first = readNode(); // There must be a first item let second = readNode(); if (!second) { return first; } for (let item = readNode(); item; item = readNode()) { // Prefer concatenating smaller trees, as the runtime of concat depends on the tree height. if (heightDiff(first, second) <= heightDiff(second, item)) { first = concat(first, second); second = item; } else { second = concat(second, item); } } const result = concat(first, second); return result; } exports.concat23Trees = concat23Trees; function concat23TreesOfSameHeight(items, createImmutableLists = false) { if (items.length === 0) { return null; } if (items.length === 1) { return items[0]; } let length = items.length; // All trees have same height, just create parent nodes. while (length > 3) { const newLength = length >> 1; for (let i = 0; i < newLength; i++) { const j = i << 1; items[i] = ast_1.ListAstNode.create23(items[j], items[j + 1], j + 3 === length ? items[j + 2] : null, createImmutableLists); } length = newLength; } return ast_1.ListAstNode.create23(items[0], items[1], length >= 3 ? items[2] : null, createImmutableLists); } exports.concat23TreesOfSameHeight = concat23TreesOfSameHeight; function heightDiff(node1, node2) { return Math.abs(node1.listHeight - node2.listHeight); } function concat(node1, node2) { if (node1.listHeight === node2.listHeight) { return ast_1.ListAstNode.create23(node1, node2, null, false); } else if (node1.listHeight > node2.listHeight) { // node1 is the tree we want to insert into return append(node1, node2); } else { return prepend(node2, node1); } } /** * Appends the given node to the end of this (2,3) tree. * Returns the new root. */ function append(list, nodeToAppend) { list = list.toMutable(); let curNode = list; const parents = new Array(); let nodeToAppendOfCorrectHeight; while (true) { // assert nodeToInsert.listHeight <= curNode.listHeight if (nodeToAppend.listHeight === curNode.listHeight) { nodeToAppendOfCorrectHeight = nodeToAppend; break; } // assert 0 <= nodeToInsert.listHeight < curNode.listHeight if (curNode.kind !== 4 /* List */) { throw new Error('unexpected'); } parents.push(curNode); // assert 2 <= curNode.childrenLength <= 3 curNode = curNode.makeLastElementMutable(); } // assert nodeToAppendOfCorrectHeight!.listHeight === curNode.listHeight for (let i = parents.length - 1; i >= 0; i--) { const parent = parents[i]; if (nodeToAppendOfCorrectHeight) { // Can we take the element? if (parent.childrenLength >= 3) { // assert parent.childrenLength === 3 && parent.listHeight === nodeToAppendOfCorrectHeight.listHeight + 1 // we need to split to maintain (2,3)-tree property. // Send the third element + the new element to the parent. nodeToAppendOfCorrectHeight = ast_1.ListAstNode.create23(parent.unappendChild(), nodeToAppendOfCorrectHeight, null, false); } else { parent.appendChildOfSameHeight(nodeToAppendOfCorrectHeight); nodeToAppendOfCorrectHeight = undefined; } } else { parent.handleChildrenChanged(); } } if (nodeToAppendOfCorrectHeight) { return ast_1.ListAstNode.create23(list, nodeToAppendOfCorrectHeight, null, false); } else { return list; } } /** * Prepends the given node to the end of this (2,3) tree. * Returns the new root. */ function prepend(list, nodeToAppend) { list = list.toMutable(); let curNode = list; const parents = new Array(); // assert nodeToInsert.listHeight <= curNode.listHeight while (nodeToAppend.listHeight !== curNode.listHeight) { // assert 0 <= nodeToInsert.listHeight < curNode.listHeight if (curNode.kind !== 4 /* List */) { throw new Error('unexpected'); } parents.push(curNode); // assert 2 <= curNode.childrenFast.length <= 3 curNode = curNode.makeFirstElementMutable(); } let nodeToPrependOfCorrectHeight = nodeToAppend; // assert nodeToAppendOfCorrectHeight!.listHeight === curNode.listHeight for (let i = parents.length - 1; i >= 0; i--) { const parent = parents[i]; if (nodeToPrependOfCorrectHeight) { // Can we take the element? if (parent.childrenLength >= 3) { // assert parent.childrenLength === 3 && parent.listHeight === nodeToAppendOfCorrectHeight.listHeight + 1 // we need to split to maintain (2,3)-tree property. // Send the third element + the new element to the parent. nodeToPrependOfCorrectHeight = ast_1.ListAstNode.create23(nodeToPrependOfCorrectHeight, parent.unprependChild(), null, false); } else { parent.prependChildOfSameHeight(nodeToPrependOfCorrectHeight); nodeToPrependOfCorrectHeight = undefined; } } else { parent.handleChildrenChanged(); } } if (nodeToPrependOfCorrectHeight) { return ast_1.ListAstNode.create23(nodeToPrependOfCorrectHeight, list, null, false); } else { return list; } } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[241/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/parser*/], __M([1/*require*/,0/*exports*/,149/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/ast*/,240/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/beforeEditPositionMapper*/,99/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet*/,83/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/,415/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/concat23Trees*/,414/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/nodeReader*/]), function (require, exports, ast_1, beforeEditPositionMapper_1, smallImmutableSet_1, length_1, concat23Trees_1, nodeReader_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseDocument = void 0; /** * Non incrementally built ASTs are immutable. */ function parseDocument(tokenizer, edits, oldNode, createImmutableLists) { const parser = new Parser(tokenizer, edits, oldNode, createImmutableLists); return parser.parseDocument(); } exports.parseDocument = parseDocument; /** * Non incrementally built ASTs are immutable. */ class Parser { constructor(tokenizer, edits, oldNode, createImmutableLists) { this.tokenizer = tokenizer; this.createImmutableLists = createImmutableLists; this._itemsConstructed = 0; this._itemsFromCache = 0; if (oldNode && createImmutableLists) { throw new Error('Not supported'); } this.oldNodeReader = oldNode ? new nodeReader_1.NodeReader(oldNode) : undefined; this.positionMapper = new beforeEditPositionMapper_1.BeforeEditPositionMapper(edits, tokenizer.length); } parseDocument() { this._itemsConstructed = 0; this._itemsFromCache = 0; let result = this.parseList(smallImmutableSet_1.SmallImmutableSet.getEmpty()); if (!result) { result = ast_1.ListAstNode.getEmpty(); } return result; } parseList(openedBracketIds) { const items = new Array(); while (true) { const token = this.tokenizer.peek(); if (!token || (token.kind === 2 /* ClosingBracket */ && token.bracketIds.intersects(openedBracketIds))) { break; } const child = this.parseChild(openedBracketIds); if (child.kind === 4 /* List */ && child.childrenLength === 0) { continue; } items.push(child); } // When there is no oldNodeReader, all items are created from scratch and must have the same height. const result = this.oldNodeReader ? (0, concat23Trees_1.concat23Trees)(items) : (0, concat23Trees_1.concat23TreesOfSameHeight)(items, this.createImmutableLists); return result; } parseChild(openedBracketIds) { if (this.oldNodeReader) { const maxCacheableLength = this.positionMapper.getDistanceToNextChange(this.tokenizer.offset); if (!(0, length_1.lengthIsZero)(maxCacheableLength)) { const cachedNode = this.oldNodeReader.readLongestNodeAt(this.positionMapper.getOffsetBeforeChange(this.tokenizer.offset), curNode => { if (!(0, length_1.lengthLessThan)(curNode.length, maxCacheableLength)) { // Either the node contains edited text or touches edited text. // In the latter case, brackets might have been extended (`end` -> `ending`), so even touching nodes cannot be reused. return false; } const canBeReused = curNode.canBeReused(openedBracketIds); return canBeReused; }); if (cachedNode) { this._itemsFromCache++; this.tokenizer.skip(cachedNode.length); return cachedNode; } } } this._itemsConstructed++; const token = this.tokenizer.read(); switch (token.kind) { case 2 /* ClosingBracket */: return new ast_1.InvalidBracketAstNode(token.bracketIds, token.length); case 0 /* Text */: return token.astNode; case 1 /* OpeningBracket */: { const set = openedBracketIds.merge(token.bracketIds); const child = this.parseList(set); const nextToken = this.tokenizer.peek(); if (nextToken && nextToken.kind === 2 /* ClosingBracket */ && (nextToken.bracketId === token.bracketId || nextToken.bracketIds.intersects(token.bracketIds))) { this.tokenizer.read(); return ast_1.PairAstNode.create(token.astNode, child, nextToken.astNode); } else { return ast_1.PairAstNode.create(token.astNode, child, null); } } default: throw new Error('unexpected'); } } } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[416/*vs/editor/common/model/indentationGuesser*/], __M([1/*require*/,0/*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++) { const aCharCode = a.charCodeAt(i); const bCharCode = b.charCodeAt(i); if (aCharCode !== bCharCode) { break; } } let aSpacesCnt = 0, aTabsCount = 0; for (let j = i; j < aLength; j++) { const aCharCode = a.charCodeAt(j); if (aCharCode === 32 /* Space */) { aSpacesCnt++; } else { aTabsCount++; } } let bSpacesCnt = 0, bTabsCount = 0; for (let j = i; j < bLength; j++) { const bCharCode = b.charCodeAt(j); if (bCharCode === 32 /* Space */) { bSpacesCnt++; } else { bTabsCount++; } } if (aSpacesCnt > 0 && aTabsCount > 0) { return; } if (bSpacesCnt > 0 && bTabsCount > 0) { return; } const tabsDiff = Math.abs(aTabsCount - bTabsCount); const spacesDiff = Math.abs(aSpacesCnt - bSpacesCnt); if (tabsDiff === 0) { // check if the indentation difference might be caused by alignment reasons // sometime folks like to align their code, but this should not be used as a hint result.spacesDiff = spacesDiff; if (spacesDiff > 0 && 0 <= bSpacesCnt - 1 && bSpacesCnt - 1 < a.length && bSpacesCnt < b.length) { if (b.charCodeAt(bSpacesCnt) !== 32 /* 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 const spacesDiffCount = [0, 0, 0, 0, 0, 0, 0, 0, 0]; // `tabSize` scores const tmp = new SpacesDiffResult(); for (let lineNumber = 1; lineNumber <= linesCount; lineNumber++) { const currentLineLength = source.getLineLength(lineNumber); const currentLineText = source.getLineContent(lineNumber); // if the text buffer is chunk based, so long lines are cons-string, v8 will flattern the string when we check charCode. // checking charCode on chunks directly is cheaper. const useCurrentLineText = (currentLineLength <= 65536); let currentLineHasContent = false; // does `currentLineText` contain non-whitespace chars let currentLineIndentation = 0; // index at which `currentLineText` contains the first non-whitespace char let currentLineSpacesCount = 0; // count of spaces found in `currentLineText` indentation let currentLineTabsCount = 0; // count of tabs found in `currentLineText` indentation for (let j = 0, lenJ = currentLineLength; j < lenJ; j++) { const charCode = (useCurrentLineText ? currentLineText.charCodeAt(j) : source.getLineCharCode(lineNumber, j)); if (charCode === 9 /* 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; } } const currentSpacesDiff = tmp.spacesDiff; if (currentSpacesDiff <= MAX_ALLOWED_TAB_SIZE_GUESS) { spacesDiffCount[currentSpacesDiff]++; } previousLineText = currentLineText; previousLineIndentation = currentLineIndentation; } let insertSpaces = defaultInsertSpaces; if (linesIndentedWithTabsCount !== linesIndentedWithSpacesCount) { insertSpaces = (linesIndentedWithTabsCount < linesIndentedWithSpacesCount); } let tabSize = defaultTabSize; // Guess tabSize only if inserting spaces... if (insertSpaces) { let tabSizeScore = (insertSpaces ? 0 : 0.1 * linesCount); // console.log("score threshold: " + tabSizeScore); ALLOWED_TAB_SIZE_GUESSES.forEach((possibleTabSize) => { const possibleTabSizeScore = spacesDiffCount[possibleTabSize]; if (possibleTabSizeScore > tabSizeScore) { tabSizeScore = possibleTabSizeScore; tabSize = possibleTabSize; } }); // Let a tabSize of 2 win even if it is not the maximum // (only in case 4 was guessed) if (tabSize === 4 && spacesDiffCount[4] > 0 && spacesDiffCount[2] > 0 && spacesDiffCount[2] >= spacesDiffCount[4] / 2) { tabSize = 2; } } // console.log('--------------------------'); // console.log('linesIndentedWithTabsCount: ' + linesIndentedWithTabsCount + ', linesIndentedWithSpacesCount: ' + linesIndentedWithSpacesCount); // console.log('spacesDiffCount: ' + spacesDiffCount); // console.log('tabSize: ' + tabSize + ', tabSizeScore: ' + tabSizeScore); return { insertSpaces: insertSpaces, tabSize: tabSize }; } 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[417/*vs/editor/common/model/intervalTree*/], __M([1/*require*/,0/*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; const 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; const result = []; let resultLen = 0; while (node !== exports.SENTINEL) { if (getNodeIsVisited(node)) { // going up from this node setNodeIsVisited(node.left, false); setNodeIsVisited(node.right, false); if (node === node.parent.right) { delta -= node.parent.delta; } node = node.parent; continue; } if (!getNodeIsVisited(node.left)) { // first time seeing this node nodeMaxEnd = delta + node.maxEnd; if (nodeMaxEnd < start) { // cover case b) from above // there is no need to search this node or its children setNodeIsVisited(node, true); continue; } if (node.left !== exports.SENTINEL) { // go left node = node.left; continue; } } // handle current node nodeStart = delta + node.start; if (nodeStart > end) { // cover case a) from above // there is no need to search this node or its right subtree setNodeIsVisited(node, true); continue; } nodeEnd = delta + node.end; if (nodeEnd >= start) { node.setCachedOffsets(nodeStart, nodeEnd, 0); result[resultLen++] = node; } setNodeIsVisited(node, true); if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) { // go right delta += node.delta; node = node.right; continue; } } setNodeIsVisited(T.root, false); return result; } function noOverlapReplace(T, start, end, textLength) { // https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree // Now, it is known that two intervals A and B overlap only when both // A.low <= B.high and A.high >= B.low. When searching the trees for // nodes overlapping with a given interval, you can immediately skip: // a) all nodes to the right of nodes whose low value is past the end of the given interval. // b) all nodes that have their maximum 'high' value below the start of the given interval. let node = T.root; let delta = 0; let nodeMaxEnd = 0; let nodeStart = 0; const editDelta = (textLength - (end - start)); while (node !== exports.SENTINEL) { if (getNodeIsVisited(node)) { // going up from this node setNodeIsVisited(node.left, false); setNodeIsVisited(node.right, false); if (node === node.parent.right) { delta -= node.parent.delta; } recomputeMaxEnd(node); node = node.parent; continue; } if (!getNodeIsVisited(node.left)) { // first time seeing this node nodeMaxEnd = delta + node.maxEnd; if (nodeMaxEnd < start) { // cover case b) from above // there is no need to search this node or its children setNodeIsVisited(node, true); continue; } if (node.left !== exports.SENTINEL) { // go left node = node.left; continue; } } // handle current node nodeStart = delta + node.start; if (nodeStart > end) { node.start += editDelta; node.end += editDelta; node.delta += editDelta; if (node.delta < -1073741824 /* 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; const result = []; let resultLen = 0; while (node !== exports.SENTINEL) { if (getNodeIsVisited(node)) { // going up from this node setNodeIsVisited(node.left, false); setNodeIsVisited(node.right, false); node = node.parent; continue; } if (node.left !== exports.SENTINEL && !getNodeIsVisited(node.left)) { // go left node = node.left; continue; } // handle current node if (node.ownerId === ownerId) { result[resultLen++] = node; } setNodeIsVisited(node, true); if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) { // go right node = node.right; continue; } } setNodeIsVisited(T.root, false); return result; } function collectNodesPostOrder(T) { let node = T.root; const result = []; let resultLen = 0; while (node !== exports.SENTINEL) { if (getNodeIsVisited(node)) { // going up from this node setNodeIsVisited(node.left, false); setNodeIsVisited(node.right, false); node = node.parent; continue; } if (node.left !== exports.SENTINEL && !getNodeIsVisited(node.left)) { // go left node = node.left; continue; } if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) { // go right node = node.right; continue; } // handle current node result[resultLen++] = node; setNodeIsVisited(node, true); } setNodeIsVisited(T.root, false); return result; } function search(T, filterOwnerId, filterOutValidation, cachedVersionId) { let node = T.root; let delta = 0; let nodeStart = 0; let nodeEnd = 0; const result = []; let resultLen = 0; while (node !== exports.SENTINEL) { if (getNodeIsVisited(node)) { // going up from this node setNodeIsVisited(node.left, false); setNodeIsVisited(node.right, false); if (node === node.parent.right) { delta -= node.parent.delta; } node = node.parent; continue; } if (node.left !== exports.SENTINEL && !getNodeIsVisited(node.left)) { // go left node = node.left; continue; } // handle current node nodeStart = delta + node.start; nodeEnd = delta + node.end; node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId); let include = true; if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) { include = false; } if (filterOutValidation && getNodeIsForValidation(node)) { include = false; } if (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; const result = []; let resultLen = 0; while (node !== exports.SENTINEL) { if (getNodeIsVisited(node)) { // going up from this node setNodeIsVisited(node.left, false); setNodeIsVisited(node.right, false); if (node === node.parent.right) { delta -= node.parent.delta; } node = node.parent; continue; } if (!getNodeIsVisited(node.left)) { // first time seeing this node nodeMaxEnd = delta + node.maxEnd; if (nodeMaxEnd < intervalStart) { // cover case b) from above // there is no need to search this node or its children setNodeIsVisited(node, true); continue; } if (node.left !== exports.SENTINEL) { // go left node = node.left; continue; } } // handle current node nodeStart = delta + node.start; if (nodeStart > intervalEnd) { // cover case a) from above // there is no need to search this node or its right subtree setNodeIsVisited(node, true); continue; } nodeEnd = delta + node.end; if (nodeEnd >= intervalStart) { // There is overlap node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId); let include = true; if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) { include = false; } if (filterOutValidation && getNodeIsForValidation(node)) { include = false; } if (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; } const 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[418/*vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase*/], __M([1/*require*/,0/*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) { const y = x.right; // fix size_left y.size_left += x.size_left + (x.piece ? x.piece.length : 0); y.lf_left += x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0); x.right = y.left; if (y.left !== exports.SENTINEL) { y.left.parent = x; } y.parent = x.parent; if (x.parent === exports.SENTINEL) { tree.root = y; } else if (x.parent.left === x) { x.parent.left = y; } else { x.parent.right = y; } y.left = x; x.parent = y; } exports.leftRotate = leftRotate; function rightRotate(tree, y) { const x = y.left; y.left = x.right; if (x.right !== exports.SENTINEL) { x.right.parent = y; } x.parent = y.parent; // fix size_left y.size_left -= x.size_left + (x.piece ? x.piece.length : 0); y.lf_left -= x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0); if (y.parent === exports.SENTINEL) { tree.root = x; } else if (y === y.parent.right) { y.parent.right = x; } else { y.parent.left = x; } x.right = y; y.parent = x; } 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; } const 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) { const newSizeLeft = calculateSize(x); const newLFLeft = calculateLF(x); if (newSizeLeft !== x.parent.size_left || newLFLeft !== x.parent.lf_left) { const delta = newSizeLeft - x.parent.size_left; const lf_delta = newLFLeft - x.parent.lf_left; x.parent.size_left = newSizeLeft; x.parent.lf_left = newLFLeft; updateTreeMetadata(tree, x.parent, delta, lf_delta); } } recomputeTreeMetadata(tree, x.parent); if (yWasRed) { resetSentinel(); return; } // RB-DELETE-FIXUP let w; while (x !== tree.root && x.color === 0 /* 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; } // 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[242/*vs/editor/common/model/prefixSumComputer*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,139/*vs/base/common/uint*/]), function (require, exports, arrays_1, uint_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PrefixSumIndexOfResult = exports.ConstantTimePrefixSumComputer = exports.PrefixSumComputer = void 0; class PrefixSumComputer { constructor(values) { this.values = values; this.prefixSum = new Uint32Array(values.length); this.prefixSumValidIndex = new Int32Array(1); this.prefixSumValidIndex[0] = -1; } insertValues(insertIndex, insertValues) { insertIndex = (0, uint_1.toUint32)(insertIndex); const oldValues = this.values; const oldPrefixSum = this.prefixSum; const insertValuesLen = insertValues.length; if (insertValuesLen === 0) { return false; } this.values = new Uint32Array(oldValues.length + insertValuesLen); this.values.set(oldValues.subarray(0, insertIndex), 0); this.values.set(oldValues.subarray(insertIndex), insertIndex + insertValuesLen); this.values.set(insertValues, insertIndex); if (insertIndex - 1 < this.prefixSumValidIndex[0]) { this.prefixSumValidIndex[0] = insertIndex - 1; } this.prefixSum = new Uint32Array(this.values.length); if (this.prefixSumValidIndex[0] >= 0) { this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1)); } return true; } setValue(index, value) { index = (0, uint_1.toUint32)(index); value = (0, uint_1.toUint32)(value); if (this.values[index] === value) { return false; } this.values[index] = value; if (index - 1 < this.prefixSumValidIndex[0]) { this.prefixSumValidIndex[0] = index - 1; } return true; } removeValues(startIndex, count) { startIndex = (0, uint_1.toUint32)(startIndex); count = (0, uint_1.toUint32)(count); const oldValues = this.values; const oldPrefixSum = this.prefixSum; if (startIndex >= oldValues.length) { return false; } const maxCount = oldValues.length - startIndex; if (count >= maxCount) { count = maxCount; } if (count === 0) { return false; } this.values = new Uint32Array(oldValues.length - count); this.values.set(oldValues.subarray(0, startIndex), 0); this.values.set(oldValues.subarray(startIndex + count), startIndex); this.prefixSum = new Uint32Array(this.values.length); if (startIndex - 1 < this.prefixSumValidIndex[0]) { this.prefixSumValidIndex[0] = startIndex - 1; } if (this.prefixSumValidIndex[0] >= 0) { this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1)); } return true; } getTotalSum() { if (this.values.length === 0) { return 0; } return this._getPrefixSum(this.values.length - 1); } /** * Returns the sum of the first `index + 1` many items. * @returns `SUM(0 <= j <= index, values[j])`. */ getPrefixSum(index) { if (index < 0) { return 0; } index = (0, uint_1.toUint32)(index); return this._getPrefixSum(index); } _getPrefixSum(index) { if (index <= this.prefixSumValidIndex[0]) { return this.prefixSum[index]; } let startIndex = this.prefixSumValidIndex[0] + 1; if (startIndex === 0) { this.prefixSum[0] = this.values[0]; startIndex++; } if (index >= this.values.length) { index = this.values.length - 1; } for (let i = startIndex; i <= index; i++) { this.prefixSum[i] = this.prefixSum[i - 1] + this.values[i]; } this.prefixSumValidIndex[0] = Math.max(this.prefixSumValidIndex[0], index); return this.prefixSum[index]; } getIndexOf(sum) { sum = Math.floor(sum); // Compute all sums (to get a fully valid prefixSum) this.getTotalSum(); let low = 0; let high = this.values.length - 1; let mid = 0; let midStop = 0; let midStart = 0; while (low <= high) { mid = low + ((high - low) / 2) | 0; midStop = this.prefixSum[mid]; midStart = midStop - this.values[mid]; if (sum < midStart) { high = mid - 1; } else if (sum >= midStop) { low = mid + 1; } else { break; } } return new PrefixSumIndexOfResult(mid, sum - midStart); } } exports.PrefixSumComputer = PrefixSumComputer; /** * {@link getIndexOf} has an amortized runtime complexity of O(1). * * ({@link PrefixSumComputer.getIndexOf} is just O(log n)) */ class ConstantTimePrefixSumComputer { constructor(values) { this._values = values; this._isValid = false; this._validEndIndex = -1; this._prefixSum = []; this._indexBySum = []; } /** * @returns SUM(0 <= j < values.length, values[j]) */ getTotalSum() { this._ensureValid(); return this._indexBySum.length; } /** * Returns the sum of the first `count` many items. * @returns `SUM(0 <= j < count, values[j])`. */ getPrefixSum(count) { this._ensureValid(); if (count === 0) { return 0; } return this._prefixSum[count - 1]; } /** * @returns `result`, such that `getPrefixSum(result.index) + result.remainder = sum` */ getIndexOf(sum) { this._ensureValid(); const idx = this._indexBySum[sum]; const viewLinesAbove = idx > 0 ? this._prefixSum[idx - 1] : 0; return new PrefixSumIndexOfResult(idx, sum - viewLinesAbove); } removeValues(start, deleteCount) { this._values.splice(start, deleteCount); this._invalidate(start); } insertValues(insertIndex, insertArr) { this._values = (0, arrays_1.arrayInsert)(this._values, insertIndex, insertArr); this._invalidate(insertIndex); } _invalidate(index) { this._isValid = false; this._validEndIndex = Math.min(this._validEndIndex, index - 1); } _ensureValid() { if (this._isValid) { return; } for (let i = this._validEndIndex + 1, len = this._values.length; i < len; i++) { const value = this._values[i]; const sumAbove = i > 0 ? this._prefixSum[i - 1] : 0; this._prefixSum[i] = sumAbove + value; for (let j = 0; j < value; j++) { this._indexBySum[sumAbove + j] = i; } } // trim things this._prefixSum.length = this._values.length; this._indexBySum.length = this._prefixSum[this._prefixSum.length - 1]; // mark as valid this._isValid = true; this._validEndIndex = this._values.length - 1; } setValue(index, value) { if (this._values[index] === value) { // no change return; } this._values[index] = value; this._invalidate(index); } } exports.ConstantTimePrefixSumComputer = ConstantTimePrefixSumComputer; class PrefixSumIndexOfResult { constructor(index, remainder) { this.index = index; this.remainder = remainder; this._prefixSumIndexOfResultBrand = undefined; this.index = index; this.remainder = remainder; } } exports.PrefixSumIndexOfResult = PrefixSumIndexOfResult; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[419/*vs/editor/common/model/mirrorTextModel*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,11/*vs/editor/common/core/position*/,242/*vs/editor/common/model/prefixSumComputer*/]), function (require, exports, strings_1, position_1, prefixSumComputer_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MirrorTextModel = void 0; class MirrorTextModel { constructor(uri, lines, eol, versionId) { this._uri = uri; this._lines = lines; this._eol = eol; this._versionId = versionId; this._lineStarts = null; this._cachedTextValue = null; } dispose() { this._lines.length = 0; } get version() { return this._versionId; } getText() { if (this._cachedTextValue === null) { this._cachedTextValue = this._lines.join(this._eol); } return this._cachedTextValue; } onEvents(e) { if (e.eol && e.eol !== this._eol) { this._eol = e.eol; this._lineStarts = null; } // Update my lines const changes = e.changes; for (const change of changes) { this._acceptDeleteRange(change.range); this._acceptInsertText(new position_1.Position(change.range.startLineNumber, change.range.startColumn), change.text); } this._versionId = e.versionId; this._cachedTextValue = null; } _ensureLineStarts() { if (!this._lineStarts) { const eolLength = this._eol.length; const linesLength = this._lines.length; const lineStartValues = new Uint32Array(linesLength); for (let i = 0; i < linesLength; i++) { lineStartValues[i] = this._lines[i].length + eolLength; } this._lineStarts = new prefixSumComputer_1.PrefixSumComputer(lineStartValues); } } /** * All changes to a line's text go through this method */ _setLineText(lineIndex, newValue) { this._lines[lineIndex] = newValue; if (this._lineStarts) { // update prefix sum this._lineStarts.setValue(lineIndex, this._lines[lineIndex].length + this._eol.length); } } _acceptDeleteRange(range) { if (range.startLineNumber === range.endLineNumber) { if (range.startColumn === range.endColumn) { // Nothing to delete return; } // Delete text on the affected line this._setLineText(range.startLineNumber - 1, this._lines[range.startLineNumber - 1].substring(0, range.startColumn - 1) + this._lines[range.startLineNumber - 1].substring(range.endColumn - 1)); return; } // Take remaining text on last line and append it to remaining text on first line this._setLineText(range.startLineNumber - 1, this._lines[range.startLineNumber - 1].substring(0, range.startColumn - 1) + this._lines[range.endLineNumber - 1].substring(range.endColumn - 1)); // Delete middle lines this._lines.splice(range.startLineNumber, range.endLineNumber - range.startLineNumber); if (this._lineStarts) { // update prefix sum this._lineStarts.removeValues(range.startLineNumber, range.endLineNumber - range.startLineNumber); } } _acceptInsertText(position, insertText) { if (insertText.length === 0) { // Nothing to insert return; } const insertLines = (0, strings_1.splitLines)(insertText); if (insertLines.length === 1) { // Inserting text on one line this._setLineText(position.lineNumber - 1, this._lines[position.lineNumber - 1].substring(0, position.column - 1) + insertLines[0] + this._lines[position.lineNumber - 1].substring(position.column - 1)); return; } // Append overflowing text from first line to the end of text to insert insertLines[insertLines.length - 1] += this._lines[position.lineNumber - 1].substring(position.column - 1); // Delete overflowing text from first line and insert text on first line this._setLineText(position.lineNumber - 1, this._lines[position.lineNumber - 1].substring(0, position.column - 1) + insertLines[0]); // Insert new lines & store lengths const newLengths = new Uint32Array(insertLines.length - 1); for (let i = 1; i < insertLines.length; i++) { this._lines.splice(position.lineNumber + i - 1, 0, insertLines[i]); newLengths[i - 1] = insertLines[i].length + this._eol.length; } if (this._lineStarts) { // update prefix sum this._lineStarts.insertValues(position.lineNumber, newLengths); } } } exports.MirrorTextModel = MirrorTextModel; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[420/*vs/editor/common/model/textModelPart*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TextModelPart = void 0; class TextModelPart { constructor() { this._isDisposed = false; } dispose() { this._isDisposed = true; } assertNotDisposed() { if (this._isDisposed) { throw new Error('TextModelPart is disposed!'); } } } exports.TextModelPart = TextModelPart; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[150/*vs/editor/common/model/textModelSearch*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,118/*vs/editor/common/core/wordCharacterClassifier*/,11/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,49/*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.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 model_1.SearchData(regex, this.wordSeparators ? (0, wordCharacterClassifier_1.getMapForWordSeparators)(this.wordSeparators) : null, canUseSimpleSearch ? this.searchString : null); } } exports.SearchParams = SearchParams; function isMultilineRegexSource(searchString) { if (!searchString || searchString.length === 0) { return false; } for (let i = 0, len = searchString.length; i < len; i++) { const chCode = searchString.charCodeAt(i); if (chCode === 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 */) { return true; } } } return false; } exports.isMultilineRegexSource = isMultilineRegexSource; function createFindMatch(range, rawMatches, captureMatches) { if (!captureMatches) { return new model_1.FindMatch(range, null); } const matches = []; for (let i = 0, len = rawMatches.length; i < len; i++) { matches[i] = rawMatches[i]; } return new model_1.FindMatch(range, matches); } exports.createFindMatch = createFindMatch; class LineFeedCounter { constructor(text) { const 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) { const lineFeedCountBeforeEndOfMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex + match0.length); const lineFeedCountInMatch = lineFeedCountBeforeEndOfMatch - lineFeedCountBeforeMatch; endOffset = startOffset + match0.length + lineFeedCountInMatch /* add as many \r as there were \n */; } else { endOffset = startOffset + match0.length; } const startPosition = model.getPositionAt(startOffset); const endPosition = model.getPositionAt(endOffset); return new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column); } static _doFindMatchesMultiline(model, searchRange, searcher, captureMatches, limitResultCount) { const deltaOffset = model.getOffsetAt(searchRange.getStartPosition()); // We always execute multiline search over the lines joined with \n // This makes it that \n will match the EOL for both CRLF and LF models // We compensate for offset errors in `_getMultilineMatchRange` const text = model.getValueInRange(searchRange, 1 /* 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[243/*vs/editor/common/languages/unicodeTextModelHighlighter*/], __M([1/*require*/,0/*exports*/,3/*vs/editor/common/core/range*/,150/*vs/editor/common/model/textModelSearch*/,8/*vs/base/common/strings*/,20/*vs/base/common/types*/]), function (require, exports, range_1, textModelSearch_1, strings, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UnicodeTextModelHighlighter = void 0; class UnicodeTextModelHighlighter { static computeUnicodeHighlights(model, options, range) { const startLine = range ? range.startLineNumber : 1; const endLine = range ? range.endLineNumber : model.getLineCount(); const codePointHighlighter = new CodePointHighlighter(options); const candidates = codePointHighlighter.getCandidateCodePoints(); let regex; if (candidates === 'allNonBasicAscii') { regex = new RegExp('[^\\t\\n\\r\\x20-\\x7E]', 'g'); } else { regex = new RegExp(`${buildRegExpCharClassExpr(Array.from(candidates))}`, 'g'); } const searcher = new textModelSearch_1.Searcher(null, regex); const ranges = []; let hasMore = false; let m; let ambiguousCharacterCount = 0; let invisibleCharacterCount = 0; let nonBasicAsciiCharacterCount = 0; forLoop: for (let lineNumber = startLine, lineCount = endLine; lineNumber <= lineCount; lineNumber++) { const lineContent = model.getLineContent(lineNumber); const lineLength = lineContent.length; // Reset regex to search from the beginning searcher.reset(0); do { m = searcher.next(lineContent); if (m) { let startIndex = m.index; let endIndex = m.index + m[0].length; // Extend range to entire code point if (startIndex > 0) { const charCodeBefore = lineContent.charCodeAt(startIndex - 1); if (strings.isHighSurrogate(charCodeBefore)) { startIndex--; } } if (endIndex + 1 < lineLength) { const charCodeBefore = lineContent.charCodeAt(endIndex - 1); if (strings.isHighSurrogate(charCodeBefore)) { endIndex++; } } const str = lineContent.substring(startIndex, endIndex); const highlightReason = codePointHighlighter.shouldHighlightNonBasicASCII(str); if (highlightReason !== 0 /* None */) { if (highlightReason === 3 /* Ambiguous */) { ambiguousCharacterCount++; } else if (highlightReason === 2 /* Invisible */) { invisibleCharacterCount++; } else if (highlightReason === 1 /* NonBasicASCII */) { nonBasicAsciiCharacterCount++; } else { (0, types_1.assertNever)(highlightReason); } const MAX_RESULT_LENGTH = 1000; if (ranges.length >= MAX_RESULT_LENGTH) { hasMore = true; break forLoop; } ranges.push(new range_1.Range(lineNumber, startIndex + 1, lineNumber, endIndex + 1)); } } } while (m); } return { ranges, hasMore, ambiguousCharacterCount, invisibleCharacterCount, nonBasicAsciiCharacterCount }; } static computeUnicodeHighlightReason(char, options) { const codePointHighlighter = new CodePointHighlighter(options); const reason = codePointHighlighter.shouldHighlightNonBasicASCII(char); switch (reason) { case 0 /* None */: return null; case 2 /* Invisible */: return { kind: 1 /* Invisible */ }; case 3 /* Ambiguous */: { const codePoint = char.codePointAt(0); const primaryConfusable = codePointHighlighter.ambiguousCharacters.getPrimaryConfusable(codePoint); const notAmbiguousInLocales = strings.AmbiguousCharacters.getLocales().filter((l) => !strings.AmbiguousCharacters.getInstance(new Set([...options.allowedLocales, l])).isAmbiguous(codePoint)); return { kind: 0 /* Ambiguous */, confusableWith: String.fromCodePoint(primaryConfusable), notAmbiguousInLocales }; } case 1 /* NonBasicASCII */: return { kind: 2 /* NonBasicAscii */ }; } } } exports.UnicodeTextModelHighlighter = UnicodeTextModelHighlighter; function buildRegExpCharClassExpr(codePoints, flags) { const src = `[${strings.escapeRegExpCharacters(codePoints.map((i) => String.fromCodePoint(i)).join(''))}]`; return src; } class CodePointHighlighter { constructor(options) { this.options = options; this.allowedCodePoints = new Set(options.allowedCodePoints); this.ambiguousCharacters = strings.AmbiguousCharacters.getInstance(new Set(options.allowedLocales)); } getCandidateCodePoints() { if (this.options.nonBasicASCII) { return 'allNonBasicAscii'; } const set = new Set(); if (this.options.invisibleCharacters) { for (const cp of strings.InvisibleCharacters.codePoints) { set.add(cp); } } if (this.options.ambiguousCharacters) { for (const cp of this.ambiguousCharacters.getConfusableCodePoints()) { set.add(cp); } } for (const cp of this.allowedCodePoints) { set.delete(cp); } return set; } shouldHighlightNonBasicASCII(character) { const codePoint = character.codePointAt(0); if (this.allowedCodePoints.has(codePoint)) { return 0 /* None */; } if (this.options.nonBasicASCII) { return 1 /* NonBasicASCII */; } if (this.options.invisibleCharacters) { const isAllowedInvisibleCharacter = character === ' ' || character === '\n' || character === '\t'; // TODO check for emojis if (!isAllowedInvisibleCharacter && strings.InvisibleCharacters.isInvisibleCharacter(codePoint)) { return 2 /* Invisible */; } } if (this.options.ambiguousCharacters) { if (this.ambiguousCharacters.isAmbiguous(codePoint)) { return 3 /* Ambiguous */; } } return 0 /* 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[244/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/], __M([1/*require*/,0/*exports*/,11/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,49/*vs/editor/common/model*/,418/*vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase*/,150/*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) { const r = [0]; let 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--) { const nodePos = this._cache[i]; if (nodePos.nodeStartOffset <= offset && nodePos.nodeStartOffset + nodePos.node.piece.length >= offset) { return nodePos; } } return null; } get2(lineNumber) { for (let i = this._cache.length - 1; i >= 0; i--) { const nodePos = this._cache[i]; if (nodePos.nodeStartLineNumber && nodePos.nodeStartLineNumber < lineNumber && nodePos.nodeStartLineNumber + nodePos.node.piece.lineFeedCnt >= lineNumber) { return nodePos; } } return null; } set(nodePosition) { if (this._cache.length >= this._limit) { this._cache.shift(); } this._cache.push(nodePosition); } validate(offset) { let hasInvalidVal = false; const tmp = this._cache; for (let i = 0; i < tmp.length; i++) { const nodePos = tmp[i]; if (nodePos.node.parent === null || nodePos.nodeStartOffset >= offset) { tmp[i] = null; hasInvalidVal = true; continue; } } if (hasInvalidVal) { const newArr = []; for (const entry of tmp) { if (entry !== null) { newArr.push(entry); } } this._cache = newArr; } } } class PieceTreeBase { constructor(chunks, eol, eolNormalized) { this.create(chunks, eol, eolNormalized); } create(chunks, eol, eolNormalized) { this._buffers = [ new StringBuffer('', [0]) ]; this._lastChangeBufferPos = { line: 0, column: 0 }; this.root = rbTreeBase_1.SENTINEL; this._lineCnt = 1; this._length = 0; this._EOL = eol; this._EOLLength = eol.length; this._EOLNormalized = eolNormalized; let lastNode = null; for (let i = 0, len = chunks.length; i < len; i++) { if (chunks[i].buffer.length > 0) { if (!chunks[i].lineStarts) { chunks[i].lineStarts = createLineStartsFast(chunks[i].buffer); } const piece = new Piece(i + 1, { line: 0, column: 0 }, { line: chunks[i].lineStarts.length - 1, column: chunks[i].buffer.length - chunks[i].lineStarts[chunks[i].lineStarts.length - 1] }, chunks[i].lineStarts.length - 1, chunks[i].buffer.length); this._buffers.push(chunks[i]); lastNode = this.rbInsertRight(lastNode, piece); } } this._searchCache = new PieceTreeSearchCache(1); this._lastVisitedLine = { lineNumber: 0, value: '' }; this.computeBufferMetadata(); } normalizeEOL(eol) { const averageBufferSize = exports.AverageBufferSize; const min = averageBufferSize - Math.floor(averageBufferSize / 3); const max = min * 2; let tempChunk = ''; let tempChunkLen = 0; const chunks = []; this.iterate(this.root, node => { const str = this.getNodeContent(node); const len = str.length; if (tempChunkLen <= min || tempChunkLen + len < max) { tempChunk += str; tempChunkLen += len; return true; } // flush anyways const text = tempChunk.replace(/\r\n|\r|\n/g, eol); chunks.push(new StringBuffer(text, createLineStartsFast(text))); tempChunk = str; tempChunkLen = len; return true; }); if (tempChunkLen > 0) { const text = tempChunk.replace(/\r\n|\r|\n/g, eol); chunks.push(new StringBuffer(text, createLineStartsFast(text))); } this.create(chunks, eol, true); } // #region Buffer API getEOL() { return this._EOL; } setEOL(newEOL) { this._EOL = newEOL; this._EOLLength = this._EOL.length; this.normalizeEOL(newEOL); } createSnapshot(BOM) { return new PieceTreeSnapshot(this, BOM); } getOffsetAt(lineNumber, column) { let leftLen = 0; // inorder let x = this.root; while (x !== rbTreeBase_1.SENTINEL) { if (x.left !== rbTreeBase_1.SENTINEL && x.lf_left + 1 >= lineNumber) { x = x.left; } else if (x.lf_left + x.piece.lineFeedCnt + 1 >= lineNumber) { leftLen += x.size_left; // lineNumber >= 2 const accumualtedValInCurrentIndex = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2); return leftLen += accumualtedValInCurrentIndex + column - 1; } else { lineNumber -= x.lf_left + x.piece.lineFeedCnt; leftLen += x.size_left + x.piece.length; x = x.right; } } return leftLen; } getPositionAt(offset) { offset = Math.floor(offset); offset = Math.max(0, offset); let x = this.root; let lfCnt = 0; const originalOffset = offset; while (x !== rbTreeBase_1.SENTINEL) { if (x.size_left !== 0 && x.size_left >= offset) { x = x.left; } else if (x.size_left + x.piece.length >= offset) { const out = this.getIndexOf(x, offset - x.size_left); lfCnt += x.lf_left + out.index; if (out.index === 0) { const lineStartOffset = this.getOffsetAt(lfCnt + 1, 1); const column = originalOffset - lineStartOffset; return new position_1.Position(lfCnt + 1, column + 1); } return new position_1.Position(lfCnt + 1, out.remainder + 1); } else { offset -= x.size_left + x.piece.length; lfCnt += x.lf_left + x.piece.lineFeedCnt; if (x.right === rbTreeBase_1.SENTINEL) { // last node const lineStartOffset = this.getOffsetAt(lfCnt + 1, 1); const column = originalOffset - offset - lineStartOffset; return new position_1.Position(lfCnt + 1, column + 1); } else { x = x.right; } } } return new position_1.Position(1, 1); } getValueInRange(range, eol) { if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) { return ''; } const startPosition = this.nodeAt2(range.startLineNumber, range.startColumn); const endPosition = this.nodeAt2(range.endLineNumber, range.endColumn); const value = this.getValueInRange2(startPosition, endPosition); if (eol) { if (eol !== this._EOL || !this._EOLNormalized) { return value.replace(/\r\n|\r|\n/g, eol); } if (eol === this.getEOL() && this._EOLNormalized) { if (eol === '\r\n') { } return value; } return value.replace(/\r\n|\r|\n/g, eol); } return value; } getValueInRange2(startPosition, endPosition) { if (startPosition.node === endPosition.node) { const node = startPosition.node; const buffer = this._buffers[node.piece.bufferIndex].buffer; const startOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start); return buffer.substring(startOffset + startPosition.remainder, startOffset + endPosition.remainder); } let x = startPosition.node; const buffer = this._buffers[x.piece.bufferIndex].buffer; const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); let ret = buffer.substring(startOffset + startPosition.remainder, startOffset + x.piece.length); x = x.next(); while (x !== rbTreeBase_1.SENTINEL) { const buffer = this._buffers[x.piece.bufferIndex].buffer; const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); if (x === endPosition.node) { ret += buffer.substring(startOffset, startOffset + endPosition.remainder); break; } else { ret += buffer.substr(startOffset, x.piece.length); } x = x.next(); } return ret; } getLinesContent() { const lines = []; let linesLength = 0; let currentLine = ''; let danglingCR = false; this.iterate(this.root, node => { if (node === rbTreeBase_1.SENTINEL) { return true; } const piece = node.piece; let pieceLength = piece.length; if (pieceLength === 0) { return true; } const buffer = this._buffers[piece.bufferIndex].buffer; const lineStarts = this._buffers[piece.bufferIndex].lineStarts; const pieceStartLine = piece.start.line; const pieceEndLine = piece.end.line; let pieceStartOffset = lineStarts[pieceStartLine] + piece.start.column; if (danglingCR) { if (buffer.charCodeAt(pieceStartOffset) === 10 /* 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. const matchingNode = nodePos.node.next(); if (!matchingNode) { return 0; } const buffer = this._buffers[matchingNode.piece.bufferIndex]; const startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start); return buffer.buffer.charCodeAt(startOffset); } else { const buffer = this._buffers[nodePos.node.piece.bufferIndex]; const startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start); const targetOffset = startOffset + nodePos.remainder; return buffer.buffer.charCodeAt(targetOffset); } } getLineCharCode(lineNumber, index) { const nodePos = this.nodeAt2(lineNumber, index + 1); return this._getCharCode(nodePos); } getLineLength(lineNumber) { if (lineNumber === this.getLineCount()) { const startOffset = this.getOffsetAt(lineNumber, 1); return this.getLength() - startOffset; } return this.getOffsetAt(lineNumber + 1, 1) - this.getOffsetAt(lineNumber, 1) - this._EOLLength; } findMatchesInNode(node, searcher, startLineNumber, startColumn, startCursor, endCursor, searchData, captureMatches, limitResultCount, resultLen, result) { const buffer = this._buffers[node.piece.bufferIndex]; const startOffsetInBuffer = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start); const start = this.offsetInBuffer(node.piece.bufferIndex, startCursor); const end = this.offsetInBuffer(node.piece.bufferIndex, endCursor); let m; // Reset regex to search from the beginning const ret = { line: 0, column: 0 }; let searchText; let offsetInBuffer; if (searcher._wordSeparators) { searchText = buffer.buffer.substring(start, end); offsetInBuffer = (offset) => offset + start; searcher.reset(0); } else { searchText = buffer.buffer; offsetInBuffer = (offset) => offset; searcher.reset(start); } do { m = searcher.next(searchText); if (m) { if (offsetInBuffer(m.index) >= end) { return resultLen; } this.positionInBuffer(node, offsetInBuffer(m.index) - startOffsetInBuffer, ret); const lineFeedCnt = this.getLineFeedCnt(node.piece.bufferIndex, startCursor, ret); const retStartColumn = ret.line === startCursor.line ? ret.column - startCursor.column + startColumn : ret.column + 1; const retEndColumn = retStartColumn + m[0].length; result[resultLen++] = (0, textModelSearch_1.createFindMatch)(new range_1.Range(startLineNumber + lineFeedCnt, retStartColumn, startLineNumber + lineFeedCnt, retEndColumn), m, captureMatches); if (offsetInBuffer(m.index) + m[0].length >= end) { return resultLen; } if (resultLen >= limitResultCount) { return resultLen; } } } while (m); return resultLen; } findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) { const result = []; let resultLen = 0; const searcher = new textModelSearch_1.Searcher(searchData.wordSeparators, searchData.regex); let startPosition = this.nodeAt2(searchRange.startLineNumber, searchRange.startColumn); if (startPosition === null) { return []; } const endPosition = this.nodeAt2(searchRange.endLineNumber, searchRange.endColumn); if (endPosition === null) { return []; } let start = this.positionInBuffer(startPosition.node, startPosition.remainder); const end = this.positionInBuffer(endPosition.node, endPosition.remainder); if (startPosition.node === endPosition.node) { this.findMatchesInNode(startPosition.node, searcher, searchRange.startLineNumber, searchRange.startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result); return result; } let startLineNumber = searchRange.startLineNumber; let currentNode = startPosition.node; while (currentNode !== endPosition.node) { const lineBreakCnt = this.getLineFeedCnt(currentNode.piece.bufferIndex, start, currentNode.piece.end); if (lineBreakCnt >= 1) { // last line break position const lineStarts = this._buffers[currentNode.piece.bufferIndex].lineStarts; const startOffsetInBuffer = this.offsetInBuffer(currentNode.piece.bufferIndex, currentNode.piece.start); const nextLineStartOffset = lineStarts[start.line + lineBreakCnt]; const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1; resultLen = this.findMatchesInNode(currentNode, searcher, startLineNumber, startColumn, start, this.positionInBuffer(currentNode, nextLineStartOffset - startOffsetInBuffer), searchData, captureMatches, limitResultCount, resultLen, result); if (resultLen >= limitResultCount) { return result; } startLineNumber += lineBreakCnt; } const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0; // search for the remaining content if (startLineNumber === searchRange.endLineNumber) { const text = this.getLineContent(startLineNumber).substring(startColumn, searchRange.endColumn - 1); resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn, resultLen, result, captureMatches, limitResultCount); return result; } resultLen = this._findMatchesInLine(searchData, searcher, this.getLineContent(startLineNumber).substr(startColumn), startLineNumber, startColumn, resultLen, result, captureMatches, limitResultCount); if (resultLen >= limitResultCount) { return result; } startLineNumber++; startPosition = this.nodeAt2(startLineNumber, 1); currentNode = startPosition.node; start = this.positionInBuffer(startPosition.node, startPosition.remainder); } if (startLineNumber === searchRange.endLineNumber) { const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0; const text = this.getLineContent(startLineNumber).substring(startColumn, searchRange.endColumn - 1); resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn, resultLen, result, captureMatches, limitResultCount); return result; } const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1; resultLen = this.findMatchesInNode(endPosition.node, searcher, startLineNumber, startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result); return result; } _findMatchesInLine(searchData, searcher, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) { const wordSeparators = searchData.wordSeparators; if (!captureMatches && searchData.simpleSearch) { const searchString = searchData.simpleSearch; const searchStringLen = searchString.length; const textLength = text.length; let lastMatchIndex = -searchStringLen; while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) { if (!wordSeparators || (0, textModelSearch_1.isValidMatch)(wordSeparators, text, textLength, lastMatchIndex, searchStringLen)) { result[resultLen++] = new model_1.FindMatch(new range_1.Range(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null); if (resultLen >= limitResultCount) { return resultLen; } } } return resultLen; } let m; // Reset regex to search from the beginning searcher.reset(0); do { m = searcher.next(text); if (m) { result[resultLen++] = (0, textModelSearch_1.createFindMatch)(new range_1.Range(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset), m, captureMatches); if (resultLen >= limitResultCount) { return resultLen; } } } while (m); return resultLen; } // #endregion // #region Piece Table insert(offset, value, eolNormalized = false) { this._EOLNormalized = this._EOLNormalized && eolNormalized; this._lastVisitedLine.lineNumber = 0; this._lastVisitedLine.value = ''; if (this.root !== rbTreeBase_1.SENTINEL) { const { node, remainder, nodeStartOffset } = this.nodeAt(offset); const piece = node.piece; const bufferIndex = piece.bufferIndex; const insertPosInBuffer = this.positionInBuffer(node, remainder); if (node.piece.bufferIndex === 0 && piece.end.line === this._lastChangeBufferPos.line && piece.end.column === this._lastChangeBufferPos.column && (nodeStartOffset + piece.length === offset) && value.length < 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. const nodesToDel = []; let newRightPiece = new Piece(piece.bufferIndex, insertPosInBuffer, piece.end, this.getLineFeedCnt(piece.bufferIndex, insertPosInBuffer, piece.end), this.offsetInBuffer(bufferIndex, piece.end) - this.offsetInBuffer(bufferIndex, insertPosInBuffer)); if (this.shouldCheckCRLF() && this.endWithCR(value)) { const headOfRight = this.nodeCharCodeAt(node, remainder); if (headOfRight === 10 /** \n */) { const newStart = { line: newRightPiece.start.line + 1, column: 0 }; newRightPiece = new Piece(newRightPiece.bufferIndex, newStart, newRightPiece.end, this.getLineFeedCnt(newRightPiece.bufferIndex, newStart, newRightPiece.end), newRightPiece.length - 1); value += '\n'; } } // reuse node for content before insertion point. if (this.shouldCheckCRLF() && this.startWithLF(value)) { const tailOfLeft = this.nodeCharCodeAt(node, remainder - 1); if (tailOfLeft === 13 /** \r */) { const previousPos = this.positionInBuffer(node, remainder - 1); this.deleteNodeTail(node, previousPos); value = '\r' + value; if (node.piece.length === 0) { nodesToDel.push(node); } } else { this.deleteNodeTail(node, insertPosInBuffer); } } else { this.deleteNodeTail(node, insertPosInBuffer); } const newPieces = this.createNewPieces(value); if (newRightPiece.length > 0) { this.rbInsertRight(node, newRightPiece); } let tmpNode = node; for (let k = 0; k < newPieces.length; k++) { tmpNode = this.rbInsertRight(tmpNode, newPieces[k]); } this.deleteNodes(nodesToDel); } else { this.insertContentToNodeRight(value, node); } } else { // insert new node const pieces = this.createNewPieces(value); let node = this.rbInsertLeft(null, pieces[0]); for (let k = 1; k < pieces.length; k++) { node = this.rbInsertRight(node, pieces[k]); } } // todo, this is too brutal. Total line feed count should be updated the same way as lf_left. this.computeBufferMetadata(); } delete(offset, cnt) { this._lastVisitedLine.lineNumber = 0; this._lastVisitedLine.value = ''; if (cnt <= 0 || this.root === rbTreeBase_1.SENTINEL) { return; } const startPosition = this.nodeAt(offset); const endPosition = this.nodeAt(offset + cnt); const startNode = startPosition.node; const endNode = endPosition.node; if (startNode === endNode) { const startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder); const endSplitPosInBuffer = this.positionInBuffer(startNode, endPosition.remainder); if (startPosition.nodeStartOffset === offset) { if (cnt === startNode.piece.length) { // delete node const next = startNode.next(); (0, rbTreeBase_1.rbDelete)(this, startNode); this.validateCRLFWithPrevNode(next); this.computeBufferMetadata(); return; } this.deleteNodeHead(startNode, endSplitPosInBuffer); this._searchCache.validate(offset); this.validateCRLFWithPrevNode(startNode); this.computeBufferMetadata(); return; } if (startPosition.nodeStartOffset + startNode.piece.length === offset + cnt) { this.deleteNodeTail(startNode, startSplitPosInBuffer); this.validateCRLFWithNextNode(startNode); this.computeBufferMetadata(); return; } // delete content in the middle, this node will be splitted to nodes this.shrinkNode(startNode, startSplitPosInBuffer, endSplitPosInBuffer); this.computeBufferMetadata(); return; } const nodesToDel = []; const startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder); this.deleteNodeTail(startNode, startSplitPosInBuffer); this._searchCache.validate(offset); if (startNode.piece.length === 0) { nodesToDel.push(startNode); } // update last touched node const endSplitPosInBuffer = this.positionInBuffer(endNode, endPosition.remainder); this.deleteNodeHead(endNode, endSplitPosInBuffer); if (endNode.piece.length === 0) { nodesToDel.push(endNode); } // delete nodes in between const secondNode = startNode.next(); for (let node = secondNode; node !== rbTreeBase_1.SENTINEL && node !== endNode; node = node.next()) { nodesToDel.push(node); } const prev = startNode.piece.length === 0 ? startNode.prev() : startNode; this.deleteNodes(nodesToDel); this.validateCRLFWithNextNode(prev); this.computeBufferMetadata(); } insertContentToNodeLeft(value, node) { // we are inserting content to the beginning of node const nodesToDel = []; if (this.shouldCheckCRLF() && this.endWithCR(value) && this.startWithLF(node)) { // move `\n` to new node. const piece = node.piece; const newStart = { line: piece.start.line + 1, column: 0 }; const nPiece = new Piece(piece.bufferIndex, newStart, piece.end, this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end), piece.length - 1); node.piece = nPiece; value += '\n'; (0, rbTreeBase_1.updateTreeMetadata)(this, node, -1, -1); if (node.piece.length === 0) { nodesToDel.push(node); } } const newPieces = this.createNewPieces(value); let newNode = this.rbInsertLeft(node, newPieces[newPieces.length - 1]); for (let k = newPieces.length - 2; k >= 0; k--) { newNode = this.rbInsertLeft(newNode, newPieces[k]); } this.validateCRLFWithPrevNode(newNode); this.deleteNodes(nodesToDel); } insertContentToNodeRight(value, node) { // we are inserting to the right of this node. if (this.adjustCarriageReturnFromNext(value, node)) { // move \n to the new node. value += '\n'; } const newPieces = this.createNewPieces(value); const newNode = this.rbInsertRight(node, newPieces[0]); let tmpNode = newNode; for (let k = 1; k < newPieces.length; k++) { tmpNode = this.rbInsertRight(tmpNode, newPieces[k]); } this.validateCRLFWithPrevNode(newNode); } positionInBuffer(node, remainder, ret) { const piece = node.piece; const bufferIndex = node.piece.bufferIndex; const lineStarts = this._buffers[bufferIndex].lineStarts; const startOffset = lineStarts[piece.start.line] + piece.start.column; const offset = startOffset + remainder; // binary search offset between startOffset and endOffset let low = piece.start.line; let high = piece.end.line; let mid = 0; let midStop = 0; let midStart = 0; while (low <= high) { mid = low + ((high - low) / 2) | 0; midStart = lineStarts[mid]; if (mid === high) { break; } midStop = lineStarts[mid + 1]; if (offset < midStart) { high = mid - 1; } else if (offset >= midStop) { low = mid + 1; } else { break; } } if (ret) { ret.line = mid; ret.column = offset - midStart; return null; } return { line: mid, column: offset - midStart }; } getLineFeedCnt(bufferIndex, start, end) { // we don't need to worry about start: abc\r|\n, or abc|\r, or abc|\n, or abc|\r\n doesn't change the fact that, there is one line break after start. // now let's take care of end: abc\r|\n, if end is in between \r and \n, we need to add line feed count by 1 if (end.column === 0) { return end.line - start.line; } const lineStarts = this._buffers[bufferIndex].lineStarts; if (end.line === lineStarts.length - 1) { // it means, there is no \n after end, otherwise, there will be one more lineStart. return end.line - start.line; } const nextLineStartOffset = lineStarts[end.line + 1]; const endOffset = lineStarts[end.line] + end.column; if (nextLineStartOffset > endOffset + 1) { // there are more than 1 character after end, which means it can't be \n return end.line - start.line; } // endOffset + 1 === nextLineStartOffset // character at endOffset is \n, so we check the character before first // if character at endOffset is \r, end.column is 0 and we can't get here. const previousCharOffset = endOffset - 1; // end.column > 0 so it's okay. const buffer = this._buffers[bufferIndex].buffer; if (buffer.charCodeAt(previousCharOffset) === 13) { return end.line - start.line + 1; } else { return end.line - start.line; } } offsetInBuffer(bufferIndex, cursor) { const lineStarts = this._buffers[bufferIndex].lineStarts; return lineStarts[cursor.line] + cursor.column; } deleteNodes(nodes) { for (let i = 0; i < nodes.length; i++) { (0, rbTreeBase_1.rbDelete)(this, nodes[i]); } } createNewPieces(text) { if (text.length > 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 const 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); } const lineStarts = createLineStartsFast(splitText); newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts.length - 1, column: splitText.length - lineStarts[lineStarts.length - 1] }, lineStarts.length - 1, splitText.length)); this._buffers.push(new StringBuffer(splitText, lineStarts)); } const lineStarts = createLineStartsFast(text); newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts.length - 1, column: text.length - lineStarts[lineStarts.length - 1] }, lineStarts.length - 1, text.length)); this._buffers.push(new StringBuffer(text, lineStarts)); return newPieces; } let startOffset = this._buffers[0].buffer.length; const lineStarts = createLineStartsFast(text, false); let start = this._lastChangeBufferPos; if (this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 1] === startOffset && startOffset !== 0 && this.startWithLF(text) && this.endWithCR(this._buffers[0].buffer) // todo, we can check this._lastChangeBufferPos's column as it's the last one ) { this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line, column: this._lastChangeBufferPos.column + 1 }; start = this._lastChangeBufferPos; for (let i = 0; i < lineStarts.length; i++) { lineStarts[i] += startOffset + 1; } this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1)); this._buffers[0].buffer += '_' + text; startOffset += 1; } else { if (startOffset !== 0) { for (let i = 0; i < lineStarts.length; i++) { lineStarts[i] += startOffset; } } this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1)); this._buffers[0].buffer += text; } const endOffset = this._buffers[0].buffer.length; const endIndex = this._buffers[0].lineStarts.length - 1; const endColumn = endOffset - this._buffers[0].lineStarts[endIndex]; const endPos = { line: endIndex, column: endColumn }; const newPiece = new Piece(0, /** todo@peng */ start, endPos, this.getLineFeedCnt(0, start, endPos), endOffset - startOffset); this._lastChangeBufferPos = endPos; return [newPiece]; } getLineRawContent(lineNumber, endOffset = 0) { let x = this.root; let ret = ''; const cache = this._searchCache.get2(lineNumber); if (cache) { x = cache.node; const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber - 1); const buffer = this._buffers[x.piece.bufferIndex].buffer; const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); if (cache.nodeStartLineNumber + x.piece.lineFeedCnt === lineNumber) { ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x.piece.length); } else { const accumulatedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber); return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset); } } else { let nodeStartOffset = 0; const originalLineNumber = lineNumber; while (x !== rbTreeBase_1.SENTINEL) { if (x.left !== rbTreeBase_1.SENTINEL && x.lf_left >= lineNumber - 1) { x = x.left; } else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) { const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2); const accumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1); const buffer = this._buffers[x.piece.bufferIndex].buffer; const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); nodeStartOffset += x.size_left; this._searchCache.set({ node: x, nodeStartOffset, nodeStartLineNumber: originalLineNumber - (lineNumber - 1 - x.lf_left) }); return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset); } else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) { const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2); const buffer = this._buffers[x.piece.bufferIndex].buffer; const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x.piece.length); break; } else { lineNumber -= x.lf_left + x.piece.lineFeedCnt; nodeStartOffset += x.size_left + x.piece.length; x = x.right; } } } // search in order, to find the node contains end column x = x.next(); while (x !== rbTreeBase_1.SENTINEL) { const buffer = this._buffers[x.piece.bufferIndex].buffer; if (x.piece.lineFeedCnt > 0) { const accumulatedValue = this.getAccumulatedValue(x, 0); const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); ret += buffer.substring(startOffset, startOffset + accumulatedValue - endOffset); return ret; } else { const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); ret += buffer.substr(startOffset, x.piece.length); } x = x.next(); } return ret; } computeBufferMetadata() { let x = this.root; let lfCnt = 1; let len = 0; while (x !== rbTreeBase_1.SENTINEL) { lfCnt += x.lf_left + x.piece.lineFeedCnt; len += x.size_left + x.piece.length; x = x.right; } this._lineCnt = lfCnt; this._length = len; this._searchCache.validate(this._length); } // #region node operations getIndexOf(node, accumulatedValue) { const piece = node.piece; const pos = this.positionInBuffer(node, accumulatedValue); const lineCnt = pos.line - piece.start.line; if (this.offsetInBuffer(piece.bufferIndex, piece.end) - this.offsetInBuffer(piece.bufferIndex, piece.start) === accumulatedValue) { // we are checking the end of this node, so a CRLF check is necessary. const realLineCnt = this.getLineFeedCnt(node.piece.bufferIndex, piece.start, pos); if (realLineCnt !== lineCnt) { // aha yes, CRLF return { index: realLineCnt, remainder: 0 }; } } return { index: lineCnt, remainder: pos.column }; } getAccumulatedValue(node, index) { if (index < 0) { return 0; } const piece = node.piece; const lineStarts = this._buffers[piece.bufferIndex].lineStarts; const expectedLineStartIndex = piece.start.line + index + 1; if (expectedLineStartIndex > piece.end.line) { return lineStarts[piece.end.line] + piece.end.column - lineStarts[piece.start.line] - piece.start.column; } else { return lineStarts[expectedLineStartIndex] - lineStarts[piece.start.line] - piece.start.column; } } deleteNodeTail(node, pos) { const piece = node.piece; const originalLFCnt = piece.lineFeedCnt; const originalEndOffset = this.offsetInBuffer(piece.bufferIndex, piece.end); const newEnd = pos; const newEndOffset = this.offsetInBuffer(piece.bufferIndex, newEnd); const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd); const lf_delta = newLineFeedCnt - originalLFCnt; const size_delta = newEndOffset - originalEndOffset; const newLength = piece.length + size_delta; node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength); (0, rbTreeBase_1.updateTreeMetadata)(this, node, size_delta, lf_delta); } deleteNodeHead(node, pos) { const piece = node.piece; const originalLFCnt = piece.lineFeedCnt; const originalStartOffset = this.offsetInBuffer(piece.bufferIndex, piece.start); const newStart = pos; const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end); const newStartOffset = this.offsetInBuffer(piece.bufferIndex, newStart); const lf_delta = newLineFeedCnt - originalLFCnt; const size_delta = originalStartOffset - newStartOffset; const newLength = piece.length + size_delta; node.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength); (0, rbTreeBase_1.updateTreeMetadata)(this, node, size_delta, lf_delta); } shrinkNode(node, start, end) { const piece = node.piece; const originalStartPos = piece.start; const originalEndPos = piece.end; // old piece, originalStartPos, start const oldLength = piece.length; const oldLFCnt = piece.lineFeedCnt; const newEnd = start; const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd); const newLength = this.offsetInBuffer(piece.bufferIndex, start) - this.offsetInBuffer(piece.bufferIndex, originalStartPos); node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength); (0, rbTreeBase_1.updateTreeMetadata)(this, node, newLength - oldLength, newLineFeedCnt - oldLFCnt); // new right piece, end, originalEndPos const newPiece = new Piece(piece.bufferIndex, end, originalEndPos, this.getLineFeedCnt(piece.bufferIndex, end, originalEndPos), this.offsetInBuffer(piece.bufferIndex, originalEndPos) - this.offsetInBuffer(piece.bufferIndex, end)); const newNode = this.rbInsertRight(node, newPiece); this.validateCRLFWithPrevNode(newNode); } appendToNode(node, value) { if (this.adjustCarriageReturnFromNext(value, node)) { value += '\n'; } const hitCRLF = this.shouldCheckCRLF() && this.startWithLF(value) && this.endWithCR(node); const startOffset = this._buffers[0].buffer.length; this._buffers[0].buffer += value; const lineStarts = createLineStartsFast(value, false); for (let i = 0; i < lineStarts.length; i++) { lineStarts[i] += startOffset; } if (hitCRLF) { const prevStartOffset = this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 2]; this._buffers[0].lineStarts.pop(); // _lastChangeBufferPos is already wrong this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line - 1, column: startOffset - prevStartOffset }; } this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1)); const endIndex = this._buffers[0].lineStarts.length - 1; const endColumn = this._buffers[0].buffer.length - this._buffers[0].lineStarts[endIndex]; const newEnd = { line: endIndex, column: endColumn }; const newLength = node.piece.length + value.length; const oldLineFeedCnt = node.piece.lineFeedCnt; const newLineFeedCnt = this.getLineFeedCnt(0, node.piece.start, newEnd); const lf_delta = newLineFeedCnt - oldLineFeedCnt; node.piece = new Piece(node.piece.bufferIndex, node.piece.start, newEnd, newLineFeedCnt, newLength); this._lastChangeBufferPos = newEnd; (0, rbTreeBase_1.updateTreeMetadata)(this, node, value.length, lf_delta); } nodeAt(offset) { let x = this.root; const cache = this._searchCache.get(offset); if (cache) { return { node: cache.node, nodeStartOffset: cache.nodeStartOffset, remainder: offset - cache.nodeStartOffset }; } let nodeStartOffset = 0; while (x !== rbTreeBase_1.SENTINEL) { if (x.size_left > offset) { x = x.left; } else if (x.size_left + x.piece.length >= offset) { nodeStartOffset += x.size_left; const ret = { node: x, remainder: offset - x.size_left, nodeStartOffset }; this._searchCache.set(ret); return ret; } else { offset -= x.size_left + x.piece.length; nodeStartOffset += x.size_left + x.piece.length; x = x.right; } } return null; } nodeAt2(lineNumber, column) { let x = this.root; let nodeStartOffset = 0; while (x !== rbTreeBase_1.SENTINEL) { if (x.left !== rbTreeBase_1.SENTINEL && x.lf_left >= lineNumber - 1) { x = x.left; } else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) { const prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2); const accumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1); nodeStartOffset += x.size_left; return { node: x, remainder: Math.min(prevAccumualtedValue + column - 1, accumulatedValue), nodeStartOffset }; } else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) { const prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2); if (prevAccumualtedValue + column - 1 <= x.piece.length) { return { node: x, remainder: prevAccumualtedValue + column - 1, nodeStartOffset }; } else { column -= x.piece.length - prevAccumualtedValue; break; } } else { lineNumber -= x.lf_left + x.piece.lineFeedCnt; nodeStartOffset += x.size_left + x.piece.length; x = x.right; } } // search in order, to find the node contains position.column x = x.next(); while (x !== rbTreeBase_1.SENTINEL) { if (x.piece.lineFeedCnt > 0) { const accumulatedValue = this.getAccumulatedValue(x, 0); const nodeStartOffset = this.offsetOfNode(x); return { node: x, remainder: Math.min(column - 1, accumulatedValue), nodeStartOffset }; } else { if (x.piece.length >= column - 1) { const nodeStartOffset = this.offsetOfNode(x); return { node: x, remainder: column - 1, nodeStartOffset }; } else { column -= x.piece.length; } } x = x.next(); } return null; } nodeCharCodeAt(node, offset) { if (node.piece.lineFeedCnt < 1) { return -1; } const buffer = this._buffers[node.piece.bufferIndex]; const newOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start) + offset; return buffer.buffer.charCodeAt(newOffset); } offsetOfNode(node) { if (!node) { return 0; } let pos = node.size_left; while (node !== this.root) { if (node.parent.right === node) { pos += node.parent.size_left + node.parent.piece.length; } node = node.parent; } return pos; } // #endregion // #region CRLF shouldCheckCRLF() { return !(this._EOLNormalized && this._EOL === '\n'); } startWithLF(val) { if (typeof val === 'string') { return val.charCodeAt(0) === 10; } if (val === rbTreeBase_1.SENTINEL || val.piece.lineFeedCnt === 0) { return false; } const piece = val.piece; const lineStarts = this._buffers[piece.bufferIndex].lineStarts; const line = piece.start.line; const startOffset = lineStarts[line] + piece.start.column; if (line === lineStarts.length - 1) { // last line, so there is no line feed at the end of this line return false; } const nextLineOffset = lineStarts[line + 1]; if (nextLineOffset > startOffset + 1) { return false; } return this._buffers[piece.bufferIndex].buffer.charCodeAt(startOffset) === 10; } endWithCR(val) { if (typeof val === 'string') { return val.charCodeAt(val.length - 1) === 13; } if (val === rbTreeBase_1.SENTINEL || val.piece.lineFeedCnt === 0) { return false; } return this.nodeCharCodeAt(val, val.piece.length - 1) === 13; } validateCRLFWithPrevNode(nextNode) { if (this.shouldCheckCRLF() && this.startWithLF(nextNode)) { const node = nextNode.prev(); if (this.endWithCR(node)) { this.fixCRLF(node, nextNode); } } } validateCRLFWithNextNode(node) { if (this.shouldCheckCRLF() && this.endWithCR(node)) { const nextNode = node.next(); if (this.startWithLF(nextNode)) { this.fixCRLF(node, nextNode); } } } fixCRLF(prev, next) { const nodesToDel = []; // update node const lineStarts = this._buffers[prev.piece.bufferIndex].lineStarts; let newEnd; if (prev.piece.end.column === 0) { // it means, last line ends with \r, not \r\n newEnd = { line: prev.piece.end.line - 1, column: lineStarts[prev.piece.end.line] - lineStarts[prev.piece.end.line - 1] - 1 }; } else { // \r\n newEnd = { line: prev.piece.end.line, column: prev.piece.end.column - 1 }; } const prevNewLength = prev.piece.length - 1; const prevNewLFCnt = prev.piece.lineFeedCnt - 1; prev.piece = new Piece(prev.piece.bufferIndex, prev.piece.start, newEnd, prevNewLFCnt, prevNewLength); (0, rbTreeBase_1.updateTreeMetadata)(this, prev, -1, -1); if (prev.piece.length === 0) { nodesToDel.push(prev); } // update nextNode const newStart = { line: next.piece.start.line + 1, column: 0 }; const newLength = next.piece.length - 1; const newLineFeedCnt = this.getLineFeedCnt(next.piece.bufferIndex, newStart, next.piece.end); next.piece = new Piece(next.piece.bufferIndex, newStart, next.piece.end, newLineFeedCnt, newLength); (0, rbTreeBase_1.updateTreeMetadata)(this, next, -1, -1); if (next.piece.length === 0) { nodesToDel.push(next); } // create new piece which contains \r\n const pieces = this.createNewPieces('\r\n'); this.rbInsertRight(prev, pieces[0]); // delete empty nodes for (let i = 0; i < nodesToDel.length; i++) { (0, rbTreeBase_1.rbDelete)(this, nodesToDel[i]); } } adjustCarriageReturnFromNext(value, node) { if (this.shouldCheckCRLF() && this.endWithCR(value)) { const nextNode = node.next(); if (this.startWithLF(nextNode)) { // move `\n` forward value += '\n'; if (nextNode.piece.length === 1) { (0, rbTreeBase_1.rbDelete)(this, nextNode); } else { const piece = nextNode.piece; const newStart = { line: piece.start.line + 1, column: 0 }; const newLength = piece.length - 1; const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end); nextNode.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength); (0, rbTreeBase_1.updateTreeMetadata)(this, nextNode, -1, -1); } return true; } } return false; } // #endregion // #endregion // #region Tree operations iterate(node, callback) { if (node === rbTreeBase_1.SENTINEL) { return callback(rbTreeBase_1.SENTINEL); } const leftRet = this.iterate(node.left, callback); if (!leftRet) { return leftRet; } return callback(node) && this.iterate(node.right, callback); } getNodeContent(node) { if (node === rbTreeBase_1.SENTINEL) { return ''; } const buffer = this._buffers[node.piece.bufferIndex]; let currentContent; const piece = node.piece; const startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start); const endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end); currentContent = buffer.buffer.substring(startOffset, endOffset); return currentContent; } getPieceContent(piece) { const buffer = this._buffers[piece.bufferIndex]; const startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start); const endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end); const currentContent = buffer.buffer.substring(startOffset, endOffset); return currentContent; } /** * node node * / \ / \ * a b <---- a b * / * z */ rbInsertRight(node, p) { const z = new rbTreeBase_1.TreeNode(p, 1 /* Red */); z.left = rbTreeBase_1.SENTINEL; z.right = rbTreeBase_1.SENTINEL; z.parent = rbTreeBase_1.SENTINEL; z.size_left = 0; z.lf_left = 0; const x = this.root; if (x === rbTreeBase_1.SENTINEL) { this.root = z; z.color = 0 /* Black */; } else if (node.right === rbTreeBase_1.SENTINEL) { node.right = z; z.parent = node; } else { const nextNode = (0, rbTreeBase_1.leftest)(node.right); nextNode.left = z; z.parent = nextNode; } (0, rbTreeBase_1.fixInsert)(this, z); return z; } /** * node node * / \ / \ * a b ----> a b * \ * z */ rbInsertLeft(node, p) { const z = new rbTreeBase_1.TreeNode(p, 1 /* 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 { const prevNode = (0, rbTreeBase_1.righttest)(node.left); // a prevNode.right = z; z.parent = prevNode; } (0, rbTreeBase_1.fixInsert)(this, z); return z; } } exports.PieceTreeBase = PieceTreeBase; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[245/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,8/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/,49/*vs/editor/common/model*/,244/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/,117/*vs/editor/common/core/eolCounter*/,237/*vs/editor/common/core/textChange*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, strings, range_1, model_1, pieceTreeBase_1, eolCounter_1, textChange_1, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PieceTreeTextBuffer = void 0; class PieceTreeTextBuffer extends lifecycle_1.Disposable { constructor(chunks, BOM, eol, containsRTL, containsUnusualLineTerminators, isBasicASCII, eolNormalized) { super(); this._onDidChangeContent = this._register(new event_1.Emitter()); this._BOM = BOM; this._mightContainNonBasicASCII = !isBasicASCII; this._mightContainRTL = containsRTL; this._mightContainUnusualLineTerminators = containsUnusualLineTerminators; this._pieceTree = new pieceTreeBase_1.PieceTreeBase(chunks, eol, eolNormalized); } mightContainRTL() { return this._mightContainRTL; } mightContainUnusualLineTerminators() { return this._mightContainUnusualLineTerminators; } resetMightContainUnusualLineTerminators() { this._mightContainUnusualLineTerminators = false; } mightContainNonBasicASCII() { return this._mightContainNonBasicASCII; } getBOM() { return this._BOM; } getEOL() { return this._pieceTree.getEOL(); } createSnapshot(preserveBOM) { return this._pieceTree.createSnapshot(preserveBOM ? this._BOM : ''); } getOffsetAt(lineNumber, column) { return this._pieceTree.getOffsetAt(lineNumber, column); } getPositionAt(offset) { return this._pieceTree.getPositionAt(offset); } getRangeAt(start, length) { const end = start + length; const startPosition = this.getPositionAt(start); const endPosition = this.getPositionAt(end); return new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column); } getValueInRange(range, eol = 0 /* 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); } const startOffset = this.getOffsetAt(range.startLineNumber, range.startColumn); const 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++) { const op = rawOperations[i]; if (canReduceOperations && op._isTracked) { canReduceOperations = false; } const validatedRange = op.range; if (op.text) { let textMightContainNonBasicASCII = true; if (!mightContainNonBasicASCII) { textMightContainNonBasicASCII = !strings.isBasicASCII(op.text); mightContainNonBasicASCII = textMightContainNonBasicASCII; } if (!mightContainRTL && textMightContainNonBasicASCII) { // check if the new inserted text contains RTL mightContainRTL = strings.containsRTL(op.text); } if (!mightContainUnusualLineTerminators && textMightContainNonBasicASCII) { // check if the new inserted text contains unusual line terminators mightContainUnusualLineTerminators = strings.containsUnusualLineTerminators(op.text); } } let validText = ''; let eolCount = 0; let firstLineLength = 0; let lastLineLength = 0; if (op.text) { let strEOL; [eolCount, firstLineLength, lastLineLength, strEOL] = (0, eolCounter_1.countEOL)(op.text); const bufferEOL = this.getEOL(); const expectedStrEOL = (bufferEOL === '\r\n' ? 2 /* 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++) { const rangeEnd = operations[i].range.getEndPosition(); const nextRangeStart = operations[i + 1].range.getStartPosition(); if (nextRangeStart.isBeforeOrEqual(rangeEnd)) { if (nextRangeStart.isBefore(rangeEnd)) { // overlapping ranges throw new Error('Overlapping ranges are not allowed!'); } hasTouchingRanges = true; } } if (canReduceOperations) { operations = this._reduceOperations(operations); } // Delta encode operations const reverseRanges = (computeUndoEdits || recordTrimAutoWhitespace ? PieceTreeTextBuffer._getInverseEditRanges(operations) : []); const newTrimAutoWhitespaceCandidates = []; if (recordTrimAutoWhitespace) { for (let i = 0; i < operations.length; i++) { const op = operations[i]; const reverseRange = reverseRanges[i]; if (op.isAutoWhitespaceEdit && op.range.isEmpty()) { // Record already the future line numbers that might be auto whitespace removal candidates on next edit for (let lineNumber = reverseRange.startLineNumber; lineNumber <= reverseRange.endLineNumber; lineNumber++) { let currentLineContent = ''; if (lineNumber === reverseRange.startLineNumber) { currentLineContent = this.getLineContent(op.range.startLineNumber); if (strings.firstNonWhitespaceIndex(currentLineContent) !== -1) { continue; } } newTrimAutoWhitespaceCandidates.push({ lineNumber: lineNumber, oldContent: currentLineContent }); } } } } let reverseOperations = null; if (computeUndoEdits) { let reverseRangeDeltaOffset = 0; reverseOperations = []; for (let i = 0; i < operations.length; i++) { const op = operations[i]; const reverseRange = reverseRanges[i]; const bufferText = this.getValueInRange(op.range); const reverseRangeOffset = op.rangeOffset + reverseRangeDeltaOffset; reverseRangeDeltaOffset += (op.text.length - bufferText.length); reverseOperations[i] = { sortIndex: op.sortIndex, identifier: op.identifier, range: reverseRange, text: bufferText, textChange: new textChange_1.TextChange(op.rangeOffset, bufferText, reverseRangeOffset, op.text) }; } // Can only sort reverse operations when the order is not significant if (!hasTouchingRanges) { reverseOperations.sort((a, b) => a.sortIndex - b.sortIndex); } } this._mightContainRTL = mightContainRTL; this._mightContainUnusualLineTerminators = mightContainUnusualLineTerminators; this._mightContainNonBasicASCII = mightContainNonBasicASCII; const contentChanges = this._doApplyEdits(operations); let trimAutoWhitespaceLineNumbers = null; if (recordTrimAutoWhitespace && newTrimAutoWhitespaceCandidates.length > 0) { // sort line numbers auto whitespace removal candidates for next edit descending newTrimAutoWhitespaceCandidates.sort((a, b) => b.lineNumber - a.lineNumber); trimAutoWhitespaceLineNumbers = []; for (let i = 0, len = newTrimAutoWhitespaceCandidates.length; i < len; i++) { const lineNumber = newTrimAutoWhitespaceCandidates[i].lineNumber; if (i > 0 && newTrimAutoWhitespaceCandidates[i - 1].lineNumber === lineNumber) { // Do not have the same line number twice continue; } const prevContent = newTrimAutoWhitespaceCandidates[i].oldContent; const lineContent = this.getLineContent(lineNumber); if (lineContent.length === 0 || lineContent === prevContent || strings.firstNonWhitespaceIndex(lineContent) !== -1) { continue; } trimAutoWhitespaceLineNumbers.push(lineNumber); } } this._onDidChangeContent.fire(); return new model_1.ApplyEditsResult(reverseOperations, contentChanges, trimAutoWhitespaceLineNumbers); } /** * Transform operations such that they represent the same logic edit, * but that they also do not cause OOM crashes. */ _reduceOperations(operations) { if (operations.length < 1000) { // We know from empirical testing that a thousand edits work fine regardless of their shape. return operations; } // At one point, due to how events are emitted and how each operation is handled, // some operations can trigger a high amount of temporary string allocations, // that will immediately get edited again. // e.g. a formatter inserting ridiculous ammounts of \n on a model with a single line // Therefore, the strategy is to collapse all the operations into a huge single edit operation return [this._toSingleEditOperation(operations)]; } _toSingleEditOperation(operations) { let forceMoveMarkers = false; const firstEditRange = operations[0].range; const lastEditRange = operations[operations.length - 1].range; const entireEditRange = new range_1.Range(firstEditRange.startLineNumber, firstEditRange.startColumn, lastEditRange.endLineNumber, lastEditRange.endColumn); let lastEndLineNumber = firstEditRange.startLineNumber; let lastEndColumn = firstEditRange.startColumn; const result = []; for (let i = 0, len = operations.length; i < len; i++) { const operation = operations[i]; const range = operation.range; forceMoveMarkers = forceMoveMarkers || operation.forceMoveMarkers; // (1) -- Push old text result.push(this.getValueInRange(new range_1.Range(lastEndLineNumber, lastEndColumn, range.startLineNumber, range.startColumn))); // (2) -- Push new text if (operation.text.length > 0) { result.push(operation.text); } lastEndLineNumber = range.endLineNumber; lastEndColumn = range.endColumn; } const text = result.join(''); const [eolCount, firstLineLength, lastLineLength] = (0, eolCounter_1.countEOL)(text); return { sortIndex: 0, identifier: operations[0].identifier, range: entireEditRange, rangeOffset: this.getOffsetAt(entireEditRange.startLineNumber, entireEditRange.startColumn), rangeLength: this.getValueLengthInRange(entireEditRange, 0 /* TextDefined */), text: text, eolCount: eolCount, firstLineLength: firstLineLength, lastLineLength: lastLineLength, forceMoveMarkers: forceMoveMarkers, isAutoWhitespaceEdit: false }; } _doApplyEdits(operations) { operations.sort(PieceTreeTextBuffer._sortOpsDescending); const contentChanges = []; // operations are from bottom to top for (let i = 0; i < operations.length; i++) { const op = operations[i]; const startLineNumber = op.range.startLineNumber; const startColumn = op.range.startColumn; const endLineNumber = op.range.endLineNumber; const endColumn = op.range.endColumn; if (startLineNumber === endLineNumber && startColumn === endColumn && op.text.length === 0) { // no-op continue; } if (op.text) { // replacement this._pieceTree.delete(op.rangeOffset, op.rangeLength); this._pieceTree.insert(op.rangeOffset, op.text, true); } else { // deletion this._pieceTree.delete(op.rangeOffset, op.rangeLength); } const contentChangeRange = new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn); contentChanges.push({ range: contentChangeRange, rangeLength: op.rangeLength, text: op.text, rangeOffset: op.rangeOffset, forceMoveMarkers: op.forceMoveMarkers }); } return contentChanges; } findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) { return this._pieceTree.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount); } /** * Assumes `operations` are validated and sorted ascending */ static _getInverseEditRanges(operations) { const result = []; let prevOpEndLineNumber = 0; let prevOpEndColumn = 0; let prevOp = null; for (let i = 0, len = operations.length; i < len; i++) { const op = operations[i]; let startLineNumber; let startColumn; if (prevOp) { if (prevOp.range.endLineNumber === op.range.startLineNumber) { startLineNumber = prevOpEndLineNumber; startColumn = prevOpEndColumn + (op.range.startColumn - prevOp.range.endColumn); } else { startLineNumber = prevOpEndLineNumber + (op.range.startLineNumber - prevOp.range.endLineNumber); startColumn = op.range.startColumn; } } else { startLineNumber = op.range.startLineNumber; startColumn = op.range.startColumn; } let resultRange; if (op.text.length > 0) { // the operation inserts something const lineCount = op.eolCount + 1; if (lineCount === 1) { // single line insert resultRange = new range_1.Range(startLineNumber, startColumn, startLineNumber, startColumn + op.firstLineLength); } else { // multi line insert resultRange = new range_1.Range(startLineNumber, startColumn, startLineNumber + lineCount - 1, op.lastLineLength + 1); } } else { // There is nothing to insert resultRange = new range_1.Range(startLineNumber, startColumn, startLineNumber, startColumn); } prevOpEndLineNumber = resultRange.endLineNumber; prevOpEndColumn = resultRange.endColumn; result.push(resultRange); prevOp = op; } return result; } static _sortOpsAscending(a, b) { const r = range_1.Range.compareRangesUsingEnds(a.range, b.range); if (r === 0) { return a.sortIndex - b.sortIndex; } return r; } static _sortOpsDescending(a, b) { const r = range_1.Range.compareRangesUsingEnds(a.range, b.range); if (r === 0) { return b.sortIndex - a.sortIndex; } return -r; } } exports.PieceTreeTextBuffer = PieceTreeTextBuffer; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[421/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,244/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/,245/*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); const chunks = this._chunks; if (this._normalizeEOL && ((eol === '\r\n' && (this._cr > 0 || this._lf > 0)) || (eol === '\n' && (this._cr > 0 || this._crlf > 0)))) { // Normalize pieces for (let i = 0, len = chunks.length; i < len; i++) { const str = chunks[i].buffer.replace(/\r\n|\r|\n/g, eol); const newLineStart = (0, pieceTreeBase_1.createLineStartsFast)(str); chunks[i] = new pieceTreeBase_1.StringBuffer(str, newLineStart); } } const textBuffer = new pieceTreeTextBuffer_1.PieceTreeTextBuffer(chunks, this._bom, eol, this._containsRTL, this._containsUnusualLineTerminators, this._isBasicASCII, this._normalizeEOL); return { textBuffer: textBuffer, disposable: textBuffer }; } } 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 const lastChunk = this.chunks[this.chunks.length - 1]; lastChunk.buffer += String.fromCharCode(this._previousChar); const newLineStarts = (0, pieceTreeBase_1.createLineStartsFast)(lastChunk.buffer); lastChunk.lineStarts = newLineStarts; if (this._previousChar === 13 /* 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[178/*vs/editor/common/model/utils*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.computeIndentLevel = void 0; /** * Returns: * - -1 => the line consists of whitespace * - otherwise => the indent level is returned value */ function computeIndentLevel(line, tabSize) { let indent = 0; let i = 0; const len = line.length; while (i < len) { const chCode = line.charCodeAt(i); if (chCode === 32 /* 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; } exports.computeIndentLevel = computeIndentLevel; }); /*--------------------------------------------------------------------------------------------- * 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/common/services/languagesAssociations*/], __M([1/*require*/,0/*exports*/,215/*vs/base/common/glob*/,135/*vs/base/common/mime*/,48/*vs/base/common/network*/,82/*vs/base/common/path*/,41/*vs/base/common/resources*/,8/*vs/base/common/strings*/]), function (require, exports, glob_1, mime_1, network_1, path_1, resources_1, strings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getMimeTypes = exports.clearLanguageAssociations = exports.registerLanguageAssociation = void 0; let registeredAssociations = []; let nonUserRegisteredAssociations = []; let userRegisteredAssociations = []; /** * Associate a language to the registry. */ function registerLanguageAssociation(association, warnOnOverwrite = false) { // Register const associationItem = toLanguageAssociationItem(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.registerLanguageAssociation = registerLanguageAssociation; function toLanguageAssociationItem(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 ? (0, glob_1.parse)(association.filepattern.toLowerCase()) : undefined, filepatternOnPath: association.filepattern ? association.filepattern.indexOf(path_1.posix.sep) >= 0 : false }; } /** * Clear language associations from the registry. */ function clearLanguageAssociations(onlyUserConfigured) { if (!onlyUserConfigured) { registeredAssociations = []; nonUserRegisteredAssociations = []; userRegisteredAssociations = []; } else { registeredAssociations = registeredAssociations.filter(a => !a.userConfigured); userRegisteredAssociations = []; } } exports.clearLanguageAssociations = clearLanguageAssociations; /** * Given a file, return the best matching mime types for it * based on the registered language associations. */ function getMimeTypes(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 [mime_1.Mimes.unknown]; } path = path.toLowerCase(); const filename = (0, path_1.basename)(path); // 1.) User configured mappings have highest priority const configuredLanguage = getMimeByPath(path, filename, userRegisteredAssociations); if (configuredLanguage) { return [configuredLanguage, mime_1.Mimes.text]; } // 2.) Registered mappings have middle priority const registeredLanguage = getMimeByPath(path, filename, nonUserRegisteredAssociations); if (registeredLanguage) { return [registeredLanguage, mime_1.Mimes.text]; } // 3.) Firstline has lowest priority if (firstLine) { const firstlineLanguage = getMimeByFirstline(firstLine); if (firstlineLanguage) { return [firstlineLanguage, mime_1.Mimes.text]; } } return [mime_1.Mimes.unknown]; } exports.getMimeTypes = getMimeTypes; function getMimeByPath(path, filename, associations) { var _a; let filenameMatch = undefined; let patternMatch = undefined; let extensionMatch = undefined; // We want to prioritize associations based on the order they are registered so that the last registered // association wins over all other. This is for https://github.com/microsoft/vscode/issues/20074 for (let i = associations.length - 1; i >= 0; i--) { const association = associations[i]; // First exact name match if (filename === association.filenameLowercase) { filenameMatch = association; break; // take it! } // Longest pattern match if (association.filepattern) { if (!patternMatch || association.filepattern.length > patternMatch.filepattern.length) { const target = association.filepatternOnPath ? path : filename; // match on full path if pattern contains path separator if ((_a = association.filepatternLowercase) === null || _a === void 0 ? void 0 : _a.call(association, target)) { patternMatch = association; } } } // Longest extension match if (association.extension) { if (!extensionMatch || association.extension.length > extensionMatch.extension.length) { if (filename.endsWith(association.extensionLowercase)) { extensionMatch = association; } } } } // 1.) Exact name match has second highest priority if (filenameMatch) { return filenameMatch.mime; } // 2.) Match on pattern if (patternMatch) { return patternMatch.mime; } // 3.) Match on extension comes next if (extensionMatch) { return extensionMatch.mime; } return undefined; } function getMimeByFirstline(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 undefined; } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[423/*vs/editor/common/services/semanticTokensDto*/], __M([1/*require*/,0/*exports*/,110/*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[179/*vs/editor/common/standalone/standaloneEnums*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WrappingIndent = exports.TrackedRangeStickiness = exports.TextEditorCursorStyle = exports.TextEditorCursorBlinkingStyle = exports.SymbolTag = exports.SymbolKind = exports.SignatureHelpTriggerKind = exports.SelectionDirection = exports.ScrollbarVisibility = exports.ScrollType = exports.RenderMinimap = exports.RenderLineNumbersType = exports.PositionAffinity = exports.OverviewRulerLane = exports.OverlayWidgetPositionPreference = exports.MouseTargetType = exports.MinimapPosition = exports.MarkerTag = exports.MarkerSeverity = exports.KeyCode = exports.InlineCompletionTriggerKind = exports.InlayHintKind = exports.InjectedTextCursorStops = 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["bracketPairColorization"] = 12] = "bracketPairColorization"; EditorOption[EditorOption["guides"] = 13] = "guides"; EditorOption[EditorOption["codeLens"] = 14] = "codeLens"; EditorOption[EditorOption["codeLensFontFamily"] = 15] = "codeLensFontFamily"; EditorOption[EditorOption["codeLensFontSize"] = 16] = "codeLensFontSize"; EditorOption[EditorOption["colorDecorators"] = 17] = "colorDecorators"; EditorOption[EditorOption["columnSelection"] = 18] = "columnSelection"; EditorOption[EditorOption["comments"] = 19] = "comments"; EditorOption[EditorOption["contextmenu"] = 20] = "contextmenu"; EditorOption[EditorOption["copyWithSyntaxHighlighting"] = 21] = "copyWithSyntaxHighlighting"; EditorOption[EditorOption["cursorBlinking"] = 22] = "cursorBlinking"; EditorOption[EditorOption["cursorSmoothCaretAnimation"] = 23] = "cursorSmoothCaretAnimation"; EditorOption[EditorOption["cursorStyle"] = 24] = "cursorStyle"; EditorOption[EditorOption["cursorSurroundingLines"] = 25] = "cursorSurroundingLines"; EditorOption[EditorOption["cursorSurroundingLinesStyle"] = 26] = "cursorSurroundingLinesStyle"; EditorOption[EditorOption["cursorWidth"] = 27] = "cursorWidth"; EditorOption[EditorOption["disableLayerHinting"] = 28] = "disableLayerHinting"; EditorOption[EditorOption["disableMonospaceOptimizations"] = 29] = "disableMonospaceOptimizations"; EditorOption[EditorOption["domReadOnly"] = 30] = "domReadOnly"; EditorOption[EditorOption["dragAndDrop"] = 31] = "dragAndDrop"; EditorOption[EditorOption["emptySelectionClipboard"] = 32] = "emptySelectionClipboard"; EditorOption[EditorOption["extraEditorClassName"] = 33] = "extraEditorClassName"; EditorOption[EditorOption["fastScrollSensitivity"] = 34] = "fastScrollSensitivity"; EditorOption[EditorOption["find"] = 35] = "find"; EditorOption[EditorOption["fixedOverflowWidgets"] = 36] = "fixedOverflowWidgets"; EditorOption[EditorOption["folding"] = 37] = "folding"; EditorOption[EditorOption["foldingStrategy"] = 38] = "foldingStrategy"; EditorOption[EditorOption["foldingHighlight"] = 39] = "foldingHighlight"; EditorOption[EditorOption["foldingImportsByDefault"] = 40] = "foldingImportsByDefault"; EditorOption[EditorOption["foldingMaximumRegions"] = 41] = "foldingMaximumRegions"; EditorOption[EditorOption["unfoldOnClickAfterEndOfLine"] = 42] = "unfoldOnClickAfterEndOfLine"; EditorOption[EditorOption["fontFamily"] = 43] = "fontFamily"; EditorOption[EditorOption["fontInfo"] = 44] = "fontInfo"; EditorOption[EditorOption["fontLigatures"] = 45] = "fontLigatures"; EditorOption[EditorOption["fontSize"] = 46] = "fontSize"; EditorOption[EditorOption["fontWeight"] = 47] = "fontWeight"; EditorOption[EditorOption["formatOnPaste"] = 48] = "formatOnPaste"; EditorOption[EditorOption["formatOnType"] = 49] = "formatOnType"; EditorOption[EditorOption["glyphMargin"] = 50] = "glyphMargin"; EditorOption[EditorOption["gotoLocation"] = 51] = "gotoLocation"; EditorOption[EditorOption["hideCursorInOverviewRuler"] = 52] = "hideCursorInOverviewRuler"; EditorOption[EditorOption["hover"] = 53] = "hover"; EditorOption[EditorOption["inDiffEditor"] = 54] = "inDiffEditor"; EditorOption[EditorOption["inlineSuggest"] = 55] = "inlineSuggest"; EditorOption[EditorOption["letterSpacing"] = 56] = "letterSpacing"; EditorOption[EditorOption["lightbulb"] = 57] = "lightbulb"; EditorOption[EditorOption["lineDecorationsWidth"] = 58] = "lineDecorationsWidth"; EditorOption[EditorOption["lineHeight"] = 59] = "lineHeight"; EditorOption[EditorOption["lineNumbers"] = 60] = "lineNumbers"; EditorOption[EditorOption["lineNumbersMinChars"] = 61] = "lineNumbersMinChars"; EditorOption[EditorOption["linkedEditing"] = 62] = "linkedEditing"; EditorOption[EditorOption["links"] = 63] = "links"; EditorOption[EditorOption["matchBrackets"] = 64] = "matchBrackets"; EditorOption[EditorOption["minimap"] = 65] = "minimap"; EditorOption[EditorOption["mouseStyle"] = 66] = "mouseStyle"; EditorOption[EditorOption["mouseWheelScrollSensitivity"] = 67] = "mouseWheelScrollSensitivity"; EditorOption[EditorOption["mouseWheelZoom"] = 68] = "mouseWheelZoom"; EditorOption[EditorOption["multiCursorMergeOverlapping"] = 69] = "multiCursorMergeOverlapping"; EditorOption[EditorOption["multiCursorModifier"] = 70] = "multiCursorModifier"; EditorOption[EditorOption["multiCursorPaste"] = 71] = "multiCursorPaste"; EditorOption[EditorOption["occurrencesHighlight"] = 72] = "occurrencesHighlight"; EditorOption[EditorOption["overviewRulerBorder"] = 73] = "overviewRulerBorder"; EditorOption[EditorOption["overviewRulerLanes"] = 74] = "overviewRulerLanes"; EditorOption[EditorOption["padding"] = 75] = "padding"; EditorOption[EditorOption["parameterHints"] = 76] = "parameterHints"; EditorOption[EditorOption["peekWidgetDefaultFocus"] = 77] = "peekWidgetDefaultFocus"; EditorOption[EditorOption["definitionLinkOpensInPeek"] = 78] = "definitionLinkOpensInPeek"; EditorOption[EditorOption["quickSuggestions"] = 79] = "quickSuggestions"; EditorOption[EditorOption["quickSuggestionsDelay"] = 80] = "quickSuggestionsDelay"; EditorOption[EditorOption["readOnly"] = 81] = "readOnly"; EditorOption[EditorOption["renameOnType"] = 82] = "renameOnType"; EditorOption[EditorOption["renderControlCharacters"] = 83] = "renderControlCharacters"; EditorOption[EditorOption["renderFinalNewline"] = 84] = "renderFinalNewline"; EditorOption[EditorOption["renderLineHighlight"] = 85] = "renderLineHighlight"; EditorOption[EditorOption["renderLineHighlightOnlyWhenFocus"] = 86] = "renderLineHighlightOnlyWhenFocus"; EditorOption[EditorOption["renderValidationDecorations"] = 87] = "renderValidationDecorations"; EditorOption[EditorOption["renderWhitespace"] = 88] = "renderWhitespace"; EditorOption[EditorOption["revealHorizontalRightPadding"] = 89] = "revealHorizontalRightPadding"; EditorOption[EditorOption["roundedSelection"] = 90] = "roundedSelection"; EditorOption[EditorOption["rulers"] = 91] = "rulers"; EditorOption[EditorOption["scrollbar"] = 92] = "scrollbar"; EditorOption[EditorOption["scrollBeyondLastColumn"] = 93] = "scrollBeyondLastColumn"; EditorOption[EditorOption["scrollBeyondLastLine"] = 94] = "scrollBeyondLastLine"; EditorOption[EditorOption["scrollPredominantAxis"] = 95] = "scrollPredominantAxis"; EditorOption[EditorOption["selectionClipboard"] = 96] = "selectionClipboard"; EditorOption[EditorOption["selectionHighlight"] = 97] = "selectionHighlight"; EditorOption[EditorOption["selectOnLineNumbers"] = 98] = "selectOnLineNumbers"; EditorOption[EditorOption["showFoldingControls"] = 99] = "showFoldingControls"; EditorOption[EditorOption["showUnused"] = 100] = "showUnused"; EditorOption[EditorOption["snippetSuggestions"] = 101] = "snippetSuggestions"; EditorOption[EditorOption["smartSelect"] = 102] = "smartSelect"; EditorOption[EditorOption["smoothScrolling"] = 103] = "smoothScrolling"; EditorOption[EditorOption["stickyTabStops"] = 104] = "stickyTabStops"; EditorOption[EditorOption["stopRenderingLineAfter"] = 105] = "stopRenderingLineAfter"; EditorOption[EditorOption["suggest"] = 106] = "suggest"; EditorOption[EditorOption["suggestFontSize"] = 107] = "suggestFontSize"; EditorOption[EditorOption["suggestLineHeight"] = 108] = "suggestLineHeight"; EditorOption[EditorOption["suggestOnTriggerCharacters"] = 109] = "suggestOnTriggerCharacters"; EditorOption[EditorOption["suggestSelection"] = 110] = "suggestSelection"; EditorOption[EditorOption["tabCompletion"] = 111] = "tabCompletion"; EditorOption[EditorOption["tabIndex"] = 112] = "tabIndex"; EditorOption[EditorOption["unicodeHighlighting"] = 113] = "unicodeHighlighting"; EditorOption[EditorOption["unusualLineTerminators"] = 114] = "unusualLineTerminators"; EditorOption[EditorOption["useShadowDOM"] = 115] = "useShadowDOM"; EditorOption[EditorOption["useTabStops"] = 116] = "useTabStops"; EditorOption[EditorOption["wordSeparators"] = 117] = "wordSeparators"; EditorOption[EditorOption["wordWrap"] = 118] = "wordWrap"; EditorOption[EditorOption["wordWrapBreakAfterCharacters"] = 119] = "wordWrapBreakAfterCharacters"; EditorOption[EditorOption["wordWrapBreakBeforeCharacters"] = 120] = "wordWrapBreakBeforeCharacters"; EditorOption[EditorOption["wordWrapColumn"] = 121] = "wordWrapColumn"; EditorOption[EditorOption["wordWrapOverride1"] = 122] = "wordWrapOverride1"; EditorOption[EditorOption["wordWrapOverride2"] = 123] = "wordWrapOverride2"; EditorOption[EditorOption["wrappingIndent"] = 124] = "wrappingIndent"; EditorOption[EditorOption["wrappingStrategy"] = 125] = "wrappingStrategy"; EditorOption[EditorOption["showDeprecated"] = 126] = "showDeprecated"; EditorOption[EditorOption["inlayHints"] = 127] = "inlayHints"; EditorOption[EditorOption["editorClassName"] = 128] = "editorClassName"; EditorOption[EditorOption["pixelRatio"] = 129] = "pixelRatio"; EditorOption[EditorOption["tabFocusMode"] = 130] = "tabFocusMode"; EditorOption[EditorOption["layoutInfo"] = 131] = "layoutInfo"; EditorOption[EditorOption["wrappingInfo"] = 132] = "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 InjectedTextCursorStops; (function (InjectedTextCursorStops) { InjectedTextCursorStops[InjectedTextCursorStops["Both"] = 0] = "Both"; InjectedTextCursorStops[InjectedTextCursorStops["Right"] = 1] = "Right"; InjectedTextCursorStops[InjectedTextCursorStops["Left"] = 2] = "Left"; InjectedTextCursorStops[InjectedTextCursorStops["None"] = 3] = "None"; })(InjectedTextCursorStops = exports.InjectedTextCursorStops || (exports.InjectedTextCursorStops = {})); 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["Digit0"] = 21] = "Digit0"; KeyCode[KeyCode["Digit1"] = 22] = "Digit1"; KeyCode[KeyCode["Digit2"] = 23] = "Digit2"; KeyCode[KeyCode["Digit3"] = 24] = "Digit3"; KeyCode[KeyCode["Digit4"] = 25] = "Digit4"; KeyCode[KeyCode["Digit5"] = 26] = "Digit5"; KeyCode[KeyCode["Digit6"] = 27] = "Digit6"; KeyCode[KeyCode["Digit7"] = 28] = "Digit7"; KeyCode[KeyCode["Digit8"] = 29] = "Digit8"; KeyCode[KeyCode["Digit9"] = 30] = "Digit9"; KeyCode[KeyCode["KeyA"] = 31] = "KeyA"; KeyCode[KeyCode["KeyB"] = 32] = "KeyB"; KeyCode[KeyCode["KeyC"] = 33] = "KeyC"; KeyCode[KeyCode["KeyD"] = 34] = "KeyD"; KeyCode[KeyCode["KeyE"] = 35] = "KeyE"; KeyCode[KeyCode["KeyF"] = 36] = "KeyF"; KeyCode[KeyCode["KeyG"] = 37] = "KeyG"; KeyCode[KeyCode["KeyH"] = 38] = "KeyH"; KeyCode[KeyCode["KeyI"] = 39] = "KeyI"; KeyCode[KeyCode["KeyJ"] = 40] = "KeyJ"; KeyCode[KeyCode["KeyK"] = 41] = "KeyK"; KeyCode[KeyCode["KeyL"] = 42] = "KeyL"; KeyCode[KeyCode["KeyM"] = 43] = "KeyM"; KeyCode[KeyCode["KeyN"] = 44] = "KeyN"; KeyCode[KeyCode["KeyO"] = 45] = "KeyO"; KeyCode[KeyCode["KeyP"] = 46] = "KeyP"; KeyCode[KeyCode["KeyQ"] = 47] = "KeyQ"; KeyCode[KeyCode["KeyR"] = 48] = "KeyR"; KeyCode[KeyCode["KeyS"] = 49] = "KeyS"; KeyCode[KeyCode["KeyT"] = 50] = "KeyT"; KeyCode[KeyCode["KeyU"] = 51] = "KeyU"; KeyCode[KeyCode["KeyV"] = 52] = "KeyV"; KeyCode[KeyCode["KeyW"] = 53] = "KeyW"; KeyCode[KeyCode["KeyX"] = 54] = "KeyX"; KeyCode[KeyCode["KeyY"] = 55] = "KeyY"; KeyCode[KeyCode["KeyZ"] = 56] = "KeyZ"; KeyCode[KeyCode["Meta"] = 57] = "Meta"; KeyCode[KeyCode["ContextMenu"] = 58] = "ContextMenu"; KeyCode[KeyCode["F1"] = 59] = "F1"; KeyCode[KeyCode["F2"] = 60] = "F2"; KeyCode[KeyCode["F3"] = 61] = "F3"; KeyCode[KeyCode["F4"] = 62] = "F4"; KeyCode[KeyCode["F5"] = 63] = "F5"; KeyCode[KeyCode["F6"] = 64] = "F6"; KeyCode[KeyCode["F7"] = 65] = "F7"; KeyCode[KeyCode["F8"] = 66] = "F8"; KeyCode[KeyCode["F9"] = 67] = "F9"; KeyCode[KeyCode["F10"] = 68] = "F10"; KeyCode[KeyCode["F11"] = 69] = "F11"; KeyCode[KeyCode["F12"] = 70] = "F12"; KeyCode[KeyCode["F13"] = 71] = "F13"; KeyCode[KeyCode["F14"] = 72] = "F14"; KeyCode[KeyCode["F15"] = 73] = "F15"; KeyCode[KeyCode["F16"] = 74] = "F16"; KeyCode[KeyCode["F17"] = 75] = "F17"; KeyCode[KeyCode["F18"] = 76] = "F18"; KeyCode[KeyCode["F19"] = 77] = "F19"; KeyCode[KeyCode["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["Semicolon"] = 80] = "Semicolon"; /** * For any country/region, the '+' key * For the US standard keyboard, the '=+' key */ KeyCode[KeyCode["Equal"] = 81] = "Equal"; /** * For any country/region, the ',' key * For the US standard keyboard, the ',<' key */ KeyCode[KeyCode["Comma"] = 82] = "Comma"; /** * For any country/region, the '-' key * For the US standard keyboard, the '-_' key */ KeyCode[KeyCode["Minus"] = 83] = "Minus"; /** * For any country/region, the '.' key * For the US standard keyboard, the '.>' key */ KeyCode[KeyCode["Period"] = 84] = "Period"; /** * Used for miscellaneous characters; it can vary by keyboard. * For the US standard keyboard, the '/?' key */ KeyCode[KeyCode["Slash"] = 85] = "Slash"; /** * Used for miscellaneous characters; it can vary by keyboard. * For the US standard keyboard, the '`~' key */ KeyCode[KeyCode["Backquote"] = 86] = "Backquote"; /** * Used for miscellaneous characters; it can vary by keyboard. * For the US standard keyboard, the '[{' key */ KeyCode[KeyCode["BracketLeft"] = 87] = "BracketLeft"; /** * Used for miscellaneous characters; it can vary by keyboard. * For the US standard keyboard, the '\|' key */ KeyCode[KeyCode["Backslash"] = 88] = "Backslash"; /** * Used for miscellaneous characters; it can vary by keyboard. * For the US standard keyboard, the ']}' key */ KeyCode[KeyCode["BracketRight"] = 89] = "BracketRight"; /** * Used for miscellaneous characters; it can vary by keyboard. * For the US standard keyboard, the ''"' key */ KeyCode[KeyCode["Quote"] = 90] = "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["IntlBackslash"] = 92] = "IntlBackslash"; KeyCode[KeyCode["Numpad0"] = 93] = "Numpad0"; KeyCode[KeyCode["Numpad1"] = 94] = "Numpad1"; KeyCode[KeyCode["Numpad2"] = 95] = "Numpad2"; KeyCode[KeyCode["Numpad3"] = 96] = "Numpad3"; KeyCode[KeyCode["Numpad4"] = 97] = "Numpad4"; KeyCode[KeyCode["Numpad5"] = 98] = "Numpad5"; KeyCode[KeyCode["Numpad6"] = 99] = "Numpad6"; KeyCode[KeyCode["Numpad7"] = 100] = "Numpad7"; KeyCode[KeyCode["Numpad8"] = 101] = "Numpad8"; KeyCode[KeyCode["Numpad9"] = 102] = "Numpad9"; KeyCode[KeyCode["NumpadMultiply"] = 103] = "NumpadMultiply"; KeyCode[KeyCode["NumpadAdd"] = 104] = "NumpadAdd"; KeyCode[KeyCode["NUMPAD_SEPARATOR"] = 105] = "NUMPAD_SEPARATOR"; KeyCode[KeyCode["NumpadSubtract"] = 106] = "NumpadSubtract"; KeyCode[KeyCode["NumpadDecimal"] = 107] = "NumpadDecimal"; KeyCode[KeyCode["NumpadDivide"] = 108] = "NumpadDivide"; /** * 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"; KeyCode[KeyCode["AudioVolumeMute"] = 112] = "AudioVolumeMute"; KeyCode[KeyCode["AudioVolumeUp"] = 113] = "AudioVolumeUp"; KeyCode[KeyCode["AudioVolumeDown"] = 114] = "AudioVolumeDown"; KeyCode[KeyCode["BrowserSearch"] = 115] = "BrowserSearch"; KeyCode[KeyCode["BrowserHome"] = 116] = "BrowserHome"; KeyCode[KeyCode["BrowserBack"] = 117] = "BrowserBack"; KeyCode[KeyCode["BrowserForward"] = 118] = "BrowserForward"; KeyCode[KeyCode["MediaTrackNext"] = 119] = "MediaTrackNext"; KeyCode[KeyCode["MediaTrackPrevious"] = 120] = "MediaTrackPrevious"; KeyCode[KeyCode["MediaStop"] = 121] = "MediaStop"; KeyCode[KeyCode["MediaPlayPause"] = 122] = "MediaPlayPause"; KeyCode[KeyCode["LaunchMediaPlayer"] = 123] = "LaunchMediaPlayer"; KeyCode[KeyCode["LaunchMail"] = 124] = "LaunchMail"; KeyCode[KeyCode["LaunchApp2"] = 125] = "LaunchApp2"; /** * Placed last to cover the length of the enum. * Please do not depend on this value! */ KeyCode[KeyCode["MAX_VALUE"] = 126] = "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 PositionAffinity; (function (PositionAffinity) { /** * Prefers the left most position. */ PositionAffinity[PositionAffinity["Left"] = 0] = "Left"; /** * Prefers the right most position. */ PositionAffinity[PositionAffinity["Right"] = 1] = "Right"; /** * No preference. */ PositionAffinity[PositionAffinity["None"] = 2] = "None"; })(PositionAffinity = exports.PositionAffinity || (exports.PositionAffinity = {})); var RenderLineNumbersType; (function (RenderLineNumbersType) { RenderLineNumbersType[RenderLineNumbersType["Off"] = 0] = "Off"; RenderLineNumbersType[RenderLineNumbersType["On"] = 1] = "On"; RenderLineNumbersType[RenderLineNumbersType["Relative"] = 2] = "Relative"; RenderLineNumbersType[RenderLineNumbersType["Interval"] = 3] = "Interval"; RenderLineNumbersType[RenderLineNumbersType["Custom"] = 4] = "Custom"; })(RenderLineNumbersType = exports.RenderLineNumbersType || (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[424/*vs/editor/common/textModelBracketPairs*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BracketPairWithMinIndentationInfo = exports.BracketPairInfo = exports.BracketInfo = void 0; class BracketInfo { constructor(range, /** 0-based level */ nestingLevel, isInvalid) { this.range = range; this.nestingLevel = nestingLevel; this.isInvalid = isInvalid; } } exports.BracketInfo = BracketInfo; class BracketPairInfo { constructor(range, openingBracketRange, closingBracketRange, /** * 0-based */ nestingLevel) { this.range = range; this.openingBracketRange = openingBracketRange; this.closingBracketRange = closingBracketRange; this.nestingLevel = nestingLevel; } } exports.BracketPairInfo = BracketPairInfo; class BracketPairWithMinIndentationInfo extends BracketPairInfo { constructor(range, openingBracketRange, closingBracketRange, /** * 0-based */ nestingLevel, /** * -1 if not requested, otherwise the size of the minimum indentation in the bracket pair in terms of visible columns. */ minVisibleColumnIndentation) { super(range, openingBracketRange, closingBracketRange, nestingLevel); this.minVisibleColumnIndentation = minVisibleColumnIndentation; } } exports.BracketPairWithMinIndentationInfo = BracketPairWithMinIndentationInfo; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[91/*vs/editor/common/textModelEvents*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.InternalModelContentChangeEvent = exports.ModelInjectedTextChangedEvent = exports.ModelRawContentChangedEvent = exports.ModelRawEOLChanged = exports.ModelRawLinesInserted = exports.ModelRawLinesDeleted = exports.ModelRawLineChanged = exports.LineInjectedText = exports.ModelRawFlush = void 0; /** * An event describing that a model has been reset to a new value. * @internal */ class ModelRawFlush { constructor() { this.changeType = 1 /* 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[180/*vs/editor/common/textModelGuides*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IndentGuideHorizontalLine = exports.IndentGuide = exports.HorizontalGuidesState = void 0; var HorizontalGuidesState; (function (HorizontalGuidesState) { HorizontalGuidesState[HorizontalGuidesState["Disabled"] = 0] = "Disabled"; HorizontalGuidesState[HorizontalGuidesState["EnabledForActive"] = 1] = "EnabledForActive"; HorizontalGuidesState[HorizontalGuidesState["Enabled"] = 2] = "Enabled"; })(HorizontalGuidesState = exports.HorizontalGuidesState || (exports.HorizontalGuidesState = {})); class IndentGuide { constructor(visibleColumn, className, /** * If set, this indent guide is a horizontal guide (no vertical part). * It starts at visibleColumn and continues until endColumn. */ horizontalLine) { this.visibleColumn = visibleColumn; this.className = className; this.horizontalLine = horizontalLine; } } exports.IndentGuide = IndentGuide; class IndentGuideHorizontalLine { constructor(top, endColumn) { this.top = top; this.endColumn = endColumn; } } exports.IndentGuideHorizontalLine = IndentGuideHorizontalLine; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[246/*vs/editor/common/model/guidesTextModelPart*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,8/*vs/base/common/strings*/,68/*vs/editor/common/core/cursorColumns*/,3/*vs/editor/common/core/range*/,420/*vs/editor/common/model/textModelPart*/,178/*vs/editor/common/model/utils*/,180/*vs/editor/common/textModelGuides*/]), function (require, exports, arrays_1, strings, cursorColumns_1, range_1, textModelPart_1, utils_1, textModelGuides_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BracketPairGuidesClassNames = exports.GuidesTextModelPart = void 0; class GuidesTextModelPart extends textModelPart_1.TextModelPart { constructor(textModel, languageConfigurationService) { super(); this.textModel = textModel; this.languageConfigurationService = languageConfigurationService; } getLanguageConfiguration(languageId) { return this.languageConfigurationService.getLanguageConfiguration(languageId); } _computeIndentLevel(lineIndex) { return (0, utils_1.computeIndentLevel)(this.textModel.getLineContent(lineIndex + 1), this.textModel.getOptions().tabSize); } getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) { this.assertNotDisposed(); const lineCount = this.textModel.getLineCount(); if (lineNumber < 1 || lineNumber > lineCount) { throw new Error('Illegal value for lineNumber'); } const foldingRules = this.getLanguageConfiguration(this.textModel.getLanguageId()).foldingRules; const offSide = Boolean(foldingRules && foldingRules.offSide); let up_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */ let up_aboveContentLineIndent = -1; let up_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */ let up_belowContentLineIndent = -1; const up_resolveIndents = (lineNumber) => { if (up_aboveContentLineIndex !== -1 && (up_aboveContentLineIndex === -2 || up_aboveContentLineIndex > lineNumber - 1)) { up_aboveContentLineIndex = -1; up_aboveContentLineIndent = -1; // must find previous line with content for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) { const indent = this._computeIndentLevel(lineIndex); if (indent >= 0) { up_aboveContentLineIndex = lineIndex; up_aboveContentLineIndent = indent; break; } } } if (up_belowContentLineIndex === -2) { up_belowContentLineIndex = -1; up_belowContentLineIndent = -1; // must find next line with content for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) { const indent = this._computeIndentLevel(lineIndex); if (indent >= 0) { up_belowContentLineIndex = lineIndex; up_belowContentLineIndent = indent; break; } } } }; let down_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */ let down_aboveContentLineIndent = -1; let down_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */ let down_belowContentLineIndent = -1; const down_resolveIndents = (lineNumber) => { if (down_aboveContentLineIndex === -2) { down_aboveContentLineIndex = -1; down_aboveContentLineIndent = -1; // must find previous line with content for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) { const indent = this._computeIndentLevel(lineIndex); if (indent >= 0) { down_aboveContentLineIndex = lineIndex; down_aboveContentLineIndent = indent; break; } } } if (down_belowContentLineIndex !== -1 && (down_belowContentLineIndex === -2 || down_belowContentLineIndex < lineNumber - 1)) { down_belowContentLineIndex = -1; down_belowContentLineIndent = -1; // must find next line with content for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) { const indent = this._computeIndentLevel(lineIndex); if (indent >= 0) { down_belowContentLineIndex = lineIndex; down_belowContentLineIndent = indent; break; } } } }; let startLineNumber = 0; let goUp = true; let endLineNumber = 0; let goDown = true; let indent = 0; let initialIndent = 0; for (let distance = 0; goUp || goDown; distance++) { const upLineNumber = lineNumber - distance; const downLineNumber = lineNumber + distance; if (distance > 1 && (upLineNumber < 1 || upLineNumber < minLineNumber)) { goUp = false; } if (distance > 1 && (downLineNumber > lineCount || downLineNumber > maxLineNumber)) { goDown = false; } if (distance > 50000) { // stop processing goUp = false; goDown = false; } let upLineIndentLevel = -1; if (goUp && upLineNumber >= 1) { // compute indent level going up const currentIndent = this._computeIndentLevel(upLineNumber - 1); if (currentIndent >= 0) { // This line has content (besides whitespace) // Use the line's indent up_belowContentLineIndex = upLineNumber - 1; up_belowContentLineIndent = currentIndent; upLineIndentLevel = Math.ceil(currentIndent / this.textModel.getOptions().indentSize); } else { up_resolveIndents(upLineNumber); upLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, up_aboveContentLineIndent, up_belowContentLineIndent); } } let downLineIndentLevel = -1; if (goDown && downLineNumber <= lineCount) { // compute indent level going down const currentIndent = this._computeIndentLevel(downLineNumber - 1); if (currentIndent >= 0) { // This line has content (besides whitespace) // Use the line's indent down_aboveContentLineIndex = downLineNumber - 1; down_aboveContentLineIndent = currentIndent; downLineIndentLevel = Math.ceil(currentIndent / this.textModel.getOptions().indentSize); } else { down_resolveIndents(downLineNumber); downLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, down_aboveContentLineIndent, down_belowContentLineIndent); } } if (distance === 0) { initialIndent = upLineIndentLevel; continue; } if (distance === 1) { if (downLineNumber <= lineCount && downLineIndentLevel >= 0 && initialIndent + 1 === downLineIndentLevel) { // This is the beginning of a scope, we have special handling here, since we want the // child scope indent to be active, not the parent scope goUp = false; startLineNumber = downLineNumber; endLineNumber = downLineNumber; indent = downLineIndentLevel; continue; } if (upLineNumber >= 1 && upLineIndentLevel >= 0 && upLineIndentLevel - 1 === initialIndent) { // This is the end of a scope, just like above goDown = false; startLineNumber = upLineNumber; endLineNumber = upLineNumber; indent = upLineIndentLevel; continue; } startLineNumber = lineNumber; endLineNumber = lineNumber; indent = initialIndent; if (indent === 0) { // No need to continue return { startLineNumber, endLineNumber, indent }; } } if (goUp) { if (upLineIndentLevel >= indent) { startLineNumber = upLineNumber; } else { goUp = false; } } if (goDown) { if (downLineIndentLevel >= indent) { endLineNumber = downLineNumber; } else { goDown = false; } } } return { startLineNumber, endLineNumber, indent }; } getLinesBracketGuides(startLineNumber, endLineNumber, activePosition, options) { var _a, _b, _c, _d, _e; const result = []; const bracketPairs = this.textModel.bracketPairs.getBracketPairsInRangeWithMinIndentation(new range_1.Range(startLineNumber, 1, endLineNumber, this.textModel.getLineMaxColumn(endLineNumber))); let activeBracketPairRange = undefined; if (activePosition && bracketPairs.length > 0) { const bracketsContainingActivePosition = startLineNumber <= activePosition.lineNumber && activePosition.lineNumber <= endLineNumber ? // Does active position intersect with the view port? -> Intersect bracket pairs with activePosition bracketPairs.filter((bp) => range_1.Range.strictContainsPosition(bp.range, activePosition)) : this.textModel.bracketPairs.getBracketPairsInRange(range_1.Range.fromPositions(activePosition)); activeBracketPairRange = (_a = (0, arrays_1.findLast)(bracketsContainingActivePosition, /* Exclude single line bracket pairs for cases such as * ``` * function test() { * if (true) { | } * } * ``` */ (i) => i.range.startLineNumber !== i.range.endLineNumber)) === null || _a === void 0 ? void 0 : _a.range; } const queue = new arrays_1.ArrayQueue(bracketPairs); /** Indexed by nesting level */ const activeGuides = new Array(); const nextGuides = new Array(); const colorProvider = new BracketPairGuidesClassNames(); for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { let guides = new Array(); if (nextGuides.length > 0) { guides = guides.concat(nextGuides); nextGuides.length = 0; } result.push(guides); // Update activeGuides for (const pair of queue.takeWhile((b) => b.openingBracketRange.startLineNumber <= lineNumber) || []) { if (pair.range.startLineNumber === pair.range.endLineNumber) { // ignore single line brackets continue; } const guideVisibleColumn = Math.min(this.getVisibleColumnFromPosition(pair.openingBracketRange.getStartPosition()), this.getVisibleColumnFromPosition((_c = (_b = pair.closingBracketRange) === null || _b === void 0 ? void 0 : _b.getStartPosition()) !== null && _c !== void 0 ? _c : pair.range.getEndPosition()), pair.minVisibleColumnIndentation + 1); let renderHorizontalEndLineAtTheBottom = false; if (pair.closingBracketRange) { const firstNonWsIndex = strings.firstNonWhitespaceIndex(this.textModel.getLineContent(pair.closingBracketRange.startLineNumber)); if (firstNonWsIndex < pair.closingBracketRange.startColumn - 1) { renderHorizontalEndLineAtTheBottom = true; } } const start = pair.openingBracketRange.getStartPosition(); const end = (_e = (_d = pair.closingBracketRange) === null || _d === void 0 ? void 0 : _d.getStartPosition()) !== null && _e !== void 0 ? _e : pair.range.getEndPosition(); if (pair.closingBracketRange === undefined) { // Don't show guides for bracket pairs that are not balanced. // See #135125. activeGuides[pair.nestingLevel] = null; } else { activeGuides[pair.nestingLevel] = { nestingLevel: pair.nestingLevel, guideVisibleColumn, start, visibleStartColumn: this.getVisibleColumnFromPosition(start), end, visibleEndColumn: this.getVisibleColumnFromPosition(end), bracketPair: pair, renderHorizontalEndLineAtTheBottom, }; } } for (const line of activeGuides) { if (!line) { continue; } const isActive = activeBracketPairRange && line.bracketPair.range.equalsRange(activeBracketPairRange); const className = colorProvider.getInlineClassNameOfLevel(line.nestingLevel) + (options.highlightActive && isActive ? ' ' + colorProvider.activeClassName : ''); if ((isActive && options.horizontalGuides !== textModelGuides_1.HorizontalGuidesState.Disabled) || (options.includeInactive && options.horizontalGuides === textModelGuides_1.HorizontalGuidesState.Enabled)) { if (line.start.lineNumber === lineNumber) { if (line.guideVisibleColumn < line.visibleStartColumn) { guides.push(new textModelGuides_1.IndentGuide(line.guideVisibleColumn, className, new textModelGuides_1.IndentGuideHorizontalLine(false, line.start.column))); } } if (line.end.lineNumber === lineNumber + 1) { // The next line might have horizontal guides. // However, the next line might also have a new bracket pair with the same indentation, // so the current bracket pair might get replaced. That's why we push the guide to nextGuides one line ahead. if (line.guideVisibleColumn < line.visibleEndColumn) { nextGuides.push(new textModelGuides_1.IndentGuide(line.guideVisibleColumn, className, new textModelGuides_1.IndentGuideHorizontalLine(!line.renderHorizontalEndLineAtTheBottom, line.end.column))); } } } } let lastVisibleColumnCount = Number.MAX_SAFE_INTEGER; // Going backwards, so the last guide potentially replaces others for (let i = activeGuides.length - 1; i >= 0; i--) { const line = activeGuides[i]; if (!line) { continue; } const isActive = options.highlightActive && activeBracketPairRange && line.bracketPair.range.equalsRange(activeBracketPairRange); const className = colorProvider.getInlineClassNameOfLevel(line.nestingLevel) + (isActive ? ' ' + colorProvider.activeClassName : ''); if (isActive || options.includeInactive) { if (line.renderHorizontalEndLineAtTheBottom && line.end.lineNumber === lineNumber + 1) { nextGuides.push(new textModelGuides_1.IndentGuide(line.guideVisibleColumn, className, null)); } } if (line.end.lineNumber <= lineNumber || line.start.lineNumber >= lineNumber) { continue; } if (line.guideVisibleColumn >= lastVisibleColumnCount && !isActive) { // Don't render a guide on top of an existing guide, unless it is active. continue; } lastVisibleColumnCount = line.guideVisibleColumn; if (isActive || options.includeInactive) { guides.push(new textModelGuides_1.IndentGuide(line.guideVisibleColumn, className, null)); } } guides.sort((a, b) => a.visibleColumn - b.visibleColumn); } return result; } getVisibleColumnFromPosition(position) { return (cursorColumns_1.CursorColumns.visibleColumnFromColumn(this.textModel.getLineContent(position.lineNumber), position.column, this.textModel.getOptions().tabSize) + 1); } getLinesIndentGuides(startLineNumber, endLineNumber) { this.assertNotDisposed(); const lineCount = this.textModel.getLineCount(); if (startLineNumber < 1 || startLineNumber > lineCount) { throw new Error('Illegal value for startLineNumber'); } if (endLineNumber < 1 || endLineNumber > lineCount) { throw new Error('Illegal value for endLineNumber'); } const options = this.textModel.getOptions(); const foldingRules = this.getLanguageConfiguration(this.textModel.getLanguageId()).foldingRules; const offSide = Boolean(foldingRules && foldingRules.offSide); const result = new Array(endLineNumber - startLineNumber + 1); let aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */ let aboveContentLineIndent = -1; let belowContentLineIndex = -2; /* -2 is a marker for not having computed it */ let belowContentLineIndent = -1; for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { const resultIndex = lineNumber - startLineNumber; const currentIndent = this._computeIndentLevel(lineNumber - 1); if (currentIndent >= 0) { // This line has content (besides whitespace) // Use the line's indent aboveContentLineIndex = lineNumber - 1; aboveContentLineIndent = currentIndent; result[resultIndex] = Math.ceil(currentIndent / options.indentSize); continue; } if (aboveContentLineIndex === -2) { aboveContentLineIndex = -1; aboveContentLineIndent = -1; // must find previous line with content for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) { const indent = this._computeIndentLevel(lineIndex); if (indent >= 0) { aboveContentLineIndex = lineIndex; aboveContentLineIndent = indent; break; } } } if (belowContentLineIndex !== -1 && (belowContentLineIndex === -2 || belowContentLineIndex < lineNumber - 1)) { belowContentLineIndex = -1; belowContentLineIndent = -1; // must find next line with content for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) { const indent = this._computeIndentLevel(lineIndex); if (indent >= 0) { belowContentLineIndex = lineIndex; belowContentLineIndent = indent; break; } } } result[resultIndex] = this._getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent); } return result; } _getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent) { const options = this.textModel.getOptions(); if (aboveContentLineIndent === -1 || belowContentLineIndent === -1) { // At the top or bottom of the file return 0; } else if (aboveContentLineIndent < belowContentLineIndent) { // we are inside the region above return 1 + Math.floor(aboveContentLineIndent / options.indentSize); } else if (aboveContentLineIndent === belowContentLineIndent) { // we are in between two regions return Math.ceil(belowContentLineIndent / options.indentSize); } else { if (offSide) { // same level as region below return Math.ceil(belowContentLineIndent / options.indentSize); } else { // we are inside the region that ends below return 1 + Math.floor(belowContentLineIndent / options.indentSize); } } } } exports.GuidesTextModelPart = GuidesTextModelPart; class BracketPairGuidesClassNames { constructor() { this.activeClassName = 'indent-active'; } getInlineClassNameOfLevel(level) { // To support a dynamic amount of colors up to 6 colors, // we use a number that is a lcm of all numbers from 1 to 6. return `bracket-indent-guide lvl-${level % 30}`; } } exports.BracketPairGuidesClassNames = BracketPairGuidesClassNames; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[425/*vs/editor/common/tokenizationRegistry*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TokenizationRegistry = void 0; class TokenizationRegistry { constructor() { this._map = new Map(); this._factories = 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]); }); } registerFactory(languageId, factory) { var _a; (_a = this._factories.get(languageId)) === null || _a === void 0 ? void 0 : _a.dispose(); const myData = new TokenizationSupportFactoryData(this, languageId, factory); this._factories.set(languageId, myData); return (0, lifecycle_1.toDisposable)(() => { const v = this._factories.get(languageId); if (!v || v !== myData) { return; } this._factories.delete(languageId); v.dispose(); }); } getOrCreate(languageId) { return __awaiter(this, void 0, void 0, function* () { // check first if the support is already set const tokenizationSupport = this.get(languageId); if (tokenizationSupport) { return tokenizationSupport; } const factory = this._factories.get(languageId); if (!factory || factory.isResolved) { // no factory or factory.resolve already finished return null; } yield factory.resolve(); return this.get(languageId); }); } get(language) { return (this._map.get(language) || null); } isResolved(languageId) { const tokenizationSupport = this.get(languageId); if (tokenizationSupport) { return true; } const factory = this._factories.get(languageId); if (!factory || factory.isResolved) { return true; } return false; } setColorMap(colorMap) { this._colorMap = colorMap; this._onDidChange.fire({ changedLanguages: Array.from(this._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.TokenizationRegistry = TokenizationRegistry; class TokenizationSupportFactoryData extends lifecycle_1.Disposable { constructor(_registry, _languageId, _factory) { super(); this._registry = _registry; this._languageId = _languageId; this._factory = _factory; this._isDisposed = false; this._resolvePromise = null; this._isResolved = false; } get isResolved() { return this._isResolved; } dispose() { this._isDisposed = true; super.dispose(); } resolve() { return __awaiter(this, void 0, void 0, function* () { if (!this._resolvePromise) { this._resolvePromise = this._create(); } return this._resolvePromise; }); } _create() { return __awaiter(this, void 0, void 0, function* () { const value = yield Promise.resolve(this._factory.createTokenizationSupport()); this._isResolved = true; if (value && !this._isDisposed) { this._register(this._registry.register(this._languageId, 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[18/*vs/editor/common/languages*/], __M([1/*require*/,0/*exports*/,25/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,413/*vs/editor/common/languageFeatureRegistry*/,425/*vs/editor/common/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.InlineValuesProviderRegistry = exports.EvaluatableExpressionProviderRegistry = exports.HoverProviderRegistry = exports.SignatureHelpProviderRegistry = exports.InlineCompletionsProviderRegistry = exports.CompletionProviderRegistry = exports.RenameProviderRegistry = exports.ReferenceProviderRegistry = exports.InlayHintKind = exports.Command = exports.FoldingRangeKind = exports.SymbolKinds = exports.isLocationLink = exports.DocumentHighlightKind = exports.SignatureHelpTriggerKind = exports.InlineCompletionTriggerKind = exports.CompletionItemKinds = exports.EncodedTokenizationResult = exports.TokenizationResult = exports.Token = exports.TokenMetadata = void 0; /** * @internal */ class TokenMetadata { static getLanguageId(metadata) { return (metadata & 255 /* LANGUAGEID_MASK */) >>> 0 /* LANGUAGEID_OFFSET */; } static getTokenType(metadata) { return (metadata & 768 /* TOKEN_TYPE_MASK */) >>> 8 /* TOKEN_TYPE_OFFSET */; } static getFontStyle(metadata) { return (metadata & 15360 /* FONT_STYLE_MASK */) >>> 10 /* 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) { const foreground = this.getForeground(metadata); let className = 'mtk' + foreground; const fontStyle = this.getFontStyle(metadata); if (fontStyle & 1 /* Italic */) { className += ' mtki'; } if (fontStyle & 2 /* Bold */) { className += ' mtkb'; } if (fontStyle & 4 /* Underline */) { className += ' mtku'; } if (fontStyle & 8 /* Strikethrough */) { className += ' mtks'; } return className; } static getInlineStyleFromMetadata(metadata, colorMap) { const foreground = this.getForeground(metadata); const fontStyle = this.getFontStyle(metadata); let result = `color: ${colorMap[foreground]};`; if (fontStyle & 1 /* Italic */) { result += 'font-style: italic;'; } if (fontStyle & 2 /* Bold */) { result += 'font-weight: bold;'; } let textDecoration = ''; if (fontStyle & 4 /* Underline */) { textDecoration += ' underline'; } if (fontStyle & 8 /* Strikethrough */) { textDecoration += ' line-through'; } if (textDecoration) { result += `text-decoration:${textDecoration};`; } return result; } static getPresentationFromMetadata(metadata) { const foreground = this.getForeground(metadata); const fontStyle = this.getFontStyle(metadata); return { foreground: foreground, italic: Boolean(fontStyle & 1 /* Italic */), bold: Boolean(fontStyle & 2 /* Bold */), underline: Boolean(fontStyle & 4 /* Underline */), strikethrough: Boolean(fontStyle & 8 /* Strikethrough */), }; } } exports.TokenMetadata = TokenMetadata; class Token { constructor(offset, type, language) { this._tokenBrand = undefined; this.offset = offset; this.type = type; this.language = language; } toString() { return '(' + this.offset + ', ' + this.type + ')'; } } exports.Token = Token; /** * @internal */ class TokenizationResult { constructor(tokens, endState) { this._tokenizationResultBrand = undefined; this.tokens = tokens; this.endState = endState; } } exports.TokenizationResult = TokenizationResult; /** * @internal */ class EncodedTokenizationResult { constructor(tokens, endState) { this._encodedTokenizationResultBrand = undefined; this.tokens = tokens; this.endState = endState; } } exports.EncodedTokenizationResult = EncodedTokenizationResult; /** * @internal */ var CompletionItemKinds; (function (CompletionItemKinds) { const byKind = new Map(); byKind.set(0 /* Method */, codicons_1.Codicon.symbolMethod); byKind.set(1 /* Function */, codicons_1.Codicon.symbolFunction); byKind.set(2 /* Constructor */, codicons_1.Codicon.symbolConstructor); byKind.set(3 /* Field */, codicons_1.Codicon.symbolField); byKind.set(4 /* Variable */, codicons_1.Codicon.symbolVariable); byKind.set(5 /* Class */, codicons_1.Codicon.symbolClass); byKind.set(6 /* Struct */, codicons_1.Codicon.symbolStruct); byKind.set(7 /* Interface */, codicons_1.Codicon.symbolInterface); byKind.set(8 /* Module */, codicons_1.Codicon.symbolModule); byKind.set(9 /* Property */, codicons_1.Codicon.symbolProperty); byKind.set(10 /* Event */, codicons_1.Codicon.symbolEvent); byKind.set(11 /* Operator */, codicons_1.Codicon.symbolOperator); byKind.set(12 /* Unit */, codicons_1.Codicon.symbolUnit); byKind.set(13 /* Value */, codicons_1.Codicon.symbolValue); byKind.set(15 /* Enum */, codicons_1.Codicon.symbolEnum); byKind.set(14 /* Constant */, codicons_1.Codicon.symbolConstant); byKind.set(15 /* Enum */, codicons_1.Codicon.symbolEnum); byKind.set(16 /* EnumMember */, codicons_1.Codicon.symbolEnumMember); byKind.set(17 /* Keyword */, codicons_1.Codicon.symbolKeyword); byKind.set(27 /* Snippet */, codicons_1.Codicon.symbolSnippet); byKind.set(18 /* Text */, codicons_1.Codicon.symbolText); byKind.set(19 /* Color */, codicons_1.Codicon.symbolColor); byKind.set(20 /* File */, codicons_1.Codicon.symbolFile); byKind.set(21 /* Reference */, codicons_1.Codicon.symbolReference); byKind.set(22 /* Customcolor */, codicons_1.Codicon.symbolCustomColor); byKind.set(23 /* Folder */, codicons_1.Codicon.symbolFolder); byKind.set(24 /* TypeParameter */, codicons_1.Codicon.symbolTypeParameter); byKind.set(25 /* User */, codicons_1.Codicon.account); byKind.set(26 /* Issue */, codicons_1.Codicon.issues); /** * @internal */ function toIcon(kind) { let codicon = byKind.get(kind); if (!codicon) { console.info('No codicon found for CompletionItemKind ' + kind); codicon = codicons_1.Codicon.symbolProperty; } return codicon; } CompletionItemKinds.toIcon = toIcon; const data = new Map(); data.set('method', 0 /* Method */); data.set('function', 1 /* Function */); data.set('constructor', 2 /* Constructor */); data.set('field', 3 /* Field */); data.set('variable', 4 /* Variable */); data.set('class', 5 /* Class */); data.set('struct', 6 /* Struct */); data.set('interface', 7 /* Interface */); data.set('module', 8 /* Module */); data.set('property', 9 /* Property */); data.set('event', 10 /* Event */); data.set('operator', 11 /* Operator */); data.set('unit', 12 /* Unit */); data.set('value', 13 /* Value */); data.set('constant', 14 /* Constant */); data.set('enum', 15 /* Enum */); data.set('enum-member', 16 /* EnumMember */); data.set('enumMember', 16 /* EnumMember */); data.set('keyword', 17 /* Keyword */); data.set('snippet', 27 /* Snippet */); data.set('text', 18 /* Text */); data.set('color', 19 /* Color */); data.set('file', 20 /* File */); data.set('reference', 21 /* Reference */); data.set('customcolor', 22 /* Customcolor */); data.set('folder', 23 /* Folder */); data.set('type-parameter', 24 /* TypeParameter */); data.set('typeParameter', 24 /* TypeParameter */); data.set('account', 25 /* User */); data.set('issue', 26 /* Issue */); /** * @internal */ function fromString(value, strict) { let res = data.get(value); if (typeof res === 'undefined' && !strict) { res = 9 /* Property */; } return res; } CompletionItemKinds.fromString = fromString; })(CompletionItemKinds = exports.CompletionItemKinds || (exports.CompletionItemKinds = {})); /** * How an {@link InlineCompletionsProvider inline completion provider} was triggered. */ var InlineCompletionTriggerKind; (function (InlineCompletionTriggerKind) { /** * Completion was triggered automatically while editing. * It is sufficient to return a single completion item in this case. */ InlineCompletionTriggerKind[InlineCompletionTriggerKind["Automatic"] = 0] = "Automatic"; /** * Completion was triggered explicitly by a user gesture. * Return multiple completion items to enable cycling through them. */ InlineCompletionTriggerKind[InlineCompletionTriggerKind["Explicit"] = 1] = "Explicit"; })(InlineCompletionTriggerKind = exports.InlineCompletionTriggerKind || (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 byKind = new Map(); byKind.set(0 /* File */, codicons_1.Codicon.symbolFile); byKind.set(1 /* Module */, codicons_1.Codicon.symbolModule); byKind.set(2 /* Namespace */, codicons_1.Codicon.symbolNamespace); byKind.set(3 /* Package */, codicons_1.Codicon.symbolPackage); byKind.set(4 /* Class */, codicons_1.Codicon.symbolClass); byKind.set(5 /* Method */, codicons_1.Codicon.symbolMethod); byKind.set(6 /* Property */, codicons_1.Codicon.symbolProperty); byKind.set(7 /* Field */, codicons_1.Codicon.symbolField); byKind.set(8 /* Constructor */, codicons_1.Codicon.symbolConstructor); byKind.set(9 /* Enum */, codicons_1.Codicon.symbolEnum); byKind.set(10 /* Interface */, codicons_1.Codicon.symbolInterface); byKind.set(11 /* Function */, codicons_1.Codicon.symbolFunction); byKind.set(12 /* Variable */, codicons_1.Codicon.symbolVariable); byKind.set(13 /* Constant */, codicons_1.Codicon.symbolConstant); byKind.set(14 /* String */, codicons_1.Codicon.symbolString); byKind.set(15 /* Number */, codicons_1.Codicon.symbolNumber); byKind.set(16 /* Boolean */, codicons_1.Codicon.symbolBoolean); byKind.set(17 /* Array */, codicons_1.Codicon.symbolArray); byKind.set(18 /* Object */, codicons_1.Codicon.symbolObject); byKind.set(19 /* Key */, codicons_1.Codicon.symbolKey); byKind.set(20 /* Null */, codicons_1.Codicon.symbolNull); byKind.set(21 /* EnumMember */, codicons_1.Codicon.symbolEnumMember); byKind.set(22 /* Struct */, codicons_1.Codicon.symbolStruct); byKind.set(23 /* Event */, codicons_1.Codicon.symbolEvent); byKind.set(24 /* Operator */, codicons_1.Codicon.symbolOperator); byKind.set(25 /* TypeParameter */, codicons_1.Codicon.symbolTypeParameter); /** * @internal */ function toIcon(kind) { let icon = byKind.get(kind); if (!icon) { console.info('No codicon found for SymbolKind ' + kind); icon = codicons_1.Codicon.symbolProperty; } return icon; } SymbolKinds.toIcon = toIcon; })(SymbolKinds = exports.SymbolKinds || (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'); /** * @internal */ var Command; (function (Command) { /** * @internal */ function is(obj) { if (!obj || typeof obj !== 'object') { return false; } return typeof obj.id === 'string' && typeof obj.title === 'string'; } Command.is = is; })(Command = exports.Command || (exports.Command = {})); 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.EvaluatableExpressionProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry(); /** * @internal */ exports.InlineValuesProviderRegistry = 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.TokenizationRegistry(); }); /*--------------------------------------------------------------------------------------------- * 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/editor/common/languages/nullMode*/], __M([1/*require*/,0/*exports*/,18/*vs/editor/common/languages*/]), function (require, exports, languages_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.nullTokenizeEncoded = exports.nullTokenize = exports.NullState = void 0; exports.NullState = new class { clone() { return this; } equals(other) { return (this === other); } }; function nullTokenize(languageId, state) { return new languages_1.TokenizationResult([new languages_1.Token(0, '', languageId)], state); } exports.nullTokenize = nullTokenize; function nullTokenizeEncoded(languageId, state) { const tokens = new Uint32Array(2); tokens[0] = 0; tokens[1] = ((languageId << 0 /* LANGUAGEID_OFFSET */) | (0 /* Other */ << 8 /* TOKEN_TYPE_OFFSET */) | (0 /* None */ << 10 /* FONT_STYLE_OFFSET */) | (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */) | (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0; return new languages_1.EncodedTokenizationResult(tokens, state === null ? exports.NullState : state); } exports.nullTokenizeEncoded = nullTokenizeEncoded; }); /*--------------------------------------------------------------------------------------------- * 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/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/tokenizer*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/errors*/,18/*vs/editor/common/languages*/,149/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/ast*/,83/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/,99/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet*/]), function (require, exports, errors_1, languages_1, ast_1, length_1, smallImmutableSet_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FastTokenizer = exports.TextBufferTokenizer = exports.Token = void 0; class Token { constructor(length, kind, /** * If this token is an opening bracket, this is the id of the opening bracket. * If this token is a closing bracket, this is the id of the first opening bracket that is closed by this bracket. * Otherwise, it is -1. */ bracketId, /** * If this token is an opening bracket, this just contains `bracketId`. * If this token is a closing bracket, this lists all opening bracket ids, that it closes. * Otherwise, it is empty. */ bracketIds, astNode) { this.length = length; this.kind = kind; this.bracketId = bracketId; this.bracketIds = bracketIds; this.astNode = astNode; } } exports.Token = Token; class TextBufferTokenizer { constructor(textModel, bracketTokens) { this.textModel = textModel; this.bracketTokens = bracketTokens; this.reader = new NonPeekableTextBufferTokenizer(this.textModel, this.bracketTokens); this._offset = length_1.lengthZero; this.didPeek = false; this.peeked = null; this.textBufferLineCount = textModel.getLineCount(); this.textBufferLastLineLength = textModel.getLineLength(this.textBufferLineCount); } get offset() { return this._offset; } get length() { return (0, length_1.toLength)(this.textBufferLineCount, this.textBufferLastLineLength); } skip(length) { this.didPeek = false; this._offset = (0, length_1.lengthAdd)(this._offset, length); const obj = (0, length_1.lengthToObj)(this._offset); this.reader.setPosition(obj.lineCount, obj.columnCount); } read() { let token; if (this.peeked) { this.didPeek = false; token = this.peeked; } else { token = this.reader.read(); } if (token) { this._offset = (0, length_1.lengthAdd)(this._offset, token.length); } return token; } peek() { if (!this.didPeek) { this.peeked = this.reader.read(); this.didPeek = true; } return this.peeked; } } exports.TextBufferTokenizer = TextBufferTokenizer; /** * Does not support peek. */ class NonPeekableTextBufferTokenizer { constructor(textModel, bracketTokens) { this.textModel = textModel; this.bracketTokens = bracketTokens; this.lineIdx = 0; this.line = null; this.lineCharOffset = 0; this.lineTokens = null; this.lineTokenOffset = 0; /** Must be a zero line token. The end of the document cannot be peeked. */ this.peekedToken = null; this.textBufferLineCount = textModel.getLineCount(); this.textBufferLastLineLength = textModel.getLineLength(this.textBufferLineCount); } setPosition(lineIdx, column) { // We must not jump into a token! if (lineIdx === this.lineIdx) { this.lineCharOffset = column; this.lineTokenOffset = this.lineCharOffset === 0 ? 0 : this.lineTokens.findTokenIndexAtOffset(this.lineCharOffset); } else { this.lineIdx = lineIdx; this.lineCharOffset = column; this.line = null; } this.peekedToken = null; } read() { if (this.peekedToken) { const token = this.peekedToken; this.peekedToken = null; this.lineCharOffset += (0, length_1.lengthGetColumnCountIfZeroLineCount)(token.length); return token; } if (this.lineIdx > this.textBufferLineCount - 1 || (this.lineIdx === this.textBufferLineCount - 1 && this.lineCharOffset >= this.textBufferLastLineLength)) { // We are after the end return null; } if (this.line === null) { this.lineTokens = this.textModel.getLineTokens(this.lineIdx + 1); this.line = this.lineTokens.getLineContent(); this.lineTokenOffset = this.lineCharOffset === 0 ? 0 : this.lineTokens.findTokenIndexAtOffset(this.lineCharOffset); } const startLineIdx = this.lineIdx; const startLineCharOffset = this.lineCharOffset; // limits the length of text tokens. // If text tokens get too long, incremental updates will be slow let lengthHeuristic = 0; while (true) { const lineTokens = this.lineTokens; const tokenCount = lineTokens.getCount(); let peekedBracketToken = null; if (this.lineTokenOffset < tokenCount) { const tokenMetadata = lineTokens.getMetadata(this.lineTokenOffset); while (this.lineTokenOffset + 1 < tokenCount && tokenMetadata === lineTokens.getMetadata(this.lineTokenOffset + 1)) { // Skip tokens that are identical. // Sometimes, (bracket) identifiers are split up into multiple tokens. this.lineTokenOffset++; } const isOther = languages_1.TokenMetadata.getTokenType(tokenMetadata) === 0 /* Other */; const endOffset = lineTokens.getEndOffset(this.lineTokenOffset); // Is there a bracket token next? Only consume text. if (isOther && endOffset !== this.lineCharOffset) { const languageId = lineTokens.getLanguageId(this.lineTokenOffset); const text = this.line.substring(this.lineCharOffset, endOffset); const brackets = this.bracketTokens.getSingleLanguageBracketTokens(languageId); const regexp = brackets.regExpGlobal; if (regexp) { regexp.lastIndex = 0; const match = regexp.exec(text); if (match) { peekedBracketToken = brackets.getToken(match[0]); if (peekedBracketToken) { // Consume leading text of the token this.lineCharOffset += match.index; } } } } lengthHeuristic += endOffset - this.lineCharOffset; if (peekedBracketToken) { // Don't skip the entire token, as a single token could contain multiple brackets. if (startLineIdx !== this.lineIdx || startLineCharOffset !== this.lineCharOffset) { // There is text before the bracket this.peekedToken = peekedBracketToken; break; } else { // Consume the peeked token this.lineCharOffset += (0, length_1.lengthGetColumnCountIfZeroLineCount)(peekedBracketToken.length); return peekedBracketToken; } } else { // Skip the entire token, as the token contains no brackets at all. this.lineTokenOffset++; this.lineCharOffset = endOffset; } } else { if (this.lineIdx === this.textBufferLineCount - 1) { break; } this.lineIdx++; this.lineTokens = this.textModel.getLineTokens(this.lineIdx + 1); this.lineTokenOffset = 0; this.line = this.lineTokens.getLineContent(); this.lineCharOffset = 0; lengthHeuristic += 33; // max 1000/33 = 30 lines // This limits the amount of work to recompute min-indentation if (lengthHeuristic > 1000) { // only break (automatically) at the end of line. break; } } if (lengthHeuristic > 1500) { // Eventually break regardless of the line length so that // very long lines do not cause bad performance. // This effective limits max indentation to 500, as // indentation is not computed across multiple text nodes. break; } } // If a token contains some proper indentation, it also contains \n{INDENTATION+}(?!{INDENTATION}), // unless the line is too long. // Thus, the min indentation of the document is the minimum min indentation of every text node. const length = (0, length_1.lengthDiff)(startLineIdx, startLineCharOffset, this.lineIdx, this.lineCharOffset); return new Token(length, 0 /* Text */, -1, smallImmutableSet_1.SmallImmutableSet.getEmpty(), new ast_1.TextAstNode(length)); } } class FastTokenizer { constructor(text, brackets) { this.text = text; this._offset = length_1.lengthZero; this.idx = 0; const regExpStr = brackets.getRegExpStr(); const regexp = regExpStr ? new RegExp(brackets.getRegExpStr() + '|\n', 'g') : null; const tokens = []; let match; let curLineCount = 0; let lastLineBreakOffset = 0; let lastTokenEndOffset = 0; let lastTokenEndLine = 0; const smallTextTokens0Line = new Array(); for (let i = 0; i < 60; i++) { smallTextTokens0Line.push(new Token((0, length_1.toLength)(0, i), 0 /* Text */, -1, smallImmutableSet_1.SmallImmutableSet.getEmpty(), new ast_1.TextAstNode((0, length_1.toLength)(0, i)))); } const smallTextTokens1Line = new Array(); for (let i = 0; i < 60; i++) { smallTextTokens1Line.push(new Token((0, length_1.toLength)(1, i), 0 /* Text */, -1, smallImmutableSet_1.SmallImmutableSet.getEmpty(), new ast_1.TextAstNode((0, length_1.toLength)(1, i)))); } if (regexp) { regexp.lastIndex = 0; // If a token contains indentation, it also contains \n{INDENTATION+}(?!{INDENTATION}) while ((match = regexp.exec(text)) !== null) { const curOffset = match.index; const value = match[0]; if (value === '\n') { curLineCount++; lastLineBreakOffset = curOffset + 1; } else { if (lastTokenEndOffset !== curOffset) { let token; if (lastTokenEndLine === curLineCount) { const colCount = curOffset - lastTokenEndOffset; if (colCount < smallTextTokens0Line.length) { token = smallTextTokens0Line[colCount]; } else { const length = (0, length_1.toLength)(0, colCount); token = new Token(length, 0 /* Text */, -1, smallImmutableSet_1.SmallImmutableSet.getEmpty(), new ast_1.TextAstNode(length)); } } else { const lineCount = curLineCount - lastTokenEndLine; const colCount = curOffset - lastLineBreakOffset; if (lineCount === 1 && colCount < smallTextTokens1Line.length) { token = smallTextTokens1Line[colCount]; } else { const length = (0, length_1.toLength)(lineCount, colCount); token = new Token(length, 0 /* Text */, -1, smallImmutableSet_1.SmallImmutableSet.getEmpty(), new ast_1.TextAstNode(length)); } } tokens.push(token); } // value is matched by regexp, so the token must exist tokens.push(brackets.getToken(value)); lastTokenEndOffset = curOffset + value.length; lastTokenEndLine = curLineCount; } } } const offset = text.length; if (lastTokenEndOffset !== offset) { const length = (lastTokenEndLine === curLineCount) ? (0, length_1.toLength)(0, offset - lastTokenEndOffset) : (0, length_1.toLength)(curLineCount - lastTokenEndLine, offset - lastLineBreakOffset); tokens.push(new Token(length, 0 /* Text */, -1, smallImmutableSet_1.SmallImmutableSet.getEmpty(), new ast_1.TextAstNode(length))); } this.length = (0, length_1.toLength)(curLineCount, offset - lastLineBreakOffset); this.tokens = tokens; } get offset() { return this._offset; } read() { return this.tokens[this.idx++] || null; } peek() { return this.tokens[this.idx] || null; } skip(length) { throw new errors_1.NotSupportedError(); } } exports.FastTokenizer = FastTokenizer; }); define(__m[247/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/brackets*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,149/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/ast*/,83/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/,99/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet*/,181/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/tokenizer*/]), function (require, exports, strings_1, ast_1, length_1, smallImmutableSet_1, tokenizer_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LanguageAgnosticBracketTokens = exports.BracketTokens = void 0; class BracketTokens { constructor(map) { this.map = map; this.hasRegExp = false; this._regExpGlobal = null; } static createFromLanguage(configuration, denseKeyProvider) { function getId(languageId, openingText) { return denseKeyProvider.getKey(`${languageId}:::${openingText}`); } const brackets = configuration.characterPair.getColorizedBrackets(); const closingBrackets = new Map(); const openingBrackets = new Set(); for (const [openingText, closingText] of brackets) { openingBrackets.add(openingText); let info = closingBrackets.get(closingText); const openingTextId = getId(configuration.languageId, openingText); if (!info) { info = { openingBrackets: smallImmutableSet_1.SmallImmutableSet.getEmpty(), first: openingTextId }; closingBrackets.set(closingText, info); } info.openingBrackets = info.openingBrackets.add(openingTextId, smallImmutableSet_1.identityKeyProvider); } const map = new Map(); for (const [closingText, info] of closingBrackets) { const length = (0, length_1.toLength)(0, closingText.length); map.set(closingText, new tokenizer_1.Token(length, 2 /* ClosingBracket */, info.first, info.openingBrackets, ast_1.BracketAstNode.create(length, configuration.languageId, info.openingBrackets))); } for (const openingText of openingBrackets) { const length = (0, length_1.toLength)(0, openingText.length); const openingTextId = getId(configuration.languageId, openingText); const bracketIds = smallImmutableSet_1.SmallImmutableSet.getEmpty().add(openingTextId, smallImmutableSet_1.identityKeyProvider); map.set(openingText, new tokenizer_1.Token(length, 1 /* OpeningBracket */, openingTextId, bracketIds, ast_1.BracketAstNode.create(length, configuration.languageId, bracketIds))); } return new BracketTokens(map); } getRegExpStr() { if (this.isEmpty) { return null; } else { const keys = [...this.map.keys()]; keys.sort(); keys.reverse(); return keys.map(k => prepareBracketForRegExp(k)).join('|'); } } /** * Returns null if there is no such regexp (because there are no brackets). */ get regExpGlobal() { if (!this.hasRegExp) { const regExpStr = this.getRegExpStr(); this._regExpGlobal = regExpStr ? new RegExp(regExpStr, 'g') : null; this.hasRegExp = true; } return this._regExpGlobal; } getToken(value) { return this.map.get(value); } findClosingTokenText(openingBracketIds) { for (const [closingText, info] of this.map) { if (info.bracketIds.intersects(openingBracketIds)) { return closingText; } } return undefined; } get isEmpty() { return this.map.size === 0; } } exports.BracketTokens = BracketTokens; function prepareBracketForRegExp(str) { const escaped = (0, strings_1.escapeRegExpCharacters)(str); // This bracket pair uses letters like e.g. "begin" - "end" (see https://github.com/microsoft/vscode/issues/132162) const needsWordBoundaries = (/^[\w ]+$/.test(str)); return (needsWordBoundaries ? `\\b${escaped}\\b` : escaped); } class LanguageAgnosticBracketTokens { constructor(denseKeyProvider, getLanguageConfiguration) { this.denseKeyProvider = denseKeyProvider; this.getLanguageConfiguration = getLanguageConfiguration; this.languageIdToBracketTokens = new Map(); } didLanguageChange(languageId) { const existing = this.languageIdToBracketTokens.get(languageId); if (!existing) { return false; } const newRegExpStr = BracketTokens.createFromLanguage(this.getLanguageConfiguration(languageId), this.denseKeyProvider).getRegExpStr(); return existing.getRegExpStr() !== newRegExpStr; } getSingleLanguageBracketTokens(languageId) { let singleLanguageBracketTokens = this.languageIdToBracketTokens.get(languageId); if (!singleLanguageBracketTokens) { singleLanguageBracketTokens = BracketTokens.createFromLanguage(this.getLanguageConfiguration(languageId), this.denseKeyProvider); this.languageIdToBracketTokens.set(languageId, singleLanguageBracketTokens); } return singleLanguageBracketTokens; } } exports.LanguageAgnosticBracketTokens = LanguageAgnosticBracketTokens; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[426/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/bracketPairsTree*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/,424/*vs/editor/common/textModelBracketPairs*/,240/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/beforeEditPositionMapper*/,247/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/brackets*/,83/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/,241/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/parser*/,99/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet*/,181/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/tokenizer*/]), function (require, exports, event_1, lifecycle_1, range_1, textModelBracketPairs_1, beforeEditPositionMapper_1, brackets_1, length_1, parser_1, smallImmutableSet_1, tokenizer_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BracketPairsTree = void 0; class BracketPairsTree extends lifecycle_1.Disposable { constructor(textModel, getLanguageConfiguration) { super(); this.textModel = textModel; this.getLanguageConfiguration = getLanguageConfiguration; this.didChangeEmitter = new event_1.Emitter(); this.denseKeyProvider = new smallImmutableSet_1.DenseKeyProvider(); this.brackets = new brackets_1.LanguageAgnosticBracketTokens(this.denseKeyProvider, this.getLanguageConfiguration); this.onDidChange = this.didChangeEmitter.event; this._register(textModel.onBackgroundTokenizationStateChanged(() => { if (textModel.backgroundTokenizationState === 2 /* Completed */) { const wasUndefined = this.initialAstWithoutTokens === undefined; // Clear the initial tree as we can use the tree with token information now. this.initialAstWithoutTokens = undefined; if (!wasUndefined) { this.didChangeEmitter.fire(); } } })); this._register(textModel.onDidChangeTokens(({ ranges }) => { const edits = ranges.map(r => new beforeEditPositionMapper_1.TextEditInfo((0, length_1.toLength)(r.fromLineNumber - 1, 0), (0, length_1.toLength)(r.toLineNumber, 0), (0, length_1.toLength)(r.toLineNumber - r.fromLineNumber + 1, 0))); this.astWithTokens = this.parseDocumentFromTextBuffer(edits, this.astWithTokens, false); if (!this.initialAstWithoutTokens) { this.didChangeEmitter.fire(); } })); if (textModel.backgroundTokenizationState === 0 /* Uninitialized */) { // There are no token information yet const brackets = this.brackets.getSingleLanguageBracketTokens(this.textModel.getLanguageId()); const tokenizer = new tokenizer_1.FastTokenizer(this.textModel.getValue(), brackets); this.initialAstWithoutTokens = (0, parser_1.parseDocument)(tokenizer, [], undefined, true); this.astWithTokens = this.initialAstWithoutTokens; } else if (textModel.backgroundTokenizationState === 2 /* Completed */) { // Skip the initial ast, as there is no flickering. // Directly create the tree with token information. this.initialAstWithoutTokens = undefined; this.astWithTokens = this.parseDocumentFromTextBuffer([], undefined, false); } else if (textModel.backgroundTokenizationState === 1 /* InProgress */) { this.initialAstWithoutTokens = this.parseDocumentFromTextBuffer([], undefined, true); this.astWithTokens = this.initialAstWithoutTokens; } } didLanguageChange(languageId) { return this.brackets.didLanguageChange(languageId); } handleContentChanged(change) { const edits = change.changes.map(c => { const range = range_1.Range.lift(c.range); return new beforeEditPositionMapper_1.TextEditInfo((0, length_1.positionToLength)(range.getStartPosition()), (0, length_1.positionToLength)(range.getEndPosition()), (0, length_1.lengthOfString)(c.text)); }).reverse(); this.astWithTokens = this.parseDocumentFromTextBuffer(edits, this.astWithTokens, false); if (this.initialAstWithoutTokens) { this.initialAstWithoutTokens = this.parseDocumentFromTextBuffer(edits, this.initialAstWithoutTokens, false); } } /** * @pure (only if isPure = true) */ parseDocumentFromTextBuffer(edits, previousAst, immutable) { // Is much faster if `isPure = false`. const isPure = false; const previousAstClone = isPure ? previousAst === null || previousAst === void 0 ? void 0 : previousAst.deepClone() : previousAst; const tokenizer = new tokenizer_1.TextBufferTokenizer(this.textModel, this.brackets); const result = (0, parser_1.parseDocument)(tokenizer, edits, previousAstClone, immutable); return result; } getBracketsInRange(range) { const startOffset = (0, length_1.toLength)(range.startLineNumber - 1, range.startColumn - 1); const endOffset = (0, length_1.toLength)(range.endLineNumber - 1, range.endColumn - 1); const result = new Array(); const node = this.initialAstWithoutTokens || this.astWithTokens; collectBrackets(node, length_1.lengthZero, node.length, startOffset, endOffset, result); return result; } getBracketPairsInRange(range, includeMinIndentation) { const result = new Array(); const startLength = (0, length_1.positionToLength)(range.getStartPosition()); const endLength = (0, length_1.positionToLength)(range.getEndPosition()); const node = this.initialAstWithoutTokens || this.astWithTokens; const context = new CollectBracketPairsContext(result, includeMinIndentation, this.textModel); collectBracketPairs(node, length_1.lengthZero, node.length, startLength, endLength, context); return result; } } exports.BracketPairsTree = BracketPairsTree; function collectBrackets(node, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, result, level = 0) { if (node.kind === 1 /* Bracket */) { const range = (0, length_1.lengthsToRange)(nodeOffsetStart, nodeOffsetEnd); result.push(new textModelBracketPairs_1.BracketInfo(range, level - 1, false)); } else if (node.kind === 3 /* UnexpectedClosingBracket */) { const range = (0, length_1.lengthsToRange)(nodeOffsetStart, nodeOffsetEnd); result.push(new textModelBracketPairs_1.BracketInfo(range, level - 1, true)); } else if (node.kind === 4 /* List */) { for (const child of node.children) { nodeOffsetEnd = (0, length_1.lengthAdd)(nodeOffsetStart, child.length); if ((0, length_1.lengthLessThanEqual)(nodeOffsetStart, endOffset) && (0, length_1.lengthGreaterThanEqual)(nodeOffsetEnd, startOffset)) { collectBrackets(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, result, level); } nodeOffsetStart = nodeOffsetEnd; } } else if (node.kind === 2 /* Pair */) { // Don't use node.children here to improve performance level++; { const child = node.openingBracket; nodeOffsetEnd = (0, length_1.lengthAdd)(nodeOffsetStart, child.length); if ((0, length_1.lengthLessThanEqual)(nodeOffsetStart, endOffset) && (0, length_1.lengthGreaterThanEqual)(nodeOffsetEnd, startOffset)) { collectBrackets(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, result, level); } nodeOffsetStart = nodeOffsetEnd; } if (node.child) { const child = node.child; nodeOffsetEnd = (0, length_1.lengthAdd)(nodeOffsetStart, child.length); if ((0, length_1.lengthLessThanEqual)(nodeOffsetStart, endOffset) && (0, length_1.lengthGreaterThanEqual)(nodeOffsetEnd, startOffset)) { collectBrackets(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, result, level); } nodeOffsetStart = nodeOffsetEnd; } if (node.closingBracket) { const child = node.closingBracket; nodeOffsetEnd = (0, length_1.lengthAdd)(nodeOffsetStart, child.length); if ((0, length_1.lengthLessThanEqual)(nodeOffsetStart, endOffset) && (0, length_1.lengthGreaterThanEqual)(nodeOffsetEnd, startOffset)) { collectBrackets(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, result, level); } nodeOffsetStart = nodeOffsetEnd; } } } class CollectBracketPairsContext { constructor(result, includeMinIndentation, textModel) { this.result = result; this.includeMinIndentation = includeMinIndentation; this.textModel = textModel; } } function collectBracketPairs(node, nodeOffset, nodeOffsetEnd, startOffset, endOffset, context, level = 0) { var _a; if (node.kind === 2 /* Pair */) { const openingBracketEnd = (0, length_1.lengthAdd)(nodeOffset, node.openingBracket.length); let minIndentation = -1; if (context.includeMinIndentation) { minIndentation = node.computeMinIndentation(nodeOffset, context.textModel); } context.result.push(new textModelBracketPairs_1.BracketPairWithMinIndentationInfo((0, length_1.lengthsToRange)(nodeOffset, nodeOffsetEnd), (0, length_1.lengthsToRange)(nodeOffset, openingBracketEnd), node.closingBracket ? (0, length_1.lengthsToRange)((0, length_1.lengthAdd)(openingBracketEnd, ((_a = node.child) === null || _a === void 0 ? void 0 : _a.length) || length_1.lengthZero), nodeOffsetEnd) : undefined, level, minIndentation)); level++; } let curOffset = nodeOffset; for (const child of node.children) { const childOffset = curOffset; curOffset = (0, length_1.lengthAdd)(curOffset, child.length); if ((0, length_1.lengthLessThanEqual)(childOffset, endOffset) && (0, length_1.lengthLessThanEqual)(startOffset, curOffset)) { collectBracketPairs(child, childOffset, curOffset, startOffset, endOffset, context, level); } } } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[427/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsImpl*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,426/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/bracketPairsTree*/,120/*vs/editor/common/languages/supports*/,177/*vs/editor/common/languages/supports/richEditBrackets*/]), function (require, exports, event_1, lifecycle_1, bracketPairsTree_1, supports_1, richEditBrackets_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BracketPairsTextModelPart = void 0; class BracketPairsTextModelPart extends lifecycle_1.Disposable { constructor(textModel, languageConfigurationService) { super(); this.textModel = textModel; this.languageConfigurationService = languageConfigurationService; this.bracketPairsTree = this._register(new lifecycle_1.MutableDisposable()); this.onDidChangeEmitter = new event_1.Emitter(); this.onDidChange = this.onDidChangeEmitter.event; this.bracketsRequested = false; this._register(textModel.onDidChangeOptions(e => { this.bracketPairsTree.clear(); this.updateBracketPairsTree(); })); this._register(textModel.onDidChangeLanguage(e => { this.bracketPairsTree.clear(); this.updateBracketPairsTree(); })); this._register(this.languageConfigurationService.onDidChange(e => { var _a; if (!e.languageId || ((_a = this.bracketPairsTree.value) === null || _a === void 0 ? void 0 : _a.object.didLanguageChange(e.languageId))) { this.bracketPairsTree.clear(); this.updateBracketPairsTree(); } })); } get isDocumentSupported() { const maxSupportedDocumentLength = /* max lines */ 50000 * /* average column count */ 100; return this.textModel.getValueLength() <= maxSupportedDocumentLength; } updateBracketPairsTree() { if (this.bracketsRequested && this.isDocumentSupported) { if (!this.bracketPairsTree.value) { const store = new lifecycle_1.DisposableStore(); this.bracketPairsTree.value = createDisposableRef(store.add(new bracketPairsTree_1.BracketPairsTree(this.textModel, (languageId) => { return this.languageConfigurationService.getLanguageConfiguration(languageId); })), store); store.add(this.bracketPairsTree.value.object.onDidChange(e => this.onDidChangeEmitter.fire(e))); this.onDidChangeEmitter.fire(); } } else { if (this.bracketPairsTree.value) { this.bracketPairsTree.clear(); // Important: Don't call fire if there was no change! this.onDidChangeEmitter.fire(); } } } handleContentChanged(change) { var _a; (_a = this.bracketPairsTree.value) === null || _a === void 0 ? void 0 : _a.object.handleContentChanged(change); } /** * Returns all bracket pairs that intersect the given range. * The result is sorted by the start position. */ getBracketPairsInRange(range) { var _a; this.bracketsRequested = true; this.updateBracketPairsTree(); return ((_a = this.bracketPairsTree.value) === null || _a === void 0 ? void 0 : _a.object.getBracketPairsInRange(range, false)) || []; } getBracketPairsInRangeWithMinIndentation(range) { var _a; this.bracketsRequested = true; this.updateBracketPairsTree(); return ((_a = this.bracketPairsTree.value) === null || _a === void 0 ? void 0 : _a.object.getBracketPairsInRange(range, true)) || []; } getBracketsInRange(range) { var _a; this.bracketsRequested = true; this.updateBracketPairsTree(); return ((_a = this.bracketPairsTree.value) === null || _a === void 0 ? void 0 : _a.object.getBracketsInRange(range)) || []; } findMatchingBracketUp(_bracket, _position) { const bracket = _bracket.toLowerCase(); const position = this.textModel.validatePosition(_position); const languageId = this.textModel.getLanguageIdAtPosition(position.lineNumber, position.column); const bracketsSupport = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets; if (!bracketsSupport) { return null; } const data = bracketsSupport.textIsBracket[bracket]; if (!data) { return null; } return stripBracketSearchCanceled(this._findMatchingBracketUp(data, position, null)); } matchBracket(position) { return this._matchBracket(this.textModel.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.textModel.getLineTokens(lineNumber); const lineText = this.textModel.getLineContent(lineNumber); const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); if (tokenIndex < 0) { return null; } const currentModeBrackets = this.languageConfigurationService.getLanguageConfiguration(lineTokens.getLanguageId(tokenIndex)).brackets; // check that the token is not to be ignored if (currentModeBrackets && !(0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(tokenIndex))) { let { searchStartOffset, searchEndOffset } = this._establishBracketSearchOffsets(position, lineTokens, currentModeBrackets, tokenIndex); // it might be the case that [currentTokenStart -> currentTokenEnd] contains multiple brackets // `bestResult` will contain the most right-side result let bestResult = null; while (true) { const foundBracket = richEditBrackets_1.BracketsUtils.findNextBracketInRange(currentModeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); if (!foundBracket) { // there are no more brackets in this text break; } // check that we didn't hit a bracket too far away from position if (foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) { const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase(); const r = this._matchFoundBracket(foundBracket, currentModeBrackets.textIsBracket[foundBracketText], currentModeBrackets.textIsOpenBracket[foundBracketText], 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 = this.languageConfigurationService.getLanguageConfiguration(lineTokens.getLanguageId(prevTokenIndex)).brackets; // check that previous token is not to be ignored if (prevModeBrackets && !(0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(prevTokenIndex))) { const { searchStartOffset, searchEndOffset } = this._establishBracketSearchOffsets(position, lineTokens, prevModeBrackets, prevTokenIndex); const foundBracket = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(prevModeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); // check that we didn't hit a bracket too far away from position if (foundBracket && foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) { const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase(); const r = this._matchFoundBracket(foundBracket, prevModeBrackets.textIsBracket[foundBracketText], prevModeBrackets.textIsOpenBracket[foundBracketText], 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.languageId; const reversedBracketRegex = bracket.reversedRegex; let count = -1; let totalCallCount = 0; const searchPrevMatchingBracketInRange = (lineNumber, lineText, searchStartOffset, searchEndOffset) => { while (true) { if (continueSearchPredicate && (++totalCallCount) % 100 === 0 && !continueSearchPredicate()) { return BracketSearchCanceled.INSTANCE; } const r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); if (!r) { break; } const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase(); if (bracket.isOpen(hitText)) { count++; } else if (bracket.isClose(hitText)) { count--; } if (count === 0) { return r; } searchEndOffset = r.startColumn - 1; } return null; }; for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) { const lineTokens = this.textModel.getLineTokens(lineNumber); const tokenCount = lineTokens.getCount(); const lineText = this.textModel.getLineContent(lineNumber); let tokenIndex = tokenCount - 1; let searchStartOffset = lineText.length; let searchEndOffset = lineText.length; if (lineNumber === position.lineNumber) { tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); searchStartOffset = position.column - 1; searchEndOffset = position.column - 1; } let prevSearchInToken = true; for (; tokenIndex >= 0; tokenIndex--) { const searchInToken = (lineTokens.getLanguageId(tokenIndex) === languageId && !(0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(tokenIndex))); if (searchInToken) { // this token should be searched if (prevSearchInToken) { // the previous token should be searched, simply extend searchStartOffset searchStartOffset = lineTokens.getStartOffset(tokenIndex); } else { // the previous token should not be searched searchStartOffset = lineTokens.getStartOffset(tokenIndex); searchEndOffset = lineTokens.getEndOffset(tokenIndex); } } else { // this token should not be searched if (prevSearchInToken && searchStartOffset !== searchEndOffset) { const r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return r; } } } prevSearchInToken = searchInToken; } if (prevSearchInToken && searchStartOffset !== searchEndOffset) { const r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return r; } } } return null; } _findMatchingBracketDown(bracket, position, continueSearchPredicate) { // console.log('_findMatchingBracketDown: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position)); const languageId = bracket.languageId; const bracketRegex = bracket.forwardRegex; let count = 1; let totalCallCount = 0; const searchNextMatchingBracketInRange = (lineNumber, lineText, searchStartOffset, searchEndOffset) => { while (true) { if (continueSearchPredicate && (++totalCallCount) % 100 === 0 && !continueSearchPredicate()) { return BracketSearchCanceled.INSTANCE; } const r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(bracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); if (!r) { break; } const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase(); if (bracket.isOpen(hitText)) { count++; } else if (bracket.isClose(hitText)) { count--; } if (count === 0) { return r; } searchStartOffset = r.endColumn - 1; } return null; }; const lineCount = this.textModel.getLineCount(); for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) { const lineTokens = this.textModel.getLineTokens(lineNumber); const tokenCount = lineTokens.getCount(); const lineText = this.textModel.getLineContent(lineNumber); let tokenIndex = 0; let searchStartOffset = 0; let searchEndOffset = 0; if (lineNumber === position.lineNumber) { tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); searchStartOffset = position.column - 1; searchEndOffset = position.column - 1; } let prevSearchInToken = true; for (; tokenIndex < tokenCount; tokenIndex++) { const searchInToken = (lineTokens.getLanguageId(tokenIndex) === languageId && !(0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(tokenIndex))); if (searchInToken) { // this token should be searched if (prevSearchInToken) { // the previous token should be searched, simply extend searchEndOffset searchEndOffset = lineTokens.getEndOffset(tokenIndex); } else { // the previous token should not be searched searchStartOffset = lineTokens.getStartOffset(tokenIndex); searchEndOffset = lineTokens.getEndOffset(tokenIndex); } } else { // this token should not be searched if (prevSearchInToken && searchStartOffset !== searchEndOffset) { const r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return r; } } } prevSearchInToken = searchInToken; } if (prevSearchInToken && searchStartOffset !== searchEndOffset) { const r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return r; } } } return null; } findPrevBracket(_position) { const position = this.textModel.validatePosition(_position); let languageId = null; let modeBrackets = null; for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) { const lineTokens = this.textModel.getLineTokens(lineNumber); const tokenCount = lineTokens.getCount(); const lineText = this.textModel.getLineContent(lineNumber); let tokenIndex = tokenCount - 1; let searchStartOffset = lineText.length; let searchEndOffset = lineText.length; if (lineNumber === position.lineNumber) { tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); searchStartOffset = position.column - 1; searchEndOffset = position.column - 1; const tokenLanguageId = lineTokens.getLanguageId(tokenIndex); if (languageId !== tokenLanguageId) { languageId = tokenLanguageId; modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets; } } 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 = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets; } 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.textModel.validatePosition(_position); const lineCount = this.textModel.getLineCount(); let languageId = null; let modeBrackets = null; for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) { const lineTokens = this.textModel.getLineTokens(lineNumber); const tokenCount = lineTokens.getCount(); const lineText = this.textModel.getLineContent(lineNumber); let tokenIndex = 0; let searchStartOffset = 0; let searchEndOffset = 0; if (lineNumber === position.lineNumber) { tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); searchStartOffset = position.column - 1; searchEndOffset = position.column - 1; const tokenLanguageId = lineTokens.getLanguageId(tokenIndex); if (languageId !== tokenLanguageId) { languageId = tokenLanguageId; modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets; } } 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 = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets; } 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.textModel.validatePosition(_position); const lineCount = this.textModel.getLineCount(); const savedCounts = new Map(); let counts = []; const resetCounts = (languageId, modeBrackets) => { if (!savedCounts.has(languageId)) { const tmp = []; for (let i = 0, len = modeBrackets ? modeBrackets.brackets.length : 0; i < len; i++) { tmp[i] = 0; } savedCounts.set(languageId, tmp); } counts = savedCounts.get(languageId); }; let totalCallCount = 0; const searchInRange = (modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset) => { while (true) { if (continueSearchPredicate && (++totalCallCount) % 100 === 0 && !continueSearchPredicate()) { return BracketSearchCanceled.INSTANCE; } const r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); if (!r) { break; } const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase(); const bracket = modeBrackets.textIsBracket[hitText]; if (bracket) { if (bracket.isOpen(hitText)) { counts[bracket.index]++; } else if (bracket.isClose(hitText)) { counts[bracket.index]--; } if (counts[bracket.index] === -1) { return this._matchFoundBracket(r, bracket, false, continueSearchPredicate); } } searchStartOffset = r.endColumn - 1; } return null; }; let languageId = null; let modeBrackets = null; for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) { const lineTokens = this.textModel.getLineTokens(lineNumber); const tokenCount = lineTokens.getCount(); const lineText = this.textModel.getLineContent(lineNumber); let tokenIndex = 0; let searchStartOffset = 0; let searchEndOffset = 0; if (lineNumber === position.lineNumber) { tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); searchStartOffset = position.column - 1; searchEndOffset = position.column - 1; const tokenLanguageId = lineTokens.getLanguageId(tokenIndex); if (languageId !== tokenLanguageId) { languageId = tokenLanguageId; modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets; resetCounts(languageId, modeBrackets); } } let prevSearchInToken = true; for (; tokenIndex < tokenCount; tokenIndex++) { const tokenLanguageId = lineTokens.getLanguageId(tokenIndex); if (languageId !== tokenLanguageId) { // language id change! if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) { const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return stripBracketSearchCanceled(r); } prevSearchInToken = false; } languageId = tokenLanguageId; modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets; resetCounts(languageId, modeBrackets); } const searchInToken = (!!modeBrackets && !(0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(tokenIndex))); if (searchInToken) { // this token should be searched if (prevSearchInToken) { // the previous token should be searched, simply extend searchEndOffset searchEndOffset = lineTokens.getEndOffset(tokenIndex); } else { // the previous token should not be searched searchStartOffset = lineTokens.getStartOffset(tokenIndex); searchEndOffset = lineTokens.getEndOffset(tokenIndex); } } else { // this token should not be searched if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) { const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return stripBracketSearchCanceled(r); } } } prevSearchInToken = searchInToken; } if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) { const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return stripBracketSearchCanceled(r); } } } return null; } _toFoundBracket(modeBrackets, r) { if (!r) { return null; } let text = this.textModel.getValueInRange(r); text = text.toLowerCase(); const data = modeBrackets.textIsBracket[text]; if (!data) { return null; } return { range: r, open: data.open, close: data.close, isOpen: modeBrackets.textIsOpenBracket[text] }; } } exports.BracketPairsTextModelPart = BracketPairsTextModelPart; function createDisposableRef(object, disposable) { return { object, dispose: () => disposable === null || disposable === void 0 ? void 0 : disposable.dispose(), }; } class BracketSearchCanceled { constructor() { this._searchCanceledBrand = undefined; } } BracketSearchCanceled.INSTANCE = new BracketSearchCanceled(); function stripBracketSearchCanceled(result) { if (result instanceof BracketSearchCanceled) { return null; } return result; } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[428/*vs/editor/common/model/bracketPairsTextModelPart/fixBrackets*/], __M([1/*require*/,0/*exports*/,247/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/brackets*/,83/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/,241/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/parser*/,99/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet*/,181/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/tokenizer*/]), function (require, exports, brackets_1, length_1, parser_1, smallImmutableSet_1, tokenizer_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fixBracketsInLine = void 0; function fixBracketsInLine(tokens, languageConfigurationService) { const denseKeyProvider = new smallImmutableSet_1.DenseKeyProvider(); const bracketTokens = new brackets_1.LanguageAgnosticBracketTokens(denseKeyProvider, (languageId) => languageConfigurationService.getLanguageConfiguration(languageId)); const tokenizer = new tokenizer_1.TextBufferTokenizer(new StaticTokenizerSource([tokens]), bracketTokens); const node = (0, parser_1.parseDocument)(tokenizer, [], undefined, true); let str = ''; const line = tokens.getLineContent(); function processNode(node, offset) { if (node.kind === 2 /* Pair */) { processNode(node.openingBracket, offset); offset = (0, length_1.lengthAdd)(offset, node.openingBracket.length); if (node.child) { processNode(node.child, offset); offset = (0, length_1.lengthAdd)(offset, node.child.length); } if (node.closingBracket) { processNode(node.closingBracket, offset); offset = (0, length_1.lengthAdd)(offset, node.closingBracket.length); } else { const singleLangBracketTokens = bracketTokens.getSingleLanguageBracketTokens(node.openingBracket.languageId); const closingTokenText = singleLangBracketTokens.findClosingTokenText(node.openingBracket.bracketIds); str += closingTokenText; } } else if (node.kind === 3 /* UnexpectedClosingBracket */) { // remove the bracket } else if (node.kind === 0 /* Text */ || node.kind === 1 /* Bracket */) { str += line.substring((0, length_1.lengthGetColumnCountIfZeroLineCount)(offset), (0, length_1.lengthGetColumnCountIfZeroLineCount)((0, length_1.lengthAdd)(offset, node.length))); } else if (node.kind === 4 /* List */) { for (const child of node.children) { processNode(child, offset); offset = (0, length_1.lengthAdd)(offset, child.length); } } } processNode(node, length_1.lengthZero); return str; } exports.fixBracketsInLine = fixBracketsInLine; class StaticTokenizerSource { constructor(lines) { this.lines = lines; } getLineCount() { return this.lines.length; } getLineLength(lineNumber) { return this.lines[lineNumber - 1].getLineContent().length; } getLineTokens(lineNumber) { return this.lines[lineNumber - 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[248/*vs/editor/common/services/editorBaseApi*/], __M([1/*require*/,0/*exports*/,21/*vs/base/common/cancellation*/,4/*vs/base/common/event*/,55/*vs/base/common/keyCodes*/,25/*vs/base/common/uri*/,11/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,18/*vs/editor/common/languages*/,179/*vs/editor/common/standalone/standaloneEnums*/]), function (require, exports, cancellation_1, event_1, keyCodes_1, uri_1, position_1, range_1, selection_1, languages_1, standaloneEnums) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.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: languages_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[429/*vs/editor/common/services/editorSimpleWorker*/], __M([1/*require*/,0/*exports*/,138/*vs/base/common/diff/diff*/,17/*vs/base/common/platform*/,25/*vs/base/common/uri*/,11/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,404/*vs/editor/common/diff/diffComputer*/,419/*vs/editor/common/model/mirrorTextModel*/,146/*vs/editor/common/core/wordHelper*/,406/*vs/editor/common/languages/linkComputer*/,409/*vs/editor/common/languages/supports/inplaceReplaceSupport*/,248/*vs/editor/common/services/editorBaseApi*/,20/*vs/base/common/types*/,65/*vs/base/common/stopwatch*/,243/*vs/editor/common/languages/unicodeTextModelHighlighter*/]), function (require, exports, diff_1, platform_1, uri_1, position_1, range_1, diffComputer_1, mirrorTextModel_1, wordHelper_1, linkComputer_1, inplaceReplaceSupport_1, editorBaseApi_1, types, stopwatch_1, unicodeTextModelHighlighter_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.create = exports.EditorSimpleWorker = exports.MirrorModel = 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) { const wordAtText = (0, wordHelper_1.getWordAtText)(position.column, (0, wordHelper_1.ensureValidWordDefinition)(wordDefinition), this._lines[position.lineNumber - 1], 0); if (wordAtText) { return new range_1.Range(position.lineNumber, wordAtText.startColumn, position.lineNumber, wordAtText.endColumn); } return null; } words(wordDefinition) { const lines = this._lines; const wordenize = this._wordenize.bind(this); let lineNumber = 0; let lineText = ''; let wordRangesIdx = 0; let wordRanges = []; return { *[Symbol.iterator]() { while (true) { if (wordRangesIdx < wordRanges.length) { const value = lineText.substring(wordRanges[wordRangesIdx].start, wordRanges[wordRangesIdx].end); wordRangesIdx += 1; yield value; } else { if (lineNumber < lines.length) { lineText = lines[lineNumber]; wordRanges = wordenize(lineText, wordDefinition); wordRangesIdx = 0; lineNumber += 1; } else { break; } } } } }; } getLineWords(lineNumber, wordDefinition) { const content = this._lines[lineNumber - 1]; const ranges = this._wordenize(content, wordDefinition); const words = []; for (const range of ranges) { words.push({ word: content.substring(range.start, range.end), startColumn: range.start + 1, endColumn: range.end + 1 }); } return words; } _wordenize(content, wordDefinition) { const result = []; let match; wordDefinition.lastIndex = 0; // reset lastIndex just to be sure while (match = wordDefinition.exec(content)) { if (match[0].length === 0) { // it did match the empty string break; } result.push({ start: match.index, end: match.index + match[0].length }); } return result; } getValueInRange(range) { range = this._validateRange(range); if (range.startLineNumber === range.endLineNumber) { return this._lines[range.startLineNumber - 1].substring(range.startColumn - 1, range.endColumn - 1); } const lineEnding = this._eol; const startLineIndex = range.startLineNumber - 1; const endLineIndex = range.endLineNumber - 1; const resultLines = []; resultLines.push(this._lines[startLineIndex].substring(range.startColumn - 1)); for (let i = startLineIndex + 1; i < endLineIndex; i++) { resultLines.push(this._lines[i]); } resultLines.push(this._lines[endLineIndex].substring(0, range.endColumn - 1)); return resultLines.join(lineEnding); } offsetAt(position) { position = this._validatePosition(position); this._ensureLineStarts(); return this._lineStarts.getPrefixSum(position.lineNumber - 2) + (position.column - 1); } positionAt(offset) { offset = Math.floor(offset); offset = Math.max(0, offset); this._ensureLineStarts(); const out = this._lineStarts.getIndexOf(offset); const lineLength = this._lines[out.index].length; // Ensure we return a valid position return { lineNumber: 1 + out.index, column: 1 + Math.min(out.remainder, lineLength) }; } _validateRange(range) { const start = this._validatePosition({ lineNumber: range.startLineNumber, column: range.startColumn }); const end = this._validatePosition({ lineNumber: range.endLineNumber, column: range.endColumn }); if (start.lineNumber !== range.startLineNumber || start.column !== range.startColumn || end.lineNumber !== range.endLineNumber || end.column !== range.endColumn) { return { startLineNumber: start.lineNumber, startColumn: start.column, endLineNumber: end.lineNumber, endColumn: end.column }; } return range; } _validatePosition(position) { if (!position_1.Position.isIPosition(position)) { throw new Error('bad position'); } let { lineNumber, column } = position; let hasChanged = false; if (lineNumber < 1) { lineNumber = 1; column = 1; hasChanged = true; } else if (lineNumber > this._lines.length) { lineNumber = this._lines.length; column = this._lines[lineNumber - 1].length + 1; hasChanged = true; } else { const maxCharacter = this._lines[lineNumber - 1].length + 1; if (column < 1) { column = 1; hasChanged = true; } else if (column > maxCharacter) { column = maxCharacter; hasChanged = true; } } if (!hasChanged) { return position; } else { return { lineNumber, column }; } } } exports.MirrorModel = MirrorModel; /** * @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() { const all = []; Object.keys(this._models).forEach((key) => all.push(this._models[key])); return all; } acceptNewModel(data) { this._models[data.url] = new MirrorModel(uri_1.URI.parse(data.url), data.lines, data.EOL, data.versionId); } acceptModelChanged(strURL, e) { if (!this._models[strURL]) { return; } const model = this._models[strURL]; model.onEvents(e); } acceptRemovedModel(strURL) { if (!this._models[strURL]) { return; } delete this._models[strURL]; } computeUnicodeHighlights(url, options, range) { return __awaiter(this, void 0, void 0, function* () { const model = this._getModel(url); if (!model) { return { ranges: [], hasMore: false, ambiguousCharacterCount: 0, invisibleCharacterCount: 0, nonBasicAsciiCharacterCount: 0 }; } return unicodeTextModelHighlighter_1.UnicodeTextModelHighlighter.computeUnicodeHighlights(model, options, range); }); } // ---- 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 const aRng = a.range ? 0 : 1; const 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* () { const 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* () { const model = this._getModel(modelUrl); if (!model) { return Object.create(null); } const wordDefRegExp = new RegExp(wordDef, wordDefFlags); const result = Object.create(null); for (let line = range.startLineNumber; line < range.endLineNumber; line++) { const words = model.getLineWords(line, wordDefRegExp); for (const word of words) { if (!isNaN(Number(word.word))) { continue; } let array = result[word.word]; if (!array) { array = []; result[word.word] = array; } array.push({ startLineNumber: line, startColumn: word.startColumn, endLineNumber: line, endColumn: word.endColumn }); } } return result; }); } //#endregion navigateValueSet(modelUrl, range, up, wordDef, wordDefFlags) { return __awaiter(this, void 0, void 0, function* () { const model = this._getModel(modelUrl); if (!model) { return null; } const wordDefRegExp = new RegExp(wordDef, wordDefFlags); if (range.startColumn === range.endColumn) { range = { startLineNumber: range.startLineNumber, startColumn: range.startColumn, endLineNumber: range.endLineNumber, endColumn: range.endColumn + 1 }; } const selectionText = model.getValueInRange(range); const wordRange = model.getWordAtPosition({ lineNumber: range.startLineNumber, column: range.startColumn }, wordDefRegExp); if (!wordRange) { return null; } const word = model.getValueInRange(wordRange); const result = inplaceReplaceSupport_1.BasicInplaceReplace.INSTANCE.navigateValueSet(range, selectionText, wordRange, word, up); return result; }); } // ---- BEGIN foreign module support -------------------------------------------------------------------------- loadForeignModule(moduleId, createData, foreignHostMethods) { const proxyMethodRequest = (method, args) => { return this._host.fhr(method, args); }; const foreignHost = types.createProxyObject(foreignHostMethods, proxyMethodRequest); const ctx = { host: foreignHost, getMirrorModels: () => { return this._getModels(); } }; if (this._foreignModuleFactory) { this._foreignModule = this._foreignModuleFactory(ctx, createData); // static foreing module return Promise.resolve(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, editorBaseApi_1.createMonacoBaseAPI)(); } }); define(__m[430/*vs/editor/common/tokens/contiguousMultilineTokens*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ContiguousMultilineTokens = void 0; /** * Represents contiguous tokens over a contiguous range of lines. */ class ContiguousMultilineTokens { constructor(startLineNumber, tokens) { this._startLineNumber = startLineNumber; this._tokens = tokens; } /** * (Inclusive) start line number for these tokens. */ get startLineNumber() { return this._startLineNumber; } /** * (Inclusive) end line number for these tokens. */ get endLineNumber() { return this._startLineNumber + this._tokens.length - 1; } /** * @see {@link _tokens} */ getLineTokens(lineNumber) { return this._tokens[lineNumber - this._startLineNumber]; } appendLineTokens(lineTokens) { this._tokens.push(lineTokens); } } exports.ContiguousMultilineTokens = ContiguousMultilineTokens; }); define(__m[431/*vs/editor/common/tokens/contiguousMultilineTokensBuilder*/], __M([1/*require*/,0/*exports*/,430/*vs/editor/common/tokens/contiguousMultilineTokens*/]), function (require, exports, contiguousMultilineTokens_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ContiguousMultilineTokensBuilder = void 0; class ContiguousMultilineTokensBuilder { constructor() { this._tokens = []; } add(lineNumber, lineTokens) { if (this._tokens.length > 0) { const last = this._tokens[this._tokens.length - 1]; if (last.endLineNumber + 1 === lineNumber) { // append last.appendLineTokens(lineTokens); return; } } this._tokens.push(new contiguousMultilineTokens_1.ContiguousMultilineTokens(lineNumber, [lineTokens])); } finalize() { return this._tokens; } } exports.ContiguousMultilineTokensBuilder = ContiguousMultilineTokensBuilder; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[75/*vs/editor/common/tokens/lineTokens*/], __M([1/*require*/,0/*exports*/,18/*vs/editor/common/languages*/]), function (require, exports, languages_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LineTokens = void 0; class LineTokens { constructor(tokens, text, decoder) { this._lineTokensBrand = undefined; this._tokens = tokens; this._tokensCount = (this._tokens.length >>> 1); this._text = text; this._languageIdCodec = decoder; } static createEmpty(lineContent, decoder) { const defaultMetadata = LineTokens.defaultTokenMetadata; const tokens = new Uint32Array(2); tokens[0] = lineContent.length; tokens[1] = defaultMetadata; return new LineTokens(tokens, lineContent, decoder); } equals(other) { if (other instanceof LineTokens) { return this.slicedEquals(other, 0, this._tokensCount); } return false; } slicedEquals(other, sliceFromTokenIndex, sliceTokenCount) { if (this._text !== other._text) { return false; } if (this._tokensCount !== other._tokensCount) { return false; } const from = (sliceFromTokenIndex << 1); const to = from + (sliceTokenCount << 1); for (let i = from; i < to; i++) { if (this._tokens[i] !== other._tokens[i]) { return false; } } return true; } getLineContent() { return this._text; } getCount() { return this._tokensCount; } getStartOffset(tokenIndex) { if (tokenIndex > 0) { return this._tokens[(tokenIndex - 1) << 1]; } return 0; } getMetadata(tokenIndex) { const metadata = this._tokens[(tokenIndex << 1) + 1]; return metadata; } getLanguageId(tokenIndex) { const metadata = this._tokens[(tokenIndex << 1) + 1]; const languageId = languages_1.TokenMetadata.getLanguageId(metadata); return this._languageIdCodec.decodeLanguageId(languageId); } getStandardTokenType(tokenIndex) { const metadata = this._tokens[(tokenIndex << 1) + 1]; return languages_1.TokenMetadata.getTokenType(metadata); } getForeground(tokenIndex) { const metadata = this._tokens[(tokenIndex << 1) + 1]; return languages_1.TokenMetadata.getForeground(metadata); } getClassName(tokenIndex) { const metadata = this._tokens[(tokenIndex << 1) + 1]; return languages_1.TokenMetadata.getClassNameFromMetadata(metadata); } getInlineStyle(tokenIndex, colorMap) { const metadata = this._tokens[(tokenIndex << 1) + 1]; return languages_1.TokenMetadata.getInlineStyleFromMetadata(metadata, colorMap); } getPresentation(tokenIndex) { const metadata = this._tokens[(tokenIndex << 1) + 1]; return languages_1.TokenMetadata.getPresentationFromMetadata(metadata); } getEndOffset(tokenIndex) { return this._tokens[tokenIndex << 1]; } /** * Find the token containing offset `offset`. * @param offset The search offset * @return The index of the token containing the offset. */ findTokenIndexAtOffset(offset) { return LineTokens.findIndexInTokensArray(this._tokens, offset); } inflate() { return this; } sliceAndInflate(startOffset, endOffset, deltaOffset) { return new SliceLineTokens(this, startOffset, endOffset, deltaOffset); } static convertToEndOffset(tokens, lineTextLength) { const tokenCount = (tokens.length >>> 1); const lastTokenIndex = tokenCount - 1; for (let tokenIndex = 0; tokenIndex < lastTokenIndex; tokenIndex++) { tokens[tokenIndex << 1] = tokens[(tokenIndex + 1) << 1]; } tokens[lastTokenIndex << 1] = lineTextLength; } static findIndexInTokensArray(tokens, desiredIndex) { if (tokens.length <= 2) { return 0; } let low = 0; let high = (tokens.length >>> 1) - 1; while (low < high) { const mid = low + Math.floor((high - low) / 2); const endOffset = tokens[(mid << 1)]; if (endOffset === desiredIndex) { return mid + 1; } else if (endOffset < desiredIndex) { low = mid + 1; } else if (endOffset > desiredIndex) { high = mid; } } return low; } /** * @pure * @param insertTokens Must be sorted by offset. */ withInserted(insertTokens) { if (insertTokens.length === 0) { return this; } let nextOriginalTokenIdx = 0; let nextInsertTokenIdx = 0; let text = ''; const newTokens = new Array(); let originalEndOffset = 0; while (true) { const nextOriginalTokenEndOffset = nextOriginalTokenIdx < this._tokensCount ? this._tokens[nextOriginalTokenIdx << 1] : -1; const nextInsertToken = nextInsertTokenIdx < insertTokens.length ? insertTokens[nextInsertTokenIdx] : null; if (nextOriginalTokenEndOffset !== -1 && (nextInsertToken === null || nextOriginalTokenEndOffset <= nextInsertToken.offset)) { // original token ends before next insert token text += this._text.substring(originalEndOffset, nextOriginalTokenEndOffset); const metadata = this._tokens[(nextOriginalTokenIdx << 1) + 1]; newTokens.push(text.length, metadata); nextOriginalTokenIdx++; originalEndOffset = nextOriginalTokenEndOffset; } else if (nextInsertToken) { if (nextInsertToken.offset > originalEndOffset) { // insert token is in the middle of the next token. text += this._text.substring(originalEndOffset, nextInsertToken.offset); const metadata = this._tokens[(nextOriginalTokenIdx << 1) + 1]; newTokens.push(text.length, metadata); originalEndOffset = nextInsertToken.offset; } text += nextInsertToken.text; newTokens.push(text.length, nextInsertToken.tokenMetadata); nextInsertTokenIdx++; } else { break; } } return new LineTokens(new Uint32Array(newTokens), text, this._languageIdCodec); } } exports.LineTokens = LineTokens; LineTokens.defaultTokenMetadata = ((0 /* None */ << 10 /* FONT_STYLE_OFFSET */) | (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */) | (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0; class SliceLineTokens { constructor(source, startOffset, endOffset, deltaOffset) { this._source = source; this._startOffset = startOffset; this._endOffset = endOffset; this._deltaOffset = deltaOffset; this._firstTokenIndex = source.findTokenIndexAtOffset(startOffset); this._tokensCount = 0; for (let i = this._firstTokenIndex, len = source.getCount(); i < len; i++) { const tokenStartOffset = source.getStartOffset(i); if (tokenStartOffset >= endOffset) { break; } this._tokensCount++; } } getMetadata(tokenIndex) { return this._source.getMetadata(this._firstTokenIndex + tokenIndex); } getLanguageId(tokenIndex) { return this._source.getLanguageId(this._firstTokenIndex + tokenIndex); } getLineContent() { return this._source.getLineContent().substring(this._startOffset, this._endOffset); } equals(other) { if (other instanceof SliceLineTokens) { return (this._startOffset === other._startOffset && this._endOffset === other._endOffset && this._deltaOffset === other._deltaOffset && this._source.slicedEquals(other._source, this._firstTokenIndex, this._tokensCount)); } return false; } getCount() { return this._tokensCount; } getForeground(tokenIndex) { return this._source.getForeground(this._firstTokenIndex + tokenIndex); } getEndOffset(tokenIndex) { const tokenEndOffset = this._source.getEndOffset(this._firstTokenIndex + tokenIndex); return Math.min(this._endOffset, tokenEndOffset) - this._startOffset + this._deltaOffset; } getClassName(tokenIndex) { return this._source.getClassName(this._firstTokenIndex + tokenIndex); } getInlineStyle(tokenIndex, colorMap) { return this._source.getInlineStyle(this._firstTokenIndex + tokenIndex, colorMap); } getPresentation(tokenIndex) { return this._source.getPresentation(this._firstTokenIndex + tokenIndex); } findTokenIndexAtOffset(offset) { return this._source.findTokenIndexAtOffset(offset + this._startOffset - this._deltaOffset) - this._firstTokenIndex; } } }); /*--------------------------------------------------------------------------------------------- * 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/common/languages/textToHtmlTokenizer*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,75/*vs/editor/common/tokens/lineTokens*/,18/*vs/editor/common/languages*/,121/*vs/editor/common/languages/nullMode*/]), function (require, exports, strings, lineTokens_1, languages_1, nullMode_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports._tokenizeToString = exports.tokenizeLineToHTML = exports.tokenizeToString = void 0; const fallback = { getInitialState: () => nullMode_1.NullState, tokenizeEncoded: (buffer, hasEOL, state) => (0, nullMode_1.nullTokenizeEncoded)(0 /* Null */, state) }; function tokenizeToString(languageService, text, languageId) { return __awaiter(this, void 0, void 0, function* () { if (!languageId) { return _tokenizeToString(text, languageService.languageIdCodec, fallback); } const tokenizationSupport = yield languages_1.TokenizationRegistry.getOrCreate(languageId); return _tokenizeToString(text, languageService.languageIdCodec, tokenizationSupport || fallback); }); } exports.tokenizeToString = tokenizeToString; function tokenizeLineToHTML(text, viewLineTokens, colorMap, startOffset, endOffset, tabSize, useNbsp) { let result = `
    `; let charIndex = startOffset; let tabsCharDelta = 0; let prevIsSpace = true; for (let tokenIndex = 0, tokenCount = viewLineTokens.getCount(); tokenIndex < tokenCount; tokenIndex++) { const tokenEndIndex = viewLineTokens.getEndOffset(tokenIndex); if (tokenEndIndex <= startOffset) { continue; } let partContent = ''; for (; charIndex < tokenEndIndex && charIndex < endOffset; charIndex++) { const charCode = text.charCodeAt(charIndex); switch (charCode) { case 9 /* Tab */: { let insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize; tabsCharDelta += insertSpacesCount - 1; while (insertSpacesCount > 0) { if (useNbsp && prevIsSpace) { partContent += ' '; prevIsSpace = false; } else { partContent += ' '; prevIsSpace = true; } insertSpacesCount--; } break; } case 60 /* LessThan */: partContent += '<'; prevIsSpace = false; break; case 62 /* GreaterThan */: partContent += '>'; prevIsSpace = false; break; case 38 /* Ampersand */: partContent += '&'; prevIsSpace = false; break; case 0 /* Null */: partContent += '�'; prevIsSpace = false; break; case 65279 /* UTF8_BOM */: case 8232 /* LINE_SEPARATOR */: case 8233 /* PARAGRAPH_SEPARATOR */: case 133 /* NEXT_LINE */: partContent += '\ufffd'; prevIsSpace = false; break; case 13 /* CarriageReturn */: // zero width space, because carriage return would introduce a line break partContent += '​'; prevIsSpace = false; break; case 32 /* Space */: if (useNbsp && prevIsSpace) { partContent += ' '; prevIsSpace = false; } else { partContent += ' '; prevIsSpace = true; } break; default: partContent += String.fromCharCode(charCode); prevIsSpace = false; } } result += `${partContent}`; if (tokenEndIndex > endOffset || charIndex >= endOffset) { break; } } result += `
    `; return result; } exports.tokenizeLineToHTML = tokenizeLineToHTML; function _tokenizeToString(text, languageIdCodec, tokenizationSupport) { let result = `
    `; const lines = strings.splitLines(text); let currentState = tokenizationSupport.getInitialState(); for (let i = 0, len = lines.length; i < len; i++) { const line = lines[i]; if (i > 0) { result += `
    `; } const tokenizationResult = tokenizationSupport.tokenizeEncoded(line, true, currentState); lineTokens_1.LineTokens.convertToEndOffset(tokenizationResult.tokens, line.length); const lineTokens = new lineTokens_1.LineTokens(tokenizationResult.tokens, line, languageIdCodec); const viewLineTokens = lineTokens.inflate(); let startOffset = 0; for (let j = 0, lenJ = viewLineTokens.getCount(); j < lenJ; j++) { const type = viewLineTokens.getClassName(j); const endIndex = viewLineTokens.getEndOffset(j); result += `${strings.escape(line.substring(startOffset, endIndex))}`; startOffset = endIndex; } currentState = tokenizationResult.endState; } result += `
    `; return result; } exports._tokenizeToString = _tokenizeToString; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[432/*vs/editor/common/model/textModelTokens*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,13/*vs/base/common/errors*/,75/*vs/editor/common/tokens/lineTokens*/,18/*vs/editor/common/languages*/,121/*vs/editor/common/languages/nullMode*/,2/*vs/base/common/lifecycle*/,65/*vs/base/common/stopwatch*/,117/*vs/editor/common/core/eolCounter*/,431/*vs/editor/common/tokens/contiguousMultilineTokensBuilder*/,10/*vs/base/common/async*/,17/*vs/base/common/platform*/]), function (require, exports, arrays, errors_1, lineTokens_1, languages_1, nullMode_1, lifecycle_1, stopwatch_1, eolCounter_1, contiguousMultilineTokensBuilder_1, async_1, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TextModelTokenization = exports.TokenizationStateStore = void 0; /** * An array that avoids being sparse by always * filling up unused indices with a default value. */ class ContiguousGrowingArray { constructor(_default) { this._default = _default; this._store = []; } get(index) { if (index < this._store.length) { return this._store[index]; } return this._default; } set(index, value) { while (index >= this._store.length) { this._store[this._store.length] = this._default; } this._store[index] = value; } delete(deleteIndex, deleteCount) { if (deleteCount === 0 || deleteIndex >= this._store.length) { return; } this._store.splice(deleteIndex, deleteCount); } insert(insertIndex, insertCount) { if (insertCount === 0 || insertIndex >= this._store.length) { return; } const arr = []; for (let i = 0; i < insertCount; i++) { arr[i] = this._default; } this._store = arrays.arrayInsert(this._store, insertIndex, arr); } } /** * Stores the states at the start of each line and keeps track of which lines * must be retokenized. Also uses state equality to quickly validate lines * that don't need to be retokenized. * * For example, when typing on a line, the line gets marked as needing to be tokenized. * Once the line is tokenized, the end state is checked for equality against the begin * state of the next line. If the states are equal, tokenization doesn't need to run * again over the rest of the file. If the states are not equal, the next line gets marked * as needing to be tokenized. */ class TokenizationStateStore { constructor(tokenizationSupport, initialState) { this.tokenizationSupport = tokenizationSupport; this.initialState = initialState; /** * `lineBeginState[i]` contains the begin state used to tokenize line number `i + 1`. */ this._lineBeginState = new ContiguousGrowingArray(null); /** * `lineNeedsTokenization[i]` describes if line number `i + 1` needs to be tokenized. */ this._lineNeedsTokenization = new ContiguousGrowingArray(true); this._firstLineNeedsTokenization = 0; this._lineBeginState.set(0, this.initialState); } get invalidLineStartIndex() { return this._firstLineNeedsTokenization; } markMustBeTokenized(lineIndex) { this._lineNeedsTokenization.set(lineIndex, true); this._firstLineNeedsTokenization = Math.min(this._firstLineNeedsTokenization, lineIndex); } getBeginState(lineIndex) { return this._lineBeginState.get(lineIndex); } setEndState(linesLength, lineIndex, endState) { this._lineNeedsTokenization.set(lineIndex, false); this._firstLineNeedsTokenization = lineIndex + 1; // Check if this was the last line if (lineIndex === linesLength - 1) { return; } // Check if the end state has changed const previousEndState = this._lineBeginState.get(lineIndex + 1); if (previousEndState === null || !endState.equals(previousEndState)) { this._lineBeginState.set(lineIndex + 1, endState); this.markMustBeTokenized(lineIndex + 1); return; } // Perhaps we can skip tokenizing some lines... let i = lineIndex + 1; while (i < linesLength) { if (this._lineNeedsTokenization.get(i)) { break; } i++; } this._firstLineNeedsTokenization = i; } //#region Editing applyEdits(range, eolCount) { this.markMustBeTokenized(range.startLineNumber - 1); this._lineBeginState.delete(range.startLineNumber, range.endLineNumber - range.startLineNumber); this._lineNeedsTokenization.delete(range.startLineNumber, range.endLineNumber - range.startLineNumber); this._lineBeginState.insert(range.startLineNumber, eolCount); this._lineNeedsTokenization.insert(range.startLineNumber, eolCount); } } exports.TokenizationStateStore = TokenizationStateStore; class TextModelTokenization extends lifecycle_1.Disposable { constructor(_textModel, _languageIdCodec) { super(); this._textModel = _textModel; this._languageIdCodec = _languageIdCodec; this._isScheduled = false; this._isDisposed = false; this._tokenizationStateStore = null; this._register(languages_1.TokenizationRegistry.onDidChange((e) => { const languageId = this._textModel.getLanguageId(); if (e.changedLanguages.indexOf(languageId) === -1) { return; } this._resetTokenizationState(); this._textModel.clearTokens(); })); this._register(this._textModel.onDidChangeContentFast((e) => { if (e.isFlush) { this._resetTokenizationState(); return; } if (this._tokenizationStateStore) { for (let i = 0, len = e.changes.length; i < len; i++) { const change = e.changes[i]; const [eolCount] = (0, eolCounter_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); if (tokenizationSupport && initialState) { this._tokenizationStateStore = new TokenizationStateStore(tokenizationSupport, initialState); } else { this._tokenizationStateStore = null; } this._beginBackgroundTokenization(); } _beginBackgroundTokenization() { if (this._isScheduled || !this._textModel.isAttachedToEditor() || !this._hasLinesToTokenize()) { return; } this._isScheduled = true; (0, async_1.runWhenIdle)((deadline) => { this._isScheduled = false; this._backgroundTokenizeWithDeadline(deadline); }); } /** * Tokenize until the deadline occurs, but try to yield every 1-2ms. */ _backgroundTokenizeWithDeadline(deadline) { // Read the time remaining from the `deadline` immediately because it is unclear // if the `deadline` object will be valid after execution leaves this function. const endTime = Date.now() + deadline.timeRemaining(); const execute = () => { if (this._isDisposed || !this._textModel.isAttachedToEditor() || !this._hasLinesToTokenize()) { // disposed in the meantime or detached or finished return; } this._backgroundTokenizeForAtLeast1ms(); if (Date.now() < endTime) { // There is still time before reaching the deadline, so yield to the browser and then // continue execution (0, platform_1.setTimeout0)(execute); } else { // The deadline has been reached, so schedule a new idle callback if necessary this._beginBackgroundTokenization(); } }; execute(); } /** * Tokenize for at least 1ms. */ _backgroundTokenizeForAtLeast1ms() { const lineCount = this._textModel.getLineCount(); const builder = new contiguousMultilineTokensBuilder_1.ContiguousMultilineTokensBuilder(); const sw = stopwatch_1.StopWatch.create(false); do { if (sw.elapsed() > 1) { // the comparison is intentionally > 1 and not >= 1 to ensure that // a full millisecond has elapsed, given how microseconds are rounded // to milliseconds break; } const tokenizedLineNumber = this._tokenizeOneInvalidLine(builder); if (tokenizedLineNumber >= lineCount) { break; } } while (this._hasLinesToTokenize()); this._textModel.setTokens(builder.finalize(), !this._hasLinesToTokenize()); } tokenizeViewport(startLineNumber, endLineNumber) { const builder = new contiguousMultilineTokensBuilder_1.ContiguousMultilineTokensBuilder(); this._tokenizeViewport(builder, startLineNumber, endLineNumber); this._textModel.setTokens(builder.finalize(), !this._hasLinesToTokenize()); } reset() { this._resetTokenizationState(); this._textModel.clearTokens(); } forceTokenization(lineNumber) { const builder = new contiguousMultilineTokensBuilder_1.ContiguousMultilineTokensBuilder(); this._updateTokensUntilLine(builder, lineNumber); this._textModel.setTokens(builder.finalize(), !this._hasLinesToTokenize()); } getTokenTypeIfInsertingCharacter(position, character) { if (!this._tokenizationStateStore) { return 0 /* Other */; } this.forceTokenization(position.lineNumber); const lineStartState = this._tokenizationStateStore.getBeginState(position.lineNumber - 1); if (!lineStartState) { return 0 /* Other */; } const languageId = this._textModel.getLanguageId(); const lineContent = this._textModel.getLineContent(position.lineNumber); // Create the text as if `character` was inserted const text = (lineContent.substring(0, position.column - 1) + character + lineContent.substring(position.column - 1)); const r = safeTokenize(this._languageIdCodec, languageId, this._tokenizationStateStore.tokenizationSupport, text, true, lineStartState); const lineTokens = new lineTokens_1.LineTokens(r.tokens, text, this._languageIdCodec); if (lineTokens.getCount() === 0) { return 0 /* Other */; } const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); return lineTokens.getStandardTokenType(tokenIndex); } tokenizeLineWithEdit(position, length, newText) { const lineNumber = position.lineNumber; const column = position.column; if (!this._tokenizationStateStore) { return null; } this.forceTokenization(lineNumber); const lineStartState = this._tokenizationStateStore.getBeginState(lineNumber - 1); if (!lineStartState) { return null; } const curLineContent = this._textModel.getLineContent(lineNumber); const newLineContent = curLineContent.substring(0, column - 1) + newText + curLineContent.substring(column - 1 + length); const languageId = this._textModel.getLanguageIdAtPosition(lineNumber, 0); const result = safeTokenize(this._languageIdCodec, languageId, this._tokenizationStateStore.tokenizationSupport, newLineContent, true, lineStartState); const lineTokens = new lineTokens_1.LineTokens(result.tokens, newLineContent, this._languageIdCodec); return lineTokens; } isCheapToTokenize(lineNumber) { if (!this._tokenizationStateStore) { 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._tokenizationStateStore) { return false; } return (this._tokenizationStateStore.invalidLineStartIndex < this._textModel.getLineCount()); } _tokenizeOneInvalidLine(builder) { if (!this._tokenizationStateStore || !this._hasLinesToTokenize()) { return this._textModel.getLineCount() + 1; } const lineNumber = this._tokenizationStateStore.invalidLineStartIndex + 1; this._updateTokensUntilLine(builder, lineNumber); return lineNumber; } _updateTokensUntilLine(builder, lineNumber) { if (!this._tokenizationStateStore) { return; } const languageId = this._textModel.getLanguageId(); 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(this._languageIdCodec, languageId, this._tokenizationStateStore.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._tokenizationStateStore) { // 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); const fakeLines = []; let initialState = null; for (let i = startLineNumber - 1; nonWhitespaceColumn > 1 && i >= 1; i--) { const 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._tokenizationStateStore.initialState; } const languageId = this._textModel.getLanguageId(); let state = initialState; for (let i = fakeLines.length - 1; i >= 0; i--) { const r = safeTokenize(this._languageIdCodec, languageId, this._tokenizationStateStore.tokenizationSupport, fakeLines[i], false, state); state = r.endState; } for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { const text = this._textModel.getLineContent(lineNumber); const r = safeTokenize(this._languageIdCodec, languageId, this._tokenizationStateStore.tokenizationSupport, text, true, state); builder.add(lineNumber, r.tokens); this._tokenizationStateStore.markMustBeTokenized(lineNumber - 1); state = r.endState; } } } exports.TextModelTokenization = TextModelTokenization; function initializeTokenization(textModel) { if (textModel.isTooLargeForTokenization()) { return [null, null]; } const tokenizationSupport = languages_1.TokenizationRegistry.get(textModel.getLanguageId()); if (!tokenizationSupport) { return [null, null]; } let initialState; try { initialState = tokenizationSupport.getInitialState(); } catch (e) { (0, errors_1.onUnexpectedError)(e); return [null, null]; } return [tokenizationSupport, initialState]; } function safeTokenize(languageIdCodec, languageId, tokenizationSupport, text, hasEOL, state) { let r = null; if (tokenizationSupport) { try { r = tokenizationSupport.tokenizeEncoded(text, hasEOL, state.clone()); } catch (e) { (0, errors_1.onUnexpectedError)(e); } } if (!r) { r = (0, nullMode_1.nullTokenizeEncoded)(languageIdCodec.encodeLanguageId(languageId), state); } 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[433/*vs/editor/common/tokens/contiguousTokensEditing*/], __M([1/*require*/,0/*exports*/,75/*vs/editor/common/tokens/lineTokens*/]), function (require, exports, lineTokens_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toUint32Array = exports.ContiguousTokensEditing = exports.EMPTY_LINE_TOKENS = void 0; exports.EMPTY_LINE_TOKENS = (new Uint32Array(0)).buffer; class ContiguousTokensEditing { static deleteBeginning(lineTokens, toChIndex) { if (lineTokens === null || lineTokens === exports.EMPTY_LINE_TOKENS) { return lineTokens; } return ContiguousTokensEditing.delete(lineTokens, 0, toChIndex); } static deleteEnding(lineTokens, fromChIndex) { if (lineTokens === null || lineTokens === exports.EMPTY_LINE_TOKENS) { return lineTokens; } const tokens = toUint32Array(lineTokens); const lineTextLength = tokens[tokens.length - 2]; return ContiguousTokensEditing.delete(lineTokens, fromChIndex, lineTextLength); } static delete(lineTokens, fromChIndex, toChIndex) { if (lineTokens === null || lineTokens === exports.EMPTY_LINE_TOKENS || fromChIndex === toChIndex) { return lineTokens; } const tokens = toUint32Array(lineTokens); const tokensCount = (tokens.length >>> 1); // special case: deleting everything if (fromChIndex === 0 && tokens[tokens.length - 2] === toChIndex) { return exports.EMPTY_LINE_TOKENS; } const fromTokenIndex = lineTokens_1.LineTokens.findIndexInTokensArray(tokens, fromChIndex); const fromTokenStartOffset = (fromTokenIndex > 0 ? tokens[(fromTokenIndex - 1) << 1] : 0); const fromTokenEndOffset = tokens[fromTokenIndex << 1]; if (toChIndex < fromTokenEndOffset) { // the delete range is inside a single token const delta = (toChIndex - fromChIndex); for (let i = fromTokenIndex; i < tokensCount; i++) { tokens[i << 1] -= delta; } return lineTokens; } let dest; let lastEnd; if (fromTokenStartOffset !== fromChIndex) { tokens[fromTokenIndex << 1] = fromChIndex; dest = ((fromTokenIndex + 1) << 1); lastEnd = fromChIndex; } else { dest = (fromTokenIndex << 1); lastEnd = fromTokenStartOffset; } const delta = (toChIndex - fromChIndex); for (let tokenIndex = fromTokenIndex + 1; tokenIndex < tokensCount; tokenIndex++) { const tokenEndOffset = tokens[tokenIndex << 1] - delta; if (tokenEndOffset > lastEnd) { tokens[dest++] = tokenEndOffset; tokens[dest++] = tokens[(tokenIndex << 1) + 1]; lastEnd = tokenEndOffset; } } if (dest === tokens.length) { // nothing to trim return lineTokens; } const tmp = new Uint32Array(dest); tmp.set(tokens.subarray(0, dest), 0); return tmp.buffer; } static append(lineTokens, _otherTokens) { if (_otherTokens === exports.EMPTY_LINE_TOKENS) { return lineTokens; } if (lineTokens === exports.EMPTY_LINE_TOKENS) { return _otherTokens; } if (lineTokens === null) { return lineTokens; } if (_otherTokens === null) { // cannot determine combined line length... return null; } const myTokens = toUint32Array(lineTokens); const otherTokens = toUint32Array(_otherTokens); const otherTokensCount = (otherTokens.length >>> 1); const result = new Uint32Array(myTokens.length + otherTokens.length); result.set(myTokens, 0); let dest = myTokens.length; const delta = myTokens[myTokens.length - 2]; for (let i = 0; i < otherTokensCount; i++) { result[dest++] = otherTokens[(i << 1)] + delta; result[dest++] = otherTokens[(i << 1) + 1]; } return result.buffer; } static insert(lineTokens, chIndex, textLength) { if (lineTokens === null || lineTokens === exports.EMPTY_LINE_TOKENS) { // nothing to do return lineTokens; } const tokens = toUint32Array(lineTokens); const tokensCount = (tokens.length >>> 1); let fromTokenIndex = lineTokens_1.LineTokens.findIndexInTokensArray(tokens, chIndex); if (fromTokenIndex > 0) { const fromTokenStartOffset = tokens[(fromTokenIndex - 1) << 1]; if (fromTokenStartOffset === chIndex) { fromTokenIndex--; } } for (let tokenIndex = fromTokenIndex; tokenIndex < tokensCount; tokenIndex++) { tokens[tokenIndex << 1] += textLength; } return lineTokens; } } exports.ContiguousTokensEditing = ContiguousTokensEditing; function toUint32Array(arr) { if (arr instanceof Uint32Array) { return arr; } else { return new Uint32Array(arr); } } exports.toUint32Array = toUint32Array; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[434/*vs/editor/common/tokens/contiguousTokensStore*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,11/*vs/editor/common/core/position*/,433/*vs/editor/common/tokens/contiguousTokensEditing*/,75/*vs/editor/common/tokens/lineTokens*/,18/*vs/editor/common/languages*/]), function (require, exports, arrays, position_1, contiguousTokensEditing_1, lineTokens_1, languages_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ContiguousTokensStore = void 0; /** * Represents contiguous tokens in a text model. */ class ContiguousTokensStore { constructor(languageIdCodec) { this._lineTokens = []; this._len = 0; this._languageIdCodec = languageIdCodec; } flush() { this._lineTokens = []; this._len = 0; } getTokens(topLevelLanguageId, lineIndex, lineText) { let rawLineTokens = null; if (lineIndex < this._len) { rawLineTokens = this._lineTokens[lineIndex]; } if (rawLineTokens !== null && rawLineTokens !== contiguousTokensEditing_1.EMPTY_LINE_TOKENS) { return new lineTokens_1.LineTokens((0, contiguousTokensEditing_1.toUint32Array)(rawLineTokens), lineText, this._languageIdCodec); } const lineTokens = new Uint32Array(2); lineTokens[0] = lineText.length; lineTokens[1] = getDefaultMetadata(this._languageIdCodec.encodeLanguageId(topLevelLanguageId)); return new lineTokens_1.LineTokens(lineTokens, lineText, this._languageIdCodec); } static _massageTokens(topLevelLanguageId, lineTextLength, _tokens) { const tokens = _tokens ? (0, contiguousTokensEditing_1.toUint32Array)(_tokens) : null; if (lineTextLength === 0) { let hasDifferentLanguageId = false; if (tokens && tokens.length > 1) { hasDifferentLanguageId = (languages_1.TokenMetadata.getLanguageId(tokens[1]) !== topLevelLanguageId); } if (!hasDifferentLanguageId) { return contiguousTokensEditing_1.EMPTY_LINE_TOKENS; } } if (!tokens || tokens.length === 0) { const tokens = new Uint32Array(2); tokens[0] = lineTextLength; tokens[1] = getDefaultMetadata(topLevelLanguageId); return tokens.buffer; } // Ensure the last token covers the end of the text tokens[tokens.length - 2] = lineTextLength; if (tokens.byteOffset === 0 && tokens.byteLength === tokens.buffer.byteLength) { // Store directly the ArrayBuffer pointer to save an object return tokens.buffer; } return tokens; } _ensureLine(lineIndex) { while (lineIndex >= this._len) { this._lineTokens[this._len] = null; this._len++; } } _deleteLines(start, deleteCount) { if (deleteCount === 0) { return; } if (start + deleteCount > this._len) { deleteCount = this._len - start; } this._lineTokens.splice(start, deleteCount); this._len -= deleteCount; } _insertLines(insertIndex, insertCount) { if (insertCount === 0) { return; } const lineTokens = []; for (let i = 0; i < insertCount; i++) { lineTokens[i] = null; } this._lineTokens = arrays.arrayInsert(this._lineTokens, insertIndex, lineTokens); this._len += insertCount; } setTokens(topLevelLanguageId, lineIndex, lineTextLength, _tokens, checkEquality) { const tokens = ContiguousTokensStore._massageTokens(this._languageIdCodec.encodeLanguageId(topLevelLanguageId), lineTextLength, _tokens); this._ensureLine(lineIndex); const oldTokens = this._lineTokens[lineIndex]; this._lineTokens[lineIndex] = tokens; if (checkEquality) { return !ContiguousTokensStore._equals(oldTokens, tokens); } return false; } static _equals(_a, _b) { if (!_a || !_b) { return !_a && !_b; } const a = (0, contiguousTokensEditing_1.toUint32Array)(_a); const b = (0, contiguousTokensEditing_1.toUint32Array)(_b); if (a.length !== b.length) { return false; } for (let i = 0, len = a.length; i < len; i++) { if (a[i] !== b[i]) { return false; } } return true; } //#region Editing acceptEdit(range, eolCount, firstLineLength) { this._acceptDeleteRange(range); this._acceptInsertText(new position_1.Position(range.startLineNumber, range.startColumn), eolCount, firstLineLength); } _acceptDeleteRange(range) { const firstLineIndex = range.startLineNumber - 1; if (firstLineIndex >= this._len) { return; } if (range.startLineNumber === range.endLineNumber) { if (range.startColumn === range.endColumn) { // Nothing to delete return; } this._lineTokens[firstLineIndex] = contiguousTokensEditing_1.ContiguousTokensEditing.delete(this._lineTokens[firstLineIndex], range.startColumn - 1, range.endColumn - 1); return; } this._lineTokens[firstLineIndex] = contiguousTokensEditing_1.ContiguousTokensEditing.deleteEnding(this._lineTokens[firstLineIndex], range.startColumn - 1); const lastLineIndex = range.endLineNumber - 1; let lastLineTokens = null; if (lastLineIndex < this._len) { lastLineTokens = contiguousTokensEditing_1.ContiguousTokensEditing.deleteBeginning(this._lineTokens[lastLineIndex], range.endColumn - 1); } // Take remaining text on last line and append it to remaining text on first line this._lineTokens[firstLineIndex] = contiguousTokensEditing_1.ContiguousTokensEditing.append(this._lineTokens[firstLineIndex], lastLineTokens); // Delete middle lines this._deleteLines(range.startLineNumber, range.endLineNumber - range.startLineNumber); } _acceptInsertText(position, eolCount, firstLineLength) { if (eolCount === 0 && firstLineLength === 0) { // Nothing to insert return; } const lineIndex = position.lineNumber - 1; if (lineIndex >= this._len) { return; } if (eolCount === 0) { // Inserting text on one line this._lineTokens[lineIndex] = contiguousTokensEditing_1.ContiguousTokensEditing.insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength); return; } this._lineTokens[lineIndex] = contiguousTokensEditing_1.ContiguousTokensEditing.deleteEnding(this._lineTokens[lineIndex], position.column - 1); this._lineTokens[lineIndex] = contiguousTokensEditing_1.ContiguousTokensEditing.insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength); this._insertLines(position.lineNumber, eolCount); } } exports.ContiguousTokensStore = ContiguousTokensStore; function getDefaultMetadata(topLevelLanguageId) { return ((topLevelLanguageId << 0 /* LANGUAGEID_OFFSET */) | (0 /* Other */ << 8 /* TOKEN_TYPE_OFFSET */) | (0 /* None */ << 10 /* FONT_STYLE_OFFSET */) | (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */) | (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 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[435/*vs/editor/common/tokens/sparseMultilineTokens*/], __M([1/*require*/,0/*exports*/,11/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,117/*vs/editor/common/core/eolCounter*/]), function (require, exports, position_1, range_1, eolCounter_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SparseLineTokens = exports.SparseMultilineTokens = void 0; /** * Represents sparse tokens over a contiguous range of lines. */ class SparseMultilineTokens { constructor(startLineNumber, tokens) { this._startLineNumber = startLineNumber; this._tokens = tokens; this._endLineNumber = this._startLineNumber + this._tokens.getMaxDeltaLine(); } static create(startLineNumber, tokens) { return new SparseMultilineTokens(startLineNumber, new SparseMultilineTokensStorage(tokens)); } /** * (Inclusive) start line number for these tokens. */ get startLineNumber() { return this._startLineNumber; } /** * (Inclusive) end line number for these tokens. */ get endLineNumber() { return this._endLineNumber; } toString() { return this._tokens.toString(this._startLineNumber); } _updateEndLineNumber() { this._endLineNumber = this._startLineNumber + this._tokens.getMaxDeltaLine(); } isEmpty() { return this._tokens.isEmpty(); } getLineTokens(lineNumber) { if (this._startLineNumber <= lineNumber && lineNumber <= this._endLineNumber) { return this._tokens.getLineTokens(lineNumber - this._startLineNumber); } return null; } getRange() { const deltaRange = this._tokens.getRange(); if (!deltaRange) { return deltaRange; } return new range_1.Range(this._startLineNumber + deltaRange.startLineNumber, deltaRange.startColumn, this._startLineNumber + deltaRange.endLineNumber, deltaRange.endColumn); } removeTokens(range) { const startLineIndex = range.startLineNumber - this._startLineNumber; const endLineIndex = range.endLineNumber - this._startLineNumber; this._startLineNumber += this._tokens.removeTokens(startLineIndex, range.startColumn - 1, endLineIndex, range.endColumn - 1); this._updateEndLineNumber(); } split(range) { // split tokens to two: // a) all the tokens before `range` // b) all the tokens after `range` const startLineIndex = range.startLineNumber - this._startLineNumber; const endLineIndex = range.endLineNumber - this._startLineNumber; const [a, b, bDeltaLine] = this._tokens.split(startLineIndex, range.startColumn - 1, endLineIndex, range.endColumn - 1); return [new SparseMultilineTokens(this._startLineNumber, a), new SparseMultilineTokens(this._startLineNumber + bDeltaLine, b)]; } applyEdit(range, text) { const [eolCount, firstLineLength, lastLineLength] = (0, eolCounter_1.countEOL)(text); this.acceptEdit(range, eolCount, firstLineLength, lastLineLength, text.length > 0 ? text.charCodeAt(0) : 0 /* Null */); } acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode) { this._acceptDeleteRange(range); this._acceptInsertText(new position_1.Position(range.startLineNumber, range.startColumn), eolCount, firstLineLength, lastLineLength, firstCharCode); this._updateEndLineNumber(); } _acceptDeleteRange(range) { if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) { // Nothing to delete return; } const firstLineIndex = range.startLineNumber - this._startLineNumber; const lastLineIndex = range.endLineNumber - this._startLineNumber; if (lastLineIndex < 0) { // this deletion occurs entirely before this block, so we only need to adjust line numbers const deletedLinesCount = lastLineIndex - firstLineIndex; this._startLineNumber -= deletedLinesCount; return; } const tokenMaxDeltaLine = this._tokens.getMaxDeltaLine(); if (firstLineIndex >= tokenMaxDeltaLine + 1) { // this deletion occurs entirely after this block, so there is nothing to do return; } if (firstLineIndex < 0 && lastLineIndex >= tokenMaxDeltaLine + 1) { // this deletion completely encompasses this block this._startLineNumber = 0; this._tokens.clear(); return; } if (firstLineIndex < 0) { const deletedBefore = -firstLineIndex; this._startLineNumber -= deletedBefore; this._tokens.acceptDeleteRange(range.startColumn - 1, 0, 0, lastLineIndex, range.endColumn - 1); } else { this._tokens.acceptDeleteRange(0, firstLineIndex, range.startColumn - 1, lastLineIndex, range.endColumn - 1); } } _acceptInsertText(position, eolCount, firstLineLength, lastLineLength, firstCharCode) { if (eolCount === 0 && firstLineLength === 0) { // Nothing to insert return; } const lineIndex = position.lineNumber - this._startLineNumber; if (lineIndex < 0) { // this insertion occurs before this block, so we only need to adjust line numbers this._startLineNumber += eolCount; return; } const tokenMaxDeltaLine = this._tokens.getMaxDeltaLine(); if (lineIndex >= tokenMaxDeltaLine + 1) { // this insertion occurs after this block, so there is nothing to do return; } this._tokens.acceptInsertText(lineIndex, position.column - 1, eolCount, firstLineLength, lastLineLength, firstCharCode); } } exports.SparseMultilineTokens = SparseMultilineTokens; class SparseMultilineTokensStorage { constructor(tokens) { this._tokens = tokens; this._tokenCount = tokens.length / 4; } toString(startLineNumber) { const pieces = []; for (let i = 0; i < this._tokenCount; i++) { pieces.push(`(${this._getDeltaLine(i) + startLineNumber},${this._getStartCharacter(i)}-${this._getEndCharacter(i)})`); } return `[${pieces.join(',')}]`; } getMaxDeltaLine() { const tokenCount = this._getTokenCount(); if (tokenCount === 0) { return -1; } return this._getDeltaLine(tokenCount - 1); } getRange() { const tokenCount = this._getTokenCount(); if (tokenCount === 0) { return null; } const startChar = this._getStartCharacter(0); const maxDeltaLine = this._getDeltaLine(tokenCount - 1); const endChar = this._getEndCharacter(tokenCount - 1); return new range_1.Range(0, startChar + 1, maxDeltaLine, endChar + 1); } _getTokenCount() { return this._tokenCount; } _getDeltaLine(tokenIndex) { return this._tokens[4 * tokenIndex]; } _getStartCharacter(tokenIndex) { return this._tokens[4 * tokenIndex + 1]; } _getEndCharacter(tokenIndex) { return this._tokens[4 * tokenIndex + 2]; } isEmpty() { return (this._getTokenCount() === 0); } getLineTokens(deltaLine) { let low = 0; let high = this._getTokenCount() - 1; while (low < high) { const mid = low + Math.floor((high - low) / 2); const midDeltaLine = this._getDeltaLine(mid); if (midDeltaLine < deltaLine) { low = mid + 1; } else if (midDeltaLine > deltaLine) { high = mid - 1; } else { let min = mid; while (min > low && this._getDeltaLine(min - 1) === deltaLine) { min--; } let max = mid; while (max < high && this._getDeltaLine(max + 1) === deltaLine) { max++; } return new SparseLineTokens(this._tokens.subarray(4 * min, 4 * max + 4)); } } if (this._getDeltaLine(low) === deltaLine) { return new SparseLineTokens(this._tokens.subarray(4 * low, 4 * low + 4)); } return null; } clear() { this._tokenCount = 0; } removeTokens(startDeltaLine, startChar, endDeltaLine, endChar) { const tokens = this._tokens; const tokenCount = this._tokenCount; let newTokenCount = 0; let hasDeletedTokens = false; let firstDeltaLine = 0; for (let i = 0; i < tokenCount; i++) { const srcOffset = 4 * i; const tokenDeltaLine = tokens[srcOffset]; const tokenStartCharacter = tokens[srcOffset + 1]; const tokenEndCharacter = tokens[srcOffset + 2]; const tokenMetadata = tokens[srcOffset + 3]; if ((tokenDeltaLine > startDeltaLine || (tokenDeltaLine === startDeltaLine && tokenEndCharacter >= startChar)) && (tokenDeltaLine < endDeltaLine || (tokenDeltaLine === endDeltaLine && tokenStartCharacter <= endChar))) { hasDeletedTokens = true; } else { if (newTokenCount === 0) { firstDeltaLine = tokenDeltaLine; } if (hasDeletedTokens) { // must move the token to the left const destOffset = 4 * newTokenCount; tokens[destOffset] = tokenDeltaLine - firstDeltaLine; tokens[destOffset + 1] = tokenStartCharacter; tokens[destOffset + 2] = tokenEndCharacter; tokens[destOffset + 3] = tokenMetadata; } newTokenCount++; } } this._tokenCount = newTokenCount; return firstDeltaLine; } split(startDeltaLine, startChar, endDeltaLine, endChar) { const tokens = this._tokens; const tokenCount = this._tokenCount; const aTokens = []; const bTokens = []; let destTokens = aTokens; let destOffset = 0; let destFirstDeltaLine = 0; for (let i = 0; i < tokenCount; i++) { const srcOffset = 4 * i; const tokenDeltaLine = tokens[srcOffset]; const tokenStartCharacter = tokens[srcOffset + 1]; const tokenEndCharacter = tokens[srcOffset + 2]; const tokenMetadata = tokens[srcOffset + 3]; if ((tokenDeltaLine > startDeltaLine || (tokenDeltaLine === startDeltaLine && tokenEndCharacter >= startChar))) { if ((tokenDeltaLine < endDeltaLine || (tokenDeltaLine === endDeltaLine && tokenStartCharacter <= endChar))) { // this token is touching the range continue; } else { // this token is after the range if (destTokens !== bTokens) { // this token is the first token after the range destTokens = bTokens; destOffset = 0; destFirstDeltaLine = tokenDeltaLine; } } } destTokens[destOffset++] = tokenDeltaLine - destFirstDeltaLine; destTokens[destOffset++] = tokenStartCharacter; destTokens[destOffset++] = tokenEndCharacter; destTokens[destOffset++] = tokenMetadata; } return [new SparseMultilineTokensStorage(new Uint32Array(aTokens)), new SparseMultilineTokensStorage(new Uint32Array(bTokens)), destFirstDeltaLine]; } acceptDeleteRange(horizontalShiftForFirstLineTokens, startDeltaLine, startCharacter, endDeltaLine, endCharacter) { // This is a bit complex, here are the cases I used to think about this: // // 1. The token starts before the deletion range // 1a. The token is completely before the deletion range // ----------- // xxxxxxxxxxx // 1b. The token starts before, the deletion range ends after the token // ----------- // xxxxxxxxxxx // 1c. The token starts before, the deletion range ends precisely with the token // --------------- // xxxxxxxx // 1d. The token starts before, the deletion range is inside the token // --------------- // xxxxx // // 2. The token starts at the same position with the deletion range // 2a. The token starts at the same position, and ends inside the deletion range // ------- // xxxxxxxxxxx // 2b. The token starts at the same position, and ends at the same position as the deletion range // ---------- // xxxxxxxxxx // 2c. The token starts at the same position, and ends after the deletion range // ------------- // xxxxxxx // // 3. The token starts inside the deletion range // 3a. The token is inside the deletion range // ------- // xxxxxxxxxxxxx // 3b. The token starts inside the deletion range, and ends at the same position as the deletion range // ---------- // xxxxxxxxxxxxx // 3c. The token starts inside the deletion range, and ends after the deletion range // ------------ // xxxxxxxxxxx // // 4. The token starts after the deletion range // ----------- // xxxxxxxx // const tokens = this._tokens; const tokenCount = this._tokenCount; const deletedLineCount = (endDeltaLine - startDeltaLine); let newTokenCount = 0; let hasDeletedTokens = false; for (let i = 0; i < tokenCount; i++) { const srcOffset = 4 * i; let tokenDeltaLine = tokens[srcOffset]; let tokenStartCharacter = tokens[srcOffset + 1]; let tokenEndCharacter = tokens[srcOffset + 2]; const tokenMetadata = tokens[srcOffset + 3]; if (tokenDeltaLine < startDeltaLine || (tokenDeltaLine === startDeltaLine && tokenEndCharacter <= startCharacter)) { // 1a. The token is completely before the deletion range // => nothing to do newTokenCount++; continue; } else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter < startCharacter) { // 1b, 1c, 1d // => the token survives, but it needs to shrink if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) { // 1d. The token starts before, the deletion range is inside the token // => the token shrinks by the deletion character count tokenEndCharacter -= (endCharacter - startCharacter); } else { // 1b. The token starts before, the deletion range ends after the token // 1c. The token starts before, the deletion range ends precisely with the token // => the token shrinks its ending to the deletion start tokenEndCharacter = startCharacter; } } else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter === startCharacter) { // 2a, 2b, 2c if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) { // 2c. The token starts at the same position, and ends after the deletion range // => the token shrinks by the deletion character count tokenEndCharacter -= (endCharacter - startCharacter); } else { // 2a. The token starts at the same position, and ends inside the deletion range // 2b. The token starts at the same position, and ends at the same position as the deletion range // => the token is deleted hasDeletedTokens = true; continue; } } else if (tokenDeltaLine < endDeltaLine || (tokenDeltaLine === endDeltaLine && tokenStartCharacter < endCharacter)) { // 3a, 3b, 3c if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) { // 3c. The token starts inside the deletion range, and ends after the deletion range // => the token moves 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; } } } class SparseLineTokens { constructor(tokens) { this._tokens = tokens; } getCount() { return this._tokens.length / 4; } getStartCharacter(tokenIndex) { return this._tokens[4 * tokenIndex + 1]; } getEndCharacter(tokenIndex) { return this._tokens[4 * tokenIndex + 2]; } getMetadata(tokenIndex) { return this._tokens[4 * tokenIndex + 3]; } } exports.SparseLineTokens = SparseLineTokens; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[436/*vs/editor/common/tokens/sparseTokensStore*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,75/*vs/editor/common/tokens/lineTokens*/]), function (require, exports, arrays, lineTokens_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SparseTokensStore = void 0; /** * Represents sparse tokens in a text model. */ class SparseTokensStore { constructor(languageIdCodec) { this._pieces = []; this._isComplete = false; this._languageIdCodec = languageIdCodec; } flush() { this._pieces = []; this._isComplete = false; } isEmpty() { return (this._pieces.length === 0); } set(pieces, isComplete) { this._pieces = pieces || []; this._isComplete = isComplete; } setPartial(_range, pieces) { // console.log(`setPartial ${_range} ${pieces.map(p => p.toString()).join(', ')}`); let range = _range; if (pieces.length > 0) { const _firstRange = pieces[0].getRange(); const _lastRange = pieces[pieces.length - 1].getRange(); if (!_firstRange || !_lastRange) { return _range; } range = _range.plusRange(_firstRange).plusRange(_lastRange); } let insertPosition = null; for (let i = 0, len = this._pieces.length; i < len; i++) { const piece = this._pieces[i]; if (piece.endLineNumber < range.startLineNumber) { // this piece is before the range continue; } if (piece.startLineNumber > range.endLineNumber) { // this piece is after the range, so mark the spot before this piece // as a good insertion position and stop looping insertPosition = insertPosition || { index: i }; break; } // this piece might intersect with the range piece.removeTokens(range); if (piece.isEmpty()) { // remove the piece if it became empty this._pieces.splice(i, 1); i--; len--; continue; } if (piece.endLineNumber < range.startLineNumber) { // after removal, this piece is before the range continue; } if (piece.startLineNumber > range.endLineNumber) { // after removal, this piece is after the range insertPosition = insertPosition || { index: i }; continue; } // after removal, this piece contains the range const [a, b] = piece.split(range); if (a.isEmpty()) { // this piece is actually after the range insertPosition = insertPosition || { index: i }; continue; } if (b.isEmpty()) { // this piece is actually before the range continue; } this._pieces.splice(i, 1, a, b); i++; len++; insertPosition = insertPosition || { index: i }; } insertPosition = insertPosition || { index: this._pieces.length }; if (pieces.length > 0) { this._pieces = arrays.arrayInsert(this._pieces, insertPosition.index, pieces); } // console.log(`I HAVE ${this._pieces.length} pieces`); // console.log(`${this._pieces.map(p => p.toString()).join('\n')}`); return range; } isComplete() { return this._isComplete; } addSparseTokens(lineNumber, aTokens) { const pieces = this._pieces; if (pieces.length === 0) { return aTokens; } const pieceIndex = SparseTokensStore._findFirstPieceWithLine(pieces, lineNumber); const bTokens = pieces[pieceIndex].getLineTokens(lineNumber); if (!bTokens) { return aTokens; } const aLen = aTokens.getCount(); const bLen = bTokens.getCount(); let aIndex = 0; const result = []; let resultLen = 0; let lastEndOffset = 0; const emitToken = (endOffset, metadata) => { if (endOffset === lastEndOffset) { return; } lastEndOffset = endOffset; result[resultLen++] = endOffset; result[resultLen++] = metadata; }; for (let bIndex = 0; bIndex < bLen; bIndex++) { const bStartCharacter = bTokens.getStartCharacter(bIndex); const bEndCharacter = bTokens.getEndCharacter(bIndex); const bMetadata = bTokens.getMetadata(bIndex); const bMask = (((bMetadata & 1 /* SEMANTIC_USE_ITALIC */) ? 1024 /* ITALIC_MASK */ : 0) | ((bMetadata & 2 /* SEMANTIC_USE_BOLD */) ? 2048 /* BOLD_MASK */ : 0) | ((bMetadata & 4 /* SEMANTIC_USE_UNDERLINE */) ? 4096 /* UNDERLINE_MASK */ : 0) | ((bMetadata & 8 /* SEMANTIC_USE_STRIKETHROUGH */) ? 8192 /* STRIKETHROUGH_MASK */ : 0) | ((bMetadata & 16 /* SEMANTIC_USE_FOREGROUND */) ? 8372224 /* FOREGROUND_MASK */ : 0) | ((bMetadata & 32 /* 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(), this._languageIdCodec); } static _findFirstPieceWithLine(pieces, lineNumber) { let low = 0; let high = pieces.length - 1; while (low < high) { let mid = low + Math.floor((high - low) / 2); if (pieces[mid].endLineNumber < lineNumber) { low = mid + 1; } else if (pieces[mid].startLineNumber > lineNumber) { high = mid - 1; } else { while (mid > low && pieces[mid - 1].startLineNumber <= lineNumber && lineNumber <= pieces[mid - 1].endLineNumber) { mid--; } return mid; } } return low; } acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode) { for (const piece of this._pieces) { piece.acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode); } } } exports.SparseTokensStore = SparseTokensStore; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[151/*vs/editor/common/viewLayout/lineDecorations*/], __M([1/*require*/,0/*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 []; } const result = []; let resultLen = 0; for (let i = 0, len = lineDecorations.length; i < len; i++) { const d = lineDecorations[i]; const range = d.range; if (range.endLineNumber < lineNumber || range.startLineNumber > lineNumber) { // Ignore decorations that sit outside this line continue; } if (range.isEmpty() && (d.type === 0 /* 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 []; } const result = []; const stack = new Stack(); let nextStartOffset = 0; for (let i = 0, len = lineDecorations.length; i < len; i++) { const d = lineDecorations[i]; let startColumn = d.startColumn; let endColumn = d.endColumn; const className = d.className; const metadata = (d.type === 1 /* 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[437/*vs/editor/common/viewLayout/linesLayout*/], __M([1/*require*/,0/*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) => { const result = []; for (const whitespace of whitespaces) { if (toRemove.has(whitespace.id)) { continue; } if (toChange.has(whitespace.id)) { const change = toChange.get(whitespace.id); whitespace.afterLineNumber = change.newAfterLineNumber; whitespace.height = change.newHeight; } result.push(whitespace); } return result; }; const result = applyRemoveAndChange(this._arr).concat(applyRemoveAndChange(inserts)); result.sort((a, b) => { if (a.afterLineNumber === b.afterLineNumber) { return a.ordinal - b.ordinal; } return a.afterLineNumber - b.afterLineNumber; }); this._arr = result; this._prefixSumValidIndex = -1; } _checkPendingChanges() { if (this._pendingChanges.mustCommit()) { this._pendingChanges.commit(this); } } _insertWhitespace(whitespace) { const insertIndex = LinesLayout.findInsertionIndex(this._arr, whitespace.afterLineNumber, whitespace.ordinal); this._arr.splice(insertIndex, 0, whitespace); this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, insertIndex - 1); } _findWhitespaceIndex(id) { const arr = this._arr; for (let i = 0, len = arr.length; i < len; i++) { if (arr[i].id === id) { return i; } } return -1; } _changeOneWhitespace(id, newAfterLineNumber, newHeight) { const index = this._findWhitespaceIndex(id); if (index === -1) { return; } if (this._arr[index].height !== newHeight) { this._arr[index].height = newHeight; this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, index - 1); } if (this._arr[index].afterLineNumber !== newAfterLineNumber) { // `afterLineNumber` changed for this whitespace // Record old whitespace const whitespace = this._arr[index]; // Since changing `afterLineNumber` can trigger a reordering, we're gonna remove this whitespace this._removeWhitespace(index); whitespace.afterLineNumber = newAfterLineNumber; // And add it again this._insertWhitespace(whitespace); } } _removeWhitespace(removeIndex) { this._arr.splice(removeIndex, 1); this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, removeIndex - 1); } /** * Notify the layouter that lines have been deleted (a continuous zone of lines). * * @param fromLineNumber The line number at which the deletion started, inclusive * @param toLineNumber The line number at which the deletion ended, inclusive */ onLinesDeleted(fromLineNumber, toLineNumber) { this._checkPendingChanges(); fromLineNumber = fromLineNumber | 0; toLineNumber = toLineNumber | 0; this._lineCount -= (toLineNumber - fromLineNumber + 1); for (let i = 0, len = this._arr.length; i < len; i++) { const afterLineNumber = this._arr[i].afterLineNumber; if (fromLineNumber <= afterLineNumber && afterLineNumber <= toLineNumber) { // The line this whitespace was after has been deleted // => move whitespace to before first deleted line this._arr[i].afterLineNumber = fromLineNumber - 1; } else if (afterLineNumber > toLineNumber) { // The line this whitespace was after has been moved up // => move whitespace up this._arr[i].afterLineNumber -= (toLineNumber - fromLineNumber + 1); } } } /** * Notify the layouter that lines have been inserted (a continuous zone of lines). * * @param fromLineNumber The line number at which the insertion started, inclusive * @param toLineNumber The line number at which the insertion ended, inclusive. */ onLinesInserted(fromLineNumber, toLineNumber) { this._checkPendingChanges(); fromLineNumber = fromLineNumber | 0; toLineNumber = toLineNumber | 0; this._lineCount += (toLineNumber - fromLineNumber + 1); for (let i = 0, len = this._arr.length; i < len; i++) { const afterLineNumber = this._arr[i].afterLineNumber; if (fromLineNumber <= afterLineNumber) { this._arr[i].afterLineNumber += (toLineNumber - fromLineNumber + 1); } } } /** * Get the sum of all the whitespaces. */ getWhitespacesTotalHeight() { this._checkPendingChanges(); if (this._arr.length === 0) { return 0; } return this.getWhitespacesAccumulatedHeight(this._arr.length - 1); } /** * Return the sum of the heights of the whitespaces at [0..index]. * This includes the whitespace at `index`. * * @param index The index of the whitespace. * @return The sum of the heights of all whitespaces before the one at `index`, including the one at `index`. */ getWhitespacesAccumulatedHeight(index) { this._checkPendingChanges(); index = index | 0; let startIndex = Math.max(0, this._prefixSumValidIndex + 1); if (startIndex === 0) { this._arr[0].prefixSum = this._arr[0].height; startIndex++; } for (let i = startIndex; i <= index; i++) { this._arr[i].prefixSum = this._arr[i - 1].prefixSum + this._arr[i].height; } this._prefixSumValidIndex = Math.max(this._prefixSumValidIndex, index); return this._arr[index].prefixSum; } /** * Get the sum of heights for all objects. * * @return The sum of heights for all objects. */ getLinesTotalHeight() { this._checkPendingChanges(); const linesHeight = this._lineHeight * this._lineCount; const whitespacesHeight = this.getWhitespacesTotalHeight(); return linesHeight + whitespacesHeight + this._paddingTop + this._paddingBottom; } /** * Returns the accumulated height of whitespaces before the given line number. * * @param lineNumber The line number */ getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber) { this._checkPendingChanges(); lineNumber = lineNumber | 0; const lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber); if (lastWhitespaceBeforeLineNumber === -1) { return 0; } return this.getWhitespacesAccumulatedHeight(lastWhitespaceBeforeLineNumber); } _findLastWhitespaceBeforeLineNumber(lineNumber) { lineNumber = lineNumber | 0; // Find the whitespace before line number const arr = this._arr; let low = 0; let high = arr.length - 1; while (low <= high) { const delta = (high - low) | 0; const halfDelta = (delta / 2) | 0; const mid = (low + halfDelta) | 0; if (arr[mid].afterLineNumber < lineNumber) { if (mid + 1 >= arr.length || arr[mid + 1].afterLineNumber >= lineNumber) { return mid; } else { low = (mid + 1) | 0; } } else { high = (mid - 1) | 0; } } return -1; } _findFirstWhitespaceAfterLineNumber(lineNumber) { lineNumber = lineNumber | 0; const lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber); const firstWhitespaceAfterLineNumber = lastWhitespaceBeforeLineNumber + 1; if (firstWhitespaceAfterLineNumber < this._arr.length) { return firstWhitespaceAfterLineNumber; } return -1; } /** * Find the index of the first whitespace which has `afterLineNumber` >= `lineNumber`. * @return The index of the first whitespace with `afterLineNumber` >= `lineNumber` or -1 if no whitespace is found. */ getFirstWhitespaceIndexAfterLineNumber(lineNumber) { this._checkPendingChanges(); lineNumber = lineNumber | 0; return this._findFirstWhitespaceAfterLineNumber(lineNumber); } /** * Get the vertical offset (the sum of heights for all objects above) a certain line number. * * @param lineNumber The line number * @return The sum of heights for all objects above `lineNumber`. */ getVerticalOffsetForLineNumber(lineNumber) { 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 []; } const result = []; for (let i = startIndex; i <= endIndex; i++) { const top = this.getVerticalOffsetForWhitespaceIndex(i); const height = this.getHeightForWhitespaceIndex(i); if (top >= verticalOffset2) { break; } result.push({ id: this.getIdForWhitespaceIndex(i), afterLineNumber: this.getAfterLineNumberForWhitespaceIndex(i), verticalOffset: top, height: height }); } return result; } /** * Get all whitespaces. */ getWhitespaces() { this._checkPendingChanges(); return this._arr.slice(0); } /** * The number of whitespaces. */ getWhitespacesCount() { this._checkPendingChanges(); return this._arr.length; } /** * Get the `id` for whitespace at index `index`. * * @param index The index of the whitespace. * @return `id` of whitespace at `index`. */ getIdForWhitespaceIndex(index) { this._checkPendingChanges(); index = index | 0; return this._arr[index].id; } /** * Get the `afterLineNumber` for whitespace at index `index`. * * @param index The index of the whitespace. * @return `afterLineNumber` of whitespace at `index`. */ getAfterLineNumberForWhitespaceIndex(index) { this._checkPendingChanges(); index = index | 0; return this._arr[index].afterLineNumber; } /** * Get the `height` for whitespace at index `index`. * * @param index The index of the whitespace. * @return `height` of whitespace at `index`. */ getHeightForWhitespaceIndex(index) { this._checkPendingChanges(); index = index | 0; return this._arr[index].height; } } exports.LinesLayout = LinesLayout; 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[122/*vs/editor/common/viewLayout/viewLineRenderer*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,90/*vs/editor/common/core/stringBuilder*/,151/*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; } const searchEntry = ((partIndex << 16 /* PART_INDEX_OFFSET */) | (charIndex << 0 /* CHAR_INDEX_OFFSET */)) >>> 0; let min = 0; let max = this.length - 1; while (min + 1 < max) { const mid = ((min + max) >>> 1); const midEntry = this._data[mid]; if (midEntry === searchEntry) { return mid; } else if (midEntry > searchEntry) { max = mid; } else { min = mid; } } if (min === max) { return min; } const minEntry = this._data[min]; const maxEntry = this._data[max]; if (minEntry === searchEntry) { return min; } if (maxEntry === searchEntry) { return max; } const minPartIndex = CharacterMapping.getPartIndex(minEntry); const minCharIndex = CharacterMapping.getCharIndex(minEntry); const maxPartIndex = CharacterMapping.getPartIndex(maxEntry); let maxCharIndex; if (minPartIndex !== maxPartIndex) { // sitting between parts maxCharIndex = partLength; } else { maxCharIndex = CharacterMapping.getCharIndex(maxEntry); } const minEntryDistance = charIndex - minCharIndex; const maxEntryDistance = maxCharIndex - charIndex; if (minEntryDistance <= maxEntryDistance) { return min; } return max; } } exports.CharacterMapping = CharacterMapping; class RenderLineOutput { constructor(characterMapping, containsRTL, containsForeignElements) { this._renderLineOutputBrand = undefined; this.characterMapping = characterMapping; this.containsRTL = containsRTL; this.containsForeignElements = containsForeignElements; } } exports.RenderLineOutput = RenderLineOutput; function renderViewLine(input, sb) { if (input.lineContent.length === 0) { if (input.lineDecorations.length > 0) { // This line is empty, but it contains inline decorations sb.appendASCIIString(``); 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(``); if (lineDecoration.type === 1 /* Before */) { containsForeignElements |= 1 /* Before */; beforeCount++; } if (lineDecoration.type === 2 /* After */) { containsForeignElements |= 2 /* After */; afterCount++; } } } sb.appendASCIIString(``); const characterMapping = new CharacterMapping(1, beforeCount + afterCount); characterMapping.setColumnInfo(1, beforeCount, 0, 0); return new RenderLineOutput(characterMapping, false, containsForeignElements); } // completely empty line sb.appendASCIIString(''); 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) { const sb = (0, stringBuilder_1.createStringBuilder)(10000); const 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.renderControlCharacters && !input.isBasicASCII) { // Calling `extractControlCharacters` before adding (possibly empty) line parts // for inline decorations. `extractControlCharacters` removes empty line parts. tokens = extractControlCharacters(lineContent, tokens); } if (input.renderWhitespace === 4 /* 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) { const result = []; let 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; const result = []; let resultLen = 0; if (onlyAtSpaces) { // Split only at spaces => we need to walk each character for (let i = 0, len = tokens.length; i < len; i++) { const token = tokens[i]; const tokenEndIndex = token.endIndex; if (lastTokenEndIndex + 50 /* 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; const 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++) { const 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; } function isControlCharacter(charCode) { if (charCode < 32) { return (charCode !== 9 /* Tab */); } if (charCode === 127) { // DEL return true; } if ((charCode >= 0x202A && charCode <= 0x202E) || (charCode >= 0x2066 && charCode <= 0x2069) || (charCode >= 0x200E && charCode <= 0x200F) || charCode === 0x061C) { // Unicode Directional Formatting Characters // LRE U+202A LEFT-TO-RIGHT EMBEDDING // RLE U+202B RIGHT-TO-LEFT EMBEDDING // PDF U+202C POP DIRECTIONAL FORMATTING // LRO U+202D LEFT-TO-RIGHT OVERRIDE // RLO U+202E RIGHT-TO-LEFT OVERRIDE // LRI U+2066 LEFT-TO-RIGHT ISOLATE // RLI U+2067 RIGHT-TO-LEFT ISOLATE // FSI U+2068 FIRST STRONG ISOLATE // PDI U+2069 POP DIRECTIONAL ISOLATE // LRM U+200E LEFT-TO-RIGHT MARK // RLM U+200F RIGHT-TO-LEFT MARK // ALM U+061C ARABIC LETTER MARK return true; } return false; } function extractControlCharacters(lineContent, tokens) { const result = []; let lastLinePart = new LinePart(0, '', 0); let charOffset = 0; for (const token of tokens) { const tokenEndIndex = token.endIndex; for (; charOffset < tokenEndIndex; charOffset++) { const charCode = lineContent.charCodeAt(charOffset); if (isControlCharacter(charCode)) { if (charOffset > lastLinePart.endIndex) { // emit previous part if it has text lastLinePart = new LinePart(charOffset, token.type, token.metadata); result.push(lastLinePart); } lastLinePart = new LinePart(charOffset + 1, 'mtkcontrol', token.metadata); result.push(lastLinePart); } } if (charOffset > lastLinePart.endIndex) { // emit previous part if it has text lastLinePart = new LinePart(tokenEndIndex, token.type, token.metadata); result.push(lastLinePart); } } return result; } /** * Whitespace is rendered by "replacing" tokens with a special-purpose `mtkw` type that is later recognized in the rendering phase. * Moreover, a token is created for every visual indent because on some fonts the glyphs used for rendering whitespace (→ or ·) do not have the same width as  . * 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); const result = []; let 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) { const lastCharCode = (len > 0 ? lineContent.charCodeAt(len - 1) : 0 /* Null */); const prevCharCode = (len > 1 ? lineContent.charCodeAt(len - 2) : 0 /* Null */); const 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; const result = []; let resultLen = 0; let lastResultEndIndex = 0; for (let tokenIndex = 0, len = tokens.length; tokenIndex < len; tokenIndex++) { const token = tokens[tokenIndex]; const tokenEndIndex = token.endIndex; const tokenType = token.type; const tokenMetadata = token.metadata; 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(''); } else { sb.appendASCIIString(''); } 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(' 1) { sb.write1(0x2192); // RIGHTWARDS ARROW } else { sb.write1(0xFFEB); // HALFWIDTH RIGHTWARDS ARROW } for (let space = 2; space <= charWidth; space++) { sb.write1(0xA0); //   } } else { // must be CharCode.Space charWidth = 1; sb.write1(renderSpaceCharCode); // · 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); //   } break; case 32 /* Space */: sb.write1(0xA0); //   break; case 60 /* LessThan */: sb.appendASCIIString('<'); break; case 62 /* GreaterThan */: sb.appendASCIIString('>'); break; case 38 /* Ampersand */: sb.appendASCIIString('&'); break; case 0 /* Null */: if (renderControlCharacters) { // See https://unicode-table.com/en/blocks/control-pictures/ sb.write1(9216); } else { sb.appendASCIIString('�'); } 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 if (renderControlCharacters && isControlCharacter(charCode)) { sb.appendASCIIString('[U+'); sb.appendASCIIString(to4CharHex(charCode)); sb.appendASCIIString(']'); producedCharacters = 8; } 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(''); } 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('…'); } sb.appendASCIIString(''); return new RenderLineOutput(characterMapping, containsRTL, containsForeignElements); } function to4CharHex(n) { return n.toString(16).toUpperCase().padStart(4, '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[438/*vs/editor/common/viewLayout/viewLinesViewportData*/], __M([1/*require*/,0/*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[250/*vs/editor/common/viewModel/minimapTokensColorTracker*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,236/*vs/editor/common/core/rgba*/,18/*vs/editor/common/languages*/]), function (require, exports, event_1, lifecycle_1, rgba_1, languages_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MinimapTokensColorTracker = void 0; class MinimapTokensColorTracker extends lifecycle_1.Disposable { constructor() { super(); this._onDidChange = new event_1.Emitter(); this.onDidChange = this._onDidChange.event; this._updateColorMap(); this._register(languages_1.TokenizationRegistry.onDidChange(e => { if (e.changedColorMap) { this._updateColorMap(); } })); } static getInstance() { if (!this._INSTANCE) { this._INSTANCE = (0, lifecycle_1.markAsSingleton)(new MinimapTokensColorTracker()); } return this._INSTANCE; } _updateColorMap() { const colorMap = languages_1.TokenizationRegistry.getColorMap(); if (!colorMap) { this._colors = [rgba_1.RGBA8.Empty]; this._backgroundIsLight = true; return; } this._colors = [rgba_1.RGBA8.Empty]; for (let colorId = 1; colorId < colorMap.length; colorId++) { const source = colorMap[colorId].rgba; // Use a VM friendly data-type this._colors[colorId] = new rgba_1.RGBA8(source.r, source.g, source.b, Math.round(source.a * 255)); } const backgroundLuminosity = colorMap[2 /* 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[251/*vs/editor/common/viewModel/modelLineProjectionData*/], __M([1/*require*/,0/*exports*/,20/*vs/base/common/types*/,11/*vs/editor/common/core/position*/,49/*vs/editor/common/model*/]), function (require, exports, types_1, position_1, model_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OutputPosition = exports.InjectedText = exports.ModelLineProjectionData = void 0; /** * *input*: * ``` * xxxxxxxxxxxxxxxxxxxxxxxxxxx * ``` * * -> Applying injections `[i...i]`, *inputWithInjections*: * ``` * xxxxxx[iiiiiiiiii]xxxxxxxxxxxxxxxxx[ii]xxxx * ``` * * -> breaking at offsets `|` in `xxxxxx[iiiiiii|iii]xxxxxxxxxxx|xxxxxx[ii]xxxx|`: * ``` * xxxxxx[iiiiiii * iii]xxxxxxxxxxx * xxxxxx[ii]xxxx * ``` * * -> applying wrappedTextIndentLength, *output*: * ``` * xxxxxx[iiiiiii * iii]xxxxxxxxxxx * xxxxxx[ii]xxxx * ``` */ class ModelLineProjectionData { constructor(injectionOffsets, /** * `injectionOptions.length` must equal `injectionOffsets.length` */ injectionOptions, /** * Refers to offsets after applying injections to the source. * The last break offset indicates the length of the source after applying injections. */ breakOffsets, /** * Refers to offsets after applying injections */ breakOffsetsVisibleColumn, wrappedTextIndentLength) { this.injectionOffsets = injectionOffsets; this.injectionOptions = injectionOptions; this.breakOffsets = breakOffsets; this.breakOffsetsVisibleColumn = breakOffsetsVisibleColumn; this.wrappedTextIndentLength = wrappedTextIndentLength; } getOutputLineCount() { return this.breakOffsets.length; } getMinOutputOffset(outputLineIndex) { if (outputLineIndex > 0) { return this.wrappedTextIndentLength; } return 0; } getLineLength(outputLineIndex) { // These offsets refer to model text with injected text. const startOffset = outputLineIndex > 0 ? this.breakOffsets[outputLineIndex - 1] : 0; const endOffset = this.breakOffsets[outputLineIndex]; let lineLength = endOffset - startOffset; if (outputLineIndex > 0) { lineLength += this.wrappedTextIndentLength; } return lineLength; } getMaxOutputOffset(outputLineIndex) { return this.getLineLength(outputLineIndex); } translateToInputOffset(outputLineIndex, outputOffset) { if (outputLineIndex > 0) { outputOffset = Math.max(0, outputOffset - this.wrappedTextIndentLength); } const offsetInInputWithInjection = outputLineIndex === 0 ? outputOffset : this.breakOffsets[outputLineIndex - 1] + outputOffset; let offsetInInput = offsetInInputWithInjection; if (this.injectionOffsets !== null) { for (let i = 0; i < this.injectionOffsets.length; i++) { if (offsetInInput > this.injectionOffsets[i]) { if (offsetInInput < this.injectionOffsets[i] + this.injectionOptions[i].content.length) { // `inputOffset` is within injected text offsetInInput = this.injectionOffsets[i]; } else { offsetInInput -= this.injectionOptions[i].content.length; } } else { break; } } } return offsetInInput; } translateToOutputPosition(inputOffset, affinity = 2 /* None */) { let inputOffsetInInputWithInjection = inputOffset; if (this.injectionOffsets !== null) { for (let i = 0; i < this.injectionOffsets.length; i++) { if (inputOffset < this.injectionOffsets[i]) { break; } if (affinity !== 1 /* Right */ && inputOffset === this.injectionOffsets[i]) { break; } inputOffsetInInputWithInjection += this.injectionOptions[i].content.length; } } return this.offsetInInputWithInjectionsToOutputPosition(inputOffsetInInputWithInjection, affinity); } offsetInInputWithInjectionsToOutputPosition(offsetInInputWithInjections, 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 (offsetInInputWithInjections <= midStart) { high = mid - 1; } else if (offsetInInputWithInjections > midStop) { low = mid + 1; } else { break; } } else { if (offsetInInputWithInjections < midStart) { high = mid - 1; } else if (offsetInInputWithInjections >= midStop) { low = mid + 1; } else { break; } } } let outputOffset = offsetInInputWithInjections - midStart; if (mid > 0) { outputOffset += this.wrappedTextIndentLength; } return new OutputPosition(mid, outputOffset); } normalizeOutputPosition(outputLineIndex, outputOffset, affinity) { if (this.injectionOffsets !== null) { const offsetInInputWithInjections = this.outputPositionToOffsetInInputWithInjections(outputLineIndex, outputOffset); const normalizedOffsetInUnwrappedLine = this.normalizeOffsetInInputWithInjectionsAroundInjections(offsetInInputWithInjections, affinity); if (normalizedOffsetInUnwrappedLine !== offsetInInputWithInjections) { // injected text caused a change return this.offsetInInputWithInjectionsToOutputPosition(normalizedOffsetInUnwrappedLine, affinity); } } if (affinity === 0 /* Left */) { if (outputLineIndex > 0 && outputOffset === this.getMinOutputOffset(outputLineIndex)) { return new OutputPosition(outputLineIndex - 1, this.getMaxOutputOffset(outputLineIndex - 1)); } } else if (affinity === 1 /* Right */) { const maxOutputLineIndex = this.getOutputLineCount() - 1; if (outputLineIndex < maxOutputLineIndex && outputOffset === this.getMaxOutputOffset(outputLineIndex)) { return new OutputPosition(outputLineIndex + 1, this.getMinOutputOffset(outputLineIndex + 1)); } } return new OutputPosition(outputLineIndex, outputOffset); } outputPositionToOffsetInInputWithInjections(outputLineIndex, outputOffset) { if (outputLineIndex > 0) { outputOffset = Math.max(0, outputOffset - this.wrappedTextIndentLength); } const result = (outputLineIndex > 0 ? this.breakOffsets[outputLineIndex - 1] : 0) + outputOffset; return result; } normalizeOffsetInInputWithInjectionsAroundInjections(offsetInInputWithInjections, affinity) { const injectedText = this.getInjectedTextAtOffset(offsetInInputWithInjections); if (!injectedText) { return offsetInInputWithInjections; } if (affinity === 2 /* None */) { if (offsetInInputWithInjections === injectedText.offsetInInputWithInjections + injectedText.length && hasRightCursorStop(this.injectionOptions[injectedText.injectedTextIndex].cursorStops)) { return injectedText.offsetInInputWithInjections + injectedText.length; } else { let result = injectedText.offsetInInputWithInjections; if (hasLeftCursorStop(this.injectionOptions[injectedText.injectedTextIndex].cursorStops)) { return result; } let index = injectedText.injectedTextIndex - 1; while (index >= 0 && this.injectionOffsets[index] === this.injectionOffsets[injectedText.injectedTextIndex]) { if (hasRightCursorStop(this.injectionOptions[index].cursorStops)) { break; } result -= this.injectionOptions[index].content.length; if (hasLeftCursorStop(this.injectionOptions[index].cursorStops)) { break; } index--; } return result; } } else if (affinity === 1 /* Right */) { let result = injectedText.offsetInInputWithInjections + injectedText.length; let index = injectedText.injectedTextIndex; // traverse all injected text that touch each other while (index + 1 < this.injectionOffsets.length && this.injectionOffsets[index + 1] === this.injectionOffsets[index]) { result += this.injectionOptions[index + 1].content.length; index++; } return result; } else if (affinity === 0 /* Left */) { // affinity is left let result = injectedText.offsetInInputWithInjections; let index = injectedText.injectedTextIndex; // traverse all injected text that touch each other while (index - 1 >= 0 && this.injectionOffsets[index - 1] === this.injectionOffsets[index]) { result -= this.injectionOptions[index - 1].content.length; index--; } return result; } (0, types_1.assertNever)(affinity); } getInjectedText(outputLineIndex, outputOffset) { const offset = this.outputPositionToOffsetInInputWithInjections(outputLineIndex, outputOffset); const injectedText = this.getInjectedTextAtOffset(offset); if (!injectedText) { return null; } return { options: this.injectionOptions[injectedText.injectedTextIndex] }; } getInjectedTextAtOffset(offsetInInputWithInjections) { const injectionOffsets = this.injectionOffsets; const injectionOptions = this.injectionOptions; if (injectionOffsets !== null) { let totalInjectedTextLengthBefore = 0; for (let i = 0; i < injectionOffsets.length; i++) { const length = injectionOptions[i].content.length; const injectedTextStartOffsetInInputWithInjections = injectionOffsets[i] + totalInjectedTextLengthBefore; const injectedTextEndOffsetInInputWithInjections = injectionOffsets[i] + totalInjectedTextLengthBefore + length; if (injectedTextStartOffsetInInputWithInjections > offsetInInputWithInjections) { // Injected text starts later. break; // All later injected texts have an even larger offset. } if (offsetInInputWithInjections <= injectedTextEndOffsetInInputWithInjections) { // Injected text ends after or with the given position (but also starts with or before it). return { injectedTextIndex: i, offsetInInputWithInjections: injectedTextStartOffsetInInputWithInjections, length }; } totalInjectedTextLengthBefore += length; } } return undefined; } } exports.ModelLineProjectionData = ModelLineProjectionData; function hasRightCursorStop(cursorStop) { if (cursorStop === null || cursorStop === undefined) { return true; } return cursorStop === model_1.InjectedTextCursorStops.Right || cursorStop === model_1.InjectedTextCursorStops.Both; } function hasLeftCursorStop(cursorStop) { if (cursorStop === null || cursorStop === undefined) { return true; } return cursorStop === model_1.InjectedTextCursorStops.Left || cursorStop === model_1.InjectedTextCursorStops.Both; } class InjectedText { constructor(options) { this.options = options; } } exports.InjectedText = InjectedText; class OutputPosition { constructor(outputLineIndex, outputOffset) { this.outputLineIndex = outputLineIndex; this.outputOffset = outputOffset; } toString() { return `${this.outputLineIndex}:${this.outputOffset}`; } toPosition(baseLineNumber) { return new position_1.Position(baseLineNumber + this.outputLineIndex, this.outputOffset + 1); } } exports.OutputPosition = OutputPosition; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[439/*vs/editor/common/viewModel/monospaceLineBreaksComputer*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,97/*vs/editor/common/core/characterClassifier*/,91/*vs/editor/common/textModelEvents*/,251/*vs/editor/common/viewModel/modelLineProjectionData*/]), function (require, exports, strings, characterClassifier_1, textModelEvents_1, modelLineProjectionData_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MonospaceLineBreaksComputerFactory = void 0; class MonospaceLineBreaksComputerFactory { constructor(breakBeforeChars, breakAfterChars) { this.classifier = new WrappingCharacterClassifier(breakBeforeChars, breakAfterChars); } static create(options) { return new MonospaceLineBreaksComputerFactory(options.get(120 /* wordWrapBreakBeforeCharacters */), options.get(119 /* wordWrapBreakAfterCharacters */)); } createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent) { const requests = []; const injectedTexts = []; const previousBreakingData = []; return { addRequest: (lineText, injectedText, previousLineBreakData) => { requests.push(lineText); injectedTexts.push(injectedText); previousBreakingData.push(previousLineBreakData); }, finalize: () => { const columnsForFullWidthChar = fontInfo.typicalFullwidthCharacterWidth / fontInfo.typicalHalfwidthCharacterWidth; const result = []; for (let i = 0, len = requests.length; i < len; i++) { const injectedText = injectedTexts[i]; const previousLineBreakData = previousBreakingData[i]; if (previousLineBreakData && !previousLineBreakData.injectionOptions && !injectedText) { result[i] = createLineBreaksFromPreviousLineBreaks(this.classifier, previousLineBreakData, requests[i], tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent); } else { result[i] = createLineBreaks(this.classifier, requests[i], injectedText, tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent); } } arrPool1.length = 0; arrPool2.length = 0; return result; } }; } } exports.MonospaceLineBreaksComputerFactory = MonospaceLineBreaksComputerFactory; 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 = []; 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; const breakingOffsets = arrPool1; const breakingOffsetsVisibleColumn = arrPool2; let breakingOffsetsCount = 0; let lastBreakingOffset = 0; let lastBreakingOffsetVisibleColumn = 0; let breakingColumn = firstLineBreakColumn; const prevLen = prevBreakingOffsets.length; let prevIndex = 0; if (prevIndex >= 0) { let bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn); while (prevIndex + 1 < prevLen) { const distance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex + 1] - breakingColumn); if (distance >= bestDistance) { break; } bestDistance = distance; prevIndex++; } } while (prevIndex < prevLen) { // Allow for prevIndex to be -1 (for the case where we hit a tab when walking backwards from the first break) let prevBreakOffset = prevIndex < 0 ? 0 : prevBreakingOffsets[prevIndex]; let prevBreakOffsetVisibleColumn = prevIndex < 0 ? 0 : prevBreakingOffsetsVisibleColumn[prevIndex]; if (lastBreakingOffset > prevBreakOffset) { prevBreakOffset = lastBreakingOffset; prevBreakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn; } let breakOffset = 0; let breakOffsetVisibleColumn = 0; let forcedBreakOffset = 0; let forcedBreakOffsetVisibleColumn = 0; // initially, we search as much as possible to the right (if it fits) if (prevBreakOffsetVisibleColumn <= breakingColumn) { let visibleColumn = prevBreakOffsetVisibleColumn; let prevCharCode = prevBreakOffset === 0 ? 0 /* 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 modelLineProjectionData_1.ModelLineProjectionData(injectionOffsets, injectionOptions, [lineText.length], [], 0); } const len = lineText.length; if (len <= 1) { if (!injectionOptions) { return null; } // creating a `LineBreakData` with an invalid `breakOffsetsVisibleColumn` is OK // because `breakOffsetsVisibleColumn` will never be used because it contains injected text return new modelLineProjectionData_1.ModelLineProjectionData(injectionOffsets, injectionOptions, [lineText.length], [], 0); } const wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent); const wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength; const breakingOffsets = []; const breakingOffsetsVisibleColumn = []; let breakingOffsetsCount = 0; let breakOffset = 0; let breakOffsetVisibleColumn = 0; let breakingColumn = firstLineBreakColumn; let prevCharCode = lineText.charCodeAt(0); let prevCharCodeClass = classifier.get(prevCharCode); let visibleColumn = computeCharWidth(prevCharCode, 0, tabSize, columnsForFullWidthChar); let startOffset = 1; if (strings.isHighSurrogate(prevCharCode)) { // A surrogate pair must always be considered as a single unit, so it is never to be broken visibleColumn += 1; prevCharCode = lineText.charCodeAt(1); prevCharCodeClass = classifier.get(prevCharCode); startOffset++; } for (let i = startOffset; i < len; i++) { const charStartOffset = i; const charCode = lineText.charCodeAt(i); let charCodeClass; let charWidth; if (strings.isHighSurrogate(charCode)) { // A surrogate pair must always be considered as a single unit, so it is never to be broken i++; charCodeClass = 0 /* 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 modelLineProjectionData_1.ModelLineProjectionData(injectionOffsets, injectionOptions, breakingOffsets, breakingOffsetsVisibleColumn, wrappedTextIndentLength); } 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[252/*vs/editor/common/viewModel/overviewZoneManager*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OverviewZoneManager = exports.OverviewRulerZone = exports.ColorZone = void 0; class ColorZone { constructor(from, to, colorId) { this._colorZoneBrand = undefined; this.from = from | 0; this.to = to | 0; this.colorId = colorId | 0; } static compare(a, b) { if (a.colorId === b.colorId) { if (a.from === b.from) { return a.to - b.to; } return a.from - b.from; } return a.colorId - b.colorId; } } exports.ColorZone = ColorZone; /** * A zone in the overview ruler */ class OverviewRulerZone { constructor(startLineNumber, endLineNumber, 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); const totalHeight = Math.floor(this.getCanvasHeight()); const outerHeight = Math.floor(this._outerHeight); const heightRatio = totalHeight / outerHeight; const halfMinimumHeight = Math.floor(4 /* MINIMUM_HEIGHT */ * this._pixelRatio / 2); const allColorZones = []; for (let i = 0, len = this._zones.length; i < len; i++) { const zone = this._zones[i]; if (!colorZonesInvalid) { const colorZone = zone.getColorZones(); if (colorZone) { allColorZones.push(colorZone); continue; } } const 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[440/*vs/editor/common/viewModel/viewContext*/], __M([1/*require*/,0/*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; } get value() { return this._theme; } 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[123/*vs/editor/common/viewModel/viewEventHandler*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/]), function (require, exports, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ViewEventHandler = void 0; class ViewEventHandler extends lifecycle_1.Disposable { constructor() { super(); this._shouldRender = true; } shouldRender() { return this._shouldRender; } forceShouldRender() { this._shouldRender = true; } setShouldRender() { this._shouldRender = true; } onDidRender() { this._shouldRender = false; } // --- begin event handlers onCompositionStart(e) { return false; } onCompositionEnd(e) { return false; } onConfigurationChanged(e) { return false; } onCursorStateChanged(e) { return false; } onDecorationsChanged(e) { return false; } onFlushed(e) { return false; } onFocusChanged(e) { return false; } onLanguageConfigurationChanged(e) { return false; } onLineMappingChanged(e) { return false; } onLinesChanged(e) { return false; } onLinesDeleted(e) { return false; } onLinesInserted(e) { return false; } onRevealRangeRequest(e) { return false; } onScrollChanged(e) { return false; } onThemeChanged(e) { return false; } onTokensChanged(e) { return false; } onTokensColorsChanged(e) { return false; } onZonesChanged(e) { return false; } // --- end event handlers handleEvents(events) { let shouldRender = false; for (let i = 0, len = events.length; i < len; i++) { const e = events[i]; switch (e.type) { case 0 /* 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[100/*vs/editor/browser/view/dynamicViewOverlay*/], __M([1/*require*/,0/*exports*/,123/*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[50/*vs/editor/browser/view/viewPart*/], __M([1/*require*/,0/*exports*/,123/*vs/editor/common/viewModel/viewEventHandler*/]), function (require, exports, viewEventHandler_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PartFingerprints = exports.ViewPart = void 0; class ViewPart extends viewEventHandler_1.ViewEventHandler { constructor(context) { super(); this._context = context; this._context.addEventHandler(this); } dispose() { this._context.removeEventHandler(this); super.dispose(); } } exports.ViewPart = ViewPart; class PartFingerprints { static write(target, partId) { target.setAttribute('data-mprt', String(partId)); } static read(target) { const r = target.getAttribute('data-mprt'); if (r === null) { return 0 /* None */; } return parseInt(r, 10); } static collect(child, stopAt) { const result = []; let 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[441/*vs/editor/browser/viewParts/contentWidgets/contentWidgets*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,50/*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(131 /* layoutInfo */); this._fixedOverflowWidgets = options.get(36 /* fixedOverflowWidgets */); this._contentWidth = layoutInfo.contentWidth; this._contentLeft = layoutInfo.contentLeft; this._lineHeight = options.get(59 /* lineHeight */); this._range = null; this._viewRange = null; this._preference = []; this._cachedDomNodeOffsetWidth = -1; this._cachedDomNodeOffsetHeight = -1; this._maxWidth = this._getMaxWidth(); this._isVisible = false; this._renderData = null; this.domNode.setPosition((this._fixedOverflowWidgets && this.allowEditorOverflow) ? 'fixed' : 'absolute'); this.domNode.setDisplay('none'); this.domNode.setVisibility('hidden'); this.domNode.setAttribute('widgetId', this.id); this.domNode.setMaxWidth(this._maxWidth); } onConfigurationChanged(e) { const options = this._context.configuration.options; this._lineHeight = options.get(59 /* lineHeight */); if (e.hasChanged(131 /* layoutInfo */)) { const layoutInfo = options.get(131 /* 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.offsetWidth || document.body.offsetWidth : this._contentWidth); } setPosition(range, preference) { this._setPosition(range); this._preference = preference; if (this._viewRange && this._preference && this._preference.length > 0) { // this content widget would like to be visible if possible // we change it from `display:none` to `display:block` even if it // might be outside the viewport such that we can measure its size // in `prepareRender` this.domNode.setDisplay('block'); } else { this.domNode.setDisplay('none'); } this._cachedDomNodeOffsetWidth = -1; this._cachedDomNodeOffsetHeight = -1; } _layoutBoxInViewport(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) { if (!this._preference || this._preference.length === 0) { return null; } const [topLeft, bottomLeft] = this._getTopAndBottomLeft(ctx); if (!topLeft || !bottomLeft) { return null; } if (this._cachedDomNodeOffsetWidth === -1 || this._cachedDomNodeOffsetHeight === -1) { let preferredDimensions = null; if (typeof this._actual.beforeRender === 'function') { preferredDimensions = safeInvoke(this._actual.beforeRender, this._actual); } if (preferredDimensions) { this._cachedDomNodeOffsetWidth = preferredDimensions.width; this._cachedDomNodeOffsetHeight = preferredDimensions.height; } else { const domNode = this.domNode.domNode; this._cachedDomNodeOffsetWidth = domNode.offsetWidth; this._cachedDomNodeOffsetHeight = domNode.offsetHeight; } } let placement; if (this.allowEditorOverflow) { placement = this._layoutBoxInPage(topLeft, bottomLeft, this._cachedDomNodeOffsetWidth, this._cachedDomNodeOffsetHeight, ctx); } else { placement = this._layoutBoxInViewport(topLeft, bottomLeft, this._cachedDomNodeOffsetWidth, this._cachedDomNodeOffsetHeight, ctx); } // Do two passes, first for perfect fit, second picks first option for (let pass = 1; pass <= 2; pass++) { for (const pref of this._preference) { // placement if (pref === 1 /* 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[442/*vs/editor/browser/viewParts/decorations/decorations*/], __M([1/*require*/,0/*exports*/,100/*vs/editor/browser/view/dynamicViewOverlay*/,3/*vs/editor/common/core/range*/,116/*vs/editor/browser/view/renderingContext*/,352/*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(59 /* lineHeight */); this._typicalHalfwidthCharacterWidth = options.get(44 /* 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(59 /* lineHeight */); this._typicalHalfwidthCharacterWidth = options.get(44 /* fontInfo */).typicalHalfwidthCharacterWidth; return true; } onDecorationsChanged(e) { return true; } onFlushed(e) { return true; } onLinesChanged(e) { return true; } onLinesDeleted(e) { return true; } onLinesInserted(e) { return true; } onScrollChanged(e) { return e.scrollTopChanged || e.scrollWidthChanged; } onZonesChanged(e) { return true; } // --- end event handlers prepareRender(ctx) { const _decorations = ctx.getDecorationsInViewport(); // Keep only decorations with `className` let decorations = []; let decorationsLen = 0; for (let i = 0, len = _decorations.length; i < len; i++) { const d = _decorations[i]; if (d.options.className) { decorations[decorationsLen++] = d; } } // Sort decorations for consistent render output decorations = decorations.sort((a, b) => { if (a.options.zIndex < b.options.zIndex) { return -1; } if (a.options.zIndex > b.options.zIndex) { return 1; } const aClassName = a.options.className; const bClassName = b.options.className; if (aClassName < bClassName) { return -1; } if (aClassName > bClassName) { return 1; } return range_1.Range.compareRangesUsingStarts(a.range, b.range); }); const visibleStartLineNumber = ctx.visibleRange.startLineNumber; const visibleEndLineNumber = ctx.visibleRange.endLineNumber; const output = []; for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) { const lineIndex = lineNumber - visibleStartLineNumber; output[lineIndex] = ''; } // Render first whole line decorations and then regular decorations this._renderWholeLineDecorations(ctx, decorations, output); this._renderNormalDecorations(ctx, decorations, output); this._renderResult = output; } _renderWholeLineDecorations(ctx, decorations, output) { const 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 = ('
    '); 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 < this._typicalHalfwidthCharacterWidth) { // collapsed/very small range case => make the decoration visible by expanding its width // expand its size on both sides (both to the left and to the right, keeping it centered) const center = Math.round(singleVisibleRange.left + singleVisibleRange.width / 2); const left = Math.max(0, Math.round(center - this._typicalHalfwidthCharacterWidth / 2)); lineVisibleRanges.ranges[0] = new renderingContext_1.HorizontalRange(left, this._typicalHalfwidthCharacterWidth); } } for (let k = 0, lenK = lineVisibleRanges.ranges.length; k < lenK; k++) { const visibleRange = lineVisibleRanges.ranges[k]; const decorationOutput = ('
    '); 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[182/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([1/*require*/,0/*exports*/,100/*vs/editor/browser/view/dynamicViewOverlay*/,353/*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(131 /* layoutInfo */); this._lineHeight = options.get(59 /* lineHeight */); this._glyphMargin = options.get(50 /* 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(131 /* layoutInfo */); this._lineHeight = options.get(59 /* lineHeight */); this._glyphMargin = options.get(50 /* 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(); const r = []; let 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;">'; 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] = (''; 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 += ''; } 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[445/*vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([1/*require*/,0/*exports*/,30/*vs/base/browser/fastDomNode*/,50/*vs/editor/browser/view/viewPart*/,360/*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(131 /* 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(131 /* 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[446/*vs/editor/browser/viewParts/overviewRuler/overviewRuler*/], __M([1/*require*/,0/*exports*/,30/*vs/base/browser/fastDomNode*/,252/*vs/editor/common/viewModel/overviewZoneManager*/,123/*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(59 /* lineHeight */)); this._zoneManager.setPixelRatio(options.get(129 /* 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(59 /* lineHeight */)) { this._zoneManager.setLineHeight(options.get(59 /* lineHeight */)); this._render(); } if (e.hasChanged(129 /* pixelRatio */)) { this._zoneManager.setPixelRatio(options.get(129 /* 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[447/*vs/editor/browser/viewParts/viewZones/viewZones*/], __M([1/*require*/,0/*exports*/,30/*vs/base/browser/fastDomNode*/,13/*vs/base/common/errors*/,50/*vs/editor/browser/view/viewPart*/,11/*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(131 /* layoutInfo */); this._lineHeight = options.get(59 /* 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); zone.isInHiddenArea = props.isInHiddenArea; const oldWhitespace = oldWhitespaces.get(id); if (oldWhitespace && (oldWhitespace.afterLineNumber !== props.afterViewLineNumber || oldWhitespace.height !== props.heightInPx)) { whitespaceAccessor.changeOneWhitespace(id, props.afterViewLineNumber, props.heightInPx); this._safeCallOnComputedHeight(zone.delegate, props.heightInPx); hadAChange = true; } } }); return hadAChange; } onConfigurationChanged(e) { const options = this._context.configuration.options; const layoutInfo = options.get(131 /* layoutInfo */); this._lineHeight = options.get(59 /* lineHeight */); this._contentWidth = layoutInfo.contentWidth; this._contentLeft = layoutInfo.contentLeft; if (e.hasChanged(59 /* 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 { isInHiddenArea: false, 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, zone.afterColumnAffinity); const isVisible = this._context.model.coordinatesConverter.modelPositionIsVisible(zoneBeforeModelPosition); return { isInHiddenArea: !isVisible, afterViewLineNumber: viewPosition.lineNumber, heightInPx: (isVisible ? this._heightInPixels(zone) : 0), minWidthInPx: this._minWidthInPixels(zone) }; } changeViewZones(callback) { let zonesHaveChanged = false; this._context.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, isInHiddenArea: props.isInHiddenArea, isVisible: false, domNode: (0, fastDomNode_1.createFastDomNode)(zone.domNode), marginDomNode: zone.marginDomNode ? (0, fastDomNode_1.createFastDomNode)(zone.marginDomNode) : null }; this._safeCallOnComputedHeight(myZone.delegate, props.heightInPx); myZone.domNode.setPosition('absolute'); myZone.domNode.domNode.style.width = '100%'; myZone.domNode.setDisplay('none'); myZone.domNode.setAttribute('monaco-view-zone', myZone.whitespaceId); this.domNode.appendChild(myZone.domNode); if (myZone.marginDomNode) { myZone.marginDomNode.setPosition('absolute'); myZone.marginDomNode.domNode.style.width = '100%'; myZone.marginDomNode.setDisplay('none'); myZone.marginDomNode.setAttribute('monaco-view-zone', myZone.whitespaceId); this.marginDomNode.appendChild(myZone.marginDomNode); } this._zones[myZone.whitespaceId] = myZone; this.setShouldRender(); return myZone.whitespaceId; } _removeZone(whitespaceAccessor, id) { if (this._zones.hasOwnProperty(id)) { const zone = this._zones[id]; delete this._zones[id]; whitespaceAccessor.removeWhitespace(zone.whitespaceId); zone.domNode.removeAttribute('monaco-visible-view-zone'); zone.domNode.removeAttribute('monaco-view-zone'); zone.domNode.domNode.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); zone.isInHiddenArea = props.isInHiddenArea; // const newOrdinal = this._getZoneOrdinal(zone.delegate); whitespaceAccessor.changeOneWhitespace(zone.whitespaceId, props.afterViewLineNumber, props.heightInPx); // TODO@Alex: change `newOrdinal` too this._safeCallOnComputedHeight(zone.delegate, props.heightInPx); this.setShouldRender(); return true; } return false; } shouldSuppressMouseDownOnViewZone(id) { if (this._zones.hasOwnProperty(id)) { const zone = this._zones[id]; return Boolean(zone.delegate.suppressMouseDown); } return false; } _heightInPixels(zone) { if (typeof zone.heightInPx === 'number') { return zone.heightInPx; } if (typeof zone.heightInLines === 'number') { return this._lineHeight * zone.heightInLines; } return this._lineHeight; } _minWidthInPixels(zone) { if (typeof zone.minWidthInPx === 'number') { return zone.minWidthInPx; } return 0; } _safeCallOnComputedHeight(zone, height) { if (typeof zone.onComputedHeight === 'function') { try { zone.onComputedHeight(height); } catch (e) { (0, errors_1.onUnexpectedError)(e); } } } _safeCallOnDomNodeTop(zone, top) { if (typeof zone.onDomNodeTop === 'function') { try { zone.onDomNodeTop(top); } catch (e) { (0, errors_1.onUnexpectedError)(e); } } } prepareRender(ctx) { // Nothing to read } render(ctx) { const visibleWhitespaces = ctx.viewportData.whitespaceViewportData; const visibleZones = {}; let hasVisibleZone = false; for (const visibleWhitespace of visibleWhitespaces) { if (this._zones[visibleWhitespace.id].isInHiddenArea) { continue; } visibleZones[visibleWhitespace.id] = visibleWhitespace; hasVisibleZone = true; } const keys = Object.keys(this._zones); for (let i = 0, len = keys.length; i < len; i++) { const id = keys[i]; const zone = this._zones[id]; let newTop = 0; let newHeight = 0; let newDisplay = 'none'; if (visibleZones.hasOwnProperty(id)) { newTop = visibleZones[id].verticalOffset - ctx.bigNumbersDelta; newHeight = visibleZones[id].height; newDisplay = 'block'; // zone is visible if (!zone.isVisible) { zone.domNode.setAttribute('monaco-visible-view-zone', 'true'); zone.isVisible = true; } this._safeCallOnDomNodeTop(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(visibleZones[id].verticalOffset)); } else { if (zone.isVisible) { zone.domNode.removeAttribute('monaco-visible-view-zone'); zone.isVisible = false; } this._safeCallOnDomNodeTop(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(-1000000)); } zone.domNode.setTop(newTop); zone.domNode.setHeight(newHeight); zone.domNode.setDisplay(newDisplay); if (zone.marginDomNode) { zone.marginDomNode.setTop(newTop); zone.marginDomNode.setHeight(newHeight); zone.marginDomNode.setDisplay(newDisplay); } } if (hasVisibleZone) { this.domNode.setWidth(Math.max(ctx.scrollWidth, this._contentWidth)); this.marginDomNode.setWidth(this._contentLeft); } } } exports.ViewZones = ViewZones; function safeInvoke1Arg(func, arg1) { try { return func(arg1); } catch (e) { (0, errors_1.onUnexpectedError)(e); } } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[183/*vs/editor/common/viewModel/viewEvents*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ViewZonesChangedEvent = exports.ViewTokensColorsChangedEvent = exports.ViewTokensChangedEvent = exports.ViewThemeChangedEvent = exports.ViewScrollChangedEvent = exports.ViewRevealRangeRequestEvent = exports.ViewLinesInsertedEvent = exports.ViewLinesDeletedEvent = exports.ViewLinesChangedEvent = exports.ViewLineMappingChangedEvent = exports.ViewLanguageConfigurationEvent = exports.ViewFocusChangedEvent = exports.ViewFlushedEvent = exports.ViewDecorationsChangedEvent = exports.ViewCursorStateChangedEvent = exports.ViewConfigurationChangedEvent = exports.ViewCompositionEndEvent = exports.ViewCompositionStartEvent = void 0; class ViewCompositionStartEvent { constructor() { this.type = 0 /* 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 of the call that caused the event. */ source, /** * Reduce the revealing to a minimum (e.g. avoid scrolling if the bounding box is visible and near the viewport edge). */ minimalReveal, /** * Range to be reavealed. */ range, /** * Selections to be revealed. */ selections, /** * The vertical reveal strategy. */ verticalType, /** * If true: there should be a horizontal & vertical revealing. * If false: there should be just a vertical revealing. */ revealHorizontal, /** * The scroll type. */ scrollType) { this.source = source; this.minimalReveal = minimalReveal; this.range = range; this.selections = selections; this.verticalType = verticalType; this.revealHorizontal = revealHorizontal; this.scrollType = scrollType; this.type = 12 /* ViewRevealRangeRequest */; } } 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[69/*vs/editor/common/viewModel/viewModel*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OverviewRulerDecorationsGroup = exports.ViewModelDecoration = exports.SingleLineInlineDecoration = exports.InlineDecoration = exports.ViewLineRenderingData = exports.ViewLineData = exports.MinimapLinesRenderingData = exports.Viewport = void 0; class Viewport { constructor(top, left, width, height) { this._viewportBrand = undefined; this.top = top | 0; this.left = left | 0; this.width = width | 0; this.height = height | 0; } } exports.Viewport = Viewport; class MinimapLinesRenderingData { constructor(tabSize, data) { this.tabSize = tabSize; this.data = data; } } exports.MinimapLinesRenderingData = MinimapLinesRenderingData; class ViewLineData { constructor(content, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens, inlineDecorations) { this._viewLineDataBrand = undefined; this.content = content; this.continuesWithWrappedLine = continuesWithWrappedLine; this.minColumn = minColumn; this.maxColumn = maxColumn; this.startVisibleColumn = startVisibleColumn; this.tokens = tokens; this.inlineDecorations = inlineDecorations; } } exports.ViewLineData = ViewLineData; class ViewLineRenderingData { constructor(minColumn, maxColumn, content, continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, tokens, inlineDecorations, tabSize, startVisibleColumn) { this.minColumn = minColumn; this.maxColumn = maxColumn; this.content = content; this.continuesWithWrappedLine = continuesWithWrappedLine; this.isBasicASCII = ViewLineRenderingData.isBasicASCII(content, mightContainNonBasicASCII); this.containsRTL = ViewLineRenderingData.containsRTL(content, this.isBasicASCII, mightContainRTL); this.tokens = tokens; this.inlineDecorations = inlineDecorations; this.tabSize = tabSize; this.startVisibleColumn = startVisibleColumn; } static isBasicASCII(lineContent, mightContainNonBasicASCII) { if (mightContainNonBasicASCII) { return strings.isBasicASCII(lineContent); } return true; } static containsRTL(lineContent, isBasicASCII, mightContainRTL) { if (!isBasicASCII && mightContainRTL) { return strings.containsRTL(lineContent); } return false; } } exports.ViewLineRenderingData = ViewLineRenderingData; class InlineDecoration { constructor(range, inlineClassName, type) { this.range = range; this.inlineClassName = inlineClassName; this.type = type; } } exports.InlineDecoration = InlineDecoration; class SingleLineInlineDecoration { constructor(startOffset, endOffset, inlineClassName, inlineClassNameAffectsLetterSpacing) { this.startOffset = startOffset; this.endOffset = endOffset; this.inlineClassName = inlineClassName; this.inlineClassNameAffectsLetterSpacing = inlineClassNameAffectsLetterSpacing; } toInlineDecoration(lineNumber) { return new InlineDecoration(new range_1.Range(lineNumber, this.startOffset + 1, lineNumber, this.endOffset + 1), this.inlineClassName, this.inlineClassNameAffectsLetterSpacing ? 3 /* RegularAffectingLetterSpacing */ : 0 /* Regular */); } } exports.SingleLineInlineDecoration = SingleLineInlineDecoration; class ViewModelDecoration { constructor(range, options) { this._viewModelDecorationBrand = undefined; this.range = range; this.options = options; } } exports.ViewModelDecoration = ViewModelDecoration; class OverviewRulerDecorationsGroup { constructor(color, zIndex, /** * Decorations are encoded in a number array using the following scheme: * - 3*i = lane * - 3*i+1 = startLineNumber * - 3*i+2 = endLineNumber */ data) { this.color = color; this.zIndex = zIndex; this.data = data; } static cmp(a, b) { if (a.zIndex === b.zIndex) { if (a.color < b.color) { return -1; } if (a.color > b.color) { return 1; } return 0; } return a.zIndex - b.zIndex; } } exports.OverviewRulerDecorationsGroup = OverviewRulerDecorationsGroup; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[448/*vs/editor/common/viewModel/modelLineProjection*/], __M([1/*require*/,0/*exports*/,75/*vs/editor/common/tokens/lineTokens*/,11/*vs/editor/common/core/position*/,91/*vs/editor/common/textModelEvents*/,69/*vs/editor/common/viewModel/viewModel*/]), function (require, exports, lineTokens_1, position_1, textModelEvents_1, viewModel_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createModelLineProjection = void 0; function createModelLineProjection(lineBreakData, isVisible) { if (lineBreakData === null) { // No mapping needed if (isVisible) { return IdentityModelLineProjection.INSTANCE; } return HiddenModelLineProjection.INSTANCE; } else { return new ModelLineProjection(lineBreakData, isVisible); } } exports.createModelLineProjection = createModelLineProjection; /** * This projection is used to * * wrap model lines * * inject text */ class ModelLineProjection { constructor(lineBreakData, isVisible) { this._projectionData = lineBreakData; this._isVisible = isVisible; } isVisible() { return this._isVisible; } setVisible(isVisible) { this._isVisible = isVisible; return this; } getProjectionData() { return this._projectionData; } getViewLineCount() { if (!this._isVisible) { return 0; } return this._projectionData.getOutputLineCount(); } getViewLineContent(model, modelLineNumber, outputLineIndex) { this._assertVisible(); const startOffsetInInputWithInjections = outputLineIndex > 0 ? this._projectionData.breakOffsets[outputLineIndex - 1] : 0; const endOffsetInInputWithInjections = this._projectionData.breakOffsets[outputLineIndex]; let r; if (this._projectionData.injectionOffsets !== null) { const injectedTexts = this._projectionData.injectionOffsets.map((offset, idx) => new textModelEvents_1.LineInjectedText(0, 0, offset + 1, this._projectionData.injectionOptions[idx], 0)); const lineWithInjections = textModelEvents_1.LineInjectedText.applyInjectedText(model.getLineContent(modelLineNumber), injectedTexts); r = lineWithInjections.substring(startOffsetInInputWithInjections, endOffsetInInputWithInjections); } else { r = model.getValueInRange({ startLineNumber: modelLineNumber, startColumn: startOffsetInInputWithInjections + 1, endLineNumber: modelLineNumber, endColumn: endOffsetInInputWithInjections + 1 }); } if (outputLineIndex > 0) { r = spaces(this._projectionData.wrappedTextIndentLength) + r; } return r; } getViewLineLength(model, modelLineNumber, outputLineIndex) { this._assertVisible(); return this._projectionData.getLineLength(outputLineIndex); } getViewLineMinColumn(_model, _modelLineNumber, outputLineIndex) { this._assertVisible(); return this._projectionData.getMinOutputOffset(outputLineIndex) + 1; } getViewLineMaxColumn(model, modelLineNumber, outputLineIndex) { this._assertVisible(); return this._projectionData.getMaxOutputOffset(outputLineIndex) + 1; } /** * Try using {@link getViewLinesData} instead. */ getViewLineData(model, modelLineNumber, outputLineIndex) { const arr = new Array(); this.getViewLinesData(model, modelLineNumber, outputLineIndex, 1, 0, [true], arr); return arr[0]; } getViewLinesData(model, modelLineNumber, outputLineIdx, lineCount, globalStartIndex, needed, result) { this._assertVisible(); const lineBreakData = this._projectionData; const injectionOffsets = lineBreakData.injectionOffsets; const injectionOptions = lineBreakData.injectionOptions; let inlineDecorationsPerOutputLine = null; if (injectionOffsets) { inlineDecorationsPerOutputLine = []; let totalInjectedTextLengthBefore = 0; let currentInjectedOffset = 0; for (let outputLineIndex = 0; outputLineIndex < lineBreakData.getOutputLineCount(); outputLineIndex++) { const inlineDecorations = new Array(); inlineDecorationsPerOutputLine[outputLineIndex] = inlineDecorations; const lineStartOffsetInInputWithInjections = outputLineIndex > 0 ? lineBreakData.breakOffsets[outputLineIndex - 1] : 0; const lineEndOffsetInInputWithInjections = lineBreakData.breakOffsets[outputLineIndex]; while (currentInjectedOffset < injectionOffsets.length) { const length = injectionOptions[currentInjectedOffset].content.length; const injectedTextStartOffsetInInputWithInjections = injectionOffsets[currentInjectedOffset] + totalInjectedTextLengthBefore; const injectedTextEndOffsetInInputWithInjections = injectedTextStartOffsetInInputWithInjections + length; if (injectedTextStartOffsetInInputWithInjections > lineEndOffsetInInputWithInjections) { // Injected text only starts in later wrapped lines. break; } if (lineStartOffsetInInputWithInjections < injectedTextEndOffsetInInputWithInjections) { // Injected text ends after or in this line (but also starts in or before this line). const options = injectionOptions[currentInjectedOffset]; if (options.inlineClassName) { const offset = (outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength : 0); const start = offset + Math.max(injectedTextStartOffsetInInputWithInjections - lineStartOffsetInInputWithInjections, 0); const end = offset + Math.min(injectedTextEndOffsetInInputWithInjections - lineStartOffsetInInputWithInjections, lineEndOffsetInInputWithInjections); if (start !== end) { inlineDecorations.push(new viewModel_1.SingleLineInlineDecoration(start, end, options.inlineClassName, options.inlineClassNameAffectsLetterSpacing)); } } } if (injectedTextEndOffsetInInputWithInjections <= lineEndOffsetInInputWithInjections) { totalInjectedTextLengthBefore += length; currentInjectedOffset++; } else { // injected text breaks into next line, process it again break; } } } } let lineWithInjections; if (injectionOffsets) { lineWithInjections = model.getLineTokens(modelLineNumber).withInserted(injectionOffsets.map((offset, idx) => ({ offset, text: injectionOptions[idx].content, tokenMetadata: lineTokens_1.LineTokens.defaultTokenMetadata }))); } else { lineWithInjections = model.getLineTokens(modelLineNumber); } for (let outputLineIndex = outputLineIdx; outputLineIndex < outputLineIdx + lineCount; outputLineIndex++) { const globalIndex = globalStartIndex + outputLineIndex - outputLineIdx; if (!needed[globalIndex]) { result[globalIndex] = null; continue; } result[globalIndex] = this._getViewLineData(lineWithInjections, inlineDecorationsPerOutputLine ? inlineDecorationsPerOutputLine[outputLineIndex] : null, outputLineIndex); } } _getViewLineData(lineWithInjections, inlineDecorations, outputLineIndex) { this._assertVisible(); const lineBreakData = this._projectionData; const deltaStartIndex = (outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength : 0); const lineStartOffsetInInputWithInjections = outputLineIndex > 0 ? lineBreakData.breakOffsets[outputLineIndex - 1] : 0; const lineEndOffsetInInputWithInjections = lineBreakData.breakOffsets[outputLineIndex]; const tokens = lineWithInjections.sliceAndInflate(lineStartOffsetInInputWithInjections, lineEndOffsetInInputWithInjections, deltaStartIndex); let lineContent = tokens.getLineContent(); if (outputLineIndex > 0) { lineContent = spaces(lineBreakData.wrappedTextIndentLength) + lineContent; } const minColumn = this._projectionData.getMinOutputOffset(outputLineIndex) + 1; const maxColumn = lineContent.length + 1; const continuesWithWrappedLine = (outputLineIndex + 1 < this.getViewLineCount()); const startVisibleColumn = (outputLineIndex === 0 ? 0 : lineBreakData.breakOffsetsVisibleColumn[outputLineIndex - 1]); return new viewModel_1.ViewLineData(lineContent, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens, inlineDecorations); } getModelColumnOfViewPosition(outputLineIndex, outputColumn) { this._assertVisible(); return this._projectionData.translateToInputOffset(outputLineIndex, outputColumn - 1) + 1; } getViewPositionOfModelPosition(deltaLineNumber, inputColumn, affinity = 2 /* None */) { this._assertVisible(); const r = this._projectionData.translateToOutputPosition(inputColumn - 1, affinity); return r.toPosition(deltaLineNumber); } getViewLineNumberOfModelPosition(deltaLineNumber, inputColumn) { this._assertVisible(); const r = this._projectionData.translateToOutputPosition(inputColumn - 1); return deltaLineNumber + r.outputLineIndex; } normalizePosition(outputLineIndex, outputPosition, affinity) { const baseViewLineNumber = outputPosition.lineNumber - outputLineIndex; const normalizedOutputPosition = this._projectionData.normalizeOutputPosition(outputLineIndex, outputPosition.column - 1, affinity); const result = normalizedOutputPosition.toPosition(baseViewLineNumber); return result; } getInjectedTextAt(outputLineIndex, outputColumn) { return this._projectionData.getInjectedText(outputLineIndex, outputColumn - 1); } _assertVisible() { if (!this._isVisible) { throw new Error('Not supported'); } } } /** * This projection does not change the model line. */ class IdentityModelLineProjection { constructor() { } isVisible() { return true; } setVisible(isVisible) { if (isVisible) { return this; } return HiddenModelLineProjection.INSTANCE; } getProjectionData() { return null; } getViewLineCount() { return 1; } getViewLineContent(model, modelLineNumber, _outputLineIndex) { return model.getLineContent(modelLineNumber); } getViewLineLength(model, modelLineNumber, _outputLineIndex) { return model.getLineLength(modelLineNumber); } getViewLineMinColumn(model, modelLineNumber, _outputLineIndex) { return model.getLineMinColumn(modelLineNumber); } getViewLineMaxColumn(model, modelLineNumber, _outputLineIndex) { return model.getLineMaxColumn(modelLineNumber); } getViewLineData(model, modelLineNumber, _outputLineIndex) { const lineTokens = model.getLineTokens(modelLineNumber); const lineContent = lineTokens.getLineContent(); return new viewModel_1.ViewLineData(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate(), null); } getViewLinesData(model, modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, globalStartIndex, needed, result) { if (!needed[globalStartIndex]) { result[globalStartIndex] = null; return; } result[globalStartIndex] = this.getViewLineData(model, modelLineNumber, 0); } getModelColumnOfViewPosition(_outputLineIndex, outputColumn) { return outputColumn; } getViewPositionOfModelPosition(deltaLineNumber, inputColumn) { return new position_1.Position(deltaLineNumber, inputColumn); } getViewLineNumberOfModelPosition(deltaLineNumber, _inputColumn) { return deltaLineNumber; } normalizePosition(outputLineIndex, outputPosition, affinity) { return outputPosition; } getInjectedTextAt(_outputLineIndex, _outputColumn) { return null; } } IdentityModelLineProjection.INSTANCE = new IdentityModelLineProjection(); /** * This projection hides the model line. */ class HiddenModelLineProjection { constructor() { } isVisible() { return false; } setVisible(isVisible) { if (!isVisible) { return this; } return IdentityModelLineProjection.INSTANCE; } getProjectionData() { return null; } getViewLineCount() { return 0; } getViewLineContent(_model, _modelLineNumber, _outputLineIndex) { throw new Error('Not supported'); } getViewLineLength(_model, _modelLineNumber, _outputLineIndex) { throw new Error('Not supported'); } getViewLineMinColumn(_model, _modelLineNumber, _outputLineIndex) { throw new Error('Not supported'); } getViewLineMaxColumn(_model, _modelLineNumber, _outputLineIndex) { throw new Error('Not supported'); } getViewLineData(_model, _modelLineNumber, _outputLineIndex) { throw new Error('Not supported'); } getViewLinesData(_model, _modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, _globalStartIndex, _needed, _result) { throw new Error('Not supported'); } getModelColumnOfViewPosition(_outputLineIndex, _outputColumn) { throw new Error('Not supported'); } getViewPositionOfModelPosition(_deltaLineNumber, _inputColumn) { throw new Error('Not supported'); } getViewLineNumberOfModelPosition(_deltaLineNumber, _inputColumn) { throw new Error('Not supported'); } normalizePosition(outputLineIndex, outputPosition, affinity) { throw new Error('Not supported'); } getInjectedTextAt(_outputLineIndex, _outputColumn) { throw new Error('Not supported'); } } HiddenModelLineProjection.INSTANCE = new HiddenModelLineProjection(); 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(' '); } }); /*--------------------------------------------------------------------------------------------- * 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/viewModel/viewModelEventDispatcher*/], __M([1/*require*/,0/*exports*/,4/*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.HiddenAreasChangedEvent = exports.ViewZonesChangedEvent = exports.ScrollChangedEvent = exports.FocusChangedEvent = exports.ContentSizeChangedEvent = exports.ViewModelEventsCollector = exports.ViewModelEventDispatcher = void 0; class ViewModelEventDispatcher extends lifecycle_1.Disposable { constructor() { super(); this._onEvent = this._register(new event_1.Emitter()); this.onEvent = this._onEvent.event; this._eventHandlers = []; this._viewEventQueue = null; this._isConsumingViewEventQueue = false; this._collector = null; this._collectorCnt = 0; this._outgoingEvents = []; } emitOutgoingEvent(e) { this._addOutgoingEvent(e); this._emitOutgoingEvents(); } _addOutgoingEvent(e) { for (let i = 0, len = this._outgoingEvents.length; i < len; i++) { if (this._outgoingEvents[i].kind === e.kind) { this._outgoingEvents[i] = this._outgoingEvents[i].merge(e); return; } } // not merged this._outgoingEvents.push(e); } _emitOutgoingEvents() { while (this._outgoingEvents.length > 0) { if (this._collector || this._isConsumingViewEventQueue) { // right now collecting or emitting view events, so let's postpone emitting return; } const event = this._outgoingEvents.shift(); if (event.isNoOp()) { continue; } this._onEvent.fire(event); } } addViewEventHandler(eventHandler) { for (let i = 0, len = this._eventHandlers.length; i < len; i++) { if (this._eventHandlers[i] === eventHandler) { console.warn('Detected duplicate listener in ViewEventDispatcher', eventHandler); } } this._eventHandlers.push(eventHandler); } removeViewEventHandler(eventHandler) { for (let i = 0; i < this._eventHandlers.length; i++) { if (this._eventHandlers[i] === eventHandler) { this._eventHandlers.splice(i, 1); break; } } } beginEmitViewEvents() { this._collectorCnt++; if (this._collectorCnt === 1) { this._collector = new ViewModelEventsCollector(); } return this._collector; } endEmitViewEvents() { this._collectorCnt--; if (this._collectorCnt === 0) { const outgoingEvents = this._collector.outgoingEvents; const viewEvents = this._collector.viewEvents; this._collector = null; for (const outgoingEvent of outgoingEvents) { this._addOutgoingEvent(outgoingEvent); } if (viewEvents.length > 0) { this._emitMany(viewEvents); } } this._emitOutgoingEvents(); } emitSingleViewEvent(event) { try { const eventsCollector = this.beginEmitViewEvents(); eventsCollector.emitViewEvent(event); } finally { this.endEmitViewEvents(); } } _emitMany(events) { if (this._viewEventQueue) { this._viewEventQueue = this._viewEventQueue.concat(events); } else { this._viewEventQueue = events; } if (!this._isConsumingViewEventQueue) { this._consumeViewEventQueue(); } } _consumeViewEventQueue() { try { this._isConsumingViewEventQueue = true; this._doConsumeQueue(); } finally { this._isConsumingViewEventQueue = false; } } _doConsumeQueue() { while (this._viewEventQueue) { // Empty event queue, as events might come in while sending these off const events = this._viewEventQueue; this._viewEventQueue = null; // Use a clone of the event handlers list, as they might remove themselves const eventHandlers = this._eventHandlers.slice(0); for (const eventHandler of eventHandlers) { eventHandler.handleEvents(events); } } } } exports.ViewModelEventDispatcher = ViewModelEventDispatcher; class ViewModelEventsCollector { constructor() { this.viewEvents = []; this.outgoingEvents = []; } emitViewEvent(event) { this.viewEvents.push(event); } emitOutgoingEvent(e) { this.outgoingEvents.push(e); } } exports.ViewModelEventsCollector = ViewModelEventsCollector; class ContentSizeChangedEvent { constructor(oldContentWidth, oldContentHeight, contentWidth, contentHeight) { this.kind = 0 /* 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 HiddenAreasChangedEvent { constructor() { this.kind = 4 /* HiddenAreasChanged */; } isNoOp() { return false; } merge(other) { return this; } } exports.HiddenAreasChangedEvent = HiddenAreasChangedEvent; class CursorStateChangedEvent { constructor(oldSelections, selections, oldModelVersionId, modelVersionId, source, reason, reachedMaxCursorCount) { this.kind = 6 /* 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 !== 6 /* 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 = 5 /* 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[449/*vs/editor/common/viewLayout/viewLayout*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,137/*vs/base/common/scrollable*/,437/*vs/editor/common/viewLayout/linesLayout*/,69/*vs/editor/common/viewModel/viewModel*/,184/*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({ forceIntegerValues: true, smoothScrollDuration, scheduleAtNextAnimationFrame })); this.onDidScroll = this._scrollable.onScroll; } getScrollable() { return this._scrollable; } setSmoothScrollDuration(smoothScrollDuration) { this._scrollable.setSmoothScrollDuration(smoothScrollDuration); } validateScrollPosition(scrollPosition) { return this._scrollable.validateScrollPosition(scrollPosition); } getScrollDimensions() { return this._dimensions; } setScrollDimensions(dimensions) { if (this._dimensions.equals(dimensions)) { return; } const oldDimensions = this._dimensions; this._dimensions = dimensions; this._scrollable.setScrollDimensions({ width: dimensions.width, scrollWidth: dimensions.scrollWidth, height: dimensions.height, scrollHeight: dimensions.scrollHeight }, true); const contentWidthChanged = (oldDimensions.contentWidth !== dimensions.contentWidth); const contentHeightChanged = (oldDimensions.contentHeight !== dimensions.contentHeight); if (contentWidthChanged || contentHeightChanged) { this._onDidContentSizeChange.fire(new viewModelEventDispatcher_1.ContentSizeChangedEvent(oldDimensions.contentWidth, oldDimensions.contentHeight, dimensions.contentWidth, dimensions.contentHeight)); } } getFutureScrollPosition() { return this._scrollable.getFutureScrollPosition(); } getCurrentScrollPosition() { return this._scrollable.getCurrentScrollPosition(); } setScrollPositionNow(update) { this._scrollable.setScrollPositionNow(update); } setScrollPositionSmooth(update) { this._scrollable.setScrollPositionSmooth(update); } } class ViewLayout extends lifecycle_1.Disposable { constructor(configuration, lineCount, scheduleAtNextAnimationFrame) { super(); this._configuration = configuration; const options = this._configuration.options; const layoutInfo = options.get(131 /* layoutInfo */); const padding = options.get(75 /* padding */); this._linesLayout = new linesLayout_1.LinesLayout(lineCount, options.get(59 /* 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(103 /* smoothScrolling */) ? SMOOTH_SCROLLING_TIME : 0); } // ---- begin view event handlers onConfigurationChanged(e) { const options = this._configuration.options; if (e.hasChanged(59 /* lineHeight */)) { this._linesLayout.setLineHeight(options.get(59 /* lineHeight */)); } if (e.hasChanged(75 /* padding */)) { const padding = options.get(75 /* padding */); this._linesLayout.setPadding(padding.top, padding.bottom); } if (e.hasChanged(131 /* layoutInfo */)) { const layoutInfo = options.get(131 /* 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(103 /* 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(92 /* 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(94 /* scrollBeyondLastLine */)) { result += Math.max(0, height - options.get(59 /* lineHeight */) - options.get(75 /* 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(132 /* wrappingInfo */); const fontInfo = options.get(44 /* fontInfo */); if (wrappingInfo.isViewportWrapping) { const layoutInfo = options.get(131 /* layoutInfo */); const minimap = options.get(65 /* 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(93 /* 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(); const scrollTop = currentScrollPosition.scrollTop; const firstLineNumberInViewport = this._linesLayout.getLineNumberAtOrAfterVerticalOffset(scrollTop); const whitespaceAboveFirstLine = this._linesLayout.getWhitespaceAccumulatedHeightBeforeLineNumber(firstLineNumberInViewport); return { scrollTop: scrollTop, scrollTopWithoutViewZones: scrollTop - whitespaceAboveFirstLine, scrollLeft: currentScrollPosition.scrollLeft }; } // ---- 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[450/*vs/editor/contrib/caretOperations/browser/moveCaretCommand*/], __M([1/*require*/,0/*exports*/,3/*vs/editor/common/core/range*/,22/*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[152/*vs/editor/contrib/codeAction/browser/types*/], __M([1/*require*/,0/*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[451/*vs/editor/contrib/colorPicker/browser/colorPickerModel*/], __M([1/*require*/,0/*exports*/,4/*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[254/*vs/editor/contrib/comment/browser/blockCommentCommand*/], __M([1/*require*/,0/*exports*/,61/*vs/editor/common/core/editOperation*/,11/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/]), function (require, exports, editOperation_1, position_1, range_1, selection_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BlockCommentCommand = void 0; class BlockCommentCommand { constructor(selection, insertSpace, languageConfigurationService) { this.languageConfigurationService = languageConfigurationService; this._selection = selection; this._insertSpace = insertSpace; this._usedEndToken = null; } static _haystackHasNeedleAtOffset(haystack, needle, offset) { if (offset < 0) { return false; } const needleLength = needle.length; const haystackLength = haystack.length; if (offset + needleLength > haystackLength) { return false; } for (let i = 0; i < needleLength; i++) { const codeA = haystack.charCodeAt(offset + i); const codeB = needle.charCodeAt(i); if (codeA === codeB) { continue; } if (codeA >= 65 /* 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 = this.languageConfigurationService.getLanguageConfiguration(languageId).comments; if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) { // Mode does not support block comments return; } this._createOperationsForBlockComment(this._selection, config.blockCommentStartToken, config.blockCommentEndToken, this._insertSpace, model, builder); } computeCursorState(model, helper) { const inverseEditOperations = helper.getInverseEditOperations(); if (inverseEditOperations.length === 2) { const startTokenEditOperation = inverseEditOperations[0]; const endTokenEditOperation = inverseEditOperations[1]; return new selection_1.Selection(startTokenEditOperation.range.endLineNumber, startTokenEditOperation.range.endColumn, endTokenEditOperation.range.startLineNumber, endTokenEditOperation.range.startColumn); } else { const srcRange = inverseEditOperations[0].range; const deltaColumn = this._usedEndToken ? -this._usedEndToken.length - 1 : 0; // minus 1 space before endToken return new selection_1.Selection(srcRange.endLineNumber, srcRange.endColumn + deltaColumn, srcRange.endLineNumber, srcRange.endColumn + deltaColumn); } } } exports.BlockCommentCommand = BlockCommentCommand; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[452/*vs/editor/contrib/dnd/browser/dragAndDropCommand*/], __M([1/*require*/,0/*exports*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/]), function (require, exports, range_1, selection_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DragAndDropCommand = void 0; class DragAndDropCommand { constructor(selection, targetPosition, copy) { this.selection = selection; this.targetPosition = targetPosition; this.copy = copy; this.targetSelection = null; } getEditOperations(model, builder) { 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[453/*vs/editor/contrib/find/browser/replaceAllCommand*/], __M([1/*require*/,0/*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[454/*vs/editor/contrib/find/browser/replacePattern*/], __M([1/*require*/,0/*exports*/,320/*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[185/*vs/editor/contrib/folding/browser/foldingRanges*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FoldingRegion = exports.FoldingRegions = exports.MAX_LINE_NUMBER = exports.MAX_FOLDING_REGIONS = 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[455/*vs/editor/contrib/folding/browser/foldingModel*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,185/*vs/editor/contrib/folding/browser/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) { const regions = foldingModel.getAllRegionsAtLine(lineNumber, undefined); if (regions.length > 0) { filteredRegions.push(regions[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 on the folding range start line, go to previous sibling. if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) { // If current line is not the start of the current fold, go to top line of current fold. If not, go to previous fold. if (lineNumber !== foldingRegion.startLineNumber) { return foldingRegion.startLineNumber; } else { // Find min line number to stay within parent. let expectedParentIndex = foldingRegion.parentIndex; let minLineNumber = 0; if (expectedParentIndex !== -1) { minLineNumber = foldingModel.regions.getStartLineNumber(foldingRegion.parentIndex); } // Find fold at same level. while (foldingRegion !== null) { if (foldingRegion.regionIndex > 0) { foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1); // Keep at same level. if (foldingRegion.startLineNumber <= minLineNumber) { return null; } else if (foldingRegion.parentIndex === expectedParentIndex) { return foldingRegion.startLineNumber; } } else { return null; } } } } else { // Go to last fold that's before the current line. if (foldingModel.regions.length > 0) { foldingRegion = foldingModel.regions.toRegion(foldingModel.regions.length - 1); while (foldingRegion !== null) { // Found fold before current line. if (foldingRegion.startLineNumber < lineNumber) { return foldingRegion.startLineNumber; } if (foldingRegion.regionIndex > 0) { foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1); } else { foldingRegion = null; } } } } return null; } 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 on the folding range start line, go to next sibling. if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) { // Find max line number to stay within parent. let expectedParentIndex = foldingRegion.parentIndex; let maxLineNumber = 0; if (expectedParentIndex !== -1) { maxLineNumber = foldingModel.regions.getEndLineNumber(foldingRegion.parentIndex); } else if (foldingModel.regions.length === 0) { return null; } else { maxLineNumber = foldingModel.regions.getEndLineNumber(foldingModel.regions.length - 1); } // Find fold at same level. while (foldingRegion !== null) { if (foldingRegion.regionIndex < foldingModel.regions.length) { foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1); // Keep at same level. if (foldingRegion.startLineNumber >= maxLineNumber) { return null; } else if (foldingRegion.parentIndex === expectedParentIndex) { return foldingRegion.startLineNumber; } } else { return null; } } } else { // Go to first fold that's after the current line. if (foldingModel.regions.length > 0) { foldingRegion = foldingModel.regions.toRegion(0); while (foldingRegion !== null) { // Found fold after current line. if (foldingRegion.startLineNumber > lineNumber) { return foldingRegion.startLineNumber; } if (foldingRegion.regionIndex < foldingModel.regions.length) { foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1); } else { foldingRegion = null; } } } } return null; } 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[456/*vs/editor/contrib/folding/browser/hiddenRangeModel*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,4/*vs/base/common/event*/,3/*vs/editor/common/core/range*/,117/*vs/editor/common/core/eolCounter*/]), function (require, exports, arrays_1, event_1, range_1, eolCounter_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HiddenRangeModel = void 0; class HiddenRangeModel { constructor(model) { this._updateEventEmitter = new event_1.Emitter(); this._hasLineChanges = false; this._foldingModel = model; this._foldingModelListener = model.onDidChange(_ => this.updateHiddenRanges()); this._hiddenRanges = []; if (model.regions.length) { this.updateHiddenRanges(); } } get onDidChange() { return this._updateEventEmitter.event; } get hiddenRanges() { return this._hiddenRanges; } notifyChangeModelContent(e) { if (this._hiddenRanges.length && !this._hasLineChanges) { this._hasLineChanges = e.changes.some(change => { return change.range.endLineNumber !== change.range.startLineNumber || (0, eolCounter_1.countEOL)(change.text)[0] !== 0; }); } } updateHiddenRanges() { let updateHiddenAreas = false; 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 (this._hasLineChanges || 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._hasLineChanges = false; this._updateEventEmitter.fire(newHiddenAreas); } hasRanges() { return this._hiddenRanges.length > 0; } isHidden(line) { return findRange(this._hiddenRanges, line) !== null; } adjustSelections(selections) { let hasChanges = false; 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[457/*vs/editor/contrib/folding/browser/indentRangeProvider*/], __M([1/*require*/,0/*exports*/,178/*vs/editor/common/model/utils*/,185/*vs/editor/contrib/folding/browser/foldingRanges*/]), function (require, exports, utils_1, foldingRanges_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_DEFAULT = 5000; exports.ID_INDENT_PROVIDER = 'indent'; class IndentRangeProvider { constructor(editorModel, languageConfigurationService, maxFoldingRegions) { this.editorModel = editorModel; this.languageConfigurationService = languageConfigurationService; this.maxFoldingRegions = maxFoldingRegions; this.id = exports.ID_INDENT_PROVIDER; } dispose() { } compute(cancelationToken, notifyTooManyRegions) { let foldingRules = this.languageConfigurationService.getLanguageConfiguration(this.editorModel.getLanguageId()).foldingRules; let offSide = foldingRules && !!foldingRules.offSide; let markers = foldingRules && foldingRules.markers; return Promise.resolve(computeRanges(this.editorModel, offSide, markers, this.maxFoldingRegions, notifyTooManyRegions)); } } exports.IndentRangeProvider = IndentRangeProvider; // public only for testing class RangesCollector { constructor(foldingRangesLimit, _notifyTooManyRegions) { this._notifyTooManyRegions = _notifyTooManyRegions; 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 { if (this._notifyTooManyRegions) { this._notifyTooManyRegions(this._foldingRangesLimit); } 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 = (0, utils_1.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, notifyTooManyRegions) { const tabSize = model.getOptions().tabSize; foldingRangesLimit = foldingRangesLimit !== null && foldingRangesLimit !== void 0 ? foldingRangesLimit : MAX_FOLDING_REGIONS_FOR_INDENT_DEFAULT; let result = new RangesCollector(foldingRangesLimit, notifyTooManyRegions); 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 = (0, utils_1.computeIndentLevel)(lineContent, tabSize); let previous = previousRegions[previousRegions.length - 1]; if (indent === -1) { if (offSide) { // for offSide languages, empty lines are associated to the previous block // note: the next block is already written to the results, so this only // impacts the end position of the block before previous.endAbove = line; } continue; // only whitespace } let m; if (pattern && (m = lineContent.match(pattern))) { // folding pattern match if (m[1]) { // start pattern match // discard all regions until the folding pattern let i = previousRegions.length - 1; while (i > 0 && previousRegions[i].indent !== -2) { i--; } if (i > 0) { previousRegions.length = i + 1; previous = previousRegions[i]; // new folding range from pattern, includes the end line result.insertFirst(line, previous.line, indent); previous.line = line; previous.indent = indent; previous.endAbove = line; continue; } else { // no end marker found, treat line as a regular line } } else { // end pattern match previousRegions.push({ indent: -2, endAbove: line, line }); continue; } } if (previous.indent > indent) { // discard all regions with larger indent do { previousRegions.pop(); previous = previousRegions[previousRegions.length - 1]; } while (previous.indent > indent); // new folding range 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[255/*vs/editor/contrib/folding/browser/syntaxRangeProvider*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,185/*vs/editor/contrib/folding/browser/foldingRanges*/]), function (require, exports, errors_1, lifecycle_1, foldingRanges_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sanitizeRanges = exports.RangesCollector = exports.SyntaxRangeProvider = exports.ID_SYNTAX_PROVIDER = void 0; const foldingContext = {}; exports.ID_SYNTAX_PROVIDER = 'syntax'; class SyntaxRangeProvider { constructor(editorModel, providers, handleFoldingRangesChange, limit) { 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, notifyTooManyRegions) { return collectSyntaxRanges(this.providers, this.editorModel, cancellationToken).then(ranges => { if (ranges) { let res = sanitizeRanges(ranges, this.limit, notifyTooManyRegions); 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, _notifyTooManyRegions) { this._notifyTooManyRegions = _notifyTooManyRegions; 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 { if (this._notifyTooManyRegions) { this._notifyTooManyRegions(this._foldingRangesLimit); } 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, notifyTooManyRegions) { 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, notifyTooManyRegions); 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[458/*vs/editor/contrib/folding/browser/intializingRangeProvider*/], __M([1/*require*/,0/*exports*/,255/*vs/editor/contrib/folding/browser/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[256/*vs/editor/contrib/format/browser/formattingEdit*/], __M([1/*require*/,0/*exports*/,61/*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[186/*vs/editor/contrib/gotoSymbol/browser/link/clickLinkGesture*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/]), function (require, exports, event_1, lifecycle_1, platform) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ClickLinkGesture = exports.ClickLinkOptions = exports.ClickLinkKeyboardEvent = exports.ClickLinkMouseEvent = void 0; function hasModifier(e, modifier) { return !!e[modifier]; } /** * An event that encapsulates the various trigger modifiers logic needed for go to definition. */ class ClickLinkMouseEvent { constructor(source, opts) { this.target = source.target; this.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(70 /* multiCursorModifier */)); this._lastMouseMoveEvent = null; this._hasTriggerKeyOnMouseDown = false; this._lineNumberOnMouseDown = 0; this._register(this._editor.onDidChangeConfiguration((e) => { if (e.hasChanged(70 /* multiCursorModifier */)) { const newOpts = createOptions(this._editor.getOption(70 /* 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. *--------------------------------------------------------------------------------------------*/ var __asyncValues = (this && this.__asyncValues) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } }; define(__m[257/*vs/editor/contrib/hover/browser/hoverOperation*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/async*/,13/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, async_1, errors_1, event_1, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HoverOperation = exports.HoverResult = void 0; class HoverResult { constructor(value, isComplete, hasLoadingMessage) { this.value = value; this.isComplete = isComplete; this.hasLoadingMessage = hasLoadingMessage; } } exports.HoverResult = HoverResult; /** * Computing the hover is very fine tuned. * * Suppose the hover delay is 300ms (the default). Then, when resting the mouse at an anchor: * - at 150ms, the async computation is triggered (i.e. semantic hover) * - if async results already come in, they are not rendered yet. * - at 300ms, the sync computation is triggered (i.e. decorations, markers) * - if there are sync or async results, they are rendered. * - at 900ms, if the async computation hasn't finished, a "Loading..." result is added. */ class HoverOperation extends lifecycle_1.Disposable { constructor(_editor, _computer) { super(); this._editor = _editor; this._computer = _computer; this._onResult = this._register(new event_1.Emitter()); this.onResult = this._onResult.event; this._firstWaitScheduler = this._register(new async_1.RunOnceScheduler(() => this._triggerAsyncComputation(), 0)); this._secondWaitScheduler = this._register(new async_1.RunOnceScheduler(() => this._triggerSyncComputation(), 0)); this._loadingMessageScheduler = this._register(new async_1.RunOnceScheduler(() => this._triggerLoadingMessage(), 0)); this._state = 0 /* Idle */; this._asyncIterable = null; this._asyncIterableDone = false; this._result = []; } dispose() { if (this._asyncIterable) { this._asyncIterable.cancel(); this._asyncIterable = null; } super.dispose(); } get _hoverTime() { return this._editor.getOption(53 /* hover */).delay; } get _firstWaitTime() { return this._hoverTime / 2; } get _secondWaitTime() { return this._hoverTime - this._firstWaitTime; } get _loadingMessageTime() { return 3 * this._hoverTime; } _setState(state, fireResult = true) { this._state = state; if (fireResult) { this._fireResult(); } } _triggerAsyncComputation() { this._setState(2 /* SecondWait */); this._secondWaitScheduler.schedule(this._secondWaitTime); if (this._computer.computeAsync) { this._asyncIterableDone = false; this._asyncIterable = (0, async_1.createCancelableAsyncIterable)(token => this._computer.computeAsync(token)); (() => __awaiter(this, void 0, void 0, function* () { var e_1, _a; try { try { for (var _b = __asyncValues(this._asyncIterable), _c; _c = yield _b.next(), !_c.done;) { const item = _c.value; if (item) { this._result.push(item); this._fireResult(); } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b); } finally { if (e_1) throw e_1.error; } } this._asyncIterableDone = true; if (this._state === 3 /* WaitingForAsync */ || this._state === 4 /* WaitingForAsyncShowingLoading */) { this._setState(0 /* Idle */); } } catch (e) { (0, errors_1.onUnexpectedError)(e); } }))(); } else { this._asyncIterableDone = true; } } _triggerSyncComputation() { if (this._computer.computeSync) { this._result = this._result.concat(this._computer.computeSync()); } this._setState(this._asyncIterableDone ? 0 /* Idle */ : 3 /* WaitingForAsync */); } _triggerLoadingMessage() { if (this._state === 3 /* WaitingForAsync */) { this._setState(4 /* WaitingForAsyncShowingLoading */); } } _fireResult() { if (this._state === 1 /* FirstWait */ || this._state === 2 /* SecondWait */) { // Do not send out results before the hover time return; } const isComplete = (this._state === 0 /* Idle */); const hasLoadingMessage = (this._state === 4 /* WaitingForAsyncShowingLoading */); this._onResult.fire(new HoverResult(this._result.slice(0), isComplete, hasLoadingMessage)); } start(mode) { if (mode === 0 /* Delayed */) { if (this._state === 0 /* Idle */) { this._setState(1 /* FirstWait */); 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 /* SecondWait */: this._secondWaitScheduler.cancel(); this._triggerSyncComputation(); break; } } } cancel() { this._firstWaitScheduler.cancel(); this._secondWaitScheduler.cancel(); this._loadingMessageScheduler.cancel(); if (this._asyncIterable) { this._asyncIterable.cancel(); this._asyncIterable = null; } this._result = []; this._setState(0 /* Idle */, false); } } exports.HoverOperation = HoverOperation; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[187/*vs/editor/contrib/hover/browser/hoverTypes*/], __M([1/*require*/,0/*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[459/*vs/editor/contrib/inPlaceReplace/browser/inPlaceReplaceCommand*/], __M([1/*require*/,0/*exports*/,22/*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[258/*vs/editor/contrib/indentation/browser/indentUtils*/], __M([1/*require*/,0/*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[460/*vs/editor/contrib/inlayHints/browser/inlayHints*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,11/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/languages*/]), function (require, exports, errors_1, lifecycle_1, position_1, range_1, languages_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.InlayHintsFragments = exports.InlayHintItem = exports.InlayHintAnchor = void 0; class InlayHintAnchor { constructor(range, direction) { this.range = range; this.direction = direction; } } exports.InlayHintAnchor = InlayHintAnchor; class InlayHintItem { constructor(hint, anchor, provider) { this.hint = hint; this.anchor = anchor; this.provider = provider; this._isResolved = false; } with(delta) { const result = new InlayHintItem(this.hint, delta.anchor, this.provider); result._isResolved = this._isResolved; result._currentResolve = this._currentResolve; return result; } resolve(token) { return __awaiter(this, void 0, void 0, function* () { if (typeof this.provider.resolveInlayHint !== 'function') { return; } if (this._currentResolve) { // wait for an active resolve operation and try again // when that's done. yield this._currentResolve; if (token.isCancellationRequested) { return; } return this.resolve(token); } if (!this._isResolved) { this._currentResolve = this._doResolve(token) .finally(() => this._currentResolve = undefined); } yield this._currentResolve; }); } _doResolve(token) { var _a, _b; return __awaiter(this, void 0, void 0, function* () { try { const newHint = yield Promise.resolve(this.provider.resolveInlayHint(this.hint, token)); this.hint.tooltip = (_a = newHint === null || newHint === void 0 ? void 0 : newHint.tooltip) !== null && _a !== void 0 ? _a : this.hint.tooltip; this.hint.label = (_b = newHint === null || newHint === void 0 ? void 0 : newHint.label) !== null && _b !== void 0 ? _b : this.hint.label; this._isResolved = true; } catch (err) { (0, errors_1.onUnexpectedExternalError)(err); this._isResolved = false; } }); } } exports.InlayHintItem = InlayHintItem; class InlayHintsFragments { constructor(ranges, data, model) { this._disposables = new lifecycle_1.DisposableStore(); this.ranges = ranges; this.provider = new Set(); const items = []; for (const [list, provider] of data) { this._disposables.add(list); this.provider.add(provider); for (const hint of list.hints) { // compute the range to which the item should be attached to let position = model.validatePosition(hint.position); let direction = 'before'; const wordRange = InlayHintsFragments._getRangeAtPosition(model, position); let range; if (wordRange.getStartPosition().isBefore(position)) { range = range_1.Range.fromPositions(wordRange.getStartPosition(), position); direction = 'after'; } else { range = range_1.Range.fromPositions(position, wordRange.getEndPosition()); direction = 'before'; } items.push(new InlayHintItem(hint, new InlayHintAnchor(range, direction), provider)); } } this.items = items.sort((a, b) => position_1.Position.compare(a.hint.position, b.hint.position)); } static create(model, ranges, token) { return __awaiter(this, void 0, void 0, function* () { const data = []; const promises = languages_1.InlayHintsProviderRegistry.ordered(model).reverse().map(provider => ranges.map((range) => __awaiter(this, void 0, void 0, function* () { try { const result = yield provider.provideInlayHints(model, range, token); if (result === null || result === void 0 ? void 0 : result.hints.length) { data.push([result, provider]); } } catch (err) { (0, errors_1.onUnexpectedExternalError)(err); } }))); yield Promise.all(promises.flat()); if (token.isCancellationRequested || model.isDisposed()) { throw new errors_1.CancellationError(); } return new InlayHintsFragments(ranges, data, model); }); } dispose() { this._disposables.dispose(); } static _getRangeAtPosition(model, position) { const line = position.lineNumber; const word = model.getWordAtPosition(position); if (word) { // always prefer the word range return new range_1.Range(line, word.startColumn, line, word.endColumn); } model.tokenizeIfCheap(line); const tokens = model.getLineTokens(line); const offset = position.column - 1; const idx = tokens.findTokenIndexAtOffset(offset); let start = tokens.getStartOffset(idx); let end = tokens.getEndOffset(idx); if (end - start === 1) { // single character token, when at its end try leading/trailing token instead if (start === offset && idx > 1) { // leading token start = tokens.getStartOffset(idx - 1); end = tokens.getEndOffset(idx - 1); } else if (end === offset && idx < tokens.getCount() - 1) { // trailing token start = tokens.getStartOffset(idx + 1); end = tokens.getEndOffset(idx + 1); } } return new range_1.Range(line, start + 1, line, end + 1); } } exports.InlayHintsFragments = InlayHintsFragments; }); /*--------------------------------------------------------------------------------------------- * 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/contrib/inlineCompletions/browser/consts*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.inlineSuggestCommitId = void 0; exports.inlineSuggestCommitId = 'editor.action.inlineSuggest.commit'; }); /*--------------------------------------------------------------------------------------------- * 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/inlineCompletions/browser/ghostText*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/]), function (require, exports, event_1, lifecycle_1, range_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; } renderForScreenReader(lineText) { if (this.parts.length === 0) { return ''; } const lastPart = this.parts[this.parts.length - 1]; const cappedLineText = lineText.substr(0, lastPart.column - 1); const text = applyEdits(cappedLineText, this.parts.map(p => ({ range: { startLineNumber: 1, endLineNumber: 1, startColumn: p.column, endColumn: p.column }, text: p.lines.join('\n') }))); return text.substring(this.parts[0].column - 1); } } exports.GhostText = GhostText; class PositionOffsetTransformer { constructor(text) { this.lineStartOffsetByLineIdx = []; this.lineStartOffsetByLineIdx.push(0); for (let i = 0; i < text.length; i++) { if (text.charAt(i) === '\n') { this.lineStartOffsetByLineIdx.push(i + 1); } } } getOffset(position) { return this.lineStartOffsetByLineIdx[position.lineNumber - 1] + position.column - 1; } } function applyEdits(text, edits) { const transformer = new PositionOffsetTransformer(text); const offsetEdits = edits.map(e => { const range = range_1.Range.lift(e.range); return ({ startOffset: transformer.getOffset(range.getStartPosition()), endOffset: transformer.getOffset(range.getEndPosition()), text: e.text }); }); offsetEdits.sort((a, b) => b.startOffset - a.startOffset); for (const edit of offsetEdits) { text = text.substring(0, edit.startOffset) + edit.text + text.substring(edit.endOffset); } return text; } class GhostTextPart { constructor(column, lines, /** * Indicates if this part is a preview of an inline suggestion when a suggestion is previewed. */ preview) { this.column = column; this.lines = lines; this.preview = preview; } } 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(106 /* suggest */) && this._expanded === undefined) { this.onDidChangeEmitter.fire(); } })); } 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[189/*vs/editor/contrib/inlineCompletions/browser/inlineCompletionToGhostText*/], __M([1/*require*/,0/*exports*/,138/*vs/base/common/diff/diff*/,8/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/,188/*vs/editor/contrib/inlineCompletions/browser/ghostText*/]), function (require, exports, diff_1, strings, range_1, ghostText_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.inlineCompletionToGhostText = exports.normalizedInlineCompletionsEquals = void 0; function normalizedInlineCompletionsEquals(a, b) { if (a === b) { return true; } if (!a || !b) { return false; } return a.range.equalsRange(b.range) && a.text === b.text && a.command === b.command; } exports.normalizedInlineCompletionsEquals = normalizedInlineCompletionsEquals; /** * @param previewSuffixLength Sets where to split `inlineCompletion.text`. * If the text is `hello` and the suffix length is 2, the non-preview part is `hel` and the preview-part is `lo`. */ function inlineCompletionToGhostText(inlineCompletion, textModel, mode, cursorPosition, previewSuffixLength = 0) { if (inlineCompletion.range.startLineNumber !== inlineCompletion.range.endLineNumber) { // Only single line replacements are supported. return undefined; } const sourceLine = textModel.getLineContent(inlineCompletion.range.startLineNumber); const sourceIndentationLength = strings.getLeadingWhitespace(sourceLine).length; const suggestionTouchesIndentation = inlineCompletion.range.startColumn - 1 <= sourceIndentationLength; if (suggestionTouchesIndentation) { // source: ··········[······abc] // ^^^^^^^^^ inlineCompletion.range // ^^^^^^^^^^ ^^^^^^ sourceIndentationLength // ^^^^^^ replacedIndentation.length // ^^^ rangeThatDoesNotReplaceIndentation // inlineCompletion.text: '··foo' // ^^ suggestionAddedIndentationLength const suggestionAddedIndentationLength = strings.getLeadingWhitespace(inlineCompletion.text).length; const replacedIndentation = sourceLine.substring(inlineCompletion.range.startColumn - 1, sourceIndentationLength); const rangeThatDoesNotReplaceIndentation = range_1.Range.fromPositions(inlineCompletion.range.getStartPosition().delta(0, replacedIndentation.length), inlineCompletion.range.getEndPosition()); const suggestionWithoutIndentationChange = inlineCompletion.text.startsWith(replacedIndentation) // Adds more indentation without changing existing indentation: We can add ghost text for this ? inlineCompletion.text.substring(replacedIndentation.length) // Changes or removes existing indentation. Only add ghost text for the non-indentation part. : inlineCompletion.text.substring(suggestionAddedIndentationLength); inlineCompletion = { range: rangeThatDoesNotReplaceIndentation, text: suggestionWithoutIndentationChange, command: inlineCompletion.command }; } // This is a single line string const valueToBeReplaced = textModel.getValueInRange(inlineCompletion.range); const changes = cachingDiff(valueToBeReplaced, inlineCompletion.text); if (!changes) { // No ghost text in case the diff would be too slow to compute return undefined; } 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; } } const previewStartInCompletionText = inlineCompletion.text.length - previewSuffixLength; 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) { return undefined; } if (c.modifiedLength === 0) { continue; } const modifiedEnd = c.modifiedStart + c.modifiedLength; const nonPreviewTextEnd = Math.max(c.modifiedStart, Math.min(modifiedEnd, previewStartInCompletionText)); const nonPreviewText = inlineCompletion.text.substring(c.modifiedStart, nonPreviewTextEnd); const italicText = inlineCompletion.text.substring(nonPreviewTextEnd, Math.max(c.modifiedStart, modifiedEnd)); if (nonPreviewText.length > 0) { const lines = strings.splitLines(nonPreviewText); parts.push(new ghostText_1.GhostTextPart(insertColumn, lines, false)); } if (italicText.length > 0) { const lines = strings.splitLines(italicText); parts.push(new ghostText_1.GhostTextPart(insertColumn, lines, true)); } } 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) { if (originalValue.length > 5000 || newValue.length > 5000) { // We don't want to work on strings that are too big return undefined; } function getMaxCharCode(val) { let maxCharCode = 0; for (let i = 0, len = val.length; i < len; i++) { const charCode = val.charCodeAt(i); if (charCode > maxCharCode) { maxCharCode = charCode; } } return maxCharCode; } const maxCharCode = Math.max(getMaxCharCode(originalValue), getMaxCharCode(newValue)); function getUniqueCharCode(id) { if (id < 0) { throw new Error('unexpected'); } return maxCharCode + id + 1; } function getElements(source) { let level = 0; let group = 0; const characters = new Int32Array(source.length); for (let i = 0, len = source.length; i < len; i++) { 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; } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[461/*vs/editor/contrib/inlineCompletions/browser/utils*/], __M([1/*require*/,0/*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[462/*vs/editor/contrib/linesOperations/browser/copyLinesCommand*/], __M([1/*require*/,0/*exports*/,3/*vs/editor/common/core/range*/,22/*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[463/*vs/editor/contrib/linesOperations/browser/sortLinesCommand*/], __M([1/*require*/,0/*exports*/,61/*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[260/*vs/editor/contrib/smartSelect/browser/bracketSelections*/], __M([1/*require*/,0/*exports*/,81/*vs/base/common/linkedList*/,11/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, linkedList_1, position_1, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BracketSelectionRangeProvider = void 0; class BracketSelectionRangeProvider { 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.bracketPairs.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.bracketPairs.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[464/*vs/editor/contrib/smartSelect/browser/wordSelections*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings_1, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WordSelectionRangeProvider = void 0; class WordSelectionRangeProvider { 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[124/*vs/editor/contrib/snippet/browser/snippetParser*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SnippetParser = exports.TextmateSnippet = exports.Variable = exports.FormatString = exports.Transform = exports.Choice = exports.Placeholder = exports.TransformableMarker = exports.Text = exports.Marker = exports.Scanner = void 0; class Scanner { constructor() { this.value = ''; this.pos = 0; } static 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:}, ${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:} 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///} 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:}, ${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:} 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///} 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) { // ...//} 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:+} 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:-} 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:?:} 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:} 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[465/*vs/editor/contrib/suggest/browser/completionModel*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,73/*vs/base/common/filters*/,8/*vs/base/common/strings*/]), function (require, exports, arrays_1, filters_1, strings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CompletionModel = exports.LineContext = void 0; class LineContext { constructor(leadingLineContent, characterCountDelta) { this.leadingLineContent = leadingLineContent; this.characterCountDelta = characterCountDelta; } } exports.LineContext = LineContext; /** * Sorted, filtered completion view model * */ class CompletionModel { constructor(items, column, lineContext, wordDistance, options, snippetSuggestions, 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[261/*vs/editor/contrib/suggest/browser/resizable*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,114/*vs/base/browser/ui/sash/sash*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, dom_1, sash_1, event_1, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ResizableHTMLElement = void 0; class ResizableHTMLElement { constructor() { this._onDidWillResize = new event_1.Emitter(); this.onDidWillResize = this._onDidWillResize.event; this._onDidResize = new event_1.Emitter(); this.onDidResize = this._onDidResize.event; this._sashListener = new lifecycle_1.DisposableStore(); this._size = new dom_1.Dimension(0, 0); this._minSize = new dom_1.Dimension(0, 0); this._maxSize = new dom_1.Dimension(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER); this.domNode = document.createElement('div'); this._eastSash = new sash_1.Sash(this.domNode, { getVerticalSashLeft: () => this._size.width }, { orientation: 0 /* 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[466/*vs/editor/contrib/suggest/browser/suggestCommitCharacters*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,97/*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[467/*vs/editor/contrib/suggest/browser/suggestOvertypingCapturer*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/]), function (require, exports, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OvertypingCapturer = void 0; class OvertypingCapturer { 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[468/*vs/editor/contrib/suggest/browser/wordDistance*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,3/*vs/editor/common/core/range*/,260/*vs/editor/contrib/smartSelect/browser/bracketSelections*/]), function (require, exports, arrays_1, range_1, bracketSelections_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WordDistance = void 0; class WordDistance { static create(service, editor) { return __awaiter(this, void 0, void 0, function* () { if (!editor.getOption(106 /* 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[262/*vs/editor/standalone/common/monarch/monarchCommon*/], __M([1/*require*/,0/*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[469/*vs/editor/standalone/common/monarch/monarchCompile*/], __M([1/*require*/,0/*exports*/,262/*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, '@'); const 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; const parts = state.split('.'); parts.unshift(state); if (num < parts.length) { return parts[num]; } } return null; } function createGuard(lexer, ruleName, tkey, val) { // get the scrutinee and pattern let scrut = -1; // -1: $!, 0-99: $n, 100+n: $Sn let oppat = tkey; let matches = tkey.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/); if (matches) { if (matches[3]) { // if digits scrut = parseInt(matches[3]); if (matches[2]) { scrut = scrut + 100; // if [sS] present } } oppat = matches[4]; } // get operator let op = '~'; let pat = oppat; if (!oppat || oppat.length === 0) { op = '!='; pat = ''; } else if (/^\w*$/.test(pat)) { // just a word op = '=='; } else { matches = oppat.match(/^(@|!@|~|!~|==|!=)(.*)$/); if (matches) { op = matches[1]; pat = matches[2]; } } // set the tester function let tester; // special case a regexp that matches just words if ((op === '~' || op === '!~') && /^(\w|\|)*$/.test(pat)) { const inWords = createKeywordMatcher(pat.split('|'), lexer.ignoreCase); tester = function (s) { return (op === '~' ? inWords(s) : !inWords(s)); }; } else if (op === '@' || op === '!@') { const words = lexer[pat]; if (!words) { throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' is not defined, in rule: ' + ruleName); } if (!(isArrayOf(function (elem) { return (typeof (elem) === 'string'); }, words))) { throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' must be an array of strings, in rule: ' + ruleName); } const inWords = createKeywordMatcher(words, lexer.ignoreCase); tester = function (s) { return (op === '@' ? inWords(s) : !inWords(s)); }; } else if (op === '~' || op === '!~') { if (pat.indexOf('$') < 0) { // precompile regular expression const re = compileRegExp(lexer, '^' + pat + '$'); tester = function (s) { return (op === '~' ? re.test(s) : !re.test(s)); }; } else { tester = function (s, id, matches, state) { const re = compileRegExp(lexer, '^' + monarchCommon.substituteMatches(lexer, pat, id, matches, state) + '$'); return re.test(s); }; } } else { // if (op==='==' || op==='!=') { if (pat.indexOf('$') < 0) { const patx = monarchCommon.fixCase(lexer, pat); tester = function (s) { return (op === '==' ? s === patx : s !== patx); }; } else { const patx = monarchCommon.fixCase(lexer, pat); tester = function (s, id, matches, state, eos) { const patexp = monarchCommon.substituteMatches(lexer, patx, id, matches, state); return (op === '==' ? s === patexp : s !== patexp); }; } } // return the branch object if (scrut === -1) { return { name: tkey, value: val, test: function (id, matches, state, eos) { return tester(id, id, matches, state, eos); } }; } else { return { name: tkey, value: val, test: function (id, matches, state, eos) { const scrutinee = selectScrutinee(id, matches, state, scrut); return tester(!scrutinee ? '' : scrutinee, id, matches, state, eos); } }; } } /** * Compiles an action: i.e. optimize regular expressions and case matches * and do many sanity checks. * * This is called only during compilation but if the lexer definition * contains user functions as actions (which is usually not allowed), then this * may be called during lexing. It is important therefore to compile common cases efficiently */ function compileAction(lexer, ruleName, action) { if (!action) { return { token: '' }; } else if (typeof (action) === 'string') { return action; // { token: action }; } else if (action.token || action.token === '') { if (typeof (action.token) !== 'string') { throw monarchCommon.createError(lexer, 'a \'token\' attribute must be of type string, in rule: ' + ruleName); } else { // only copy specific typed fields (only happens once during compile Lexer) const newAction = { token: action.token }; if (action.token.indexOf('$') >= 0) { newAction.tokenSubst = true; } if (typeof (action.bracket) === 'string') { if (action.bracket === '@open') { newAction.bracket = 1 /* 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)) { const results = []; for (let i = 0, len = action.length; i < len; i++) { results[i] = compileAction(lexer, ruleName, action[i]); } return { group: results }; } else if (action.cases) { // build an array of test cases const cases = []; // for each case, push a test function and result value for (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 const 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 const lexerMin = json; lexerMin.languageId = languageId; lexerMin.includeLF = lexer.includeLF; lexerMin.ignoreCase = lexer.ignoreCase; lexerMin.unicode = lexer.unicode; lexerMin.noThrow = lexer.noThrow; lexerMin.usesEmbedded = lexer.usesEmbedded; lexerMin.stateNames = json.tokenizer; lexerMin.defaultToken = lexer.defaultToken; // Compile an array of rules into newrules where RegExp objects are created. function addRules(state, newrules, rules) { for (const rule of rules) { let include = rule.include; if (include) { if (typeof (include) !== 'string') { throw monarchCommon.createError(lexer, 'an \'include\' attribute must be a string at: ' + state); } if (include[0] === '@') { include = include.substr(1); // peel off starting @ } if (!json.tokenizer[include]) { throw monarchCommon.createError(lexer, 'include target \'' + include + '\' is not defined at: ' + state); } addRules(state + '.' + include, newrules, json.tokenizer[include]); } else { const newrule = new Rule(state); // Set up new rule attributes if (Array.isArray(rule) && rule.length >= 1 && rule.length <= 3) { newrule.setRegex(lexerMin, rule[0]); if (rule.length >= 3) { if (typeof (rule[1]) === 'string') { newrule.setAction(lexerMin, { token: rule[1], next: rule[2] }); } else if (typeof (rule[1]) === 'object') { const rule1 = rule[1]; rule1.next = rule[2]; newrule.setAction(lexerMin, rule1); } else { throw monarchCommon.createError(lexer, 'a next state as the last element of a rule can only be given if the action is either an object or a string, at: ' + state); } } else { newrule.setAction(lexerMin, rule[1]); } } else { if (!rule.regex) { throw monarchCommon.createError(lexer, 'a rule must either be an array, or an object with a \'regex\' or \'include\' field at: ' + state); } if (rule.name) { if (typeof rule.name === 'string') { newrule.name = rule.name; } } if (rule.matchOnlyAtStart) { newrule.matchOnlyAtLineStart = bool(rule.matchOnlyAtLineStart, false); } newrule.setRegex(lexerMin, rule.regex); newrule.setAction(lexerMin, rule.action); } newrules.push(newrule); } } } // compile the tokenizer rules if (!json.tokenizer || typeof (json.tokenizer) !== 'object') { throw monarchCommon.createError(lexer, 'a language definition must define the \'tokenizer\' attribute as an object'); } lexer.tokenizer = []; for (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' } ]; } const 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; }); /*--------------------------------------------------------------------------------------------- * 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/common/monarch/monarchLexer*/], __M([1/*require*/,0/*exports*/,18/*vs/editor/common/languages*/,121/*vs/editor/common/languages/nullMode*/,262/*vs/editor/standalone/common/monarch/monarchCommon*/]), function (require, exports, languages, nullMode_1, monarchCommon) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MonarchTokenizer = void 0; const CACHE_STACK_DEPTH = 5; /** * Reuse the same stack elements up to a certain depth. */ class MonarchStackElementFactory { 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 EmbeddedLanguageData { constructor(languageId, state) { this.languageId = languageId; this.state = state; } equals(other) { return (this.languageId === other.languageId && this.state.equals(other.state)); } clone() { const stateClone = this.state.clone(); // save an object if (stateClone === this.state) { return this; } return new EmbeddedLanguageData(this.languageId, this.state); } } /** * Reuse the same line states up to a certain depth. */ class MonarchLineStateFactory { constructor(maxCacheDepth) { this._maxCacheDepth = maxCacheDepth; this._entries = Object.create(null); } static create(stack, embeddedLanguageData) { return this._INSTANCE.create(stack, embeddedLanguageData); } create(stack, embeddedLanguageData) { if (embeddedLanguageData !== null) { // no caching when embedding return new MonarchLineState(stack, embeddedLanguageData); } if (stack !== null && stack.depth >= this._maxCacheDepth) { // no caching above a certain depth return new MonarchLineState(stack, embeddedLanguageData); } const stackElementId = MonarchStackElement.getStackElementId(stack); let result = this._entries[stackElementId]; if (result) { return result; } result = new MonarchLineState(stack, null); this._entries[stackElementId] = result; return result; } } MonarchLineStateFactory._INSTANCE = new MonarchLineStateFactory(CACHE_STACK_DEPTH); class MonarchLineState { constructor(stack, embeddedLanguageData) { this.stack = stack; this.embeddedLanguageData = embeddedLanguageData; } clone() { const embeddedlanguageDataClone = this.embeddedLanguageData ? this.embeddedLanguageData.clone() : null; // save an object if (embeddedlanguageDataClone === this.embeddedLanguageData) { return this; } return MonarchLineStateFactory.create(this.stack, this.embeddedLanguageData); } equals(other) { if (!(other instanceof MonarchLineState)) { return false; } if (!this.stack.equals(other.stack)) { return false; } if (this.embeddedLanguageData === null && other.embeddedLanguageData === null) { return true; } if (this.embeddedLanguageData === null || other.embeddedLanguageData === null) { return false; } return this.embeddedLanguageData.equals(other.embeddedLanguageData); } } class MonarchClassicTokensCollector { constructor() { this._tokens = []; this._languageId = null; this._lastTokenType = null; this._lastTokenLanguage = null; } enterLanguage(languageId) { this._languageId = languageId; } emit(startOffset, type) { if (this._lastTokenType === type && this._lastTokenLanguage === this._languageId) { return; } this._lastTokenType = type; this._lastTokenLanguage = this._languageId; this._tokens.push(new languages.Token(startOffset, type, this._languageId)); } nestedLanguageTokenize(embeddedLanguageLine, hasEOL, embeddedLanguageData, offsetDelta) { const nestedLanguageId = embeddedLanguageData.languageId; const embeddedModeState = embeddedLanguageData.state; const nestedLanguageTokenizationSupport = languages.TokenizationRegistry.get(nestedLanguageId); if (!nestedLanguageTokenizationSupport) { this.enterLanguage(nestedLanguageId); this.emit(offsetDelta, ''); return embeddedModeState; } const nestedResult = nestedLanguageTokenizationSupport.tokenize(embeddedLanguageLine, hasEOL, embeddedModeState); if (offsetDelta !== 0) { for (const token of nestedResult.tokens) { this._tokens.push(new languages.Token(token.offset + offsetDelta, token.type, token.language)); } } else { this._tokens = this._tokens.concat(nestedResult.tokens); } this._lastTokenType = null; this._lastTokenLanguage = null; this._languageId = null; return nestedResult.endState; } finalize(endState) { return new languages.TokenizationResult(this._tokens, endState); } } class MonarchModernTokensCollector { constructor(languageService, theme) { this._languageService = languageService; this._theme = theme; this._prependTokens = null; this._tokens = []; this._currentLanguageId = 0 /* Null */; this._lastTokenMetadata = 0; } enterLanguage(languageId) { this._currentLanguageId = this._languageService.languageIdCodec.encodeLanguageId(languageId); } emit(startOffset, type) { const 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) { const aLen = (a !== null ? a.length : 0); const bLen = b.length; const cLen = (c !== null ? c.length : 0); if (aLen === 0 && bLen === 0 && cLen === 0) { return new Uint32Array(0); } if (aLen === 0 && bLen === 0) { return c; } if (bLen === 0 && cLen === 0) { return a; } const result = new Uint32Array(aLen + bLen + cLen); if (a !== null) { result.set(a); } for (let i = 0; i < bLen; i++) { result[aLen + i] = b[i]; } if (c !== null) { result.set(c, aLen + bLen); } return result; } nestedLanguageTokenize(embeddedLanguageLine, hasEOL, embeddedLanguageData, offsetDelta) { const nestedLanguageId = embeddedLanguageData.languageId; const embeddedModeState = embeddedLanguageData.state; const nestedLanguageTokenizationSupport = languages.TokenizationRegistry.get(nestedLanguageId); if (!nestedLanguageTokenizationSupport) { this.enterLanguage(nestedLanguageId); this.emit(offsetDelta, ''); return embeddedModeState; } const nestedResult = nestedLanguageTokenizationSupport.tokenizeEncoded(embeddedLanguageLine, hasEOL, embeddedModeState); if (offsetDelta !== 0) { for (let i = 0, len = nestedResult.tokens.length; i < len; i += 2) { nestedResult.tokens[i] += offsetDelta; } } this._prependTokens = MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, nestedResult.tokens); this._tokens = []; this._currentLanguageId = 0; this._lastTokenMetadata = 0; return nestedResult.endState; } finalize(endState) { return new languages.EncodedTokenizationResult(MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, null), endState); } } class MonarchTokenizer { constructor(languageService, standaloneThemeService, languageId, lexer) { this._languageService = languageService; this._standaloneThemeService = standaloneThemeService; this._languageId = languageId; this._lexer = lexer; this._embeddedLanguages = Object.create(null); this.embeddedLoaded = Promise.resolve(undefined); // Set up listening for embedded modes let emitting = false; this._tokenizationRegistryListener = languages.TokenizationRegistry.onDidChange((e) => { if (emitting) { return; } let isOneOfMyEmbeddedModes = false; for (let i = 0, len = e.changedLanguages.length; i < len; i++) { const language = e.changedLanguages[i]; if (this._embeddedLanguages[language]) { isOneOfMyEmbeddedModes = true; break; } } if (isOneOfMyEmbeddedModes) { emitting = true; languages.TokenizationRegistry.fire([this._languageId]); emitting = false; } }); } dispose() { this._tokenizationRegistryListener.dispose(); } getLoadStatus() { const promises = []; for (let nestedLanguageId in this._embeddedLanguages) { const tokenizationSupport = languages.TokenizationRegistry.get(nestedLanguageId); if (tokenizationSupport) { // The nested language is already loaded if (tokenizationSupport instanceof MonarchTokenizer) { const nestedModeStatus = tokenizationSupport.getLoadStatus(); if (nestedModeStatus.loaded === false) { promises.push(nestedModeStatus.promise); } } continue; } if (!languages.TokenizationRegistry.isResolved(nestedLanguageId)) { // The nested language is in the process of being loaded promises.push(languages.TokenizationRegistry.getOrCreate(nestedLanguageId)); } } if (promises.length === 0) { return { loaded: true }; } return { loaded: false, promise: Promise.all(promises).then(_ => undefined) }; } getInitialState() { const rootState = MonarchStackElementFactory.create(null, this._lexer.start); return MonarchLineStateFactory.create(rootState, null); } tokenize(line, hasEOL, lineState) { const tokensCollector = new MonarchClassicTokensCollector(); const endLineState = this._tokenize(line, hasEOL, lineState, tokensCollector); return tokensCollector.finalize(endLineState); } tokenizeEncoded(line, hasEOL, lineState) { const tokensCollector = new MonarchModernTokensCollector(this._languageService, this._standaloneThemeService.getColorTheme().tokenTheme); const endLineState = this._tokenize(line, hasEOL, lineState, tokensCollector); return tokensCollector.finalize(endLineState); } _tokenize(line, hasEOL, lineState, collector) { if (lineState.embeddedLanguageData) { return this._nestedTokenize(line, hasEOL, lineState, 0, collector); } else { return this._myTokenize(line, hasEOL, lineState, 0, collector); } } _findLeavingNestedLanguageOffset(line, state) { let rules = this._lexer.tokenizer[state.stack.state]; if (!rules) { rules = monarchCommon.findRules(this._lexer, state.stack.state); // do parent matching if (!rules) { throw monarchCommon.createError(this._lexer, 'tokenizer state is not defined: ' + state.stack.state); } } let popOffset = -1; let hasEmbeddedPopRule = false; for (const rule of rules) { if (!monarchCommon.isIAction(rule.action) || rule.action.nextEmbedded !== '@pop') { continue; } hasEmbeddedPopRule = true; let regex = rule.regex; const regexSource = rule.regex.source; if (regexSource.substr(0, 4) === '^(?:' && regexSource.substr(regexSource.length - 1, 1) === ')') { const flags = (regex.ignoreCase ? 'i' : '') + (regex.unicode ? 'u' : ''); regex = new RegExp(regexSource.substr(4, regexSource.length - 5), flags); } const result = line.search(regex); if (result === -1 || (result !== 0 && rule.matchOnlyAtLineStart)) { continue; } if (popOffset === -1 || result < popOffset) { popOffset = result; } } if (!hasEmbeddedPopRule) { throw monarchCommon.createError(this._lexer, 'no rule containing nextEmbedded: "@pop" in tokenizer embedded state: ' + state.stack.state); } return popOffset; } _nestedTokenize(line, hasEOL, lineState, offsetDelta, tokensCollector) { const popOffset = this._findLeavingNestedLanguageOffset(line, lineState); if (popOffset === -1) { // tokenization will not leave nested language const nestedEndState = tokensCollector.nestedLanguageTokenize(line, hasEOL, lineState.embeddedLanguageData, offsetDelta); return MonarchLineStateFactory.create(lineState.stack, new EmbeddedLanguageData(lineState.embeddedLanguageData.languageId, nestedEndState)); } const nestedLanguageLine = line.substring(0, popOffset); if (nestedLanguageLine.length > 0) { // tokenize with the nested language tokensCollector.nestedLanguageTokenize(nestedLanguageLine, false, lineState.embeddedLanguageData, offsetDelta); } const restOfTheLine = line.substring(popOffset); return this._myTokenize(restOfTheLine, hasEOL, lineState, offsetDelta + popOffset, tokensCollector); } _safeRuleName(rule) { if (rule) { return rule.name; } return '(unknown)'; } _myTokenize(lineWithoutLF, hasEOL, lineState, offsetDelta, tokensCollector) { tokensCollector.enterLanguage(this._languageId); const lineWithoutLFLength = lineWithoutLF.length; const line = (hasEOL && this._lexer.includeLF ? lineWithoutLF + '\n' : lineWithoutLF); const lineLength = line.length; let embeddedLanguageData = lineState.embeddedLanguageData; let stack = lineState.stack; let pos = 0; let groupMatching = null; // See https://github.com/microsoft/monaco-editor/issues/1235 // Evaluate rules at least once for an empty line let forceEvaluation = true; while (forceEvaluation || pos < lineLength) { const pos0 = pos; const stackLen0 = stack.depth; const groupLen0 = groupMatching ? groupMatching.groups.length : 0; const state = stack.state; let matches = null; let matched = null; let action = null; let rule = null; let enteringEmbeddedLanguage = null; // check if we need to process group matches first if (groupMatching) { matches = groupMatching.matches; const groupEntry = groupMatching.groups.shift(); matched = groupEntry.matched; action = groupEntry.action; rule = groupMatching.rule; // cleanup if necessary if (groupMatching.groups.length === 0) { groupMatching = null; } } else { // otherwise we match on the token stream if (!forceEvaluation && pos >= lineLength) { // nothing to do break; } forceEvaluation = false; // get the rules for this state let rules = this._lexer.tokenizer[state]; if (!rules) { rules = monarchCommon.findRules(this._lexer, state); // do parent matching if (!rules) { throw monarchCommon.createError(this._lexer, 'tokenizer state is not defined: ' + state); } } // try each rule until we match 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 language? if (action.nextEmbedded) { if (action.nextEmbedded === '@pop') { if (!embeddedLanguageData) { throw monarchCommon.createError(this._lexer, 'cannot pop embedded language if not inside one'); } embeddedLanguageData = null; } else if (embeddedLanguageData) { throw monarchCommon.createError(this._lexer, 'cannot enter embedded language from within an embedded language'); } else { enteringEmbeddedLanguage = monarchCommon.substituteMatches(this._lexer, action.nextEmbedded, matched, matches, state); } } // state transformations if (action.goBack) { // back up the stream.. pos = Math.max(0, pos - action.goBack); } if (action.switchTo && typeof action.switchTo === 'string') { let nextState = monarchCommon.substituteMatches(this._lexer, action.switchTo, matched, matches, state); // switch state without a push... if (nextState[0] === '@') { nextState = nextState.substr(1); // peel off starting '@' } if (!monarchCommon.findRules(this._lexer, nextState)) { throw monarchCommon.createError(this._lexer, 'trying to switch to a state \'' + nextState + '\' that is undefined in rule: ' + this._safeRuleName(rule)); } else { stack = stack.switchTo(nextState); } } else if (action.transform && typeof action.transform === 'function') { throw monarchCommon.createError(this._lexer, 'action.transform not supported'); } else if (action.next) { if (action.next === '@push') { if (stack.depth >= this._lexer.maxStack) { throw monarchCommon.createError(this._lexer, 'maximum tokenizer stack size reached: [' + stack.state + ',' + stack.parent.state + ',...]'); } else { stack = stack.push(state); } } else if (action.next === '@pop') { if (stack.depth <= 1) { throw monarchCommon.createError(this._lexer, 'trying to pop an empty stack in rule: ' + this._safeRuleName(rule)); } else { stack = stack.pop(); } } else if (action.next === '@popall') { stack = stack.popall(); } else { let nextState = monarchCommon.substituteMatches(this._lexer, action.next, matched, matches, state); if (nextState[0] === '@') { nextState = nextState.substr(1); // peel off starting '@' } if (!monarchCommon.findRules(this._lexer, nextState)) { throw monarchCommon.createError(this._lexer, 'trying to set a next state \'' + nextState + '\' that is undefined in rule: ' + this._safeRuleName(rule)); } else { stack = stack.push(nextState); } } } if (action.log && typeof (action.log) === 'string') { monarchCommon.log(this._lexer, this._lexer.languageId + ': ' + monarchCommon.substituteMatches(this._lexer, action.log, matched, matches, state)); } } // check result if (result === null) { throw monarchCommon.createError(this._lexer, 'lexer rule has no well-defined action in rule: ' + this._safeRuleName(rule)); } const computeNewStateForEmbeddedLanguage = (enteringEmbeddedLanguage) => { // support language names, mime types, and language ids const languageId = (this._languageService.getLanguageIdByLanguageName(enteringEmbeddedLanguage) || this._languageService.getLanguageIdByMimeType(enteringEmbeddedLanguage) || enteringEmbeddedLanguage); const embeddedLanguageData = this._getNestedEmbeddedLanguageData(languageId); if (pos < lineLength) { // there is content from the embedded language on this line const restOfLine = lineWithoutLF.substr(pos); return this._nestedTokenize(restOfLine, hasEOL, MonarchLineStateFactory.create(stack, embeddedLanguageData), offsetDelta + pos, tokensCollector); } else { return MonarchLineStateFactory.create(stack, embeddedLanguageData); } }; // is the result a group match? if (Array.isArray(result)) { if (groupMatching && groupMatching.groups.length > 0) { throw monarchCommon.createError(this._lexer, 'groups cannot be nested: ' + this._safeRuleName(rule)); } if (matches.length !== result.length + 1) { throw monarchCommon.createError(this._lexer, 'matched number of groups does not match the number of actions in rule: ' + this._safeRuleName(rule)); } let totalLen = 0; for (let i = 1; i < matches.length; i++) { totalLen += matches[i].length; } if (totalLen !== matched.length) { throw monarchCommon.createError(this._lexer, 'with groups, all characters should be matched in consecutive groups in rule: ' + this._safeRuleName(rule)); } groupMatching = { rule: rule, matches: matches, groups: [] }; for (let i = 0; i < result.length; i++) { groupMatching.groups[i] = { action: result[i], matched: matches[i + 1] }; } pos -= matched.length; // call recursively to initiate first result match continue; } else { // regular result // check for '@rematch' if (result === '@rematch') { pos -= matched.length; matched = ''; // better set the next state too.. matches = null; result = ''; // Even though `@rematch` was specified, if `nextEmbedded` also specified, // a state transition should occur. if (enteringEmbeddedLanguage !== null) { return computeNewStateForEmbeddedLanguage(enteringEmbeddedLanguage); } } // check progress if (matched.length === 0) { if (lineLength === 0 || stackLen0 !== stack.depth || state !== stack.state || (!groupMatching ? 0 : groupMatching.groups.length) !== groupLen0) { continue; } else { throw monarchCommon.createError(this._lexer, 'no progress in tokenizer in rule: ' + this._safeRuleName(rule)); } } // return the result (and check for brace matching) // todo: for efficiency we could pre-sanitize tokenPostfix and substitutions let tokenType = null; if (monarchCommon.isString(result) && result.indexOf('@brackets') === 0) { const rest = result.substr('@brackets'.length); const bracket = findBracket(this._lexer, matched); if (!bracket) { throw monarchCommon.createError(this._lexer, '@brackets token returned but no bracket defined as: ' + matched); } tokenType = monarchCommon.sanitize(bracket.token + rest); } else { const token = (result === '' ? '' : result + this._lexer.tokenPostfix); tokenType = monarchCommon.sanitize(token); } if (pos0 < lineWithoutLFLength) { tokensCollector.emit(pos0 + offsetDelta, tokenType); } } if (enteringEmbeddedLanguage !== null) { return computeNewStateForEmbeddedLanguage(enteringEmbeddedLanguage); } } return MonarchLineStateFactory.create(stack, embeddedLanguageData); } _getNestedEmbeddedLanguageData(languageId) { if (!this._languageService.isRegisteredLanguageId(languageId)) { return new EmbeddedLanguageData(languageId, nullMode_1.NullState); } if (languageId !== this._languageId) { // Fire language loading event languages.TokenizationRegistry.getOrCreate(languageId); this._embeddedLanguages[languageId] = true; } const tokenizationSupport = languages.TokenizationRegistry.get(languageId); if (tokenizationSupport) { return new EmbeddedLanguageData(languageId, tokenizationSupport.getInitialState()); } return new EmbeddedLanguageData(languageId, nullMode_1.NullState); } } 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); const 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; } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[470/*vs/editor/standalone/browser/colorizer*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,75/*vs/editor/common/tokens/lineTokens*/,18/*vs/editor/common/languages*/,122/*vs/editor/common/viewLayout/viewLineRenderer*/,69/*vs/editor/common/viewModel/viewModel*/,263/*vs/editor/standalone/common/monarch/monarchLexer*/]), function (require, exports, strings, lineTokens_1, languages_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, languageService, domNode, options) { options = options || {}; const theme = options.theme || 'vs'; const mimeType = options.mimeType || domNode.getAttribute('lang') || domNode.getAttribute('data-lang'); if (!mimeType) { console.error('Mode not detected'); return Promise.resolve(); } const languageId = languageService.getLanguageIdByMimeType(mimeType) || mimeType; themeService.setTheme(theme); const text = domNode.firstChild ? domNode.firstChild.nodeValue : ''; domNode.className += ' ' + theme; const render = (str) => { 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(languageService, text || '', languageId, options).then(render, (err) => console.error(err)); } static colorize(languageService, text, languageId, options) { return __awaiter(this, void 0, void 0, function* () { const languageIdCodec = languageService.languageIdCodec; let tabSize = 4; if (options && typeof options.tabSize === 'number') { tabSize = options.tabSize; } if (strings.startsWithUTF8BOM(text)) { text = text.substr(1); } const lines = strings.splitLines(text); if (!languageService.isRegisteredLanguageId(languageId)) { return _fakeColorize(lines, tabSize, languageIdCodec); } const tokenizationSupport = yield languages_1.TokenizationRegistry.getOrCreate(languageId); if (tokenizationSupport) { return _colorize(lines, tabSize, tokenizationSupport, languageIdCodec); } return _fakeColorize(lines, tabSize, languageIdCodec); }); } static colorizeLine(line, mightContainNonBasicASCII, mightContainRTL, tokens, tabSize = 4) { const isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, mightContainNonBasicASCII); const containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, mightContainRTL); const renderResult = (0, viewLineRenderer_1.renderViewLine2)(new viewLineRenderer_1.RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, tokens, [], tabSize, 0, 0, 0, 0, -1, 'none', false, false, null)); return renderResult.html; } static colorizeModelLine(model, lineNumber, tabSize = 4) { const content = model.getLineContent(lineNumber); model.forceTokenization(lineNumber); const tokens = model.getLineTokens(lineNumber); const inflatedTokens = tokens.inflate(); return this.colorizeLine(content, model.mightContainNonBasicASCII(), model.mightContainRTL(), inflatedTokens, tabSize); } } exports.Colorizer = Colorizer; function _colorize(lines, tabSize, tokenizationSupport, languageIdCodec) { return new Promise((c, e) => { const execute = () => { const result = _actualColorize(lines, tabSize, tokenizationSupport, languageIdCodec); if (tokenizationSupport instanceof monarchLexer_1.MonarchTokenizer) { const status = tokenizationSupport.getLoadStatus(); if (status.loaded === false) { status.promise.then(execute, e); return; } } c(result); }; execute(); }); } function _fakeColorize(lines, tabSize, languageIdCodec) { let html = []; const defaultMetadata = ((0 /* None */ << 10 /* 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++) { const line = lines[i]; tokens[0] = line.length; const lineTokens = new lineTokens_1.LineTokens(tokens, line, languageIdCodec); const isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true); const containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true); const renderResult = (0, viewLineRenderer_1.renderViewLine2)(new viewLineRenderer_1.RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens, [], tabSize, 0, 0, 0, 0, -1, 'none', false, false, null)); html = html.concat(renderResult.html); html.push('
    '); } return html.join(''); } function _actualColorize(lines, tabSize, tokenizationSupport, languageIdCodec) { let html = []; let state = tokenizationSupport.getInitialState(); for (let i = 0, length = lines.length; i < length; i++) { const line = lines[i]; const tokenizeResult = tokenizationSupport.tokenizeEncoded(line, true, state); lineTokens_1.LineTokens.convertToEndOffset(tokenizeResult.tokens, line.length); const lineTokens = new lineTokens_1.LineTokens(tokenizeResult.tokens, line, languageIdCodec); const isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true); const containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true); const renderResult = (0, viewLineRenderer_1.renderViewLine2)(new viewLineRenderer_1.RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens.inflate(), [], tabSize, 0, 0, 0, 0, -1, 'none', false, false, null)); html = html.concat(renderResult.html); html.push('
    '); state = tokenizeResult.endState; } return html.join(''); } }); define(__m[471/*vs/nls!vs/base/browser/ui/actionbar/actionViewItems*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/actionbar/actionViewItems", data); }); define(__m[472/*vs/nls!vs/base/browser/ui/findinput/findInput*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/findinput/findInput", data); }); define(__m[473/*vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes*/], __M([5/*vs/nls*/,6/*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[264/*vs/base/browser/ui/findinput/findInputCheckboxes*/], __M([1/*require*/,0/*exports*/,172/*vs/base/browser/ui/checkbox/checkbox*/,27/*vs/base/common/codicons*/,473/*vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes*/]), function (require, exports, checkbox_1, codicons_1, nls) { "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[474/*vs/nls!vs/base/browser/ui/findinput/replaceInput*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/findinput/replaceInput", data); }); define(__m[475/*vs/nls!vs/base/browser/ui/iconLabel/iconLabelHover*/], __M([5/*vs/nls*/,6/*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[476/*vs/base/browser/ui/iconLabel/iconLabelHover*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,10/*vs/base/common/async*/,21/*vs/base/common/cancellation*/,66/*vs/base/common/htmlContent*/,95/*vs/base/common/iconLabels*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/,475/*vs/nls!vs/base/browser/ui/iconLabel/iconLabelHover*/]), function (require, exports, dom, async_1, cancellation_1, htmlContent_1, iconLabels_1, lifecycle_1, types_1, nls_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)) { // Icons don't render in the native hover so we strip them out htmlElement.title = (0, iconLabels_1.stripIcons)(tooltip); } else if (tooltip === null || tooltip === void 0 ? void 0 : tooltip.markdownNotSupportedFallback) { htmlElement.title = tooltip.markdownNotSupportedFallback; } else { htmlElement.removeAttribute('title'); } } exports.setupNativeHover = setupNativeHover; class UpdatableHoverWidget { constructor(hoverDelegate, target, fadeInAnimation) { this.hoverDelegate = hoverDelegate; this.target = target; this.fadeInAnimation = fadeInAnimation; } update(markdownTooltip, focus) { var _a; return __awaiter(this, void 0, void 0, function* () { if (this._cancellationTokenSource) { // there's an computation ongoing, cancel it this._cancellationTokenSource.dispose(true); this._cancellationTokenSource = undefined; } if (this.isDisposed) { return; } let resolvedContent; if (markdownTooltip === undefined || (0, types_1.isString)(markdownTooltip) || markdownTooltip instanceof HTMLElement) { resolvedContent = markdownTooltip; } else if (!(0, types_1.isFunction)(markdownTooltip.markdown)) { resolvedContent = (_a = markdownTooltip.markdown) !== null && _a !== void 0 ? _a : markdownTooltip.markdownNotSupportedFallback; } else { // compute the content, potentially long-running // show 'Loading' if no hover is up yet if (!this._hoverWidget) { this.show((0, nls_1.localize)(0, null), focus); } // compute the content this._cancellationTokenSource = new cancellation_1.CancellationTokenSource(); const token = this._cancellationTokenSource.token; resolvedContent = yield markdownTooltip.markdown(token); if (this.isDisposed || token.isCancellationRequested) { // either the widget has been closed in the meantime // or there has been a new call to `update` return; } } this.show(resolvedContent, focus); }); } show(content, focus) { const oldHoverWidget = this._hoverWidget; if (this.hasContent(content)) { const hoverOptions = { content, target: this.target, showPointer: this.hoverDelegate.placement === 'element', hoverPosition: 2 /* BELOW */, skipFadeInAnimation: !this.fadeInAnimation || !!oldHoverWidget // do not fade in if the hover is already showing }; this._hoverWidget = this.hoverDelegate.showHover(hoverOptions, focus); } oldHoverWidget === null || oldHoverWidget === void 0 ? void 0 : oldHoverWidget.dispose(); } hasContent(content) { if (!content) { return false; } if ((0, htmlContent_1.isMarkdownString)(content)) { return !!content.value; } return true; } get isDisposed() { var _a; return (_a = this._hoverWidget) === null || _a === void 0 ? void 0 : _a.isDisposed; } dispose() { var _a, _b; (_a = this._hoverWidget) === null || _a === void 0 ? void 0 : _a.dispose(); (_b = this._cancellationTokenSource) === null || _b === void 0 ? void 0 : _b.dispose(true); this._cancellationTokenSource = undefined; } } function setupCustomHover(hoverDelegate, htmlElement, markdownTooltip) { let hoverPreparation; let hoverWidget; const hideHover = (disposeWidget, disposePreparation) => { var _a; if (disposeWidget) { hoverWidget === null || hoverWidget === void 0 ? void 0 : hoverWidget.dispose(); hoverWidget = undefined; } if (disposePreparation) { hoverPreparation === null || hoverPreparation === void 0 ? void 0 : hoverPreparation.dispose(); hoverPreparation = undefined; } (_a = hoverDelegate.onDidHideHover) === null || _a === void 0 ? void 0 : _a.call(hoverDelegate); }; const triggerShowHover = (delay, focus, target) => { return new async_1.TimeoutTimer(() => __awaiter(this, void 0, void 0, function* () { if (!hoverWidget || hoverWidget.isDisposed) { hoverWidget = new UpdatableHoverWidget(hoverDelegate, target || htmlElement, delay > 0); yield hoverWidget.update(markdownTooltip, focus); } }), delay); }; const onMouseOver = () => { if (hoverPreparation) { return; } const toDispose = new lifecycle_1.DisposableStore(); const onMouseLeave = (e) => hideHover(false, e.fromElement === htmlElement); toDispose.add(dom.addDisposableListener(htmlElement, dom.EventType.MOUSE_LEAVE, onMouseLeave, true)); const onMouseDown = () => hideHover(true, true); toDispose.add(dom.addDisposableListener(htmlElement, dom.EventType.MOUSE_DOWN, onMouseDown, true)); const target = { targetElements: [htmlElement], dispose: () => { } }; if (hoverDelegate.placement === undefined || hoverDelegate.placement === 'mouse') { // track the mouse position const onMouseMove = (e) => target.x = e.x + 10; toDispose.add(dom.addDisposableListener(htmlElement, dom.EventType.MOUSE_MOVE, onMouseMove, true)); } toDispose.add(triggerShowHover(hoverDelegate.delay, false, target)); hoverPreparation = toDispose; }; const mouseOverDomEmitter = dom.addDisposableListener(htmlElement, dom.EventType.MOUSE_OVER, onMouseOver, true); const hover = { show: focus => { hideHover(false, true); // terminate a ongoing mouse over preparation triggerShowHover(0, focus); // show hover immediately }, hide: () => { hideHover(true, true); }, update: (newTooltip) => __awaiter(this, void 0, void 0, function* () { markdownTooltip = newTooltip; yield (hoverWidget === null || hoverWidget === void 0 ? void 0 : hoverWidget.update(markdownTooltip)); }), dispose: () => { mouseOverDomEmitter.dispose(); hideHover(true, true); } }; return hover; } exports.setupCustomHover = setupCustomHover; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[190/*vs/base/browser/ui/iconLabel/iconLabel*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,217/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,476/*vs/base/browser/ui/iconLabel/iconLabelHover*/,2/*vs/base/common/lifecycle*/,39/*vs/base/common/objects*/,136/*vs/base/common/range*/,337/*vs/css!vs/base/browser/ui/iconLabel/iconlabel*/]), function (require, exports, dom, highlightedLabel_1, iconLabelHover_1, lifecycle_1, objects_1, range_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')), { supportIcons: !!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; } get element() { return this.domNode.element; } 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((options === null || options === void 0 ? void 0 : options.descriptionTitle) ? this.labelContainer : this.element, 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 })), { supportIcons: 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), { supportIcons: 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[477/*vs/nls!vs/base/browser/ui/inputbox/inputBox*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/inputbox/inputBox", data); }); define(__m[478/*vs/nls!vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/keybindingLabel/keybindingLabel", data); }); define(__m[479/*vs/nls!vs/base/browser/ui/tree/abstractTree*/], __M([5/*vs/nls*/,6/*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[191/*vs/base/browser/ui/tree/abstractTree*/], __M([1/*require*/,0/*exports*/,164/*vs/base/browser/dnd*/,7/*vs/base/browser/dom*/,89/*vs/base/browser/event*/,46/*vs/base/browser/keyboardEvent*/,173/*vs/base/browser/ui/list/listView*/,115/*vs/base/browser/ui/list/listWidget*/,167/*vs/base/browser/ui/tree/indexTreeModel*/,109/*vs/base/browser/ui/tree/tree*/,19/*vs/base/common/arrays*/,10/*vs/base/common/async*/,27/*vs/base/common/codicons*/,214/*vs/base/common/collections*/,4/*vs/base/common/event*/,73/*vs/base/common/filters*/,2/*vs/base/common/lifecycle*/,111/*vs/base/common/numbers*/,17/*vs/base/common/platform*/,479/*vs/nls!vs/base/browser/ui/tree/abstractTree*/,349/*vs/css!vs/base/browser/ui/tree/media/tree*/]), function (require, exports, dnd_1, dom_1, event_1, keyboardEvent_1, listView_1, listWidget_1, indexTreeModel_1, tree_1, arrays_1, async_1, codicons_1, collections_1, event_2, filters_1, lifecycle_1, numbers_1, platform_1, nls_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_2.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_2.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(...codicons_1.Codicon.treeItemExpanded.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(...codicons_1.Codicon.treeItemExpanded.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_2.Emitter(); this.positionClassName = 'ne'; this.automaticKeyboardNavigation = true; this.triggered = false; this._onDidChangePattern = new event_2.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' + codicons_1.Codicon.treeFilterClear.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_1.DomEmitter(this.view.getHTMLElement(), 'keydown')); const onKeyDown = event_2.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_1.DomEmitter(this.clearDomNode, 'click')); event_2.Event.chain(event_2.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(...codicons_1.Codicon.treeFilterOnTypeOff.classNamesArray); this.filterOnTypeDomNode.classList.add(...codicons_1.Codicon.treeFilterOnTypeOn.classNamesArray); this.filterOnTypeDomNode.title = (0, nls_1.localize)(1, null); } else { this.filterOnTypeDomNode.classList.remove(...codicons_1.Codicon.treeFilterOnTypeOn.classNamesArray); this.filterOnTypeDomNode.classList.add(...codicons_1.Codicon.treeFilterOnTypeOff.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_2.Emitter(); this.onDidChange = this._onDidChange.event; } get nodeSet() { if (!this._nodeSet) { this._nodeSet = this.createNodeSet(); } return this._nodeSet; } set(nodes, browserEvent) { if (!(browserEvent === null || browserEvent === void 0 ? void 0 : browserEvent.__forceEvent) && (0, arrays_1.equals)(this.nodes, nodes)) { return; } this._set(nodes, false, browserEvent); } _set(nodes, silent, browserEvent) { this.nodes = [...nodes]; this.elements = undefined; this._nodeSet = undefined; if (!silent) { const that = this; this._onDidChange.fire({ get elements() { return that.get(); }, browserEvent }); } } get() { if (!this.elements) { this.elements = this.nodes.map(node => node.element); } return [...this.elements]; } getNodes() { return this.nodes; } has(node) { return this.nodeSet.has(node); } onDidModelSplice({ insertedNodes, deletedNodes }) { if (!this.identityProvider) { const set = this.createNodeSet(); const visit = (node) => set.delete(node); deletedNodes.forEach(node => dfs(node, visit)); this.set([...set.values()]); return; } const deletedNodesIdSet = new Set(); const deletedNodesVisitor = (node) => deletedNodesIdSet.add(this.identityProvider.getId(node.element).toString()); deletedNodes.forEach(node => dfs(node, deletedNodesVisitor)); const insertedNodesMap = new Map(); const insertedNodesVisitor = (node) => insertedNodesMap.set(this.identityProvider.getId(node.element).toString(), node); insertedNodes.forEach(node => dfs(node, insertedNodesVisitor)); const nodes = []; for (const node of this.nodes) { const id = this.identityProvider.getId(node.element).toString(); const wasDeleted = deletedNodesIdSet.has(id); if (!wasDeleted) { nodes.push(node); } else { const insertedNode = insertedNodesMap.get(id); if (insertedNode) { 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.distinct)([...super.getFocus(), ...additionalFocus])); } if (additionalSelection.length > 0) { super.setSelection((0, arrays_1.distinct)([...super.getSelection(), ...additionalSelection])); } if (typeof anchor === 'number') { super.setAnchor(anchor); } } setFocus(indexes, browserEvent, fromAPI = false) { super.setFocus(indexes, browserEvent); if (!fromAPI) { this.focusTrait.set(indexes.map(i => this.element(i)), browserEvent); } } setSelection(indexes, browserEvent, fromAPI = false) { super.setSelection(indexes, browserEvent); if (!fromAPI) { this.selectionTrait.set(indexes.map(i => this.element(i)), browserEvent); } } setAnchor(index, fromAPI = false) { super.setAnchor(index); if (!fromAPI) { if (typeof index === 'undefined') { this.anchorTrait.set([]); } else { this.anchorTrait.set([this.element(index)]); } } } } class AbstractTree { constructor(_user, container, delegate, renderers, _options = {}) { this._user = _user; this._options = _options; this.eventBufferer = new event_2.EventBufferer(); this.disposables = new lifecycle_1.DisposableStore(); this._onWillRefilter = new event_2.Emitter(); this.onWillRefilter = this._onWillRefilter.event; this._onDidUpdateOptions = new event_2.Emitter(); const treeDelegate = new ComposedTreeDelegate(delegate); const onDidChangeCollapseStateRelay = new event_2.Relay(); const onDidChangeActiveNodes = new event_2.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_2.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_2.Event.chain(event_2.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_2.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_2.Event.map(this.view.onMouseDblClick, asTreeMouseEvent); } get onPointer() { return event_2.Event.map(this.view.onPointer, asTreeMouseEvent); } get onDidFocus() { return this.view.onDidFocus; } get onDidChangeModel() { return event_2.Event.signal(this.model.onDidSplice); } 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); } // Tree navigation getParentElement(location) { const parentRef = this.model.getParentNodeLocation(location); const parentNode = this.model.getNode(parentRef); return parentNode.element; } getFirstElementChild(location) { return this.model.getFirstElementChild(location); } // Tree getNode(location) { return this.model.getNode(location); } 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[480/*vs/base/browser/ui/tree/dataTree*/], __M([1/*require*/,0/*exports*/,191/*vs/base/browser/ui/tree/abstractTree*/,168/*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[265/*vs/base/browser/ui/tree/objectTree*/], __M([1/*require*/,0/*exports*/,191/*vs/base/browser/ui/tree/abstractTree*/,318/*vs/base/browser/ui/tree/compressedObjectTreeModel*/,168/*vs/base/browser/ui/tree/objectTreeModel*/,93/*vs/base/common/decorators*/,54/*vs/base/common/iterator*/]), function (require, exports, abstractTree_1, compressedObjectTreeModel_1, objectTreeModel_1, decorators_1, iterator_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CompressibleObjectTree = exports.ObjectTree = void 0; class ObjectTree extends abstractTree_1.AbstractTree { constructor(user, container, delegate, renderers, options = {}) { super(user, container, delegate, renderers, options); this.user = user; } 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[481/*vs/base/browser/ui/tree/asyncDataTree*/], __M([1/*require*/,0/*exports*/,173/*vs/base/browser/ui/list/listView*/,191/*vs/base/browser/ui/tree/abstractTree*/,167/*vs/base/browser/ui/tree/indexTreeModel*/,265/*vs/base/browser/ui/tree/objectTree*/,109/*vs/base/browser/ui/tree/tree*/,10/*vs/base/common/async*/,27/*vs/base/common/codicons*/,13/*vs/base/common/errors*/,4/*vs/base/common/event*/,54/*vs/base/common/iterator*/,2/*vs/base/common/lifecycle*/]), function (require, exports, listView_1, abstractTree_1, indexTreeModel_1, objectTree_1, tree_1, async_1, codicons_1, errors_1, event_1, iterator_1, lifecycle_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(...codicons_1.Codicon.treeItemLoading.classNamesArray); return true; } else { twistieElement.classList.remove(...codicons_1.Codicon.treeItemLoading.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 onDidChangeModel() { return this.tree.onDidChangeModel; } get onDidChangeCollapseState() { return this.tree.onDidChangeCollapseState; } 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); } // Tree getNode(element = this.root.element) { const dataNode = this.getDataNode(element); const node = this.tree.getNode(dataNode === this.root ? null : dataNode); return this.nodeMapper.map(node); } collapse(element, recursive = false) { const node = this.getDataNode(element); return this.tree.collapse(node === this.root ? null : node, recursive); } 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); } // Tree navigation getParentElement(element) { const node = this.tree.getParentElement(this.getDataNode(element)); return (node && node.element); } getFirstElementChild(element = this.root.element) { const dataNode = this.getDataNode(element); const node = this.tree.getFirstElementChild(dataNode === this.root ? null : dataNode); return (node && node.element); } // Implementation getDataNode(element) { const node = this.nodes.get((element === this.root.element ? null : element)); if (!node) { throw new tree_1.TreeError(this.user, `Data tree node not found: ${element}`); } return node; } 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.isCancellationError)(err)) { return []; } throw err; } finally { if (node.slow) { node.slow = false; this._onDidChangeNodeSlowState.fire(node); } } }); } doGetChildren(node) { let result = this.refreshPromises.get(node); if (result) { return result; } 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(...codicons_1.Codicon.treeItemLoading.classNamesArray); return true; } else { twistieElement.classList.remove(...codicons_1.Codicon.treeItemLoading.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[482/*vs/nls!vs/base/common/actions*/], __M([5/*vs/nls*/,6/*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[44/*vs/base/common/actions*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,482/*vs/nls!vs/base/common/actions*/]), function (require, exports, event_1, lifecycle_1, nls) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EmptySubmenuAction = exports.SubmenuAction = exports.Separator = exports.ActionRunner = exports.Action = void 0; class Action extends lifecycle_1.Disposable { constructor(id, label = '', cssClass = '', enabled = true, actionCallback) { super(); this._onDidChange = this._register(new event_1.Emitter()); this.onDidChange = this._onDidChange.event; this._enabled = true; this._id = id; this._label = label; this._cssClass = cssClass; this._enabled = enabled; this._actionCallback = actionCallback; } get id() { return this._id; } get label() { return this._label; } set label(value) { this._setLabel(value); } _setLabel(value) { if (this._label !== value) { this._label = value; this._onDidChange.fire({ label: value }); } } get tooltip() { return this._tooltip || ''; } set tooltip(value) { this._setTooltip(value); } _setTooltip(value) { if (this._tooltip !== value) { this._tooltip = value; this._onDidChange.fire({ tooltip: value }); } } get class() { return this._cssClass; } set class(value) { this._setClass(value); } _setClass(value) { if (this._cssClass !== value) { this._cssClass = value; this._onDidChange.fire({ class: value }); } } get enabled() { return this._enabled; } set enabled(value) { this._setEnabled(value); } _setEnabled(value) { if (this._enabled !== value) { this._enabled = value; this._onDidChange.fire({ enabled: value }); } } get checked() { return this._checked; } set checked(value) { this._setChecked(value); } _setChecked(value) { if (this._checked !== value) { this._checked = value; this._onDidChange.fire({ checked: value }); } } 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 = undefined; 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[125/*vs/base/browser/ui/actionbar/actionViewItems*/], __M([1/*require*/,0/*exports*/,34/*vs/base/browser/browser*/,164/*vs/base/browser/dnd*/,7/*vs/base/browser/dom*/,57/*vs/base/browser/touch*/,44/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,20/*vs/base/common/types*/,471/*vs/nls!vs/base/browser/ui/actionbar/actionViewItems*/,221/*vs/css!vs/base/browser/ui/actionbar/actionbar*/]), function (require, exports, browser_1, dnd_1, dom_1, touch_1, actions_1, lifecycle_1, platform, types, nls) { "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)) { 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([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,46/*vs/base/browser/keyboardEvent*/,125/*vs/base/browser/ui/actionbar/actionViewItems*/,44/*vs/base/common/actions*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/,221/*vs/css!vs/base/browser/ui/actionbar/actionbar*/]), function (require, exports, DOM, keyboardEvent_1, actionViewItems_1, actions_1, event_1, lifecycle_1, types) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ActionBar = void 0; class ActionBar extends lifecycle_1.Disposable { constructor(container, options = {}) { 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.previouslyFocusedItem = 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); } // Some action bars should not be focusable at times // When an action bar is not focusable make sure to make all the elements inside it not focusable // When an action bar is focusable again, make sure the first item can be focused setFocusable(focusable) { this.focusable = focusable; if (this.focusable) { const firstEnabled = this.viewItems.find(vi => vi instanceof actionViewItems_1.BaseActionViewItem && vi.isEnabled()); if (firstEnabled instanceof actionViewItems_1.BaseActionViewItem) { firstEnabled.setFocusable(true); } } else { this.viewItems.forEach(vi => { if (vi instanceof actionViewItems_1.BaseActionViewItem) { vi.setFocusable(false); } }); } } isTriggerKeyEvent(event) { let ret = false; this._triggerKeys.keys.forEach(keyCode => { ret = ret || event.equals(keyCode); }); return ret; } updateFocusedItem() { for (let i = 0; i < this.actionsList.children.length; i++) { const elem = this.actionsList.children[i]; if (DOM.isAncestor(DOM.getActiveElement(), elem)) { this.focusedItem = i; 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(undefined, undefined, true); } else { if (index !== undefined) { this.focusedItem = index; } this.updateFocus(undefined, undefined, true); } } focusFirst() { this.focusedItem = this.length() - 1; return this.focusNext(true); } focusLast() { this.focusedItem = 0; return this.focusPrevious(true); } focusNext(forceLoop) { if (typeof this.focusedItem === 'undefined') { this.focusedItem = this.viewItems.length - 1; } else if (this.viewItems.length <= 1) { return false; } const startIndex = this.focusedItem; let item; do { if (!forceLoop && this.options.preventLoopNavigation && this.focusedItem + 1 >= this.viewItems.length) { this.focusedItem = startIndex; return false; } this.focusedItem = (this.focusedItem + 1) % this.viewItems.length; item = this.viewItems[this.focusedItem]; } while (this.focusedItem !== startIndex && this.options.focusOnlyEnabledItems && !item.isEnabled()); this.updateFocus(); return true; } focusPrevious(forceLoop) { if (typeof this.focusedItem === 'undefined') { this.focusedItem = 0; } else if (this.viewItems.length <= 1) { return false; } const startIndex = this.focusedItem; let item; do { this.focusedItem = this.focusedItem - 1; if (this.focusedItem < 0) { if (!forceLoop && this.options.preventLoopNavigation) { this.focusedItem = startIndex; return false; } this.focusedItem = this.viewItems.length - 1; } item = this.viewItems[this.focusedItem]; } while (this.focusedItem !== startIndex && this.options.focusOnlyEnabledItems && !item.isEnabled()); this.updateFocus(true); return true; } updateFocus(fromRight, preventScroll, forceFocus = false) { var _a; if (typeof this.focusedItem === 'undefined') { this.actionsList.focus({ preventScroll }); } if (this.previouslyFocusedItem !== undefined && this.previouslyFocusedItem !== this.focusedItem) { (_a = this.viewItems[this.previouslyFocusedItem]) === null || _a === void 0 ? void 0 : _a.blur(); } const actionViewItem = this.focusedItem !== undefined && this.viewItems[this.focusedItem]; if (actionViewItem) { let focusItem = true; if (!types.isFunction(actionViewItem.focus)) { focusItem = false; } if (this.options.focusOnlyEnabledItems && types.isFunction(actionViewItem.isEnabled) && !actionViewItem.isEnabled()) { focusItem = false; } if (!focusItem) { this.actionsList.focus({ preventScroll }); this.previouslyFocusedItem = undefined; } else if (forceFocus || this.previouslyFocusedItem !== this.focusedItem) { actionViewItem.focus(fromRight); this.previouslyFocusedItem = this.focusedItem; } } } 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[483/*vs/base/browser/ui/dropdown/dropdown*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,46/*vs/base/browser/keyboardEvent*/,57/*vs/base/browser/touch*/,44/*vs/base/common/actions*/,4/*vs/base/common/event*/,224/*vs/css!vs/base/browser/ui/dropdown/dropdown*/]), function (require, exports, dom_1, keyboardEvent_1, touch_1, actions_1, event_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DropdownMenu = exports.BaseDropdown = void 0; class BaseDropdown extends actions_1.ActionRunner { constructor(container, options) { super(); this._onDidChangeVisibility = this._register(new event_1.Emitter()); this.onDidChangeVisibility = this._onDidChangeVisibility.event; this._element = (0, dom_1.append)(container, (0, dom_1.$)('.monaco-dropdown')); this._label = (0, dom_1.append)(this._element, (0, dom_1.$)('.dropdown-label')); let labelRenderer = options.labelRenderer; if (!labelRenderer) { labelRenderer = (container) => { container.textContent = options.label || ''; return null; }; } for (const event of [dom_1.EventType.CLICK, dom_1.EventType.MOUSE_DOWN, touch_1.EventType.Tap]) { this._register((0, dom_1.addDisposableListener)(this.element, event, e => dom_1.EventHelper.stop(e, true))); // prevent default click behaviour to trigger } for (const event of [dom_1.EventType.MOUSE_DOWN, touch_1.EventType.Tap]) { this._register((0, dom_1.addDisposableListener)(this._label, event, e => { if (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[484/*vs/base/browser/ui/dropdown/dropdownActionViewItem*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,125/*vs/base/browser/ui/actionbar/actionViewItems*/,483/*vs/base/browser/ui/dropdown/dropdown*/,4/*vs/base/common/event*/,224/*vs/css!vs/base/browser/ui/dropdown/dropdown*/]), function (require, exports, dom_1, actionViewItems_1, dropdown_1, event_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[192/*vs/base/browser/ui/inputbox/inputBox*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,89/*vs/base/browser/event*/,169/*vs/base/browser/formattedTextRenderer*/,84/*vs/base/browser/ui/actionbar/actionbar*/,43/*vs/base/browser/ui/aria/aria*/,67/*vs/base/browser/ui/scrollbar/scrollableElement*/,60/*vs/base/browser/ui/widget*/,29/*vs/base/common/color*/,4/*vs/base/common/event*/,313/*vs/base/common/history*/,39/*vs/base/common/objects*/,477/*vs/nls!vs/base/browser/ui/inputbox/inputBox*/,338/*vs/css!vs/base/browser/ui/inputbox/inputBox*/]), function (require, exports, dom, event_1, formattedTextRenderer_1, actionbar_1, aria, scrollableElement_1, widget_1, color_1, event_2, history_1, objects_1, nls) { "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_2.Emitter()); this.onDidChange = this._onDidChange.event; this._onDidHeightChange = this._register(new event_2.Emitter()); this.onDidHeightChange = this._onDidHeightChange.event; this.contextViewProvider = contextViewProvider; this.options = options || 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_1.DomEmitter(document, 'selectionchange')); const onAnchoredSelectionChange = event_2.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) { // Set width to avoid hint text overlapping buttons this.input.style.width = `calc(100% - ${paddingRight}px)`; if (this.mirror) { this.mirror.style.paddingRight = paddingRight + 'px'; } } updateScrollDimensions() { if (typeof this.cachedContentHeight !== 'number' || typeof this.cachedHeight !== 'number' || !this.scrollableElement) { return; } const scrollHeight = this.cachedContentHeight; const height = this.cachedHeight; const scrollTop = this.input.scrollTop; this.scrollableElement.setScrollDimensions({ scrollHeight, height }); this.scrollableElement.setScrollPosition({ scrollTop }); } showMessage(message, force) { 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) { const NLS_PLACEHOLDER_HISTORY_HINT = nls.localize(3, null); const NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX = ` or \u21C5 ${NLS_PLACEHOLDER_HISTORY_HINT}`; const NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS = ` (\u21C5 ${NLS_PLACEHOLDER_HISTORY_HINT})`; super(container, contextViewProvider, options); this.history = new history_1.HistoryNavigator(options.history, 100); // Function to append the history suffix to the placeholder if necessary const addSuffix = () => { if (options.showHistoryHint && options.showHistoryHint() && !this.placeholder.endsWith(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX) && !this.placeholder.endsWith(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS) && this.history.getHistory().length) { const suffix = this.placeholder.endsWith(')') ? NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX : NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS; const suffixedPlaceholder = this.placeholder + suffix; if (options.showPlaceholderOnFocus && document.activeElement !== this.input) { this.placeholder = suffixedPlaceholder; } else { this.setPlaceHolder(suffixedPlaceholder); } } }; // Spot the change to the textarea class attribute which occurs when it changes between non-empty and empty, // and add the history suffix to the placeholder if not yet present this.observer = new MutationObserver((mutationList, observer) => { mutationList.forEach((mutation) => { if (!mutation.target.textContent) { addSuffix(); } }); }); this.observer.observe(this.input, { attributeFilter: ['class'] }); this.onfocus(this.input, () => addSuffix()); this.onblur(this.input, () => { const resetPlaceholder = (historyHint) => { if (!this.placeholder.endsWith(historyHint)) { return false; } else { const revertedPlaceholder = this.placeholder.slice(0, this.placeholder.length - historyHint.length); if (options.showPlaceholderOnFocus) { this.placeholder = revertedPlaceholder; } else { this.setPlaceHolder(revertedPlaceholder); } return true; } }; if (!resetPlaceholder(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS)) { resetPlaceholder(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX); } }); } dispose() { super.dispose(); if (this.observer) { this.observer.disconnect(); this.observer = undefined; } } 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[485/*vs/base/browser/ui/findinput/findInput*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,264/*vs/base/browser/ui/findinput/findInputCheckboxes*/,192/*vs/base/browser/ui/inputbox/inputBox*/,60/*vs/base/browser/ui/widget*/,4/*vs/base/common/event*/,472/*vs/nls!vs/base/browser/ui/findinput/findInput*/,225/*vs/css!vs/base/browser/ui/findinput/findInput*/]), function (require, exports, dom, findInputCheckboxes_1, inputBox_1, widget_1, event_1, nls) { "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, showHistoryHint: options.showHistoryHint, 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); } } }); this.controls = document.createElement('div'); this.controls.className = 'controls'; this.controls.style.display = this._showOptionButtons ? 'block' : 'none'; this.controls.appendChild(this.caseSensitive.domNode); this.controls.appendChild(this.wholeWords.domNode); this.controls.appendChild(this.regex.domNode); this.domNode.appendChild(this.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[486/*vs/base/browser/ui/findinput/replaceInput*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,172/*vs/base/browser/ui/checkbox/checkbox*/,192/*vs/base/browser/ui/inputbox/inputBox*/,60/*vs/base/browser/ui/widget*/,27/*vs/base/common/codicons*/,4/*vs/base/common/event*/,474/*vs/nls!vs/base/browser/ui/findinput/replaceInput*/,225/*vs/css!vs/base/browser/ui/findinput/findInput*/]), function (require, exports, dom, checkbox_1, inputBox_1, widget_1, codicons_1, event_1, nls) { "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, showHistoryHint: options.showHistoryHint, 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[487/*vs/base/browser/ui/menu/menu*/], __M([1/*require*/,0/*exports*/,34/*vs/base/browser/browser*/,57/*vs/base/browser/touch*/,7/*vs/base/browser/dom*/,46/*vs/base/browser/keyboardEvent*/,56/*vs/base/browser/mouseEvent*/,84/*vs/base/browser/ui/actionbar/actionbar*/,125/*vs/base/browser/ui/actionbar/actionViewItems*/,140/*vs/base/browser/ui/codicons/codiconStyles*/,222/*vs/base/browser/ui/contextview/contextview*/,67/*vs/base/browser/ui/scrollbar/scrollableElement*/,44/*vs/base/common/actions*/,10/*vs/base/common/async*/,27/*vs/base/common/codicons*/,95/*vs/base/common/iconLabels*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,8/*vs/base/common/strings*/]), function (require, exports, browser_1, touch_1, dom_1, keyboardEvent_1, mouseEvent_1, actionbar_1, actionViewItems_1, codiconStyles_1, contextview_1, scrollableElement_1, actions_1, async_1, codicons_1, iconLabels_1, lifecycle_1, platform_1, strings) { "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 = /(&)?(&)([^\s&])/g; 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.initializeOrUpdateStyleSheet(container, {}); this._register(touch_1.Gesture.addTarget(menuElement)); (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(); } } })); // Support touch on actions list to focus items (needed for submenus) this._register(touch_1.Gesture.addTarget(this.actionsList)); this._register((0, dom_1.addDisposableListener)(this.actionsList, touch_1.EventType.Tap, e => { let target = e.initialTarget; if (!target || !(0, dom_1.isAncestor)(target, this.actionsList) || target === this.actionsList) { return; } while (target.parentElement !== this.actionsList && target.parentElement !== null) { target = target.parentElement; } if (target.classList.contains('action-item')) { const lastFocusedItem = this.focusedItem; this.setFocusedItem(target); if (lastFocusedItem !== this.focusedItem) { this.updateFocus(); } } })); 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 = ''; // Support scroll on menu drag this._register((0, dom_1.addDisposableListener)(menuElement, touch_1.EventType.Change, e => { dom_1.EventHelper.stop(e, true); const scrollTop = this.scrollableElement.getScrollPosition().scrollTop; this.scrollableElement.setScrollPosition({ scrollTop: scrollTop - e.translationY }); })); this._register((0, dom_1.addDisposableListener)(scrollElement, dom_1.EventType.MOUSE_UP, e => { // Absorb clicks in menu dead space https://github.com/microsoft/vscode/issues/63575 // We do this on the scroll element so the scroll bar doesn't dismiss the menu either e.preventDefault(); })); 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); }); } initializeOrUpdateStyleSheet(container, style) { if (!this.styleSheet) { if ((0, dom_1.isInShadowDOM)(container)) { this.styleSheet = (0, dom_1.createStyleSheet)(container); } else { if (!Menu.globalStyleSheet) { Menu.globalStyleSheet = (0, dom_1.createStyleSheet)(); } this.styleSheet = Menu.globalStyleSheet; } } this.styleSheet.textContent = getMenuWidgetCSS(style); } style(style) { const container = this.getContainer(); this.initializeOrUpdateStyleSheet(container, style); 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, 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 timeout to allow context menu cancellation to trigger // otherwise the action will destroy the menu and a second context menu // will still trigger for right click. else { setTimeout(() => { this.onClick(e); }, 0); } })); this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.CONTEXT_MENU, e => { dom_1.EventHelper.stop(e, true); })); }, 100); this._register(this.runOnceToEnableMouseUp); } render(container) { super.render(container); if (!this.element) { return; } this.container = container; this.item = (0, dom_1.append)(this.element, (0, dom_1.$)('a.action-menu-item')); if (this._action.id === actions_1.Separator.ID) { // A separator is a presentation item this.item.setAttribute('role', 'presentation'); } else { this.item.setAttribute('role', 'menuitem'); if (this.mnemonic) { this.item.setAttribute('aria-keyshortcuts', `${this.mnemonic}`); } } this.check = (0, dom_1.append)(this.item, (0, dom_1.$)('span.menu-item-check' + codicons_1.Codicon.menuSelection.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(/&&/g, '&'); 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() { // menus should function like native menus and they do not have tooltips } updateClass() { if (this.cssClass && this.item) { this.item.classList.remove(...this.cssClass.split(' ')); } if (this.options.icon && this.label) { this.cssClass = this.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; } const checked = this.getAction().checked; this.item.classList.toggle('checked', !!checked); if (checked !== undefined) { this.item.setAttribute('role', 'menuitemcheckbox'); this.item.setAttribute('aria-checked', checked ? 'true' : 'false'); } else { this.item.setAttribute('role', 'menuitem'); this.item.setAttribute('aria-checked', ''); } } getMnemonic() { return this.mnemonic; } applyStyle() { 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' + codicons_1.Codicon.menuSubmenu.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); // subtract offsets caused by transform parent this.submenuContainer.style.left = `${left - viewBox.left}px`; this.submenuContainer.style.top = `${top - viewBox.top}px`; this.submenuDisposables.add((0, dom_1.addDisposableListener)(this.submenuContainer, dom_1.EventType.KEY_UP, e => { 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; function getMenuWidgetCSS(style) { let result = /* css */ ` .monaco-menu { font-size: 13px; } ${(0, codiconStyles_1.formatRule)(codicons_1.Codicon.menuSelection)} ${(0, codiconStyles_1.formatRule)(codicons_1.Codicon.menuSubmenu)} .monaco-menu .monaco-action-bar { text-align: right; overflow: hidden; white-space: nowrap; } .monaco-menu .monaco-action-bar .actions-container { display: flex; margin: 0 auto; padding: 0; width: 100%; justify-content: flex-end; } .monaco-menu .monaco-action-bar.vertical .actions-container { display: inline-block; } .monaco-menu .monaco-action-bar.reverse .actions-container { flex-direction: row-reverse; } .monaco-menu .monaco-action-bar .action-item { cursor: pointer; display: inline-block; transition: transform 50ms ease; position: relative; /* DO NOT REMOVE - this is the key to preventing the ghosting icon bug in Chrome 42 */ } .monaco-menu .monaco-action-bar .action-item.disabled { cursor: default; } .monaco-menu .monaco-action-bar.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%; } .monaco-scrollable-element > .shadow.left { display: block; top: 3px; left: 0; height: 100%; width: 3px; } .monaco-scrollable-element > .shadow.top-left-corner { display: block; top: 0; left: 0; height: 3px; width: 3px; } `; // Scrollbars const scrollbarShadowColor = style.scrollbarShadow; if (scrollbarShadowColor) { result += ` .monaco-scrollable-element > .shadow.top { box-shadow: ${scrollbarShadowColor} 0 6px 6px -6px inset; } .monaco-scrollable-element > .shadow.left { box-shadow: ${scrollbarShadowColor} 6px 0 6px -6px inset; } .monaco-scrollable-element > .shadow.top.left { box-shadow: ${scrollbarShadowColor} 6px 6px 6px -6px inset; } `; } const scrollbarSliderBackgroundColor = style.scrollbarSliderBackground; if (scrollbarSliderBackgroundColor) { result += ` .monaco-scrollable-element > .scrollbar > .slider { background: ${scrollbarSliderBackgroundColor}; } `; } const scrollbarSliderHoverBackgroundColor = style.scrollbarSliderHoverBackground; if (scrollbarSliderHoverBackgroundColor) { result += ` .monaco-scrollable-element > .scrollbar > .slider:hover { background: ${scrollbarSliderHoverBackgroundColor}; } `; } const scrollbarSliderActiveBackgroundColor = style.scrollbarSliderActiveBackground; if (scrollbarSliderActiveBackgroundColor) { result += ` .monaco-scrollable-element > .scrollbar > .slider.active { background: ${scrollbarSliderActiveBackgroundColor}; } `; } return result; } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[488/*vs/base/parts/quickinput/browser/quickInputBox*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,46/*vs/base/browser/keyboardEvent*/,56/*vs/base/browser/mouseEvent*/,192/*vs/base/browser/ui/inputbox/inputBox*/,2/*vs/base/common/lifecycle*/,74/*vs/base/common/severity*/,142/*vs/css!vs/base/parts/quickinput/browser/media/quickInput*/]), function (require, exports, dom, keyboardEvent_1, mouseEvent_1, inputBox_1, lifecycle_1, severity_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.QuickInputBox = void 0; const $ = dom.$; class QuickInputBox extends lifecycle_1.Disposable { constructor(parent) { 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[489/*vs/nls!vs/base/common/errorMessage*/], __M([5/*vs/nls*/,6/*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[490/*vs/base/common/errorMessage*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,20/*vs/base/common/types*/,489/*vs/nls!vs/base/common/errorMessage*/]), function (require, exports, arrays, types, nls) { "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[491/*vs/nls!vs/base/common/keybindingLabels*/], __M([5/*vs/nls*/,6/*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[193/*vs/base/common/keybindingLabels*/], __M([1/*require*/,0/*exports*/,491/*vs/nls!vs/base/common/keybindingLabels*/]), function (require, exports, nls) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UserSettingsLabelProvider = exports.ElectronAcceleratorLabelProvider = exports.AriaLabelProvider = exports.UILabelProvider = exports.ModifierLabelProvider = void 0; class ModifierLabelProvider { constructor(mac, windows, linux = windows) { this.modifierLabels = [null]; // index 0 will never me accessed. this.modifierLabels[2 /* 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: '\u2303', 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: '+', }); /** * A label provider that prints modifiers in a suitable format for Electron Accelerators. * See https://github.com/electron/electron/blob/master/docs/api/accelerator.md */ exports.ElectronAcceleratorLabelProvider = new ModifierLabelProvider({ ctrlKey: 'Ctrl', shiftKey: 'Shift', altKey: 'Alt', metaKey: 'Cmd', separator: '+', }, { ctrlKey: 'Ctrl', shiftKey: 'Shift', altKey: 'Alt', metaKey: 'Super', separator: '+', }); /** * A label provider that prints modifiers in a suitable format for user settings. */ exports.UserSettingsLabelProvider = new ModifierLabelProvider({ ctrlKey: 'ctrl', shiftKey: 'shift', altKey: 'alt', metaKey: 'cmd', separator: '+', }, { ctrlKey: 'ctrl', shiftKey: 'shift', altKey: 'alt', metaKey: 'win', separator: '+', }, { ctrlKey: 'ctrl', shiftKey: 'shift', altKey: 'alt', metaKey: 'meta', separator: '+', }); function _simpleAsString(modifiers, key, labels) { if (key === null) { return ''; } const result = []; // translate modifier keys: Ctrl-Shift-Alt-Meta if (modifiers.ctrlKey) { result.push(labels.ctrlKey); } if (modifiers.shiftKey) { result.push(labels.shiftKey); } if (modifiers.altKey) { result.push(labels.altKey); } if (modifiers.metaKey) { result.push(labels.metaKey); } // the actual key if (key !== '') { result.push(key); } return result.join(labels.separator); } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[492/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,193/*vs/base/common/keybindingLabels*/,39/*vs/base/common/objects*/,478/*vs/nls!vs/base/browser/ui/keybindingLabel/keybindingLabel*/,339/*vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel*/]), function (require, exports, dom, keybindingLabels_1, objects_1, 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[493/*vs/nls!vs/base/parts/quickinput/browser/quickInput*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/parts/quickinput/browser/quickInput", data); }); define(__m[494/*vs/nls!vs/base/parts/quickinput/browser/quickInputList*/], __M([5/*vs/nls*/,6/*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[495/*vs/base/parts/quickinput/browser/quickInputList*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,46/*vs/base/browser/keyboardEvent*/,84/*vs/base/browser/ui/actionbar/actionbar*/,190/*vs/base/browser/ui/iconLabel/iconLabel*/,492/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/,44/*vs/base/common/actions*/,19/*vs/base/common/arrays*/,27/*vs/base/common/codicons*/,317/*vs/base/common/comparers*/,93/*vs/base/common/decorators*/,4/*vs/base/common/event*/,95/*vs/base/common/iconLabels*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,20/*vs/base/common/types*/,229/*vs/base/parts/quickinput/browser/quickInputUtils*/,494/*vs/nls!vs/base/parts/quickinput/browser/quickInputList*/,142/*vs/css!vs/base/parts/quickinput/browser/media/quickInput*/]), function (require, exports, dom, keyboardEvent_1, actionbar_1, iconLabel_1, keybindingLabel_1, actions_1, arrays_1, codicons_1, comparers_1, decorators_1, event_1, iconLabels_1, lifecycle_1, platform, types_1, quickInputUtils_1, nls_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 iconLabel_1.IconLabel(detailContainer, { supportHighlights: true, supportIcons: 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 if (element.saneDetail) { data.detail.setLabel(element.saneDetail, undefined, { matches: detailHighlights, title: element.saneDetail }); } // 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 /* KeyA */: 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 })); } get scrollTop() { return this.list.scrollTop; } set scrollTop(scrollTop) { this.list.scrollTop = scrollTop; } 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[496/*vs/base/parts/quickinput/browser/quickInput*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,46/*vs/base/browser/keyboardEvent*/,84/*vs/base/browser/ui/actionbar/actionbar*/,330/*vs/base/browser/ui/button/button*/,223/*vs/base/browser/ui/countBadge/countBadge*/,113/*vs/base/browser/ui/iconLabel/iconLabels*/,342/*vs/base/browser/ui/progressbar/progressbar*/,44/*vs/base/common/actions*/,19/*vs/base/common/arrays*/,10/*vs/base/common/async*/,21/*vs/base/common/cancellation*/,27/*vs/base/common/codicons*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,74/*vs/base/common/severity*/,20/*vs/base/common/types*/,229/*vs/base/parts/quickinput/browser/quickInputUtils*/,220/*vs/base/parts/quickinput/common/quickInput*/,493/*vs/nls!vs/base/parts/quickinput/browser/quickInput*/,488/*vs/base/parts/quickinput/browser/quickInputBox*/,495/*vs/base/parts/quickinput/browser/quickInputList*/,142/*vs/css!vs/base/parts/quickinput/browser/media/quickInput*/]), function (require, exports, dom, keyboardEvent_1, actionbar_1, button_1, countBadge_1, iconLabels_1, progressbar_1, actions_1, arrays_1, async_1, cancellation_1, codicons_1, event_1, lifecycle_1, platform_1, severity_1, types_1, quickInputUtils_1, quickInput_1, nls_1, quickInputBox_1, quickInputList_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.QuickInputController = void 0; const $ = dom.$; const backButton = { iconClass: codicons_1.Codicon.quickInputBack.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); // update properties in the controller that get reset in the ui.show() call this.visible = true; // This ensures the message/prompt gets rendered this._lastValidationMessage = undefined; // This ensures the input box has the right severity applied this._lastSeverity = undefined; if (this.buttons.length) { // if there are buttons, the ui.show() clears them out of the UI so we should // rerender them. this.buttonsUpdated = true; } 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 !== ' ') { 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.marginBottom = '-2px'; } else { this.ui.message.style.color = ''; this.ui.message.style.backgroundColor = ''; this.ui.message.style.border = ''; this.ui.message.style.marginBottom = ''; } } dispose() { this.hide(); this.onDisposeEmitter.fire(); super.dispose(); } } 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._keepScrollPosition = false; 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) { this.doSetValue(value); } doSetValue(value, skipUpdate) { if (this._value !== value) { this._value = value; if (!skipUpdate) { this.update(); } if (this.visible) { const didFilter = this.ui.list.filter(this.filterValue(this._value)); if (didFilter) { this.trySelectFirst(); } } this.onDidChangeValueEmitter.fire(this._value); } } set ariaLabel(ariaLabel) { this._ariaLabel = ariaLabel; this.update(); } get ariaLabel() { return this._ariaLabel; } get placeholder() { return this._placeholder; } set placeholder(placeholder) { this._placeholder = placeholder; this.update(); } get items() { return this._items; } get scrollTop() { return this.ui.list.scrollTop; } set scrollTop(scrollTop) { this.ui.list.scrollTop = scrollTop; } set items(items) { this._items = items; this.itemsUpdated = true; this.update(); } get canSelectMany() { return this._canSelectMany; } set canSelectMany(canSelectMany) { this._canSelectMany = canSelectMany; this.update(); } get canAcceptInBackground() { return this._canAcceptInBackground; } set canAcceptInBackground(canAcceptInBackground) { this._canAcceptInBackground = canAcceptInBackground; } get matchOnDescription() { return this._matchOnDescription; } set matchOnDescription(matchOnDescription) { this._matchOnDescription = matchOnDescription; this.update(); } get matchOnDetail() { return this._matchOnDetail; } set matchOnDetail(matchOnDetail) { this._matchOnDetail = matchOnDetail; this.update(); } get matchOnLabel() { return this._matchOnLabel; } set matchOnLabel(matchOnLabel) { this._matchOnLabel = matchOnLabel; this.update(); } get 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 keepScrollPosition() { return this._keepScrollPosition; } set keepScrollPosition(keepScrollPosition) { this._keepScrollPosition = keepScrollPosition; } get itemActivation() { return this._itemActivation; } set itemActivation(itemActivation) { this._itemActivation = itemActivation; } get activeItems() { return this._activeItems; } set activeItems(activeItems) { this._activeItems = activeItems; this.activeItemsUpdated = true; this.update(); } get selectedItems() { return this._selectedItems; } set selectedItems(selectedItems) { this._selectedItems = selectedItems; this.selectedItemsUpdated = true; this.update(); } get keyMods() { if (this._quickNavigate) { // Disable keyMods when quick navigate is enabled // because in this model the interaction is purely // keyboard driven and Ctrl/Alt are typically // pressed and hold during this interaction. return quickInput_1.NO_KEY_MODS; } return this.ui.keyMods; } 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 => { this.doSetValue(value, true /* skip update since this originates from the UI */); })); 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) { // if there are no checked elements, it means that an onDidChangeSelection never fired to overwrite // `_selectedItems`. In that case, we should emit one with an empty array to ensure that // `.selectedItems` is up to date. if (!this.ui.list.getCheckedElements().length) { this._selectedItems = []; this.onDidChangeSelectionEmitter.fire(this.selectedItems); } } else if (this.activeItems[0]) { // For single-select, we set `selectedItems` to the item that was accepted. this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); } this.handleAccept(false); })); this.visibleDisposables.add(this.ui.onDidCustom(() => { this.onDidCustomEmitter.fire(); })); this.visibleDisposables.add(this.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 `onDidAccept` if no veto if (!veto) { this.onDidAcceptEmitter.fire({ inBackground }); } } registerQuickNavigation() { return dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => { if (this.canSelectMany || !this._quickNavigate) { return; } const keyboardEvent = new keyboardEvent_1.StandardKeyboardEvent(e); const keyCode = keyboardEvent.keyCode; // Select element when keys are pressed that signal it const quickNavKeys = this._quickNavigate.keybindings; const wasTriggerKeyPressed = quickNavKeys.some(k => { const [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; } // store the scrollTop before it is reset const scrollTopBefore = this.keepScrollPosition ? this.scrollTop : 0; 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); } } // Set the scroll position to what it was before updating the items if (this.keepScrollPosition) { this.scrollTop = scrollTopBefore; } } } 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(activeItem => activeItem !== removed[0]); const keepScrollPositionBefore = input.keepScrollPosition; input.keepScrollPosition = true; input.items = items; if (activeItems) { input.activeItems = activeItems; } input.keepScrollPosition = keepScrollPositionBefore; } } }))), 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) { let currentElement = this.previousFocusElement; while (currentElement && !currentElement.offsetParent) { currentElement = (0, types_1.withNullAsUndefined)(currentElement.parentElement); } if (currentElement === null || currentElement === void 0 ? void 0 : currentElement.offsetParent) { currentElement.focus(); this.previousFocusElement = undefined; } else { this.options.returnFocus(); } } controller.didHide(reason); } } layout(dimension, titleBarOffset) { this.dimension = dimension; this.titleBarOffset = titleBarOffset; this.updateLayout(); } updateLayout() { if (this.ui) { this.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[497/*vs/nls!vs/editor/browser/controller/coreCommands*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/controller/coreCommands", data); }); define(__m[498/*vs/nls!vs/editor/browser/controller/textAreaHandler*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/controller/textAreaHandler", data); }); define(__m[499/*vs/nls!vs/editor/browser/editorExtensions*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/editorExtensions", data); }); define(__m[500/*vs/nls!vs/editor/browser/widget/codeEditorWidget*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/codeEditorWidget", data); }); define(__m[501/*vs/nls!vs/editor/browser/widget/diffEditorWidget*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/diffEditorWidget", data); }); define(__m[502/*vs/nls!vs/editor/browser/widget/diffReview*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/diffReview", data); }); define(__m[503/*vs/nls!vs/editor/browser/widget/inlineDiffMargin*/], __M([5/*vs/nls*/,6/*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[504/*vs/editor/browser/widget/inlineDiffMargin*/], __M([1/*require*/,0/*exports*/,503/*vs/nls!vs/editor/browser/widget/inlineDiffMargin*/,7/*vs/base/browser/dom*/,44/*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(59 /* 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 = []; const isDeletion = diff.modifiedEndLineNumber === 0; // default action actions.push(new actions_1.Action('diff.clipboard.copyDeletedContent', isDeletion ? (diff.originalEndLineNumber > diff.modifiedStartLineNumber ? nls.localize(0, null) : nls.localize(1, null)) : (diff.originalEndLineNumber > diff.modifiedStartLineNumber ? nls.localize(2, null) : nls.localize(3, 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', isDeletion ? nls.localize(4, null, diff.originalStartLineNumber) : nls.localize(5, null, diff.originalStartLineNumber), undefined, true, () => __awaiter(this, void 0, void 0, function* () { const lineContent = diff.originalModel.getLineContent(diff.originalStartLineNumber + currentLineNumberOffset); if (lineContent === '') { // empty line const eof = diff.originalModel.getEndOfLineSequence(); yield this._clipboardService.writeText(eof === 0 /* LF */ ? '\n' : '\r\n'); } else { yield this._clipboardService.writeText(lineContent); } })); actions.push(copyLineAction); } const readOnly = editor.getOption(81 /* readOnly */); if (!readOnly) { actions.push(new actions_1.Action('diff.inline.revertChange', nls.localize(6, 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 = isDeletion ? nls.localize(7, null, diff.originalStartLineNumber + currentLineNumberOffset) : nls.localize(8, null, diff.originalStartLineNumber + currentLineNumberOffset); } return actions; }, autoSelectFirstItem: true }); }; this._register(dom.addStandardDisposableListener(this._diffActions, 'mousedown', e => { const { top, height } = dom.getDomNodePagePosition(this._diffActions); const 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[505/*vs/nls!vs/editor/common/config/editorConfigurationSchema*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/config/editorConfigurationSchema", data); }); define(__m[506/*vs/nls!vs/editor/common/config/editorOptions*/], __M([5/*vs/nls*/,6/*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[31/*vs/editor/common/config/editorOptions*/], __M([1/*require*/,0/*exports*/,506/*vs/nls!vs/editor/common/config/editorOptions*/,17/*vs/base/common/platform*/,146/*vs/editor/common/core/wordHelper*/,19/*vs/base/common/arrays*/,39/*vs/base/common/objects*/,145/*vs/editor/common/core/textModelDefaults*/]), function (require, exports, nls, platform, wordHelper_1, arrays, objects, textModelDefaults_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EditorOptions = exports.editorOptionsRegistry = exports.EDITOR_FONT_DEFAULTS = exports.unicodeHighlightConfigKeys = exports.inUntrustedWorkspace = exports.filterValidationDecorations = exports.EditorLayoutInfoComputer = exports.EditorFontLigatures = exports.TextEditorCursorStyle = exports.stringSet = exports.clampedInt = exports.boolean = exports.ApplyUpdateResult = exports.ComputeOptionsMemory = 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 ComputeOptionsMemory { constructor() { this.stableMinimapLayoutInput = null; this.stableFitMaxMinimapScale = 0; this.stableFitRemainingWidth = 0; } } exports.ComputeOptionsMemory = ComputeOptionsMemory; /** * @internal */ class BaseEditorOption { constructor(id, name, defaultValue, schema) { this.id = id; this.name = name; this.defaultValue = defaultValue; this.schema = schema; } applyUpdate(value, update) { return applyUpdate(value, update); } compute(env, options, value) { return value; } } class ApplyUpdateResult { constructor(newValue, didChange) { this.newValue = newValue; this.didChange = didChange; } } exports.ApplyUpdateResult = ApplyUpdateResult; function applyUpdate(value, update) { if (typeof value !== 'object' || typeof update !== 'object' || !value || !update) { return new ApplyUpdateResult(update, value !== update); } if (Array.isArray(value) || Array.isArray(update)) { const arrayEquals = Array.isArray(value) && Array.isArray(update) && arrays.equals(value, update); return new ApplyUpdateResult(update, arrayEquals); } let didChange = false; for (const key in update) { if (update.hasOwnProperty(key)) { const result = applyUpdate(value[key], update[key]); if (result.didChange) { value[key] = result.newValue; didChange = true; } } } return new ApplyUpdateResult(value, didChange); } /** * @internal */ class ComputedEditorOption { constructor(id) { this.schema = undefined; this.id = id; this.name = '_never_'; this.defaultValue = undefined; } applyUpdate(value, update) { return applyUpdate(value, update); } validate(input) { return this.defaultValue; } } class SimpleEditorOption { constructor(id, name, defaultValue, schema) { this.id = id; this.name = name; this.defaultValue = defaultValue; this.schema = schema; } applyUpdate(value, update) { return applyUpdate(value, update); } validate(input) { if (typeof input === 'undefined') { return this.defaultValue; } return input; } compute(env, options, value) { return value; } } /** * @internal */ function boolean(value, defaultValue) { if (typeof value === 'undefined') { return defaultValue; } if (value === 'false') { // treat the string 'false' as false return false; } return Boolean(value); } 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); } } /** * @internal */ function clampedInt(value, defaultValue, minimum, maximum) { if (typeof value === 'undefined') { return defaultValue; } let r = parseInt(value, 10); if (isNaN(r)) { return defaultValue; } r = Math.max(minimum, r); r = Math.min(maximum, r); return r | 0; } exports.clampedInt = clampedInt; 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) { return clampedInt(value, defaultValue, minimum, maximum); } 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(19 /* 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(128 /* editorClassName */); } compute(env, options, _) { const classNames = ['monaco-editor']; if (options.get(33 /* extraEditorClassName */)) { classNames.push(options.get(33 /* extraEditorClassName */)); } if (env.extraEditorClassName) { classNames.push(env.extraEditorClassName); } if (options.get(66 /* mouseStyle */) === 'default') { classNames.push('mouse-default'); } else if (options.get(66 /* mouseStyle */) === 'copy') { classNames.push('mouse-copy'); } if (options.get(100 /* showUnused */)) { classNames.push('showUnused'); } if (options.get(126 /* showDeprecated */)) { classNames.push('showDeprecated'); } return classNames.join(' '); } } //#endregion //#region emptySelectionClipboard class EditorEmptySelectionClipboard extends EditorBooleanOption { constructor() { super(32 /* 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(35 /* 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(45 /* 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(44 /* fontInfo */); } compute(env, options, _) { return env.fontInfo; } } //#endregion //#region fontSize class EditorFontSize extends SimpleEditorOption { constructor() { super(46 /* 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) { const r = EditorFloatOption.float(input, this.defaultValue); if (r === 0) { return exports.EDITOR_FONT_DEFAULTS.fontSize; } return EditorFloatOption.clamp(r, 6, 100); } compute(env, options, value) { // The final fontSize respects the editor zoom level. // So take the result from env.fontInfo return env.fontInfo.fontSize; } } //#endregion //#region fontWeight class EditorFontWeight extends BaseEditorOption { constructor() { super(47 /* 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(51 /* 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, above: true, }; super(53 /* hover */, 'hover', defaults, { 'editor.hover.enabled': { type: 'boolean', default: defaults.enabled, description: nls.localize(39, null) }, 'editor.hover.delay': { type: 'number', default: defaults.delay, minimum: 0, maximum: 10000, description: nls.localize(40, null) }, 'editor.hover.sticky': { type: 'boolean', default: defaults.sticky, description: nls.localize(41, null) }, 'editor.hover.above': { type: 'boolean', default: defaults.above, 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), delay: EditorIntOption.clampedInt(input.delay, this.defaultValue.delay, 0, 10000), sticky: boolean(input.sticky, this.defaultValue.sticky), above: boolean(input.above, this.defaultValue.above), }; } } /** * @internal */ class EditorLayoutInfoComputer extends ComputedEditorOption { constructor() { super(131 /* layoutInfo */); } compute(env, options, _) { return EditorLayoutInfoComputer.computeLayout(options, { memory: env.memory, outerWidth: env.outerWidth, outerHeight: env.outerHeight, isDominatedByLongLines: env.isDominatedByLongLines, lineHeight: env.fontInfo.lineHeight, viewLineCount: env.viewLineCount, lineNumbersDigitCount: env.lineNumbersDigitCount, typicalHalfwidthCharacterWidth: env.fontInfo.typicalHalfwidthCharacterWidth, maxDigitWidth: env.fontInfo.maxDigitWidth, pixelRatio: env.pixelRatio }); } 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(123 /* wordWrapOverride2 */); const wordWrapOverride1 = (wordWrapOverride2 === 'inherit' ? options.get(122 /* wordWrapOverride1 */) : wordWrapOverride2); const wordWrap = (wordWrapOverride1 === 'inherit' ? options.get(118 /* wordWrap */) : wordWrapOverride1); const wordWrapColumn = options.get(121 /* wordWrapColumn */); const accessibilitySupport = options.get(2 /* accessibilitySupport */); const isDominatedByLongLines = env.isDominatedByLongLines; const showGlyphMargin = options.get(50 /* glyphMargin */); const showLineNumbers = (options.get(60 /* lineNumbers */).renderType !== 0 /* Off */); const lineNumbersMinChars = options.get(61 /* lineNumbersMinChars */); const scrollBeyondLastLine = options.get(94 /* scrollBeyondLastLine */); const minimap = options.get(65 /* minimap */); const scrollbar = options.get(92 /* scrollbar */); const verticalScrollbarWidth = scrollbar.verticalScrollbarSize; const verticalScrollbarHasArrows = scrollbar.verticalHasArrows; const scrollbarArrowSize = scrollbar.arrowSize; const horizontalScrollbarHeight = scrollbar.horizontalScrollbarSize; const rawLineDecorationsWidth = options.get(58 /* lineDecorationsWidth */); const folding = options.get(37 /* 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(57 /* lightbulb */, 'lightbulb', defaults, { 'editor.lightbulb.enabled': { type: 'boolean', default: defaults.enabled, description: nls.localize(43, 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(127 /* inlayHints */, 'inlayHints', defaults, { 'editor.inlayHints.enabled': { type: 'boolean', default: defaults.enabled, description: nls.localize(44, null) }, 'editor.inlayHints.fontSize': { type: 'number', default: defaults.fontSize, markdownDescription: nls.localize(45, null) }, 'editor.inlayHints.fontFamily': { type: 'string', default: defaults.fontFamily, markdownDescription: nls.localize(46, 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(59 /* lineHeight */, 'lineHeight', exports.EDITOR_FONT_DEFAULTS.lineHeight, x => EditorFloatOption.clamp(x, 0, 150), { markdownDescription: nls.localize(47, 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(65 /* minimap */, 'minimap', defaults, { 'editor.minimap.enabled': { type: 'boolean', default: defaults.enabled, description: nls.localize(48, null) }, 'editor.minimap.size': { type: 'string', enum: ['proportional', 'fill', 'fit'], enumDescriptions: [ nls.localize(49, null), nls.localize(50, null), nls.localize(51, null), ], default: defaults.size, description: nls.localize(52, null) }, 'editor.minimap.side': { type: 'string', enum: ['left', 'right'], default: defaults.side, description: nls.localize(53, null) }, 'editor.minimap.showSlider': { type: 'string', enum: ['always', 'mouseover'], default: defaults.showSlider, description: nls.localize(54, null) }, 'editor.minimap.scale': { type: 'number', default: defaults.scale, minimum: 1, maximum: 3, enum: [1, 2, 3], description: nls.localize(55, null) }, 'editor.minimap.renderCharacters': { type: 'boolean', default: defaults.renderCharacters, description: nls.localize(56, null) }, 'editor.minimap.maxColumn': { type: 'number', default: defaults.maxColumn, description: nls.localize(57, 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(75 /* padding */, 'padding', { top: 0, bottom: 0 }, { 'editor.padding.top': { type: 'number', default: 0, minimum: 0, maximum: 1000, description: nls.localize(58, null) }, 'editor.padding.bottom': { type: 'number', default: 0, minimum: 0, maximum: 1000, description: nls.localize(59, 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(76 /* parameterHints */, 'parameterHints', defaults, { 'editor.parameterHints.enabled': { type: 'boolean', default: defaults.enabled, description: nls.localize(60, null) }, 'editor.parameterHints.cycle': { type: 'boolean', default: defaults.cycle, description: nls.localize(61, 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(129 /* pixelRatio */); } compute(env, options, _) { return env.pixelRatio; } } class EditorQuickSuggestions extends BaseEditorOption { constructor() { const defaults = { other: true, comments: false, strings: false }; super(79 /* quickSuggestions */, 'quickSuggestions', defaults, { anyOf: [ { type: 'boolean', }, { type: 'object', properties: { strings: { type: 'boolean', default: defaults.strings, description: nls.localize(62, null) }, comments: { type: 'boolean', default: defaults.comments, description: nls.localize(63, null) }, other: { type: 'boolean', default: defaults.other, description: nls.localize(64, null) }, } } ], default: defaults, description: nls.localize(65, 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(60 /* lineNumbers */, 'lineNumbers', { renderType: 1 /* On */, renderFn: null }, { type: 'string', enum: ['off', 'on', 'relative', 'interval'], enumDescriptions: [ nls.localize(66, null), nls.localize(67, null), nls.localize(68, null), nls.localize(69, null) ], default: 'on', description: nls.localize(70, 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(87 /* renderValidationDecorations */); if (renderValidationDecorations === 'editable') { return options.get(81 /* readOnly */); } return renderValidationDecorations === 'on' ? false : true; } exports.filterValidationDecorations = filterValidationDecorations; class EditorRulers extends BaseEditorOption { constructor() { const defaults = []; const columnSchema = { type: 'number', description: nls.localize(71, null) }; super(91 /* rulers */, 'rulers', defaults, { type: 'array', items: { anyOf: [ columnSchema, { type: [ 'object' ], properties: { column: columnSchema, color: { type: 'string', description: nls.localize(72, null), format: 'color-hex' } } } ] }, default: defaults, description: nls.localize(73, null) }); } validate(input) { if (Array.isArray(input)) { const 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(92 /* scrollbar */, 'scrollbar', defaults, { 'editor.scrollbar.vertical': { type: 'string', enum: ['auto', 'visible', 'hidden'], enumDescriptions: [ nls.localize(74, null), nls.localize(75, null), nls.localize(76, null), ], default: 'auto', description: nls.localize(77, null) }, 'editor.scrollbar.horizontal': { type: 'string', enum: ['auto', 'visible', 'hidden'], enumDescriptions: [ nls.localize(78, null), nls.localize(79, null), nls.localize(80, null), ], default: 'auto', description: nls.localize(81, null) }, 'editor.scrollbar.verticalScrollbarSize': { type: 'number', default: defaults.verticalScrollbarSize, description: nls.localize(82, null) }, 'editor.scrollbar.horizontalScrollbarSize': { type: 'number', default: defaults.horizontalScrollbarSize, description: nls.localize(83, null) }, 'editor.scrollbar.scrollByPage': { type: 'boolean', default: defaults.scrollByPage, description: nls.localize(84, 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), }; } } /** * @internal */ exports.inUntrustedWorkspace = 'inUntrustedWorkspace'; /** * @internal */ exports.unicodeHighlightConfigKeys = { allowedCharacters: 'editor.unicodeHighlight.allowedCharacters', invisibleCharacters: 'editor.unicodeHighlight.invisibleCharacters', nonBasicASCII: 'editor.unicodeHighlight.nonBasicASCII', ambiguousCharacters: 'editor.unicodeHighlight.ambiguousCharacters', includeComments: 'editor.unicodeHighlight.includeComments', includeStrings: 'editor.unicodeHighlight.includeStrings', allowedLocales: 'editor.unicodeHighlight.allowedLocales', }; class UnicodeHighlight extends BaseEditorOption { constructor() { const defaults = { nonBasicASCII: exports.inUntrustedWorkspace, invisibleCharacters: true, ambiguousCharacters: true, includeComments: exports.inUntrustedWorkspace, includeStrings: true, allowedCharacters: {}, allowedLocales: { _os: true, _vscode: true }, }; super(113 /* unicodeHighlighting */, 'unicodeHighlight', defaults, { [exports.unicodeHighlightConfigKeys.nonBasicASCII]: { restricted: true, type: ['boolean', 'string'], enum: [true, false, exports.inUntrustedWorkspace], default: defaults.nonBasicASCII, description: nls.localize(85, null) }, [exports.unicodeHighlightConfigKeys.invisibleCharacters]: { restricted: true, type: 'boolean', default: defaults.invisibleCharacters, description: nls.localize(86, null) }, [exports.unicodeHighlightConfigKeys.ambiguousCharacters]: { restricted: true, type: 'boolean', default: defaults.ambiguousCharacters, description: nls.localize(87, null) }, [exports.unicodeHighlightConfigKeys.includeComments]: { restricted: true, type: ['boolean', 'string'], enum: [true, false, exports.inUntrustedWorkspace], default: defaults.includeComments, description: nls.localize(88, null) }, [exports.unicodeHighlightConfigKeys.includeStrings]: { restricted: true, type: ['boolean', 'string'], enum: [true, false, exports.inUntrustedWorkspace], default: defaults.includeStrings, description: nls.localize(89, null) }, [exports.unicodeHighlightConfigKeys.allowedCharacters]: { restricted: true, type: 'object', default: defaults.allowedCharacters, description: nls.localize(90, null), additionalProperties: { type: 'boolean' } }, [exports.unicodeHighlightConfigKeys.allowedLocales]: { restricted: true, type: 'object', additionalProperties: { type: 'boolean' }, default: defaults.allowedLocales, description: nls.localize(91, null) }, }); } applyUpdate(value, update) { let didChange = false; if (update.allowedCharacters) { // Treat allowedCharacters atomically if (!objects.equals(value.allowedCharacters, update.allowedCharacters)) { value = Object.assign(Object.assign({}, value), { allowedCharacters: update.allowedCharacters }); didChange = true; } } if (update.allowedLocales) { // Treat allowedLocales atomically if (!objects.equals(value.allowedLocales, update.allowedLocales)) { value = Object.assign(Object.assign({}, value), { allowedLocales: update.allowedLocales }); didChange = true; } } const result = super.applyUpdate(value, update); if (didChange) { return new ApplyUpdateResult(result.newValue, true); } return result; } validate(_input) { if (!_input || typeof _input !== 'object') { return this.defaultValue; } const input = _input; return { nonBasicASCII: primitiveSet(input.nonBasicASCII, exports.inUntrustedWorkspace, [true, false, exports.inUntrustedWorkspace]), invisibleCharacters: boolean(input.invisibleCharacters, this.defaultValue.invisibleCharacters), ambiguousCharacters: boolean(input.ambiguousCharacters, this.defaultValue.ambiguousCharacters), includeComments: primitiveSet(input.includeComments, exports.inUntrustedWorkspace, [true, false, exports.inUntrustedWorkspace]), includeStrings: primitiveSet(input.includeStrings, exports.inUntrustedWorkspace, [true, false, exports.inUntrustedWorkspace]), allowedCharacters: this.validateBooleanMap(_input.allowedCharacters, this.defaultValue.allowedCharacters), allowedLocales: this.validateBooleanMap(_input.allowedLocales, this.defaultValue.allowedLocales), }; } validateBooleanMap(map, defaultValue) { if ((typeof map !== 'object') || !map) { return defaultValue; } const result = {}; for (const [key, value] of Object.entries(map)) { if (value === true) { result[key] = true; } } return result; } } /** * Configuration options for inline suggestions */ class InlineEditorSuggest extends BaseEditorOption { constructor() { const defaults = { enabled: true, mode: 'subwordSmart' }; super(55 /* inlineSuggest */, 'inlineSuggest', defaults, { 'editor.inlineSuggest.enabled': { type: 'boolean', default: defaults.enabled, description: nls.localize(92, 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']), }; } } /** * Configuration options for inline suggestions */ class BracketPairColorization extends BaseEditorOption { constructor() { const defaults = { enabled: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions.enabled }; super(12 /* bracketPairColorization */, 'bracketPairColorization', defaults, { 'editor.bracketPairColorization.enabled': { type: 'boolean', default: defaults.enabled, description: nls.localize(93, null) } }); } validate(_input) { if (!_input || typeof _input !== 'object') { return this.defaultValue; } const input = _input; return { enabled: boolean(input.enabled, this.defaultValue.enabled) }; } } /** * Configuration options for inline suggestions */ class GuideOptions extends BaseEditorOption { constructor() { const defaults = { bracketPairs: false, bracketPairsHorizontal: 'active', highlightActiveBracketPair: true, indentation: true, highlightActiveIndentation: true }; super(13 /* guides */, 'guides', defaults, { 'editor.guides.bracketPairs': { type: ['boolean', 'string'], enum: [true, 'active', false], enumDescriptions: [ nls.localize(94, null), nls.localize(95, null), nls.localize(96, null), ], default: defaults.bracketPairs, description: nls.localize(97, null) }, 'editor.guides.bracketPairsHorizontal': { type: ['boolean', 'string'], enum: [true, 'active', false], enumDescriptions: [ nls.localize(98, null), nls.localize(99, null), nls.localize(100, null), ], default: defaults.bracketPairsHorizontal, description: nls.localize(101, null) }, 'editor.guides.highlightActiveBracketPair': { type: 'boolean', default: defaults.highlightActiveBracketPair, description: nls.localize(102, null) }, 'editor.guides.indentation': { type: 'boolean', default: defaults.indentation, description: nls.localize(103, null) }, 'editor.guides.highlightActiveIndentation': { type: 'boolean', default: defaults.highlightActiveIndentation, description: nls.localize(104, null) } }); } validate(_input) { if (!_input || typeof _input !== 'object') { return this.defaultValue; } const input = _input; return { bracketPairs: primitiveSet(input.bracketPairs, this.defaultValue.bracketPairs, [true, false, 'active']), bracketPairsHorizontal: primitiveSet(input.bracketPairsHorizontal, this.defaultValue.bracketPairsHorizontal, [true, false, 'active']), highlightActiveBracketPair: boolean(input.highlightActiveBracketPair, this.defaultValue.highlightActiveBracketPair), indentation: boolean(input.indentation, this.defaultValue.indentation), highlightActiveIndentation: boolean(input.highlightActiveIndentation, this.defaultValue.highlightActiveIndentation), }; } } function primitiveSet(value, defaultValue, allowedValues) { const idx = allowedValues.indexOf(value); if (idx === -1) { return defaultValue; } return allowedValues[idx]; } class EditorSuggest extends BaseEditorOption { constructor() { const defaults = { insertMode: 'insert', filterGraceful: true, snippetsPreventQuickSuggestions: 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(106 /* suggest */, 'suggest', defaults, { 'editor.suggest.insertMode': { type: 'string', enum: ['insert', 'replace'], enumDescriptions: [ nls.localize(105, null), nls.localize(106, null), ], default: defaults.insertMode, description: nls.localize(107, null) }, 'editor.suggest.filterGraceful': { type: 'boolean', default: defaults.filterGraceful, description: nls.localize(108, null) }, 'editor.suggest.localityBonus': { type: 'boolean', default: defaults.localityBonus, description: nls.localize(109, null) }, 'editor.suggest.shareSuggestSelections': { type: 'boolean', default: defaults.shareSuggestSelections, markdownDescription: nls.localize(110, null) }, 'editor.suggest.snippetsPreventQuickSuggestions': { type: 'boolean', default: defaults.snippetsPreventQuickSuggestions, description: nls.localize(111, null) }, 'editor.suggest.showIcons': { type: 'boolean', default: defaults.showIcons, description: nls.localize(112, null) }, 'editor.suggest.showStatusBar': { type: 'boolean', default: defaults.showStatusBar, description: nls.localize(113, null) }, 'editor.suggest.preview': { type: 'boolean', default: defaults.preview, description: nls.localize(114, null) }, 'editor.suggest.showInlineDetails': { type: 'boolean', default: defaults.showInlineDetails, description: nls.localize(115, null) }, 'editor.suggest.maxVisibleSuggestions': { type: 'number', deprecationMessage: nls.localize(116, null), }, 'editor.suggest.filteredTypes': { type: 'object', deprecationMessage: nls.localize(117, null) }, 'editor.suggest.showMethods': { type: 'boolean', default: true, markdownDescription: nls.localize(118, null) }, 'editor.suggest.showFunctions': { type: 'boolean', default: true, markdownDescription: nls.localize(119, null) }, 'editor.suggest.showConstructors': { type: 'boolean', default: true, markdownDescription: nls.localize(120, null) }, 'editor.suggest.showDeprecated': { type: 'boolean', default: true, markdownDescription: nls.localize(121, null) }, 'editor.suggest.showFields': { type: 'boolean', default: true, markdownDescription: nls.localize(122, null) }, 'editor.suggest.showVariables': { type: 'boolean', default: true, markdownDescription: nls.localize(123, null) }, 'editor.suggest.showClasses': { type: 'boolean', default: true, markdownDescription: nls.localize(124, null) }, 'editor.suggest.showStructs': { type: 'boolean', default: true, markdownDescription: nls.localize(125, null) }, 'editor.suggest.showInterfaces': { type: 'boolean', default: true, markdownDescription: nls.localize(126, null) }, 'editor.suggest.showModules': { type: 'boolean', default: true, markdownDescription: nls.localize(127, null) }, 'editor.suggest.showProperties': { type: 'boolean', default: true, markdownDescription: nls.localize(128, null) }, 'editor.suggest.showEvents': { type: 'boolean', default: true, markdownDescription: nls.localize(129, null) }, 'editor.suggest.showOperators': { type: 'boolean', default: true, markdownDescription: nls.localize(130, null) }, 'editor.suggest.showUnits': { type: 'boolean', default: true, markdownDescription: nls.localize(131, null) }, 'editor.suggest.showValues': { type: 'boolean', default: true, markdownDescription: nls.localize(132, null) }, 'editor.suggest.showConstants': { type: 'boolean', default: true, markdownDescription: nls.localize(133, null) }, 'editor.suggest.showEnums': { type: 'boolean', default: true, markdownDescription: nls.localize(134, null) }, 'editor.suggest.showEnumMembers': { type: 'boolean', default: true, markdownDescription: nls.localize(135, null) }, 'editor.suggest.showKeywords': { type: 'boolean', default: true, markdownDescription: nls.localize(136, null) }, 'editor.suggest.showWords': { type: 'boolean', default: true, markdownDescription: nls.localize(137, null) }, 'editor.suggest.showColors': { type: 'boolean', default: true, markdownDescription: nls.localize(138, null) }, 'editor.suggest.showFiles': { type: 'boolean', default: true, markdownDescription: nls.localize(139, null) }, 'editor.suggest.showReferences': { type: 'boolean', default: true, markdownDescription: nls.localize(140, null) }, 'editor.suggest.showCustomcolors': { type: 'boolean', default: true, markdownDescription: nls.localize(141, null) }, 'editor.suggest.showFolders': { type: 'boolean', default: true, markdownDescription: nls.localize(142, null) }, 'editor.suggest.showTypeParameters': { type: 'boolean', default: true, markdownDescription: nls.localize(143, null) }, 'editor.suggest.showSnippets': { type: 'boolean', default: true, markdownDescription: nls.localize(144, null) }, 'editor.suggest.showUsers': { type: 'boolean', default: true, markdownDescription: nls.localize(145, null) }, 'editor.suggest.showIssues': { type: 'boolean', default: true, markdownDescription: nls.localize(146, 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(102 /* smartSelect */, 'smartSelect', { selectLeadingAndTrailingWhitespace: true }, { 'editor.smartSelect.selectLeadingAndTrailingWhitespace': { description: nls.localize(147, 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(130 /* tabFocusMode */); } compute(env, options, _) { const readOnly = options.get(81 /* 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(132 /* wrappingInfo */); } compute(env, options, _) { const layoutInfo = options.get(131 /* 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'; /** * @internal */ exports.EDITOR_FONT_DEFAULTS = { fontFamily: (platform.isMacintosh ? DEFAULT_MAC_FONT_FAMILY : (platform.isLinux ? DEFAULT_LINUX_FONT_FAMILY : DEFAULT_WINDOWS_FONT_FAMILY)), fontWeight: 'normal', fontSize: (platform.isMacintosh ? 12 : 14), lineHeight: 0, letterSpacing: 0, }; /** * @internal */ exports.editorOptionsRegistry = []; function register(option) { exports.editorOptionsRegistry[option.id] = option; return option; } exports.EditorOptions = { acceptSuggestionOnCommitCharacter: register(new EditorBooleanOption(0 /* acceptSuggestionOnCommitCharacter */, 'acceptSuggestionOnCommitCharacter', true, { markdownDescription: nls.localize(148, null) })), acceptSuggestionOnEnter: register(new EditorStringEnumOption(1 /* acceptSuggestionOnEnter */, 'acceptSuggestionOnEnter', 'on', ['on', 'smart', 'off'], { markdownEnumDescriptions: [ '', nls.localize(149, null), '' ], markdownDescription: nls.localize(150, null) })), accessibilitySupport: register(new EditorAccessibilitySupport()), accessibilityPageSize: register(new EditorIntOption(3 /* accessibilityPageSize */, 'accessibilityPageSize', 10, 1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(151, null) })), ariaLabel: register(new EditorStringOption(4 /* ariaLabel */, 'ariaLabel', nls.localize(152, null))), autoClosingBrackets: register(new EditorStringEnumOption(5 /* autoClosingBrackets */, 'autoClosingBrackets', 'languageDefined', ['always', 'languageDefined', 'beforeWhitespace', 'never'], { enumDescriptions: [ '', nls.localize(153, null), nls.localize(154, null), '', ], description: nls.localize(155, null) })), autoClosingDelete: register(new EditorStringEnumOption(6 /* autoClosingDelete */, 'autoClosingDelete', 'auto', ['always', 'auto', 'never'], { enumDescriptions: [ '', nls.localize(156, null), '', ], description: nls.localize(157, null) })), autoClosingOvertype: register(new EditorStringEnumOption(7 /* autoClosingOvertype */, 'autoClosingOvertype', 'auto', ['always', 'auto', 'never'], { enumDescriptions: [ '', nls.localize(158, null), '', ], description: nls.localize(159, null) })), autoClosingQuotes: register(new EditorStringEnumOption(8 /* autoClosingQuotes */, 'autoClosingQuotes', 'languageDefined', ['always', 'languageDefined', 'beforeWhitespace', 'never'], { enumDescriptions: [ '', nls.localize(160, null), nls.localize(161, null), '', ], description: nls.localize(162, null) })), autoIndent: register(new EditorEnumOption(9 /* autoIndent */, 'autoIndent', 4 /* Full */, 'full', ['none', 'keep', 'brackets', 'advanced', 'full'], _autoIndentFromString, { enumDescriptions: [ nls.localize(163, null), nls.localize(164, null), nls.localize(165, null), nls.localize(166, null), nls.localize(167, null), ], description: nls.localize(168, null) })), automaticLayout: register(new EditorBooleanOption(10 /* automaticLayout */, 'automaticLayout', false)), autoSurround: register(new EditorStringEnumOption(11 /* autoSurround */, 'autoSurround', 'languageDefined', ['languageDefined', 'quotes', 'brackets', 'never'], { enumDescriptions: [ nls.localize(169, null), nls.localize(170, null), nls.localize(171, null), '' ], description: nls.localize(172, null) })), bracketPairColorization: register(new BracketPairColorization()), bracketPairGuides: register(new GuideOptions()), stickyTabStops: register(new EditorBooleanOption(104 /* stickyTabStops */, 'stickyTabStops', false, { description: nls.localize(173, null) })), codeLens: register(new EditorBooleanOption(14 /* codeLens */, 'codeLens', true, { description: nls.localize(174, null) })), codeLensFontFamily: register(new EditorStringOption(15 /* codeLensFontFamily */, 'codeLensFontFamily', '', { description: nls.localize(175, null) })), codeLensFontSize: register(new EditorIntOption(16 /* codeLensFontSize */, 'codeLensFontSize', 0, 0, 100, { type: 'number', default: 0, minimum: 0, maximum: 100, markdownDescription: nls.localize(176, null) })), colorDecorators: register(new EditorBooleanOption(17 /* colorDecorators */, 'colorDecorators', true, { description: nls.localize(177, null) })), columnSelection: register(new EditorBooleanOption(18 /* columnSelection */, 'columnSelection', false, { description: nls.localize(178, null) })), comments: register(new EditorComments()), contextmenu: register(new EditorBooleanOption(20 /* contextmenu */, 'contextmenu', true)), copyWithSyntaxHighlighting: register(new EditorBooleanOption(21 /* copyWithSyntaxHighlighting */, 'copyWithSyntaxHighlighting', true, { description: nls.localize(179, null) })), cursorBlinking: register(new EditorEnumOption(22 /* cursorBlinking */, 'cursorBlinking', 1 /* Blink */, 'blink', ['blink', 'smooth', 'phase', 'expand', 'solid'], _cursorBlinkingStyleFromString, { description: nls.localize(180, null) })), cursorSmoothCaretAnimation: register(new EditorBooleanOption(23 /* cursorSmoothCaretAnimation */, 'cursorSmoothCaretAnimation', false, { description: nls.localize(181, null) })), cursorStyle: register(new EditorEnumOption(24 /* cursorStyle */, 'cursorStyle', TextEditorCursorStyle.Line, 'line', ['line', 'block', 'underline', 'line-thin', 'block-outline', 'underline-thin'], _cursorStyleFromString, { description: nls.localize(182, null) })), cursorSurroundingLines: register(new EditorIntOption(25 /* cursorSurroundingLines */, 'cursorSurroundingLines', 0, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(183, null) })), cursorSurroundingLinesStyle: register(new EditorStringEnumOption(26 /* cursorSurroundingLinesStyle */, 'cursorSurroundingLinesStyle', 'default', ['default', 'all'], { enumDescriptions: [ nls.localize(184, null), nls.localize(185, null) ], description: nls.localize(186, null) })), cursorWidth: register(new EditorIntOption(27 /* cursorWidth */, 'cursorWidth', 0, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { markdownDescription: nls.localize(187, null) })), disableLayerHinting: register(new EditorBooleanOption(28 /* disableLayerHinting */, 'disableLayerHinting', false)), disableMonospaceOptimizations: register(new EditorBooleanOption(29 /* disableMonospaceOptimizations */, 'disableMonospaceOptimizations', false)), domReadOnly: register(new EditorBooleanOption(30 /* domReadOnly */, 'domReadOnly', false)), dragAndDrop: register(new EditorBooleanOption(31 /* dragAndDrop */, 'dragAndDrop', true, { description: nls.localize(188, null) })), emptySelectionClipboard: register(new EditorEmptySelectionClipboard()), extraEditorClassName: register(new EditorStringOption(33 /* extraEditorClassName */, 'extraEditorClassName', '')), fastScrollSensitivity: register(new EditorFloatOption(34 /* fastScrollSensitivity */, 'fastScrollSensitivity', 5, x => (x <= 0 ? 5 : x), { markdownDescription: nls.localize(189, null) })), find: register(new EditorFind()), fixedOverflowWidgets: register(new EditorBooleanOption(36 /* fixedOverflowWidgets */, 'fixedOverflowWidgets', false)), folding: register(new EditorBooleanOption(37 /* folding */, 'folding', true, { description: nls.localize(190, null) })), foldingStrategy: register(new EditorStringEnumOption(38 /* foldingStrategy */, 'foldingStrategy', 'auto', ['auto', 'indentation'], { enumDescriptions: [ nls.localize(191, null), nls.localize(192, null), ], description: nls.localize(193, null) })), foldingHighlight: register(new EditorBooleanOption(39 /* foldingHighlight */, 'foldingHighlight', true, { description: nls.localize(194, null) })), foldingImportsByDefault: register(new EditorBooleanOption(40 /* foldingImportsByDefault */, 'foldingImportsByDefault', false, { description: nls.localize(195, null) })), foldingMaximumRegions: register(new EditorIntOption(41 /* foldingMaximumRegions */, 'foldingMaximumRegions', 5000, 10, 65000, // limit must be less than foldingRanges MAX_FOLDING_REGIONS { description: nls.localize(196, null) })), unfoldOnClickAfterEndOfLine: register(new EditorBooleanOption(42 /* unfoldOnClickAfterEndOfLine */, 'unfoldOnClickAfterEndOfLine', false, { description: nls.localize(197, null) })), fontFamily: register(new EditorStringOption(43 /* fontFamily */, 'fontFamily', exports.EDITOR_FONT_DEFAULTS.fontFamily, { description: nls.localize(198, null) })), fontInfo: register(new EditorFontInfo()), fontLigatures2: register(new EditorFontLigatures()), fontSize: register(new EditorFontSize()), fontWeight: register(new EditorFontWeight()), formatOnPaste: register(new EditorBooleanOption(48 /* formatOnPaste */, 'formatOnPaste', false, { description: nls.localize(199, null) })), formatOnType: register(new EditorBooleanOption(49 /* formatOnType */, 'formatOnType', false, { description: nls.localize(200, null) })), glyphMargin: register(new EditorBooleanOption(50 /* glyphMargin */, 'glyphMargin', true, { description: nls.localize(201, null) })), gotoLocation: register(new EditorGoToLocation()), hideCursorInOverviewRuler: register(new EditorBooleanOption(52 /* hideCursorInOverviewRuler */, 'hideCursorInOverviewRuler', false, { description: nls.localize(202, null) })), hover: register(new EditorHover()), inDiffEditor: register(new EditorBooleanOption(54 /* inDiffEditor */, 'inDiffEditor', false)), letterSpacing: register(new EditorFloatOption(56 /* letterSpacing */, 'letterSpacing', exports.EDITOR_FONT_DEFAULTS.letterSpacing, x => EditorFloatOption.clamp(x, -5, 20), { description: nls.localize(203, null) })), lightbulb: register(new EditorLightbulb()), lineDecorationsWidth: register(new SimpleEditorOption(58 /* lineDecorationsWidth */, 'lineDecorationsWidth', 10)), lineHeight: register(new EditorLineHeight()), lineNumbers: register(new EditorRenderLineNumbersOption()), lineNumbersMinChars: register(new EditorIntOption(61 /* lineNumbersMinChars */, 'lineNumbersMinChars', 5, 1, 300)), linkedEditing: register(new EditorBooleanOption(62 /* linkedEditing */, 'linkedEditing', false, { description: nls.localize(204, null) })), links: register(new EditorBooleanOption(63 /* links */, 'links', true, { description: nls.localize(205, null) })), matchBrackets: register(new EditorStringEnumOption(64 /* matchBrackets */, 'matchBrackets', 'always', ['always', 'near', 'never'], { description: nls.localize(206, null) })), minimap: register(new EditorMinimap()), mouseStyle: register(new EditorStringEnumOption(66 /* mouseStyle */, 'mouseStyle', 'text', ['text', 'default', 'copy'])), mouseWheelScrollSensitivity: register(new EditorFloatOption(67 /* mouseWheelScrollSensitivity */, 'mouseWheelScrollSensitivity', 1, x => (x === 0 ? 1 : x), { markdownDescription: nls.localize(207, null) })), mouseWheelZoom: register(new EditorBooleanOption(68 /* mouseWheelZoom */, 'mouseWheelZoom', false, { markdownDescription: nls.localize(208, null) })), multiCursorMergeOverlapping: register(new EditorBooleanOption(69 /* multiCursorMergeOverlapping */, 'multiCursorMergeOverlapping', true, { description: nls.localize(209, null) })), multiCursorModifier: register(new EditorEnumOption(70 /* multiCursorModifier */, 'multiCursorModifier', 'altKey', 'alt', ['ctrlCmd', 'alt'], _multiCursorModifierFromString, { markdownEnumDescriptions: [ nls.localize(210, null), nls.localize(211, null) ], markdownDescription: nls.localize(212, null) })), multiCursorPaste: register(new EditorStringEnumOption(71 /* multiCursorPaste */, 'multiCursorPaste', 'spread', ['spread', 'full'], { markdownEnumDescriptions: [ nls.localize(213, null), nls.localize(214, null) ], markdownDescription: nls.localize(215, null) })), occurrencesHighlight: register(new EditorBooleanOption(72 /* occurrencesHighlight */, 'occurrencesHighlight', true, { description: nls.localize(216, null) })), overviewRulerBorder: register(new EditorBooleanOption(73 /* overviewRulerBorder */, 'overviewRulerBorder', true, { description: nls.localize(217, null) })), overviewRulerLanes: register(new EditorIntOption(74 /* overviewRulerLanes */, 'overviewRulerLanes', 3, 0, 3)), padding: register(new EditorPadding()), parameterHints: register(new EditorParameterHints()), peekWidgetDefaultFocus: register(new EditorStringEnumOption(77 /* peekWidgetDefaultFocus */, 'peekWidgetDefaultFocus', 'tree', ['tree', 'editor'], { enumDescriptions: [ nls.localize(218, null), nls.localize(219, null) ], description: nls.localize(220, null) })), definitionLinkOpensInPeek: register(new EditorBooleanOption(78 /* definitionLinkOpensInPeek */, 'definitionLinkOpensInPeek', false, { description: nls.localize(221, null) })), quickSuggestions: register(new EditorQuickSuggestions()), quickSuggestionsDelay: register(new EditorIntOption(80 /* quickSuggestionsDelay */, 'quickSuggestionsDelay', 10, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(222, null) })), readOnly: register(new EditorBooleanOption(81 /* readOnly */, 'readOnly', false)), renameOnType: register(new EditorBooleanOption(82 /* renameOnType */, 'renameOnType', false, { description: nls.localize(223, null), markdownDeprecationMessage: nls.localize(224, null) })), renderControlCharacters: register(new EditorBooleanOption(83 /* renderControlCharacters */, 'renderControlCharacters', true, { description: nls.localize(225, null), restricted: true })), renderFinalNewline: register(new EditorBooleanOption(84 /* renderFinalNewline */, 'renderFinalNewline', true, { description: nls.localize(226, null) })), renderLineHighlight: register(new EditorStringEnumOption(85 /* renderLineHighlight */, 'renderLineHighlight', 'line', ['none', 'gutter', 'line', 'all'], { enumDescriptions: [ '', '', '', nls.localize(227, null), ], description: nls.localize(228, null) })), renderLineHighlightOnlyWhenFocus: register(new EditorBooleanOption(86 /* renderLineHighlightOnlyWhenFocus */, 'renderLineHighlightOnlyWhenFocus', false, { description: nls.localize(229, null) })), renderValidationDecorations: register(new EditorStringEnumOption(87 /* renderValidationDecorations */, 'renderValidationDecorations', 'editable', ['editable', 'on', 'off'])), renderWhitespace: register(new EditorStringEnumOption(88 /* renderWhitespace */, 'renderWhitespace', 'selection', ['none', 'boundary', 'selection', 'trailing', 'all'], { enumDescriptions: [ '', nls.localize(230, null), nls.localize(231, null), nls.localize(232, null), '' ], description: nls.localize(233, null) })), revealHorizontalRightPadding: register(new EditorIntOption(89 /* revealHorizontalRightPadding */, 'revealHorizontalRightPadding', 30, 0, 1000)), roundedSelection: register(new EditorBooleanOption(90 /* roundedSelection */, 'roundedSelection', true, { description: nls.localize(234, null) })), rulers: register(new EditorRulers()), scrollbar: register(new EditorScrollbar()), scrollBeyondLastColumn: register(new EditorIntOption(93 /* scrollBeyondLastColumn */, 'scrollBeyondLastColumn', 5, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(235, null) })), scrollBeyondLastLine: register(new EditorBooleanOption(94 /* scrollBeyondLastLine */, 'scrollBeyondLastLine', true, { description: nls.localize(236, null) })), scrollPredominantAxis: register(new EditorBooleanOption(95 /* scrollPredominantAxis */, 'scrollPredominantAxis', true, { description: nls.localize(237, null) })), selectionClipboard: register(new EditorBooleanOption(96 /* selectionClipboard */, 'selectionClipboard', true, { description: nls.localize(238, null), included: platform.isLinux })), selectionHighlight: register(new EditorBooleanOption(97 /* selectionHighlight */, 'selectionHighlight', true, { description: nls.localize(239, null) })), selectOnLineNumbers: register(new EditorBooleanOption(98 /* selectOnLineNumbers */, 'selectOnLineNumbers', true)), showFoldingControls: register(new EditorStringEnumOption(99 /* showFoldingControls */, 'showFoldingControls', 'mouseover', ['always', 'mouseover'], { enumDescriptions: [ nls.localize(240, null), nls.localize(241, null), ], description: nls.localize(242, null) })), showUnused: register(new EditorBooleanOption(100 /* showUnused */, 'showUnused', true, { description: nls.localize(243, null) })), showDeprecated: register(new EditorBooleanOption(126 /* showDeprecated */, 'showDeprecated', true, { description: nls.localize(244, null) })), inlayHints: register(new EditorInlayHints()), snippetSuggestions: register(new EditorStringEnumOption(101 /* snippetSuggestions */, 'snippetSuggestions', 'inline', ['top', 'bottom', 'inline', 'none'], { enumDescriptions: [ nls.localize(245, null), nls.localize(246, null), nls.localize(247, null), nls.localize(248, null), ], description: nls.localize(249, null) })), smartSelect: register(new SmartSelect()), smoothScrolling: register(new EditorBooleanOption(103 /* smoothScrolling */, 'smoothScrolling', false, { description: nls.localize(250, null) })), stopRenderingLineAfter: register(new EditorIntOption(105 /* stopRenderingLineAfter */, 'stopRenderingLineAfter', 10000, -1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */)), suggest: register(new EditorSuggest()), inlineSuggest: register(new InlineEditorSuggest()), suggestFontSize: register(new EditorIntOption(107 /* suggestFontSize */, 'suggestFontSize', 0, 0, 1000, { markdownDescription: nls.localize(251, null) })), suggestLineHeight: register(new EditorIntOption(108 /* suggestLineHeight */, 'suggestLineHeight', 0, 0, 1000, { markdownDescription: nls.localize(252, null) })), suggestOnTriggerCharacters: register(new EditorBooleanOption(109 /* suggestOnTriggerCharacters */, 'suggestOnTriggerCharacters', true, { description: nls.localize(253, null) })), suggestSelection: register(new EditorStringEnumOption(110 /* suggestSelection */, 'suggestSelection', 'first', ['first', 'recentlyUsed', 'recentlyUsedByPrefix'], { markdownEnumDescriptions: [ nls.localize(254, null), nls.localize(255, null), nls.localize(256, null), ], description: nls.localize(257, null) })), tabCompletion: register(new EditorStringEnumOption(111 /* tabCompletion */, 'tabCompletion', 'off', ['on', 'off', 'onlySnippets'], { enumDescriptions: [ nls.localize(258, null), nls.localize(259, null), nls.localize(260, null), ], description: nls.localize(261, null) })), tabIndex: register(new EditorIntOption(112 /* tabIndex */, 'tabIndex', 0, -1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */)), unicodeHighlight: register(new UnicodeHighlight()), unusualLineTerminators: register(new EditorStringEnumOption(114 /* unusualLineTerminators */, 'unusualLineTerminators', 'prompt', ['auto', 'off', 'prompt'], { enumDescriptions: [ nls.localize(262, null), nls.localize(263, null), nls.localize(264, null), ], description: nls.localize(265, null) })), useShadowDOM: register(new EditorBooleanOption(115 /* useShadowDOM */, 'useShadowDOM', true)), useTabStops: register(new EditorBooleanOption(116 /* useTabStops */, 'useTabStops', true, { description: nls.localize(266, null) })), wordSeparators: register(new EditorStringOption(117 /* wordSeparators */, 'wordSeparators', wordHelper_1.USUAL_WORD_SEPARATORS, { description: nls.localize(267, null) })), wordWrap: register(new EditorStringEnumOption(118 /* wordWrap */, 'wordWrap', 'off', ['off', 'on', 'wordWrapColumn', 'bounded'], { markdownEnumDescriptions: [ nls.localize(268, null), nls.localize(269, null), nls.localize(270, null), nls.localize(271, null), ], description: nls.localize(272, null) })), wordWrapBreakAfterCharacters: register(new EditorStringOption(119 /* wordWrapBreakAfterCharacters */, 'wordWrapBreakAfterCharacters', // allow-any-unicode-next-line ' \t})]?|/&.,;¢°′″‰℃、。。、¢,.:;?!%・・ゝゞヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻ァィゥェォャュョッー”〉》」』】〕)]}」')), wordWrapBreakBeforeCharacters: register(new EditorStringOption(120 /* wordWrapBreakBeforeCharacters */, 'wordWrapBreakBeforeCharacters', // allow-any-unicode-next-line '([{‘“〈《「『【〔([{「£¥$£¥++')), wordWrapColumn: register(new EditorIntOption(121 /* wordWrapColumn */, 'wordWrapColumn', 80, 1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { markdownDescription: nls.localize(273, null) })), wordWrapOverride1: register(new EditorStringEnumOption(122 /* wordWrapOverride1 */, 'wordWrapOverride1', 'inherit', ['off', 'on', 'inherit'])), wordWrapOverride2: register(new EditorStringEnumOption(123 /* wordWrapOverride2 */, 'wordWrapOverride2', 'inherit', ['off', 'on', 'inherit'])), wrappingIndent: register(new EditorEnumOption(124 /* wrappingIndent */, 'wrappingIndent', 1 /* Same */, 'same', ['none', 'same', 'indent', 'deepIndent'], _wrappingIndentFromString, { enumDescriptions: [ nls.localize(274, null), nls.localize(275, null), nls.localize(276, null), nls.localize(277, null), ], description: nls.localize(278, null), })), wrappingStrategy: register(new EditorStringEnumOption(125 /* wrappingStrategy */, 'wrappingStrategy', 'simple', ['simple', 'advanced'], { enumDescriptions: [ nls.localize(279, null), nls.localize(280, null) ], description: nls.localize(281, 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[62/*vs/editor/browser/config/domFontInfo*/], __M([1/*require*/,0/*exports*/,34/*vs/base/browser/browser*/,30/*vs/base/browser/fastDomNode*/,31/*vs/editor/common/config/editorOptions*/]), function (require, exports, browser, fastDomNode_1, editorOptions_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.applyFontInfo = void 0; function applyFontInfo(domNode, fontInfo) { if (domNode instanceof fastDomNode_1.FastDomNode) { domNode.setFontFamily(fontInfo.getMassagedFontFamily(browser.isSafari ? editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily : null)); domNode.setFontWeight(fontInfo.fontWeight); domNode.setFontSize(fontInfo.fontSize); domNode.setFontFeatureSettings(fontInfo.fontFeatureSettings); domNode.setLineHeight(fontInfo.lineHeight); domNode.setLetterSpacing(fontInfo.letterSpacing); } else { domNode.style.fontFamily = fontInfo.getMassagedFontFamily(browser.isSafari ? editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily : null); 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'; } } exports.applyFontInfo = applyFontInfo; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[507/*vs/editor/browser/config/charWidthReader*/], __M([1/*require*/,0/*exports*/,62/*vs/editor/browser/config/domFontInfo*/]), function (require, exports, domFontInfo_1) { "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'); (0, domFontInfo_1.applyFontInfo)(regularDomNode, this._bareFontInfo); container.appendChild(regularDomNode); const boldDomNode = document.createElement('div'); (0, domFontInfo_1.applyFontInfo)(boldDomNode, this._bareFontInfo); boldDomNode.style.fontWeight = 'bold'; container.appendChild(boldDomNode); const italicDomNode = document.createElement('div'); (0, domFontInfo_1.applyFontInfo)(italicDomNode, this._bareFontInfo); italicDomNode.style.fontStyle = 'italic'; container.appendChild(italicDomNode); const testElements = []; for (const request of this._requests) { let parent; if (request.type === 0 /* 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[266/*vs/editor/browser/config/fontMeasurements*/], __M([1/*require*/,0/*exports*/,34/*vs/base/browser/browser*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,507/*vs/editor/browser/config/charWidthReader*/,31/*vs/editor/common/config/editorOptions*/,174/*vs/editor/common/config/fontInfo*/]), function (require, exports, browser, event_1, lifecycle_1, charWidthReader_1, editorOptions_1, fontInfo_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FontMeasurements = void 0; class FontMeasurementsImpl extends lifecycle_1.Disposable { constructor() { super(); this._onDidChange = this._register(new event_1.Emitter()); this.onDidChange = this._onDidChange.event; this._cache = new FontMeasurementsCache(); this._evictUntrustedReadingsTimeout = -1; } dispose() { if (this._evictUntrustedReadingsTimeout !== -1) { window.clearTimeout(this._evictUntrustedReadingsTimeout); this._evictUntrustedReadingsTimeout = -1; } super.dispose(); } /** * Clear all cached font information and trigger a change event. */ clearAllFontInfos() { this._cache = new FontMeasurementsCache(); 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 = window.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(); } } /** * Read font information. */ readFontInfo(bareFontInfo) { if (!this._cache.has(bareFontInfo)) { let readConfig = this._actualReadFontInfo(bareFontInfo); if (readConfig.typicalHalfwidthCharacterWidth <= 2 || readConfig.typicalFullwidthCharacterWidth <= 2 || readConfig.spaceWidth <= 2 || readConfig.maxDigitWidth <= 2) { // Hey, it's Bug 14341 ... we couldn't read readConfig = new fontInfo_1.FontInfo({ pixelRatio: browser.PixelRatio.value, 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); } _createRequest(chr, type, all, monospace) { const result = new charWidthReader_1.CharWidthRequest(chr, type); all.push(result); if (monospace) { monospace.push(result); } return result; } _actualReadFontInfo(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 const monospaceTestChars = '|/-_ilm%'; for (let i = 0, len = monospaceTestChars.length; i < len; i++) { this._createRequest(monospaceTestChars.charAt(i), 0 /* Regular */, all, monospace); this._createRequest(monospaceTestChars.charAt(i), 1 /* Italic */, all, monospace); this._createRequest(monospaceTestChars.charAt(i), 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; } return new fontInfo_1.FontInfo({ pixelRatio: browser.PixelRatio.value, 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 }, true); } } class FontMeasurementsCache { constructor() { this._keys = Object.create(null); this._values = Object.create(null); } has(item) { const itemId = item.getId(); return !!this._values[itemId]; } get(item) { const itemId = item.getId(); return this._values[itemId]; } put(item, value) { const itemId = item.getId(); this._keys[itemId] = item; this._values[itemId] = value; } remove(item) { const itemId = item.getId(); delete this._keys[itemId]; delete this._values[itemId]; } getValues() { return Object.keys(this._keys).map(id => this._values[id]); } } exports.FontMeasurements = new FontMeasurementsImpl(); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[508/*vs/editor/browser/view/domLineBreaksComputer*/], __M([1/*require*/,0/*exports*/,90/*vs/editor/common/core/stringBuilder*/,8/*vs/base/common/strings*/,62/*vs/editor/browser/config/domFontInfo*/,91/*vs/editor/common/textModelEvents*/,251/*vs/editor/common/viewModel/modelLineProjectionData*/]), function (require, exports, stringBuilder_1, strings, domFontInfo_1, textModelEvents_1, modelLineProjectionData_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) { const requests = []; const 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 modelLineProjectionData_1.ModelLineProjectionData(injectionOffsets, injectionOptions, [lineText.length], [], 0); } else { return null; } } if (firstLineBreakColumn === -1) { const result = []; for (let i = 0, len = requests.length; i < len; i++) { result[i] = createEmptyLineBreakWithPossiblyInjectedText(i); } return result; } const overallWidth = Math.round(firstLineBreakColumn * fontInfo.typicalHalfwidthCharacterWidth); const additionalIndent = (wrappingIndent === 3 /* DeepIndent */ ? 2 : wrappingIndent === 2 /* Indent */ ? 1 : 0); const additionalIndentSize = Math.round(tabSize * additionalIndent); const additionalIndentLength = Math.ceil(fontInfo.spaceWidth * additionalIndentSize); const containerDomNode = document.createElement('div'); (0, domFontInfo_1.applyFontInfo)(containerDomNode, fontInfo); const sb = (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, additionalIndentLength); 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); const range = document.createRange(); const lineDomNodes = Array.prototype.slice.call(containerDomNode.children, 0); const result = []; for (let i = 0; i < requests.length; i++) { const lineDomNode = lineDomNodes[i]; const breakOffsets = readLineBreaks(range, lineDomNode, renderLineContents[i], allCharOffsets[i]); if (breakOffsets === null) { result[i] = createEmptyLineBreakWithPossiblyInjectedText(i); continue; } const firstNonWhitespaceIndex = firstNonWhitespaceIndices[i]; const wrappedTextIndentLength = wrappedTextIndentLengths[i] + additionalIndentSize; const visibleColumns = allVisibleColumns[i]; const breakOffsetsVisibleColumn = []; for (let j = 0, len = breakOffsets.length; j < len; j++) { breakOffsetsVisibleColumn[j] = visibleColumns[breakOffsets[j]]; } if (firstNonWhitespaceIndex !== 0) { // All break offsets are relative to the renderLineContent, make them absolute again for (let j = 0, len = breakOffsets.length; j < len; j++) { breakOffsets[j] += firstNonWhitespaceIndex; } } let injectionOptions; let injectionOffsets; const curInjectedTexts = injectedTextsPerLine[i]; if (curInjectedTexts) { injectionOptions = curInjectedTexts.map(t => t.options); injectionOffsets = curInjectedTexts.map(text => text.column - 1); } else { injectionOptions = null; injectionOffsets = null; } result[i] = new modelLineProjectionData_1.ModelLineProjectionData(injectionOffsets, injectionOptions, breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength); } document.body.removeChild(containerDomNode); return result; } function renderLine(lineContent, initialVisibleColumn, tabSize, width, sb, wrappingIndentLength) { if (wrappingIndentLength !== 0) { const hangingOffset = String(wrappingIndentLength); sb.appendASCIIString('
    '); // if (containsRTL) { // sb.appendASCIIString('" dir="ltr'); // } const len = lineContent.length; let visibleColumn = initialVisibleColumn; let charOffset = 0; const charOffsets = []; const visibleColumns = []; let nextCharCode = (0 < len ? lineContent.charCodeAt(0) : 0 /* Null */); sb.appendASCIIString(''); for (let charIndex = 0; charIndex < len; charIndex++) { if (charIndex !== 0 && charIndex % 16384 /* SPAN_MODULO_LIMIT */ === 0) { sb.appendASCIIString(''); } 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); //   } else { sb.appendASCII(32 /* Space */); } } break; case 32 /* Space */: if (nextCharCode === 32 /* Space */) { sb.write1(0xA0); //   } else { sb.appendASCII(32 /* Space */); } break; case 60 /* LessThan */: sb.appendASCIIString('<'); break; case 62 /* GreaterThan */: sb.appendASCIIString('>'); break; case 38 /* Ampersand */: sb.appendASCIIString('&'); break; case 0 /* Null */: sb.appendASCIIString('�'); 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(''); charOffsets[lineContent.length] = charOffset; visibleColumns[lineContent.length] = visibleColumn; sb.appendASCIIString('
    '); 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[509/*vs/editor/browser/view/viewOverlays*/], __M([1/*require*/,0/*exports*/,30/*vs/base/browser/fastDomNode*/,62/*vs/editor/browser/config/domFontInfo*/,176/*vs/editor/browser/view/viewLayer*/,50/*vs/editor/browser/view/viewPart*/]), function (require, exports, fastDomNode_1, domFontInfo_1, viewLayer_1, viewPart_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MarginViewOverlays = exports.ContentViewOverlays = exports.ViewOverlayLine = exports.ViewOverlays = void 0; class ViewOverlays extends viewPart_1.ViewPart { constructor(context) { super(context); this._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(59 /* 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(59 /* 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('
    '); sb.appendASCIIString(result); sb.appendASCIIString('
    '); 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(131 /* layoutInfo */); this._contentWidth = layoutInfo.contentWidth; this.domNode.setHeight(0); } // --- begin event handlers onConfigurationChanged(e) { const options = this._context.configuration.options; const layoutInfo = options.get(131 /* 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(131 /* layoutInfo */); this._contentLeft = layoutInfo.contentLeft; this.domNode.setClassName('margin-view-overlays'); this.domNode.setWidth(1); (0, domFontInfo_1.applyFontInfo)(this.domNode, options.get(44 /* fontInfo */)); } onConfigurationChanged(e) { const options = this._context.configuration.options; (0, domFontInfo_1.applyFontInfo)(this.domNode, options.get(44 /* fontInfo */)); const layoutInfo = options.get(131 /* 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[510/*vs/editor/browser/viewParts/viewCursors/viewCursor*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,8/*vs/base/common/strings*/,62/*vs/editor/browser/config/domFontInfo*/,31/*vs/editor/common/config/editorOptions*/,11/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,141/*vs/base/browser/ui/mouseCursor/mouseCursor*/]), function (require, exports, dom, fastDomNode_1, strings, domFontInfo_1, editorOptions_1, position_1, range_1, mouseCursor_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ViewCursor = 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(44 /* fontInfo */); this._cursorStyle = options.get(24 /* cursorStyle */); this._lineHeight = options.get(59 /* lineHeight */); this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth; this._lineCursorWidth = Math.min(options.get(27 /* cursorWidth */), this._typicalHalfwidthCharacterWidth); this._isVisible = true; // Create the dom node this._domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div')); this._domNode.setClassName(`cursor ${mouseCursor_1.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`); this._domNode.setHeight(this._lineHeight); this._domNode.setTop(0); this._domNode.setLeft(0); (0, domFontInfo_1.applyFontInfo)(this._domNode, fontInfo); this._domNode.setDisplay('none'); this._position = new position_1.Position(1, 1); this._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(44 /* fontInfo */); this._cursorStyle = options.get(24 /* cursorStyle */); this._lineHeight = options.get(59 /* lineHeight */); this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth; this._lineCursorWidth = Math.min(options.get(27 /* cursorWidth */), this._typicalHalfwidthCharacterWidth); (0, domFontInfo_1.applyFontInfo)(this._domNode, fontInfo); return true; } onCursorPositionChanged(position) { this._position = position; return true; } /** * If `this._position` is inside a grapheme, returns the position where the grapheme starts. * Also returns the next grapheme. */ _getGraphemeAwarePosition() { const { lineNumber, column } = this._position; const lineContent = this._context.model.getLineContent(lineNumber); const [startOffset, endOffset] = strings.getCharContainingOffset(lineContent, column - 1); return [new position_1.Position(lineNumber, startOffset + 1), lineContent.substring(startOffset, endOffset)]; } _prepareRender(ctx) { let textContent = ''; const [position, nextGrapheme] = this._getGraphemeAwarePosition(); if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Line || this._cursorStyle === editorOptions_1.TextEditorCursorStyle.LineThin) { const visibleRange = ctx.visibleRangeForPosition(position); if (!visibleRange || visibleRange.outsideRenderedLine) { // Outside viewport return null; } let width; if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Line) { width = dom.computeScreenAwareSize(this._lineCursorWidth > 0 ? this._lineCursorWidth : 2); if (width > 2) { textContent = nextGrapheme; } } else { width = dom.computeScreenAwareSize(1); } let left = visibleRange.left; if (width >= 2 && left >= 1) { // try to center cursor left -= 1; } const top = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.bigNumbersDelta; return new ViewCursorRenderData(top, left, width, this._lineHeight, textContent, ''); } const visibleRangeForCharacter = ctx.linesVisibleRangesForRange(new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column + nextGrapheme.length), false); if (!visibleRangeForCharacter || visibleRangeForCharacter.length === 0) { // Outside viewport return null; } const firstVisibleRangeForCharacter = visibleRangeForCharacter[0]; if (firstVisibleRangeForCharacter.outsideRenderedLine || firstVisibleRangeForCharacter.ranges.length === 0) { // Outside viewport return null; } const range = firstVisibleRangeForCharacter.ranges[0]; const width = range.width < 1 ? this._typicalHalfwidthCharacterWidth : range.width; let textContentClassName = ''; if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Block) { const lineData = this._context.model.getViewLineData(position.lineNumber); textContent = nextGrapheme; const tokenIndex = lineData.tokens.findTokenIndexAtOffset(position.column - 1); textContentClassName = lineData.tokens.getClassName(tokenIndex); } let top = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.bigNumbersDelta; let height = this._lineHeight; // Underline might interfere with clicking if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Underline || this._cursorStyle === editorOptions_1.TextEditorCursorStyle.UnderlineThin) { top += this._lineHeight - 2; height = 2; } return new ViewCursorRenderData(top, range.left, 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[267/*vs/editor/common/viewModel/viewModelDecorations*/], __M([1/*require*/,0/*exports*/,11/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,69/*vs/editor/common/viewModel/viewModel*/,31/*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.isModelDecorationInString = exports.isModelDecorationInComment = exports.isModelDecorationVisible = 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; const decorationsInViewport = []; let decorationsInViewportLen = 0; const inlineDecorations = []; for (let j = startLineNumber; j <= endLineNumber; j++) { inlineDecorations[j - startLineNumber] = []; } for (let i = 0, len = modelDecorations.length; i < len; i++) { const modelDecoration = modelDecorations[i]; const decorationOptions = modelDecoration.options; if (!isModelDecorationVisible(this.model, modelDecoration)) { continue; } const viewModelDecoration = this._getOrCreateViewModelDecoration(modelDecoration); const viewRange = viewModelDecoration.range; decorationsInViewport[decorationsInViewportLen++] = viewModelDecoration; if (decorationOptions.inlineClassName) { const inlineDecoration = new viewModel_1.InlineDecoration(viewRange, decorationOptions.inlineClassName, decorationOptions.inlineClassNameAffectsLetterSpacing ? 3 /* RegularAffectingLetterSpacing */ : 0 /* Regular */); const intersectedStartLineNumber = Math.max(startLineNumber, viewRange.startLineNumber); const intersectedEndLineNumber = Math.min(endLineNumber, viewRange.endLineNumber); for (let j = intersectedStartLineNumber; j <= intersectedEndLineNumber; j++) { inlineDecorations[j - startLineNumber].push(inlineDecoration); } } if (decorationOptions.beforeContentClassName) { if (startLineNumber <= viewRange.startLineNumber && viewRange.startLineNumber <= endLineNumber) { const inlineDecoration = new viewModel_1.InlineDecoration(new range_1.Range(viewRange.startLineNumber, viewRange.startColumn, viewRange.startLineNumber, viewRange.startColumn), decorationOptions.beforeContentClassName, 1 /* Before */); inlineDecorations[viewRange.startLineNumber - startLineNumber].push(inlineDecoration); } } if (decorationOptions.afterContentClassName) { if (startLineNumber <= viewRange.endLineNumber && viewRange.endLineNumber <= endLineNumber) { const inlineDecoration = new viewModel_1.InlineDecoration(new range_1.Range(viewRange.endLineNumber, viewRange.endColumn, viewRange.endLineNumber, viewRange.endColumn), decorationOptions.afterContentClassName, 2 /* After */); inlineDecorations[viewRange.endLineNumber - startLineNumber].push(inlineDecoration); } } } return { decorations: decorationsInViewport, inlineDecorations: inlineDecorations }; } } exports.ViewModelDecorations = ViewModelDecorations; function isModelDecorationVisible(model, decoration) { if (decoration.options.hideInCommentTokens && isModelDecorationInComment(model, decoration)) { return false; } if (decoration.options.hideInStringTokens && isModelDecorationInString(model, decoration)) { return false; } return true; } exports.isModelDecorationVisible = isModelDecorationVisible; function isModelDecorationInComment(model, decoration) { return testTokensInRange(model, decoration.range, (tokenType) => tokenType === 1 /* Comment */); } exports.isModelDecorationInComment = isModelDecorationInComment; function isModelDecorationInString(model, decoration) { return testTokensInRange(model, decoration.range, (tokenType) => tokenType === 2 /* String */); } exports.isModelDecorationInString = isModelDecorationInString; /** * Calls the callback for every token that intersects the range. * If the callback returns `false`, iteration stops and `false` is returned. * Otherwise, `true` is returned. */ function testTokensInRange(model, range, callback) { for (let lineNumber = range.startLineNumber; lineNumber <= range.endLineNumber; lineNumber++) { const lineTokens = model.getLineTokens(lineNumber); const isFirstLine = lineNumber === range.startLineNumber; const isEndLine = lineNumber === range.endLineNumber; let tokenIdx = isFirstLine ? lineTokens.findTokenIndexAtOffset(range.startColumn - 1) : 0; while (tokenIdx < lineTokens.getCount()) { if (isEndLine) { const startOffset = lineTokens.getStartOffset(tokenIdx); if (startOffset > range.endColumn - 1) { break; } } const callbackResult = callback(lineTokens.getStandardTokenType(tokenIdx)); if (!callbackResult) { return false; } tokenIdx++; } } return true; } }); define(__m[511/*vs/nls!vs/editor/common/core/editorColorRegistry*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/core/editorColorRegistry", data); }); define(__m[512/*vs/nls!vs/editor/common/editorContextKeys*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/editorContextKeys", data); }); define(__m[513/*vs/nls!vs/editor/common/languages/modesRegistry*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/languages/modesRegistry", data); }); define(__m[514/*vs/nls!vs/editor/common/model/editStack*/], __M([5/*vs/nls*/,6/*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[268/*vs/editor/common/model/editStack*/], __M([1/*require*/,0/*exports*/,514/*vs/nls!vs/editor/common/model/editStack*/,13/*vs/base/common/errors*/,22/*vs/editor/common/core/selection*/,25/*vs/base/common/uri*/,237/*vs/editor/common/core/textChange*/,110/*vs/base/common/buffer*/,41/*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[515/*vs/nls!vs/editor/common/standaloneStrings*/], __M([5/*vs/nls*/,6/*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[70/*vs/editor/common/standaloneStrings*/], __M([1/*require*/,0/*exports*/,515/*vs/nls!vs/editor/common/standaloneStrings*/]), function (require, exports, nls) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.StandaloneServicesNLS = exports.ToggleHighContrastNLS = exports.StandaloneCodeEditorNLS = exports.QuickOutlineNLS = exports.QuickCommandNLS = exports.QuickHelpNLS = exports.GoToLineNLS = exports.InspectTokensNLS = 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 StandaloneServicesNLS; (function (StandaloneServicesNLS) { StandaloneServicesNLS.bulkEditServiceSummary = nls.localize(33, null); })(StandaloneServicesNLS = exports.StandaloneServicesNLS || (exports.StandaloneServicesNLS = {})); }); define(__m[516/*vs/nls!vs/editor/contrib/anchorSelect/browser/anchorSelect*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/anchorSelect/browser/anchorSelect", data); }); define(__m[517/*vs/nls!vs/editor/contrib/bracketMatching/browser/bracketMatching*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/bracketMatching/browser/bracketMatching", data); }); define(__m[518/*vs/nls!vs/editor/contrib/caretOperations/browser/caretOperations*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/caretOperations/browser/caretOperations", data); }); define(__m[519/*vs/nls!vs/editor/contrib/caretOperations/browser/transpose*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/caretOperations/browser/transpose", data); }); define(__m[520/*vs/nls!vs/editor/contrib/clipboard/browser/clipboard*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/clipboard/browser/clipboard", data); }); define(__m[521/*vs/nls!vs/editor/contrib/codeAction/browser/codeActionCommands*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/codeAction/browser/codeActionCommands", data); }); define(__m[522/*vs/nls!vs/editor/contrib/codeAction/browser/lightBulbWidget*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/codeAction/browser/lightBulbWidget", data); }); define(__m[523/*vs/nls!vs/editor/contrib/codelens/browser/codelensController*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/codelens/browser/codelensController", data); }); define(__m[524/*vs/nls!vs/editor/contrib/colorPicker/browser/colorPickerWidget*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/colorPicker/browser/colorPickerWidget", data); }); define(__m[525/*vs/nls!vs/editor/contrib/comment/browser/comment*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/comment/browser/comment", data); }); define(__m[526/*vs/nls!vs/editor/contrib/contextmenu/browser/contextmenu*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/contextmenu/browser/contextmenu", data); }); define(__m[527/*vs/nls!vs/editor/contrib/cursorUndo/browser/cursorUndo*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/cursorUndo/browser/cursorUndo", data); }); define(__m[528/*vs/nls!vs/editor/contrib/editorState/browser/keybindingCancellation*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/editorState/browser/keybindingCancellation", data); }); define(__m[529/*vs/nls!vs/editor/contrib/find/browser/findController*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/find/browser/findController", data); }); define(__m[530/*vs/nls!vs/editor/contrib/find/browser/findWidget*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/find/browser/findWidget", data); }); define(__m[531/*vs/nls!vs/editor/contrib/folding/browser/folding*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/folding/browser/folding", data); }); define(__m[532/*vs/nls!vs/editor/contrib/folding/browser/foldingDecorations*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/folding/browser/foldingDecorations", data); }); define(__m[533/*vs/nls!vs/editor/contrib/fontZoom/browser/fontZoom*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/fontZoom/browser/fontZoom", data); }); define(__m[534/*vs/nls!vs/editor/contrib/format/browser/format*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/format/browser/format", data); }); define(__m[535/*vs/nls!vs/editor/contrib/format/browser/formatActions*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/format/browser/formatActions", data); }); define(__m[536/*vs/nls!vs/editor/contrib/gotoError/browser/gotoError*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoError/browser/gotoError", data); }); define(__m[537/*vs/nls!vs/editor/contrib/gotoError/browser/gotoErrorWidget*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoError/browser/gotoErrorWidget", data); }); define(__m[538/*vs/nls!vs/editor/contrib/gotoSymbol/browser/goToCommands*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/browser/goToCommands", data); }); define(__m[539/*vs/nls!vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition", data); }); define(__m[540/*vs/nls!vs/editor/contrib/gotoSymbol/browser/peek/referencesController*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/browser/peek/referencesController", data); }); define(__m[541/*vs/nls!vs/editor/contrib/gotoSymbol/browser/peek/referencesTree*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/browser/peek/referencesTree", data); }); define(__m[542/*vs/nls!vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget", data); }); define(__m[543/*vs/nls!vs/editor/contrib/gotoSymbol/browser/referencesModel*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/browser/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[126/*vs/editor/contrib/gotoSymbol/browser/referencesModel*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/errors*/,4/*vs/base/common/event*/,133/*vs/base/common/idGenerator*/,2/*vs/base/common/lifecycle*/,47/*vs/base/common/map*/,41/*vs/base/common/resources*/,8/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/,543/*vs/nls!vs/editor/contrib/gotoSymbol/browser/referencesModel*/]), function (require, exports, errors_1, event_1, idGenerator_1, lifecycle_1, map_1, resources_1, strings, range_1, nls_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ReferencesModel = exports.FileReferences = exports.FilePreview = exports.OneReference = void 0; class OneReference { constructor(isProviderFirst, parent, link, _rangeCallback) { this.isProviderFirst = isProviderFirst; this.parent = parent; this.link = link; this._rangeCallback = _rangeCallback; this.id = idGenerator_1.defaultGenerator.nextId(); } get uri() { return this.link.uri; } get range() { 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[544/*vs/nls!vs/editor/contrib/gotoSymbol/browser/symbolNavigation*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/browser/symbolNavigation", data); }); define(__m[545/*vs/nls!vs/editor/contrib/hover/browser/hover*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/browser/hover", data); }); define(__m[546/*vs/nls!vs/editor/contrib/hover/browser/markdownHoverParticipant*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/browser/markdownHoverParticipant", data); }); define(__m[547/*vs/nls!vs/editor/contrib/hover/browser/markerHoverParticipant*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/browser/markerHoverParticipant", data); }); define(__m[548/*vs/nls!vs/editor/contrib/inPlaceReplace/browser/inPlaceReplace*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/inPlaceReplace/browser/inPlaceReplace", data); }); define(__m[549/*vs/nls!vs/editor/contrib/indentation/browser/indentation*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/indentation/browser/indentation", data); }); define(__m[550/*vs/nls!vs/editor/contrib/inlineCompletions/browser/ghostTextController*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/inlineCompletions/browser/ghostTextController", data); }); define(__m[551/*vs/nls!vs/editor/contrib/inlineCompletions/browser/inlineCompletionsHoverParticipant*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/inlineCompletions/browser/inlineCompletionsHoverParticipant", data); }); define(__m[552/*vs/nls!vs/editor/contrib/lineSelection/browser/lineSelection*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/lineSelection/browser/lineSelection", data); }); define(__m[553/*vs/nls!vs/editor/contrib/linesOperations/browser/linesOperations*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/linesOperations/browser/linesOperations", data); }); define(__m[554/*vs/nls!vs/editor/contrib/linkedEditing/browser/linkedEditing*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/linkedEditing/browser/linkedEditing", data); }); define(__m[555/*vs/nls!vs/editor/contrib/links/browser/links*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/links/browser/links", data); }); define(__m[556/*vs/nls!vs/editor/contrib/message/browser/messageController*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/message/browser/messageController", data); }); define(__m[557/*vs/nls!vs/editor/contrib/multicursor/browser/multicursor*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/multicursor/browser/multicursor", data); }); define(__m[558/*vs/nls!vs/editor/contrib/parameterHints/browser/parameterHints*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/parameterHints/browser/parameterHints", data); }); define(__m[559/*vs/nls!vs/editor/contrib/parameterHints/browser/parameterHintsWidget*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/parameterHints/browser/parameterHintsWidget", data); }); define(__m[560/*vs/nls!vs/editor/contrib/peekView/browser/peekView*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/peekView/browser/peekView", data); }); define(__m[561/*vs/nls!vs/editor/contrib/quickAccess/browser/gotoLineQuickAccess*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/quickAccess/browser/gotoLineQuickAccess", data); }); define(__m[562/*vs/nls!vs/editor/contrib/quickAccess/browser/gotoSymbolQuickAccess*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/quickAccess/browser/gotoSymbolQuickAccess", data); }); define(__m[563/*vs/nls!vs/editor/contrib/rename/browser/rename*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/rename/browser/rename", data); }); define(__m[564/*vs/nls!vs/editor/contrib/rename/browser/renameInputField*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/rename/browser/renameInputField", data); }); define(__m[565/*vs/nls!vs/editor/contrib/smartSelect/browser/smartSelect*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/smartSelect/browser/smartSelect", data); }); define(__m[566/*vs/nls!vs/editor/contrib/snippet/browser/snippetController2*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/snippet/browser/snippetController2", data); }); define(__m[567/*vs/nls!vs/editor/contrib/snippet/browser/snippetVariables*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/snippet/browser/snippetVariables", data); }); define(__m[568/*vs/nls!vs/editor/contrib/suggest/browser/suggest*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/browser/suggest", data); }); define(__m[569/*vs/nls!vs/editor/contrib/suggest/browser/suggestController*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/browser/suggestController", data); }); define(__m[570/*vs/nls!vs/editor/contrib/suggest/browser/suggestWidget*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/browser/suggestWidget", data); }); define(__m[571/*vs/nls!vs/editor/contrib/suggest/browser/suggestWidgetDetails*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/browser/suggestWidgetDetails", data); }); define(__m[572/*vs/nls!vs/editor/contrib/suggest/browser/suggestWidgetRenderer*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/browser/suggestWidgetRenderer", data); }); define(__m[573/*vs/nls!vs/editor/contrib/suggest/browser/suggestWidgetStatus*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/browser/suggestWidgetStatus", data); }); define(__m[574/*vs/nls!vs/editor/contrib/symbolIcons/browser/symbolIcons*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/symbolIcons/browser/symbolIcons", data); }); define(__m[575/*vs/nls!vs/editor/contrib/toggleTabFocusMode/browser/toggleTabFocusMode*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/toggleTabFocusMode/browser/toggleTabFocusMode", data); }); define(__m[576/*vs/nls!vs/editor/contrib/tokenization/browser/tokenization*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/tokenization/browser/tokenization", data); }); define(__m[577/*vs/nls!vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter", data); }); define(__m[578/*vs/nls!vs/editor/contrib/unusualLineTerminators/browser/unusualLineTerminators*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/unusualLineTerminators/browser/unusualLineTerminators", data); }); define(__m[579/*vs/nls!vs/editor/contrib/wordHighlighter/browser/wordHighlighter*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/wordHighlighter/browser/wordHighlighter", data); }); define(__m[580/*vs/nls!vs/editor/contrib/wordOperations/browser/wordOperations*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/wordOperations/browser/wordOperations", data); }); define(__m[581/*vs/nls!vs/platform/actions/browser/menuEntryActionViewItem*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/actions/browser/menuEntryActionViewItem", data); }); define(__m[582/*vs/nls!vs/platform/configuration/common/configurationRegistry*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/configuration/common/configurationRegistry", data); }); define(__m[583/*vs/nls!vs/platform/contextkey/browser/contextKeyService*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/contextkey/browser/contextKeyService", data); }); define(__m[584/*vs/nls!vs/platform/contextkey/common/contextkeys*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/contextkey/common/contextkeys", data); }); define(__m[585/*vs/nls!vs/platform/keybinding/common/abstractKeybindingService*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/keybinding/common/abstractKeybindingService", data); }); define(__m[586/*vs/nls!vs/platform/list/browser/listService*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/list/browser/listService", data); }); define(__m[587/*vs/nls!vs/platform/markers/common/markers*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/markers/common/markers", data); }); define(__m[588/*vs/nls!vs/platform/quickinput/browser/commandsQuickAccess*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/quickinput/browser/commandsQuickAccess", data); }); define(__m[589/*vs/nls!vs/platform/quickinput/browser/helpQuickAccess*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/quickinput/browser/helpQuickAccess", data); }); define(__m[590/*vs/nls!vs/platform/theme/common/colorRegistry*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/theme/common/colorRegistry", data); }); define(__m[591/*vs/nls!vs/platform/theme/common/iconRegistry*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/theme/common/iconRegistry", data); }); define(__m[592/*vs/nls!vs/platform/undoRedo/common/undoRedoService*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/undoRedo/common/undoRedoService", data); }); define(__m[593/*vs/nls!vs/platform/workspaces/common/workspaces*/], __M([5/*vs/nls*/,6/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/workspaces/common/workspaces", data); }); define(__m[594/*vs/platform/editor/common/editor*/], __M([1/*require*/,0/*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[595/*vs/platform/extensions/common/extensions*/], __M([1/*require*/,0/*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[269/*vs/platform/files/common/files*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FileKind = void 0; //#region Utilities var FileKind; (function (FileKind) { FileKind[FileKind["FILE"] = 0] = "FILE"; FileKind[FileKind["FOLDER"] = 1] = "FOLDER"; FileKind[FileKind["ROOT_FOLDER"] = 2] = "ROOT_FOLDER"; })(FileKind = exports.FileKind || (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[596/*vs/platform/history/browser/historyWidgetKeybindingHint*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.showHistoryKeybindingHint = void 0; function showHistoryKeybindingHint(keybindingService) { var _a, _b; return ((_a = keybindingService.lookupKeybinding('history.showPrevious')) === null || _a === void 0 ? void 0 : _a.getElectronAccelerator()) === 'Up' && ((_b = keybindingService.lookupKeybinding('history.showNext')) === null || _b === void 0 ? void 0 : _b.getElectronAccelerator()) === 'Down'; } exports.showHistoryKeybindingHint = showHistoryKeybindingHint; }); /*--------------------------------------------------------------------------------------------- * 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/platform/instantiation/common/descriptors*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SyncDescriptor = void 0; class SyncDescriptor { constructor(ctor, staticArguments = [], supportsDelayedInstantiation = false) { this.ctor = ctor; this.staticArguments = staticArguments; this.supportsDelayedInstantiation = supportsDelayedInstantiation; } } exports.SyncDescriptor = SyncDescriptor; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[53/*vs/platform/instantiation/common/extensions*/], __M([1/*require*/,0/*exports*/,194/*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[597/*vs/platform/instantiation/common/graph*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Graph = exports.Node = void 0; class Node { constructor(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([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }); /*--------------------------------------------------------------------------------------------- * 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/browser/services/bulkEditService*/], __M([1/*require*/,0/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,25/*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([1/*require*/,0/*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[85/*vs/editor/common/services/editorWorker*/], __M([1/*require*/,0/*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[35/*vs/editor/common/services/language*/], __M([1/*require*/,0/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ILanguageService = void 0; exports.ILanguageService = (0, instantiation_1.createDecorator)('languageService'); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[196/*vs/editor/common/services/markerDecorations*/], __M([1/*require*/,0/*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[45/*vs/editor/common/services/model*/], __M([1/*require*/,0/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IModelService = void 0; exports.IModelService = (0, instantiation_1.createDecorator)('modelService'); }); /*--------------------------------------------------------------------------------------------- * 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/editor/common/services/resolverService*/], __M([1/*require*/,0/*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[153/*vs/editor/common/services/textResourceConfiguration*/], __M([1/*require*/,0/*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[101/*vs/editor/standalone/common/standaloneTheme*/], __M([1/*require*/,0/*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'); }); define(__m[102/*vs/platform/clipboard/common/clipboardService*/], __M([1/*require*/,0/*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([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,54/*vs/base/common/iterator*/,2/*vs/base/common/lifecycle*/,81/*vs/base/common/linkedList*/,20/*vs/base/common/types*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, event_1, iterator_1, lifecycle_1, linkedList_1, types_1, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NullCommandService = 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.NullCommandService = { _serviceBrand: undefined, onWillExecuteCommand: () => lifecycle_1.Disposable.None, onDidExecuteCommand: () => lifecycle_1.Disposable.None, executeCommand() { return Promise.resolve(undefined); } }; 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[270/*vs/editor/common/services/getSemanticTokens*/], __M([1/*require*/,0/*exports*/,21/*vs/base/common/cancellation*/,13/*vs/base/common/errors*/,25/*vs/base/common/uri*/,18/*vs/editor/common/languages*/,45/*vs/editor/common/services/model*/,26/*vs/platform/commands/common/commands*/,20/*vs/base/common/types*/,423/*vs/editor/common/services/semanticTokensDto*/,3/*vs/editor/common/core/range*/]), function (require, exports, cancellation_1, errors_1, uri_1, languages_1, model_1, commands_1, types_1, semanticTokensDto_1, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getDocumentRangeSemanticTokens = exports.hasDocumentRangeSemanticTokensProvider = exports.getDocumentSemanticTokens = exports.hasDocumentSemanticTokensProvider = exports.DocumentSemanticTokensResult = 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; class DocumentSemanticTokensResult { constructor(provider, tokens, error) { this.provider = provider; this.tokens = tokens; this.error = error; } } exports.DocumentSemanticTokensResult = DocumentSemanticTokensResult; function hasDocumentSemanticTokensProvider(model) { return languages_1.DocumentSemanticTokensProviderRegistry.has(model); } exports.hasDocumentSemanticTokensProvider = hasDocumentSemanticTokensProvider; function getDocumentSemanticTokensProviders(model) { const groups = languages_1.DocumentSemanticTokensProviderRegistry.orderedGroups(model); return (groups.length > 0 ? groups[0] : []); } function getDocumentSemanticTokens(model, lastProvider, lastResultId, token) { return __awaiter(this, void 0, void 0, function* () { const providers = getDocumentSemanticTokensProviders(model); // Get tokens from all providers at the same time. const results = yield Promise.all(providers.map((provider) => __awaiter(this, void 0, void 0, function* () { let result; let error = null; try { result = yield provider.provideDocumentSemanticTokens(model, (provider === lastProvider ? lastResultId : null), token); } catch (err) { error = err; result = null; } if (!result || (!isSemanticTokens(result) && !isSemanticTokensEdits(result))) { result = null; } return new DocumentSemanticTokensResult(provider, result, error); }))); // Try to return the first result with actual tokens or // the first result which threw an error (!!) for (const result of results) { if (result.error) { throw result.error; } if (result.tokens) { return result; } } // Return the first result, even if it doesn't have tokens if (results.length > 0) { return results[0]; } return null; }); } exports.getDocumentSemanticTokens = getDocumentSemanticTokens; function _getDocumentSemanticTokensProviderHighestGroup(model) { const result = languages_1.DocumentSemanticTokensProviderRegistry.orderedGroups(model); return (result.length > 0 ? result[0] : null); } class DocumentRangeSemanticTokensResult { constructor(provider, tokens) { this.provider = provider; this.tokens = tokens; } } function hasDocumentRangeSemanticTokensProvider(model) { return languages_1.DocumentRangeSemanticTokensProviderRegistry.has(model); } exports.hasDocumentRangeSemanticTokensProvider = hasDocumentRangeSemanticTokensProvider; function getDocumentRangeSemanticTokensProviders(model) { const groups = languages_1.DocumentRangeSemanticTokensProviderRegistry.orderedGroups(model); return (groups.length > 0 ? groups[0] : []); } function getDocumentRangeSemanticTokens(model, range, token) { return __awaiter(this, void 0, void 0, function* () { const providers = getDocumentRangeSemanticTokensProviders(model); // Get tokens from all providers at the same time. const results = yield Promise.all(providers.map((provider) => __awaiter(this, void 0, void 0, function* () { let result; try { result = yield provider.provideDocumentRangeSemanticTokens(model, range, token); } catch (err) { (0, errors_1.onUnexpectedExternalError)(err); result = null; } if (!result || !isSemanticTokens(result)) { result = null; } return new DocumentRangeSemanticTokensResult(provider, result); }))); // Try to return the first result with actual tokens for (const result of results) { if (result.tokens) { return result; } } // Return the first result, even if it doesn't have tokens if (results.length > 0) { return results[0]; } return null; }); } exports.getDocumentRangeSemanticTokens = getDocumentRangeSemanticTokens; 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(model_1.IModelService).getModel(uri); if (!model) { return undefined; } const providers = _getDocumentSemanticTokensProviderHighestGroup(model); if (!providers) { // there is no provider => fall back to a document range semantic tokens provider return accessor.get(commands_1.ICommandService).executeCommand('_provideDocumentRangeSemanticTokensLegend', uri); } return providers[0].getLegend(); })); commands_1.CommandsRegistry.registerCommand('_provideDocumentSemanticTokens', (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(model_1.IModelService).getModel(uri); if (!model) { return undefined; } if (!hasDocumentSemanticTokensProvider(model)) { // there is no provider => fall back to a document range semantic tokens provider return accessor.get(commands_1.ICommandService).executeCommand('_provideDocumentRangeSemanticTokens', uri, model.getFullModelRange()); } const r = yield getDocumentSemanticTokens(model, null, null, cancellation_1.CancellationToken.None); if (!r) { return undefined; } const { provider, tokens } = r; if (!tokens || !isSemanticTokens(tokens)) { return undefined; } const buff = (0, semanticTokensDto_1.encodeSemanticTokensDto)({ id: 0, type: 'full', data: tokens.data }); if (tokens.resultId) { provider.releaseDocumentSemanticTokens(tokens.resultId); } return buff; })); commands_1.CommandsRegistry.registerCommand('_provideDocumentRangeSemanticTokensLegend', (accessor, ...args) => __awaiter(void 0, void 0, void 0, function* () { const [uri, range] = args; (0, types_1.assertType)(uri instanceof uri_1.URI); const model = accessor.get(model_1.IModelService).getModel(uri); if (!model) { return undefined; } const providers = getDocumentRangeSemanticTokensProviders(model); if (providers.length === 0) { // no providers return undefined; } if (providers.length === 1) { // straight forward case, just a single provider return providers[0].getLegend(); } if (!range || !range_1.Range.isIRange(range)) { // if no range is provided, we cannot support multiple providers // as we cannot fall back to the one which would give results // => return the first legend for backwards compatibility and print a warning console.warn(`provideDocumentRangeSemanticTokensLegend might be out-of-sync with provideDocumentRangeSemanticTokens unless a range argument is passed in`); return providers[0].getLegend(); } const result = yield getDocumentRangeSemanticTokens(model, range_1.Range.lift(range), cancellation_1.CancellationToken.None); if (!result) { return undefined; } return result.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(model_1.IModelService).getModel(uri); if (!model) { return undefined; } const result = yield getDocumentRangeSemanticTokens(model, range_1.Range.lift(range), cancellation_1.CancellationToken.None); if (!result || !result.tokens) { // there is no provider or it didn't return tokens return undefined; } return (0, semanticTokensDto_1.encodeSemanticTokensDto)({ id: 0, type: 'full', data: result.tokens.data }); })); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[271/*vs/editor/contrib/codelens/browser/codelens*/], __M([1/*require*/,0/*exports*/,21/*vs/base/common/cancellation*/,13/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/,25/*vs/base/common/uri*/,18/*vs/editor/common/languages*/,45/*vs/editor/common/services/model*/,26/*vs/platform/commands/common/commands*/]), function (require, exports, cancellation_1, errors_1, lifecycle_1, types_1, uri_1, languages_1, model_1, commands_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(); } get isDisposed() { return this._disposables.isDisposed; } add(list, provider) { this._disposables.add(list); for (const symbol of list.lenses) { this.lenses.push({ symbol, provider }); } } } exports.CodeLensModel = CodeLensModel; function getCodeLensModel(model, token) { return __awaiter(this, void 0, void 0, function* () { const provider = languages_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(model_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[272/*vs/editor/contrib/colorPicker/browser/color*/], __M([1/*require*/,0/*exports*/,21/*vs/base/common/cancellation*/,13/*vs/base/common/errors*/,25/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/languages*/,45/*vs/editor/common/services/model*/,26/*vs/platform/commands/common/commands*/]), function (require, exports, cancellation_1, errors_1, uri_1, range_1, languages_1, model_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 = languages_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(model_1.IModelService).getModel(resource); if (!model) { throw (0, errors_1.illegalArgument)(); } const rawCIs = []; const providers = languages_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(model_1.IModelService).getModel(uri); if (!model) { throw (0, errors_1.illegalArgument)(); } const colorInfo = { range, color: { red, green, blue, alpha } }; const presentations = []; const providers = languages_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[598/*vs/editor/contrib/links/browser/getLinks*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,21/*vs/base/common/cancellation*/,13/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/,25/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/languages*/,45/*vs/editor/common/services/model*/,26/*vs/platform/commands/common/commands*/]), function (require, exports, arrays_1, cancellation_1, errors_1, lifecycle_1, types_1, uri_1, range_1, languages_1, model_1, commands_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 = languages_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(model_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[40/*vs/platform/configuration/common/configuration*/], __M([1/*require*/,0/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }); /*--------------------------------------------------------------------------------------------- * 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[32/*vs/editor/common/languages/languageConfigurationRegistry*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,146/*vs/editor/common/core/wordHelper*/,119/*vs/editor/common/languages/languageConfiguration*/,120/*vs/editor/common/languages/supports*/,407/*vs/editor/common/languages/supports/characterPair*/,411/*vs/editor/common/languages/supports/electricCharacter*/,408/*vs/editor/common/languages/supports/indentRules*/,410/*vs/editor/common/languages/supports/onEnter*/,177/*vs/editor/common/languages/supports/richEditBrackets*/,9/*vs/platform/instantiation/common/instantiation*/,40/*vs/platform/configuration/common/configuration*/,35/*vs/editor/common/services/language*/,53/*vs/platform/instantiation/common/extensions*/]), function (require, exports, event_1, lifecycle_1, strings, wordHelper_1, languageConfiguration_1, supports_1, characterPair_1, electricCharacter_1, indentRules_1, onEnter_1, richEditBrackets_1, instantiation_1, configuration_1, language_1, extensions_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ResolvedLanguageConfiguration = exports.LanguageConfigurationRegistry = exports.LanguageConfigurationRegistryImpl = exports.LanguageConfigurationChangeEvent = exports.LanguageConfigurationService = exports.ILanguageConfigurationService = exports.LanguageConfigurationServiceChangeEvent = void 0; class LanguageConfigurationServiceChangeEvent { constructor(languageId) { this.languageId = languageId; } affects(languageId) { return !this.languageId ? true : this.languageId === languageId; } } exports.LanguageConfigurationServiceChangeEvent = LanguageConfigurationServiceChangeEvent; exports.ILanguageConfigurationService = (0, instantiation_1.createDecorator)('languageConfigurationService'); let LanguageConfigurationService = class LanguageConfigurationService extends lifecycle_1.Disposable { constructor(configurationService, languageService) { super(); this.configurationService = configurationService; this.languageService = languageService; this.onDidChangeEmitter = this._register(new event_1.Emitter()); this.onDidChange = this.onDidChangeEmitter.event; this.configurations = new Map(); const languageConfigKeys = new Set(Object.values(customizedLanguageConfigKeys)); this._register(this.configurationService.onDidChangeConfiguration((e) => { const globalConfigChanged = e.change.keys.some((k) => languageConfigKeys.has(k)); const localConfigChanged = e.change.overrides .filter(([overrideLangName, keys]) => keys.some((k) => languageConfigKeys.has(k))) .map(([overrideLangName]) => overrideLangName); if (globalConfigChanged) { this.configurations.clear(); this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(undefined)); } else { for (const languageId of localConfigChanged) { if (this.languageService.isRegisteredLanguageId(languageId)) { this.configurations.delete(languageId); this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(languageId)); } } } })); this._register(exports.LanguageConfigurationRegistry.onDidChange((e) => { this.configurations.delete(e.languageId); this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(e.languageId)); })); } getLanguageConfiguration(languageId) { let result = this.configurations.get(languageId); if (!result) { result = computeConfig(languageId, this.configurationService, this.languageService); this.configurations.set(languageId, result); } return result; } }; LanguageConfigurationService = __decorate([ __param(0, configuration_1.IConfigurationService), __param(1, language_1.ILanguageService) ], LanguageConfigurationService); exports.LanguageConfigurationService = LanguageConfigurationService; function computeConfig(languageId, configurationService, languageService) { let languageConfig = exports.LanguageConfigurationRegistry.getLanguageConfiguration(languageId); if (!languageConfig) { if (!languageService.isRegisteredLanguageId(languageId)) { throw new Error('Unexpected languageId'); } languageConfig = new ResolvedLanguageConfiguration(languageId, {}); } const customizedConfig = getCustomizedLanguageConfig(languageConfig.languageId, configurationService); const data = combineLanguageConfigurations([languageConfig.underlyingConfig, customizedConfig]); const config = new ResolvedLanguageConfiguration(languageConfig.languageId, data); return config; } const customizedLanguageConfigKeys = { brackets: 'editor.language.brackets', colorizedBracketPairs: 'editor.language.colorizedBracketPairs' }; function getCustomizedLanguageConfig(languageId, configurationService) { const brackets = configurationService.getValue(customizedLanguageConfigKeys.brackets, { overrideIdentifier: languageId, }); const colorizedBracketPairs = configurationService.getValue(customizedLanguageConfigKeys.colorizedBracketPairs, { overrideIdentifier: languageId, }); return { brackets: validateBracketPairs(brackets), colorizedBracketPairs: validateBracketPairs(colorizedBracketPairs), }; } function validateBracketPairs(data) { if (!Array.isArray(data)) { return undefined; } return data.map(pair => { if (!Array.isArray(pair) || pair.length !== 2) { return undefined; } return [pair[0], pair[1]]; }).filter((p) => !!p); } class LanguageConfigurationChangeEvent { constructor(languageId) { this.languageId = languageId; } } exports.LanguageConfigurationChangeEvent = LanguageConfigurationChangeEvent; class LanguageConfigurationRegistryImpl { constructor() { this._entries = new Map(); this._onDidChange = new event_1.Emitter(); this.onDidChange = this._onDidChange.event; } /** * @param priority Use a higher number for higher priority */ register(languageId, configuration, priority = 0) { let entries = this._entries.get(languageId); if (!entries) { entries = new ComposedLanguageConfiguration(languageId); this._entries.set(languageId, entries); } const disposable = entries.register(configuration, priority); this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageId)); return (0, lifecycle_1.toDisposable)(() => { disposable.dispose(); this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageId)); }); } getLanguageConfiguration(languageId) { const entries = this._entries.get(languageId); return (entries === null || entries === void 0 ? void 0 : entries.getResolvedConfiguration()) || null; } getComments(languageId) { const value = this.getLanguageConfiguration(languageId); if (!value) { return null; } return value.comments || null; } // begin Indent Rules getIndentRulesSupport(languageId) { const value = this.getLanguageConfiguration(languageId); if (!value) { return null; } return value.indentRulesSupport || null; } /** * Get nearest preceding line which doesn't match unIndentPattern or contains all whitespace. * Result: * -1: run into the boundary of embedded languages * 0: every line above are invalid * else: nearest preceding line of the same language */ getPrecedingValidLine(model, lineNumber, indentRulesSupport) { const 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; } const 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.getLanguageId()); 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.getLanguageConfiguration(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); }, getLanguageId: () => { return model.getLanguageId(); }, 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.getLanguageId()); 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.getLanguageConfiguration(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); } } exports.LanguageConfigurationRegistryImpl = LanguageConfigurationRegistryImpl; /** * @deprecated Use ILanguageConfigurationService instead. */ exports.LanguageConfigurationRegistry = new LanguageConfigurationRegistryImpl(); class ComposedLanguageConfiguration { constructor(languageId) { this.languageId = languageId; this._resolved = null; this._entries = []; this._order = 0; this._resolved = null; } register(configuration, priority) { const entry = new LanguageConfigurationContribution(configuration, priority, ++this._order); this._entries.push(entry); this._resolved = null; return (0, lifecycle_1.toDisposable)(() => { for (let i = 0; i < this._entries.length; i++) { if (this._entries[i] === entry) { this._entries.splice(i, 1); this._resolved = null; break; } } }); } getResolvedConfiguration() { if (!this._resolved) { const config = this._resolve(); if (config) { this._resolved = new ResolvedLanguageConfiguration(this.languageId, config); } } return this._resolved; } _resolve() { if (this._entries.length === 0) { return null; } this._entries.sort(LanguageConfigurationContribution.cmp); return combineLanguageConfigurations(this._entries.map(e => e.configuration)); } } function combineLanguageConfigurations(configs) { let result = { comments: undefined, brackets: undefined, wordPattern: undefined, indentationRules: undefined, onEnterRules: undefined, autoClosingPairs: undefined, surroundingPairs: undefined, autoCloseBefore: undefined, folding: undefined, colorizedBracketPairs: undefined, __electricCharacterSupport: undefined, }; for (const entry of configs) { result = { comments: entry.comments || result.comments, brackets: entry.brackets || result.brackets, wordPattern: entry.wordPattern || result.wordPattern, indentationRules: entry.indentationRules || result.indentationRules, onEnterRules: entry.onEnterRules || result.onEnterRules, autoClosingPairs: entry.autoClosingPairs || result.autoClosingPairs, surroundingPairs: entry.surroundingPairs || result.surroundingPairs, autoCloseBefore: entry.autoCloseBefore || result.autoCloseBefore, folding: entry.folding || result.folding, colorizedBracketPairs: entry.colorizedBracketPairs || result.colorizedBracketPairs, __electricCharacterSupport: entry.__electricCharacterSupport || result.__electricCharacterSupport, }; } return result; } class LanguageConfigurationContribution { constructor(configuration, priority, order) { this.configuration = configuration; this.priority = priority; this.order = order; } static cmp(a, b) { if (a.priority === b.priority) { // higher order last return a.order - b.order; } // higher priority last return a.priority - b.priority; } } /** * Immutable. */ class ResolvedLanguageConfiguration { constructor(languageId, underlyingConfig) { this.languageId = languageId; this.underlyingConfig = underlyingConfig; this._brackets = null; this._electricCharacter = null; this._onEnterSupport = this.underlyingConfig.brackets || this.underlyingConfig.indentationRules || this.underlyingConfig.onEnterRules ? new onEnter_1.OnEnterSupport(this.underlyingConfig) : null; this.comments = ResolvedLanguageConfiguration._handleComments(this.underlyingConfig); this.characterPair = new characterPair_1.CharacterPairSupport(this.underlyingConfig); this.wordDefinition = this.underlyingConfig.wordPattern || wordHelper_1.DEFAULT_WORD_REGEXP; this.indentationRules = this.underlyingConfig.indentationRules; if (this.underlyingConfig.indentationRules) { this.indentRulesSupport = new indentRules_1.IndentRulesSupport(this.underlyingConfig.indentationRules); } else { this.indentRulesSupport = null; } this.foldingRules = this.underlyingConfig.folding || {}; } getWordDefinition() { return (0, wordHelper_1.ensureValidWordDefinition)(this.wordDefinition); } get brackets() { if (!this._brackets && this.underlyingConfig.brackets) { this._brackets = new richEditBrackets_1.RichEditBrackets(this.languageId, this.underlyingConfig.brackets); } return this._brackets; } get electricCharacter() { if (!this._electricCharacter) { this._electricCharacter = new electricCharacter_1.BracketElectricCharacterSupport(this.brackets); } return this._electricCharacter; } onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText) { if (!this._onEnterSupport) { return null; } return this._onEnterSupport.onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText); } getAutoClosingPairs() { return new languageConfiguration_1.AutoClosingPairs(this.characterPair.getAutoClosingPairs()); } getAutoCloseBeforeSet() { return this.characterPair.getAutoCloseBeforeSet(); } getSurroundingPairs() { return this.characterPair.getSurroundingPairs(); } static _handleComments(conf) { const commentRule = conf.comments; if (!commentRule) { return null; } // comment configuration const comments = {}; if (commentRule.lineComment) { comments.lineCommentToken = commentRule.lineComment; } if (commentRule.blockComment) { const [blockStart, blockEnd] = commentRule.blockComment; comments.blockCommentStartToken = blockStart; comments.blockCommentEndToken = blockEnd; } return comments; } } exports.ResolvedLanguageConfiguration = ResolvedLanguageConfiguration; (0, extensions_1.registerSingleton)(exports.ILanguageConfigurationService, LanguageConfigurationService); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[197/*vs/editor/common/commands/shiftCommand*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,68/*vs/editor/common/core/cursorColumns*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,32/*vs/editor/common/languages/languageConfigurationRegistry*/]), function (require, exports, strings, cursorColumns_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 = cursorColumns_1.CursorColumns.visibleColumnFromColumn(line, column, tabSize); if (insertSpaces) { const indent = cachedStringRepeat(' ', indentSize); const desiredTabStop = cursorColumns_1.CursorColumns.prevIndentTabStop(contentStartVisibleColumn, indentSize); const indentCount = desiredTabStop / indentSize; // will be an integer return cachedStringRepeat(indent, indentCount); } else { const indent = '\t'; const desiredTabStop = cursorColumns_1.CursorColumns.prevRenderTabStop(contentStartVisibleColumn, tabSize); const indentCount = desiredTabStop / tabSize; // will be an integer return cachedStringRepeat(indent, indentCount); } } static shiftIndent(line, column, tabSize, indentSize, insertSpaces) { // Determine the visible column where the content starts const contentStartVisibleColumn = cursorColumns_1.CursorColumns.visibleColumnFromColumn(line, column, tabSize); if (insertSpaces) { const indent = cachedStringRepeat(' ', indentSize); const desiredTabStop = cursorColumns_1.CursorColumns.nextIndentTabStop(contentStartVisibleColumn, indentSize); const indentCount = desiredTabStop / indentSize; // will be an integer return cachedStringRepeat(indent, indentCount); } else { const indent = '\t'; const desiredTabStop = cursorColumns_1.CursorColumns.nextRenderTabStop(contentStartVisibleColumn, tabSize); const indentCount = desiredTabStop / tabSize; // will be an integer return cachedStringRepeat(indent, indentCount); } } _addEditOperation(builder, range, text) { if (this._useLastEditRangeForCursorEndPosition) { builder.addTrackedEditOperation(range, text); } else { builder.addEditOperation(range, text); } } getEditOperations(model, builder) { const startLine = this._selection.startLineNumber; let endLine = this._selection.endLineNumber; if (this._selection.endColumn === 1 && startLine !== endLine) { endLine = endLine - 1; } const { tabSize, indentSize, insertSpaces } = this._opts; const shouldIndentEmptyLines = (startLine === endLine); if (this._opts.useTabStops) { // if indenting or outdenting on a whitespace only line if (this._selection.isEmpty()) { if (/^\s*$/.test(model.getLineContent(startLine))) { this._useLastEditRangeForCursorEndPosition = true; } } // keep track of previous line's "miss-alignment" let previousLineExtraSpaces = 0, extraSpaces = 0; for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++, previousLineExtraSpaces = extraSpaces) { extraSpaces = 0; const lineText = model.getLineContent(lineNumber); let indentationEndIndex = strings.firstNonWhitespaceIndex(lineText); if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) { // empty line or line with no leading whitespace => nothing to do continue; } if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) { // do not indent empty lines => nothing to do continue; } if (indentationEndIndex === -1) { // the entire line is whitespace indentationEndIndex = lineText.length; } if (lineNumber > 1) { const contentStartVisibleColumn = cursorColumns_1.CursorColumns.visibleColumnFromColumn(lineText, indentationEndIndex + 1, tabSize); if (contentStartVisibleColumn % indentSize !== 0) { // The current line is "miss-aligned", so let's see if this is expected... // This can only happen when it has trailing commas in the indent if (model.isCheapToTokenize(lineNumber - 1)) { const 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) { const lastOp = helper.getInverseEditOperations()[0]; return new selection_1.Selection(lastOp.range.endLineNumber, lastOp.range.endColumn, lastOp.range.endLineNumber, lastOp.range.endColumn); } const result = helper.getTrackedSelection(this._selectionId); if (this._selectionStartColumnStaysPut) { // The selection start should not move const initialStartColumn = this._selection.startColumn; const resultStartColumn = result.startColumn; if (resultStartColumn <= initialStartColumn) { return result; } if (result.getDirection() === 0 /* 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[599/*vs/editor/contrib/comment/browser/lineCommentCommand*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,61/*vs/editor/common/core/editOperation*/,11/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,32/*vs/editor/common/languages/languageConfigurationRegistry*/,254/*vs/editor/contrib/comment/browser/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(languageConfigurationService, selection, tabSize, type, insertSpace, ignoreEmptyLines, ignoreFirstLine) { this.languageConfigurationService = languageConfigurationService; 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, languageConfigurationService) { model.tokenizeIfCheap(startLineNumber); const languageId = model.getLanguageIdAtPosition(startLineNumber, 1); const config = languageConfigurationService.getLanguageConfiguration(languageId).comments; const commentStr = (config ? config.lineCommentToken : null); if (!commentStr) { // Mode does not support line comments return null; } 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, languageConfigurationService) { 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, languageConfigurationService) { const lines = LineCommentCommand._gatherPreflightCommentStrings(model, startLineNumber, endLineNumber, languageConfigurationService); if (lines === null) { return { supported: false }; } return LineCommentCommand._analyzeLines(type, insertSpace, model, lines, startLineNumber, ignoreEmptyLines, ignoreFirstLine, languageConfigurationService); } /** * Given a successful analysis, execute either insert line comments, either remove line comments */ _executeLineComments(model, builder, data, s) { let ops; if (data.shouldRemoveComments) { ops = LineCommentCommand._createRemoveLineCommentsOperations(data.lines, s.startLineNumber); } else { LineCommentCommand._normalizeInsertionPoint(model, data.lines, s.startLineNumber, this._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, this.languageConfigurationService); if (data.supported) { return this._executeLineComments(model, builder, data, s); } return this._executeBlockComment(model, builder, s); } computeCursorState(model, helper) { let result = helper.getTrackedSelection(this._selectionId); if (this._moveEndPositionDown) { result = result.setEndPosition(result.endLineNumber + 1, 1); } return new selection_1.Selection(result.selectionStartLineNumber, result.selectionStartColumn + this._deltaColumn, result.positionLineNumber, result.positionColumn + this._deltaColumn); } /** * Generate edit operations in the remove line comment case */ static _createRemoveLineCommentsOperations(lines, startLineNumber) { 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[600/*vs/editor/contrib/linesOperations/browser/moveLinesCommand*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/strings*/,197/*vs/editor/common/commands/shiftCommand*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,119/*vs/editor/common/languages/languageConfiguration*/,32/*vs/editor/common/languages/languageConfigurationRegistry*/,258/*vs/editor/contrib/indentation/browser/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); }, getLanguageId: () => { return model.getLanguageId(); }, 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[16/*vs/platform/contextkey/common/contextkey*/], __M([1/*require*/,0/*exports*/,17/*vs/base/common/platform*/,8/*vs/base/common/strings*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, platform_1, strings_1, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.implies = exports.SET_CONTEXT_COMMAND_ID = exports.IContextKeyService = exports.RawContextKey = 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.expressionsAreEqualWithConstantSubstitution = exports.ContextKeyExpr = void 0; const CONSTANT_VALUES = new Map(); CONSTANT_VALUES.set('false', false); CONSTANT_VALUES.set('true', true); CONSTANT_VALUES.set('isMac', platform_1.isMacintosh); CONSTANT_VALUES.set('isLinux', platform_1.isLinux); CONSTANT_VALUES.set('isWindows', platform_1.isWindows); CONSTANT_VALUES.set('isWeb', platform_1.isWeb); CONSTANT_VALUES.set('isMacNative', platform_1.isMacintosh && !platform_1.isWeb); CONSTANT_VALUES.set('isEdge', platform_1.isEdge); CONSTANT_VALUES.set('isFirefox', platform_1.isFirefox); CONSTANT_VALUES.set('isChrome', platform_1.isChrome); CONSTANT_VALUES.set('isSafari', platform_1.isSafari); const hasOwnProperty = Object.prototype.hasOwnProperty; 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, null); } static or(...expr) { return ContextKeyOrExpr.create(expr, null, true); } 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)), null, true); } static _deserializeAndExpression(serialized, strict) { let pieces = serialized.split('&&'); return ContextKeyAndExpr.create(pieces.map(p => this._deserializeOne(p, strict)), null); } 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 expressionsAreEqualWithConstantSubstitution(a, b) { const aExpr = a ? a.substituteConstants() : undefined; const bExpr = b ? b.substituteConstants() : undefined; if (!aExpr && !bExpr) { return true; } if (!aExpr || !bExpr) { return false; } return aExpr.equals(bExpr); } exports.expressionsAreEqualWithConstantSubstitution = expressionsAreEqualWithConstantSubstitution; 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); } substituteConstants() { return this; } 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); } substituteConstants() { return this; } evaluate(context) { return true; } serialize() { return 'true'; } keys() { return []; } negate() { return ContextKeyFalseExpr.INSTANCE; } } exports.ContextKeyTrueExpr = ContextKeyTrueExpr; ContextKeyTrueExpr.INSTANCE = new ContextKeyTrueExpr(); class ContextKeyDefinedExpr { constructor(key, negated) { this.key = key; this.negated = negated; this.type = 2 /* Defined */; } static create(key, negated = null) { const constantValue = CONSTANT_VALUES.get(key); if (typeof constantValue === 'boolean') { return constantValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE; } return new ContextKeyDefinedExpr(key, negated); } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp1(this.key, other.key); } equals(other) { if (other.type === this.type) { return (this.key === other.key); } return false; } substituteConstants() { const constantValue = CONSTANT_VALUES.get(this.key); if (typeof constantValue === 'boolean') { return constantValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE; } return this; } evaluate(context) { return (!!context.getValue(this.key)); } serialize() { return this.key; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeyNotExpr.create(this.key, this); } return this.negated; } } exports.ContextKeyDefinedExpr = ContextKeyDefinedExpr; class ContextKeyEqualsExpr { constructor(key, value, negated) { this.key = key; this.value = value; this.negated = negated; this.type = 4 /* Equals */; } static create(key, value, negated = null) { if (typeof value === 'boolean') { return (value ? ContextKeyDefinedExpr.create(key, negated) : ContextKeyNotExpr.create(key, negated)); } const constantValue = CONSTANT_VALUES.get(key); if (typeof constantValue === 'boolean') { const trueValue = constantValue ? 'true' : 'false'; return (value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE); } return new ContextKeyEqualsExpr(key, value, negated); } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } equals(other) { if (other.type === this.type) { return (this.key === other.key && this.value === other.value); } return false; } substituteConstants() { const constantValue = CONSTANT_VALUES.get(this.key); if (typeof constantValue === 'boolean') { const trueValue = constantValue ? 'true' : 'false'; return (this.value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE); } return this; } evaluate(context) { // Intentional == // eslint-disable-next-line eqeqeq return (context.getValue(this.key) == this.value); } serialize() { return `${this.key} == '${this.value}'`; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeyNotEqualsExpr.create(this.key, this.value, this); } return this.negated; } } exports.ContextKeyEqualsExpr = ContextKeyEqualsExpr; class ContextKeyInExpr { constructor(key, valueKey) { this.key = key; this.valueKey = valueKey; this.type = 10 /* In */; this.negated = null; } 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; } substituteConstants() { return this; } 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() { if (!this.negated) { this.negated = ContextKeyNotInExpr.create(this); } return this.negated; } } 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; } substituteConstants() { return this; } 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, negated) { this.key = key; this.value = value; this.negated = negated; this.type = 5 /* NotEquals */; } static create(key, value, negated = null) { if (typeof value === 'boolean') { if (value) { return ContextKeyNotExpr.create(key, negated); } return ContextKeyDefinedExpr.create(key, negated); } const constantValue = CONSTANT_VALUES.get(key); if (typeof constantValue === 'boolean') { const falseValue = constantValue ? 'true' : 'false'; return (value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE); } return new ContextKeyNotEqualsExpr(key, value, negated); } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } equals(other) { if (other.type === this.type) { return (this.key === other.key && this.value === other.value); } return false; } substituteConstants() { const constantValue = CONSTANT_VALUES.get(this.key); if (typeof constantValue === 'boolean') { const falseValue = constantValue ? 'true' : 'false'; return (this.value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE); } return this; } evaluate(context) { // Intentional != // eslint-disable-next-line eqeqeq return (context.getValue(this.key) != this.value); } serialize() { return `${this.key} != '${this.value}'`; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeyEqualsExpr.create(this.key, this.value, this); } return this.negated; } } exports.ContextKeyNotEqualsExpr = ContextKeyNotEqualsExpr; class ContextKeyNotExpr { constructor(key, negated) { this.key = key; this.negated = negated; this.type = 3 /* Not */; } static create(key, negated = null) { const constantValue = CONSTANT_VALUES.get(key); if (typeof constantValue === 'boolean') { return (constantValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE); } return new ContextKeyNotExpr(key, negated); } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp1(this.key, other.key); } equals(other) { if (other.type === this.type) { return (this.key === other.key); } return false; } substituteConstants() { const constantValue = CONSTANT_VALUES.get(this.key); if (typeof constantValue === 'boolean') { return (constantValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE); } return this; } evaluate(context) { return (!context.getValue(this.key)); } serialize() { return `!${this.key}`; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeyDefinedExpr.create(this.key, this); } return this.negated; } } exports.ContextKeyNotExpr = ContextKeyNotExpr; function withFloatOrStr(value, callback) { if (typeof value === 'string') { const n = parseFloat(value); if (!isNaN(n)) { value = n; } } if (typeof value === 'string' || typeof value === 'number') { return callback(value); } return ContextKeyFalseExpr.INSTANCE; } class ContextKeyGreaterExpr { constructor(key, value, negated) { this.key = key; this.value = value; this.negated = negated; this.type = 12 /* Greater */; } static create(key, _value, negated = null) { return withFloatOrStr(_value, (value) => new ContextKeyGreaterExpr(key, value, negated)); } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } equals(other) { if (other.type === this.type) { return (this.key === other.key && this.value === other.value); } return false; } substituteConstants() { return this; } evaluate(context) { if (typeof this.value === 'string') { return false; } return (parseFloat(context.getValue(this.key)) > this.value); } serialize() { return `${this.key} > ${this.value}`; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeySmallerEqualsExpr.create(this.key, this.value, this); } return this.negated; } } exports.ContextKeyGreaterExpr = ContextKeyGreaterExpr; class ContextKeyGreaterEqualsExpr { constructor(key, value, negated) { this.key = key; this.value = value; this.negated = negated; this.type = 13 /* GreaterEquals */; } static create(key, _value, negated = null) { return withFloatOrStr(_value, (value) => new ContextKeyGreaterEqualsExpr(key, value, negated)); } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } equals(other) { if (other.type === this.type) { return (this.key === other.key && this.value === other.value); } return false; } substituteConstants() { return this; } evaluate(context) { if (typeof this.value === 'string') { return false; } return (parseFloat(context.getValue(this.key)) >= this.value); } serialize() { return `${this.key} >= ${this.value}`; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeySmallerExpr.create(this.key, this.value, this); } return this.negated; } } exports.ContextKeyGreaterEqualsExpr = ContextKeyGreaterEqualsExpr; class ContextKeySmallerExpr { constructor(key, value, negated) { this.key = key; this.value = value; this.negated = negated; this.type = 14 /* Smaller */; } static create(key, _value, negated = null) { return withFloatOrStr(_value, (value) => new ContextKeySmallerExpr(key, value, negated)); } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } equals(other) { if (other.type === this.type) { return (this.key === other.key && this.value === other.value); } return false; } substituteConstants() { return this; } evaluate(context) { if (typeof this.value === 'string') { return false; } return (parseFloat(context.getValue(this.key)) < this.value); } serialize() { return `${this.key} < ${this.value}`; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeyGreaterEqualsExpr.create(this.key, this.value, this); } return this.negated; } } exports.ContextKeySmallerExpr = ContextKeySmallerExpr; class ContextKeySmallerEqualsExpr { constructor(key, value, negated) { this.key = key; this.value = value; this.negated = negated; this.type = 15 /* SmallerEquals */; } static create(key, _value, negated = null) { return withFloatOrStr(_value, (value) => new ContextKeySmallerEqualsExpr(key, value, negated)); } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } equals(other) { if (other.type === this.type) { return (this.key === other.key && this.value === other.value); } return false; } substituteConstants() { return this; } evaluate(context) { if (typeof this.value === 'string') { return false; } return (parseFloat(context.getValue(this.key)) <= this.value); } serialize() { return `${this.key} <= ${this.value}`; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeyGreaterExpr.create(this.key, this.value, this); } return this.negated; } } exports.ContextKeySmallerEqualsExpr = ContextKeySmallerEqualsExpr; class ContextKeyRegexExpr { constructor(key, regexp) { this.key = key; this.regexp = regexp; this.type = 7 /* Regex */; this.negated = null; // } 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; } substituteConstants() { return this; } 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() { if (!this.negated) { this.negated = ContextKeyNotRegexExpr.create(this); } return this.negated; } } 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; } substituteConstants() { return this; } 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; /** * @returns the same instance if nothing changed. */ function eliminateConstantsInArray(arr) { // Allocate array only if there is a difference let newArr = null; for (let i = 0, len = arr.length; i < len; i++) { const newExpr = arr[i].substituteConstants(); if (arr[i] !== newExpr) { // something has changed! // allocate array on first difference if (newArr === null) { newArr = []; for (let j = 0; j < i; j++) { newArr[j] = arr[j]; } } } if (newArr !== null) { newArr[i] = newExpr; } } if (newArr === null) { return arr; } return newArr; } class ContextKeyAndExpr { constructor(expr, negated) { this.expr = expr; this.negated = negated; this.type = 6 /* And */; } static create(_expr, negated) { return ContextKeyAndExpr._normalizeArr(_expr, negated); } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } if (this.expr.length < other.expr.length) { return -1; } if (this.expr.length > other.expr.length) { return 1; } for (let i = 0, len = this.expr.length; i < len; i++) { const r = cmp(this.expr[i], other.expr[i]); if (r !== 0) { return r; } } return 0; } equals(other) { if (other.type === this.type) { if (this.expr.length !== other.expr.length) { return false; } for (let i = 0, len = this.expr.length; i < len; i++) { if (!this.expr[i].equals(other.expr[i])) { return false; } } return true; } return false; } substituteConstants() { const exprArr = eliminateConstantsInArray(this.expr); if (exprArr === this.expr) { // no change return this; } return ContextKeyAndExpr.create(exprArr, this.negated); } evaluate(context) { for (let i = 0, len = this.expr.length; i < len; i++) { if (!this.expr[i].evaluate(context)) { return false; } } return true; } static _normalizeArr(arr, negated) { 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); // eliminate duplicate terms for (let i = 1; i < expr.length; i++) { if (expr[i - 1].equals(expr[i])) { expr.splice(i, 1); i--; } } if (expr.length === 1) { return expr[0]; } // We must distribute any OR expression because we don't support parens // OR extensions will be at the end (due to sorting rules) while (expr.length > 1) { const lastElement = expr[expr.length - 1]; if (lastElement.type !== 9 /* Or */) { break; } // pop the last element expr.pop(); // pop the second to last element const secondToLastElement = expr.pop(); const isFinished = (expr.length === 0); // distribute `lastElement` over `secondToLastElement` const resultElement = ContextKeyOrExpr.create(lastElement.expr.map(el => ContextKeyAndExpr.create([el, secondToLastElement], null)), null, isFinished); if (resultElement) { expr.push(resultElement); expr.sort(cmp); } } if (expr.length === 1) { return expr[0]; } return new ContextKeyAndExpr(expr, negated); } serialize() { return this.expr.map(e => e.serialize()).join(' && '); } keys() { const result = []; for (let expr of this.expr) { result.push(...expr.keys()); } return result; } negate() { if (!this.negated) { const result = []; for (let expr of this.expr) { result.push(expr.negate()); } this.negated = ContextKeyOrExpr.create(result, this, true); } return this.negated; } } class ContextKeyOrExpr { constructor(expr, negated) { this.expr = expr; this.negated = negated; this.type = 9 /* Or */; } static create(_expr, negated, extraRedundantCheck) { return ContextKeyOrExpr._normalizeArr(_expr, negated, extraRedundantCheck); } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } if (this.expr.length < other.expr.length) { return -1; } if (this.expr.length > other.expr.length) { return 1; } for (let i = 0, len = this.expr.length; i < len; i++) { const r = cmp(this.expr[i], other.expr[i]); if (r !== 0) { return r; } } return 0; } equals(other) { if (other.type === this.type) { if (this.expr.length !== other.expr.length) { return false; } for (let i = 0, len = this.expr.length; i < len; i++) { if (!this.expr[i].equals(other.expr[i])) { return false; } } return true; } return false; } substituteConstants() { const exprArr = eliminateConstantsInArray(this.expr); if (exprArr === this.expr) { // no change return this; } return ContextKeyOrExpr.create(exprArr, this.negated, false); } evaluate(context) { for (let i = 0, len = this.expr.length; i < len; i++) { if (this.expr[i].evaluate(context)) { return true; } } return false; } static _normalizeArr(arr, negated, extraRedundantCheck) { let expr = []; let hasFalse = false; if (arr) { for (let i = 0, len = arr.length; i < len; i++) { const e = arr[i]; if (!e) { continue; } if (e.type === 0 /* 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); } if (expr.length === 0) { return undefined; } if (expr.length === 1) { return expr[0]; } // eliminate duplicate terms for (let i = 1; i < expr.length; i++) { if (expr[i - 1].equals(expr[i])) { expr.splice(i, 1); i--; } } if (expr.length === 1) { return expr[0]; } // eliminate redundant terms if (extraRedundantCheck) { for (let i = 0; i < expr.length; i++) { for (let j = i + 1; j < expr.length; j++) { if (implies(expr[i], expr[j])) { expr.splice(j, 1); j--; } } } if (expr.length === 1) { return expr[0]; } } return new ContextKeyOrExpr(expr, negated); } serialize() { return this.expr.map(e => e.serialize()).join(' || '); } keys() { const result = []; for (let expr of this.expr) { result.push(...expr.keys()); } return result; } negate() { if (!this.negated) { let result = []; for (let expr of this.expr) { result.push(expr.negate()); } // We don't support parens, so here we distribute the AND over the OR terminals // We always take the first 2 AND pairs and distribute them while (result.length > 1) { const LEFT = result.shift(); const RIGHT = result.shift(); const all = []; for (const left of getTerminals(LEFT)) { for (const right of getTerminals(RIGHT)) { all.push(ContextKeyAndExpr.create([left, right], null)); } } const isFinished = (result.length === 0); result.unshift(ContextKeyOrExpr.create(all, null, isFinished)); } this.negated = result[0]; } return this.negated; } } class RawContextKey extends ContextKeyDefinedExpr { constructor(key, defaultValue, metaOrHide) { super(key, null); this._defaultValue = defaultValue; // collect all context keys into a central place if (typeof metaOrHide === 'object') { RawContextKey._info.push(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 this.negate(); } isEqualTo(value) { return ContextKeyEqualsExpr.create(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; } /** * Returns true if it is provable `p` implies `q`. */ function implies(p, q) { if (q.type === 6 /* And */ && (p.type !== 9 /* Or */ && p.type !== 6 /* And */)) { // covers the case: A implies A && B for (const qTerm of q.expr) { if (p.equals(qTerm)) { return true; } } } const notP = p.negate(); const expr = getTerminals(notP).concat(getTerminals(q)); expr.sort(cmp); 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; } exports.implies = implies; function getTerminals(node) { if (node.type === 9 /* Or */) { return node.expr; } return [node]; } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[24/*vs/editor/common/editorContextKeys*/], __M([1/*require*/,0/*exports*/,512/*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[198/*vs/editor/contrib/parameterHints/browser/provideSignatureHelp*/], __M([1/*require*/,0/*exports*/,21/*vs/base/common/cancellation*/,13/*vs/base/common/errors*/,20/*vs/base/common/types*/,25/*vs/base/common/uri*/,11/*vs/editor/common/core/position*/,18/*vs/editor/common/languages*/,58/*vs/editor/common/services/resolverService*/,26/*vs/platform/commands/common/commands*/,16/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, cancellation_1, errors_1, types_1, uri_1, position_1, modes, resolverService_1, commands_1, contextkey_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[601/*vs/editor/contrib/parameterHints/browser/parameterHintsModel*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/async*/,13/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,97/*vs/editor/common/core/characterClassifier*/,18/*vs/editor/common/languages*/,198/*vs/editor/contrib/parameterHints/browser/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(76 /* 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(76 /* 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(76 /* 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. *--------------------------------------------------------------------------------------------*/ define(__m[602/*vs/editor/contrib/suggest/browser/suggestAlternatives*/], __M([1/*require*/,0/*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[603/*vs/editor/contrib/suggest/browser/wordContextKey*/], __M([1/*require*/,0/*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(111 /* 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(111 /* 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[63/*vs/platform/accessibility/common/accessibility*/], __M([1/*require*/,0/*exports*/,16/*vs/platform/contextkey/common/contextkey*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, contextkey_1, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CONTEXT_ACCESSIBILITY_MODE_ENABLED = exports.IAccessibilityService = void 0; exports.IAccessibilityService = (0, instantiation_1.createDecorator)('accessibilityService'); exports.CONTEXT_ACCESSIBILITY_MODE_ENABLED = new contextkey_1.RawContextKey('accessibilityModeEnabled', false); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[604/*vs/editor/browser/config/editorConfiguration*/], __M([1/*require*/,0/*exports*/,34/*vs/base/browser/browser*/,19/*vs/base/common/arrays*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,39/*vs/base/common/objects*/,17/*vs/base/common/platform*/,230/*vs/editor/browser/config/elementSizeObserver*/,266/*vs/editor/browser/config/fontMeasurements*/,397/*vs/editor/browser/config/migrateOptions*/,231/*vs/editor/browser/config/tabFocus*/,31/*vs/editor/common/config/editorOptions*/,144/*vs/editor/common/config/editorZoom*/,174/*vs/editor/common/config/fontInfo*/,63/*vs/platform/accessibility/common/accessibility*/]), function (require, exports, browser, arrays, event_1, lifecycle_1, objects, platform, elementSizeObserver_1, fontMeasurements_1, migrateOptions_1, tabFocus_1, editorOptions_1, editorZoom_1, fontInfo_1, accessibility_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ComputedEditorOptions = exports.EditorConfiguration = void 0; let EditorConfiguration = class EditorConfiguration extends lifecycle_1.Disposable { constructor(isSimpleWidget, options, container, _accessibilityService) { super(); this._accessibilityService = _accessibilityService; this._onDidChange = this._register(new event_1.Emitter()); this.onDidChange = this._onDidChange.event; this._onDidChangeFast = this._register(new event_1.Emitter()); this.onDidChangeFast = this._onDidChangeFast.event; this._isDominatedByLongLines = false; this._viewLineCount = 1; this._lineNumbersDigitCount = 1; this._reservedHeight = 0; this._computeOptionsMemory = new editorOptions_1.ComputeOptionsMemory(); this.isSimpleWidget = isSimpleWidget; this._containerObserver = this._register(new elementSizeObserver_1.ElementSizeObserver(container, options.dimension)); this._rawOptions = deepCloneAndMigrateOptions(options); this._validatedOptions = EditorOptionsUtil.validateOptions(this._rawOptions); this.options = this._computeOptions(); if (this.options.get(10 /* automaticLayout */)) { this._containerObserver.startObserving(); } this._register(editorZoom_1.EditorZoom.onDidChangeZoomLevel(() => this._recomputeOptions())); this._register(tabFocus_1.TabFocus.onDidChangeTabFocus(() => this._recomputeOptions())); this._register(this._containerObserver.onDidChange(() => this._recomputeOptions())); this._register(fontMeasurements_1.FontMeasurements.onDidChange(() => this._recomputeOptions())); this._register(browser.PixelRatio.onDidChange(() => this._recomputeOptions())); this._register(this._accessibilityService.onDidChangeScreenReaderOptimized(() => this._recomputeOptions())); } _recomputeOptions() { const newOptions = this._computeOptions(); const changeEvent = EditorOptionsUtil.checkEquals(this.options, newOptions); if (changeEvent === null) { // nothing changed! return; } this.options = newOptions; this._onDidChangeFast.fire(changeEvent); this._onDidChange.fire(changeEvent); } _computeOptions() { const partialEnv = this._readEnvConfiguration(); const bareFontInfo = fontInfo_1.BareFontInfo.createFromValidatedSettings(this._validatedOptions, partialEnv.pixelRatio, this.isSimpleWidget); const fontInfo = this._readFontInfo(bareFontInfo); const env = { memory: this._computeOptionsMemory, outerWidth: partialEnv.outerWidth, outerHeight: partialEnv.outerHeight - this._reservedHeight, fontInfo: fontInfo, extraEditorClassName: partialEnv.extraEditorClassName, isDominatedByLongLines: this._isDominatedByLongLines, viewLineCount: this._viewLineCount, lineNumbersDigitCount: this._lineNumbersDigitCount, emptySelectionClipboard: partialEnv.emptySelectionClipboard, pixelRatio: partialEnv.pixelRatio, tabFocusMode: tabFocus_1.TabFocus.getTabFocusMode(), accessibilitySupport: partialEnv.accessibilitySupport }; return EditorOptionsUtil.computeOptions(this._validatedOptions, env); } _readEnvConfiguration() { return { extraEditorClassName: getExtraEditorClassName(), outerWidth: this._containerObserver.getWidth(), outerHeight: this._containerObserver.getHeight(), emptySelectionClipboard: browser.isWebKit || browser.isFirefox, pixelRatio: browser.PixelRatio.value, accessibilitySupport: (this._accessibilityService.isScreenReaderOptimized() ? 2 /* Enabled */ : this._accessibilityService.getAccessibilitySupport()) }; } _readFontInfo(bareFontInfo) { return fontMeasurements_1.FontMeasurements.readFontInfo(bareFontInfo); } getRawOptions() { return this._rawOptions; } updateOptions(_newOptions) { const newOptions = deepCloneAndMigrateOptions(_newOptions); const didChange = EditorOptionsUtil.applyUpdate(this._rawOptions, newOptions); if (!didChange) { return; } this._validatedOptions = EditorOptionsUtil.validateOptions(this._rawOptions); this._recomputeOptions(); } observeContainer(dimension) { this._containerObserver.observe(dimension); } setIsDominatedByLongLines(isDominatedByLongLines) { if (this._isDominatedByLongLines === isDominatedByLongLines) { return; } this._isDominatedByLongLines = isDominatedByLongLines; this._recomputeOptions(); } setModelLineCount(modelLineCount) { const lineNumbersDigitCount = digitCount(modelLineCount); if (this._lineNumbersDigitCount === lineNumbersDigitCount) { return; } this._lineNumbersDigitCount = lineNumbersDigitCount; this._recomputeOptions(); } setViewLineCount(viewLineCount) { if (this._viewLineCount === viewLineCount) { return; } this._viewLineCount = viewLineCount; this._recomputeOptions(); } setReservedHeight(reservedHeight) { if (this._reservedHeight === reservedHeight) { return; } this._reservedHeight = reservedHeight; this._recomputeOptions(); } }; EditorConfiguration = __decorate([ __param(3, accessibility_1.IAccessibilityService) ], EditorConfiguration); exports.EditorConfiguration = EditorConfiguration; function digitCount(n) { let r = 0; while (n) { n = Math.floor(n / 10); r++; } return r ? r : 1; } function getExtraEditorClassName() { let extra = ''; if (!browser.isSafari && !browser.isWebkitWebView) { // Use user-select: none in all browsers except Safari and native macOS WebView extra += 'no-user-select '; } if (browser.isSafari) { // See https://github.com/microsoft/vscode/issues/108822 extra += 'no-minimap-shadow '; } if (platform.isMacintosh) { extra += 'mac '; } return extra; } class ValidatedEditorOptions { constructor() { this._values = []; } _read(option) { return this._values[option]; } get(id) { return this._values[id]; } _write(option, value) { this._values[option] = value; } } class ComputedEditorOptions { constructor() { this._values = []; } _read(id) { if (id >= this._values.length) { throw new Error('Cannot read uninitialized value'); } return this._values[id]; } get(id) { return this._read(id); } _write(id, value) { this._values[id] = value; } } exports.ComputedEditorOptions = ComputedEditorOptions; class EditorOptionsUtil { static validateOptions(options) { const result = new ValidatedEditorOptions(); for (const editorOption of editorOptions_1.editorOptionsRegistry) { const value = (editorOption.name === '_never_' ? undefined : options[editorOption.name]); result._write(editorOption.id, editorOption.validate(value)); } return result; } static computeOptions(options, env) { const result = new ComputedEditorOptions(); for (const editorOption of editorOptions_1.editorOptionsRegistry) { result._write(editorOption.id, editorOption.compute(env, result, options._read(editorOption.id))); } return result; } static _deepEquals(a, b) { if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) { return a === b; } if (Array.isArray(a) || Array.isArray(b)) { return (Array.isArray(a) && Array.isArray(b) ? arrays.equals(a, b) : false); } if (Object.keys(a).length !== Object.keys(b).length) { return false; } for (const key in a) { if (!EditorOptionsUtil._deepEquals(a[key], b[key])) { return false; } } return true; } static checkEquals(a, b) { const result = []; let somethingChanged = false; for (const editorOption of editorOptions_1.editorOptionsRegistry) { const changed = !EditorOptionsUtil._deepEquals(a._read(editorOption.id), b._read(editorOption.id)); result[editorOption.id] = changed; if (changed) { somethingChanged = true; } } return (somethingChanged ? new editorOptions_1.ConfigurationChangedEvent(result) : null); } /** * Returns true if something changed. * Modifies `options`. */ static applyUpdate(options, update) { let changed = false; for (const editorOption of editorOptions_1.editorOptionsRegistry) { if (update.hasOwnProperty(editorOption.name)) { const result = editorOption.applyUpdate(options[editorOption.name], update[editorOption.name]); options[editorOption.name] = result.newValue; changed = changed || result.didChange; } } return changed; } } function deepCloneAndMigrateOptions(_options) { const options = objects.deepClone(_options); (0, migrateOptions_1.migrateOptions)(options); return options; } }); define(__m[605/*vs/platform/accessibility/browser/accessibilityService*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,63/*vs/platform/accessibility/common/accessibility*/,40/*vs/platform/configuration/common/configuration*/,16/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, event_1, lifecycle_1, accessibility_1, configuration_1, contextkey_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; }); /*--------------------------------------------------------------------------------------------- * 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/platform/contextkey/browser/contextKeyService*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,54/*vs/base/common/iterator*/,2/*vs/base/common/lifecycle*/,47/*vs/base/common/map*/,583/*vs/nls!vs/platform/contextkey/browser/contextKeyService*/,26/*vs/platform/commands/common/commands*/,40/*vs/platform/configuration/common/configuration*/,16/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, event_1, iterator_1, lifecycle_1, map_1, nls_1, commands_1, configuration_1, contextkey_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ContextKeyService = exports.AbstractContextKeyService = exports.Context = void 0; 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 = (rules ? rules.evaluate(context) : true); // console.group(rules.serialize() + ' -> ' + result); // rules.keys().forEach(key => { console.log(key, ctx[key]); }); // console.groupEnd(); return result; } getContextKeyValue(key) { if (this._isDisposed) { return undefined; } return this.getContextValuesContainer(this._myContextId).getValue(key); } setContext(key, value) { if (this._isDisposed) { return; } const myContext = this.getContextValuesContainer(this._myContextId); if (!myContext) { return; } if (myContext.setValue(key, value)) { this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key)); } } removeContext(key) { if (this._isDisposed) { return; } if (this.getContextValuesContainer(this._myContextId).removeValue(key)) { this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key)); } } getContext(target) { if (this._isDisposed) { return NullContext.INSTANCE; } return this.getContextValuesContainer(findContextAttr(target)); } } 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[273/*vs/platform/contextkey/common/contextkeys*/], __M([1/*require*/,0/*exports*/,17/*vs/base/common/platform*/,584/*vs/nls!vs/platform/contextkey/common/contextkeys*/,16/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, platform_1, nls_1, contextkey_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.InputFocusedContext = exports.InputFocusedContextKey = exports.IsDevelopmentContext = exports.IsIOSContext = exports.IsMacNativeContext = exports.IsWebContext = exports.IsWindowsContext = exports.IsLinuxContext = exports.IsMacContext = void 0; exports.IsMacContext = new contextkey_1.RawContextKey('isMac', platform_1.isMacintosh, (0, nls_1.localize)(0, null)); exports.IsLinuxContext = new contextkey_1.RawContextKey('isLinux', platform_1.isLinux, (0, nls_1.localize)(1, null)); exports.IsWindowsContext = new contextkey_1.RawContextKey('isWindows', platform_1.isWindows, (0, nls_1.localize)(2, null)); exports.IsWebContext = new contextkey_1.RawContextKey('isWeb', platform_1.isWeb, (0, nls_1.localize)(3, null)); exports.IsMacNativeContext = new contextkey_1.RawContextKey('isMacNative', platform_1.isMacintosh && !platform_1.isWeb, (0, nls_1.localize)(4, null)); exports.IsIOSContext = new contextkey_1.RawContextKey('isIOS', platform_1.isIOS, (0, nls_1.localize)(5, null)); exports.IsDevelopmentContext = new contextkey_1.RawContextKey('isDevelopment', false, true); exports.InputFocusedContextKey = 'inputFocus'; exports.InputFocusedContext = new contextkey_1.RawContextKey(exports.InputFocusedContextKey, false, (0, nls_1.localize)(6, 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[76/*vs/platform/contextview/browser/contextView*/], __M([1/*require*/,0/*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'); }); define(__m[127/*vs/platform/dialogs/common/dialogs*/], __M([1/*require*/,0/*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[154/*vs/platform/instantiation/common/serviceCollection*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ServiceCollection = void 0; class ServiceCollection { constructor(...entries) { this._entries = new Map(); for (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; } 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[607/*vs/platform/instantiation/common/instantiationService*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/async*/,13/*vs/base/common/errors*/,194/*vs/platform/instantiation/common/descriptors*/,597/*vs/platform/instantiation/common/graph*/,9/*vs/platform/instantiation/common/instantiation*/,154/*vs/platform/instantiation/common/serviceCollection*/]), function (require, exports, async_1, errors_1, descriptors_1, graph_1, instantiation_1, serviceCollection_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Trace = 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) => { if (_done) { throw (0, errors_1.illegalState)('service accessor is only valid during the invocation of its target method'); } const result = this._getOrCreateServiceInstance(id, _trace); if (!result) { throw new Error(`[invokeFunction] unknown service '${id}'`); } return result; } }; return fn(accessor, ...args); } finally { _done = true; _trace.stop(); } } createInstance(ctorOrDescriptor, ...rest) { 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')); } } } exports.Trace = Trace; 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[608/*vs/platform/keybinding/common/abstractKeybindingService*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/async*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,585/*vs/nls!vs/platform/keybinding/common/abstractKeybindingService*/]), function (require, exports, async_1, event_1, lifecycle_1, nls) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AbstractKeybindingService = void 0; const HIGH_FREQ_COMMANDS = /^(cursor|delete)/; 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._ignoreSingleModifiers = KeybindingModifierSet.EMPTY; 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) { if (this._ignoreSingleModifiers.has(singleModifier)) { this._log(`+ Ignoring single modifier ${singleModifier} due to it being pressed together with other keys.`); this._ignoreSingleModifiers = KeybindingModifierSet.EMPTY; this._currentSingleModifierClearTimeout.cancel(); this._currentSingleModifier = null; return false; } this._ignoreSingleModifiers = KeybindingModifierSet.EMPTY; if (this._currentSingleModifier === null) { // we have a valid `singleModifier`, store it for the next keyup, but clear it in 300ms this._log(`+ Storing single modifier for possible chord ${singleModifier}.`); this._currentSingleModifier = singleModifier; this._currentSingleModifierClearTimeout.cancelAndSet(() => { this._log(`+ Clearing single modifier due to 300ms elapsed.`); this._currentSingleModifier = null; }, 300); return false; } if (singleModifier === this._currentSingleModifier) { // bingo! this._log(`/ Dispatching single modifier chord ${singleModifier} ${singleModifier}`); this._currentSingleModifierClearTimeout.cancel(); this._currentSingleModifier = null; return this._doDispatch(keybinding, target, /*isSingleModiferChord*/ true); } this._log(`+ Clearing single modifier due to modifier mismatch: ${this._currentSingleModifier} ${singleModifier}`); this._currentSingleModifierClearTimeout.cancel(); this._currentSingleModifier = null; return false; } // When pressing a modifier and holding it pressed with any other modifier or key combination, // the pressed modifiers should no longer be considered for single modifier dispatch. const [firstPart,] = keybinding.getParts(); this._ignoreSingleModifiers = new KeybindingModifierSet(firstPart); if (this._currentSingleModifier !== null) { this._log(`+ Clearing single modifier due to other key up.`); } 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)); } if (!HIGH_FREQ_COMMANDS.test(resolveResult.commandId)) { 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 /* KeyA */ && event.keyCode <= 56 /* KeyZ */) || (event.keyCode >= 21 /* Digit0 */ && event.keyCode <= 30 /* Digit9 */)) { return true; } return false; } } exports.AbstractKeybindingService = AbstractKeybindingService; class KeybindingModifierSet { constructor(source) { this._ctrlKey = source ? source.ctrlKey : false; this._shiftKey = source ? source.shiftKey : false; this._altKey = source ? source.altKey : false; this._metaKey = source ? source.metaKey : false; } has(modifier) { switch (modifier) { case 'ctrl': return this._ctrlKey; case 'shift': return this._shiftKey; case 'alt': return this._altKey; case 'meta': return this._metaKey; } } } KeybindingModifierSet.EMPTY = new KeybindingModifierSet(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[609/*vs/platform/keybinding/common/baseResolvedKeybinding*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/errors*/,193/*vs/base/common/keybindingLabels*/,94/*vs/base/common/keybindings*/]), function (require, exports, errors_1, keybindingLabels_1, keybindings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseResolvedKeybinding = void 0; class BaseResolvedKeybinding extends keybindings_1.ResolvedKeybinding { constructor(os, 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)); } getElectronAccelerator() { if (this._parts.length > 1) { // [Electron Accelerators] Electron cannot handle chords return null; } if (this._parts[0].isDuplicateModifierCase()) { // [Electron Accelerators] Electron cannot handle modifier only keybindings // e.g. "shift shift" return null; } return keybindingLabels_1.ElectronAcceleratorLabelProvider.toLabel(this._os, this._parts, (keybinding) => this._getElectronAccelerator(keybinding)); } isChord() { return (this._parts.length > 1); } getParts() { return this._parts.map((keybinding) => this._getPart(keybinding)); } _getPart(keybinding) { return new keybindings_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[42/*vs/platform/keybinding/common/keybinding*/], __M([1/*require*/,0/*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[610/*vs/platform/keybinding/common/keybindingResolver*/], __M([1/*require*/,0/*exports*/,16/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, contextkey_1) { "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 (const defaultKeybinding of defaultKeybindings) { const command = defaultKeybinding.command; if (command && command.charAt(0) !== '-') { this._defaultBoundCommands.set(command, true); } } this._map = new Map(); this._lookupMap = new Map(); this._keybindings = KeybindingResolver.handleRemovals([].concat(defaultKeybindings).concat(overrides)); for (let i = 0, len = this._keybindings.length; i < len; i++) { 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, when) { // 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 (!(0, contextkey_1.expressionsAreEqualWithConstantSubstitution)(when, defaultKb.when)) { return false; } } return true; } /** * Looks for rules containing "-commandId" and removes them. */ static handleRemovals(rules) { // Do a first pass and construct a hash-map for removals const removals = new Map(); for (let i = 0, len = rules.length; i < len; i++) { const rule = rules[i]; if (rule.command && rule.command.charAt(0) === '-') { const command = rule.command.substring(1); if (!removals.has(command)) { removals.set(command, [rule]); } else { removals.get(command).push(rule); } } } if (removals.size === 0) { // There are no removals return rules; } // Do a second pass and keep only non-removed keybindings const result = []; for (let i = 0, len = rules.length; i < len; i++) { const rule = rules[i]; if (!rule.command || rule.command.length === 0) { result.push(rule); continue; } if (rule.command.charAt(0) === '-') { continue; } const commandRemovals = removals.get(rule.command); if (!commandRemovals || !rule.isDefault) { result.push(rule); continue; } let isRemoved = false; for (const commandRemoval of commandRemovals) { // TODO@chords const keypressFirstPart = commandRemoval.keypressParts[0]; const keypressChordPart = commandRemoval.keypressParts[1]; const when = commandRemoval.when; if (this._isTargetedForRemoval(rule, keypressFirstPart, keypressChordPart, when)) { isRemoved = true; break; } } if (!isRemoved) { result.push(rule); continue; } } return result; } _addKeyPress(keypress, item) { const conflicts = this._map.get(keypress); if (typeof conflicts === 'undefined') { // There is no conflict so far this._map.set(keypress, [item]); this._addToLookupMap(item); return; } for (let i = conflicts.length - 1; i >= 0; i--) { 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 (0, contextkey_1.implies)(a, b); } getKeybindings() { return this._keybindings; } lookupPrimaryKeybinding(commandId, context) { const items = this._lookupMap.get(commandId); if (typeof items === 'undefined' || items.length === 0) { return null; } if (items.length === 1) { return items[0]; } for (let i = items.length - 1; i >= 0; i--) { const item = items[i]; if (context.contextMatchesRules(item.when)) { return item; } } return items[items.length - 1]; } 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[274/*vs/platform/keybinding/common/resolvedKeybindingItem*/], __M([1/*require*/,0/*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[611/*vs/platform/keybinding/common/usLayoutResolvedKeybinding*/], __M([1/*require*/,0/*exports*/,55/*vs/base/common/keyCodes*/,94/*vs/base/common/keybindings*/,609/*vs/platform/keybinding/common/baseResolvedKeybinding*/,274/*vs/platform/keybinding/common/resolvedKeybindingItem*/]), function (require, exports, keyCodes_1, keybindings_1, baseResolvedKeybinding_1, resolvedKeybindingItem_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.USLayoutResolvedKeybinding = void 0; /** * Do not instantiate. Use KeybindingService to get a ResolvedKeybinding seeded with information about the current kb layout. */ class USLayoutResolvedKeybinding extends baseResolvedKeybinding_1.BaseResolvedKeybinding { constructor(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); } _getElectronAccelerator(keybinding) { return keyCodes_1.KeyCodeUtils.toElectronAccelerator(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; } /** * *NOTE*: Check return value for `KeyCode.Unknown`. */ static _scanCodeToKeyCode(scanCode) { const immutableKeyCode = keyCodes_1.IMMUTABLE_CODE_TO_KEY_CODE[scanCode]; if (immutableKeyCode !== -1 /* DependsOnKbLayout */) { return immutableKeyCode; } switch (scanCode) { case 10 /* KeyA */: return 31 /* KeyA */; case 11 /* KeyB */: return 32 /* KeyB */; case 12 /* KeyC */: return 33 /* KeyC */; case 13 /* KeyD */: return 34 /* KeyD */; case 14 /* KeyE */: return 35 /* KeyE */; case 15 /* KeyF */: return 36 /* KeyF */; case 16 /* KeyG */: return 37 /* KeyG */; case 17 /* KeyH */: return 38 /* KeyH */; case 18 /* KeyI */: return 39 /* KeyI */; case 19 /* KeyJ */: return 40 /* KeyJ */; case 20 /* KeyK */: return 41 /* KeyK */; case 21 /* KeyL */: return 42 /* KeyL */; case 22 /* KeyM */: return 43 /* KeyM */; case 23 /* KeyN */: return 44 /* KeyN */; case 24 /* KeyO */: return 45 /* KeyO */; case 25 /* KeyP */: return 46 /* KeyP */; case 26 /* KeyQ */: return 47 /* KeyQ */; case 27 /* KeyR */: return 48 /* KeyR */; case 28 /* KeyS */: return 49 /* KeyS */; case 29 /* KeyT */: return 50 /* KeyT */; case 30 /* KeyU */: return 51 /* KeyU */; case 31 /* KeyV */: return 52 /* KeyV */; case 32 /* KeyW */: return 53 /* KeyW */; case 33 /* KeyX */: return 54 /* KeyX */; case 34 /* KeyY */: return 55 /* KeyY */; case 35 /* KeyZ */: return 56 /* KeyZ */; case 36 /* Digit1 */: return 22 /* Digit1 */; case 37 /* Digit2 */: return 23 /* Digit2 */; case 38 /* Digit3 */: return 24 /* Digit3 */; case 39 /* Digit4 */: return 25 /* Digit4 */; case 40 /* Digit5 */: return 26 /* Digit5 */; case 41 /* Digit6 */: return 27 /* Digit6 */; case 42 /* Digit7 */: return 28 /* Digit7 */; case 43 /* Digit8 */: return 29 /* Digit8 */; case 44 /* Digit9 */: return 30 /* Digit9 */; case 45 /* Digit0 */: return 21 /* Digit0 */; case 51 /* Minus */: return 83 /* Minus */; case 52 /* Equal */: return 81 /* Equal */; case 53 /* BracketLeft */: return 87 /* BracketLeft */; case 54 /* BracketRight */: return 89 /* BracketRight */; case 55 /* Backslash */: return 88 /* Backslash */; case 56 /* IntlHash */: return 0 /* Unknown */; // missing case 57 /* Semicolon */: return 80 /* Semicolon */; case 58 /* Quote */: return 90 /* Quote */; case 59 /* Backquote */: return 86 /* Backquote */; case 60 /* Comma */: return 82 /* Comma */; case 61 /* Period */: return 84 /* Period */; case 62 /* Slash */: return 85 /* Slash */; case 106 /* IntlBackslash */: return 92 /* IntlBackslash */; } return 0 /* Unknown */; } static _resolveSimpleUserBinding(binding) { if (!binding) { return null; } if (binding instanceof keybindings_1.SimpleKeybinding) { return binding; } const keyCode = this._scanCodeToKeyCode(binding.scanCode); if (keyCode === 0 /* Unknown */) { return null; } return new keybindings_1.SimpleKeybinding(binding.ctrlKey, binding.shiftKey, binding.altKey, binding.metaKey, keyCode); } static resolveUserBinding(input, os) { const parts = (0, resolvedKeybindingItem_1.removeElementsAfterNulls)(input.map(keybinding => this._resolveSimpleUserBinding(keybinding))); if (parts.length > 0) { return [new USLayoutResolvedKeybinding(new keybindings_1.ChordKeybinding(parts), os)]; } return []; } } exports.USLayoutResolvedKeybinding = USLayoutResolvedKeybinding; }); define(__m[128/*vs/platform/label/common/label*/], __M([1/*require*/,0/*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[129/*vs/platform/layout/browser/layoutService*/], __M([1/*require*/,0/*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[275/*vs/editor/standalone/browser/standaloneLayoutService*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,4/*vs/base/common/event*/,129/*vs/platform/layout/browser/layoutService*/,28/*vs/editor/browser/services/codeEditorService*/,53/*vs/platform/instantiation/common/extensions*/]), function (require, exports, dom, event_1, layoutService_1, codeEditorService_1, extensions_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EditorScopedLayoutService = void 0; let StandaloneLayoutService = class StandaloneLayoutService { constructor(_codeEditorService) { this._codeEditorService = _codeEditorService; this.onDidLayout = event_1.Event.None; } get dimension() { if (!this._dimension) { this._dimension = dom.getClientArea(window.document.body); } return this._dimension; } get hasContainer() { return false; } get container() { // On a page, multiple editors can be created. Therefore, there are multiple containers, not // just a single one. Please use `ICodeEditorService` to get the current focused code editor // and use its container if necessary. You can also instantiate `EditorScopedLayoutService` // which implements `ILayoutService` but is not a part of the service collection because // it is code editor instance specific. throw new Error(`ILayoutService.container is not available in the standalone editor!`); } focus() { var _a; (_a = this._codeEditorService.getFocusedCodeEditor()) === null || _a === void 0 ? void 0 : _a.focus(); } }; StandaloneLayoutService = __decorate([ __param(0, codeEditorService_1.ICodeEditorService) ], StandaloneLayoutService); let EditorScopedLayoutService = class EditorScopedLayoutService extends StandaloneLayoutService { constructor(_container, codeEditorService) { super(codeEditorService); this._container = _container; } get hasContainer() { return false; } get container() { return this._container; } }; EditorScopedLayoutService = __decorate([ __param(1, codeEditorService_1.ICodeEditorService) ], EditorScopedLayoutService); exports.EditorScopedLayoutService = EditorScopedLayoutService; (0, extensions_1.registerSingleton)(layoutService_1.ILayoutService, StandaloneLayoutService); }); /*--------------------------------------------------------------------------------------------- * 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/platform/contextview/browser/contextViewService*/], __M([1/*require*/,0/*exports*/,222/*vs/base/browser/ui/contextview/contextview*/,2/*vs/base/common/lifecycle*/,129/*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.hasContainer ? layoutService.container : null; 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.layoutService.hasContainer && 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; }); define(__m[64/*vs/platform/log/common/log*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, event_1, lifecycle_1, instantiation_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[276/*vs/editor/browser/services/editorWorkerService*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,219/*vs/base/common/worker/simpleWorker*/,326/*vs/base/browser/defaultWorkerFactory*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/languages*/,32/*vs/editor/common/languages/languageConfigurationRegistry*/,429/*vs/editor/common/services/editorSimpleWorker*/,45/*vs/editor/common/services/model*/,153/*vs/editor/common/services/textResourceConfiguration*/,8/*vs/base/common/strings*/,19/*vs/base/common/arrays*/,64/*vs/platform/log/common/log*/,65/*vs/base/common/stopwatch*/,13/*vs/base/common/errors*/]), function (require, exports, async_1, lifecycle_1, simpleWorker_1, defaultWorkerFactory_1, range_1, modes, languageConfigurationRegistry_1, editorSimpleWorker_1, model_1, textResourceConfiguration_1, strings_1, arrays_1, log_1, stopwatch_1, errors_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EditorWorkerClient = exports.EditorWorkerHost = exports.EditorWorkerService = 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) { const model = modelService.getModel(resource); if (!model) { return false; } if (model.isTooLargeForSyncing()) { return false; } return true; } let EditorWorkerService = class EditorWorkerService extends lifecycle_1.Disposable { constructor(modelService, configurationService, logService, languageConfigurationService) { super(); this._modelService = modelService; this._workerManager = this._register(new WorkerManager(this._modelService, languageConfigurationService)); this._logService = logService; // register default link-provider and default completions-provider this._register(modes.LinkProviderRegistry.register({ language: '*', hasAccessToAllModels: true }, { 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, languageConfigurationService))); } dispose() { super.dispose(); } canComputeUnicodeHighlights(uri) { return canSyncModel(this._modelService, uri); } computedUnicodeHighlights(uri, options, range) { return this._workerManager.withWorker().then(client => client.computedUnicodeHighlights(uri, options, range)); } 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)); } }; EditorWorkerService = __decorate([ __param(0, model_1.IModelService), __param(1, textResourceConfiguration_1.ITextResourceConfigurationService), __param(2, log_1.ILogService), __param(3, languageConfigurationRegistry_1.ILanguageConfigurationService) ], EditorWorkerService); exports.EditorWorkerService = EditorWorkerService; class WordBasedCompletionItemProvider { constructor(workerManager, configurationService, modelService, languageConfigurationService) { this.languageConfigurationService = languageConfigurationService; 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.getLanguageId() === model.getLanguageId()) { models.push(candidate.uri); } } } if (models.length === 0) { return undefined; // File too large, no other files } const wordDefRegExp = this.languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition(); const word = model.getWordAtPosition(position); const replace = !word ? range_1.Range.fromPositions(position) : new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn); const insert = replace.setEndPosition(position.lineNumber, position.column); const client = 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, languageConfigurationService) { super(); this.languageConfigurationService = languageConfigurationService; this._modelService = modelService; this._editorWorkerClient = null; this._lastWorkerUsedTime = (new Date()).getTime(); const 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; } const models = this._modelService.getModels(); if (models.length === 0) { // There are no more models => nothing possible for me to do this._editorWorkerClient.dispose(); this._editorWorkerClient = null; } } /** * Check if the worker has been idle for a while and then stop it. */ _checkStopIdleWorker() { if (!this._editorWorkerClient) { return; } const timeSinceLastWorkerUsedTime = (new Date()).getTime() - this._lastWorkerUsedTime; if (timeSinceLastWorkerUsedTime > STOP_WORKER_DELTA_TIME_MS) { this._editorWorkerClient.dispose(); this._editorWorkerClient = null; } } withWorker() { this._lastWorkerUsedTime = (new Date()).getTime(); if (!this._editorWorkerClient) { this._editorWorkerClient = new EditorWorkerClient(this._modelService, false, 'editorWorkerService', this.languageConfigurationService); } 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) { const 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, forceLargeModels) { for (const resource of resources) { const resourceStr = resource.toString(); if (!this._syncedModels[resourceStr]) { this._beginModelSync(resource, forceLargeModels); } if (this._syncedModels[resourceStr]) { this._syncedModelsLastUsedTime[resourceStr] = (new Date()).getTime(); } } } _checkStopModelSync() { const currentTime = (new Date()).getTime(); const toRemove = []; for (let modelUrl in this._syncedModelsLastUsedTime) { const 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, forceLargeModels) { const model = this._modelService.getModel(resource); if (!model) { return; } if (!forceLargeModels && model.isTooLargeForSyncing()) { return; } const modelUrl = resource.toString(); this._proxy.acceptNewModel({ url: model.uri.toString(), lines: model.getLinesContent(), EOL: model.getEOL(), versionId: model.getVersionId() }); const toDispose = new lifecycle_1.DisposableStore(); toDispose.add(model.onDidChangeContent((e) => { this._proxy.acceptModelChanged(modelUrl.toString(), e); })); toDispose.add(model.onWillDispose(() => { this._stopModelSync(modelUrl); })); toDispose.add((0, lifecycle_1.toDisposable)(() => { this._proxy.acceptRemovedModel(modelUrl); })); this._syncedModels[modelUrl] = toDispose; } _stopModelSync(modelUrl) { const toDispose = this._syncedModels[modelUrl]; delete this._syncedModels[modelUrl]; delete this._syncedModelsLastUsedTime[modelUrl]; (0, lifecycle_1.dispose)(toDispose); } } 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, languageConfigurationService) { super(); this.languageConfigurationService = languageConfigurationService; 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, forceLargeModels = false) { return __awaiter(this, void 0, void 0, function* () { if (this._disposed) { return Promise.reject((0, errors_1.canceled)()); } return this._getProxy().then((proxy) => { this._getOrCreateModelManager(proxy).ensureSyncedResources(resources, forceLargeModels); return proxy; }); }); } computedUnicodeHighlights(uri, options, range) { return this._withSyncedResources([uri]).then(proxy => { return proxy.computeUnicodeHighlights(uri.toString(), options, range); }); } computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime) { return this._withSyncedResources([original, modified], /* forceLargeModels */ true).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 => { const model = this._modelService.getModel(resource); if (!model) { return Promise.resolve(null); } const wordDefRegExp = this.languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition(); const wordDef = wordDefRegExp.source; const wordDefFlags = (0, strings_1.regExpFlags)(wordDefRegExp); return proxy.computeWordRanges(resource.toString(), range, wordDef, wordDefFlags); }); } navigateValueSet(resource, range, up) { return this._withSyncedResources([resource]).then(proxy => { const model = this._modelService.getModel(resource); if (!model) { return null; } const wordDefRegExp = this.languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition(); const wordDef = wordDefRegExp.source; const 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[613/*vs/editor/browser/services/webWorker*/], __M([1/*require*/,0/*exports*/,276/*vs/editor/browser/services/editorWorkerService*/,20/*vs/base/common/types*/]), function (require, exports, editorWorkerService_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, languageConfigurationService, opts) { return new MonacoWebWorkerImpl(modelService, languageConfigurationService, opts); } exports.createWebWorker = createWebWorker; class MonacoWebWorkerImpl extends editorWorkerService_1.EditorWorkerClient { constructor(modelService, languageConfigurationService, opts) { super(modelService, opts.keepIdleModels || false, opts.label, languageConfigurationService); 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); }; }; const foreignProxy = {}; for (const foreignMethod of foreignMethods) { foreignProxy[foreignMethod] = createProxyMethod(foreignMethod, proxyMethodRequest); } return foreignProxy; }); }); } return this._foreignProxy; } getProxy() { return this._getForeignProxy(); } withSyncedResources(resources) { return this._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[92/*vs/editor/common/services/languageFeatureDebounce*/], __M([1/*require*/,0/*exports*/,112/*vs/base/common/hash*/,47/*vs/base/common/map*/,111/*vs/base/common/numbers*/,53/*vs/platform/instantiation/common/extensions*/,9/*vs/platform/instantiation/common/instantiation*/,64/*vs/platform/log/common/log*/]), function (require, exports, hash_1, map_1, numbers_1, extensions_1, instantiation_1, log_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LanguageFeatureDebounceService = exports.ILanguageFeatureDebounceService = void 0; exports.ILanguageFeatureDebounceService = (0, instantiation_1.createDecorator)('ILanguageFeatureDebounceService'); var IdentityHash; (function (IdentityHash) { const _hashes = new WeakMap(); let pool = 0; function of(obj) { let value = _hashes.get(obj); if (value === undefined) { value = ++pool; _hashes.set(obj, value); } return value; } IdentityHash.of = of; })(IdentityHash || (IdentityHash = {})); class FeatureDebounceInformation { constructor(_logService, _name, _registry, _default, _min, _max) { this._logService = _logService; this._name = _name; this._registry = _registry; this._default = _default; this._min = _min; this._max = _max; this._cache = new map_1.LRUCache(50, 0.7); } _key(model) { return model.id + this._registry.all(model).reduce((hashVal, obj) => (0, hash_1.doHash)(IdentityHash.of(obj), hashVal), 0); } get(model) { const key = this._key(model); const avg = this._cache.get(key); return avg ? (0, numbers_1.clamp)(avg.value, this._min, this._max) : this.default(); } update(model, value) { const key = this._key(model); let avg = this._cache.get(key); if (!avg) { avg = new numbers_1.SlidingWindowAverage(6); this._cache.set(key, avg); } const newValue = (0, numbers_1.clamp)(avg.update(value), this._min, this._max); this._logService.trace(`[DEBOUNCE: ${this._name}] for ${model.uri.toString()} is ${newValue}ms`); return newValue; } _overall() { const result = new numbers_1.MovingAverage(); for (const [, avg] of this._cache) { result.update(avg.value); } return result.value; } default() { const value = (this._overall() | 0) || this._default; return (0, numbers_1.clamp)(value, this._min, this._max); } } let LanguageFeatureDebounceService = class LanguageFeatureDebounceService { constructor(_logService) { this._logService = _logService; this._data = new Map(); } for(feature, name, config) { var _a, _b, _c; const min = (_a = config === null || config === void 0 ? void 0 : config.min) !== null && _a !== void 0 ? _a : 50; const max = (_b = config === null || config === void 0 ? void 0 : config.max) !== null && _b !== void 0 ? _b : Math.pow(min, 2); const extra = (_c = config === null || config === void 0 ? void 0 : config.key) !== null && _c !== void 0 ? _c : undefined; const key = `${IdentityHash.of(feature)},${min}${extra ? ',' + extra : ''}`; let info = this._data.get(key); if (!info) { info = new FeatureDebounceInformation(this._logService, name, feature, (this._overallAverage() | 0) || (min * 1.5), // default is overall default or derived from min-value min, max); this._data.set(key, info); } return info; } _overallAverage() { // Average of all language features. Not a great value but an approximation let result = new numbers_1.MovingAverage(); for (let info of this._data.values()) { result.update(info.default()); } return result.value; } }; LanguageFeatureDebounceService = __decorate([ __param(0, log_1.ILogService) ], LanguageFeatureDebounceService); exports.LanguageFeatureDebounceService = LanguageFeatureDebounceService; (0, extensions_1.registerSingleton)(exports.ILanguageFeatureDebounceService, LanguageFeatureDebounceService, 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[199/*vs/editor/contrib/documentSymbols/browser/outlineModel*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,21/*vs/base/common/cancellation*/,13/*vs/base/common/errors*/,54/*vs/base/common/iterator*/,47/*vs/base/common/map*/,11/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/languages*/,92/*vs/editor/common/services/languageFeatureDebounce*/,9/*vs/platform/instantiation/common/instantiation*/,53/*vs/platform/instantiation/common/extensions*/,45/*vs/editor/common/services/model*/,2/*vs/base/common/lifecycle*/]), function (require, exports, arrays_1, cancellation_1, errors_1, iterator_1, map_1, position_1, range_1, languages_1, languageFeatureDebounce_1, instantiation_1, extensions_1, model_1, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OutlineModelService = exports.IOutlineModelService = exports.OutlineModel = exports.OutlineGroup = exports.OutlineElement = exports.TreeElement = void 0; class TreeElement { remove() { 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) { const cts = new cancellation_1.CancellationTokenSource(token); const result = new OutlineModel(textModel.uri); const provider = languages_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 = languages_1.DocumentSymbolProviderRegistry.onDidChange(() => { const newProvider = languages_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) => position_1.Position.compare(range_1.Range.getStartPosition(a.range), range_1.Range.getStartPosition(b.range)) || position_1.Position.compare(range_1.Range.getEndPosition(b.range), range_1.Range.getEndPosition(a.range))); } static _flattenDocumentSymbols(bucket, entries, overrideContainerLabel) { for (const entry of entries) { bucket.push({ kind: entry.kind, tags: entry.tags, name: entry.name, detail: entry.detail, containerName: entry.containerName || overrideContainerLabel, range: entry.range, selectionRange: entry.selectionRange, children: undefined, // we flatten it... }); // Recurse over children if (entry.children) { OutlineModel._flattenDocumentSymbols(bucket, entry.children, entry.name); } } } } exports.OutlineModel = OutlineModel; exports.IOutlineModelService = (0, instantiation_1.createDecorator)('IOutlineModelService'); let OutlineModelService = class OutlineModelService { constructor(debounces, modelService) { this._disposables = new lifecycle_1.DisposableStore(); this._cache = new map_1.LRUCache(10, 0.7); this._debounceInformation = debounces.for(languages_1.DocumentSymbolProviderRegistry, 'DocumentSymbols', { min: 350 }); // don't cache outline models longer than their text model this._disposables.add(modelService.onModelRemoved(textModel => { this._cache.delete(textModel.id); })); } dispose() { this._disposables.dispose(); } getOrCreate(textModel, token) { return __awaiter(this, void 0, void 0, function* () { const provider = languages_1.DocumentSymbolProviderRegistry.ordered(textModel); let data = this._cache.get(textModel.id); if (!data || data.versionId !== textModel.getVersionId() || !(0, arrays_1.equals)(data.provider, provider)) { let source = new cancellation_1.CancellationTokenSource(); data = { versionId: textModel.getVersionId(), provider, promiseCnt: 0, source, promise: OutlineModel.create(textModel, source.token), model: undefined, }; this._cache.set(textModel.id, data); const now = Date.now(); data.promise.then(outlineModel => { data.model = outlineModel; this._debounceInformation.update(textModel, Date.now() - now); }).catch(_err => { this._cache.delete(textModel.id); }); } if (data.model) { // resolved -> return data return data.model; } // increase usage counter data.promiseCnt += 1; const listener = token.onCancellationRequested(() => { // last -> cancel provider request, remove cached promise if (--data.promiseCnt === 0) { data.source.cancel(); this._cache.delete(textModel.id); } }); try { return yield data.promise; } finally { listener.dispose(); } }); } }; OutlineModelService = __decorate([ __param(0, languageFeatureDebounce_1.ILanguageFeatureDebounceService), __param(1, model_1.IModelService) ], OutlineModelService); exports.OutlineModelService = OutlineModelService; (0, extensions_1.registerSingleton)(exports.IOutlineModelService, OutlineModelService, 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[614/*vs/editor/contrib/documentSymbols/browser/documentSymbols*/], __M([1/*require*/,0/*exports*/,21/*vs/base/common/cancellation*/,20/*vs/base/common/types*/,25/*vs/base/common/uri*/,58/*vs/editor/common/services/resolverService*/,199/*vs/editor/contrib/documentSymbols/browser/outlineModel*/,26/*vs/platform/commands/common/commands*/]), function (require, exports, cancellation_1, types_1, uri_1, resolverService_1, outlineModel_1, commands_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); commands_1.CommandsRegistry.registerCommand('_executeDocumentSymbolProvider', function (accessor, ...args) { return __awaiter(this, void 0, void 0, function* () { const [resource] = args; (0, types_1.assertType)(uri_1.URI.isUri(resource)); const outlineService = accessor.get(outlineModel_1.IOutlineModelService); const modelService = accessor.get(resolverService_1.ITextModelService); const reference = yield modelService.createModelReference(resource); try { return (yield outlineService.getOrCreate(reference.object.textEditorModel, cancellation_1.CancellationToken.None)).getTopLevelSymbols(); } finally { reference.dispose(); } }); }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[615/*vs/platform/clipboard/browser/clipboardService*/], __M([1/*require*/,0/*exports*/,34/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,10/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,129/*vs/platform/layout/browser/layoutService*/,64/*vs/platform/log/common/log*/]), function (require, exports, browser_1, dom_1, async_1, lifecycle_1, layoutService_1, log_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BrowserClipboardService = void 0; let BrowserClipboardService = class BrowserClipboardService extends lifecycle_1.Disposable { constructor(layoutService, logService) { super(); this.layoutService = layoutService; this.logService = logService; this.mapTextToType = new Map(); // unsupported in web (only in-memory) this.findText = ''; // unsupported in web (only in-memory) if (browser_1.isSafari || browser_1.isWebkitWebView) { this.installWebKitWriteTextWorkaround(); } } // In Safari, it has the following note: // // "The request to write to the clipboard must be triggered during a user gesture. // A call to clipboard.write or clipboard.writeText outside the scope of a user // gesture(such as "click" or "touch" event handlers) will result in the immediate // rejection of the promise returned by the API call." // From: https://webkit.org/blog/10855/async-clipboard-api/ // // Since extensions run in a web worker, and handle gestures in an asynchronous way, // they are not classified by Safari as "in response to a user gesture" and will reject. // // This function sets up some handlers to work around that behavior. installWebKitWriteTextWorkaround() { const handler = () => { const currentWritePromise = new async_1.DeferredPromise(); // Cancel the previous promise since we just created a new one in response to this new event if (this.webKitPendingClipboardWritePromise && !this.webKitPendingClipboardWritePromise.isSettled) { this.webKitPendingClipboardWritePromise.cancel(); } this.webKitPendingClipboardWritePromise = currentWritePromise; // The ctor of ClipboardItem allows you to pass in a promise that will resolve to a string. // This allows us to pass in a Promise that will either be cancelled by another event or // resolved with the contents of the first call to this.writeText. // see https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem/ClipboardItem#parameters navigator.clipboard.write([new ClipboardItem({ 'text/plain': currentWritePromise.p, })]).catch((err) => __awaiter(this, void 0, void 0, function* () { if (!(err instanceof Error) || err.name !== 'NotAllowedError' || !currentWritePromise.isRejected) { this.logService.error(err); } })); }; if (this.layoutService.hasContainer) { this._register((0, dom_1.addDisposableListener)(this.layoutService.container, 'click', handler)); this._register((0, dom_1.addDisposableListener)(this.layoutService.container, 'keydown', handler)); } } 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; } if (this.webKitPendingClipboardWritePromise) { // For Safari, we complete this Promise which allows the call to `navigator.clipboard.write()` // above to resolve and successfully copy to the clipboard. If we let this continue, Safari // would throw an error because this call stack doesn't appear to originate from a user gesture. return this.webKitPendingClipboardWritePromise.complete(text); } // Guard access to navigator.clipboard with try/catch // as we have seen DOMExceptions in certain browsers // due to security policies. try { return 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; }); } }; BrowserClipboardService = __decorate([ __param(0, layoutService_1.ILayoutService), __param(1, log_1.ILogService) ], BrowserClipboardService); 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[77/*vs/platform/markers/common/markers*/], __M([1/*require*/,0/*exports*/,74/*vs/base/common/severity*/,587/*vs/nls!vs/platform/markers/common/markers*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, severity_1, nls_1, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IMarkerService = exports.IMarkerData = exports.MarkerSeverity = void 0; var MarkerSeverity; (function (MarkerSeverity) { MarkerSeverity[MarkerSeverity["Hint"] = 1] = "Hint"; MarkerSeverity[MarkerSeverity["Info"] = 2] = "Info"; MarkerSeverity[MarkerSeverity["Warning"] = 4] = "Warning"; MarkerSeverity[MarkerSeverity["Error"] = 8] = "Error"; })(MarkerSeverity = exports.MarkerSeverity || (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[616/*vs/editor/contrib/gotoError/browser/markerNavigationService*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,81/*vs/base/common/linkedList*/,8/*vs/base/common/strings*/,25/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,53/*vs/platform/instantiation/common/extensions*/,9/*vs/platform/instantiation/common/instantiation*/,77/*vs/platform/markers/common/markers*/,40/*vs/platform/configuration/common/configuration*/]), function (require, exports, arrays_1, event_1, lifecycle_1, linkedList_1, strings_1, uri_1, range_1, extensions_1, instantiation_1, markers_1, configuration_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IMarkerNavigationService = exports.MarkerList = exports.MarkerCoordinate = void 0; class MarkerCoordinate { constructor(marker, index, total) { this.marker = marker; this.index = index; this.total = total; } } exports.MarkerCoordinate = MarkerCoordinate; let MarkerList = class MarkerList { constructor(resourceFilter, _markerService, _configService) { this._markerService = _markerService; this._configService = _configService; this._onDidChange = new event_1.Emitter(); this.onDidChange = this._onDidChange.event; this._dispoables = new lifecycle_1.DisposableStore(); this._markers = []; this._nextIdx = -1; if (uri_1.URI.isUri(resourceFilter)) { this._resourceFilter = uri => uri.toString() === resourceFilter.toString(); } else if (resourceFilter) { this._resourceFilter = resourceFilter; } const compareOrder = this._configService.getValue('problems.sortOrder'); const compareMarker = (a, b) => { let res = (0, strings_1.compare)(a.resource.toString(), b.resource.toString()); if (compareOrder === 'position') { res = range_1.Range.compareRangesUsingStarts(a, b) || markers_1.MarkerSeverity.compare(a.severity, b.severity); } else { res = markers_1.MarkerSeverity.compare(a.severity, b.severity) || range_1.Range.compareRangesUsingStarts(a, b); } return res; }; const updateMarker = () => { this._markers = this._markerService.read({ resource: uri_1.URI.isUri(resourceFilter) ? resourceFilter : undefined, severities: markers_1.MarkerSeverity.Error | markers_1.MarkerSeverity.Warning | markers_1.MarkerSeverity.Info }); if (typeof resourceFilter === 'function') { this._markers = this._markers.filter(m => this._resourceFilter(m.resource)); } this._markers.sort(compareMarker); }; updateMarker(); this._dispoables.add(_markerService.onMarkerChanged(uris => { if (!this._resourceFilter || uris.some(uri => this._resourceFilter(uri))) { updateMarker(); this._nextIdx = -1; this._onDidChange.fire(); } })); } dispose() { this._dispoables.dispose(); this._onDidChange.dispose(); } matches(uri) { if (!this._resourceFilter && !uri) { return true; } if (!this._resourceFilter || !uri) { return false; } return this._resourceFilter(uri); } get selected() { const marker = this._markers[this._nextIdx]; return marker && new MarkerCoordinate(marker, this._nextIdx + 1, this._markers.length); } _initIdx(model, position, fwd) { let found = false; let idx = this._markers.findIndex(marker => marker.resource.toString() === model.uri.toString()); if (idx < 0) { idx = (0, arrays_1.binarySearch)(this._markers, { resource: model.uri }, (a, b) => (0, strings_1.compare)(a.resource.toString(), b.resource.toString())); if (idx < 0) { idx = ~idx; } } for (let i = idx; i < this._markers.length; i++) { let range = range_1.Range.lift(this._markers[i]); if (range.isEmpty()) { const word = model.getWordAtPosition(range.getStartPosition()); if (word) { range = new range_1.Range(range.startLineNumber, word.startColumn, range.startLineNumber, word.endColumn); } } if (position && (range.containsPosition(position) || position.isBeforeOrEqual(range.getStartPosition()))) { this._nextIdx = i; found = true; break; } if (this._markers[i].resource.toString() !== model.uri.toString()) { break; } } if (!found) { // after the last change this._nextIdx = fwd ? 0 : this._markers.length - 1; } if (this._nextIdx < 0) { this._nextIdx = this._markers.length - 1; } } resetIndex() { this._nextIdx = -1; } move(fwd, model, position) { if (this._markers.length === 0) { return false; } 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; } }; MarkerList = __decorate([ __param(1, markers_1.IMarkerService), __param(2, configuration_1.IConfigurationService) ], MarkerList); exports.MarkerList = MarkerList; exports.IMarkerNavigationService = (0, instantiation_1.createDecorator)('IMarkerNavigationService'); let MarkerNavigationService = class MarkerNavigationService { constructor(_markerService, _configService) { this._markerService = _markerService; this._configService = _configService; this._provider = new linkedList_1.LinkedList(); } getMarkerList(resource) { for (let provider of this._provider) { const result = provider.getMarkerList(resource); if (result) { return result; } } // default return new MarkerList(resource, this._markerService, this._configService); } }; MarkerNavigationService = __decorate([ __param(0, markers_1.IMarkerService), __param(1, configuration_1.IConfigurationService) ], MarkerNavigationService); (0, extensions_1.registerSingleton)(exports.IMarkerNavigationService, MarkerNavigationService, 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[617/*vs/platform/markers/common/markerService*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,4/*vs/base/common/event*/,54/*vs/base/common/iterator*/,47/*vs/base/common/map*/,48/*vs/base/common/network*/,25/*vs/base/common/uri*/,77/*vs/platform/markers/common/markers*/]), function (require, exports, arrays_1, event_1, iterator_1, map_1, network_1, uri_1, markers_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MarkerService = 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; }); define(__m[38/*vs/platform/notification/common/notification*/], __M([1/*require*/,0/*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[51/*vs/platform/opener/common/opener*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,25/*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.selectionFragment = exports.matchesSomeScheme = 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; function matchesSomeScheme(target, ...schemes) { return schemes.some(scheme => matchesScheme(target, scheme)); } exports.matchesSomeScheme = matchesSomeScheme; function selectionFragment(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 }; } return selection; } exports.selectionFragment = selectionFragment; }); /*--------------------------------------------------------------------------------------------- * 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/browser/services/openerService*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,21/*vs/base/common/cancellation*/,81/*vs/base/common/linkedList*/,47/*vs/base/common/map*/,216/*vs/base/common/marshalling*/,48/*vs/base/common/network*/,41/*vs/base/common/resources*/,25/*vs/base/common/uri*/,28/*vs/editor/browser/services/codeEditorService*/,26/*vs/platform/commands/common/commands*/,594/*vs/platform/editor/common/editor*/,51/*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); } const selection = (0, opener_1.selectionFragment)(target); if (selection) { 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.matchesSomeScheme)(href, network_1.Schemas.http, 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.matchesSomeScheme)(target, network_1.Schemas.mailto, network_1.Schemas.http, network_1.Schemas.https, network_1.Schemas.vsls)) { // 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; }); define(__m[71/*vs/platform/progress/common/progress*/], __M([1/*require*/,0/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IEditorProgressService = exports.Progress = exports.emptyProgressRunner = void 0; exports.emptyProgressRunner = Object.freeze({ total() { }, worked() { }, done() { } }); 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[619/*vs/platform/quickinput/browser/pickerQuickAccess*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/async*/,21/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/]), function (require, exports, async_1, cancellation_1, lifecycle_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(); const removed = items.splice(index, 1); const activeItems = picker.activeItems.filter(activeItem => activeItem !== removed[0]); const keepScrollPositionBefore = picker.keepScrollPosition; picker.keepScrollPosition = true; picker.items = items; if (activeItems) { picker.activeItems = activeItems; } picker.keepScrollPosition = keepScrollPositionBefore; } break; } } } } }))); return disposables; } } exports.PickerQuickAccessProvider = PickerQuickAccessProvider; PickerQuickAccessProvider.FAST_PICKS_RACE_DELAY = 200; // timeout before we accept fast results before slow results are present }); /*--------------------------------------------------------------------------------------------- * 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[78/*vs/platform/quickinput/common/quickInput*/], __M([1/*require*/,0/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,220/*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[36/*vs/platform/registry/common/platform*/], __M([1/*require*/,0/*exports*/,213/*vs/base/common/assert*/,20/*vs/base/common/types*/]), function (require, exports, Assert, Types) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Registry = void 0; class RegistryImpl { constructor() { this.data = new Map(); } add(id, data) { Assert.ok(Types.isString(id)); Assert.ok(Types.isObject(data)); Assert.ok(!this.data.has(id), 'There is already an extension with this id'); this.data.set(id, data); } as(id) { return this.data.get(id) || null; } } exports.Registry = new RegistryImpl(); }); /*--------------------------------------------------------------------------------------------- * 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/platform/jsonschemas/common/jsonContributionRegistry*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,36/*vs/platform/registry/common/platform*/]), function (require, exports, event_1, platform) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Extensions = void 0; exports.Extensions = { JSONContribution: 'base.contributions.json' }; function normalizeId(id) { if (id.length > 0 && id.charAt(id.length - 1) === '#') { return id.substring(0, id.length - 1); } return id; } class JSONContributionRegistry { constructor() { this._onDidChangeSchema = new event_1.Emitter(); this.schemasById = {}; } registerSchema(uri, unresolvedSchemaContent) { this.schemasById[normalizeId(uri)] = unresolvedSchemaContent; this._onDidChangeSchema.fire(uri); } notifySchemaChanged(uri) { this._onDidChangeSchema.fire(uri); } } const jsonContributionRegistry = new JSONContributionRegistry(); platform.Registry.add(exports.Extensions.JSONContribution, jsonContributionRegistry); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[103/*vs/platform/configuration/common/configurationRegistry*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,4/*vs/base/common/event*/,20/*vs/base/common/types*/,582/*vs/nls!vs/platform/configuration/common/configurationRegistry*/,200/*vs/platform/jsonschemas/common/jsonContributionRegistry*/,36/*vs/platform/registry/common/platform*/]), function (require, exports, arrays_1, event_1, types, nls, jsonContributionRegistry_1, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateProperty = exports.getDefaultValue = exports.overrideIdentifiersFromKey = exports.OVERRIDE_PROPERTY_REGEX = exports.OVERRIDE_PROPERTY_PATTERN = exports.resourceLanguageSettingsSchemaId = exports.resourceSettings = exports.windowSettings = exports.machineOverridableSettings = exports.machineSettings = exports.applicationSettings = exports.allSettings = exports.Extensions = void 0; exports.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.configurationDefaultsOverrides = new Map(); 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); this.registerOverridePropertyPatternKey(); } registerConfiguration(configuration, validate = true) { this.registerConfigurations([configuration], validate); } registerConfigurations(configurations, validate = true) { const properties = this.doRegisterConfigurations(configurations, validate); contributionRegistry.registerSchema(exports.resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema); this._onDidSchemaChange.fire(); this._onDidUpdateConfiguration.fire({ properties }); } registerDefaultConfigurations(configurationDefaults) { var _a; const properties = []; const overrideIdentifiers = []; for (const { overrides, source } of configurationDefaults) { for (const key in overrides) { properties.push(key); if (exports.OVERRIDE_PROPERTY_REGEX.test(key)) { const defaultValue = Object.assign(Object.assign({}, (((_a = this.configurationDefaultsOverrides.get(key)) === null || _a === void 0 ? void 0 : _a.value) || {})), overrides[key]); this.configurationDefaultsOverrides.set(key, { source, value: defaultValue }); const property = { type: 'object', default: defaultValue, description: nls.localize(1, null, key), $ref: exports.resourceLanguageSettingsSchemaId, defaultDefaultValue: defaultValue, source: types.isString(source) ? undefined : source, }; overrideIdentifiers.push(...overrideIdentifiersFromKey(key)); this.configurationProperties[key] = property; this.defaultLanguageConfigurationOverridesNode.properties[key] = property; } else { this.configurationDefaultsOverrides.set(key, { value: overrides[key], source }); const property = this.configurationProperties[key]; if (property) { this.updatePropertyDefaultValue(key, property); this.updateSchema(key, property); } } } } this.registerOverrideIdentifiers(overrideIdentifiers); this._onDidSchemaChange.fire(); this._onDidUpdateConfiguration.fire({ properties, defaultsOverrides: true }); } registerOverrideIdentifiers(overrideIdentifiers) { for (const overrideIdentifier of overrideIdentifiers) { this.overrideIdentifiers.add(overrideIdentifier); } this.updateOverridePropertyPatternKey(); } doRegisterConfigurations(configurations, validate) { const properties = []; configurations.forEach(configuration => { properties.push(...this.validateAndRegisterProperties(configuration, validate, configuration.extensionInfo, configuration.restrictedProperties)); // fills in defaults this.configurationContributors.push(configuration); this.registerJSONConfiguration(configuration); }); return properties; } validateAndRegisterProperties(configuration, validate = true, extensionInfo, restrictedProperties, scope = 3 /* WINDOW */) { 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]; property.source = extensionInfo; // update default value property.defaultDefaultValue = properties[key].default; this.updatePropertyDefaultValue(key, property); // update scope if (exports.OVERRIDE_PROPERTY_REGEX.test(key)) { property.scope = undefined; // No scope for overridable properties `[${identifier}]` } else { property.scope = types.isUndefinedOrNull(property.scope) ? scope : property.scope; property.restricted = types.isUndefinedOrNull(property.restricted) ? !!(restrictedProperties === null || restrictedProperties === void 0 ? void 0 : restrictedProperties.includes(key)) : property.restricted; } // Add to properties maps // Property is included by default if 'included' is unspecified if (properties[key].hasOwnProperty('included') && !properties[key].included) { this.excludedConfigurationProperties[key] = properties[key]; delete properties[key]; continue; } else { this.configurationProperties[key] = properties[key]; } if (!properties[key].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, restrictedProperties, 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(2, null), errorMessage: nls.localize(3, 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(); } registerOverridePropertyPatternKey() { const resourceLanguagePropertiesSchema = { type: 'object', description: nls.localize(4, null), errorMessage: nls.localize(5, null), $ref: exports.resourceLanguageSettingsSchemaId, }; exports.allSettings.patternProperties[exports.OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema; exports.applicationSettings.patternProperties[exports.OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema; exports.machineSettings.patternProperties[exports.OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema; exports.machineOverridableSettings.patternProperties[exports.OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema; exports.windowSettings.patternProperties[exports.OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema; exports.resourceSettings.patternProperties[exports.OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema; this._onDidSchemaChange.fire(); } updatePropertyDefaultValue(key, property) { const configurationdefaultOverride = this.configurationDefaultsOverrides.get(key); let defaultValue = configurationdefaultOverride === null || configurationdefaultOverride === void 0 ? void 0 : configurationdefaultOverride.value; let defaultSource = configurationdefaultOverride === null || configurationdefaultOverride === void 0 ? void 0 : configurationdefaultOverride.source; if (types.isUndefined(defaultValue)) { defaultValue = property.defaultDefaultValue; defaultSource = undefined; } if (types.isUndefined(defaultValue)) { defaultValue = getDefaultValue(property.type); } property.default = defaultValue; property.defaultValueSource = defaultSource; } } const OVERRIDE_IDENTIFIER_PATTERN = `\\[([^\\]]+)\\]`; const OVERRIDE_IDENTIFIER_REGEX = new RegExp(OVERRIDE_IDENTIFIER_PATTERN, 'g'); exports.OVERRIDE_PROPERTY_PATTERN = `^(${OVERRIDE_IDENTIFIER_PATTERN})+$`; exports.OVERRIDE_PROPERTY_REGEX = new RegExp(exports.OVERRIDE_PROPERTY_PATTERN); function overrideIdentifiersFromKey(key) { const identifiers = []; if (exports.OVERRIDE_PROPERTY_REGEX.test(key)) { let matches = OVERRIDE_IDENTIFIER_REGEX.exec(key); while (matches === null || matches === void 0 ? void 0 : matches.length) { const identifier = matches[1].trim(); if (identifier) { identifiers.push(identifier); } matches = OVERRIDE_IDENTIFIER_REGEX.exec(key); } } return (0, arrays_1.distinct)(identifiers); } exports.overrideIdentifiersFromKey = overrideIdentifiersFromKey; 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(6, null); } if (exports.OVERRIDE_PROPERTY_REGEX.test(property)) { return nls.localize(7, null, property); } if (configurationRegistry.getConfigurationProperties()[property] !== undefined) { return nls.localize(8, 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[620/*vs/editor/common/config/editorConfigurationSchema*/], __M([1/*require*/,0/*exports*/,31/*vs/editor/common/config/editorOptions*/,145/*vs/editor/common/core/textModelDefaults*/,505/*vs/nls!vs/editor/common/config/editorConfigurationSchema*/,103/*vs/platform/configuration/common/configurationRegistry*/,36/*vs/platform/registry/common/platform*/]), function (require, exports, editorOptions_1, textModelDefaults_1, nls, configurationRegistry_1, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isDiffEditorConfigurationKey = exports.isEditorConfigurationKey = exports.editorConfigurationBaseNode = void 0; exports.editorConfigurationBaseNode = Object.freeze({ id: 'editor', order: 5, type: 'object', title: nls.localize(0, null), scope: 5 /* LANGUAGE_OVERRIDABLE */, }); const editorConfiguration = Object.assign(Object.assign({}, exports.editorConfigurationBaseNode), { properties: { 'editor.tabSize': { type: 'number', default: textModelDefaults_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: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.insertSpaces, markdownDescription: nls.localize(2, null) }, 'editor.detectIndentation': { type: 'boolean', default: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.detectIndentation, markdownDescription: nls.localize(3, null) }, 'editor.trimAutoWhitespace': { type: 'boolean', default: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.trimAutoWhitespace, description: nls.localize(4, null) }, 'editor.largeFileOptimizations': { type: 'boolean', default: textModelDefaults_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) }, 'editor.language.brackets': { type: 'array', default: false, description: nls.localize(17, null), items: { type: 'array', items: [ { type: 'string', description: nls.localize(18, null) }, { type: 'string', description: nls.localize(19, null) } ] } }, 'editor.language.colorizedBracketPairs': { type: 'array', default: false, description: nls.localize(20, null), items: { type: 'array', items: [ { type: 'string', description: nls.localize(21, null) }, { type: 'string', description: nls.localize(22, null) } ] } }, 'diffEditor.maxComputationTime': { type: 'number', default: 5000, description: nls.localize(23, null) }, 'diffEditor.maxFileSize': { type: 'number', default: 50, description: nls.localize(24, null) }, 'diffEditor.renderSideBySide': { type: 'boolean', default: true, description: nls.localize(25, null) }, 'diffEditor.ignoreTrimWhitespace': { type: 'boolean', default: true, description: nls.localize(26, null) }, 'diffEditor.renderIndicators': { type: 'boolean', default: true, description: nls.localize(27, null) }, 'diffEditor.codeLens': { type: 'boolean', default: false, description: nls.localize(28, null) }, 'diffEditor.wordWrap': { type: 'string', enum: ['off', 'on', 'inherit'], default: 'inherit', markdownEnumDescriptions: [ nls.localize(29, null), nls.localize(30, null), nls.localize(31, 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 (const key in schema) { if (Object.hasOwnProperty.call(schema, key)) { editorConfiguration.properties[key] = schema[key]; } } } } } let cachedEditorConfigurationKeys = null; function getEditorConfigurationKeys() { if (cachedEditorConfigurationKeys === null) { cachedEditorConfigurationKeys = Object.create(null); Object.keys(editorConfiguration.properties).forEach((prop) => { cachedEditorConfigurationKeys[prop] = true; }); } return cachedEditorConfigurationKeys; } function isEditorConfigurationKey(key) { const editorConfigurationKeys = getEditorConfigurationKeys(); return (editorConfigurationKeys[`editor.${key}`] || false); } exports.isEditorConfigurationKey = isEditorConfigurationKey; function isDiffEditorConfigurationKey(key) { const editorConfigurationKeys = getEditorConfigurationKeys(); return (editorConfigurationKeys[`diffEditor.${key}`] || false); } exports.isDiffEditorConfigurationKey = isDiffEditorConfigurationKey; const configurationRegistry = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration); configurationRegistry.registerConfiguration(editorConfiguration); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[79/*vs/editor/common/languages/modesRegistry*/], __M([1/*require*/,0/*exports*/,513/*vs/nls!vs/editor/common/languages/modesRegistry*/,4/*vs/base/common/event*/,32/*vs/editor/common/languages/languageConfigurationRegistry*/,36/*vs/platform/registry/common/platform*/,135/*vs/base/common/mime*/,103/*vs/platform/configuration/common/configurationRegistry*/]), function (require, exports, nls, event_1, languageConfigurationRegistry_1, platform_1, mime_1, configurationRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PLAINTEXT_EXTENSION = exports.PLAINTEXT_LANGUAGE_ID = exports.ModesRegistry = exports.EditorModesRegistry = exports.Extensions = void 0; // Define extension point ids exports.Extensions = { ModesRegistry: 'editor.modesRegistry' }; class EditorModesRegistry { constructor() { this._onDidChangeLanguages = new event_1.Emitter(); this.onDidChangeLanguages = this._onDidChangeLanguages.event; this._languages = []; } registerLanguage(def) { this._languages.push(def); this._onDidChangeLanguages.fire(undefined); return { dispose: () => { for (let i = 0, len = this._languages.length; i < len; i++) { if (this._languages[i] === def) { this._languages.splice(i, 1); return; } } } }; } getLanguages() { return this._languages; } } exports.EditorModesRegistry = EditorModesRegistry; exports.ModesRegistry = new EditorModesRegistry(); platform_1.Registry.add(exports.Extensions.ModesRegistry, exports.ModesRegistry); exports.PLAINTEXT_LANGUAGE_ID = 'plaintext'; exports.PLAINTEXT_EXTENSION = '.txt'; exports.ModesRegistry.registerLanguage({ id: exports.PLAINTEXT_LANGUAGE_ID, extensions: [exports.PLAINTEXT_EXTENSION], aliases: [nls.localize(0, null), 'text'], mimetypes: [mime_1.Mimes.text] }); languageConfigurationRegistry_1.LanguageConfigurationRegistry.register(exports.PLAINTEXT_LANGUAGE_ID, { brackets: [ ['(', ')'], ['[', ']'], ['{', '}'], ], surroundingPairs: [ { open: '{', close: '}' }, { open: '[', close: ']' }, { open: '(', close: ')' }, { open: '<', close: '>' }, { open: '\"', close: '\"' }, { open: '\'', close: '\'' }, { open: '`', close: '`' }, ], colorizedBracketPairs: [], folding: { offSide: true } }, 0); platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration) .registerDefaultConfigurations([{ overrides: { '[plaintext]': { 'editor.unicodeHighlight.ambiguousCharacters': false, 'editor.unicodeHighlight.invisibleCharacters': false } } }]); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[621/*vs/editor/common/services/getIconClasses*/], __M([1/*require*/,0/*exports*/,48/*vs/base/common/network*/,41/*vs/base/common/resources*/,79/*vs/editor/common/languages/modesRegistry*/,269/*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.getIconClasses = void 0; function getIconClasses(modelService, languageService, 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 detectedLanguageId = detectLanguageId(modelService, languageService, resource); if (detectedLanguageId) { classes.push(`${cssEscape(detectedLanguageId)}-lang-file-icon`); } } } return classes; } exports.getIconClasses = getIconClasses; function detectLanguageId(modelService, languageService, resource) { if (!resource) { return null; // we need a resource at least } let languageId = null; // Data URI: check for encoded metadata if (resource.scheme === network_1.Schemas.data) { const metadata = resources_1.DataUri.parseMetaData(resource); const mime = metadata.get(resources_1.DataUri.META_DATA_MIME); if (mime) { languageId = languageService.getLanguageIdByMimeType(mime); } } // Any other URI: check for model if existing else { const model = modelService.getModel(resource); if (model) { languageId = model.getLanguageId(); } } // only take if the language id is specific (aka no just plain text) if (languageId && languageId !== modesRegistry_1.PLAINTEXT_LANGUAGE_ID) { return languageId; } // otherwise fallback to path based detection return languageService.guessLanguageIdByFilepathOrFirstLine(resource); } function cssEscape(str) { return str.replace(/[\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[622/*vs/editor/common/services/languagesRegistry*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,13/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,422/*vs/editor/common/services/languagesAssociations*/,79/*vs/editor/common/languages/modesRegistry*/,103/*vs/platform/configuration/common/configurationRegistry*/,36/*vs/platform/registry/common/platform*/]), function (require, exports, arrays_1, errors_1, event_1, lifecycle_1, strings_1, languagesAssociations_1, modesRegistry_1, configurationRegistry_1, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LanguagesRegistry = exports.LanguageIdCodec = void 0; const hasOwnProperty = Object.prototype.hasOwnProperty; const NULL_LANGUAGE_ID = 'vs.editor.nullLanguage'; class LanguageIdCodec { constructor() { this._languageIdToLanguage = []; this._languageToLanguageId = new Map(); this._register(NULL_LANGUAGE_ID, 0 /* Null */); this._register(modesRegistry_1.PLAINTEXT_LANGUAGE_ID, 1 /* PlainText */); this._nextLanguageId = 2; } _register(language, languageId) { this._languageIdToLanguage[languageId] = language; this._languageToLanguageId.set(language, languageId); } register(language) { if (this._languageToLanguageId.has(language)) { return; } const languageId = this._nextLanguageId++; this._register(language, languageId); } encodeLanguageId(languageId) { return this._languageToLanguageId.get(languageId) || 0 /* Null */; } decodeLanguageId(languageId) { return this._languageIdToLanguage[languageId] || NULL_LANGUAGE_ID; } } exports.LanguageIdCodec = LanguageIdCodec; 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; LanguagesRegistry.instanceCount++; this._warnOnOverwrite = warnOnOverwrite; this.languageIdCodec = new LanguageIdCodec(); this._dynamicLanguages = []; this._languages = {}; this._mimeTypesMap = {}; this._nameMap = {}; this._lowercaseNameMap = {}; if (useModesRegistry) { this._initializeFromRegistry(); this._register(modesRegistry_1.ModesRegistry.onDidChangeLanguages((m) => { this._initializeFromRegistry(); })); } } dispose() { LanguagesRegistry.instanceCount--; super.dispose(); } _initializeFromRegistry() { this._languages = {}; this._mimeTypesMap = {}; this._nameMap = {}; this._lowercaseNameMap = {}; (0, languagesAssociations_1.clearLanguageAssociations)(); const desc = [].concat(modesRegistry_1.ModesRegistry.getLanguages()).concat(this._dynamicLanguages); this._registerLanguages(desc); } _registerLanguages(desc) { for (const d of desc) { this._registerLanguage(d); } // Rebuild fast path maps this._mimeTypesMap = {}; this._nameMap = {}; this._lowercaseNameMap = {}; Object.keys(this._languages).forEach((langId) => { const language = this._languages[langId]; if (language.name) { this._nameMap[language.name] = language.identifier; } language.aliases.forEach((alias) => { this._lowercaseNameMap[alias.toLowerCase()] = language.identifier; }); language.mimetypes.forEach((mimetype) => { this._mimeTypesMap[mimetype] = language.identifier; }); }); platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).registerOverrideIdentifiers(this.getRegisteredLanguageIds()); this._onDidChange.fire(); } _registerLanguage(lang) { const langId = lang.id; let resolvedLanguage; if (hasOwnProperty.call(this._languages, langId)) { resolvedLanguage = this._languages[langId]; } else { this.languageIdCodec.register(langId); resolvedLanguage = { identifier: langId, name: null, mimetypes: [], aliases: [], extensions: [], filenames: [], configurationFiles: [], icons: [] }; this._languages[langId] = resolvedLanguage; } this._mergeLanguage(resolvedLanguage, lang); } _mergeLanguage(resolvedLanguage, lang) { const langId = lang.id; let primaryMime = null; if (Array.isArray(lang.mimetypes) && lang.mimetypes.length > 0) { resolvedLanguage.mimetypes.push(...lang.mimetypes); primaryMime = lang.mimetypes[0]; } if (!primaryMime) { primaryMime = `text/x-${langId}`; resolvedLanguage.mimetypes.push(primaryMime); } if (Array.isArray(lang.extensions)) { if (lang.configuration) { // insert first as this appears to be the 'primary' language definition resolvedLanguage.extensions = lang.extensions.concat(resolvedLanguage.extensions); } else { resolvedLanguage.extensions = resolvedLanguage.extensions.concat(lang.extensions); } for (let extension of lang.extensions) { (0, languagesAssociations_1.registerLanguageAssociation)({ id: langId, mime: primaryMime, extension: extension }, this._warnOnOverwrite); } } if (Array.isArray(lang.filenames)) { for (let filename of lang.filenames) { (0, languagesAssociations_1.registerLanguageAssociation)({ id: langId, mime: primaryMime, filename: filename }, this._warnOnOverwrite); resolvedLanguage.filenames.push(filename); } } if (Array.isArray(lang.filenamePatterns)) { for (let filenamePattern of lang.filenamePatterns) { (0, languagesAssociations_1.registerLanguageAssociation)({ id: langId, mime: primaryMime, filepattern: filenamePattern }, this._warnOnOverwrite); } } if (typeof lang.firstLine === 'string' && lang.firstLine.length > 0) { let firstLineRegexStr = lang.firstLine; if (firstLineRegexStr.charAt(0) !== '^') { firstLineRegexStr = '^' + firstLineRegexStr; } try { const firstLineRegex = new RegExp(firstLineRegexStr); if (!(0, strings_1.regExpLeadsToEndlessLoop)(firstLineRegex)) { (0, languagesAssociations_1.registerLanguageAssociation)({ 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); } } const containsAliases = (langAliases !== null && langAliases.length > 0); if (containsAliases && langAliases[0] === null) { // signal that this language should not get a name } else { const bestName = (containsAliases ? langAliases[0] : null) || langId; if (containsAliases || !resolvedLanguage.name) { resolvedLanguage.name = bestName; } } if (lang.configuration) { resolvedLanguage.configurationFiles.push(lang.configuration); } if (lang.icon) { resolvedLanguage.icons.push(lang.icon); } } isRegisteredLanguageId(languageId) { if (!languageId) { return false; } return hasOwnProperty.call(this._languages, languageId); } getRegisteredLanguageIds() { return Object.keys(this._languages); } getLanguageIdByLanguageName(languageName) { const languageNameLower = languageName.toLowerCase(); if (!hasOwnProperty.call(this._lowercaseNameMap, languageNameLower)) { return null; } return this._lowercaseNameMap[languageNameLower]; } getLanguageIdByMimeType(mimeType) { if (!mimeType) { return null; } if (hasOwnProperty.call(this._mimeTypesMap, mimeType)) { return this._mimeTypesMap[mimeType]; } return null; } guessLanguageIdByFilepathOrFirstLine(resource, firstLine) { if (!resource && !firstLine) { return []; } const mimeTypes = (0, languagesAssociations_1.getMimeTypes)(resource, firstLine); return (0, arrays_1.coalesce)(mimeTypes.map(mimeType => this.getLanguageIdByMimeType(mimeType))); } } exports.LanguagesRegistry = LanguagesRegistry; LanguagesRegistry.instanceCount = 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[623/*vs/editor/common/services/languageService*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,622/*vs/editor/common/services/languagesRegistry*/,19/*vs/base/common/arrays*/,18/*vs/editor/common/languages*/,79/*vs/editor/common/languages/modesRegistry*/]), function (require, exports, event_1, lifecycle_1, languagesRegistry_1, arrays_1, languages_1, modesRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LanguageService = void 0; class LanguageService extends lifecycle_1.Disposable { constructor(warnOnOverwrite = false) { super(); this._onDidEncounterLanguage = this._register(new event_1.Emitter()); this.onDidEncounterLanguage = this._onDidEncounterLanguage.event; this._onDidChange = this._register(new event_1.Emitter({ leakWarningThreshold: 200 /* https://github.com/microsoft/vscode/issues/119968 */ })); this.onDidChange = this._onDidChange.event; LanguageService.instanceCount++; this._encounteredLanguages = new Set(); this._registry = this._register(new languagesRegistry_1.LanguagesRegistry(true, warnOnOverwrite)); this.languageIdCodec = this._registry.languageIdCodec; this._register(this._registry.onDidChange(() => this._onDidChange.fire())); } dispose() { LanguageService.instanceCount--; super.dispose(); } isRegisteredLanguageId(languageId) { return this._registry.isRegisteredLanguageId(languageId); } getLanguageIdByLanguageName(languageName) { return this._registry.getLanguageIdByLanguageName(languageName); } getLanguageIdByMimeType(mimeType) { return this._registry.getLanguageIdByMimeType(mimeType); } guessLanguageIdByFilepathOrFirstLine(resource, firstLine) { const languageIds = this._registry.guessLanguageIdByFilepathOrFirstLine(resource, firstLine); return (0, arrays_1.firstOrDefault)(languageIds, null); } createById(languageId) { return new LanguageSelection(this.onDidChange, () => { return this._createAndGetLanguageIdentifier(languageId); }); } createByFilepathOrFirstLine(resource, firstLine) { return new LanguageSelection(this.onDidChange, () => { const languageId = this.guessLanguageIdByFilepathOrFirstLine(resource, firstLine); return this._createAndGetLanguageIdentifier(languageId); }); } _createAndGetLanguageIdentifier(languageId) { if (!languageId || !this.isRegisteredLanguageId(languageId)) { // Fall back to plain text if language is unknown languageId = modesRegistry_1.PLAINTEXT_LANGUAGE_ID; } if (!this._encounteredLanguages.has(languageId)) { this._encounteredLanguages.add(languageId); // Ensure tokenizers are created languages_1.TokenizationRegistry.getOrCreate(languageId); // Fire event this._onDidEncounterLanguage.fire(languageId); } return languageId; } } exports.LanguageService = LanguageService; LanguageService.instanceCount = 0; class LanguageSelection { constructor(_onDidChangeLanguages, _selector) { this._onDidChangeLanguages = _onDidChangeLanguages; this._selector = _selector; this._listener = null; this._emitter = null; this.languageId = this._selector(); } _dispose() { if (this._listener) { this._listener.dispose(); this._listener = null; } if (this._emitter) { this._emitter.dispose(); this._emitter = null; } } get onDidChange() { if (!this._listener) { this._listener = this._onDidChangeLanguages(() => this._evaluate()); } if (!this._emitter) { this._emitter = new event_1.Emitter({ onLastListenerRemove: () => { this._dispose(); } }); } return this._emitter.event; } _evaluate() { const languageId = this._selector(); if (languageId === this.languageId) { // no change return; } this.languageId = languageId; if (this._emitter) { this._emitter.fire(this.languageId); } } } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[104/*vs/editor/contrib/markdownRenderer/browser/markdownRenderer*/], __M([1/*require*/,0/*exports*/,324/*vs/base/browser/markdownRenderer*/,51/*vs/platform/opener/common/opener*/,35/*vs/editor/common/services/language*/,13/*vs/base/common/errors*/,249/*vs/editor/common/languages/textToHtmlTokenizer*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,62/*vs/editor/browser/config/domFontInfo*/,79/*vs/editor/common/languages/modesRegistry*/]), function (require, exports, markdownRenderer_1, opener_1, language_1, errors_1, textToHtmlTokenizer_1, event_1, lifecycle_1, domFontInfo_1, modesRegistry_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, _languageService, _openerService) { this._options = _options; this._languageService = _languageService; this._openerService = _openerService; this._onDidRenderAsync = new event_1.Emitter(); this.onDidRenderAsync = this._onDidRenderAsync.event; } dispose() { this._onDidRenderAsync.dispose(); } render(markdown, options, markedOptions) { if (!markdown) { const element = document.createElement('span'); return { element, dispose: () => { } }; } const disposables = new lifecycle_1.DisposableStore(); const rendered = disposables.add((0, markdownRenderer_1.renderMarkdown)(markdown, Object.assign(Object.assign({}, this._getRenderOptions(markdown, disposables)), options), markedOptions)); return { element: rendered.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; // In markdown, // it is possible that we stumble upon language aliases (e.g.js instead of javascript) // it is possible no alias is given in which case we fall back to the current editor lang let languageId; if (languageAlias) { languageId = this._languageService.getLanguageIdByLanguageName(languageAlias); } else if (this._options.editor) { languageId = (_a = this._options.editor.getModel()) === null || _a === void 0 ? void 0 : _a.getLanguageId(); } if (!languageId) { languageId = modesRegistry_1.PLAINTEXT_LANGUAGE_ID; } const html = yield (0, textToHtmlTokenizer_1.tokenizeToString)(this._languageService, value, languageId); const element = document.createElement('span'); element.innerHTML = ((_c = (_b = MarkdownRenderer._ttpTokenizer) === null || _b === void 0 ? void 0 : _b.createHTML(html)) !== null && _c !== void 0 ? _c : html); // use "good" font if (this._options.editor) { const fontInfo = this._options.editor.getOption(44 /* fontInfo */); (0, domFontInfo_1.applyFontInfo)(element, fontInfo); } else if (this._options.codeBlockFontFamily) { element.style.fontFamily = this._options.codeBlockFontFamily; } return element; }), asyncRenderCallback: () => this._onDidRenderAsync.fire(), actionHandler: { callback: (content) => this._openerService.open(content, { fromUserGesture: true, allowContributedOpeners: true, allowCommands: markdown.isTrusted }).catch(errors_1.onUnexpectedError), disposables: disposeables } }; } }; MarkdownRenderer._ttpTokenizer = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('tokenizeToString', { createHTML(html) { return html; } }); MarkdownRenderer = __decorate([ __param(1, language_1.ILanguageService), __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[624/*vs/editor/contrib/hover/browser/marginHover*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,19/*vs/base/common/arrays*/,66/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,104/*vs/editor/contrib/markdownRenderer/browser/markdownRenderer*/,257/*vs/editor/contrib/hover/browser/hoverOperation*/,51/*vs/platform/opener/common/opener*/,227/*vs/base/browser/ui/hover/hoverWidget*/]), function (require, exports, dom, arrays_1, htmlContent_1, lifecycle_1, markdownRenderer_1, hoverOperation_1, opener_1, hoverWidget_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MarginHoverWidget = void 0; const $ = dom.$; class MarginHoverWidget extends lifecycle_1.Disposable { constructor(editor, languageService, openerService = opener_1.NullOpenerService) { super(); this._renderDisposeables = this._register(new lifecycle_1.DisposableStore()); this._editor = editor; this._isVisible = false; this._messages = []; this._hover = this._register(new hoverWidget_1.HoverWidget()); this._hover.containerDomNode.classList.toggle('hidden', !this._isVisible); this._markdownRenderer = this._register(new markdownRenderer_1.MarkdownRenderer({ editor: this._editor }, languageService, openerService)); this._computer = new MarginHoverComputer(this._editor); this._hoverOperation = this._register(new hoverOperation_1.HoverOperation(this._editor, this._computer)); this._register(this._hoverOperation.onResult((result) => { this._withResult(result.value); })); this._register(this._editor.onDidChangeModelDecorations(() => this._onModelDecorationsChanged())); this._register(this._editor.onDidChangeConfiguration((e) => { if (e.hasChanged(44 /* fontInfo */)) { this._updateFont(); } })); this._editor.addOverlayWidget(this); } dispose() { this._editor.removeOverlayWidget(this); super.dispose(); } getId() { return MarginHoverWidget.ID; } getDomNode() { return this._hover.containerDomNode; } getPosition() { return null; } _updateFont() { const codeClasses = Array.prototype.slice.call(this._hover.contentsDomNode.getElementsByClassName('code')); codeClasses.forEach(node => this._editor.applyFontInfo(node)); } _onModelDecorationsChanged() { if (this._isVisible) { // The decorations have changed and the hover is visible, // we need to recompute the displayed text this._hoverOperation.cancel(); this._hoverOperation.start(0 /* Delayed */); } } startShowingAt(lineNumber) { if (this._computer.lineNumber === 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._computer.lineNumber = lineNumber; this._hoverOperation.start(0 /* Delayed */); } hide() { this._computer.lineNumber = -1; this._hoverOperation.cancel(); if (!this._isVisible) { return; } this._isVisible = false; this._hover.containerDomNode.classList.toggle('hidden', !this._isVisible); } _withResult(result) { this._messages = result; if (this._messages.length > 0) { this._renderMessages(this._computer.lineNumber, this._messages); } else { this.hide(); } } _renderMessages(lineNumber, messages) { this._renderDisposeables.clear(); const fragment = document.createDocumentFragment(); for (const msg of messages) { const markdownHoverElement = $('div.hover-row.markdown-hover'); const hoverContentsElement = dom.append(markdownHoverElement, $('div.hover-contents')); const renderedContents = this._renderDisposeables.add(this._markdownRenderer.render(msg.value)); hoverContentsElement.appendChild(renderedContents.element); fragment.appendChild(markdownHoverElement); } this._updateContents(fragment); this._showAt(lineNumber); } _updateContents(node) { this._hover.contentsDomNode.textContent = ''; this._hover.contentsDomNode.appendChild(node); this._updateFont(); } _showAt(lineNumber) { if (!this._isVisible) { this._isVisible = true; this._hover.containerDomNode.classList.toggle('hidden', !this._isVisible); } const editorLayout = this._editor.getLayoutInfo(); const topForLineNumber = this._editor.getTopForLineNumber(lineNumber); const editorScrollTop = this._editor.getScrollTop(); const lineHeight = this._editor.getOption(59 /* lineHeight */); const nodeHeight = this._hover.containerDomNode.clientHeight; const top = topForLineNumber - editorScrollTop - ((nodeHeight - lineHeight) / 2); this._hover.containerDomNode.style.left = `${editorLayout.glyphMarginLeft + editorLayout.glyphMarginWidth}px`; this._hover.containerDomNode.style.top = `${Math.max(Math.round(top), 0)}px`; } } exports.MarginHoverWidget = MarginHoverWidget; MarginHoverWidget.ID = 'editor.contrib.modesGlyphHoverWidget'; class MarginHoverComputer { constructor(_editor) { this._editor = _editor; this._lineNumber = -1; } get lineNumber() { return this._lineNumber; } set lineNumber(value) { this._lineNumber = value; } 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; } } }); /*--------------------------------------------------------------------------------------------- * 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/suggest/browser/suggestWidgetDetails*/], __M([1/*require*/,0/*exports*/,34/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,67/*vs/base/browser/ui/scrollbar/scrollableElement*/,27/*vs/base/common/codicons*/,4/*vs/base/common/event*/,66/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,104/*vs/editor/contrib/markdownRenderer/browser/markdownRenderer*/,31/*vs/editor/common/config/editorOptions*/,261/*vs/editor/contrib/suggest/browser/resizable*/,571/*vs/nls!vs/editor/contrib/suggest/browser/suggestWidgetDetails*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, browser_1, dom, scrollableElement_1, codicons_1, event_1, htmlContent_1, lifecycle_1, markdownRenderer_1, editorOptions_1, resizable_1, nls, 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(44 /* fontInfo */)) { this._configureFont(); } })); } dispose() { this._disposables.dispose(); this._renderDisposeable.dispose(); } _configureFont() { const options = this._editor.getOptions(); const fontInfo = options.get(44 /* fontInfo */); const fontFamily = fontInfo.getMassagedFontFamily(browser_1.isSafari ? editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily : null); const fontSize = options.get(107 /* suggestFontSize */) || fontInfo.fontSize; const lineHeight = options.get(108 /* suggestLineHeight */) || fontInfo.lineHeight; const fontWeight = fontInfo.fontWeight; const fontSizePx = `${fontSize}px`; const lineHeightPx = `${lineHeight}px`; this.domNode.style.fontSize = fontSizePx; this.domNode.style.lineHeight = `${lineHeight / fontSize}`; this.domNode.style.fontWeight = fontWeight; this.domNode.style.fontFeatureSettings = fontInfo.fontFeatureSettings; this._type.style.fontFamily = fontFamily; this._close.style.height = lineHeightPx; this._close.style.width = lineHeightPx; } getLayoutInfo() { const lineHeight = this._editor.getOption(108 /* suggestLineHeight */) || this._editor.getOption(44 /* 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._preferAlignAtTop = true; this._resizable = new resizable_1.ResizableHTMLElement(); this._resizable.domNode.classList.add('suggest-details-container'); this._resizable.domNode.appendChild(widget.domNode); this._resizable.enableSashes(false, true, true, false); let topLeftNow; let sizeNow; let deltaTop = 0; let deltaLeft = 0; this._disposables.add(this._resizable.onDidWillResize(() => { topLeftNow = this._topLeft; sizeNow = this._resizable.size; })); this._disposables.add(this._resizable.onDidResize(e => { if (topLeftNow && sizeNow) { this.widget.layout(e.dimension.width, e.dimension.height); let updateTopLeft = false; if (e.west) { deltaLeft = sizeNow.width - e.dimension.width; updateTopLeft = true; } if (e.north) { deltaTop = sizeNow.height - e.dimension.height; updateTopLeft = true; } if (updateTopLeft) { this._applyTopLeft({ top: topLeftNow.top + deltaTop, left: topLeftNow.left + deltaLeft, }); } } if (e.done) { topLeftNow = undefined; sizeNow = undefined; deltaTop = 0; deltaLeft = 0; this._userSize = e.dimension; } })); this._disposables.add(this.widget.onDidChangeContents(() => { var _a; if (this._anchorBox) { this._placeAtAnchor(this._anchorBox, (_a = this._userSize) !== null && _a !== void 0 ? _a : this.widget.size, this._preferAlignAtTop); } })); } dispose() { this._resizable.dispose(); this._disposables.dispose(); this.hide(); } getId() { return 'suggest.details'; } getDomNode() { return this._resizable.domNode; } getPosition() { return 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, preferAlignAtTop) { var _a; const anchorBox = anchor.getBoundingClientRect(); this._anchorBox = anchorBox; this._preferAlignAtTop = preferAlignAtTop; this._placeAtAnchor(this._anchorBox, (_a = this._userSize) !== null && _a !== void 0 ? _a : this.widget.size, preferAlignAtTop); } _placeAtAnchor(anchorBox, size, preferAlignAtTop) { var _a; const bodyBox = dom.getClientArea(document.body); const info = this.widget.getLayoutInfo(); const defaultMinSize = new dom.Dimension(220, 2 * info.lineHeight); const defaultTop = anchorBox.top; // EAST const eastPlacement = (function () { const width = bodyBox.width - (anchorBox.left + anchorBox.width + info.borderWidth + info.horizontalPadding); const left = -info.borderWidth + anchorBox.left + anchorBox.width; const maxSizeTop = new dom.Dimension(width, bodyBox.height - anchorBox.top - info.borderHeight - info.verticalPadding); const maxSizeBottom = maxSizeTop.with(undefined, anchorBox.top + anchorBox.height - info.borderHeight - info.verticalPadding); return { top: defaultTop, left, fit: width - size.width, maxSizeTop, maxSizeBottom, minSize: defaultMinSize.with(Math.min(width, defaultMinSize.width)) }; })(); // WEST const westPlacement = (function () { const width = anchorBox.left - info.borderWidth - info.horizontalPadding; const left = Math.max(info.horizontalPadding, anchorBox.left - size.width - info.borderWidth); const maxSizeTop = new dom.Dimension(width, bodyBox.height - anchorBox.top - info.borderHeight - info.verticalPadding); const maxSizeBottom = maxSizeTop.with(undefined, anchorBox.top + anchorBox.height - info.borderHeight - info.verticalPadding); return { top: defaultTop, left, fit: width - size.width, maxSizeTop, maxSizeBottom, minSize: defaultMinSize.with(Math.min(width, defaultMinSize.width)) }; })(); // SOUTH const southPacement = (function () { const left = anchorBox.left; const top = -info.borderWidth + anchorBox.top + anchorBox.height; const maxSizeBottom = new dom.Dimension(anchorBox.width - info.borderHeight, bodyBox.height - anchorBox.top - anchorBox.height - info.verticalPadding); return { top, left, fit: maxSizeBottom.height - size.height, maxSizeBottom, maxSizeTop: maxSizeBottom, minSize: defaultMinSize.with(maxSizeBottom.width) }; })(); // take first placement that fits or the first with "least bad" fit const placements = [eastPlacement, westPlacement, southPacement]; const placement = (_a = placements.find(p => p.fit >= 0)) !== null && _a !== void 0 ? _a : placements.sort((a, b) => b.fit - a.fit)[0]; // top/bottom placement const bottom = anchorBox.top + anchorBox.height - info.borderHeight; let alignAtTop; let height = size.height; const maxHeight = Math.max(placement.maxSizeTop.height, placement.maxSizeBottom.height); if (height > maxHeight) { height = maxHeight; } let maxSize; if (preferAlignAtTop) { if (height <= placement.maxSizeTop.height) { alignAtTop = true; maxSize = placement.maxSizeTop; } else { alignAtTop = false; maxSize = placement.maxSizeBottom; } } else { if (height <= placement.maxSizeBottom.height) { alignAtTop = false; maxSize = placement.maxSizeBottom; } else { alignAtTop = true; maxSize = placement.maxSizeTop; } } this._applyTopLeft({ left: placement.left, top: alignAtTop ? placement.top : bottom - height }); this.getDomNode().style.position = 'fixed'; this._resizable.enableSashes(!alignAtTop, placement === eastPlacement, alignAtTop, placement !== eastPlacement); this._resizable.minSize = placement.minSize; this._resizable.maxSize = maxSize; this._resizable.layout(height, Math.min(maxSize.width, size.width)); this.widget.layout(this._resizable.size.width, this._resizable.size.height); } _applyTopLeft(topLeft) { this._topLeft = topLeft; this.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[625/*vs/platform/configuration/common/configurationModels*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,47/*vs/base/common/map*/,39/*vs/base/common/objects*/,20/*vs/base/common/types*/,25/*vs/base/common/uri*/,40/*vs/platform/configuration/common/configuration*/,103/*vs/platform/configuration/common/configurationRegistry*/,36/*vs/platform/registry/common/platform*/]), function (require, exports, arrays, map_1, objects, types, uri_1, configuration_1, configurationRegistry_1, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ConfigurationChangeEvent = exports.Configuration = exports.DefaultConfigurationModel = exports.ConfigurationModel = void 0; class ConfigurationModel { constructor(_contents = {}, _keys = [], _overrides = []) { this._contents = _contents; this._keys = _keys; this._overrides = _overrides; this.isFrozen = false; this.overrideConfigurations = new Map(); } 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; } getOverrideValue(section, overrideIdentifier) { const overrideContents = this.getContentsForOverrideIdentifer(overrideIdentifier); return overrideContents ? section ? (0, configuration_1.getConfigurationValue)(overrideContents, section) : overrideContents : undefined; } override(identifier) { let overrideConfigurationModel = this.overrideConfigurations.get(identifier); if (!overrideConfigurationModel) { overrideConfigurationModel = this.createOverrideConfigurationModel(identifier); this.overrideConfigurations.set(identifier, overrideConfigurationModel); } return overrideConfigurationModel; } merge(...others) { const contents = objects.deepClone(this.contents); const overrides = objects.deepClone(this.overrides); const keys = [...this.keys]; 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); override.keys.push(...otherOverride.keys); override.keys = arrays.distinct(override.keys); } else { overrides.push(objects.deepClone(otherOverride)); } } for (const key of other.keys) { if (keys.indexOf(key) === -1) { keys.push(key); } } } return new ConfigurationModel(contents, keys, overrides); } freeze() { this.isFrozen = true; return this; } createOverrideConfigurationModel(identifier) { const overrideContents = this.getContentsForOverrideIdentifer(identifier); if (!overrideContents || typeof overrideContents !== 'object' || !Object.keys(overrideContents).length) { // If there are no valid overrides, return self return this; } 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); } 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) { let contentsForIdentifierOnly = null; let contents = null; const mergeContents = (contentsToMerge) => { if (contentsToMerge) { if (contents) { this.mergeContents(contents, contentsToMerge); } else { contents = objects.deepClone(contentsToMerge); } } }; for (const override of this.overrides) { if (arrays.equals(override.identifiers, [identifier])) { contentsForIdentifierOnly = override.contents; } else if (override.identifiers.includes(identifier)) { mergeContents(override.contents); } } // Merge contents of the identifier only at the end to take precedence. mergeContents(contentsForIdentifierOnly); return contents; } toJSON() { return { contents: this.contents, overrides: this.overrides, keys: this.keys }; } // 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(configurationDefaultsOverrides = {}) { const properties = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).getConfigurationProperties(); const keys = Object.keys(properties); const contents = Object.create(null); const overrides = []; for (const key in properties) { const defaultOverrideValue = configurationDefaultsOverrides[key]; const value = defaultOverrideValue !== undefined ? defaultOverrideValue : properties[key].default; (0, configuration_1.addToValueTree)(contents, key, value, message => console.error(`Conflict in default settings: ${message}`)); } for (const key of Object.keys(contents)) { if (configurationRegistry_1.OVERRIDE_PROPERTY_REGEX.test(key)) { overrides.push({ identifiers: (0, configurationRegistry_1.overrideIdentifiersFromKey)(key), 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; } } inspect(key, overrides, workspace) { const consolidateConfigurationModel = this.getConsolidateConfigurationModel(overrides, workspace); const folderConfigurationModel = this.getFolderConfigurationModelForResource(overrides.resource, workspace); const memoryConfigurationModel = overrides.resource ? this._memoryConfigurationByResource.get(overrides.resource) || this._memoryConfiguration : this._memoryConfiguration; const defaultValue = overrides.overrideIdentifier ? this._defaultConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this._defaultConfiguration.freeze().getValue(key); const userValue = overrides.overrideIdentifier ? this.userConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this.userConfiguration.freeze().getValue(key); const userLocalValue = overrides.overrideIdentifier ? this.localUserConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this.localUserConfiguration.freeze().getValue(key); const userRemoteValue = overrides.overrideIdentifier ? this.remoteUserConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this.remoteUserConfiguration.freeze().getValue(key); const workspaceValue = workspace ? overrides.overrideIdentifier ? this._workspaceConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this._workspaceConfiguration.freeze().getValue(key) : undefined; //Check on workspace exists or not because _workspaceConfiguration is never null const workspaceFolderValue = folderConfigurationModel ? overrides.overrideIdentifier ? folderConfigurationModel.freeze().override(overrides.overrideIdentifier).getValue(key) : folderConfigurationModel.freeze().getValue(key) : undefined; const memoryValue = overrides.overrideIdentifier ? memoryConfigurationModel.override(overrides.overrideIdentifier).getValue(key) : memoryConfigurationModel.getValue(key); const value = consolidateConfigurationModel.getValue(key); const overrideIdentifiers = arrays.distinct(arrays.flatten(consolidateConfigurationModel.overrides.map(override => override.identifiers))).filter(overrideIdentifier => consolidateConfigurationModel.getOverrideValue(key, overrideIdentifier) !== undefined); return { defaultValue: defaultValue, userValue: userValue, userLocalValue: userLocalValue, userRemoteValue: userRemoteValue, workspaceValue: workspaceValue, workspaceFolderValue: workspaceFolderValue, memoryValue: memoryValue, value, default: defaultValue !== undefined ? { value: this._defaultConfiguration.freeze().getValue(key), override: overrides.overrideIdentifier ? this._defaultConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined, user: userValue !== undefined ? { value: this.userConfiguration.freeze().getValue(key), override: overrides.overrideIdentifier ? this.userConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined, userLocal: userLocalValue !== undefined ? { value: this.localUserConfiguration.freeze().getValue(key), override: overrides.overrideIdentifier ? this.localUserConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined, userRemote: userRemoteValue !== undefined ? { value: this.remoteUserConfiguration.freeze().getValue(key), override: overrides.overrideIdentifier ? this.remoteUserConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined, workspace: workspaceValue !== undefined ? { value: this._workspaceConfiguration.freeze().getValue(key), override: overrides.overrideIdentifier ? this._workspaceConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined, workspaceFolder: workspaceFolderValue !== undefined ? { value: folderConfigurationModel === null || folderConfigurationModel === void 0 ? void 0 : folderConfigurationModel.freeze().getValue(key), override: overrides.overrideIdentifier ? folderConfigurationModel === null || folderConfigurationModel === void 0 ? void 0 : folderConfigurationModel.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined, memory: memoryValue !== undefined ? { value: memoryConfigurationModel.getValue(key), override: overrides.overrideIdentifier ? memoryConfigurationModel.getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined, overrideIdentifiers: overrideIdentifiers.length ? overrideIdentifiers : undefined }; } 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; } get localUserConfiguration() { return this._localUserConfiguration; } get remoteUserConfiguration() { return this._remoteUserConfiguration; } 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; } getFolderConfigurationModelForResource(resource, workspace) { if (workspace && resource) { const root = workspace.getFolder(resource); if (root) { return this._folderConfigurations.get(root.uri); } } return undefined; } toData() { return { defaults: { contents: this._defaultConfiguration.contents, overrides: this._defaultConfiguration.overrides, keys: this._defaultConfiguration.keys }, 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[86/*vs/platform/keybinding/common/keybindingsRegistry*/], __M([1/*require*/,0/*exports*/,94/*vs/base/common/keybindings*/,17/*vs/base/common/platform*/,26/*vs/platform/commands/common/commands*/,36/*vs/platform/registry/common/platform*/]), function (require, exports, keybindings_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, keybindings_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, keybindings_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 /* Digit0 */ && keyCode <= 30 /* Digit9 */) { return true; } if (keyCode >= 31 /* KeyA */ && keyCode <= 56 /* KeyZ */) { return true; } return (keyCode === 80 /* Semicolon */ || keyCode === 81 /* Equal */ || keyCode === 82 /* Comma */ || keyCode === 83 /* Minus */ || keyCode === 84 /* Period */ || keyCode === 85 /* Slash */ || keyCode === 86 /* Backquote */ || keyCode === 110 /* ABNT_C1 */ || keyCode === 111 /* ABNT_C2 */ || keyCode === 87 /* BracketLeft */ || keyCode === 88 /* Backslash */ || keyCode === 89 /* BracketRight */ || keyCode === 90 /* Quote */ || keyCode === 91 /* OEM_8 */ || keyCode === 92 /* IntlBackslash */); } _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.parts, 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[626/*vs/platform/history/browser/contextScopedHistoryWidget*/], __M([1/*require*/,0/*exports*/,485/*vs/base/browser/ui/findinput/findInput*/,486/*vs/base/browser/ui/findinput/replaceInput*/,16/*vs/platform/contextkey/common/contextkey*/,86/*vs/platform/keybinding/common/keybindingsRegistry*/]), function (require, exports, findInput_1, replaceInput_1, contextkey_1, keybindingsRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ContextScopedReplaceInput = exports.ContextScopedFindInput = exports.createAndBindHistoryNavigationWidgetScopedContextKeyService = exports.HistoryNavigationWidgetContext = void 0; // TODO@Connor: this constant is duplicated here to avoid a layer breaker import const suggestWidgetVisibleContext = 'suggestWidgetVisible'; exports.HistoryNavigationWidgetContext = 'historyNavigationWidget'; const HistoryNavigationForwardsEnablementContext = 'historyNavigationForwardsEnabled'; const HistoryNavigationBackwardsEnablementContext = 'historyNavigationBackwardsEnabled'; 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 historyNavigationForwardsEnablement = new contextkey_1.RawContextKey(HistoryNavigationForwardsEnablementContext, true).bindTo(scopedContextKeyService); const historyNavigationBackwardsEnablement = new contextkey_1.RawContextKey(HistoryNavigationBackwardsEnablementContext, true).bindTo(scopedContextKeyService); return { scopedContextKeyService, historyNavigationForwardsEnablement, historyNavigationBackwardsEnablement, }; } 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(HistoryNavigationBackwardsEnablementContext, true), contextkey_1.ContextKeyExpr.equals(suggestWidgetVisibleContext, false)), primary: 16 /* UpArrow */, secondary: [512 /* Alt */ | 16 /* UpArrow */], handler: (accessor) => { 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(HistoryNavigationForwardsEnablementContext, true), contextkey_1.ContextKeyExpr.equals(suggestWidgetVisibleContext, false)), primary: 18 /* DownArrow */, secondary: [512 /* Alt */ | 18 /* DownArrow */], handler: (accessor) => { 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[105/*vs/platform/quickinput/common/quickAccess*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,36/*vs/platform/registry/common/platform*/]), function (require, exports, arrays_1, lifecycle_1, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.QuickAccessRegistry = exports.Extensions = exports.DefaultQuickAccessFilterValue = void 0; var DefaultQuickAccessFilterValue; (function (DefaultQuickAccessFilterValue) { /** * Keep the value as it is given to quick access. */ DefaultQuickAccessFilterValue[DefaultQuickAccessFilterValue["PRESERVE"] = 0] = "PRESERVE"; /** * Use the value that was used last time something was accepted from the picker. */ DefaultQuickAccessFilterValue[DefaultQuickAccessFilterValue["LAST"] = 1] = "LAST"; })(DefaultQuickAccessFilterValue = exports.DefaultQuickAccessFilterValue || (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[627/*vs/platform/quickinput/browser/helpQuickAccess*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,589/*vs/nls!vs/platform/quickinput/browser/helpQuickAccess*/,105/*vs/platform/quickinput/common/quickAccess*/,78/*vs/platform/quickinput/common/quickInput*/,36/*vs/platform/registry/common/platform*/]), function (require, exports, lifecycle_1, nls_1, quickAccess_1, quickInput_1, platform_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[628/*vs/editor/standalone/browser/quickAccess/standaloneHelpQuickAccess*/], __M([1/*require*/,0/*exports*/,36/*vs/platform/registry/common/platform*/,105/*vs/platform/quickinput/common/quickAccess*/,70/*vs/editor/common/standaloneStrings*/,627/*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[629/*vs/platform/quickinput/browser/quickAccess*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/async*/,21/*vs/base/common/cancellation*/,88/*vs/base/common/functional*/,2/*vs/base/common/lifecycle*/,9/*vs/platform/instantiation/common/instantiation*/,105/*vs/platform/quickinput/common/quickAccess*/,78/*vs/platform/quickinput/common/quickInput*/,36/*vs/platform/registry/common/platform*/]), function (require, exports, async_1, cancellation_1, functional_1, lifecycle_1, instantiation_1, quickAccess_1, quickInput_1, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.QuickAccessController = void 0; let QuickAccessController = class QuickAccessController extends lifecycle_1.Disposable { constructor(quickInputService, instantiationService) { super(); this.quickInputService = quickInputService; this.instantiationService = instantiationService; this.registry = platform_1.Registry.as(quickAccess_1.Extensions.Quickaccess); this.mapProviderToDescriptor = new Map(); this.lastAcceptedPickerValues = new Map(); this.visibleQuickAccess = undefined; } show(value = '', options) { this.doShowOrPick(value, false, options); } doShowOrPick(value, pick, options) { 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; if (pick) { pickPromise = new async_1.DeferredPromise(); 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 pickPromise === null || pickPromise === void 0 ? void 0 : pickPromise.complete(picker.selectedItems.slice(0)); }); // Finally, show the picker. This is important because a provider // may not call this and then our disposables would leak that rely // on the onDidHide event. picker.show(); // Pick mode: return with promise if (pick) { return pickPromise === null || pickPromise === void 0 ? void 0 : pickPromise.p; } } 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; }); define(__m[80/*vs/platform/storage/common/storage*/], __M([1/*require*/,0/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/,327/*vs/base/parts/storage/common/storage*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, event_1, lifecycle_1, types_1, storage_1, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.InMemoryStorageService = exports.AbstractStorageService = exports.WillSaveStateReason = exports.IStorageService = 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[630/*vs/editor/contrib/codelens/browser/codeLensCache*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/async*/,88/*vs/base/common/functional*/,47/*vs/base/common/map*/,3/*vs/editor/common/core/range*/,271/*vs/editor/contrib/codelens/browser/codelens*/,53/*vs/platform/instantiation/common/extensions*/,9/*vs/platform/instantiation/common/instantiation*/,80/*vs/platform/storage/common/storage*/]), function (require, exports, async_1, functional_1, map_1, range_1, codelens_1, extensions_1, instantiation_1, storage_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[631/*vs/editor/contrib/suggest/browser/suggestMemory*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,47/*vs/base/common/map*/,18/*vs/editor/common/languages*/,40/*vs/platform/configuration/common/configuration*/,53/*vs/platform/instantiation/common/extensions*/,9/*vs/platform/instantiation/common/instantiation*/,80/*vs/platform/storage/common/storage*/]), function (require, exports, async_1, lifecycle_1, map_1, languages_1, configuration_1, extensions_1, instantiation_1, storage_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.getLanguageId()}/${item.textLabel}`; this._cache.set(key, { touch: this._seq++, type: item.completion.kind, insertText: item.completion.insertText }); } select(model, pos, items) { if (items.length === 0) { return 0; } const lineSuffix = model.getLineContent(pos.lineNumber).substr(pos.column - 10, pos.column - 1); if (/\s$/.test(lineSuffix)) { return super.select(model, pos, items); } 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.getLanguageId()}/${items[i].textLabel}`; const item = this._cache.peek(key); if (item && item.touch > seq && item.type === items[i].completion.kind && item.insertText === items[i].completion.insertText) { seq = item.touch; indexRecency = i; } if (items[i].completion.preselect && indexPreselect === -1) { // stop when seeing an auto-select-item return indexPreselect = i; } } if (indexRecency !== -1) { return indexRecency; } else if (indexPreselect !== -1) { return indexPreselect; } else { return 0; } } toJSON() { return this._cache.toJSON(); } fromJSON(data) { this._cache.clear(); let seq = 0; for (const [key, value] of data) { value.touch = seq; value.type = typeof value.type === 'number' ? value.type : languages_1.CompletionItemKinds.fromString(value.type); this._cache.set(key, value); } this._seq = this._cache.size; } } exports.LRUMemory = LRUMemory; class PrefixMemory extends Memory { constructor() { super('recentlyUsedByPrefix'); this._trie = map_1.TernarySearchTree.forStrings(); this._seq = 0; } memorize(model, pos, item) { const { word } = model.getWordUntilPosition(pos); const key = `${model.getLanguageId()}/${word}`; this._trie.set(key, { type: item.completion.kind, insertText: item.completion.insertText, touch: this._seq++ }); } select(model, pos, items) { let { word } = model.getWordUntilPosition(pos); if (!word) { return super.select(model, pos, items); } let key = `${model.getLanguageId()}/${word}`; let item = this._trie.get(key); if (!item) { item = this._trie.findSubstr(key); } if (item) { for (let i = 0; i < items.length; i++) { 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 : languages_1.CompletionItemKinds.fromString(value.type); this._trie.set(key, value); } } } } exports.PrefixMemory = PrefixMemory; let SuggestMemoryService = class SuggestMemoryService { constructor(_storageService, _configService) { this._storageService = _storageService; this._configService = _configService; this._disposables = new lifecycle_1.DisposableStore(); this._persistSoon = new async_1.RunOnceScheduler(() => this._saveState(), 500); this._disposables.add(_storageService.onWillSaveState(e => { if (e.reason === storage_1.WillSaveStateReason.SHUTDOWN) { this._saveState(); } })); } dispose() { this._disposables.dispose(); this._persistSoon.dispose(); } memorize(model, pos, item) { this._withStrategy(model, pos).memorize(model, pos, item); this._persistSoon.schedule(); } select(model, pos, items) { return this._withStrategy(model, pos).select(model, pos, items); } _withStrategy(model, pos) { var _a; const mode = this._configService.getValue('editor.suggestSelection', { overrideIdentifier: model.getLanguageIdAtPosition(pos.lineNumber, pos.column), resource: model.uri }); if (((_a = this._strategy) === null || _a === void 0 ? void 0 : _a.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, 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[87/*vs/platform/telemetry/common/telemetry*/], __M([1/*require*/,0/*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[632/*vs/platform/quickinput/browser/commandsQuickAccess*/], __M([1/*require*/,0/*exports*/,490/*vs/base/common/errorMessage*/,13/*vs/base/common/errors*/,73/*vs/base/common/filters*/,2/*vs/base/common/lifecycle*/,47/*vs/base/common/map*/,74/*vs/base/common/severity*/,20/*vs/base/common/types*/,588/*vs/nls!vs/platform/quickinput/browser/commandsQuickAccess*/,26/*vs/platform/commands/common/commands*/,40/*vs/platform/configuration/common/configuration*/,127/*vs/platform/dialogs/common/dialogs*/,9/*vs/platform/instantiation/common/instantiation*/,42/*vs/platform/keybinding/common/keybinding*/,619/*vs/platform/quickinput/browser/pickerQuickAccess*/,80/*vs/platform/storage/common/storage*/,87/*vs/platform/telemetry/common/telemetry*/]), function (require, exports, errorMessage_1, errors_1, filters_1, lifecycle_1, map_1, severity_1, types_1, nls_1, commands_1, configuration_1, dialogs_1, instantiation_1, keybinding_1, pickerQuickAccess_1, storage_1, telemetry_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.isCancellationError)(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[633/*vs/editor/contrib/quickAccess/browser/commandsQuickAccess*/], __M([1/*require*/,0/*exports*/,95/*vs/base/common/iconLabels*/,632/*vs/platform/quickinput/browser/commandsQuickAccess*/]), function (require, exports, iconLabels_1, commandsQuickAccess_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AbstractEditorCommandsQuickAccessProvider = void 0; class AbstractEditorCommandsQuickAccessProvider extends commandsQuickAccess_1.AbstractCommandsQuickAccessProvider { constructor(options, instantiationService, keybindingService, commandService, telemetryService, dialogService) { super(options, instantiationService, keybindingService, commandService, telemetryService, dialogService); } getCodeEditorCommandPicks() { const activeTextEditorControl = this.activeTextEditorControl; if (!activeTextEditorControl) { return []; } const editorCommandPicks = []; for (const editorAction of activeTextEditorControl.getSupportedActions()) { 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[23/*vs/platform/theme/common/colorRegistry*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/async*/,29/*vs/base/common/color*/,4/*vs/base/common/event*/,20/*vs/base/common/types*/,590/*vs/nls!vs/platform/theme/common/colorRegistry*/,200/*vs/platform/jsonschemas/common/jsonContributionRegistry*/,36/*vs/platform/registry/common/platform*/]), function (require, exports, async_1, color_1, event_1, types_1, nls, jsonContributionRegistry_1, platform) { "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.chartsPurple = exports.chartsGreen = exports.chartsOrange = exports.chartsYellow = exports.chartsBlue = exports.chartsRed = exports.chartsLines = exports.chartsForeground = exports.problemsInfoIconForeground = exports.problemsWarningIconForeground = exports.problemsErrorIconForeground = exports.minimapSliderActiveBackground = exports.minimapSliderHoverBackground = exports.minimapSliderBackground = exports.minimapForegroundOpacity = exports.minimapBackground = exports.minimapWarning = exports.minimapError = exports.minimapSelection = exports.minimapSelectionOccurrenceHighlight = exports.minimapFindMatch = exports.overviewRulerSelectionHighlightForeground = exports.overviewRulerFindMatchForeground = exports.overviewRulerCommonContentForeground = exports.overviewRulerIncomingContentForeground = exports.overviewRulerCurrentContentForeground = exports.mergeBorder = exports.mergeCommonContentBackground = exports.mergeCommonHeaderBackground = exports.mergeIncomingContentBackground = exports.mergeIncomingHeaderBackground = exports.mergeCurrentContentBackground = exports.mergeCurrentHeaderBackground = exports.breadcrumbsPickerBackground = exports.breadcrumbsActiveSelectionForeground = exports.breadcrumbsFocusForeground = exports.breadcrumbsBackground = exports.breadcrumbsForeground = exports.snippetFinalTabstopHighlightBorder = exports.snippetFinalTabstopHighlightBackground = exports.snippetTabstopHighlightBorder = exports.snippetTabstopHighlightBackground = exports.toolbarActiveBackground = exports.toolbarHoverOutline = exports.toolbarHoverBackground = exports.menuSeparatorBackground = exports.menuSelectionBorder = exports.menuSelectionBackground = exports.menuSelectionForeground = exports.menuBackground = exports.menuForeground = exports.menuBorder = exports.quickInputListFocusBackground = exports.quickInputListFocusIconForeground = exports.quickInputListFocusForeground = exports._deprecatedQuickInputListFocusBackground = exports.listDeemphasizedForeground = exports.tableOddRowsBackgroundColor = exports.tableColumnsBorder = exports.treeIndentGuidesStroke = exports.listFilterMatchHighlightBorder = exports.listFilterMatchHighlight = exports.listFilterWidgetNoMatchesOutline = exports.listFilterWidgetOutline = exports.listFilterWidgetBackground = exports.listWarningForeground = exports.listErrorForeground = exports.listInvalidItemForeground = 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.editorInlayHintParameterBackground = exports.editorInlayHintParameterForeground = exports.editorInlayHintTypeBackground = exports.editorInlayHintTypeForeground = exports.editorInlayHintBackground = exports.editorInlayHintForeground = exports.editorActiveLinkForeground = exports.editorHoverStatusBarBackground = exports.editorHoverBorder = exports.editorHoverForeground = exports.editorHoverBackground = exports.editorHoverHighlight = exports.searchEditorFindMatchBorder = exports.searchEditorFindMatch = 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.sashHoverBorder = 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.buttonSecondaryHoverBackground = exports.buttonSecondaryBackground = exports.buttonSecondaryForeground = exports.buttonBorder = exports.buttonHoverBackground = exports.buttonBackground = exports.buttonForeground = exports.simpleCheckboxBorder = exports.simpleCheckboxForeground = exports.simpleCheckboxBackground = exports.selectBorder = exports.selectForeground = exports.selectListBackground = exports.selectBackground = exports.inputValidationErrorBorder = exports.inputValidationErrorForeground = exports.inputValidationErrorBackground = exports.inputValidationWarningBorder = exports.inputValidationWarningForeground = exports.inputValidationWarningBackground = exports.inputValidationInfoBorder = exports.inputValidationInfoForeground = exports.inputValidationInfoBackground = exports.inputPlaceholderForeground = exports.inputActiveOptionForeground = exports.inputActiveOptionBackground = exports.inputActiveOptionHoverBackground = exports.inputActiveOptionBorder = exports.inputBorder = exports.inputForeground = exports.inputBackground = exports.widgetShadow = exports.textCodeBlockBackground = exports.textBlockQuoteBorder = exports.textBlockQuoteBackground = exports.textPreformatForeground = exports.textLinkActiveForeground = exports.textLinkForeground = exports.textSeparatorForeground = exports.selectionBackground = exports.activeContrastBorder = exports.contrastBorder = exports.focusBorder = exports.iconForeground = exports.descriptionForeground = exports.errorForeground = exports.foreground = exports.registerColor = exports.Extensions = exports.asCssVariableName = void 0; /** * Returns the css variable name for the given color identifier. Dots (`.`) are replaced with hyphens (`-`) and * everything is prefixed with `--vscode-`. * * @sample `editorSuggestWidget.background` is `--vscode-editorSuggestWidget-background`. */ function asCssVariableName(colorIdent) { return `--vscode-${colorIdent.replace('.', '-')}`; } exports.asCssVariableName = asCssVariableName; // 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; } getColors() { return Object.keys(this.colorsById).map(id => this.colorsById[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.descriptionForeground = registerColor('descriptionForeground', { light: '#717171', dark: transparent(exports.foreground, 0.7), hc: transparent(exports.foreground, 0.7) }, nls.localize(2, null)); exports.iconForeground = registerColor('icon.foreground', { dark: '#C5C5C5', light: '#424242', hc: '#FFFFFF' }, nls.localize(3, null)); exports.focusBorder = registerColor('focusBorder', { dark: '#007FD4', light: '#0090F1', hc: '#F38518' }, nls.localize(4, null)); exports.contrastBorder = registerColor('contrastBorder', { light: null, dark: null, hc: '#6FC3DF' }, nls.localize(5, null)); exports.activeContrastBorder = registerColor('contrastActiveBorder', { light: null, dark: null, hc: exports.focusBorder }, nls.localize(6, null)); exports.selectionBackground = registerColor('selection.background', { light: null, dark: null, hc: null }, nls.localize(7, null)); // ------ text colors exports.textSeparatorForeground = registerColor('textSeparator.foreground', { light: '#0000002e', dark: '#ffffff2e', hc: color_1.Color.black }, nls.localize(8, null)); exports.textLinkForeground = registerColor('textLink.foreground', { light: '#006AB1', dark: '#3794FF', hc: '#3794FF' }, nls.localize(9, null)); exports.textLinkActiveForeground = registerColor('textLink.activeForeground', { light: '#006AB1', dark: '#3794FF', hc: '#3794FF' }, nls.localize(10, null)); exports.textPreformatForeground = registerColor('textPreformat.foreground', { light: '#A31515', dark: '#D7BA7D', hc: '#D7BA7D' }, nls.localize(11, null)); exports.textBlockQuoteBackground = registerColor('textBlockQuote.background', { light: '#7f7f7f1a', dark: '#7f7f7f1a', hc: null }, nls.localize(12, null)); exports.textBlockQuoteBorder = registerColor('textBlockQuote.border', { light: '#007acc80', dark: '#007acc80', hc: color_1.Color.white }, nls.localize(13, null)); exports.textCodeBlockBackground = registerColor('textCodeBlock.background', { light: '#dcdcdc66', dark: '#0a0a0a66', hc: color_1.Color.black }, nls.localize(14, 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(15, null)); exports.inputBackground = registerColor('input.background', { dark: '#3C3C3C', light: color_1.Color.white, hc: color_1.Color.black }, nls.localize(16, null)); exports.inputForeground = registerColor('input.foreground', { dark: exports.foreground, light: exports.foreground, hc: exports.foreground }, nls.localize(17, null)); exports.inputBorder = registerColor('input.border', { dark: null, light: null, hc: exports.contrastBorder }, nls.localize(18, null)); exports.inputActiveOptionBorder = registerColor('inputOption.activeBorder', { dark: '#007ACC00', light: '#007ACC00', hc: exports.contrastBorder }, nls.localize(19, null)); exports.inputActiveOptionHoverBackground = registerColor('inputOption.hoverBackground', { dark: '#5a5d5e80', light: '#b8b8b850', hc: null }, nls.localize(20, 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(21, null)); exports.inputActiveOptionForeground = registerColor('inputOption.activeForeground', { dark: color_1.Color.white, light: color_1.Color.black, hc: null }, nls.localize(22, null)); exports.inputPlaceholderForeground = registerColor('input.placeholderForeground', { light: transparent(exports.foreground, 0.5), dark: transparent(exports.foreground, 0.5), hc: transparent(exports.foreground, 0.7) }, nls.localize(23, null)); exports.inputValidationInfoBackground = registerColor('inputValidation.infoBackground', { dark: '#063B49', light: '#D6ECF2', hc: color_1.Color.black }, nls.localize(24, null)); exports.inputValidationInfoForeground = registerColor('inputValidation.infoForeground', { dark: null, light: null, hc: null }, nls.localize(25, null)); exports.inputValidationInfoBorder = registerColor('inputValidation.infoBorder', { dark: '#007acc', light: '#007acc', hc: exports.contrastBorder }, nls.localize(26, null)); exports.inputValidationWarningBackground = registerColor('inputValidation.warningBackground', { dark: '#352A05', light: '#F6F5D2', hc: color_1.Color.black }, nls.localize(27, null)); exports.inputValidationWarningForeground = registerColor('inputValidation.warningForeground', { dark: null, light: null, hc: null }, nls.localize(28, null)); exports.inputValidationWarningBorder = registerColor('inputValidation.warningBorder', { dark: '#B89500', light: '#B89500', hc: exports.contrastBorder }, nls.localize(29, null)); exports.inputValidationErrorBackground = registerColor('inputValidation.errorBackground', { dark: '#5A1D1D', light: '#F2DEDE', hc: color_1.Color.black }, nls.localize(30, null)); exports.inputValidationErrorForeground = registerColor('inputValidation.errorForeground', { dark: null, light: null, hc: null }, nls.localize(31, null)); exports.inputValidationErrorBorder = registerColor('inputValidation.errorBorder', { dark: '#BE1100', light: '#BE1100', hc: exports.contrastBorder }, nls.localize(32, null)); exports.selectBackground = registerColor('dropdown.background', { dark: '#3C3C3C', light: color_1.Color.white, hc: color_1.Color.black }, nls.localize(33, null)); exports.selectListBackground = registerColor('dropdown.listBackground', { dark: null, light: null, hc: color_1.Color.black }, nls.localize(34, null)); exports.selectForeground = registerColor('dropdown.foreground', { dark: '#F0F0F0', light: null, hc: color_1.Color.white }, nls.localize(35, null)); exports.selectBorder = registerColor('dropdown.border', { dark: exports.selectBackground, light: '#CECECE', hc: exports.contrastBorder }, nls.localize(36, null)); exports.simpleCheckboxBackground = registerColor('checkbox.background', { dark: exports.selectBackground, light: exports.selectBackground, hc: exports.selectBackground }, nls.localize(37, null)); exports.simpleCheckboxForeground = registerColor('checkbox.foreground', { dark: exports.selectForeground, light: exports.selectForeground, hc: exports.selectForeground }, nls.localize(38, null)); exports.simpleCheckboxBorder = registerColor('checkbox.border', { dark: exports.selectBorder, light: exports.selectBorder, hc: exports.selectBorder }, nls.localize(39, null)); exports.buttonForeground = registerColor('button.foreground', { dark: color_1.Color.white, light: color_1.Color.white, hc: color_1.Color.white }, nls.localize(40, null)); exports.buttonBackground = registerColor('button.background', { dark: '#0E639C', light: '#007ACC', hc: null }, nls.localize(41, null)); exports.buttonHoverBackground = registerColor('button.hoverBackground', { dark: lighten(exports.buttonBackground, 0.2), light: darken(exports.buttonBackground, 0.2), hc: null }, nls.localize(42, null)); exports.buttonBorder = registerColor('button.border', { dark: exports.contrastBorder, light: exports.contrastBorder, hc: exports.contrastBorder }, nls.localize(43, null)); exports.buttonSecondaryForeground = registerColor('button.secondaryForeground', { dark: color_1.Color.white, light: color_1.Color.white, hc: color_1.Color.white }, nls.localize(44, null)); exports.buttonSecondaryBackground = registerColor('button.secondaryBackground', { dark: '#3A3D41', light: '#5F6A79', hc: null }, nls.localize(45, null)); exports.buttonSecondaryHoverBackground = registerColor('button.secondaryHoverBackground', { dark: lighten(exports.buttonSecondaryBackground, 0.2), light: darken(exports.buttonSecondaryBackground, 0.2), hc: null }, nls.localize(46, null)); exports.badgeBackground = registerColor('badge.background', { dark: '#4D4D4D', light: '#C4C4C4', hc: color_1.Color.black }, nls.localize(47, null)); exports.badgeForeground = registerColor('badge.foreground', { dark: color_1.Color.white, light: '#333', hc: color_1.Color.white }, nls.localize(48, null)); exports.scrollbarShadow = registerColor('scrollbar.shadow', { dark: '#000000', light: '#DDDDDD', hc: null }, nls.localize(49, 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(50, 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(51, 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(52, null)); exports.progressBarBackground = registerColor('progressBar.background', { dark: color_1.Color.fromHex('#0E70C0'), light: color_1.Color.fromHex('#0E70C0'), hc: exports.contrastBorder }, nls.localize(53, null)); exports.editorErrorBackground = registerColor('editorError.background', { dark: null, light: null, hc: null }, nls.localize(54, null), true); exports.editorErrorForeground = registerColor('editorError.foreground', { dark: '#F14C4C', light: '#E51400', hc: null }, nls.localize(55, null)); exports.editorErrorBorder = registerColor('editorError.border', { dark: null, light: null, hc: color_1.Color.fromHex('#E47777').transparent(0.8) }, nls.localize(56, null)); exports.editorWarningBackground = registerColor('editorWarning.background', { dark: null, light: null, hc: null }, nls.localize(57, null), true); exports.editorWarningForeground = registerColor('editorWarning.foreground', { dark: '#CCA700', light: '#BF8803', hc: null }, nls.localize(58, null)); exports.editorWarningBorder = registerColor('editorWarning.border', { dark: null, light: null, hc: color_1.Color.fromHex('#FFCC00').transparent(0.8) }, nls.localize(59, null)); exports.editorInfoBackground = registerColor('editorInfo.background', { dark: null, light: null, hc: null }, nls.localize(60, null), true); exports.editorInfoForeground = registerColor('editorInfo.foreground', { dark: '#3794FF', light: '#1a85ff', hc: '#3794FF' }, nls.localize(61, null)); exports.editorInfoBorder = registerColor('editorInfo.border', { dark: null, light: null, hc: color_1.Color.fromHex('#3794FF').transparent(0.8) }, nls.localize(62, null)); exports.editorHintForeground = registerColor('editorHint.foreground', { dark: color_1.Color.fromHex('#eeeeee').transparent(0.7), light: '#6c6c6c', hc: null }, nls.localize(63, null)); exports.editorHintBorder = registerColor('editorHint.border', { dark: null, light: null, hc: color_1.Color.fromHex('#eeeeee').transparent(0.8) }, nls.localize(64, null)); exports.sashHoverBorder = registerColor('sash.hoverBorder', { dark: exports.focusBorder, light: exports.focusBorder, hc: exports.focusBorder }, nls.localize(65, 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(66, null)); /** * Editor foreground color. */ exports.editorForeground = registerColor('editor.foreground', { light: '#333333', dark: '#BBBBBB', hc: color_1.Color.white }, nls.localize(67, null)); /** * Editor widgets */ exports.editorWidgetBackground = registerColor('editorWidget.background', { dark: '#252526', light: '#F3F3F3', hc: '#0C141F' }, nls.localize(68, null)); exports.editorWidgetForeground = registerColor('editorWidget.foreground', { dark: exports.foreground, light: exports.foreground, hc: exports.foreground }, nls.localize(69, null)); exports.editorWidgetBorder = registerColor('editorWidget.border', { dark: '#454545', light: '#C8C8C8', hc: exports.contrastBorder }, nls.localize(70, null)); exports.editorWidgetResizeBorder = registerColor('editorWidget.resizeBorder', { light: null, dark: null, hc: null }, nls.localize(71, null)); /** * Quick pick widget */ exports.quickInputBackground = registerColor('quickInput.background', { dark: exports.editorWidgetBackground, light: exports.editorWidgetBackground, hc: exports.editorWidgetBackground }, nls.localize(72, null)); exports.quickInputForeground = registerColor('quickInput.foreground', { dark: exports.editorWidgetForeground, light: exports.editorWidgetForeground, hc: exports.editorWidgetForeground }, nls.localize(73, 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(74, null)); exports.pickerGroupForeground = registerColor('pickerGroup.foreground', { dark: '#3794FF', light: '#0066BF', hc: color_1.Color.white }, nls.localize(75, null)); exports.pickerGroupBorder = registerColor('pickerGroup.border', { dark: '#3F3F46', light: '#CCCEDB', hc: color_1.Color.white }, nls.localize(76, 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(77, 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(78, 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(79, 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(80, null)); /** * Editor selection colors. */ exports.editorSelectionBackground = registerColor('editor.selectionBackground', { light: '#ADD6FF', dark: '#264F78', hc: '#f3f518' }, nls.localize(81, null)); exports.editorSelectionForeground = registerColor('editor.selectionForeground', { light: null, dark: null, hc: '#000000' }, nls.localize(82, 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(83, 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(84, null), true); exports.editorSelectionHighlightBorder = registerColor('editor.selectionHighlightBorder', { light: null, dark: null, hc: exports.activeContrastBorder }, nls.localize(85, null)); /** * Editor find match colors. */ exports.editorFindMatch = registerColor('editor.findMatchBackground', { light: '#A8AC94', dark: '#515C6A', hc: null }, nls.localize(86, null)); exports.editorFindMatchHighlight = registerColor('editor.findMatchHighlightBackground', { light: '#EA5C0055', dark: '#EA5C0055', hc: null }, nls.localize(87, null), true); exports.editorFindRangeHighlight = registerColor('editor.findRangeHighlightBackground', { dark: '#3a3d4166', light: '#b4b4b44d', hc: null }, nls.localize(88, null), true); exports.editorFindMatchBorder = registerColor('editor.findMatchBorder', { light: null, dark: null, hc: exports.activeContrastBorder }, nls.localize(89, null)); exports.editorFindMatchHighlightBorder = registerColor('editor.findMatchHighlightBorder', { light: null, dark: null, hc: exports.activeContrastBorder }, nls.localize(90, null)); exports.editorFindRangeHighlightBorder = registerColor('editor.findRangeHighlightBorder', { dark: null, light: null, hc: transparent(exports.activeContrastBorder, 0.4) }, nls.localize(91, null), true); /** * Search Editor query match colors. * * Distinct from normal editor find match to allow for better differentiation */ exports.searchEditorFindMatch = registerColor('searchEditor.findMatchBackground', { light: transparent(exports.editorFindMatchHighlight, 0.66), dark: transparent(exports.editorFindMatchHighlight, 0.66), hc: exports.editorFindMatchHighlight }, nls.localize(92, null)); exports.searchEditorFindMatchBorder = registerColor('searchEditor.findMatchBorder', { light: transparent(exports.editorFindMatchHighlightBorder, 0.66), dark: transparent(exports.editorFindMatchHighlightBorder, 0.66), hc: exports.editorFindMatchHighlightBorder }, nls.localize(93, null)); /** * Editor hover */ exports.editorHoverHighlight = registerColor('editor.hoverHighlightBackground', { light: '#ADD6FF26', dark: '#264f7840', hc: '#ADD6FF26' }, nls.localize(94, null), true); exports.editorHoverBackground = registerColor('editorHoverWidget.background', { light: exports.editorWidgetBackground, dark: exports.editorWidgetBackground, hc: exports.editorWidgetBackground }, nls.localize(95, null)); exports.editorHoverForeground = registerColor('editorHoverWidget.foreground', { light: exports.editorWidgetForeground, dark: exports.editorWidgetForeground, hc: exports.editorWidgetForeground }, nls.localize(96, null)); exports.editorHoverBorder = registerColor('editorHoverWidget.border', { light: exports.editorWidgetBorder, dark: exports.editorWidgetBorder, hc: exports.editorWidgetBorder }, nls.localize(97, null)); exports.editorHoverStatusBarBackground = registerColor('editorHoverWidget.statusBarBackground', { dark: lighten(exports.editorHoverBackground, 0.2), light: darken(exports.editorHoverBackground, 0.05), hc: exports.editorWidgetBackground }, nls.localize(98, null)); /** * Editor link colors */ exports.editorActiveLinkForeground = registerColor('editorLink.activeForeground', { dark: '#4E94CE', light: color_1.Color.blue, hc: color_1.Color.cyan }, nls.localize(99, null)); /** * Inline hints */ exports.editorInlayHintForeground = registerColor('editorInlayHint.foreground', { dark: transparent(exports.badgeForeground, .8), light: transparent(exports.badgeForeground, .8), hc: exports.badgeForeground }, nls.localize(100, null)); exports.editorInlayHintBackground = registerColor('editorInlayHint.background', { dark: transparent(exports.badgeBackground, .6), light: transparent(exports.badgeBackground, .3), hc: exports.badgeBackground }, nls.localize(101, null)); exports.editorInlayHintTypeForeground = registerColor('editorInlayHint.typeForeground', { dark: exports.editorInlayHintForeground, light: exports.editorInlayHintForeground, hc: exports.editorInlayHintForeground }, nls.localize(102, null)); exports.editorInlayHintTypeBackground = registerColor('editorInlayHint.typeBackground', { dark: exports.editorInlayHintBackground, light: exports.editorInlayHintBackground, hc: exports.editorInlayHintBackground }, nls.localize(103, null)); exports.editorInlayHintParameterForeground = registerColor('editorInlayHint.parameterForeground', { dark: exports.editorInlayHintForeground, light: exports.editorInlayHintForeground, hc: exports.editorInlayHintForeground }, nls.localize(104, null)); exports.editorInlayHintParameterBackground = registerColor('editorInlayHint.parameterBackground', { dark: exports.editorInlayHintBackground, light: exports.editorInlayHintBackground, hc: exports.editorInlayHintBackground }, nls.localize(105, null)); /** * Editor lighbulb icon colors */ exports.editorLightBulbForeground = registerColor('editorLightBulb.foreground', { dark: '#FFCC00', light: '#DDB100', hc: '#FFCC00' }, nls.localize(106, null)); exports.editorLightBulbAutoFixForeground = registerColor('editorLightBulbAutoFix.foreground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, nls.localize(107, 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(108, null), true); exports.diffRemoved = registerColor('diffEditor.removedTextBackground', { dark: exports.defaultRemoveColor, light: exports.defaultRemoveColor, hc: null }, nls.localize(109, null), true); exports.diffInsertedOutline = registerColor('diffEditor.insertedTextBorder', { dark: null, light: null, hc: '#33ff2eff' }, nls.localize(110, null)); exports.diffRemovedOutline = registerColor('diffEditor.removedTextBorder', { dark: null, light: null, hc: '#FF008F' }, nls.localize(111, null)); exports.diffBorder = registerColor('diffEditor.border', { dark: null, light: null, hc: exports.contrastBorder }, nls.localize(112, null)); exports.diffDiagonalFill = registerColor('diffEditor.diagonalFill', { dark: '#cccccc33', light: '#22222233', hc: null }, nls.localize(113, null)); /** * List and tree colors */ exports.listFocusBackground = registerColor('list.focusBackground', { dark: null, light: null, hc: null }, nls.localize(114, null)); exports.listFocusForeground = registerColor('list.focusForeground', { dark: null, light: null, hc: null }, nls.localize(115, null)); exports.listFocusOutline = registerColor('list.focusOutline', { dark: exports.focusBorder, light: exports.focusBorder, hc: exports.activeContrastBorder }, nls.localize(116, null)); exports.listActiveSelectionBackground = registerColor('list.activeSelectionBackground', { dark: '#094771', light: '#0060C0', hc: null }, nls.localize(117, null)); exports.listActiveSelectionForeground = registerColor('list.activeSelectionForeground', { dark: color_1.Color.white, light: color_1.Color.white, hc: null }, nls.localize(118, null)); exports.listActiveSelectionIconForeground = registerColor('list.activeSelectionIconForeground', { dark: null, light: null, hc: null }, nls.localize(119, null)); exports.listInactiveSelectionBackground = registerColor('list.inactiveSelectionBackground', { dark: '#37373D', light: '#E4E6F1', hc: null }, nls.localize(120, null)); exports.listInactiveSelectionForeground = registerColor('list.inactiveSelectionForeground', { dark: null, light: null, hc: null }, nls.localize(121, null)); exports.listInactiveSelectionIconForeground = registerColor('list.inactiveSelectionIconForeground', { dark: null, light: null, hc: null }, nls.localize(122, null)); exports.listInactiveFocusBackground = registerColor('list.inactiveFocusBackground', { dark: null, light: null, hc: null }, nls.localize(123, null)); exports.listInactiveFocusOutline = registerColor('list.inactiveFocusOutline', { dark: null, light: null, hc: null }, nls.localize(124, null)); exports.listHoverBackground = registerColor('list.hoverBackground', { dark: '#2A2D2E', light: '#F0F0F0', hc: null }, nls.localize(125, null)); exports.listHoverForeground = registerColor('list.hoverForeground', { dark: null, light: null, hc: null }, nls.localize(126, null)); exports.listDropBackground = registerColor('list.dropBackground', { dark: '#062F4A', light: '#D6EBFF', hc: null }, nls.localize(127, null)); exports.listHighlightForeground = registerColor('list.highlightForeground', { dark: '#18A3FF', light: '#0066BF', hc: exports.focusBorder }, nls.localize(128, null)); exports.listFocusHighlightForeground = registerColor('list.focusHighlightForeground', { dark: exports.listHighlightForeground, light: ifDefinedThenElse(exports.listActiveSelectionBackground, exports.listHighlightForeground, '#9DDDFF'), hc: exports.listHighlightForeground }, nls.localize(129, null)); exports.listInvalidItemForeground = registerColor('list.invalidItemForeground', { dark: '#B89500', light: '#B89500', hc: '#B89500' }, nls.localize(130, null)); exports.listErrorForeground = registerColor('list.errorForeground', { dark: '#F88070', light: '#B01011', hc: null }, nls.localize(131, null)); exports.listWarningForeground = registerColor('list.warningForeground', { dark: '#CCA700', light: '#855F00', hc: null }, nls.localize(132, null)); exports.listFilterWidgetBackground = registerColor('listFilterWidget.background', { light: '#efc1ad', dark: '#653723', hc: color_1.Color.black }, nls.localize(133, null)); exports.listFilterWidgetOutline = registerColor('listFilterWidget.outline', { dark: color_1.Color.transparent, light: color_1.Color.transparent, hc: '#f38518' }, nls.localize(134, null)); exports.listFilterWidgetNoMatchesOutline = registerColor('listFilterWidget.noMatchesOutline', { dark: '#BE1100', light: '#BE1100', hc: exports.contrastBorder }, nls.localize(135, null)); exports.listFilterMatchHighlight = registerColor('list.filterMatchBackground', { dark: exports.editorFindMatchHighlight, light: exports.editorFindMatchHighlight, hc: null }, nls.localize(136, null)); exports.listFilterMatchHighlightBorder = registerColor('list.filterMatchBorder', { dark: exports.editorFindMatchHighlightBorder, light: exports.editorFindMatchHighlightBorder, hc: exports.contrastBorder }, nls.localize(137, null)); exports.treeIndentGuidesStroke = registerColor('tree.indentGuidesStroke', { dark: '#585858', light: '#a9a9a9', hc: '#a9a9a9' }, nls.localize(138, null)); exports.tableColumnsBorder = registerColor('tree.tableColumnsBorder', { dark: '#CCCCCC20', light: '#61616120', hc: null }, nls.localize(139, null)); exports.tableOddRowsBackgroundColor = registerColor('tree.tableOddRowsBackground', { dark: transparent(exports.foreground, 0.04), light: transparent(exports.foreground, 0.04), hc: null }, nls.localize(140, null)); exports.listDeemphasizedForeground = registerColor('list.deemphasizedForeground', { dark: '#8C8C8C', light: '#8E8E90', hc: '#A7A8A9' }, nls.localize(141, 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(142, null)); exports.quickInputListFocusForeground = registerColor('quickInputList.focusForeground', { dark: exports.listActiveSelectionForeground, light: exports.listActiveSelectionForeground, hc: exports.listActiveSelectionForeground }, nls.localize(143, null)); exports.quickInputListFocusIconForeground = registerColor('quickInputList.focusIconForeground', { dark: exports.listActiveSelectionIconForeground, light: exports.listActiveSelectionIconForeground, hc: exports.listActiveSelectionIconForeground }, nls.localize(144, null)); exports.quickInputListFocusBackground = registerColor('quickInputList.focusBackground', { dark: oneOf(exports._deprecatedQuickInputListFocusBackground, exports.listActiveSelectionBackground), light: oneOf(exports._deprecatedQuickInputListFocusBackground, exports.listActiveSelectionBackground), hc: null }, nls.localize(145, null)); /** * Menu colors */ exports.menuBorder = registerColor('menu.border', { dark: null, light: null, hc: exports.contrastBorder }, nls.localize(146, null)); exports.menuForeground = registerColor('menu.foreground', { dark: exports.selectForeground, light: exports.foreground, hc: exports.selectForeground }, nls.localize(147, null)); exports.menuBackground = registerColor('menu.background', { dark: exports.selectBackground, light: exports.selectBackground, hc: exports.selectBackground }, nls.localize(148, null)); exports.menuSelectionForeground = registerColor('menu.selectionForeground', { dark: exports.listActiveSelectionForeground, light: exports.listActiveSelectionForeground, hc: exports.listActiveSelectionForeground }, nls.localize(149, null)); exports.menuSelectionBackground = registerColor('menu.selectionBackground', { dark: exports.listActiveSelectionBackground, light: exports.listActiveSelectionBackground, hc: exports.listActiveSelectionBackground }, nls.localize(150, null)); exports.menuSelectionBorder = registerColor('menu.selectionBorder', { dark: null, light: null, hc: exports.activeContrastBorder }, nls.localize(151, null)); exports.menuSeparatorBackground = registerColor('menu.separatorBackground', { dark: '#BBBBBB', light: '#888888', hc: exports.contrastBorder }, nls.localize(152, null)); /** * Toolbar colors */ exports.toolbarHoverBackground = registerColor('toolbar.hoverBackground', { dark: '#5a5d5e50', light: '#b8b8b850', hc: null }, nls.localize(153, null)); exports.toolbarHoverOutline = registerColor('toolbar.hoverOutline', { dark: null, light: null, hc: exports.activeContrastBorder }, nls.localize(154, null)); exports.toolbarActiveBackground = registerColor('toolbar.activeBackground', { dark: lighten(exports.toolbarHoverBackground, 0.1), light: darken(exports.toolbarHoverBackground, 0.1), hc: null }, nls.localize(155, 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(156, null)); exports.snippetTabstopHighlightBorder = registerColor('editor.snippetTabstopHighlightBorder', { dark: null, light: null, hc: null }, nls.localize(157, null)); exports.snippetFinalTabstopHighlightBackground = registerColor('editor.snippetFinalTabstopHighlightBackground', { dark: null, light: null, hc: null }, nls.localize(158, 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(159, null)); /** * Breadcrumb colors */ exports.breadcrumbsForeground = registerColor('breadcrumb.foreground', { light: transparent(exports.foreground, 0.8), dark: transparent(exports.foreground, 0.8), hc: transparent(exports.foreground, 0.8) }, nls.localize(160, null)); exports.breadcrumbsBackground = registerColor('breadcrumb.background', { light: exports.editorBackground, dark: exports.editorBackground, hc: exports.editorBackground }, nls.localize(161, null)); exports.breadcrumbsFocusForeground = registerColor('breadcrumb.focusForeground', { light: darken(exports.foreground, 0.2), dark: lighten(exports.foreground, 0.1), hc: lighten(exports.foreground, 0.1) }, nls.localize(162, null)); exports.breadcrumbsActiveSelectionForeground = registerColor('breadcrumb.activeSelectionForeground', { light: darken(exports.foreground, 0.2), dark: lighten(exports.foreground, 0.1), hc: lighten(exports.foreground, 0.1) }, nls.localize(163, null)); exports.breadcrumbsPickerBackground = registerColor('breadcrumbPicker.background', { light: exports.editorWidgetBackground, dark: exports.editorWidgetBackground, hc: exports.editorWidgetBackground }, nls.localize(164, null)); /** * Merge-conflict colors */ const headerTransparency = 0.5; const currentBaseColor = color_1.Color.fromHex('#40C8AE').transparent(headerTransparency); const incomingBaseColor = color_1.Color.fromHex('#40A6FF').transparent(headerTransparency); const commonBaseColor = color_1.Color.fromHex('#606060').transparent(0.4); const contentTransparency = 0.4; const rulerTransparency = 1; exports.mergeCurrentHeaderBackground = registerColor('merge.currentHeaderBackground', { dark: currentBaseColor, light: currentBaseColor, hc: null }, nls.localize(165, null), true); exports.mergeCurrentContentBackground = registerColor('merge.currentContentBackground', { dark: transparent(exports.mergeCurrentHeaderBackground, contentTransparency), light: transparent(exports.mergeCurrentHeaderBackground, contentTransparency), hc: transparent(exports.mergeCurrentHeaderBackground, contentTransparency) }, nls.localize(166, null), true); exports.mergeIncomingHeaderBackground = registerColor('merge.incomingHeaderBackground', { dark: incomingBaseColor, light: incomingBaseColor, hc: null }, nls.localize(167, null), true); exports.mergeIncomingContentBackground = registerColor('merge.incomingContentBackground', { dark: transparent(exports.mergeIncomingHeaderBackground, contentTransparency), light: transparent(exports.mergeIncomingHeaderBackground, contentTransparency), hc: transparent(exports.mergeIncomingHeaderBackground, contentTransparency) }, nls.localize(168, null), true); exports.mergeCommonHeaderBackground = registerColor('merge.commonHeaderBackground', { dark: commonBaseColor, light: commonBaseColor, hc: null }, nls.localize(169, null), true); exports.mergeCommonContentBackground = registerColor('merge.commonContentBackground', { dark: transparent(exports.mergeCommonHeaderBackground, contentTransparency), light: transparent(exports.mergeCommonHeaderBackground, contentTransparency), hc: transparent(exports.mergeCommonHeaderBackground, contentTransparency) }, nls.localize(170, null), true); exports.mergeBorder = registerColor('merge.border', { dark: null, light: null, hc: '#C3DF6F' }, nls.localize(171, null)); exports.overviewRulerCurrentContentForeground = registerColor('editorOverviewRuler.currentContentForeground', { dark: transparent(exports.mergeCurrentHeaderBackground, rulerTransparency), light: transparent(exports.mergeCurrentHeaderBackground, rulerTransparency), hc: exports.mergeBorder }, nls.localize(172, null)); exports.overviewRulerIncomingContentForeground = registerColor('editorOverviewRuler.incomingContentForeground', { dark: transparent(exports.mergeIncomingHeaderBackground, rulerTransparency), light: transparent(exports.mergeIncomingHeaderBackground, rulerTransparency), hc: exports.mergeBorder }, nls.localize(173, null)); exports.overviewRulerCommonContentForeground = registerColor('editorOverviewRuler.commonContentForeground', { dark: transparent(exports.mergeCommonHeaderBackground, rulerTransparency), light: transparent(exports.mergeCommonHeaderBackground, rulerTransparency), hc: exports.mergeBorder }, nls.localize(174, null)); exports.overviewRulerFindMatchForeground = registerColor('editorOverviewRuler.findMatchForeground', { dark: '#d186167e', light: '#d186167e', hc: '#AB5A00' }, nls.localize(175, null), true); exports.overviewRulerSelectionHighlightForeground = registerColor('editorOverviewRuler.selectionHighlightForeground', { dark: '#A0A0A0CC', light: '#A0A0A0CC', hc: '#A0A0A0CC' }, nls.localize(176, null), true); exports.minimapFindMatch = registerColor('minimap.findMatchHighlight', { light: '#d18616', dark: '#d18616', hc: '#AB5A00' }, nls.localize(177, null), true); exports.minimapSelectionOccurrenceHighlight = registerColor('minimap.selectionOccurrenceHighlight', { light: '#c9c9c9', dark: '#676767', hc: '#ffffff' }, nls.localize(178, null), true); exports.minimapSelection = registerColor('minimap.selectionHighlight', { light: '#ADD6FF', dark: '#264F78', hc: '#ffffff' }, nls.localize(179, 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(180, null)); exports.minimapWarning = registerColor('minimap.warningHighlight', { dark: exports.editorWarningForeground, light: exports.editorWarningForeground, hc: exports.editorWarningBorder }, nls.localize(181, null)); exports.minimapBackground = registerColor('minimap.background', { dark: null, light: null, hc: null }, nls.localize(182, null)); exports.minimapForegroundOpacity = registerColor('minimap.foregroundOpacity', { dark: color_1.Color.fromHex('#000f'), light: color_1.Color.fromHex('#000f'), hc: color_1.Color.fromHex('#000f') }, nls.localize(183, 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(184, 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(185, 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(186, null)); exports.problemsErrorIconForeground = registerColor('problemsErrorIcon.foreground', { dark: exports.editorErrorForeground, light: exports.editorErrorForeground, hc: exports.editorErrorForeground }, nls.localize(187, null)); exports.problemsWarningIconForeground = registerColor('problemsWarningIcon.foreground', { dark: exports.editorWarningForeground, light: exports.editorWarningForeground, hc: exports.editorWarningForeground }, nls.localize(188, null)); exports.problemsInfoIconForeground = registerColor('problemsInfoIcon.foreground', { dark: exports.editorInfoForeground, light: exports.editorInfoForeground, hc: exports.editorInfoForeground }, nls.localize(189, null)); /** * Chart colors */ exports.chartsForeground = registerColor('charts.foreground', { dark: exports.foreground, light: exports.foreground, hc: exports.foreground }, nls.localize(190, null)); exports.chartsLines = registerColor('charts.lines', { dark: transparent(exports.foreground, .5), light: transparent(exports.foreground, .5), hc: transparent(exports.foreground, .5) }, nls.localize(191, null)); exports.chartsRed = registerColor('charts.red', { dark: exports.editorErrorForeground, light: exports.editorErrorForeground, hc: exports.editorErrorForeground }, nls.localize(192, null)); exports.chartsBlue = registerColor('charts.blue', { dark: exports.editorInfoForeground, light: exports.editorInfoForeground, hc: exports.editorInfoForeground }, nls.localize(193, null)); exports.chartsYellow = registerColor('charts.yellow', { dark: exports.editorWarningForeground, light: exports.editorWarningForeground, hc: exports.editorWarningForeground }, nls.localize(194, null)); exports.chartsOrange = registerColor('charts.orange', { dark: exports.minimapFindMatch, light: exports.minimapFindMatch, hc: exports.minimapFindMatch }, nls.localize(195, null)); exports.chartsGreen = registerColor('charts.green', { dark: '#89D185', light: '#388A34', hc: '#89D185' }, nls.localize(196, null)); exports.chartsPurple = registerColor('charts.purple', { dark: '#B180D7', light: '#652D90', hc: '#B180D7' }, nls.localize(197, 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[130/*vs/editor/browser/editorDom*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,96/*vs/base/browser/globalMouseMoveMonitor*/,56/*vs/base/browser/mouseEvent*/,10/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,23/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, dom, globalMouseMoveMonitor_1, mouseEvent_1, async_1, lifecycle_1, colorRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DynamicCssRules = exports.GlobalEditorMouseMoveMonitor = exports.EditorPointerEventFactory = exports.EditorMouseEventFactory = exports.EditorMouseEvent = exports.createCoordinatesRelativeToEditor = exports.createEditorPagePosition = exports.CoordinatesRelativeToEditor = 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; /** * Coordinates relative to the the (top;left) of the editor that can be used safely with other internal editor metrics. * **NOTE**: This position is obtained by taking page coordinates and transforming them relative to the * editor's (top;left) position in a way in which scale transformations are taken into account. * **NOTE**: These coordinates could be negative if the mouse position is outside the editor. */ class CoordinatesRelativeToEditor { constructor(x, y) { this.x = x; this.y = y; this._positionRelativeToEditorBrand = undefined; } } exports.CoordinatesRelativeToEditor = CoordinatesRelativeToEditor; function createEditorPagePosition(editorViewDomNode) { const editorPos = dom.getDomNodePagePosition(editorViewDomNode); return new EditorPagePosition(editorPos.left, editorPos.top, editorPos.width, editorPos.height); } exports.createEditorPagePosition = createEditorPagePosition; function createCoordinatesRelativeToEditor(editorViewDomNode, editorPagePosition, pos) { // The editor's page position is read from the DOM using getBoundingClientRect(). // // getBoundingClientRect() returns the actual dimensions, while offsetWidth and offsetHeight // reflect the unscaled size. We can use this difference to detect a transform:scale() // and we will apply the transformation in inverse to get mouse coordinates that make sense inside the editor. // // This could be expanded to cover rotation as well maybe by walking the DOM up from `editorViewDomNode` // and computing the effective transformation matrix using getComputedStyle(element).transform. // const scaleX = editorPagePosition.width / editorViewDomNode.offsetWidth; const scaleY = editorPagePosition.height / editorViewDomNode.offsetHeight; // Adjust mouse offsets if editor appears to be scaled via transforms const relativeX = (pos.x - editorPagePosition.x) / scaleX; const relativeY = (pos.y - editorPagePosition.y) / scaleY; return new CoordinatesRelativeToEditor(relativeX, relativeY); } exports.createCoordinatesRelativeToEditor = createCoordinatesRelativeToEditor; 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); this.relativePos = createCoordinatesRelativeToEditor(editorViewDomNode, this.editorPos, this.pos); } } 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 <> 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; /** * A helper to create dynamic css rules, bound to a class name. * Rules are reused. * Reference counting and delayed garbage collection ensure that no rules leak. */ class DynamicCssRules { constructor(_editor) { this._editor = _editor; this._instanceId = ++DynamicCssRules._idPool; this._counter = 0; this._rules = new Map(); // We delay garbage collection so that hanging rules can be reused. this._garbageCollectionScheduler = new async_1.RunOnceScheduler(() => this.garbageCollect(), 1000); } createClassNameRef(options) { const rule = this.getOrCreateRule(options); rule.increaseRefCount(); return { className: rule.className, dispose: () => { rule.decreaseRefCount(); this._garbageCollectionScheduler.schedule(); } }; } getOrCreateRule(properties) { const key = this.computeUniqueKey(properties); let existingRule = this._rules.get(key); if (!existingRule) { const counter = this._counter++; existingRule = new RefCountedCssRule(key, `dyn-rule-${this._instanceId}-${counter}`, dom.isInShadowDOM(this._editor.getContainerDomNode()) ? this._editor.getContainerDomNode() : undefined, properties); this._rules.set(key, existingRule); } return existingRule; } computeUniqueKey(properties) { return JSON.stringify(properties); } garbageCollect() { for (const rule of this._rules.values()) { if (!rule.hasReferences()) { this._rules.delete(rule.key); rule.dispose(); } } } } exports.DynamicCssRules = DynamicCssRules; DynamicCssRules._idPool = 0; class RefCountedCssRule { constructor(key, className, _containerElement, properties) { this.key = key; this.className = className; this.properties = properties; this._referenceCount = 0; this._styleElement = dom.createStyleSheet(_containerElement); this._styleElement.textContent = this.getCssText(this.className, this.properties); } getCssText(className, properties) { let str = `.${className} {`; for (const prop in properties) { const value = properties[prop]; let cssValue; if (typeof value === 'object') { cssValue = `var(${(0, colorRegistry_1.asCssVariableName)(value.id)})`; } else { cssValue = value; } const cssPropName = camelToDashes(prop); str += `\n\t${cssPropName}: ${cssValue};`; } str += `\n}`; return str; } dispose() { this._styleElement.remove(); } increaseRefCount() { this._referenceCount++; } decreaseRefCount() { this._referenceCount--; } hasReferences() { return this._referenceCount > 0; } } function camelToDashes(str) { return str.replace(/(^[A-Z])/, ([first]) => first.toLowerCase()) .replace(/([A-Z])/g, ([letter]) => `-${letter.toLowerCase()}`); } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[131/*vs/platform/theme/common/styler*/], __M([1/*require*/,0/*exports*/,23/*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, tableOddRowsBackgroundColor: colorRegistry_1.tableOddRowsBackgroundColor }; 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, scrollbarShadow: colorRegistry_1.scrollbarShadow, scrollbarSliderBackground: colorRegistry_1.scrollbarSliderBackground, scrollbarSliderHoverBackground: colorRegistry_1.scrollbarSliderHoverBackground, scrollbarSliderActiveBackground: colorRegistry_1.scrollbarSliderActiveBackground }; 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[634/*vs/platform/contextview/browser/contextMenuHandler*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,56/*vs/base/browser/mouseEvent*/,487/*vs/base/browser/ui/menu/menu*/,44/*vs/base/common/actions*/,13/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,131/*vs/platform/theme/common/styler*/,396/*vs/css!vs/platform/contextview/browser/contextMenuHandler*/]), function (require, exports, dom_1, mouseEvent_1, menu_1, actions_1, errors_1, lifecycle_1, styler_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.isCancellationError)(e.error)) { this.notificationService.error(e.error); } } } exports.ContextMenuHandler = ContextMenuHandler; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[132/*vs/platform/theme/common/theme*/], __M([1/*require*/,0/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ColorScheme = void 0; /** * 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[278/*vs/editor/browser/viewParts/lines/viewLine*/], __M([1/*require*/,0/*exports*/,34/*vs/base/browser/browser*/,30/*vs/base/browser/fastDomNode*/,17/*vs/base/common/platform*/,398/*vs/editor/browser/viewParts/lines/rangeUtil*/,116/*vs/editor/browser/view/renderingContext*/,151/*vs/editor/common/viewLayout/lineDecorations*/,122/*vs/editor/common/viewLayout/viewLineRenderer*/,132/*vs/platform/theme/common/theme*/,31/*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._clientRectScale = 1; this._clientRectRead = false; this.endNode = endNode; } readClientRect() { if (!this._clientRectRead) { this._clientRectRead = true; const rect = this._domNode.getBoundingClientRect(); this._clientRectDeltaLeft = rect.left; this._clientRectScale = rect.width / this._domNode.offsetWidth; } } get clientRectDeltaLeft() { if (!this._clientRectRead) { this.readClientRect(); } return this._clientRectDeltaLeft; } get clientRectScale() { if (!this._clientRectRead) { this.readClientRect(); } return this._clientRectScale; } } exports.DomReadingContext = DomReadingContext; class ViewLineOptions { constructor(config, themeType) { this.themeType = themeType; const options = config.options; const fontInfo = options.get(44 /* fontInfo */); this.renderWhitespace = options.get(88 /* renderWhitespace */); this.renderControlCharacters = options.get(83 /* renderControlCharacters */); this.spaceWidth = fontInfo.spaceWidth; this.middotWidth = fontInfo.middotWidth; this.wsmiddotWidth = fontInfo.wsmiddotWidth; this.useMonospaceOptimizations = (fontInfo.isMonospace && !options.get(29 /* disableMonospaceOptimizations */)); this.canUseHalfwidthRightwardsArrow = fontInfo.canUseHalfwidthRightwardsArrow; this.lineHeight = options.get(59 /* lineHeight */); this.stopRenderingLineAfter = options.get(105 /* stopRenderingLineAfter */); this.fontLigatures = options.get(45 /* 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('
    '); const output = (0, viewLineRenderer_1.renderViewLine)(renderLineInput, sb); sb.appendASCIIString('
    '); 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 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(lineNumber, startColumn, endColumn, context) { if (!this._renderedViewLine) { return null; } startColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, startColumn)); endColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, endColumn)); const stopRenderingLineAfter = this._renderedViewLine.input.stopRenderingLineAfter; 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(lineNumber, 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 Math.round(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(lineNumber, startColumn, endColumn, context) { const startPosition = this._getCharPosition(startColumn); const endPosition = this._getCharPosition(endColumn); return [new renderingContext_1.FloatHorizontalRange(startPosition, endPosition - startPosition)]; } _getCharPosition(column) { const charOffset = this._characterMapping.getAbsoluteOffset(column); return 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 Float32Array(Math.max(2, this._characterMapping.length + 1)); for (let column = 0, len = this._characterMapping.length; column <= len; column++) { this._pixelOffsetCache[column] = -1; } } } // --- Reading from the DOM methods _getReadingTarget(myDomNode) { return myDomNode.domNode.firstChild; } /** * Width of the line in pixels */ getWidth() { 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(lineNumber, startColumn, endColumn, context) { if (!this.domNode) { return null; } if (this._pixelOffsetCache !== null) { // the text is LTR const startOffset = this._readPixelOffset(this.domNode, lineNumber, startColumn, context); if (startOffset === -1) { return null; } const endOffset = this._readPixelOffset(this.domNode, lineNumber, endColumn, context); if (endOffset === -1) { return null; } return [new renderingContext_1.FloatHorizontalRange(startOffset, endOffset - startOffset)]; } return this._readVisibleRangesForRange(this.domNode, lineNumber, startColumn, endColumn, context); } _readVisibleRangesForRange(domNode, lineNumber, startColumn, endColumn, context) { if (startColumn === endColumn) { const pixelOffset = this._readPixelOffset(domNode, lineNumber, startColumn, context); if (pixelOffset === -1) { return null; } else { return [new renderingContext_1.FloatHorizontalRange(pixelOffset, 0)]; } } else { return this._readRawVisibleRangesForRange(domNode, startColumn, endColumn, context); } } _readPixelOffset(domNode, lineNumber, column, context) { if (this._characterMapping.length === 0) { // This line has no content if (this._containsForeignElements === 0 /* 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, lineNumber, column, context); this._pixelOffsetCache[column] = result; return result; } return this._actualReadPixelOffset(domNode, lineNumber, column, context); } _actualReadPixelOffset(domNode, lineNumber, column, context) { if (this._characterMapping.length === 0) { // This line has no content const r = rangeUtil_1.RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), 0, 0, 0, 0, context.clientRectDeltaLeft, context.clientRectScale, 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.clientRectScale, 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.FloatHorizontalRange(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.clientRectScale, 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, lineNumber, startColumn, endColumn, context) { const output = super._readVisibleRangesForRange(domNode, lineNumber, startColumn, endColumn, context); if (!output || output.length === 0 || startColumn === endColumn || (startColumn === 1 && endColumn === this._characterMapping.length)) { return output; } // WebKit is buggy and returns an expanded range (to contain words in some cases) // The last client rect is enlarged (I think) if (!this.input.containsRTL) { // This is an attempt to patch things up // Find position of last column const endPixelOffset = this._readPixelOffset(domNode, lineNumber, endColumn, context); if (endPixelOffset !== -1) { const lastRange = output[output.length - 1]; if (lastRange.left < endPixelOffset) { // Trim down the width of the last visible range to not go after the last column's position lastRange.width = endPixelOffset - lastRange.left; } } } return output; } } const createRenderedLine = (function () { if (browser.isWebKit) { return createWebKitRenderedLine; } return createNormalRenderedLine; })(); function createWebKitRenderedLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements) { return new WebKitRenderedViewLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements); } function createNormalRenderedLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements) { return new RenderedViewLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements); } }); /*--------------------------------------------------------------------------------------------- * 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/browser/controller/mouseTarget*/], __M([1/*require*/,0/*exports*/,130/*vs/editor/browser/editorDom*/,50/*vs/editor/browser/view/viewPart*/,278/*vs/editor/browser/viewParts/lines/viewLine*/,11/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,68/*vs/editor/common/core/cursorColumns*/,7/*vs/base/browser/dom*/,238/*vs/editor/common/cursor/cursorAtomicMoveOperations*/]), function (require, exports, editorDom_1, viewPart_1, viewLine_1, position_1, range_1, cursorColumns_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 { static _deduceRage(position, range = null) { if (!range && position) { return new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column); } return range !== null && range !== void 0 ? range : null; } static createUnknown(element, mouseColumn, position) { return { type: 0 /* UNKNOWN */, element, mouseColumn, position, range: this._deduceRage(position) }; } static createTextarea(element, mouseColumn) { return { type: 1 /* TEXTAREA */, element, mouseColumn, position: null, range: null }; } static createMargin(type, element, mouseColumn, position, range, detail) { return { type, element, mouseColumn, position, range, detail }; } static createViewZone(type, element, mouseColumn, position, detail) { return { type, element, mouseColumn, position, range: this._deduceRage(position), detail }; } static createContentText(element, mouseColumn, position, range, detail) { return { type: 6 /* CONTENT_TEXT */, element, mouseColumn, position, range: this._deduceRage(position, range), detail }; } static createContentEmpty(element, mouseColumn, position, detail) { return { type: 7 /* CONTENT_EMPTY */, element, mouseColumn, position, range: this._deduceRage(position), detail }; } static createContentWidget(element, mouseColumn, detail) { return { type: 9 /* CONTENT_WIDGET */, element, mouseColumn, position: null, range: null, detail }; } static createScrollbar(element, mouseColumn, position) { return { type: 11 /* SCROLLBAR */, element, mouseColumn, position, range: this._deduceRage(position) }; } static createOverlayWidget(element, mouseColumn, detail) { return { type: 12 /* OVERLAY_WIDGET */, element, mouseColumn, position: null, range: null, detail }; } static createOutsideEditor(mouseColumn, position) { return { type: 13 /* OUTSIDE_EDITOR */, element: null, mouseColumn, position, range: this._deduceRage(position) }; } 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 + ' - ' + JSON.stringify(target.detail); } } 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(131 /* layoutInfo */); this.viewDomNode = viewHelper.viewDomNode; this.lineHeight = options.get(59 /* lineHeight */); this.stickyTabStops = options.get(104 /* stickyTabStops */); this.typicalHalfwidthCharacterWidth = options.get(44 /* 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, relativePos) { this.editorPos = editorPos; this.pos = pos; this.relativePos = relativePos; this.mouseVerticalOffset = Math.max(0, ctx.getCurrentScrollTop() + this.relativePos.y); this.mouseContentHorizontalOffset = ctx.getCurrentScrollLeft() + this.relativePos.x - ctx.layoutInfo.contentLeft; this.isInMarginArea = (this.relativePos.x < ctx.layoutInfo.contentLeft && this.relativePos.x >= ctx.layoutInfo.glyphMarginLeft); this.isInContentArea = !this.isInMarginArea; this.mouseColumn = Math.max(0, MouseTargetFactory._getMouseColumn(this.mouseContentHorizontalOffset, ctx.typicalHalfwidthCharacterWidth)); } } class HitTestRequest extends BareHitTestRequest { constructor(ctx, editorPos, pos, relativePos, target) { super(ctx, editorPos, pos, relativePos); 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}), relativePos(${this.relativePos.x},${this.relativePos.y}), mouseVerticalOffset: ${this.mouseVerticalOffset}, mouseContentHorizontalOffset: ${this.mouseContentHorizontalOffset}\n\ttarget: ${this.target ? this.target.outerHTML : null}`; } _getMouseColumn(position = null) { if (position && position.column < this._ctx.model.getLineMaxColumn(position.lineNumber)) { // Most likely, the line contains foreign decorations... return cursorColumns_1.CursorColumns.visibleColumnFromColumn(this._ctx.model.getLineContent(position.lineNumber), position.column, this._ctx.model.getTextModelOptions().tabSize) + 1; } return this.mouseColumn; } fulfillUnknown(position = null) { return MouseTarget.createUnknown(this.target, this._getMouseColumn(position), position); } fulfillTextarea() { return MouseTarget.createTextarea(this.target, this._getMouseColumn()); } fulfillMargin(type, position, range, detail) { return MouseTarget.createMargin(type, this.target, this._getMouseColumn(position), position, range, detail); } fulfillViewZone(type, position, detail) { return MouseTarget.createViewZone(type, this.target, this._getMouseColumn(position), position, detail); } fulfillContentText(position, range, detail) { return MouseTarget.createContentText(this.target, this._getMouseColumn(position), position, range, detail); } fulfillContentEmpty(position, detail) { return MouseTarget.createContentEmpty(this.target, this._getMouseColumn(position), position, detail); } fulfillContentWidget(detail) { return MouseTarget.createContentWidget(this.target, this._getMouseColumn(), detail); } fulfillScrollbar(position) { return MouseTarget.createScrollbar(this.target, this._getMouseColumn(position), position); } fulfillOverlayWidget(detail) { return MouseTarget.createOverlayWidget(this.target, this._getMouseColumn(), detail); } withTarget(target) { return new HitTestRequest(this._ctx, this.editorPos, this.pos, this.relativePos, 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, relativePos, target) { const ctx = new HitTestContext(this._context, this._viewHelper, lastRenderData); const request = new HitTestRequest(ctx, editorPos, pos, relativePos, target); try { const r = MouseTargetFactory._createMouseTarget(ctx, request, false); // console.log(MouseTarget.toString(r)); return r; } catch (err) { // console.log(err); return request.fulfillUnknown(); } } 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.fulfillUnknown(); } 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.fulfillUnknown()); } static _hitTestContentWidget(ctx, request) { // Is it a content widget? if (ElementPath.isChildOfContentWidgets(request.targetPath) || ElementPath.isChildOfOverflowingContentWidgets(request.targetPath)) { const widgetId = ctx.findAttribute(request.target, 'widgetId'); if (widgetId) { return request.fulfillContentWidget(widgetId); } else { return request.fulfillUnknown(); } } return null; } static _hitTestOverlayWidget(ctx, request) { // Is it an overlay widget? if (ElementPath.isChildOfOverlayWidgets(request.targetPath)) { const widgetId = ctx.findAttribute(request.target, 'widgetId'); if (widgetId) { return request.fulfillOverlayWidget(widgetId); } else { return request.fulfillUnknown(); } } return null; } static _hitTestViewCursor(ctx, request) { if (request.target) { // Check if we've hit a painted cursor const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData; for (const d of lastViewCursorsRenderData) { if (request.target === d.domNode) { return request.fulfillContentText(d.position, null, { mightBeForeignElement: false, injectedText: null }); } } } if (request.isInContentArea) { // Edge has a bug when hit-testing the exact position of a cursor, // instead of returning the correct dom node, it returns the // first or last rendered view line dom node, therefore help it out // and first check if we are on top of a cursor const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData; const mouseContentHorizontalOffset = request.mouseContentHorizontalOffset; const mouseVerticalOffset = request.mouseVerticalOffset; for (const d of lastViewCursorsRenderData) { if (mouseContentHorizontalOffset < d.contentLeft) { // mouse position is to the left of the cursor continue; } if (mouseContentHorizontalOffset > d.contentLeft + d.width) { // mouse position is to the right of the cursor continue; } const cursorVerticalOffset = ctx.getVerticalOffsetForLineNumber(d.position.lineNumber); if (cursorVerticalOffset <= mouseVerticalOffset && mouseVerticalOffset <= cursorVerticalOffset + d.height) { return request.fulfillContentText(d.position, null, { mightBeForeignElement: false, injectedText: null }); } } } return null; } static _hitTestViewZone(ctx, request) { const viewZoneData = ctx.getZoneAtCoord(request.mouseVerticalOffset); if (viewZoneData) { const mouseTargetType = (request.isInContentArea ? 8 /* CONTENT_VIEW_ZONE */ : 5 /* GUTTER_VIEW_ZONE */); return request.fulfillViewZone(mouseTargetType, viewZoneData.position, viewZoneData); } return null; } static _hitTestTextArea(ctx, request) { // Is it the textarea? if (ElementPath.isTextArea(request.targetPath)) { if (ctx.lastRenderData.lastTextareaPosition) { return request.fulfillContentText(ctx.lastRenderData.lastTextareaPosition, null, { mightBeForeignElement: false, injectedText: null }); } return request.fulfillTextarea(); } return null; } static _hitTestMargin(ctx, request) { if (request.isInMarginArea) { const res = ctx.getFullLineRangeAtCoord(request.mouseVerticalOffset); const pos = res.range.getStartPosition(); let offset = Math.abs(request.relativePos.x); const detail = { isAfterLines: res.isAfterLines, glyphMarginLeft: ctx.layoutInfo.glyphMarginLeft, glyphMarginWidth: ctx.layoutInfo.glyphMarginWidth, lineNumbersWidth: ctx.layoutInfo.lineNumbersWidth, offsetX: offset }; offset -= ctx.layoutInfo.glyphMarginLeft; if (offset <= ctx.layoutInfo.glyphMarginWidth) { // On the glyph margin return request.fulfillMargin(2 /* GUTTER_GLYPH_MARGIN */, pos, res.range, detail); } offset -= ctx.layoutInfo.glyphMarginWidth; if (offset <= ctx.layoutInfo.lineNumbersWidth) { // On the line numbers return request.fulfillMargin(3 /* GUTTER_LINE_NUMBERS */, pos, res.range, detail); } offset -= ctx.layoutInfo.lineNumbersWidth; // On the line decorations return request.fulfillMargin(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.fulfillContentEmpty(new position_1.Position(1, 1), EMPTY_CONTENT_AFTER_LINES); } // Check if it is below any lines and any view zones if (ctx.isAfterLines(request.mouseVerticalOffset) || ctx.isInBottomPadding(request.mouseVerticalOffset)) { // This most likely indicates it happened after the last view-line const lineCount = ctx.model.getLineCount(); const maxLineColumn = ctx.model.getLineMaxColumn(lineCount); return request.fulfillContentEmpty(new position_1.Position(lineCount, maxLineColumn), 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.fulfillContentEmpty(new position_1.Position(lineNumber, 1), 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.fulfillContentEmpty(pos, detail); } } // We have already executed hit test... return request.fulfillUnknown(); } 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.fulfillScrollbar(new position_1.Position(possibleLineNumber, maxColumn)); } return null; } static _hitTestScrollbarSlider(ctx, request) { if (ElementPath.isChildOfScrollableElement(request.targetPath)) { if (request.target && request.target.nodeType === 1) { const className = request.target.className; if (className && /\b(slider|scrollbar)\b/.test(className)) { const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); const maxColumn = ctx.model.getLineMaxColumn(possibleLineNumber); return request.fulfillScrollbar(new position_1.Position(possibleLineNumber, maxColumn)); } } } return null; } static _hitTestScrollbar(ctx, request) { // Is it the overview ruler? // Is it a child of the scrollable element? if (ElementPath.isChildOfScrollableElement(request.targetPath)) { const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); const maxColumn = ctx.model.getLineMaxColumn(possibleLineNumber); return request.fulfillScrollbar(new position_1.Position(possibleLineNumber, maxColumn)); } return null; } getMouseColumn(relativePos) { const options = this._context.configuration.options; const layoutInfo = options.get(131 /* layoutInfo */); const mouseContentHorizontalOffset = this._context.viewLayout.getCurrentScrollLeft() + relativePos.x - layoutInfo.contentLeft; return MouseTargetFactory._getMouseColumn(mouseContentHorizontalOffset, options.get(44 /* fontInfo */).typicalHalfwidthCharacterWidth); } static _getMouseColumn(mouseContentHorizontalOffset, typicalHalfwidthCharacterWidth) { if (mouseContentHorizontalOffset < 0) { return 1; } const chars = Math.round(mouseContentHorizontalOffset / typicalHalfwidthCharacterWidth); return (chars + 1); } static createMouseTargetFromHitTestPosition(ctx, request, spanNode, pos, injectedText) { const lineNumber = pos.lineNumber; const column = pos.column; const lineWidth = ctx.getLineWidth(lineNumber); if (request.mouseContentHorizontalOffset > lineWidth) { const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth); return request.fulfillContentEmpty(pos, detail); } const visibleRange = ctx.visibleRangeForPosition(lineNumber, column); if (!visibleRange) { return request.fulfillUnknown(pos); } const columnHorizontalOffset = visibleRange.left; if (request.mouseContentHorizontalOffset === columnHorizontalOffset) { return request.fulfillContentText(pos, null, { mightBeForeignElement: !!injectedText, injectedText }); } const points = []; points.push({ offset: visibleRange.left, column: column }); if (column > 1) { const visibleRange = ctx.visibleRangeForPosition(lineNumber, column - 1); if (visibleRange) { points.push({ offset: visibleRange.left, column: column - 1 }); } } const lineMaxColumn = ctx.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.fulfillContentText(pos, rng, { mightBeForeignElement: !mouseIsOverSpanNode || !!injectedText, injectedText }); } } return request.fulfillContentText(pos, null, { mightBeForeignElement: !mouseIsOverSpanNode || !!injectedText, injectedText }); } /** * Most probably WebKit browsers and Edge */ static _doHitTestWithCaretRangeFromPoint(ctx, request) { // In Chrome, especially on Linux it is possible to click between lines, // so try to adjust the `hity` below so that it lands in the center of a line const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); const 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 + request.editorPos.height) { adjustedPageY = request.editorPos.y + request.editorPos.height - 1; } const adjustedPage = new editorDom_1.PageCoordinates(request.pos.x, adjustedPageY); const r = this._actualDoHitTestWithCaretRangeFromPoint(ctx, adjustedPage.toClientCoordinates()); 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 `` of the line and the offset is the `` with the inline decoration // Some other times, it returns the `` 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 `` of the line and the offset is the `` 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 `` 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[635/*vs/editor/browser/controller/mouseHandler*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,56/*vs/base/browser/mouseEvent*/,10/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,279/*vs/editor/browser/controller/mouseTarget*/,130/*vs/editor/browser/editorDom*/,144/*vs/editor/common/config/editorZoom*/,11/*vs/editor/common/core/position*/,22/*vs/editor/common/core/selection*/,123/*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(131 /* 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(68 /* 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(131 /* layoutInfo */)) { // layout change const height = this._context.configuration.options.get(131 /* 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; } const relativePos = (0, editorDom_1.createCoordinatesRelativeToEditor)(this.viewHelper.viewDomNode, editorPos, pos); return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), editorPos, pos, relativePos, null); } _createMouseTarget(e, testEventTarget) { let target = e.target; if (!this.viewHelper.viewDomNode.contains(target)) { const shadowRoot = dom.getShadowRoot(this.viewHelper.viewDomNode); if (shadowRoot) { target = shadowRoot.elementsFromPoint(e.posx, e.posy).find((el) => this.viewHelper.viewDomNode.contains(el)); } } return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), e.editorPos, e.pos, e.relativePos, testEventTarget ? target : null); } _getMouseColumn(e) { return this.mouseTargetFactory.getMouseColumn(e.relativePos); } _onContextMenu(e, testEventTarget) { this.viewController.emitContextMenu({ event: e, target: this._createMouseTarget(e, testEventTarget) }); } _onMouseMove(e) { 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(98 /* 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(81 /* readOnly */) && options.get(31 /* dragAndDrop */) && !options.get(18 /* 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 mouseTarget_1.MouseTarget.createOutsideEditor(mouseColumn, newPosition); } } const aboveLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset); return mouseTarget_1.MouseTarget.createOutsideEditor(mouseColumn, new position_1.Position(aboveLineNumber, 1)); } if (e.posy > editorContent.y + editorContent.height) { const verticalOffset = viewLayout.getCurrentScrollTop() + e.relativePos.y; const viewZoneData = mouseTarget_1.HitTestContext.getZoneAtCoord(this._context, verticalOffset); if (viewZoneData) { const newPosition = this._helpPositionJumpOverViewZone(viewZoneData); if (newPosition) { return mouseTarget_1.MouseTarget.createOutsideEditor(mouseColumn, newPosition); } } const belowLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset); return mouseTarget_1.MouseTarget.createOutsideEditor(mouseColumn, new position_1.Position(belowLineNumber, model.getLineMaxColumn(belowLineNumber))); } const possibleLineNumber = viewLayout.getLineNumberAtVerticalOffset(viewLayout.getCurrentScrollTop() + e.relativePos.y); if (e.posx < editorContent.x) { return mouseTarget_1.MouseTarget.createOutsideEditor(mouseColumn, new position_1.Position(possibleLineNumber, 1)); } if (e.posx > editorContent.x + editorContent.width) { return mouseTarget_1.MouseTarget.createOutsideEditor(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 mouseTarget_1.MouseTarget.createViewZone(t.type, t.element, t.mouseColumn, newPosition, t.detail); } } return t; } _helpPositionJumpOverViewZone(viewZoneData) { // Force position on view zones to go above or below depending on where selection started from const selectionStart = new position_1.Position(this._currentSelection.selectionStartLineNumber, this._currentSelection.selectionStartColumn); const positionBefore = viewZoneData.positionBefore; const positionAfter = viewZoneData.positionAfter; if (positionBefore && positionAfter) { if (positionBefore.isBefore(selectionStart)) { return positionBefore; } else { return positionAfter; } } return null; } _dispatchMouse(position, inSelectionMode) { 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[636/*vs/editor/browser/controller/pointerHandler*/], __M([1/*require*/,0/*exports*/,7/*vs/base/browser/dom*/,17/*vs/base/common/platform*/,57/*vs/base/browser/touch*/,2/*vs/base/common/lifecycle*/,635/*vs/editor/browser/controller/mouseHandler*/,130/*vs/editor/browser/editorDom*/,165/*vs/base/browser/canIUse*/,175/*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