/*!----------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Version: 0.20.0(6363745c0a33c27b149b89342a7b96d354fb554c) * Released under the MIT license * https://github.com/Microsoft/vscode/blob/master/LICENSE.txt *-----------------------------------------------------------*/ (function() { var __m = ["require","exports","vs/base/common/lifecycle","vs/editor/common/core/range","vs/base/common/event","vs/base/common/strings","vs/base/browser/dom","vs/nls","vs/nls!vs/editor/editor.main","vs/css!vs/editor/editor.main","vs/base/common/errors","vs/platform/instantiation/common/instantiation","vs/editor/browser/editorExtensions","vs/editor/common/core/position","vs/platform/theme/common/themeService","vs/base/common/async","vs/base/common/platform","vs/editor/common/modes","vs/platform/contextkey/common/contextkey","vs/base/common/arrays","vs/platform/theme/common/colorRegistry","vs/base/common/types","vs/editor/common/core/selection","vs/editor/common/editorContextKeys","vs/base/browser/browser","vs/base/common/uri","vs/base/common/cancellation","vs/base/common/color","vs/base/browser/fastDomNode","vs/platform/commands/common/commands","vs/editor/common/model/textModel","vs/base/common/objects","vs/editor/browser/services/codeEditorService","vs/editor/common/config/editorOptions","vs/platform/keybinding/common/keybinding","vs/platform/notification/common/notification","vs/base/common/keyCodes","vs/editor/browser/view/viewPart","vs/base/common/map","vs/base/common/resources","vs/editor/common/controller/cursorCommon","vs/editor/common/modes/languageConfigurationRegistry","vs/platform/registry/common/platform","vs/platform/configuration/common/configuration","vs/editor/common/view/editorColorRegistry","vs/base/browser/mouseEvent","vs/base/common/network","vs/base/browser/ui/widget","vs/editor/common/model","vs/editor/common/services/modelService","vs/base/browser/ui/aria/aria","vs/platform/opener/common/opener","vs/base/browser/event","vs/base/browser/ui/scrollbar/scrollableElement","vs/base/common/iterator","vs/base/common/actions","vs/base/browser/keyboardEvent","vs/base/browser/touch","vs/editor/common/core/editOperation","vs/editor/common/standaloneStrings","vs/editor/browser/config/configuration","vs/base/common/filters","vs/editor/common/services/editorWorkerService","vs/editor/common/modes/nullMode","vs/platform/accessibility/common/accessibility","vs/platform/actions/common/actions","vs/platform/contextview/browser/contextView","vs/editor/browser/core/editorState","vs/editor/common/editorCommon","vs/editor/common/viewModel/viewModel","vs/base/browser/ui/actionbar/actionbar","vs/editor/common/services/modeService","vs/platform/markers/common/markers","vs/platform/progress/common/progress","vs/platform/storage/common/storage","vs/base/common/htmlContent","vs/base/common/linkedList","vs/base/common/path","vs/base/browser/globalMouseMoveMonitor","vs/editor/common/core/characterClassifier","vs/editor/common/commands/replaceCommand","vs/editor/common/view/viewEvents","vs/editor/browser/view/dynamicViewOverlay","vs/platform/instantiation/common/extensions","vs/editor/common/services/resolverService","vs/platform/configuration/common/configurationRegistry","vs/platform/keybinding/common/keybindingsRegistry","vs/base/common/collections","vs/base/browser/canIUse","vs/editor/common/controller/wordCharacterClassifier","vs/editor/common/modes/languageConfiguration","vs/editor/common/view/renderingContext","vs/editor/common/viewModel/viewEventHandler","vs/editor/common/core/lineTokens","vs/editor/standalone/common/standaloneThemeService","vs/platform/log/common/log","vs/platform/telemetry/common/telemetry","vs/platform/theme/common/styler","vs/base/browser/dnd","vs/base/browser/ui/tree/tree","vs/base/common/codicons","vs/base/common/decorators","vs/base/common/functional","vs/base/common/range","vs/base/browser/ui/sash/sash","vs/editor/common/config/editorZoom","vs/editor/common/core/stringBuilder","vs/editor/common/core/token","vs/editor/browser/editorBrowser","vs/editor/common/model/wordHelper","vs/editor/common/viewLayout/viewLineRenderer","vs/editor/contrib/codeAction/types","vs/base/common/severity","vs/editor/contrib/gotoSymbol/referencesModel","vs/editor/common/services/textResourceConfigurationService","vs/platform/instantiation/common/serviceCollection","vs/platform/label/common/label","vs/editor/contrib/markdown/markdownRenderer","vs/editor/common/modes/modesRegistry","vs/editor/contrib/codeAction/codeAction","vs/editor/contrib/suggest/suggest","vs/editor/browser/widget/codeEditorWidget","vs/editor/contrib/message/messageController","vs/editor/contrib/peekView/peekView","vs/base/common/assert","vs/base/common/hash","vs/base/common/diff/diff","vs/base/common/idGenerator","vs/base/common/lazy","vs/base/browser/ui/tree/indexTreeModel","vs/base/browser/ui/tree/objectTreeModel","vs/base/common/numbers","vs/base/common/stopwatch","vs/base/browser/ui/highlightedlabel/highlightedLabel","vs/base/browser/formattedTextRenderer","vs/base/browser/ui/scrollbar/scrollbarArrow","vs/base/common/labels","vs/base/parts/tree/browser/treeDefaults","vs/base/browser/ui/checkbox/checkbox","vs/base/browser/ui/iconLabel/iconLabel","vs/base/browser/ui/list/listView","vs/editor/browser/editorDom","vs/editor/common/config/fontInfo","vs/editor/browser/view/viewLayer","vs/editor/common/model/textModelSearch","vs/editor/common/modes/supports","vs/editor/common/modes/supports/richEditBrackets","vs/editor/common/standalone/standaloneEnums","vs/editor/common/viewLayout/lineDecorations","vs/editor/browser/viewParts/glyphMargin/glyphMargin","vs/editor/contrib/folding/foldingRanges","vs/editor/contrib/snippet/snippetParser","vs/base/browser/ui/inputbox/inputBox","vs/base/browser/ui/list/listWidget","vs/base/browser/ui/tree/abstractTree","vs/base/parts/quickopen/browser/quickOpenModel","vs/editor/browser/services/bulkEditService","vs/editor/common/model/tokensStore","vs/editor/common/controller/cursorMoveOperations","vs/editor/common/controller/cursorTypeOperations","vs/editor/common/controller/cursorWordOperations","vs/editor/common/viewModel/splitLinesCollection","vs/platform/clipboard/common/clipboardService","vs/editor/common/config/commonEditorConfig","vs/editor/browser/controller/coreCommands","vs/editor/contrib/parameterHints/provideSignatureHelp","vs/editor/browser/controller/mouseTarget","vs/editor/browser/widget/embeddedCodeEditorWidget","vs/editor/contrib/find/findModel","vs/editor/standalone/browser/quickOpen/editorQuickOpen","vs/platform/list/browser/listService","vs/platform/workspace/common/workspace","vs/editor/standalone/browser/simpleServices","vs/editor/contrib/snippet/snippetController2","vs/base/browser/iframe","vs/base/browser/ui/scrollbar/scrollbarState","vs/base/common/scrollable","vs/base/common/extpath","vs/base/common/glob","vs/base/common/uint","vs/base/common/marshalling","vs/base/browser/ui/scrollbar/abstractScrollbar","vs/base/common/worker/simpleWorker","vs/base/browser/ui/codiconLabel/codiconLabel","vs/css!vs/base/browser/ui/findinput/findInput","vs/editor/browser/config/elementSizeObserver","vs/editor/browser/viewParts/minimap/minimapCharSheet","vs/editor/browser/controller/textAreaState","vs/editor/browser/widget/diffNavigator","vs/editor/browser/controller/textAreaInput","vs/editor/common/editorAction","vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase","vs/editor/common/standalone/standaloneBase","vs/editor/common/view/overviewZoneManager","vs/editor/common/viewModel/prefixSumComputer","vs/editor/browser/viewParts/margin/margin","vs/editor/contrib/comment/blockCommentCommand","vs/editor/contrib/folding/syntaxRangeProvider","vs/editor/contrib/format/formattingEdit","vs/editor/contrib/gotoSymbol/link/clickLinkGesture","vs/editor/contrib/hover/hoverOperation","vs/editor/contrib/hover/hoverWidgets","vs/editor/contrib/smartSelect/bracketSelections","vs/editor/standalone/common/monarch/monarchCommon","vs/base/browser/ui/findinput/findInputCheckboxes","vs/base/browser/ui/menu/menu","vs/base/browser/ui/tree/objectTree","vs/base/common/keybindingLabels","vs/platform/files/common/files","vs/platform/instantiation/common/descriptors","vs/editor/common/services/markersDecorationService","vs/editor/common/commands/shiftCommand","vs/editor/common/controller/cursorDeleteOperations","vs/editor/common/controller/cursorMoveCommands","vs/editor/common/modes/textToHtmlTokenizer","vs/editor/common/viewModel/minimapTokensColorTracker","vs/editor/standalone/common/monarch/monarchLexer","vs/platform/keybinding/common/keybindingResolver","vs/platform/layout/browser/layoutService","vs/editor/common/services/editorWorkerServiceImpl","vs/platform/jsonschemas/common/jsonContributionRegistry","vs/editor/contrib/codelens/codelens","vs/editor/contrib/colorPicker/color","vs/editor/contrib/colorPicker/colorDetector","vs/editor/contrib/gotoSymbol/goToSymbol","vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode","vs/editor/contrib/wordOperations/wordOperations","vs/editor/browser/viewParts/lines/viewLine","vs/editor/browser/view/viewOutgoingEvents","vs/editor/browser/viewParts/lineNumbers/lineNumbers","vs/editor/browser/widget/diffEditorWidget","vs/editor/contrib/documentSymbols/outlineTree","vs/editor/contrib/find/findController","vs/editor/contrib/codeAction/codeActionCommands","vs/editor/contrib/gotoSymbol/peek/referencesController","vs/editor/contrib/gotoSymbol/goToCommands","vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition","vs/editor/contrib/gotoError/gotoError","vs/editor/standalone/browser/standaloneServices","vs/base/browser/ui/list/list","vs/base/browser/ui/list/splice","vs/base/common/diff/diffChange","vs/base/common/history","vs/base/browser/ui/tree/compressedObjectTreeModel","vs/base/browser/ui/scrollbar/scrollbarVisibilityController","vs/base/common/process","vs/base/browser/ui/list/rangeMap","vs/base/common/search","vs/base/browser/markdownRenderer","vs/base/browser/ui/list/rowCache","vs/base/browser/ui/scrollbar/horizontalScrollbar","vs/base/browser/ui/scrollbar/verticalScrollbar","vs/base/common/mime","vs/base/parts/quickopen/browser/quickOpenViewer","vs/base/parts/tree/browser/tree","vs/base/parts/tree/browser/treeDnd","vs/base/parts/tree/browser/treeModel","vs/base/parts/tree/browser/treeViewModel","vs/base/worker/defaultWorkerFactory","vs/css!vs/base/browser/ui/actionbar/actionbar","vs/css!vs/base/browser/ui/aria/aria","vs/css!vs/base/browser/ui/checkbox/checkbox","vs/css!vs/base/browser/ui/codiconLabel/codicon/codicon","vs/css!vs/base/browser/ui/codiconLabel/codicon/codicon-animations","vs/css!vs/base/browser/ui/contextview/contextview","vs/base/browser/ui/contextview/contextview","vs/css!vs/base/browser/ui/countBadge/countBadge","vs/base/browser/ui/countBadge/countBadge","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/list/list","vs/css!vs/base/browser/ui/menu/menu","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/parts/tree/browser/treeView","vs/css!vs/base/browser/ui/splitview/splitview","vs/base/browser/ui/splitview/splitview","vs/css!vs/base/browser/ui/tree/media/tree","vs/css!vs/base/parts/quickopen/browser/quickopen","vs/css!vs/base/parts/tree/browser/tree","vs/base/parts/tree/browser/treeImpl","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/bracketMatching/bracketMatching","vs/css!vs/editor/contrib/clipboard/clipboard","vs/css!vs/editor/contrib/codeAction/lightBulbWidget","vs/css!vs/editor/contrib/codelens/codelensWidget","vs/css!vs/editor/contrib/colorPicker/colorPicker","vs/css!vs/editor/contrib/dnd/dnd","vs/css!vs/editor/contrib/documentSymbols/media/outlineTree","vs/css!vs/editor/contrib/documentSymbols/media/symbol-icons","vs/css!vs/editor/contrib/find/findWidget","vs/css!vs/editor/contrib/folding/folding","vs/css!vs/editor/contrib/gotoError/media/gotoErrorWidget","vs/css!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition","vs/css!vs/editor/contrib/gotoSymbol/peek/referencesWidget","vs/css!vs/editor/contrib/hover/hover","vs/css!vs/editor/contrib/links/links","vs/css!vs/editor/contrib/message/messageController","vs/css!vs/editor/contrib/parameterHints/parameterHints","vs/css!vs/editor/contrib/peekView/media/peekViewWidget","vs/css!vs/editor/contrib/rename/renameInputField","vs/css!vs/editor/contrib/snippet/snippetSession","vs/css!vs/editor/contrib/suggest/media/suggest","vs/css!vs/editor/contrib/suggest/media/suggestStatusBar","vs/css!vs/editor/contrib/zoneWidget/zoneWidget","vs/css!vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp","vs/css!vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard","vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens","vs/css!vs/editor/standalone/browser/quickOpen/editorQuickOpen","vs/css!vs/editor/standalone/browser/quickOpen/gotoLine","vs/css!vs/editor/standalone/browser/quickOpen/quickOutline","vs/css!vs/editor/standalone/browser/standalone-tokens","vs/css!vs/platform/contextview/browser/contextMenuHandler","vs/editor/browser/config/charWidthReader","vs/editor/browser/services/abstractCodeEditorService","vs/editor/browser/viewParts/minimap/minimapCharRenderer","vs/editor/browser/viewParts/minimap/minimapPreBaked","vs/editor/browser/viewParts/minimap/minimapCharRendererFactory","vs/editor/common/commands/trimTrailingWhitespaceCommand","vs/editor/common/core/rgba","vs/editor/common/commands/surroundSelectionCommand","vs/editor/common/diff/diffComputer","vs/editor/common/model/editStack","vs/editor/common/model/indentationGuesser","vs/editor/common/model/intervalTree","vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase","vs/editor/common/model/textModelEvents","vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer","vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder","vs/editor/common/modes/abstractMode","vs/editor/common/modes/languageSelector","vs/editor/common/modes/linkComputer","vs/editor/common/modes/supports/characterPair","vs/editor/common/modes/supports/indentRules","vs/editor/common/modes/supports/inplaceReplaceSupport","vs/editor/common/modes/supports/onEnter","vs/editor/common/modes/supports/electricCharacter","vs/editor/common/modes/supports/tokenization","vs/editor/common/modes/tokenizationRegistry","vs/editor/browser/viewParts/lines/rangeUtil","vs/editor/common/view/viewContext","vs/editor/common/view/viewEventDispatcher","vs/editor/common/viewLayout/linesLayout","vs/editor/common/viewLayout/viewLinesViewportData","vs/editor/common/model/mirrorTextModel","vs/editor/common/services/editorSimpleWorker","vs/editor/browser/viewParts/contentWidgets/contentWidgets","vs/editor/browser/viewParts/decorations/decorations","vs/editor/browser/viewParts/linesDecorations/linesDecorations","vs/editor/browser/viewParts/marginDecorations/marginDecorations","vs/editor/browser/viewParts/overlayWidgets/overlayWidgets","vs/editor/browser/viewParts/overviewRuler/overviewRuler","vs/editor/browser/viewParts/viewZones/viewZones","vs/editor/common/viewLayout/viewLayout","vs/editor/contrib/caretOperations/moveCaretCommand","vs/editor/contrib/colorPicker/colorPickerModel","vs/editor/contrib/comment/lineCommentCommand","vs/editor/contrib/dnd/dragAndDropCommand","vs/editor/contrib/find/findState","vs/editor/contrib/find/replaceAllCommand","vs/editor/contrib/find/replacePattern","vs/editor/contrib/folding/foldingModel","vs/editor/contrib/folding/hiddenRangeModel","vs/editor/contrib/folding/intializingRangeProvider","vs/editor/contrib/inPlaceReplace/inPlaceReplaceCommand","vs/editor/contrib/indentation/indentUtils","vs/editor/contrib/linesOperations/copyLinesCommand","vs/editor/contrib/linesOperations/sortLinesCommand","vs/editor/contrib/smartSelect/wordSelections","vs/editor/contrib/suggest/completionModel","vs/editor/contrib/suggest/suggestCommitCharacters","vs/editor/contrib/suggest/suggestRangeHighlighter","vs/editor/contrib/suggest/wordDistance","vs/editor/standalone/common/monarch/monarchCompile","vs/nls!vs/base/browser/ui/actionbar/actionbar","vs/nls!vs/base/browser/ui/aria/aria","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/inputbox/inputBox","vs/base/browser/ui/findinput/findInput","vs/base/browser/ui/findinput/replaceInput","vs/nls!vs/base/browser/ui/keybindingLabel/keybindingLabel","vs/nls!vs/base/browser/ui/list/listWidget","vs/nls!vs/base/browser/ui/menu/menu","vs/base/browser/contextmenu","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/keybindingLabels","vs/base/browser/ui/keybindingLabel/keybindingLabel","vs/nls!vs/base/common/severity","vs/nls!vs/base/parts/quickopen/browser/quickOpenModel","vs/nls!vs/base/parts/quickopen/browser/quickOpenWidget","vs/base/parts/quickopen/browser/quickOpenWidget","vs/nls!vs/editor/browser/controller/coreCommands","vs/nls!vs/editor/browser/controller/textAreaHandler","vs/nls!vs/editor/browser/widget/codeEditorWidget","vs/nls!vs/editor/browser/widget/diffEditorWidget","vs/nls!vs/editor/browser/widget/diffReview","vs/nls!vs/editor/browser/widget/inlineDiffMargin","vs/editor/browser/widget/inlineDiffMargin","vs/nls!vs/editor/common/config/commonEditorConfig","vs/nls!vs/editor/common/config/editorOptions","vs/editor/common/viewModel/viewModelDecorations","vs/nls!vs/editor/common/modes/modesRegistry","vs/nls!vs/editor/common/standaloneStrings","vs/nls!vs/editor/common/view/editorColorRegistry","vs/nls!vs/editor/contrib/bracketMatching/bracketMatching","vs/nls!vs/editor/contrib/caretOperations/caretOperations","vs/nls!vs/editor/contrib/caretOperations/transpose","vs/nls!vs/editor/contrib/clipboard/clipboard","vs/nls!vs/editor/contrib/codeAction/codeActionCommands","vs/nls!vs/editor/contrib/codeAction/lightBulbWidget","vs/nls!vs/editor/contrib/comment/comment","vs/nls!vs/editor/contrib/contextmenu/contextmenu","vs/nls!vs/editor/contrib/cursorUndo/cursorUndo","vs/nls!vs/editor/contrib/documentSymbols/outlineTree","vs/nls!vs/editor/contrib/find/findController","vs/nls!vs/editor/contrib/find/findWidget","vs/nls!vs/editor/contrib/folding/folding","vs/nls!vs/editor/contrib/fontZoom/fontZoom","vs/nls!vs/editor/contrib/format/format","vs/nls!vs/editor/contrib/format/formatActions","vs/nls!vs/editor/contrib/gotoError/gotoError","vs/nls!vs/editor/contrib/gotoError/gotoErrorWidget","vs/nls!vs/editor/contrib/gotoSymbol/goToCommands","vs/nls!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition","vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesController","vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesTree","vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesWidget","vs/nls!vs/editor/contrib/gotoSymbol/referencesModel","vs/nls!vs/editor/contrib/gotoSymbol/symbolNavigation","vs/nls!vs/editor/contrib/hover/hover","vs/nls!vs/editor/contrib/hover/modesContentHover","vs/nls!vs/editor/contrib/inPlaceReplace/inPlaceReplace","vs/nls!vs/editor/contrib/linesOperations/linesOperations","vs/nls!vs/editor/contrib/links/links","vs/nls!vs/editor/contrib/message/messageController","vs/nls!vs/editor/contrib/multicursor/multicursor","vs/nls!vs/editor/contrib/parameterHints/parameterHints","vs/nls!vs/editor/contrib/parameterHints/parameterHintsWidget","vs/nls!vs/editor/contrib/peekView/peekView","vs/nls!vs/editor/contrib/rename/rename","vs/nls!vs/editor/contrib/rename/renameInputField","vs/nls!vs/editor/contrib/smartSelect/smartSelect","vs/nls!vs/editor/contrib/snippet/snippetVariables","vs/nls!vs/editor/contrib/suggest/suggestController","vs/nls!vs/editor/contrib/suggest/suggestWidget","vs/nls!vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode","vs/nls!vs/editor/contrib/tokenization/tokenization","vs/nls!vs/editor/contrib/wordHighlighter/wordHighlighter","vs/nls!vs/platform/configuration/common/configurationRegistry","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/theme/common/colorRegistry","vs/platform/contextkey/common/contextkeys","vs/platform/editor/common/editor","vs/platform/extensions/common/extensions","vs/platform/instantiation/common/graph","vs/editor/common/modes/languageFeatureRegistry","vs/editor/common/model/textModelTokens","vs/editor/common/controller/cursorColumnSelection","vs/editor/common/controller/oneCursor","vs/editor/common/controller/cursorCollection","vs/editor/common/controller/cursor","vs/editor/common/viewModel/monospaceLineBreaksComputer","vs/editor/common/viewModel/viewModelImpl","vs/editor/contrib/documentSymbols/outlineModel","vs/editor/contrib/folding/foldingDecorations","vs/editor/contrib/folding/indentRangeProvider","vs/editor/contrib/linesOperations/moveLinesCommand","vs/editor/contrib/zoneWidget/zoneWidget","vs/editor/standalone/browser/colorizer","vs/editor/contrib/links/getLinks","vs/editor/contrib/quickOpen/quickOpen","vs/editor/contrib/suggest/suggestAlternatives","vs/editor/contrib/suggest/wordContextKey","vs/platform/actions/common/menuService","vs/platform/dialogs/common/dialogs","vs/platform/instantiation/common/instantiationService","vs/platform/keybinding/common/abstractKeybindingService","vs/platform/keybinding/common/baseResolvedKeybinding","vs/platform/keybinding/common/resolvedKeybindingItem","vs/platform/keybinding/common/usLayoutResolvedKeybinding","vs/platform/contextview/browser/contextViewService","vs/editor/common/services/webWorker","vs/platform/markers/common/markerService","vs/editor/browser/services/openerService","vs/editor/contrib/hover/modesGlyphHover","vs/editor/common/services/getIconClasses","vs/editor/browser/view/domLineBreaksComputer","vs/editor/browser/view/viewOverlays","vs/editor/browser/viewParts/viewCursors/viewCursor","vs/editor/common/services/languagesRegistry","vs/editor/common/services/modeServiceImpl","vs/platform/accessibility/common/accessibilityService","vs/platform/configuration/common/configurationModels","vs/platform/contextkey/browser/contextKeyService","vs/platform/browser/contextScopedHistoryWidget","vs/editor/contrib/suggest/suggestMemory","vs/editor/browser/core/keybindingCancellation","vs/editor/browser/view/viewController","vs/editor/contrib/caretOperations/caretOperations","vs/editor/contrib/caretOperations/transpose","vs/editor/contrib/clipboard/clipboard","vs/editor/contrib/codeAction/codeActionMenu","vs/editor/contrib/codeAction/codeActionModel","vs/editor/contrib/codelens/codeLensCache","vs/editor/contrib/comment/comment","vs/editor/contrib/contextmenu/contextmenu","vs/editor/contrib/cursorUndo/cursorUndo","vs/editor/contrib/dnd/dnd","vs/editor/contrib/fontZoom/fontZoom","vs/editor/contrib/format/format","vs/editor/contrib/format/formatActions","vs/editor/contrib/gotoSymbol/symbolNavigation","vs/editor/contrib/hover/getHover","vs/editor/contrib/linesOperations/linesOperations","vs/editor/contrib/parameterHints/parameterHintsModel","vs/editor/contrib/smartSelect/smartSelect","vs/editor/contrib/tokenization/tokenization","vs/editor/contrib/wordPartOperations/wordPartOperations","vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard","vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast","vs/editor/standalone/browser/quickOpen/quickOpenEditorWidget","vs/platform/contextview/browser/contextMenuHandler","vs/editor/browser/services/codeEditorServiceImpl","vs/editor/browser/viewParts/editorScrollbar/editorScrollbar","vs/editor/browser/controller/mouseHandler","vs/editor/browser/controller/pointerHandler","vs/editor/browser/viewParts/lines/viewLines","vs/editor/browser/viewParts/minimap/minimap","vs/editor/browser/viewParts/scrollDecoration/scrollDecoration","vs/editor/browser/viewParts/selections/selections","vs/editor/common/services/modelServiceImpl","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/browser/view/viewImpl","vs/editor/browser/widget/diffReview","vs/editor/common/services/markerDecorationsServiceImpl","vs/editor/contrib/bracketMatching/bracketMatching","vs/editor/contrib/codeAction/lightBulbWidget","vs/editor/contrib/codelens/codelensWidget","vs/editor/contrib/codelens/codelensController","vs/editor/contrib/colorPicker/colorPickerWidget","vs/editor/contrib/find/findDecorations","vs/editor/contrib/find/findOptionsWidget","vs/editor/contrib/find/findWidget","vs/editor/contrib/folding/folding","vs/editor/contrib/gotoSymbol/peek/referencesTree","vs/editor/contrib/inPlaceReplace/inPlaceReplace","vs/editor/contrib/links/links","vs/editor/contrib/codeAction/codeActionUi","vs/editor/contrib/codeAction/codeActionContributions","vs/editor/contrib/multicursor/multicursor","vs/editor/contrib/parameterHints/parameterHintsWidget","vs/editor/contrib/parameterHints/parameterHints","vs/editor/contrib/rename/renameInputField","vs/editor/contrib/rename/rename","vs/editor/contrib/suggest/suggestWidget","vs/editor/contrib/wordHighlighter/wordHighlighter","vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp","vs/editor/standalone/browser/inspectTokens/inspectTokens","vs/editor/standalone/browser/quickOpen/gotoLine","vs/editor/standalone/browser/quickOpen/quickCommand","vs/editor/standalone/browser/quickOpen/quickOutline","vs/editor/standalone/browser/standaloneCodeServiceImpl","vs/editor/standalone/common/themes","vs/editor/standalone/browser/standaloneThemeServiceImpl","vs/platform/contextview/browser/contextMenuService","vs/editor/contrib/gotoSymbol/peek/referencesWidget","vs/editor/standalone/browser/referenceSearch/standaloneReferenceSearch","vs/platform/severityIcon/common/severityIcon","vs/editor/contrib/gotoError/gotoErrorWidget","vs/editor/contrib/hover/modesContentHover","vs/editor/contrib/hover/hover","vs/editor/standalone/browser/standaloneCodeEditor","vs/editor/standalone/browser/standaloneEditor","vs/editor/standalone/browser/standaloneLanguages","vs/editor/editor.api","vs/platform/workspaces/common/workspaces","vs/editor/contrib/snippet/snippetVariables","vs/editor/contrib/snippet/snippetSession","vs/editor/contrib/suggest/suggestModel","vs/editor/contrib/suggest/suggestController","vs/editor/editor.all","vs/base/common/marked/marked","vs/base/common/insane/insane","vs/editor/common/standalone/promise-polyfill/polyfill","vs/editor/edcore.main"]; var __M = function(deps) { var result = []; for (var i = 0, len = deps.length; i < len; i++) { result[i] = __m[deps[i]]; } return result; }; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- * Please make sure to make edits in the .ts file at https://github.com/Microsoft/vscode-loader/ *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------*/ 'use strict'; var CSSLoaderPlugin; (function (CSSLoaderPlugin) { /** * Known issue: * - In IE there is no way to know if the CSS file loaded successfully or not. */ var BrowserCSSLoader = /** @class */ (function () { function BrowserCSSLoader() { this._pendingLoads = 0; } BrowserCSSLoader.prototype.attachListeners = function (name, linkNode, callback, errorback) { var unbind = function () { linkNode.removeEventListener('load', loadEventListener); linkNode.removeEventListener('error', errorEventListener); }; var loadEventListener = function (e) { unbind(); callback(); }; var errorEventListener = function (e) { unbind(); errorback(e); }; linkNode.addEventListener('load', loadEventListener); linkNode.addEventListener('error', errorEventListener); }; BrowserCSSLoader.prototype._onLoad = function (name, callback) { this._pendingLoads--; callback(); }; BrowserCSSLoader.prototype._onLoadError = function (name, errorback, err) { this._pendingLoads--; errorback(err); }; BrowserCSSLoader.prototype._insertLinkNode = function (linkNode) { this._pendingLoads++; var head = document.head || document.getElementsByTagName('head')[0]; var other = head.getElementsByTagName('link') || document.head.getElementsByTagName('script'); if (other.length > 0) { head.insertBefore(linkNode, other[other.length - 1]); } else { head.appendChild(linkNode); } }; BrowserCSSLoader.prototype.createLinkTag = function (name, cssUrl, externalCallback, externalErrorback) { var _this = this; var linkNode = document.createElement('link'); linkNode.setAttribute('rel', 'stylesheet'); linkNode.setAttribute('type', 'text/css'); linkNode.setAttribute('data-name', name); var callback = function () { return _this._onLoad(name, externalCallback); }; var errorback = function (err) { return _this._onLoadError(name, externalErrorback, err); }; this.attachListeners(name, linkNode, callback, errorback); linkNode.setAttribute('href', cssUrl); return linkNode; }; BrowserCSSLoader.prototype._linkTagExists = function (name, cssUrl) { var i, len, nameAttr, hrefAttr, links = document.getElementsByTagName('link'); for (i = 0, len = links.length; i < len; i++) { nameAttr = links[i].getAttribute('data-name'); hrefAttr = links[i].getAttribute('href'); if (nameAttr === name || hrefAttr === cssUrl) { return true; } } return false; }; BrowserCSSLoader.prototype.load = function (name, cssUrl, externalCallback, externalErrorback) { if (this._linkTagExists(name, cssUrl)) { externalCallback(); return; } var linkNode = this.createLinkTag(name, cssUrl, externalCallback, externalErrorback); this._insertLinkNode(linkNode); }; return BrowserCSSLoader; }()); // ------------------------------ Finally, the plugin var CSSPlugin = /** @class */ (function () { function CSSPlugin() { this._cssLoader = new BrowserCSSLoader(); } CSSPlugin.prototype.load = function (name, req, load) { 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 NLSLoaderPlugin; (function (NLSLoaderPlugin) { var Environment = /** @class */ (function () { function Environment() { this._detected = false; this._isPseudo = false; } Object.defineProperty(Environment.prototype, "isPseudo", { get: function () { this._detect(); return this._isPseudo; }, enumerable: true, configurable: true }); Environment.prototype._detect = function () { if (this._detected) { return; } this._detected = true; this._isPseudo = (typeof document !== 'undefined' && document.location && document.location.hash.indexOf('pseudo=true') >= 0); }; return Environment; }()); function _format(message, args, env) { var result; if (args.length === 0) { result = message; } else { result = message.replace(/\{(\d+)\}/g, function (match, rest) { var index = rest[0]; var arg = args[index]; var result = match; if (typeof arg === 'string') { result = arg; } else if (typeof arg === 'number' || typeof arg === 'boolean' || arg === void 0 || arg === null) { result = String(arg); } return result; }); } if (env.isPseudo) { // FF3B and FF3D is the Unicode zenkaku representation for [ and ] result = '\uFF3B' + result.replace(/[aouei]/g, '$&$&') + '\uFF3D'; } return result; } function findLanguageForModule(config, name) { var result = config[name]; if (result) return result; result = config['*']; if (result) return result; return null; } function localize(env, data, message) { var args = []; for (var _i = 3; _i < arguments.length; _i++) { args[_i - 3] = arguments[_i]; } return _format(message, args, env); } function createScopedLocalize(scope, env) { return function (idx, defaultValue) { var restArgs = Array.prototype.slice.call(arguments, 2); return _format(scope[idx], restArgs, env); }; } var NLSPlugin = /** @class */ (function () { function NLSPlugin(env) { var _this = this; this._env = env; this.localize = function (data, message) { var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } return localize.apply(void 0, [_this._env, data, message].concat(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 = {})); define(__m[98/*vs/base/browser/dnd*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // 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: 'text/plain' }; var DragAndDropData = /** @class */ (function () { function DragAndDropData(data) { this.data = data; } DragAndDropData.prototype.update = function () { // noop }; DragAndDropData.prototype.getData = function () { return this.data; }; return DragAndDropData; }()); 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[174/*vs/base/browser/iframe*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var hasDifferentOriginAncestorFlag = false; var sameOriginWindowChainCache = null; function getParentWindowIfSameOrigin(w) { if (!w.parent || w.parent === w) { return null; } // Cannot really tell if we have access to the parent window unless we try to access something in it try { var location_1 = w.location; var parentLocation = w.parent.location; if (location_1.protocol !== parentLocation.protocol || location_1.hostname !== parentLocation.hostname || location_1.port !== parentLocation.port) { hasDifferentOriginAncestorFlag = true; return null; } } catch (e) { hasDifferentOriginAncestorFlag = true; return null; } return w.parent; } function findIframeElementInParentWindow(parentWindow, childWindow) { var parentWindowIframes = parentWindow.document.getElementsByTagName('iframe'); var iframe; for (var i = 0, len = parentWindowIframes.length; i < len; i++) { iframe = parentWindowIframes[i]; if (iframe.contentWindow === childWindow) { return iframe; } } return null; } var IframeUtils = /** @class */ (function () { function IframeUtils() { } /** * Returns a chain of embedded windows with the same origin (which can be accessed programmatically). * Having a chain of length 1 might mean that the current execution environment is running outside of an iframe or inside an iframe embedded in a window with a different origin. * To distinguish if at one point the current execution environment is running inside a window with a different origin, see hasDifferentOriginAncestor() */ IframeUtils.getSameOriginWindowChain = function () { if (!sameOriginWindowChainCache) { sameOriginWindowChainCache = []; var w = window; var parent_1; do { parent_1 = getParentWindowIfSameOrigin(w); if (parent_1) { sameOriginWindowChainCache.push({ window: w, iframeElement: findIframeElementInParentWindow(parent_1, w) }); } else { sameOriginWindowChainCache.push({ window: w, iframeElement: null }); } w = parent_1; } while (w); } return sameOriginWindowChainCache.slice(0); }; /** * Returns true if the current execution environment is chained in a list of iframes which at one point ends in a window with a different origin. * Returns false if the current execution environment is not running inside an iframe or if the entire chain of iframes have the same origin. */ IframeUtils.hasDifferentOriginAncestor = function () { if (!sameOriginWindowChainCache) { this.getSameOriginWindowChain(); } return hasDifferentOriginAncestorFlag; }; /** * Returns the position of `childWindow` relative to `ancestorWindow` */ IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow = function (childWindow, ancestorWindow) { if (!ancestorWindow || childWindow === ancestorWindow) { return { top: 0, left: 0 }; } var top = 0, left = 0; var windowChain = this.getSameOriginWindowChain(); for (var _i = 0, windowChain_1 = windowChain; _i < windowChain_1.length; _i++) { var windowChainEl = windowChain_1[_i]; if (windowChainEl.window === ancestorWindow) { break; } if (!windowChainEl.iframeElement) { break; } var boundingRect = windowChainEl.iframeElement.getBoundingClientRect(); top += boundingRect.top; left += boundingRect.left; } return { top: top, left: left }; }; return IframeUtils; }()); exports.IframeUtils = IframeUtils; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); define(__m[239/*vs/base/browser/ui/list/list*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ListAriaRootRole; (function (ListAriaRootRole) { /** default tree structure role */ ListAriaRootRole["TREE"] = "tree"; /** role='tree' can interfere with screenreaders reading nested elements inside the tree row. Use FORM in that case. */ ListAriaRootRole["FORM"] = "form"; })(ListAriaRootRole = exports.ListAriaRootRole || (exports.ListAriaRootRole = {})); var ListError = /** @class */ (function (_super) { __extends(ListError, _super); function ListError(user, message) { return _super.call(this, "ListError [" + user + "] " + message) || this; } return ListError; }(Error)); exports.ListError = ListError; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[240/*vs/base/browser/ui/list/splice*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CombinedSpliceable = /** @class */ (function () { function CombinedSpliceable(spliceables) { this.spliceables = spliceables; } CombinedSpliceable.prototype.splice = function (start, deleteCount, elements) { this.spliceables.forEach(function (s) { return s.splice(start, deleteCount, elements); }); }; return CombinedSpliceable; }()); exports.CombinedSpliceable = CombinedSpliceable; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[175/*vs/base/browser/ui/scrollbar/scrollbarState*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * The minimal size of the slider (such that it can still be clickable) -- it is artificially enlarged. */ var MINIMUM_SLIDER_SIZE = 20; var ScrollbarState = /** @class */ (function () { function ScrollbarState(arrowSize, scrollbarSize, oppositeScrollbarSize, visibleSize, scrollSize, scrollPosition) { this._scrollbarSize = Math.round(scrollbarSize); this._oppositeScrollbarSize = Math.round(oppositeScrollbarSize); this._arrowSize = Math.round(arrowSize); this._visibleSize = visibleSize; this._scrollSize = scrollSize; this._scrollPosition = scrollPosition; this._computedAvailableSize = 0; this._computedIsNeeded = false; this._computedSliderSize = 0; this._computedSliderRatio = 0; this._computedSliderPosition = 0; this._refreshComputedValues(); } ScrollbarState.prototype.clone = function () { return new ScrollbarState(this._arrowSize, this._scrollbarSize, this._oppositeScrollbarSize, this._visibleSize, this._scrollSize, this._scrollPosition); }; ScrollbarState.prototype.setVisibleSize = function (visibleSize) { var iVisibleSize = Math.round(visibleSize); if (this._visibleSize !== iVisibleSize) { this._visibleSize = iVisibleSize; this._refreshComputedValues(); return true; } return false; }; ScrollbarState.prototype.setScrollSize = function (scrollSize) { var iScrollSize = Math.round(scrollSize); if (this._scrollSize !== iScrollSize) { this._scrollSize = iScrollSize; this._refreshComputedValues(); return true; } return false; }; ScrollbarState.prototype.setScrollPosition = function (scrollPosition) { var iScrollPosition = Math.round(scrollPosition); if (this._scrollPosition !== iScrollPosition) { this._scrollPosition = iScrollPosition; this._refreshComputedValues(); return true; } return false; }; ScrollbarState._computeValues = function (oppositeScrollbarSize, arrowSize, visibleSize, scrollSize, scrollPosition) { var computedAvailableSize = Math.max(0, visibleSize - oppositeScrollbarSize); var computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * arrowSize); var computedIsNeeded = (scrollSize > 0 && scrollSize > visibleSize); if (!computedIsNeeded) { // There is no need for a slider return { computedAvailableSize: Math.round(computedAvailableSize), computedIsNeeded: computedIsNeeded, computedSliderSize: Math.round(computedRepresentableSize), computedSliderRatio: 0, computedSliderPosition: 0, }; } // We must artificially increase the size of the slider if needed, since the slider would be too small to grab with the mouse otherwise var computedSliderSize = Math.round(Math.max(MINIMUM_SLIDER_SIZE, Math.floor(visibleSize * computedRepresentableSize / scrollSize))); // The slider can move from 0 to `computedRepresentableSize` - `computedSliderSize` // in the same way `scrollPosition` can move from 0 to `scrollSize` - `visibleSize`. var computedSliderRatio = (computedRepresentableSize - computedSliderSize) / (scrollSize - visibleSize); var computedSliderPosition = (scrollPosition * computedSliderRatio); return { computedAvailableSize: Math.round(computedAvailableSize), computedIsNeeded: computedIsNeeded, computedSliderSize: Math.round(computedSliderSize), computedSliderRatio: computedSliderRatio, computedSliderPosition: Math.round(computedSliderPosition), }; }; ScrollbarState.prototype._refreshComputedValues = function () { var r = ScrollbarState._computeValues(this._oppositeScrollbarSize, this._arrowSize, this._visibleSize, this._scrollSize, this._scrollPosition); this._computedAvailableSize = r.computedAvailableSize; this._computedIsNeeded = r.computedIsNeeded; this._computedSliderSize = r.computedSliderSize; this._computedSliderRatio = r.computedSliderRatio; this._computedSliderPosition = r.computedSliderPosition; }; ScrollbarState.prototype.getArrowSize = function () { return this._arrowSize; }; ScrollbarState.prototype.getScrollPosition = function () { return this._scrollPosition; }; ScrollbarState.prototype.getRectangleLargeSize = function () { return this._computedAvailableSize; }; ScrollbarState.prototype.getRectangleSmallSize = function () { return this._scrollbarSize; }; ScrollbarState.prototype.isNeeded = function () { return this._computedIsNeeded; }; ScrollbarState.prototype.getSliderSize = function () { return this._computedSliderSize; }; ScrollbarState.prototype.getSliderPosition = function () { return this._computedSliderPosition; }; /** * Compute a desired `scrollPosition` such that `offset` ends up in the center of the slider. * `offset` is based on the same coordinate system as the `sliderPosition`. */ ScrollbarState.prototype.getDesiredScrollPositionFromOffset = function (offset) { if (!this._computedIsNeeded) { // no need for a slider return 0; } var desiredSliderPosition = offset - this._arrowSize - this._computedSliderSize / 2; return Math.round(desiredSliderPosition / this._computedSliderRatio); }; /** * Compute a desired `scrollPosition` such that the slider moves by `delta`. */ ScrollbarState.prototype.getDesiredScrollPositionFromDelta = function (delta) { if (!this._computedIsNeeded) { // no need for a slider return 0; } var desiredSliderPosition = this._computedSliderPosition + delta; return Math.round(desiredSliderPosition / this._computedSliderRatio); }; return ScrollbarState; }()); exports.ScrollbarState = ScrollbarState; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[99/*vs/base/browser/ui/tree/tree*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var TreeError = /** @class */ (function (_super) { __extends(TreeError, _super); function TreeError(user, message) { return _super.call(this, "TreeError [" + user + "] " + message) || this; } return TreeError; }(Error)); exports.TreeError = TreeError; var WeakMapper = /** @class */ (function () { function WeakMapper(fn) { this.fn = fn; this._map = new WeakMap(); } WeakMapper.prototype.map = function (key) { var result = this._map.get(key); if (!result) { result = this.fn(key); this._map.set(key, result); } return result; }; return WeakMapper; }()); exports.WeakMapper = WeakMapper; }); define(__m[19/*vs/base/common/arrays*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Returns the last element of an array. * @param array The array. * @param n Which element from the end (default is zero). */ function tail(array, n) { if (n === void 0) { n = 0; } return array[array.length - (1 + n)]; } exports.tail = tail; function tail2(arr) { if (arr.length === 0) { throw new Error('Invalid tail call'); } return [arr.slice(0, arr.length - 1), arr[arr.length - 1]]; } exports.tail2 = tail2; function equals(one, other, itemEquals) { if (itemEquals === void 0) { itemEquals = function (a, b) { return a === b; }; } if (one === other) { return true; } if (!one || !other) { return false; } if (one.length !== other.length) { return false; } for (var i = 0, len = one.length; i < len; i++) { if (!itemEquals(one[i], other[i])) { return false; } } return true; } exports.equals = equals; function binarySearch(array, key, comparator) { var low = 0, high = array.length - 1; while (low <= high) { var mid = ((low + high) / 2) | 0; var comp = comparator(array[mid], key); if (comp < 0) { low = mid + 1; } else if (comp > 0) { high = mid - 1; } else { return mid; } } return -(low + 1); } exports.binarySearch = binarySearch; /** * Takes a sorted array and a function p. The array is sorted in such a way that all elements where p(x) is false * are located before all elements where p(x) is true. * @returns the least x for which p(x) is true or array.length if no element fullfills the given function. */ function findFirstInSorted(array, p) { var low = 0, high = array.length; if (high === 0) { return 0; // no children } while (low < high) { var mid = Math.floor((low + high) / 2); if (p(array[mid])) { high = mid; } else { low = mid + 1; } } return low; } exports.findFirstInSorted = findFirstInSorted; /** * Like `Array#sort` but always stable. Usually runs a little slower `than Array#sort` * so only use this when actually needing stable sort. */ function mergeSort(data, compare) { _sort(data, compare, 0, data.length - 1, []); return data; } exports.mergeSort = mergeSort; function _merge(a, compare, lo, mid, hi, aux) { var leftIdx = lo, rightIdx = mid + 1; for (var i = lo; i <= hi; i++) { aux[i] = a[i]; } for (var i = lo; i <= hi; i++) { if (leftIdx > mid) { // left side consumed a[i] = aux[rightIdx++]; } else if (rightIdx > hi) { // right side consumed a[i] = aux[leftIdx++]; } else if (compare(aux[rightIdx], aux[leftIdx]) < 0) { // right element is less -> comes first a[i] = aux[rightIdx++]; } else { // left element comes first (less or equal) a[i] = aux[leftIdx++]; } } } function _sort(a, compare, lo, hi, aux) { if (hi <= lo) { return; } var mid = lo + ((hi - lo) / 2) | 0; _sort(a, compare, lo, mid, aux); _sort(a, compare, mid + 1, hi, aux); if (compare(a[mid], a[mid + 1]) <= 0) { // left and right are sorted and if the last-left element is less // or equals than the first-right element there is nothing else // to do return; } _merge(a, compare, lo, mid, hi, aux); } function groupBy(data, compare) { var result = []; var currentGroup = undefined; for (var _i = 0, _a = mergeSort(data.slice(0), compare); _i < _a.length; _i++) { var element = _a[_i]; if (!currentGroup || compare(currentGroup[0], element) !== 0) { currentGroup = [element]; result.push(currentGroup); } else { currentGroup.push(element); } } return result; } exports.groupBy = groupBy; /** * @returns New array with all falsy values removed. The original array IS NOT modified. */ function coalesce(array) { return array.filter(function (e) { return !!e; }); } exports.coalesce = coalesce; /** * @returns false if the provided object is an array and not empty. */ function isFalsyOrEmpty(obj) { return !Array.isArray(obj) || obj.length === 0; } exports.isFalsyOrEmpty = isFalsyOrEmpty; function isNonEmptyArray(obj) { return Array.isArray(obj) && obj.length > 0; } exports.isNonEmptyArray = isNonEmptyArray; /** * Removes duplicates from the given array. The optional keyFn allows to specify * how elements are checked for equalness by returning a unique string for each. */ function distinct(array, keyFn) { if (!keyFn) { return array.filter(function (element, position) { return array.indexOf(element) === position; }); } var seen = Object.create(null); return array.filter(function (elem) { var key = keyFn(elem); if (seen[key]) { return false; } seen[key] = true; return true; }); } exports.distinct = distinct; function distinctES6(array) { var seen = new Set(); return array.filter(function (element) { if (seen.has(element)) { return false; } seen.add(element); return true; }); } exports.distinctES6 = distinctES6; function fromSet(set) { var result = []; set.forEach(function (o) { return result.push(o); }); return result; } exports.fromSet = fromSet; function firstIndex(array, fn) { for (var i = 0; i < array.length; i++) { var element = array[i]; if (fn(element)) { return i; } } return -1; } exports.firstIndex = firstIndex; function first(array, fn, notFoundValue) { if (notFoundValue === void 0) { notFoundValue = undefined; } var index = firstIndex(array, fn); return index < 0 ? notFoundValue : array[index]; } exports.first = first; function firstOrDefault(array, notFoundValue) { return array.length > 0 ? array[0] : notFoundValue; } exports.firstOrDefault = firstOrDefault; function flatten(arr) { var _a; return (_a = []).concat.apply(_a, arr); } exports.flatten = flatten; function range(arg, to) { var from = typeof to === 'number' ? arg : 0; if (typeof to === 'number') { from = arg; } else { from = 0; to = arg; } var result = []; if (from <= to) { for (var i = from; i < to; i++) { result.push(i); } } else { for (var i = from; i > to; i--) { result.push(i); } } return result; } exports.range = range; /** * Insert `insertArr` inside `target` at `insertIndex`. * Please don't touch unless you understand https://jsperf.com/inserting-an-array-within-an-array */ function arrayInsert(target, insertIndex, insertArr) { var before = target.slice(0, insertIndex); var after = target.slice(insertIndex); return before.concat(insertArr, after); } exports.arrayInsert = arrayInsert; /** * Pushes an element to the start of the array, if found. */ function pushToStart(arr, value) { var index = arr.indexOf(value); if (index > -1) { arr.splice(index, 1); arr.unshift(value); } } exports.pushToStart = pushToStart; /** * Pushes an element to the end of the array, if found. */ function pushToEnd(arr, value) { var index = arr.indexOf(value); if (index > -1) { arr.splice(index, 1); arr.push(value); } } exports.pushToEnd = pushToEnd; function find(arr, predicate) { for (var i = 0; i < arr.length; i++) { var element = arr[i]; if (predicate(element, i, arr)) { return element; } } return undefined; } exports.find = find; function asArray(x) { return Array.isArray(x) ? x : [x]; } exports.asArray = asArray; }); /*--------------------------------------------------------------------------------------------- * 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/base/common/assert*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Throws an error with the provided message if the provided value does not evaluate to a true Javascript value. */ function ok(value, message) { if (!value) { throw new Error(message ? 'Assertion failed (' + message + ')' : 'Assertion Failed'); } } exports.ok = ok; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[100/*vs/base/common/codicons*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var escapeCodiconsRegex = /(\\)?\$\([a-z0-9\-]+?(?:~[a-z0-9\-]*?)?\)/gi; function escapeCodicons(text) { return text.replace(escapeCodiconsRegex, function (match, escaped) { return escaped ? match : "\\" + match; }); } exports.escapeCodicons = escapeCodicons; var markdownEscapedCodiconsRegex = /\\\$\([a-z0-9\-]+?(?:~[a-z0-9\-]*?)?\)/gi; function markdownEscapeEscapedCodicons(text) { // Need to add an extra \ for escaping in markdown return text.replace(markdownEscapedCodiconsRegex, function (match) { return "\\" + match; }); } exports.markdownEscapeEscapedCodicons = markdownEscapeEscapedCodicons; var renderCodiconsRegex = /(\\)?\$\((([a-z0-9\-]+?)(?:~([a-z0-9\-]*?))?)\)/gi; function renderCodicons(text) { return text.replace(renderCodiconsRegex, function (_, escaped, codicon, name, animation) { return escaped ? "$(" + codicon + ")" : ""; }); } exports.renderCodicons = renderCodicons; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[87/*vs/base/common/collections*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Returns an array which contains all values that reside * in the given set. */ function values(from) { var result = []; for (var key in from) { if (hasOwnProperty.call(from, key)) { result.push(from[key]); } } return result; } exports.values = values; function first(from) { for (var key in from) { if (hasOwnProperty.call(from, key)) { return from[key]; } } return undefined; } exports.first = first; /** * Iterates over each entry in the provided set. The iterator allows * to remove elements and will stop when the callback returns {{false}}. */ function forEach(from, callback) { var _loop_1 = function (key) { if (hasOwnProperty.call(from, key)) { var result = callback({ key: key, value: from[key] }, function () { delete from[key]; }); if (result === false) { return { value: void 0 }; } } }; for (var key in from) { var state_1 = _loop_1(key); if (typeof state_1 === "object") return state_1.value; } } exports.forEach = forEach; var SetMap = /** @class */ (function () { function SetMap() { this.map = new Map(); } SetMap.prototype.add = function (key, value) { var values = this.map.get(key); if (!values) { values = new Set(); this.map.set(key, values); } values.add(value); }; SetMap.prototype.delete = function (key, value) { var values = this.map.get(key); if (!values) { return; } values.delete(value); if (values.size === 0) { this.map.delete(key); } }; SetMap.prototype.forEach = function (key, fn) { var values = this.map.get(key); if (!values) { return; } values.forEach(fn); }; return SetMap; }()); exports.SetMap = SetMap; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[27/*vs/base/common/color*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function roundFloat(number, decimalPoints) { var decimal = Math.pow(10, decimalPoints); return Math.round(number * decimal) / decimal; } var RGBA = /** @class */ (function () { function RGBA(r, g, b, a) { if (a === void 0) { a = 1; } this.r = Math.min(255, Math.max(0, r)) | 0; this.g = Math.min(255, Math.max(0, g)) | 0; this.b = Math.min(255, Math.max(0, b)) | 0; this.a = roundFloat(Math.max(Math.min(1, a), 0), 3); } RGBA.equals = function (a, b) { return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a; }; return RGBA; }()); exports.RGBA = RGBA; var HSLA = /** @class */ (function () { function HSLA(h, s, l, a) { this.h = Math.max(Math.min(360, h), 0) | 0; this.s = roundFloat(Math.max(Math.min(1, s), 0), 3); this.l = roundFloat(Math.max(Math.min(1, l), 0), 3); this.a = roundFloat(Math.max(Math.min(1, a), 0), 3); } HSLA.equals = function (a, b) { return a.h === b.h && a.s === b.s && a.l === b.l && a.a === b.a; }; /** * Converts an RGB color value to HSL. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes r, g, and b are contained in the set [0, 255] and * returns h in the set [0, 360], s, and l in the set [0, 1]. */ HSLA.fromRGBA = function (rgba) { var r = rgba.r / 255; var g = rgba.g / 255; var b = rgba.b / 255; var a = rgba.a; var max = Math.max(r, g, b); var min = Math.min(r, g, b); var h = 0; var s = 0; var l = (min + max) / 2; var chroma = max - min; if (chroma > 0) { s = Math.min((l <= 0.5 ? chroma / (2 * l) : chroma / (2 - (2 * l))), 1); switch (max) { case r: h = (g - b) / chroma + (g < b ? 6 : 0); break; case g: h = (b - r) / chroma + 2; break; case b: h = (r - g) / chroma + 4; break; } h *= 60; h = Math.round(h); } return new HSLA(h, s, l, a); }; HSLA._hue2rgb = function (p, q, t) { if (t < 0) { t += 1; } if (t > 1) { t -= 1; } if (t < 1 / 6) { return p + (q - p) * 6 * t; } if (t < 1 / 2) { return q; } if (t < 2 / 3) { return p + (q - p) * (2 / 3 - t) * 6; } return p; }; /** * Converts an HSL color value to RGB. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes h in the set [0, 360] s, and l are contained in the set [0, 1] and * returns r, g, and b in the set [0, 255]. */ HSLA.toRGBA = function (hsla) { var h = hsla.h / 360; var s = hsla.s, l = hsla.l, a = hsla.a; var r, g, b; if (s === 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = HSLA._hue2rgb(p, q, h + 1 / 3); g = HSLA._hue2rgb(p, q, h); b = HSLA._hue2rgb(p, q, h - 1 / 3); } return new RGBA(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a); }; return HSLA; }()); exports.HSLA = HSLA; var HSVA = /** @class */ (function () { function HSVA(h, s, v, a) { this.h = Math.max(Math.min(360, h), 0) | 0; this.s = roundFloat(Math.max(Math.min(1, s), 0), 3); this.v = roundFloat(Math.max(Math.min(1, v), 0), 3); this.a = roundFloat(Math.max(Math.min(1, a), 0), 3); } HSVA.equals = function (a, b) { return a.h === b.h && a.s === b.s && a.v === b.v && a.a === b.a; }; // from http://www.rapidtables.com/convert/color/rgb-to-hsv.htm HSVA.fromRGBA = function (rgba) { var r = rgba.r / 255; var g = rgba.g / 255; var b = rgba.b / 255; var cmax = Math.max(r, g, b); var cmin = Math.min(r, g, b); var delta = cmax - cmin; var s = cmax === 0 ? 0 : (delta / cmax); var m; if (delta === 0) { m = 0; } else if (cmax === r) { m = ((((g - b) / delta) % 6) + 6) % 6; } else if (cmax === g) { m = ((b - r) / delta) + 2; } else { m = ((r - g) / delta) + 4; } return new HSVA(Math.round(m * 60), s, cmax, rgba.a); }; // from http://www.rapidtables.com/convert/color/hsv-to-rgb.htm HSVA.toRGBA = function (hsva) { var h = hsva.h, s = hsva.s, v = hsva.v, a = hsva.a; var c = v * s; var x = c * (1 - Math.abs((h / 60) % 2 - 1)); var m = v - c; var _a = [0, 0, 0], r = _a[0], g = _a[1], b = _a[2]; if (h < 60) { r = c; g = x; } else if (h < 120) { r = x; g = c; } else if (h < 180) { g = c; b = x; } else if (h < 240) { g = x; b = c; } else if (h < 300) { r = x; b = c; } else if (h < 360) { r = c; b = x; } r = Math.round((r + m) * 255); g = Math.round((g + m) * 255); b = Math.round((b + m) * 255); return new RGBA(r, g, b, a); }; return HSVA; }()); exports.HSVA = HSVA; var Color = /** @class */ (function () { function Color(arg) { if (!arg) { throw new Error('Color needs a value'); } else if (arg instanceof RGBA) { this.rgba = arg; } else if (arg instanceof HSLA) { this._hsla = arg; this.rgba = HSLA.toRGBA(arg); } else if (arg instanceof HSVA) { this._hsva = arg; this.rgba = HSVA.toRGBA(arg); } else { throw new Error('Invalid color ctor argument'); } } Color.fromHex = function (hex) { return Color.Format.CSS.parseHex(hex) || Color.red; }; Object.defineProperty(Color.prototype, "hsla", { get: function () { if (this._hsla) { return this._hsla; } else { return HSLA.fromRGBA(this.rgba); } }, enumerable: true, configurable: true }); Object.defineProperty(Color.prototype, "hsva", { get: function () { if (this._hsva) { return this._hsva; } return HSVA.fromRGBA(this.rgba); }, enumerable: true, configurable: true }); Color.prototype.equals = function (other) { return !!other && RGBA.equals(this.rgba, other.rgba) && HSLA.equals(this.hsla, other.hsla) && HSVA.equals(this.hsva, other.hsva); }; /** * http://www.w3.org/TR/WCAG20/#relativeluminancedef * Returns the number in the set [0, 1]. O => Darkest Black. 1 => Lightest white. */ Color.prototype.getRelativeLuminance = function () { var R = Color._relativeLuminanceForComponent(this.rgba.r); var G = Color._relativeLuminanceForComponent(this.rgba.g); var B = Color._relativeLuminanceForComponent(this.rgba.b); var luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B; return roundFloat(luminance, 4); }; Color._relativeLuminanceForComponent = function (color) { var c = color / 255; return (c <= 0.03928) ? c / 12.92 : Math.pow(((c + 0.055) / 1.055), 2.4); }; /** * http://24ways.org/2010/calculating-color-contrast * Return 'true' if lighter color otherwise 'false' */ Color.prototype.isLighter = function () { var yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1000; return yiq >= 128; }; Color.prototype.isLighterThan = function (another) { var lum1 = this.getRelativeLuminance(); var lum2 = another.getRelativeLuminance(); return lum1 > lum2; }; Color.prototype.isDarkerThan = function (another) { var lum1 = this.getRelativeLuminance(); var lum2 = another.getRelativeLuminance(); return lum1 < lum2; }; Color.prototype.lighten = function (factor) { return new Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l + this.hsla.l * factor, this.hsla.a)); }; Color.prototype.darken = function (factor) { return new Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l - this.hsla.l * factor, this.hsla.a)); }; Color.prototype.transparent = function (factor) { var _a = this.rgba, r = _a.r, g = _a.g, b = _a.b, a = _a.a; return new Color(new RGBA(r, g, b, a * factor)); }; Color.prototype.isTransparent = function () { return this.rgba.a === 0; }; Color.prototype.isOpaque = function () { return this.rgba.a === 1; }; Color.prototype.opposite = function () { return new Color(new RGBA(255 - this.rgba.r, 255 - this.rgba.g, 255 - this.rgba.b, this.rgba.a)); }; Color.prototype.toString = function () { return '' + Color.Format.CSS.format(this); }; Color.getLighterColor = function (of, relative, factor) { if (of.isLighterThan(relative)) { return of; } factor = factor ? factor : 0.5; var lum1 = of.getRelativeLuminance(); var lum2 = relative.getRelativeLuminance(); factor = factor * (lum2 - lum1) / lum2; return of.lighten(factor); }; Color.getDarkerColor = function (of, relative, factor) { if (of.isDarkerThan(relative)) { return of; } factor = factor ? factor : 0.5; var lum1 = of.getRelativeLuminance(); var lum2 = relative.getRelativeLuminance(); factor = factor * (lum1 - lum2) / lum1; return of.darken(factor); }; Color.white = new Color(new RGBA(255, 255, 255, 1)); Color.black = new Color(new RGBA(0, 0, 0, 1)); Color.red = new Color(new RGBA(255, 0, 0, 1)); Color.blue = new Color(new RGBA(0, 0, 255, 1)); Color.cyan = new Color(new RGBA(0, 255, 255, 1)); Color.lightgrey = new Color(new RGBA(211, 211, 211, 1)); Color.transparent = new Color(new RGBA(0, 0, 0, 0)); return Color; }()); exports.Color = Color; (function (Color) { var Format; (function (Format) { var CSS; (function (CSS) { function formatRGB(color) { if (color.rgba.a === 1) { return "rgb(" + color.rgba.r + ", " + color.rgba.g + ", " + color.rgba.b + ")"; } return Color.Format.CSS.formatRGBA(color); } CSS.formatRGB = formatRGB; function formatRGBA(color) { return "rgba(" + color.rgba.r + ", " + color.rgba.g + ", " + color.rgba.b + ", " + +(color.rgba.a).toFixed(2) + ")"; } CSS.formatRGBA = formatRGBA; function formatHSL(color) { if (color.hsla.a === 1) { return "hsl(" + color.hsla.h + ", " + (color.hsla.s * 100).toFixed(2) + "%, " + (color.hsla.l * 100).toFixed(2) + "%)"; } return Color.Format.CSS.formatHSLA(color); } CSS.formatHSL = formatHSL; function formatHSLA(color) { return "hsla(" + color.hsla.h + ", " + (color.hsla.s * 100).toFixed(2) + "%, " + (color.hsla.l * 100).toFixed(2) + "%, " + color.hsla.a.toFixed(2) + ")"; } CSS.formatHSLA = formatHSLA; function _toTwoDigitHex(n) { var r = n.toString(16); return r.length !== 2 ? '0' + r : r; } /** * Formats the color as #RRGGBB */ function formatHex(color) { return "#" + _toTwoDigitHex(color.rgba.r) + _toTwoDigitHex(color.rgba.g) + _toTwoDigitHex(color.rgba.b); } CSS.formatHex = formatHex; /** * Formats the color as #RRGGBBAA * If 'compact' is set, colors without transparancy will be printed as #RRGGBB */ function formatHexA(color, compact) { if (compact === void 0) { compact = false; } if (compact && color.rgba.a === 1) { return Color.Format.CSS.formatHex(color); } return "#" + _toTwoDigitHex(color.rgba.r) + _toTwoDigitHex(color.rgba.g) + _toTwoDigitHex(color.rgba.b) + _toTwoDigitHex(Math.round(color.rgba.a * 255)); } CSS.formatHexA = formatHexA; /** * The default format will use HEX if opaque and RGBA otherwise. */ function format(color) { if (color.isOpaque()) { return Color.Format.CSS.formatHex(color); } return Color.Format.CSS.formatRGBA(color); } CSS.format = format; /** * Converts an Hex color value to a Color. * returns r, g, and b are contained in the set [0, 255] * @param hex string (#RGB, #RGBA, #RRGGBB or #RRGGBBAA). */ function parseHex(hex) { var length = hex.length; if (length === 0) { // Invalid color return null; } if (hex.charCodeAt(0) !== 35 /* Hash */) { // Does not begin with a # return null; } if (length === 7) { // #RRGGBB format var r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2)); var g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4)); var b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6)); return new Color(new RGBA(r, g, b, 1)); } if (length === 9) { // #RRGGBBAA format var r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2)); var g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4)); var b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6)); var a = 16 * _parseHexDigit(hex.charCodeAt(7)) + _parseHexDigit(hex.charCodeAt(8)); return new Color(new RGBA(r, g, b, a / 255)); } if (length === 4) { // #RGB format var r = _parseHexDigit(hex.charCodeAt(1)); var g = _parseHexDigit(hex.charCodeAt(2)); var b = _parseHexDigit(hex.charCodeAt(3)); return new Color(new RGBA(16 * r + r, 16 * g + g, 16 * b + b)); } if (length === 5) { // #RGBA format var r = _parseHexDigit(hex.charCodeAt(1)); var g = _parseHexDigit(hex.charCodeAt(2)); var b = _parseHexDigit(hex.charCodeAt(3)); var a = _parseHexDigit(hex.charCodeAt(4)); return new Color(new RGBA(16 * r + r, 16 * g + g, 16 * b + b, (16 * a + a) / 255)); } // Invalid color return null; } CSS.parseHex = parseHex; function _parseHexDigit(charCode) { switch (charCode) { case 48 /* Digit0 */: return 0; case 49 /* Digit1 */: return 1; case 50 /* Digit2 */: return 2; case 51 /* Digit3 */: return 3; case 52 /* Digit4 */: return 4; case 53 /* Digit5 */: return 5; case 54 /* Digit6 */: return 6; case 55 /* Digit7 */: return 7; case 56 /* Digit8 */: return 8; case 57 /* Digit9 */: return 9; case 97 /* a */: return 10; case 65 /* A */: return 10; case 98 /* b */: return 11; case 66 /* B */: return 11; case 99 /* c */: return 12; case 67 /* C */: return 12; case 100 /* d */: return 13; case 68 /* D */: return 13; case 101 /* e */: return 14; case 69 /* E */: return 14; case 102 /* f */: return 15; case 70 /* F */: return 15; } return 0; } })(CSS = Format.CSS || (Format.CSS = {})); })(Format = Color.Format || (Color.Format = {})); })(Color = exports.Color || (exports.Color = {})); exports.Color = Color; }); define(__m[101/*vs/base/common/decorators*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var memoizeId = 0; function createMemoizer() { var memoizeKeyPrefix = "$memoize" + memoizeId++; var self = undefined; var result = function memoize(target, key, descriptor) { var fnKey = null; var fn = null; if (typeof descriptor.value === 'function') { fnKey = 'value'; fn = descriptor.value; if (fn.length !== 0) { console.warn('Memoize should only be used in functions with zero parameters'); } } else if (typeof descriptor.get === 'function') { fnKey = 'get'; fn = descriptor.get; } if (!fn) { throw new Error('not supported'); } var memoizeKey = memoizeKeyPrefix + ":" + key; descriptor[fnKey] = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } self = this; if (!this.hasOwnProperty(memoizeKey)) { Object.defineProperty(this, memoizeKey, { configurable: true, enumerable: false, writable: true, value: fn.apply(this, args) }); } return this[memoizeKey]; }; }; result.clear = function () { if (typeof self === 'undefined') { return; } Object.getOwnPropertyNames(self).forEach(function (property) { if (property.indexOf(memoizeKeyPrefix) === 0) { delete self[property]; } }); }; return result; } exports.createMemoizer = createMemoizer; function memoize(target, key, descriptor) { return createMemoizer()(target, key, descriptor); } exports.memoize = memoize; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[241/*vs/base/common/diff/diffChange*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Represents information about a specific difference between two sequences. */ var DiffChange = /** @class */ (function () { /** * Constructs a new DiffChange with the given sequence information * and content. */ function DiffChange(originalStart, originalLength, modifiedStart, modifiedLength) { //Debug.Assert(originalLength > 0 || modifiedLength > 0, "originalLength and modifiedLength cannot both be <= 0"); this.originalStart = originalStart; this.originalLength = originalLength; this.modifiedStart = modifiedStart; this.modifiedLength = modifiedLength; } /** * The end point (exclusive) of the change in the original sequence. */ DiffChange.prototype.getOriginalEnd = function () { return this.originalStart + this.originalLength; }; /** * The end point (exclusive) of the change in the modified sequence. */ DiffChange.prototype.getModifiedEnd = function () { return this.modifiedStart + this.modifiedLength; }; return DiffChange; }()); exports.DiffChange = DiffChange; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[10/*vs/base/common/errors*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // Avoid circular dependency on EventEmitter by implementing a subset of the interface. var ErrorHandler = /** @class */ (function () { function ErrorHandler() { this.listeners = []; this.unexpectedErrorHandler = function (e) { setTimeout(function () { if (e.stack) { throw new Error(e.message + '\n\n' + e.stack); } throw e; }, 0); }; } ErrorHandler.prototype.emit = function (e) { this.listeners.forEach(function (listener) { listener(e); }); }; ErrorHandler.prototype.onUnexpectedError = function (e) { this.unexpectedErrorHandler(e); this.emit(e); }; // For external errors, we don't want the listeners to be called ErrorHandler.prototype.onUnexpectedExternalError = function (e) { this.unexpectedErrorHandler(e); }; return ErrorHandler; }()); exports.ErrorHandler = ErrorHandler; exports.errorHandler = new ErrorHandler(); function onUnexpectedError(e) { // ignore errors from cancelled promises if (!isPromiseCanceledError(e)) { exports.errorHandler.onUnexpectedError(e); } return undefined; } exports.onUnexpectedError = onUnexpectedError; function onUnexpectedExternalError(e) { // ignore errors from cancelled promises if (!isPromiseCanceledError(e)) { exports.errorHandler.onUnexpectedExternalError(e); } return undefined; } exports.onUnexpectedExternalError = onUnexpectedExternalError; function transformErrorForSerialization(error) { if (error instanceof Error) { var name_1 = error.name, message = error.message; var stack = error.stacktrace || error.stack; return { $isError: true, name: name_1, message: message, stack: stack }; } // return as is return error; } exports.transformErrorForSerialization = transformErrorForSerialization; var canceledName = 'Canceled'; /** * Checks if the given error is a promise in canceled state */ function isPromiseCanceledError(error) { return error instanceof Error && error.name === canceledName && error.message === canceledName; } exports.isPromiseCanceledError = isPromiseCanceledError; /** * Returns an error that signals cancellation. */ function canceled() { var error = new Error(canceledName); error.name = error.message; return error; } exports.canceled = canceled; function illegalArgument(name) { if (name) { return new Error("Illegal argument: " + name); } else { return new Error('Illegal argument'); } } exports.illegalArgument = illegalArgument; function illegalState(name) { if (name) { return new Error("Illegal state: " + name); } else { return new Error('Illegal state'); } } exports.illegalState = illegalState; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[102/*vs/base/common/functional*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function once(fn) { var _this = this; var didCall = false; var result; return function () { if (didCall) { return result; } didCall = true; result = fn.apply(_this, arguments); return result; }; } exports.once = once; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[125/*vs/base/common/hash*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Return a hash value for an object. */ function hash(obj, hashVal) { if (hashVal === void 0) { hashVal = 0; } 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(0, 937); default: return numberHash(0, 617); } } exports.hash = hash; function numberHash(val, initialHashVal) { return (((initialHashVal << 5) - initialHashVal) + val) | 0; // hashVal * 31 + ch, keep as int32 } function booleanHash(b, initialHashVal) { return numberHash(b ? 433 : 863, initialHashVal); } function stringHash(s, hashVal) { hashVal = numberHash(149417, hashVal); for (var i = 0, length_1 = s.length; i < length_1; i++) { hashVal = numberHash(s.charCodeAt(i), hashVal); } return hashVal; } exports.stringHash = stringHash; function arrayHash(arr, initialHashVal) { initialHashVal = numberHash(104579, initialHashVal); return arr.reduce(function (hashVal, item) { return hash(item, hashVal); }, initialHashVal); } function objectHash(obj, initialHashVal) { initialHashVal = numberHash(181387, initialHashVal); return Object.keys(obj).sort().reduce(function (hashVal, key) { hashVal = stringHash(key, hashVal); return hash(obj[key], hashVal); }, initialHashVal); } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[126/*vs/base/common/diff/diff*/], __M([0/*require*/,1/*exports*/,241/*vs/base/common/diff/diffChange*/,125/*vs/base/common/hash*/]), function (require, exports, diffChange_1, hash_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var StringDiffSequence = /** @class */ (function () { function StringDiffSequence(source) { this.source = source; } StringDiffSequence.prototype.getElements = function () { var source = this.source; var characters = new Int32Array(source.length); for (var i = 0, len = source.length; i < len; i++) { characters[i] = source.charCodeAt(i); } return characters; }; return StringDiffSequence; }()); 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 // var Debug = /** @class */ (function () { function Debug() { } Debug.Assert = function (condition, message) { if (!condition) { throw new Error(message); } }; return Debug; }()); exports.Debug = Debug; var MyArray = /** @class */ (function () { function 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. */ MyArray.Copy = function (sourceArray, sourceIndex, destinationArray, destinationIndex, length) { for (var i = 0; i < length; i++) { destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i]; } }; MyArray.Copy2 = function (sourceArray, sourceIndex, destinationArray, destinationIndex, length) { for (var i = 0; i < length; i++) { destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i]; } }; return MyArray; }()); exports.MyArray = MyArray; /** * A utility class which helps to create the set of DiffChanges from * a difference operation. This class accepts original DiffElements and * modified DiffElements that are involved in a particular change. The * MarktNextChange() method can be called to mark the separation between * distinct changes. At the end, the Changes property can be called to retrieve * the constructed changes. */ var DiffChangeHelper = /** @class */ (function () { /** * Constructs a new DiffChangeHelper for the given DiffSequences. */ function DiffChangeHelper() { 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. */ DiffChangeHelper.prototype.MarkNextChange = function () { // 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. */ DiffChangeHelper.prototype.AddOriginalElement = function (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. */ DiffChangeHelper.prototype.AddModifiedElement = function (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. */ DiffChangeHelper.prototype.getChanges = function () { 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 */ DiffChangeHelper.prototype.getReverseChanges = function () { 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; }; return DiffChangeHelper; }()); /** * An implementation of the difference algorithm described in * "An O(ND) Difference Algorithm and its variations" by Eugene W. Myers */ var LcsDiff = /** @class */ (function () { /** * Constructs the DiffFinder */ function LcsDiff(originalSequence, modifiedSequence, continueProcessingPredicate) { if (continueProcessingPredicate === void 0) { continueProcessingPredicate = null; } this.ContinueProcessingPredicate = continueProcessingPredicate; var _a = LcsDiff._getElements(originalSequence), originalStringElements = _a[0], originalElementsOrHash = _a[1], originalHasStrings = _a[2]; var _b = LcsDiff._getElements(modifiedSequence), modifiedStringElements = _b[0], modifiedElementsOrHash = _b[1], modifiedHasStrings = _b[2]; this._hasStrings = (originalHasStrings && modifiedHasStrings); this._originalStringElements = originalStringElements; this._originalElementsOrHash = originalElementsOrHash; this._modifiedStringElements = modifiedStringElements; this._modifiedElementsOrHash = modifiedElementsOrHash; this.m_forwardHistory = []; this.m_reverseHistory = []; } LcsDiff._isStringArray = function (arr) { return (arr.length > 0 && typeof arr[0] === 'string'); }; LcsDiff._getElements = function (sequence) { var elements = sequence.getElements(); if (LcsDiff._isStringArray(elements)) { var hashes = new Int32Array(elements.length); for (var i = 0, len = elements.length; i < len; i++) { hashes[i] = hash_1.stringHash(elements[i], 0); } return [elements, hashes, true]; } if (elements instanceof Int32Array) { return [[], elements, false]; } return [[], new Int32Array(elements), false]; }; LcsDiff.prototype.ElementsAreEqual = function (originalIndex, newIndex) { if (this._originalElementsOrHash[originalIndex] !== this._modifiedElementsOrHash[newIndex]) { return false; } return (this._hasStrings ? this._originalStringElements[originalIndex] === this._modifiedStringElements[newIndex] : true); }; LcsDiff.prototype.OriginalElementsAreEqual = function (index1, index2) { if (this._originalElementsOrHash[index1] !== this._originalElementsOrHash[index2]) { return false; } return (this._hasStrings ? this._originalStringElements[index1] === this._originalStringElements[index2] : true); }; LcsDiff.prototype.ModifiedElementsAreEqual = function (index1, index2) { if (this._modifiedElementsOrHash[index1] !== this._modifiedElementsOrHash[index2]) { return false; } return (this._hasStrings ? this._modifiedStringElements[index1] === this._modifiedStringElements[index2] : true); }; LcsDiff.prototype.ComputeDiff = function (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. */ LcsDiff.prototype._ComputeDiff = function (originalStart, originalEnd, modifiedStart, modifiedEnd, pretty) { var quitEarlyArr = [false]; var 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. */ LcsDiff.prototype.ComputeDiffRecursive = function (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) { var changes = void 0; 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. var midOriginalArr = [0]; var midModifiedArr = [0]; var result = this.ComputeRecursionPoint(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr); var midOriginal = midOriginalArr[0]; var 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 var leftChanges = this.ComputeDiffRecursive(originalStart, midOriginal, modifiedStart, midModified, quitEarlyArr); var rightChanges = []; if (!quitEarlyArr[0]) { rightChanges = this.ComputeDiffRecursive(midOriginal + 1, originalEnd, midModified + 1, modifiedEnd, quitEarlyArr); } else { // We did't have time to finish the first half, so we don't have time to compute this half. // Consider the entire rest of the sequence different. rightChanges = [ new diffChange_1.DiffChange(midOriginal + 1, originalEnd - (midOriginal + 1) + 1, midModified + 1, modifiedEnd - (midModified + 1) + 1) ]; } return this.ConcatenateChanges(leftChanges, rightChanges); } // If we hit here, we quit early, and so can't return anything meaningful return [ new diffChange_1.DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1) ]; }; LcsDiff.prototype.WALKTRACE = function (diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr) { var forwardChanges = null; var reverseChanges = null; // First, walk backward through the forward diagonals history var changeHelper = new DiffChangeHelper(); var diagonalMin = diagonalForwardStart; var diagonalMax = diagonalForwardEnd; var diagonalRelative = (midOriginalArr[0] - midModifiedArr[0]) - diagonalForwardOffset; var lastOriginalIndex = -1073741824 /* MIN_SAFE_SMALL_INTEGER */; var historyIndex = this.m_forwardHistory.length - 1; do { // Get the diagonal index from the relative diagonal number var 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 var originalStartPoint = midOriginalArr[0] + 1; var modifiedStartPoint = midModifiedArr[0] + 1; if (forwardChanges !== null && forwardChanges.length > 0) { var 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 var 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 */ LcsDiff.prototype.ComputeRecursionPoint = function (originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr) { var originalIndex = 0, modifiedIndex = 0; var diagonalForwardStart = 0, diagonalForwardEnd = 0; var 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. var maxDifferences = (originalEnd - originalStart) + (modifiedEnd - modifiedStart); var numDiagonals = maxDifferences + 1; var forwardPoints = new Int32Array(numDiagonals); var 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) var diagonalForwardBase = (modifiedEnd - modifiedStart); var 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) var diagonalForwardOffset = (originalStart - modifiedStart); var 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 var delta = diagonalReverseBase - diagonalForwardBase; var 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 (var numDifferences = 1; numDifferences <= (maxDifferences / 2) + 1; numDifferences++) { var furthestOriginalIndex = 0; var 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 (var 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 var 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. var matchLengthOfLongest = ((furthestOriginalIndex - originalStart) + (furthestModifiedIndex - modifiedStart) - numDifferences) / 2; if (this.ContinueProcessingPredicate !== null && !this.ContinueProcessingPredicate(furthestOriginalIndex, matchLengthOfLongest)) { // We can't finish, so skip ahead to generating a result from what we have. quitEarlyArr[0] = true; // Use the furthest distance we got in the forward direction. midOriginalArr[0] = furthestOriginalIndex; midModifiedArr[0] = furthestModifiedIndex; if (matchLengthOfLongest > 0 && 1447 /* MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* MaxDifferencesHistory */ + 1)) { // Enough of the history is in memory to walk it backwards return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr); } else { // We didn't actually remember enough of the history. //Since we are quiting the diff early, we need to shift back the originalStart and modified start //back into the boundary limits since we decremented their value above beyond the boundary limit. originalStart++; modifiedStart++; return [ new diffChange_1.DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1) ]; } } // Run the algorithm in the reverse direction diagonalReverseStart = this.ClipDiagonalBound(diagonalReverseBase - numDifferences, numDifferences, diagonalReverseBase, numDiagonals); diagonalReverseEnd = this.ClipDiagonalBound(diagonalReverseBase + numDifferences, numDifferences, diagonalReverseBase, numDiagonals); for (var 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 var 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 var 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 */ LcsDiff.prototype.PrettifyChanges = function (changes) { // Shift all the changes down first for (var i = 0; i < changes.length; i++) { var change = changes[i]; var originalStop = (i < changes.length - 1) ? changes[i + 1].originalStart : this._originalElementsOrHash.length; var modifiedStop = (i < changes.length - 1) ? changes[i + 1].modifiedStart : this._modifiedElementsOrHash.length; var checkOriginal = change.originalLength > 0; var 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))) { change.originalStart++; change.modifiedStart++; } var 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 (var i = changes.length - 1; i >= 0; i--) { var change = changes[i]; var originalStop = 0; var modifiedStop = 0; if (i > 0) { var prevChange = changes[i - 1]; if (prevChange.originalLength > 0) { originalStop = prevChange.originalStart + prevChange.originalLength; } if (prevChange.modifiedLength > 0) { modifiedStop = prevChange.modifiedStart + prevChange.modifiedLength; } } var checkOriginal = change.originalLength > 0; var checkModified = change.modifiedLength > 0; var bestDelta = 0; var bestScore = this._boundaryScore(change.originalStart, change.originalLength, change.modifiedStart, change.modifiedLength); for (var delta = 1;; delta++) { var originalStart = change.originalStart - delta; var 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; } var score = this._boundaryScore(originalStart, change.originalLength, modifiedStart, change.modifiedLength); if (score > bestScore) { bestScore = score; bestDelta = delta; } } change.originalStart -= bestDelta; change.modifiedStart -= bestDelta; } return changes; }; LcsDiff.prototype._OriginalIsBoundary = function (index) { if (index <= 0 || index >= this._originalElementsOrHash.length - 1) { return true; } return (this._hasStrings && /^\s*$/.test(this._originalStringElements[index])); }; LcsDiff.prototype._OriginalRegionIsBoundary = function (originalStart, originalLength) { if (this._OriginalIsBoundary(originalStart) || this._OriginalIsBoundary(originalStart - 1)) { return true; } if (originalLength > 0) { var originalEnd = originalStart + originalLength; if (this._OriginalIsBoundary(originalEnd - 1) || this._OriginalIsBoundary(originalEnd)) { return true; } } return false; }; LcsDiff.prototype._ModifiedIsBoundary = function (index) { if (index <= 0 || index >= this._modifiedElementsOrHash.length - 1) { return true; } return (this._hasStrings && /^\s*$/.test(this._modifiedStringElements[index])); }; LcsDiff.prototype._ModifiedRegionIsBoundary = function (modifiedStart, modifiedLength) { if (this._ModifiedIsBoundary(modifiedStart) || this._ModifiedIsBoundary(modifiedStart - 1)) { return true; } if (modifiedLength > 0) { var modifiedEnd = modifiedStart + modifiedLength; if (this._ModifiedIsBoundary(modifiedEnd - 1) || this._ModifiedIsBoundary(modifiedEnd)) { return true; } } return false; }; LcsDiff.prototype._boundaryScore = function (originalStart, originalLength, modifiedStart, modifiedLength) { var originalScore = (this._OriginalRegionIsBoundary(originalStart, originalLength) ? 1 : 0); var 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 */ LcsDiff.prototype.ConcatenateChanges = function (left, right) { var 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 var 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 { var 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 */ LcsDiff.prototype.ChangesOverlap = function (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) { var originalStart = left.originalStart; var originalLength = left.originalLength; var modifiedStart = left.modifiedStart; var 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. */ LcsDiff.prototype.ClipDiagonalBound = function (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 var diagonalsBelow = diagonalBaseIndex; var diagonalsAbove = numDiagonals - diagonalBaseIndex - 1; var diffEven = (numDifferences % 2 === 0); if (diagonal < 0) { var lowerBoundEven = (diagonalsBelow % 2 === 0); return (diffEven === lowerBoundEven) ? 0 : 1; } else { var upperBoundEven = (diagonalsAbove % 2 === 0); return (diffEven === upperBoundEven) ? numDiagonals - 1 : numDiagonals - 2; } }; return LcsDiff; }()); 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[75/*vs/base/common/htmlContent*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,100/*vs/base/common/codicons*/]), function (require, exports, arrays_1, codicons_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MarkdownString = /** @class */ (function () { function MarkdownString(_value, isTrustedOrOptions) { if (_value === void 0) { _value = ''; } if (isTrustedOrOptions === void 0) { isTrustedOrOptions = false; } var _a, _b; this._value = _value; if (typeof isTrustedOrOptions === 'boolean') { this._isTrusted = isTrustedOrOptions; this._supportThemeIcons = false; } else { this._isTrusted = (_a = isTrustedOrOptions.isTrusted) !== null && _a !== void 0 ? _a : false; this._supportThemeIcons = (_b = isTrustedOrOptions.supportThemeIcons) !== null && _b !== void 0 ? _b : false; } } Object.defineProperty(MarkdownString.prototype, "value", { get: function () { return this._value; }, enumerable: true, configurable: true }); Object.defineProperty(MarkdownString.prototype, "isTrusted", { get: function () { return this._isTrusted; }, enumerable: true, configurable: true }); Object.defineProperty(MarkdownString.prototype, "supportThemeIcons", { get: function () { return this._supportThemeIcons; }, enumerable: true, configurable: true }); MarkdownString.prototype.appendText = function (value) { // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash this._value += (this._supportThemeIcons ? codicons_1.escapeCodicons(value) : value) .replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&') .replace('\n', '\n\n'); return this; }; MarkdownString.prototype.appendMarkdown = function (value) { this._value += value; return this; }; MarkdownString.prototype.appendCodeblock = function (langId, code) { this._value += '\n```'; this._value += langId; this._value += '\n'; this._value += code; this._value += '\n```\n'; return this; }; return MarkdownString; }()); 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 markedStringsEquals(a, b) { if (!a && !b) { return true; } else if (!a || !b) { return false; } else if (Array.isArray(a) && Array.isArray(b)) { return arrays_1.equals(a, b, markdownStringEqual); } else if (isMarkdownString(a) && isMarkdownString(b)) { return markdownStringEqual(a, b); } else { return false; } } exports.markedStringsEquals = markedStringsEquals; function markdownStringEqual(a, b) { if (a === b) { return true; } else if (!a || !b) { return false; } else { return a.value === b.value && a.isTrusted === b.isTrusted && a.supportThemeIcons === b.supportThemeIcons; } } function removeMarkdownEscapes(text) { if (!text) { return text; } return text.replace(/\\([\\`*_{}[\]()#+\-.!])/g, '$1'); } exports.removeMarkdownEscapes = removeMarkdownEscapes; function parseHrefAndDimensions(href) { var dimensions = []; var splitted = href.split('|').map(function (s) { return s.trim(); }); href = splitted[0]; var parameters = splitted[1]; if (parameters) { var heightFromParams = /height=(\d+)/.exec(parameters); var widthFromParams = /width=(\d+)/.exec(parameters); var height = heightFromParams ? heightFromParams[1] : ''; var width = widthFromParams ? widthFromParams[1] : ''; var widthIsFinite = isFinite(parseInt(width)); var heightIsFinite = isFinite(parseInt(height)); if (widthIsFinite) { dimensions.push("width=\"" + width + "\""); } if (heightIsFinite) { dimensions.push("height=\"" + height + "\""); } } return { href: href, dimensions: 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[127/*vs/base/common/idGenerator*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var IdGenerator = /** @class */ (function () { function IdGenerator(prefix) { this._prefix = prefix; this._lastId = 0; } IdGenerator.prototype.nextId = function () { return this._prefix + (++this._lastId); }; return IdGenerator; }()); exports.IdGenerator = IdGenerator; exports.defaultGenerator = new IdGenerator('id#'); }); /* The MIT License (MIT) Copyright © 2015 Nicolas Bevacqua Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ let __insane_func; (function () { function r(e, n, t) { function o(i, f) { if (!n[i]) { if (!e[i]) { var c = "function" == typeof require && require; if (!f && c) return c(i, !0); if (u) return u(i, !0); var a = new Error("Cannot find module '" + i + "'"); throw a.code = "MODULE_NOT_FOUND", a } var p = n[i] = { exports: {} }; e[i][0].call(p.exports, function (r) { var n = e[i][1][r]; return o(n || r) }, p, p.exports, r, e, n, t) } return n[i].exports } for (var u = "function" == typeof require && require, i = 0; i < t.length; i++)o(t[i]); return o } return r })()({ 1: [function (require, module, exports) { 'use strict'; var toMap = require('./toMap'); var uris = ['background', 'base', 'cite', 'href', 'longdesc', 'src', 'usemap']; module.exports = { uris: toMap(uris) // attributes that have an href and hence need to be sanitized }; }, { "./toMap": 10 }], 2: [function (require, module, exports) { 'use strict'; var defaults = { allowedAttributes: { '*': ['title', 'accesskey'], a: ['href', 'name', 'target', 'aria-label'], iframe: ['allowfullscreen', 'frameborder', 'src'], img: ['src', 'alt', 'title', 'aria-label'] }, allowedClasses: {}, allowedSchemes: ['http', 'https', 'mailto'], allowedTags: [ 'a', 'abbr', 'article', 'b', 'blockquote', 'br', 'caption', 'code', 'del', 'details', 'div', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'main', 'mark', 'ol', 'p', 'pre', 'section', 'span', 'strike', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'th', 'thead', 'tr', 'u', 'ul' ], filter: null }; module.exports = defaults; }, {}], 3: [function (require, module, exports) { 'use strict'; var toMap = require('./toMap'); var voids = ['area', 'br', 'col', 'hr', 'img', 'wbr', 'input', 'base', 'basefont', 'link', 'meta']; module.exports = { voids: toMap(voids) }; }, { "./toMap": 10 }], 4: [function (require, module, exports) { 'use strict'; var he = require('he'); var assign = require('assignment'); var parser = require('./parser'); var sanitizer = require('./sanitizer'); var defaults = require('./defaults'); function insane(html, options, strict) { var buffer = []; var configuration = strict === true ? options : assign({}, defaults, options); var handler = sanitizer(buffer, configuration); parser(html, handler); return buffer.join(''); } insane.defaults = defaults; module.exports = insane; __insane_func = insane; }, { "./defaults": 2, "./parser": 7, "./sanitizer": 8, "assignment": 6, "he": 9 }], 5: [function (require, module, exports) { 'use strict'; module.exports = function lowercase(string) { return typeof string === 'string' ? string.toLowerCase() : string; }; }, {}], 6: [function (require, module, exports) { 'use strict'; function assignment(result) { var stack = Array.prototype.slice.call(arguments, 1); var item; var key; while (stack.length) { item = stack.shift(); for (key in item) { if (item.hasOwnProperty(key)) { if (Object.prototype.toString.call(result[key]) === '[object Object]') { result[key] = assignment(result[key], item[key]); } else { result[key] = item[key]; } } } } return result; } module.exports = assignment; }, {}], 7: [function (require, module, exports) { 'use strict'; var he = require('he'); var lowercase = require('./lowercase'); var attributes = require('./attributes'); var elements = require('./elements'); var rstart = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/; var rend = /^<\s*\/\s*([\w:-]+)[^>]*>/; var rattrs = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g; var rtag = /^'); if (index >= 0) { if (handler.comment) { handler.comment(html.substring(4, index)); } html = html.substring(index + 3); chars = false; } } function parseTagDecode() { if (!chars) { return; } var text; var index = html.indexOf('<'); if (index >= 0) { text = html.substring(0, index); html = html.substring(index); } else { text = html; html = ''; } if (handler.chars) { handler.chars(text); } } function parseStartTag(tag, tagName, rest, unary) { var attrs = {}; var low = lowercase(tagName); var u = elements.voids[low] || !!unary; rest.replace(rattrs, attrReplacer); if (!u) { stack.push(low); } if (handler.start) { handler.start(low, attrs, u); } function attrReplacer(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) { if (doubleQuotedValue === void 0 && singleQuotedValue === void 0 && unquotedValue === void 0) { attrs[name] = void 0; // attribute is like } else { attrs[name] = he.decode(doubleQuotedValue || singleQuotedValue || unquotedValue || ''); } } } function parseEndTag(tag, tagName) { var i; var pos = 0; var low = lowercase(tagName); if (low) { for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos] === low) { break; // find the closest opened tag of the same type } } } if (pos >= 0) { for (i = stack.length - 1; i >= pos; i--) { if (handler.end) { // close all the open elements, up the stack handler.end(stack[i]); } } stack.length = pos; } } } module.exports = parser; }, { "./attributes": 1, "./elements": 3, "./lowercase": 5, "he": 9 }], 8: [function (require, module, exports) { 'use strict'; var he = require('he'); var lowercase = require('./lowercase'); var attributes = require('./attributes'); var elements = require('./elements'); function sanitizer(buffer, options) { var last; var context; var o = options || {}; reset(); return { start: start, end: end, chars: chars }; function out(value) { buffer.push(value); } function start(tag, attrs, unary) { var low = lowercase(tag); if (context.ignoring) { ignore(low); return; } if ((o.allowedTags || []).indexOf(low) === -1) { ignore(low); return; } if (o.filter && !o.filter({ tag: low, attrs: attrs })) { ignore(low); return; } out('<'); out(low); Object.keys(attrs).forEach(parse); out(unary ? '/>' : '>'); function parse(key) { var value = attrs[key]; var classesOk = (o.allowedClasses || {})[low] || []; var attrsOk = (o.allowedAttributes || {})[low] || []; attrsOk = attrsOk.concat((o.allowedAttributes || {})['*'] || []); var valid; var lkey = lowercase(key); if (lkey === 'class' && attrsOk.indexOf(lkey) === -1) { value = value.split(' ').filter(isValidClass).join(' ').trim(); valid = value.length; } else { valid = attrsOk.indexOf(lkey) !== -1 && (attributes.uris[lkey] !== true || testUrl(value)); } if (valid) { out(' '); out(key); if (typeof value === 'string') { out('="'); out(he.encode(value)); out('"'); } } function isValidClass(className) { return classesOk && classesOk.indexOf(className) !== -1; } } } function end(tag) { var low = lowercase(tag); var allowed = (o.allowedTags || []).indexOf(low) !== -1; if (allowed) { if (context.ignoring === false) { out(''); } else { unignore(low); } } else { unignore(low); } } function testUrl(text) { var start = text[0]; if (start === '#' || start === '/') { return true; } var colon = text.indexOf(':'); if (colon === -1) { return true; } var questionmark = text.indexOf('?'); if (questionmark !== -1 && colon > questionmark) { return true; } var hash = text.indexOf('#'); if (hash !== -1 && colon > hash) { return true; } return o.allowedSchemes.some(matches); function matches(scheme) { return text.indexOf(scheme + ':') === 0; } } function chars(text) { if (context.ignoring === false) { out(o.transformText ? o.transformText(text) : text); } } function ignore(tag) { if (elements.voids[tag]) { return; } if (context.ignoring === false) { context = { ignoring: tag, depth: 1 }; } else if (context.ignoring === tag) { context.depth++; } } function unignore(tag) { if (context.ignoring === tag) { if (--context.depth <= 0) { reset(); } } } function reset() { context = { ignoring: false, depth: 0 }; } } module.exports = sanitizer; }, { "./attributes": 1, "./elements": 3, "./lowercase": 5, "he": 9 }], 9: [function (require, module, exports) { 'use strict'; var escapes = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; var unescapes = { '&': '&', '<': '<', '>': '>', '"': '"', ''': "'" }; var rescaped = /(&|<|>|"|')/g; var runescaped = /[&<>"']/g; function escapeHtmlChar(match) { return escapes[match]; } function unescapeHtmlChar(match) { return unescapes[match]; } function escapeHtml(text) { return text == null ? '' : String(text).replace(runescaped, escapeHtmlChar); } function unescapeHtml(html) { return html == null ? '' : String(html).replace(rescaped, unescapeHtmlChar); } escapeHtml.options = unescapeHtml.options = {}; module.exports = { encode: escapeHtml, escape: escapeHtml, decode: unescapeHtml, unescape: unescapeHtml, version: '1.0.0-browser' }; }, {}], 10: [function (require, module, exports) { 'use strict'; function toMap(list) { return list.reduce(asKey, {}); } function asKey(accumulator, item) { accumulator[item] = true; return accumulator; } module.exports = toMap; }, {}] }, {}, [4]); // ESM-comment-begin define("vs/base/common/insane/insane", function() { return { insane: __insane_func }; }); // ESM-comment-end // ESM-uncomment-begin // export var insane = __insane_func; // ESM-uncomment-end /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[54/*vs/base/common/iterator*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FIN = { done: true, value: undefined }; var Iterator; (function (Iterator) { var _empty = { next: function () { return exports.FIN; } }; function empty() { return _empty; } Iterator.empty = empty; function single(value) { var done = false; return { next: function () { if (done) { return exports.FIN; } done = true; return { done: false, value: value }; } }; } Iterator.single = single; function fromArray(array, index, length) { if (index === void 0) { index = 0; } if (length === void 0) { length = array.length; } return { next: function () { if (index >= length) { return exports.FIN; } return { done: false, value: array[index++] }; } }; } Iterator.fromArray = fromArray; function fromNativeIterator(it) { return { next: function () { var result = it.next(); if (result.done) { return exports.FIN; } return { done: false, value: result.value }; } }; } Iterator.fromNativeIterator = fromNativeIterator; function from(elements) { if (!elements) { return Iterator.empty(); } else if (Array.isArray(elements)) { return Iterator.fromArray(elements); } else { return elements; } } Iterator.from = from; function map(iterator, fn) { return { next: function () { var element = iterator.next(); if (element.done) { return exports.FIN; } else { return { done: false, value: fn(element.value) }; } } }; } Iterator.map = map; function filter(iterator, fn) { return { next: function () { while (true) { var element = iterator.next(); if (element.done) { return exports.FIN; } if (fn(element.value)) { return { done: false, value: element.value }; } } } }; } Iterator.filter = filter; function forEach(iterator, fn) { for (var next = iterator.next(); !next.done; next = iterator.next()) { fn(next.value); } } Iterator.forEach = forEach; function collect(iterator, atMost) { if (atMost === void 0) { atMost = Number.POSITIVE_INFINITY; } var result = []; if (atMost === 0) { return result; } var i = 0; for (var next = iterator.next(); !next.done; next = iterator.next()) { result.push(next.value); if (++i >= atMost) { break; } } return result; } Iterator.collect = collect; function concat() { var iterators = []; for (var _i = 0; _i < arguments.length; _i++) { iterators[_i] = arguments[_i]; } var i = 0; return { next: function () { if (i >= iterators.length) { return exports.FIN; } var iterator = iterators[i]; var result = iterator.next(); if (result.done) { i++; return this.next(); } return result; } }; } Iterator.concat = concat; function chain(iterator) { return new ChainableIterator(iterator); } Iterator.chain = chain; })(Iterator = exports.Iterator || (exports.Iterator = {})); var ChainableIterator = /** @class */ (function () { function ChainableIterator(it) { this.it = it; } ChainableIterator.prototype.next = function () { return this.it.next(); }; return ChainableIterator; }()); exports.ChainableIterator = ChainableIterator; function getSequenceIterator(arg) { if (Array.isArray(arg)) { return Iterator.fromArray(arg); } else if (!arg) { return Iterator.empty(); } else { return arg; } } exports.getSequenceIterator = getSequenceIterator; var ArrayIterator = /** @class */ (function () { function ArrayIterator(items, start, end, index) { if (start === void 0) { start = 0; } if (end === void 0) { end = items.length; } if (index === void 0) { index = start - 1; } this.items = items; this.start = start; this.end = end; this.index = index; } ArrayIterator.prototype.first = function () { this.index = this.start; return this.current(); }; ArrayIterator.prototype.next = function () { this.index = Math.min(this.index + 1, this.end); return this.current(); }; ArrayIterator.prototype.current = function () { if (this.index === this.start - 1 || this.index === this.end) { return null; } return this.items[this.index]; }; return ArrayIterator; }()); exports.ArrayIterator = ArrayIterator; var ArrayNavigator = /** @class */ (function (_super) { __extends(ArrayNavigator, _super); function ArrayNavigator(items, start, end, index) { if (start === void 0) { start = 0; } if (end === void 0) { end = items.length; } if (index === void 0) { index = start - 1; } return _super.call(this, items, start, end, index) || this; } ArrayNavigator.prototype.current = function () { return _super.prototype.current.call(this); }; ArrayNavigator.prototype.previous = function () { this.index = Math.max(this.index - 1, this.start - 1); return this.current(); }; ArrayNavigator.prototype.first = function () { this.index = this.start; return this.current(); }; ArrayNavigator.prototype.last = function () { this.index = this.end - 1; return this.current(); }; ArrayNavigator.prototype.parent = function () { return null; }; return ArrayNavigator; }(ArrayIterator)); exports.ArrayNavigator = ArrayNavigator; var MappedIterator = /** @class */ (function () { function MappedIterator(iterator, fn) { this.iterator = iterator; this.fn = fn; // noop } MappedIterator.prototype.next = function () { return this.fn(this.iterator.next()); }; return MappedIterator; }()); exports.MappedIterator = MappedIterator; }); /*--------------------------------------------------------------------------------------------- * 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/base/common/history*/], __M([0/*require*/,1/*exports*/,54/*vs/base/common/iterator*/]), function (require, exports, iterator_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var HistoryNavigator = /** @class */ (function () { function HistoryNavigator(history, limit) { if (history === void 0) { history = []; } if (limit === void 0) { limit = 10; } this._initialize(history); this._limit = limit; this._onChange(); } HistoryNavigator.prototype.add = function (t) { this._history.delete(t); this._history.add(t); this._onChange(); }; HistoryNavigator.prototype.next = function () { return this._navigator.next(); }; HistoryNavigator.prototype.previous = function () { return this._navigator.previous(); }; HistoryNavigator.prototype.current = function () { return this._navigator.current(); }; HistoryNavigator.prototype.parent = function () { return null; }; HistoryNavigator.prototype.first = function () { return this._navigator.first(); }; HistoryNavigator.prototype.last = function () { return this._navigator.last(); }; HistoryNavigator.prototype.has = function (t) { return this._history.has(t); }; HistoryNavigator.prototype._onChange = function () { this._reduceToLimit(); var elements = this._elements; this._navigator = new iterator_1.ArrayNavigator(elements, 0, elements.length, elements.length); }; HistoryNavigator.prototype._reduceToLimit = function () { var data = this._elements; if (data.length > this._limit) { this._initialize(data.slice(data.length - this._limit)); } }; HistoryNavigator.prototype._initialize = function (history) { this._history = new Set(); for (var _i = 0, history_1 = history; _i < history_1.length; _i++) { var entry = history_1[_i]; this._history.add(entry); } }; Object.defineProperty(HistoryNavigator.prototype, "_elements", { get: function () { var elements = []; this._history.forEach(function (e) { return elements.push(e); }); return elements; }, enumerable: true, configurable: true }); return HistoryNavigator; }()); 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[36/*vs/base/common/keyCodes*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/]), function (require, exports, errors_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var KeyCodeStrMap = /** @class */ (function () { function KeyCodeStrMap() { this._keyCodeToStr = []; this._strToKeyCode = Object.create(null); } KeyCodeStrMap.prototype.define = function (keyCode, str) { this._keyCodeToStr[keyCode] = str; this._strToKeyCode[str.toLowerCase()] = keyCode; }; KeyCodeStrMap.prototype.keyCodeToStr = function (keyCode) { return this._keyCodeToStr[keyCode]; }; KeyCodeStrMap.prototype.strToKeyCode = function (str) { return this._strToKeyCode[str.toLowerCase()] || 0 /* Unknown */; }; return KeyCodeStrMap; }()); var uiMap = new KeyCodeStrMap(); var userSettingsUSMap = new KeyCodeStrMap(); var userSettingsGeneralMap = new KeyCodeStrMap(); (function () { function define(keyCode, uiLabel, usUserSettingsLabel, generalUserSettingsLabel) { if (usUserSettingsLabel === void 0) { usUserSettingsLabel = uiLabel; } if (generalUserSettingsLabel === void 0) { generalUserSettingsLabel = usUserSettingsLabel; } uiMap.define(keyCode, uiLabel); userSettingsUSMap.define(keyCode, usUserSettingsLabel); userSettingsGeneralMap.define(keyCode, generalUserSettingsLabel); } define(0 /* Unknown */, 'unknown'); define(1 /* Backspace */, 'Backspace'); define(2 /* Tab */, 'Tab'); define(3 /* Enter */, 'Enter'); define(4 /* Shift */, 'Shift'); define(5 /* Ctrl */, 'Ctrl'); define(6 /* Alt */, 'Alt'); define(7 /* PauseBreak */, 'PauseBreak'); define(8 /* CapsLock */, 'CapsLock'); define(9 /* Escape */, 'Escape'); define(10 /* Space */, 'Space'); define(11 /* PageUp */, 'PageUp'); define(12 /* PageDown */, 'PageDown'); define(13 /* End */, 'End'); define(14 /* Home */, 'Home'); define(15 /* LeftArrow */, 'LeftArrow', 'Left'); define(16 /* UpArrow */, 'UpArrow', 'Up'); define(17 /* RightArrow */, 'RightArrow', 'Right'); define(18 /* DownArrow */, 'DownArrow', 'Down'); define(19 /* Insert */, 'Insert'); define(20 /* Delete */, 'Delete'); define(21 /* KEY_0 */, '0'); define(22 /* KEY_1 */, '1'); define(23 /* KEY_2 */, '2'); define(24 /* KEY_3 */, '3'); define(25 /* KEY_4 */, '4'); define(26 /* KEY_5 */, '5'); define(27 /* KEY_6 */, '6'); define(28 /* KEY_7 */, '7'); define(29 /* KEY_8 */, '8'); define(30 /* KEY_9 */, '9'); define(31 /* KEY_A */, 'A'); define(32 /* KEY_B */, 'B'); define(33 /* KEY_C */, 'C'); define(34 /* KEY_D */, 'D'); define(35 /* KEY_E */, 'E'); define(36 /* KEY_F */, 'F'); define(37 /* KEY_G */, 'G'); define(38 /* KEY_H */, 'H'); define(39 /* KEY_I */, 'I'); define(40 /* KEY_J */, 'J'); define(41 /* KEY_K */, 'K'); define(42 /* KEY_L */, 'L'); define(43 /* KEY_M */, 'M'); define(44 /* KEY_N */, 'N'); define(45 /* KEY_O */, 'O'); define(46 /* KEY_P */, 'P'); define(47 /* KEY_Q */, 'Q'); define(48 /* KEY_R */, 'R'); define(49 /* KEY_S */, 'S'); define(50 /* KEY_T */, 'T'); define(51 /* KEY_U */, 'U'); define(52 /* KEY_V */, 'V'); define(53 /* KEY_W */, 'W'); define(54 /* KEY_X */, 'X'); define(55 /* KEY_Y */, 'Y'); define(56 /* KEY_Z */, 'Z'); define(57 /* Meta */, 'Meta'); define(58 /* ContextMenu */, 'ContextMenu'); define(59 /* F1 */, 'F1'); define(60 /* F2 */, 'F2'); define(61 /* F3 */, 'F3'); define(62 /* F4 */, 'F4'); define(63 /* F5 */, 'F5'); define(64 /* F6 */, 'F6'); define(65 /* F7 */, 'F7'); define(66 /* F8 */, 'F8'); define(67 /* F9 */, 'F9'); define(68 /* F10 */, 'F10'); define(69 /* F11 */, 'F11'); define(70 /* F12 */, 'F12'); define(71 /* F13 */, 'F13'); define(72 /* F14 */, 'F14'); define(73 /* F15 */, 'F15'); define(74 /* F16 */, 'F16'); define(75 /* F17 */, 'F17'); define(76 /* F18 */, 'F18'); define(77 /* F19 */, 'F19'); define(78 /* NumLock */, 'NumLock'); define(79 /* ScrollLock */, 'ScrollLock'); define(80 /* US_SEMICOLON */, ';', ';', 'OEM_1'); define(81 /* US_EQUAL */, '=', '=', 'OEM_PLUS'); define(82 /* US_COMMA */, ',', ',', 'OEM_COMMA'); define(83 /* US_MINUS */, '-', '-', 'OEM_MINUS'); define(84 /* US_DOT */, '.', '.', 'OEM_PERIOD'); define(85 /* US_SLASH */, '/', '/', 'OEM_2'); define(86 /* US_BACKTICK */, '`', '`', 'OEM_3'); define(110 /* ABNT_C1 */, 'ABNT_C1'); define(111 /* ABNT_C2 */, 'ABNT_C2'); define(87 /* US_OPEN_SQUARE_BRACKET */, '[', '[', 'OEM_4'); define(88 /* US_BACKSLASH */, '\\', '\\', 'OEM_5'); define(89 /* US_CLOSE_SQUARE_BRACKET */, ']', ']', 'OEM_6'); define(90 /* US_QUOTE */, '\'', '\'', 'OEM_7'); define(91 /* OEM_8 */, 'OEM_8'); define(92 /* OEM_102 */, 'OEM_102'); define(93 /* NUMPAD_0 */, 'NumPad0'); define(94 /* NUMPAD_1 */, 'NumPad1'); define(95 /* NUMPAD_2 */, 'NumPad2'); define(96 /* NUMPAD_3 */, 'NumPad3'); define(97 /* NUMPAD_4 */, 'NumPad4'); define(98 /* NUMPAD_5 */, 'NumPad5'); define(99 /* NUMPAD_6 */, 'NumPad6'); define(100 /* NUMPAD_7 */, 'NumPad7'); define(101 /* NUMPAD_8 */, 'NumPad8'); define(102 /* NUMPAD_9 */, 'NumPad9'); define(103 /* NUMPAD_MULTIPLY */, 'NumPad_Multiply'); define(104 /* NUMPAD_ADD */, 'NumPad_Add'); define(105 /* NUMPAD_SEPARATOR */, 'NumPad_Separator'); define(106 /* NUMPAD_SUBTRACT */, 'NumPad_Subtract'); define(107 /* NUMPAD_DECIMAL */, 'NumPad_Decimal'); define(108 /* NUMPAD_DIVIDE */, 'NumPad_Divide'); })(); var KeyCodeUtils; (function (KeyCodeUtils) { function toString(keyCode) { return uiMap.keyCodeToStr(keyCode); } KeyCodeUtils.toString = toString; function fromString(key) { return uiMap.strToKeyCode(key); } KeyCodeUtils.fromString = fromString; function toUserSettingsUS(keyCode) { return userSettingsUSMap.keyCodeToStr(keyCode); } KeyCodeUtils.toUserSettingsUS = toUserSettingsUS; function toUserSettingsGeneral(keyCode) { return userSettingsGeneralMap.keyCodeToStr(keyCode); } KeyCodeUtils.toUserSettingsGeneral = toUserSettingsGeneral; function fromUserSettings(key) { return userSettingsUSMap.strToKeyCode(key) || userSettingsGeneralMap.strToKeyCode(key); } KeyCodeUtils.fromUserSettings = fromUserSettings; })(KeyCodeUtils = exports.KeyCodeUtils || (exports.KeyCodeUtils = {})); function KeyChord(firstPart, secondPart) { var chordPart = ((secondPart & 0x0000FFFF) << 16) >>> 0; return (firstPart | chordPart) >>> 0; } exports.KeyChord = KeyChord; function createKeybinding(keybinding, OS) { if (keybinding === 0) { return null; } var firstPart = (keybinding & 0x0000FFFF) >>> 0; var chordPart = (keybinding & 0xFFFF0000) >>> 16; if (chordPart !== 0) { return new ChordKeybinding([ createSimpleKeybinding(firstPart, OS), createSimpleKeybinding(chordPart, OS) ]); } return new ChordKeybinding([createSimpleKeybinding(firstPart, OS)]); } exports.createKeybinding = createKeybinding; function createSimpleKeybinding(keybinding, OS) { var ctrlCmd = (keybinding & 2048 /* CtrlCmd */ ? true : false); var winCtrl = (keybinding & 256 /* WinCtrl */ ? true : false); var ctrlKey = (OS === 2 /* Macintosh */ ? winCtrl : ctrlCmd); var shiftKey = (keybinding & 1024 /* Shift */ ? true : false); var altKey = (keybinding & 512 /* Alt */ ? true : false); var metaKey = (OS === 2 /* Macintosh */ ? ctrlCmd : winCtrl); var keyCode = (keybinding & 255 /* KeyCode */); return new SimpleKeybinding(ctrlKey, shiftKey, altKey, metaKey, keyCode); } exports.createSimpleKeybinding = createSimpleKeybinding; var SimpleKeybinding = /** @class */ (function () { function SimpleKeybinding(ctrlKey, shiftKey, altKey, metaKey, keyCode) { this.ctrlKey = ctrlKey; this.shiftKey = shiftKey; this.altKey = altKey; this.metaKey = metaKey; this.keyCode = keyCode; } SimpleKeybinding.prototype.equals = function (other) { return (this.ctrlKey === other.ctrlKey && this.shiftKey === other.shiftKey && this.altKey === other.altKey && this.metaKey === other.metaKey && this.keyCode === other.keyCode); }; SimpleKeybinding.prototype.isModifierKey = function () { return (this.keyCode === 0 /* Unknown */ || this.keyCode === 5 /* Ctrl */ || this.keyCode === 57 /* Meta */ || this.keyCode === 6 /* Alt */ || this.keyCode === 4 /* Shift */); }; SimpleKeybinding.prototype.toChord = function () { return new ChordKeybinding([this]); }; /** * Does this keybinding refer to the key code of a modifier and it also has the modifier flag? */ SimpleKeybinding.prototype.isDuplicateModifierCase = function () { return ((this.ctrlKey && this.keyCode === 5 /* Ctrl */) || (this.shiftKey && this.keyCode === 4 /* Shift */) || (this.altKey && this.keyCode === 6 /* Alt */) || (this.metaKey && this.keyCode === 57 /* Meta */)); }; return SimpleKeybinding; }()); exports.SimpleKeybinding = SimpleKeybinding; var ChordKeybinding = /** @class */ (function () { function ChordKeybinding(parts) { if (parts.length === 0) { throw errors_1.illegalArgument("parts"); } this.parts = parts; } ChordKeybinding.prototype.equals = function (other) { if (other === null) { return false; } if (this.parts.length !== other.parts.length) { return false; } for (var i = 0; i < this.parts.length; i++) { if (!this.parts[i].equals(other.parts[i])) { return false; } } return true; }; return ChordKeybinding; }()); exports.ChordKeybinding = ChordKeybinding; var ResolvedKeybindingPart = /** @class */ (function () { function ResolvedKeybindingPart(ctrlKey, shiftKey, altKey, metaKey, kbLabel, kbAriaLabel) { this.ctrlKey = ctrlKey; this.shiftKey = shiftKey; this.altKey = altKey; this.metaKey = metaKey; this.keyLabel = kbLabel; this.keyAriaLabel = kbAriaLabel; } return ResolvedKeybindingPart; }()); exports.ResolvedKeybindingPart = ResolvedKeybindingPart; /** * A resolved keybinding. Can be a simple keybinding or a chord keybinding. */ var ResolvedKeybinding = /** @class */ (function () { function ResolvedKeybinding() { } return ResolvedKeybinding; }()); exports.ResolvedKeybinding = ResolvedKeybinding; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[128/*vs/base/common/lazy*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Lazy = /** @class */ (function () { function Lazy(executor) { this.executor = executor; this._didRun = false; } /** * Get the wrapped value. * * This will force evaluation of the lazy value if it has not been resolved yet. Lazy values are only * resolved once. `getValue` will re-throw exceptions that are hit while resolving the value */ Lazy.prototype.getValue = function () { if (!this._didRun) { try { this._value = this.executor(); } catch (err) { this._error = err; } finally { this._didRun = true; } } if (this._error) { throw this._error; } return this._value; }; Object.defineProperty(Lazy.prototype, "rawValue", { /** * Get the wrapped value without forcing evaluation. */ get: function () { return this._value; }, enumerable: true, configurable: true }); return Lazy; }()); exports.Lazy = Lazy; }); define(__m[2/*vs/base/common/lifecycle*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Enables logging of potentially leaked disposables. * * A disposable is considered leaked if it is not disposed or not registered as the child of * another disposable. This tracking is very simple an only works for classes that either * extend Disposable or use a DisposableStore. This means there are a lot of false positives. */ var TRACK_DISPOSABLES = false; var __is_disposable_tracked__ = '__is_disposable_tracked__'; function markTracked(x) { if (!TRACK_DISPOSABLES) { return; } if (x && x !== Disposable.None) { try { x[__is_disposable_tracked__] = true; } catch (_a) { // noop } } } function trackDisposable(x) { if (!TRACK_DISPOSABLES) { return x; } var stack = new Error('Potentially leaked disposable').stack; setTimeout(function () { if (!x[__is_disposable_tracked__]) { console.log(stack); } }, 3000); return x; } function isDisposable(thing) { return typeof thing.dispose === 'function' && thing.dispose.length === 0; } exports.isDisposable = isDisposable; function dispose(disposables) { if (Array.isArray(disposables)) { disposables.forEach(function (d) { if (d) { markTracked(d); d.dispose(); } }); return []; } else if (disposables) { markTracked(disposables); disposables.dispose(); return disposables; } else { return undefined; } } exports.dispose = dispose; function combinedDisposable() { var disposables = []; for (var _i = 0; _i < arguments.length; _i++) { disposables[_i] = arguments[_i]; } disposables.forEach(markTracked); return trackDisposable({ dispose: function () { return dispose(disposables); } }); } exports.combinedDisposable = combinedDisposable; function toDisposable(fn) { var self = trackDisposable({ dispose: function () { markTracked(self); fn(); } }); return self; } exports.toDisposable = toDisposable; var DisposableStore = /** @class */ (function () { function DisposableStore() { this._toDispose = new Set(); this._isDisposed = false; } /** * Dispose of all registered disposables and mark this object as disposed. * * Any future disposables added to this object will be disposed of on `add`. */ DisposableStore.prototype.dispose = function () { if (this._isDisposed) { return; } markTracked(this); this._isDisposed = true; this.clear(); }; /** * Dispose of all registered disposables but do not mark this object as disposed. */ DisposableStore.prototype.clear = function () { this._toDispose.forEach(function (item) { return item.dispose(); }); this._toDispose.clear(); }; DisposableStore.prototype.add = function (t) { if (!t) { return t; } if (t === this) { throw new Error('Cannot register a disposable on itself!'); } markTracked(t); if (this._isDisposed) { console.warn(new Error('Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!').stack); } else { this._toDispose.add(t); } return t; }; return DisposableStore; }()); exports.DisposableStore = DisposableStore; var Disposable = /** @class */ (function () { function Disposable() { this._store = new DisposableStore(); trackDisposable(this); } Disposable.prototype.dispose = function () { markTracked(this); this._store.dispose(); }; Disposable.prototype._register = function (t) { if (t === this) { throw new Error('Cannot register a disposable on itself!'); } return this._store.add(t); }; Disposable.None = Object.freeze({ dispose: function () { } }); return Disposable; }()); exports.Disposable = Disposable; /** * Manages the lifecycle of a disposable value that may be changed. * * This ensures that when the disposable value is changed, the previously held disposable is disposed of. You can * also register a `MutableDisposable` on a `Disposable` to ensure it is automatically cleaned up. */ var MutableDisposable = /** @class */ (function () { function MutableDisposable() { this._isDisposed = false; trackDisposable(this); } Object.defineProperty(MutableDisposable.prototype, "value", { get: function () { return this._isDisposed ? undefined : this._value; }, set: function (value) { if (this._isDisposed || value === this._value) { return; } if (this._value) { this._value.dispose(); } if (value) { markTracked(value); } this._value = value; }, enumerable: true, configurable: true }); MutableDisposable.prototype.clear = function () { this.value = undefined; }; MutableDisposable.prototype.dispose = function () { this._isDisposed = true; markTracked(this); if (this._value) { this._value.dispose(); } this._value = undefined; }; return MutableDisposable; }()); exports.MutableDisposable = MutableDisposable; var ImmortalReference = /** @class */ (function () { function ImmortalReference(object) { this.object = object; } ImmortalReference.prototype.dispose = function () { }; return ImmortalReference; }()); exports.ImmortalReference = ImmortalReference; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[76/*vs/base/common/linkedList*/], __M([0/*require*/,1/*exports*/,54/*vs/base/common/iterator*/]), function (require, exports, iterator_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Node = /** @class */ (function () { function Node(element) { this.element = element; this.next = Node.Undefined; this.prev = Node.Undefined; } Node.Undefined = new Node(undefined); return Node; }()); var LinkedList = /** @class */ (function () { function LinkedList() { this._first = Node.Undefined; this._last = Node.Undefined; this._size = 0; } Object.defineProperty(LinkedList.prototype, "size", { get: function () { return this._size; }, enumerable: true, configurable: true }); LinkedList.prototype.isEmpty = function () { return this._first === Node.Undefined; }; LinkedList.prototype.clear = function () { this._first = Node.Undefined; this._last = Node.Undefined; this._size = 0; }; LinkedList.prototype.unshift = function (element) { return this._insert(element, false); }; LinkedList.prototype.push = function (element) { return this._insert(element, true); }; LinkedList.prototype._insert = function (element, atTheEnd) { var _this = this; var newNode = new Node(element); if (this._first === Node.Undefined) { this._first = newNode; this._last = newNode; } else if (atTheEnd) { // push var oldLast = this._last; this._last = newNode; newNode.prev = oldLast; oldLast.next = newNode; } else { // unshift var oldFirst = this._first; this._first = newNode; newNode.next = oldFirst; oldFirst.prev = newNode; } this._size += 1; var didRemove = false; return function () { if (!didRemove) { didRemove = true; _this._remove(newNode); } }; }; LinkedList.prototype.shift = function () { if (this._first === Node.Undefined) { return undefined; } else { var res = this._first.element; this._remove(this._first); return res; } }; LinkedList.prototype.pop = function () { if (this._last === Node.Undefined) { return undefined; } else { var res = this._last.element; this._remove(this._last); return res; } }; LinkedList.prototype._remove = function (node) { if (node.prev !== Node.Undefined && node.next !== Node.Undefined) { // middle var anchor = node.prev; anchor.next = node.next; node.next.prev = anchor; } else if (node.prev === Node.Undefined && node.next === Node.Undefined) { // only node this._first = Node.Undefined; this._last = Node.Undefined; } else if (node.next === Node.Undefined) { // last this._last = this._last.prev; this._last.next = Node.Undefined; } else if (node.prev === Node.Undefined) { // first this._first = this._first.next; this._first.prev = Node.Undefined; } // done this._size -= 1; }; LinkedList.prototype.iterator = function () { var element; var node = this._first; return { next: function () { if (node === Node.Undefined) { return iterator_1.FIN; } if (!element) { element = { done: false, value: node.element }; } else { element.value = node.element; } node = node.next; return element; } }; }; LinkedList.prototype.toArray = function () { var result = []; for (var node = this._first; node !== Node.Undefined; node = node.next) { result.push(node.element); } return result; }; return LinkedList; }()); exports.LinkedList = LinkedList; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[4/*vs/base/common/event*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,102/*vs/base/common/functional*/,2/*vs/base/common/lifecycle*/,76/*vs/base/common/linkedList*/]), function (require, exports, errors_1, functional_1, lifecycle_1, linkedList_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Event; (function (Event) { Event.None = function () { return lifecycle_1.Disposable.None; }; /** * Given an event, returns another event which only fires once. */ function once(event) { return function (listener, thisArgs, disposables) { if (thisArgs === void 0) { thisArgs = null; } // we need this, in case the event fires during the listener call var didFire = false; var result; result = event(function (e) { if (didFire) { return; } else if (result) { result.dispose(); } else { didFire = true; } return listener.call(thisArgs, e); }, null, disposables); if (didFire) { result.dispose(); } return result; }; } Event.once = once; /** * Given an event and a `map` function, returns another event which maps each element * through the mapping function. */ function map(event, map) { return snapshot(function (listener, thisArgs, disposables) { if (thisArgs === void 0) { thisArgs = null; } return event(function (i) { return listener.call(thisArgs, map(i)); }, null, disposables); }); } Event.map = map; /** * Given an event and an `each` function, returns another identical event and calls * the `each` function per each element. */ function forEach(event, each) { return snapshot(function (listener, thisArgs, disposables) { if (thisArgs === void 0) { thisArgs = null; } return event(function (i) { each(i); listener.call(thisArgs, i); }, null, disposables); }); } Event.forEach = forEach; function filter(event, filter) { return snapshot(function (listener, thisArgs, disposables) { if (thisArgs === void 0) { thisArgs = null; } return event(function (e) { return 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; /** * Given a collection of events, returns a single event which emits * whenever any of the provided events emit. */ function any() { var events = []; for (var _i = 0; _i < arguments.length; _i++) { events[_i] = arguments[_i]; } return function (listener, thisArgs, disposables) { if (thisArgs === void 0) { thisArgs = null; } return lifecycle_1.combinedDisposable.apply(void 0, events.map(function (event) { return event(function (e) { return listener.call(thisArgs, e); }, null, disposables); })); }; } Event.any = any; /** * Given an event and a `merge` function, returns another event which maps each element * and the cumulative result through the `merge` function. Similar to `map`, but with memory. */ function reduce(event, merge, initial) { var output = initial; return map(event, function (e) { output = merge(output, e); return output; }); } Event.reduce = reduce; /** * Given a chain of event processing functions (filter, map, etc), each * function will be invoked per event & per listener. Snapshotting an event * chain allows each function to be invoked just once per event. */ function snapshot(event) { var listener; var emitter = new Emitter({ onFirstListenerAdd: function () { listener = event(emitter.fire, emitter); }, onLastListenerRemove: function () { listener.dispose(); } }); return emitter.event; } Event.snapshot = snapshot; function debounce(event, merge, delay, leading, leakWarningThreshold) { if (delay === void 0) { delay = 100; } if (leading === void 0) { leading = false; } var subscription; var output = undefined; var handle = undefined; var numDebouncedCalls = 0; var emitter = new Emitter({ leakWarningThreshold: leakWarningThreshold, onFirstListenerAdd: function () { subscription = event(function (cur) { numDebouncedCalls++; output = merge(output, cur); if (leading && !handle) { emitter.fire(output); output = undefined; } clearTimeout(handle); handle = setTimeout(function () { var _output = output; output = undefined; handle = undefined; if (!leading || numDebouncedCalls > 1) { emitter.fire(_output); } numDebouncedCalls = 0; }, delay); }); }, onLastListenerRemove: function () { subscription.dispose(); } }); return emitter.event; } Event.debounce = debounce; /** * Given an event, it returns another event which fires only once and as soon as * the input event emits. The event data is the number of millis it took for the * event to fire. */ function stopwatch(event) { var start = new Date().getTime(); return map(once(event), function (_) { return new Date().getTime() - start; }); } Event.stopwatch = stopwatch; /** * Given an event, it returns another event which fires only when the event * element changes. */ function latch(event) { var firstCall = true; var cache; return filter(event, function (value) { var shouldEmit = firstCall || value !== cache; firstCall = false; cache = value; return shouldEmit; }); } Event.latch = latch; /** * Buffers the provided event until a first listener comes * along, at which point fire all the events at once and * pipe the event from then on. * * ```typescript * const emitter = new Emitter(); * const event = emitter.event; * const bufferedEvent = buffer(event); * * emitter.fire(1); * emitter.fire(2); * emitter.fire(3); * // nothing... * * const listener = bufferedEvent(num => console.log(num)); * // 1, 2, 3 * * emitter.fire(4); * // 4 * ``` */ function buffer(event, nextTick, _buffer) { if (nextTick === void 0) { nextTick = false; } if (_buffer === void 0) { _buffer = []; } var buffer = _buffer.slice(); var listener = event(function (e) { if (buffer) { buffer.push(e); } else { emitter.fire(e); } }); var flush = function () { if (buffer) { buffer.forEach(function (e) { return emitter.fire(e); }); } buffer = null; }; var emitter = new Emitter({ onFirstListenerAdd: function () { if (!listener) { listener = event(function (e) { return emitter.fire(e); }); } }, onFirstListenerDidAdd: function () { if (buffer) { if (nextTick) { setTimeout(flush); } else { flush(); } } }, onLastListenerRemove: function () { if (listener) { listener.dispose(); } listener = null; } }); return emitter.event; } Event.buffer = buffer; var ChainableEvent = /** @class */ (function () { function ChainableEvent(event) { this.event = event; } ChainableEvent.prototype.map = function (fn) { return new ChainableEvent(map(this.event, fn)); }; ChainableEvent.prototype.forEach = function (fn) { return new ChainableEvent(forEach(this.event, fn)); }; ChainableEvent.prototype.filter = function (fn) { return new ChainableEvent(filter(this.event, fn)); }; ChainableEvent.prototype.reduce = function (merge, initial) { return new ChainableEvent(reduce(this.event, merge, initial)); }; ChainableEvent.prototype.latch = function () { return new ChainableEvent(latch(this.event)); }; ChainableEvent.prototype.debounce = function (merge, delay, leading, leakWarningThreshold) { if (delay === void 0) { delay = 100; } if (leading === void 0) { leading = false; } return new ChainableEvent(debounce(this.event, merge, delay, leading, leakWarningThreshold)); }; ChainableEvent.prototype.on = function (listener, thisArgs, disposables) { return this.event(listener, thisArgs, disposables); }; ChainableEvent.prototype.once = function (listener, thisArgs, disposables) { return once(this.event)(listener, thisArgs, disposables); }; return ChainableEvent; }()); function chain(event) { return new ChainableEvent(event); } Event.chain = chain; function fromNodeEventEmitter(emitter, eventName, map) { if (map === void 0) { map = function (id) { return id; }; } var fn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return result.fire(map.apply(void 0, args)); }; var onFirstListenerAdd = function () { return emitter.on(eventName, fn); }; var onLastListenerRemove = function () { return emitter.removeListener(eventName, fn); }; var result = new Emitter({ onFirstListenerAdd: onFirstListenerAdd, onLastListenerRemove: onLastListenerRemove }); return result.event; } Event.fromNodeEventEmitter = fromNodeEventEmitter; function fromDOMEventEmitter(emitter, eventName, map) { if (map === void 0) { map = function (id) { return id; }; } var fn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return result.fire(map.apply(void 0, args)); }; var onFirstListenerAdd = function () { return emitter.addEventListener(eventName, fn); }; var onLastListenerRemove = function () { return emitter.removeEventListener(eventName, fn); }; var result = new Emitter({ onFirstListenerAdd: onFirstListenerAdd, onLastListenerRemove: onLastListenerRemove }); return result.event; } Event.fromDOMEventEmitter = fromDOMEventEmitter; function fromPromise(promise) { var emitter = new Emitter(); var shouldEmit = false; promise .then(undefined, function () { return null; }) .then(function () { if (!shouldEmit) { setTimeout(function () { return emitter.fire(undefined); }, 0); } else { emitter.fire(undefined); } }); shouldEmit = true; return emitter.event; } Event.fromPromise = fromPromise; function toPromise(event) { return new Promise(function (c) { return once(event)(c); }); } Event.toPromise = toPromise; })(Event = exports.Event || (exports.Event = {})); var _globalLeakWarningThreshold = -1; var LeakageMonitor = /** @class */ (function () { function LeakageMonitor(customThreshold, name) { if (name === void 0) { name = Math.random().toString(18).slice(2, 5); } this.customThreshold = customThreshold; this.name = name; this._warnCountdown = 0; } LeakageMonitor.prototype.dispose = function () { if (this._stacks) { this._stacks.clear(); } }; LeakageMonitor.prototype.check = function (listenerCount) { var _this = this; var threshold = _globalLeakWarningThreshold; if (typeof this.customThreshold === 'number') { threshold = this.customThreshold; } if (threshold <= 0 || listenerCount < threshold) { return undefined; } if (!this._stacks) { this._stacks = new Map(); } var stack = new Error().stack.split('\n').slice(3).join('\n'); var 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 var topStack_1; var topCount_1 = 0; this._stacks.forEach(function (count, stack) { if (!topStack_1 || topCount_1 < count) { topStack_1 = stack; topCount_1 = count; } }); console.warn("[" + this.name + "] potential listener LEAK detected, having " + listenerCount + " listeners already. MOST frequent listener (" + topCount_1 + "):"); console.warn(topStack_1); } return function () { var count = (_this._stacks.get(stack) || 0); _this._stacks.set(stack, count - 1); }; }; return LeakageMonitor; }()); /** * 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); } } */ var Emitter = /** @class */ (function () { function Emitter(options) { this._disposed = false; this._options = options; this._leakageMon = _globalLeakWarningThreshold > 0 ? new LeakageMonitor(this._options && this._options.leakWarningThreshold) : undefined; } Object.defineProperty(Emitter.prototype, "event", { /** * For the public to allow to subscribe * to events from this Emitter */ get: function () { var _this = this; if (!this._event) { this._event = function (listener, thisArgs, disposables) { if (!_this._listeners) { _this._listeners = new linkedList_1.LinkedList(); } var firstListener = _this._listeners.isEmpty(); if (firstListener && _this._options && _this._options.onFirstListenerAdd) { _this._options.onFirstListenerAdd(_this); } var 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 var removeMonitor; if (_this._leakageMon) { removeMonitor = _this._leakageMon.check(_this._listeners.size); } var result; result = { dispose: function () { if (removeMonitor) { removeMonitor(); } result.dispose = Emitter._noop; if (!_this._disposed) { remove(); if (_this._options && _this._options.onLastListenerRemove) { var 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; }, enumerable: true, configurable: true }); /** * To be kept private to fire an event to * subscribers */ Emitter.prototype.fire = function (event) { 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 (var iter = this._listeners.iterator(), e = iter.next(); !e.done; e = iter.next()) { this._deliveryQueue.push([e.value, event]); } while (this._deliveryQueue.size > 0) { var _a = this._deliveryQueue.shift(), listener = _a[0], event_1 = _a[1]; try { if (typeof listener === 'function') { listener.call(undefined, event_1); } else { listener[0].call(listener[1], event_1); } } catch (e) { errors_1.onUnexpectedError(e); } } } }; Emitter.prototype.dispose = function () { if (this._listeners) { this._listeners.clear(); } if (this._deliveryQueue) { this._deliveryQueue.clear(); } if (this._leakageMon) { this._leakageMon.dispose(); } this._disposed = true; }; Emitter._noop = function () { }; return Emitter; }()); exports.Emitter = Emitter; var PauseableEmitter = /** @class */ (function (_super) { __extends(PauseableEmitter, _super); function PauseableEmitter(options) { var _this = _super.call(this, options) || this; _this._isPaused = 0; _this._eventQueue = new linkedList_1.LinkedList(); _this._mergeFn = options && options.merge; return _this; } PauseableEmitter.prototype.pause = function () { this._isPaused++; }; PauseableEmitter.prototype.resume = function () { 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 var events = this._eventQueue.toArray(); this._eventQueue.clear(); _super.prototype.fire.call(this, 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.prototype.fire.call(this, this._eventQueue.shift()); } } } }; PauseableEmitter.prototype.fire = function (event) { if (this._listeners) { if (this._isPaused !== 0) { this._eventQueue.push(event); } else { _super.prototype.fire.call(this, event); } } }; return PauseableEmitter; }(Emitter)); exports.PauseableEmitter = PauseableEmitter; var EventMultiplexer = /** @class */ (function () { function EventMultiplexer() { var _this = this; this.hasListeners = false; this.events = []; this.emitter = new Emitter({ onFirstListenerAdd: function () { return _this.onFirstListenerAdd(); }, onLastListenerRemove: function () { return _this.onLastListenerRemove(); } }); } Object.defineProperty(EventMultiplexer.prototype, "event", { get: function () { return this.emitter.event; }, enumerable: true, configurable: true }); EventMultiplexer.prototype.add = function (event) { var _this = this; var e = { event: event, listener: null }; this.events.push(e); if (this.hasListeners) { this.hook(e); } var dispose = function () { if (_this.hasListeners) { _this.unhook(e); } var idx = _this.events.indexOf(e); _this.events.splice(idx, 1); }; return lifecycle_1.toDisposable(functional_1.once(dispose)); }; EventMultiplexer.prototype.onFirstListenerAdd = function () { var _this = this; this.hasListeners = true; this.events.forEach(function (e) { return _this.hook(e); }); }; EventMultiplexer.prototype.onLastListenerRemove = function () { var _this = this; this.hasListeners = false; this.events.forEach(function (e) { return _this.unhook(e); }); }; EventMultiplexer.prototype.hook = function (e) { var _this = this; e.listener = e.event(function (r) { return _this.emitter.fire(r); }); }; EventMultiplexer.prototype.unhook = function (e) { if (e.listener) { e.listener.dispose(); } e.listener = null; }; EventMultiplexer.prototype.dispose = function () { this.emitter.dispose(); }; return EventMultiplexer; }()); exports.EventMultiplexer = EventMultiplexer; /** * The EventBufferer is useful in situations in which you want * to delay firing your events during some code. * You can wrap that code and be sure that the event will not * be fired during that wrap. * * ``` * const emitter: Emitter; * const delayer = new EventDelayer(); * const delayedEvent = delayer.wrapEvent(emitter.event); * * delayedEvent(console.log); * * delayer.bufferEvents(() => { * emitter.fire(); // event will not be fired yet * }); * * // event will only be fired at this point * ``` */ var EventBufferer = /** @class */ (function () { function EventBufferer() { this.buffers = []; } EventBufferer.prototype.wrapEvent = function (event) { var _this = this; return function (listener, thisArgs, disposables) { return event(function (i) { var buffer = _this.buffers[_this.buffers.length - 1]; if (buffer) { buffer.push(function () { return listener.call(thisArgs, i); }); } else { listener.call(thisArgs, i); } }, undefined, disposables); }; }; EventBufferer.prototype.bufferEvents = function (fn) { var buffer = []; this.buffers.push(buffer); var r = fn(); this.buffers.pop(); buffer.forEach(function (flush) { return flush(); }); return r; }; return EventBufferer; }()); 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. */ var Relay = /** @class */ (function () { function Relay() { var _this = this; this.listening = false; this.inputEvent = Event.None; this.inputEventListener = lifecycle_1.Disposable.None; this.emitter = new Emitter({ onFirstListenerDidAdd: function () { _this.listening = true; _this.inputEventListener = _this.inputEvent(_this.emitter.fire, _this.emitter); }, onLastListenerRemove: function () { _this.listening = false; _this.inputEventListener.dispose(); } }); this.event = this.emitter.event; } Object.defineProperty(Relay.prototype, "input", { set: function (event) { this.inputEvent = event; if (this.listening) { this.inputEventListener.dispose(); this.inputEventListener = event(this.emitter.fire, this.emitter); } }, enumerable: true, configurable: true }); Relay.prototype.dispose = function () { this.inputEventListener.dispose(); this.emitter.dispose(); }; return Relay; }()); 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[24/*vs/base/browser/browser*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/]), function (require, exports, event_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var WindowManager = /** @class */ (function () { function WindowManager() { // --- Zoom Level this._zoomLevel = 0; this._lastZoomLevelChangeTime = 0; this._onDidChangeZoomLevel = new event_1.Emitter(); this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event; } WindowManager.prototype.getZoomLevel = function () { return this._zoomLevel; }; WindowManager.prototype.getTimeSinceLastZoomLevelChanged = function () { return Date.now() - this._lastZoomLevelChangeTime; }; // --- Pixel Ratio WindowManager.prototype.getPixelRatio = function () { var ctx = document.createElement('canvas').getContext('2d'); var dpr = window.devicePixelRatio || 1; var bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1; return dpr / bsr; }; WindowManager.INSTANCE = new WindowManager(); return WindowManager; }()); function getZoomLevel() { return WindowManager.INSTANCE.getZoomLevel(); } exports.getZoomLevel = getZoomLevel; /** Returns the time (in ms) since the zoom level was changed */ function getTimeSinceLastZoomLevelChanged() { return WindowManager.INSTANCE.getTimeSinceLastZoomLevelChanged(); } exports.getTimeSinceLastZoomLevelChanged = getTimeSinceLastZoomLevelChanged; function onDidChangeZoomLevel(callback) { return WindowManager.INSTANCE.onDidChangeZoomLevel(callback); } exports.onDidChangeZoomLevel = onDidChangeZoomLevel; function getPixelRatio() { return WindowManager.INSTANCE.getPixelRatio(); } exports.getPixelRatio = getPixelRatio; var userAgent = navigator.userAgent; exports.isIE = (userAgent.indexOf('Trident') >= 0); exports.isEdge = (userAgent.indexOf('Edge/') >= 0); exports.isEdgeOrIE = exports.isIE || exports.isEdge; 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.isIPad = (userAgent.indexOf('iPad') >= 0 || (exports.isSafari && navigator.maxTouchPoints > 0)); exports.isEdgeWebView = exports.isEdge && (userAgent.indexOf('WebView/') >= 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[52/*vs/base/browser/event*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/]), function (require, exports, event_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.domEvent = function (element, type, useCapture) { var fn = function (e) { return emitter.fire(e); }; var emitter = new event_1.Emitter({ onFirstListenerAdd: function () { element.addEventListener(type, fn, useCapture); }, onLastListenerRemove: function () { element.removeEventListener(type, fn, useCapture); } }); return emitter.event; }; function stop(event) { return event_1.Event.map(event, function (e) { e.preventDefault(); e.stopPropagation(); return e; }); } exports.stop = stop; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[129/*vs/base/browser/ui/tree/indexTreeModel*/], __M([0/*require*/,1/*exports*/,99/*vs/base/browser/ui/tree/tree*/,19/*vs/base/common/arrays*/,4/*vs/base/common/event*/,54/*vs/base/common/iterator*/]), function (require, exports, tree_1, arrays_1, event_1, iterator_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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'; } var IndexTreeModel = /** @class */ (function () { function IndexTreeModel(user, list, rootElement, options) { if (options === void 0) { options = {}; } this.user = user; this.list = list; this.rootRef = []; this.eventBufferer = new event_1.EventBufferer(); this._onDidChangeCollapseState = new event_1.Emitter(); this.onDidChangeCollapseState = this.eventBufferer.wrapEvent(this._onDidChangeCollapseState.event); this._onDidChangeRenderNodeCount = new event_1.Emitter(); this.onDidChangeRenderNodeCount = this.eventBufferer.wrapEvent(this._onDidChangeRenderNodeCount.event); this._onDidSplice = new event_1.Emitter(); this.onDidSplice = this._onDidSplice.event; this.collapseByDefault = typeof options.collapseByDefault === 'undefined' ? false : options.collapseByDefault; this.filter = options.filter; this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === 'undefined' ? false : options.autoExpandSingleChildren; this.root = { parent: undefined, element: rootElement, children: [], depth: 0, visibleChildrenCount: 0, visibleChildIndex: -1, collapsible: false, collapsed: false, renderNodeCount: 0, visible: true, filterData: undefined }; } IndexTreeModel.prototype.splice = function (location, deleteCount, toInsert, onDidCreateNode, onDidDeleteNode) { var _a; var _this = this; if (location.length === 0) { throw new tree_1.TreeError(this.user, 'Invalid tree location'); } var _b = this.getParentNodeWithListIndex(location), parentNode = _b.parentNode, listIndex = _b.listIndex, revealed = _b.revealed, visible = _b.visible; var treeListElementsToInsert = []; var nodesToInsertIterator = iterator_1.Iterator.map(iterator_1.Iterator.from(toInsert), function (el) { return _this.createTreeNode(el, parentNode, parentNode.visible ? 1 /* Visible */ : 0 /* Hidden */, revealed, treeListElementsToInsert, onDidCreateNode); }); var lastIndex = location[location.length - 1]; // figure out what's the visible child start index right before the // splice point var visibleChildStartIndex = 0; for (var i = lastIndex; i >= 0 && i < parentNode.children.length; i--) { var child = parentNode.children[i]; if (child.visible) { visibleChildStartIndex = child.visibleChildIndex; break; } } var nodesToInsert = []; var insertedVisibleChildrenCount = 0; var renderNodeCount = 0; iterator_1.Iterator.forEach(nodesToInsertIterator, function (child) { nodesToInsert.push(child); renderNodeCount += child.renderNodeCount; if (child.visible) { child.visibleChildIndex = visibleChildStartIndex + insertedVisibleChildrenCount++; } }); var deletedNodes = (_a = parentNode.children).splice.apply(_a, __spreadArrays([lastIndex, deleteCount], nodesToInsert)); // figure out what is the count of deleted visible children var deletedVisibleChildrenCount = 0; for (var _i = 0, deletedNodes_1 = deletedNodes; _i < deletedNodes_1.length; _i++) { var child = deletedNodes_1[_i]; if (child.visible) { deletedVisibleChildrenCount++; } } // and adjust for all visible children after the splice point if (deletedVisibleChildrenCount !== 0) { for (var i = lastIndex + nodesToInsert.length; i < parentNode.children.length; i++) { var child = parentNode.children[i]; if (child.visible) { child.visibleChildIndex -= deletedVisibleChildrenCount; } } } // update parent's visible children count parentNode.visibleChildrenCount += insertedVisibleChildrenCount - deletedVisibleChildrenCount; if (revealed && visible) { var visibleDeleteCount = deletedNodes.reduce(function (r, node) { return r + (node.visible ? node.renderNodeCount : 0); }, 0); this._updateAncestorsRenderNodeCount(parentNode, renderNodeCount - visibleDeleteCount); this.list.splice(listIndex, visibleDeleteCount, treeListElementsToInsert); } if (deletedNodes.length > 0 && onDidDeleteNode) { var visit_1 = function (node) { onDidDeleteNode(node); node.children.forEach(visit_1); }; deletedNodes.forEach(visit_1); } this._onDidSplice.fire({ insertedNodes: nodesToInsert, deletedNodes: deletedNodes }); }; IndexTreeModel.prototype.rerender = function (location) { if (location.length === 0) { throw new tree_1.TreeError(this.user, 'Invalid tree location'); } var _a = this.getTreeNodeWithListIndex(location), node = _a.node, listIndex = _a.listIndex, revealed = _a.revealed; if (revealed) { this.list.splice(listIndex, 1, [node]); } }; IndexTreeModel.prototype.has = function (location) { return this.hasTreeNode(location); }; IndexTreeModel.prototype.getListIndex = function (location) { var _a = this.getTreeNodeWithListIndex(location), listIndex = _a.listIndex, visible = _a.visible, revealed = _a.revealed; return visible && revealed ? listIndex : -1; }; IndexTreeModel.prototype.getListRenderCount = function (location) { return this.getTreeNode(location).renderNodeCount; }; IndexTreeModel.prototype.isCollapsible = function (location) { return this.getTreeNode(location).collapsible; }; IndexTreeModel.prototype.setCollapsible = function (location, collapsible) { var _this = this; var node = this.getTreeNode(location); if (typeof collapsible === 'undefined') { collapsible = !node.collapsible; } var update = { collapsible: collapsible }; return this.eventBufferer.bufferEvents(function () { return _this._setCollapseState(location, update); }); }; IndexTreeModel.prototype.isCollapsed = function (location) { return this.getTreeNode(location).collapsed; }; IndexTreeModel.prototype.setCollapsed = function (location, collapsed, recursive) { var _this = this; var node = this.getTreeNode(location); if (typeof collapsed === 'undefined') { collapsed = !node.collapsed; } var update = { collapsed: collapsed, recursive: recursive || false }; return this.eventBufferer.bufferEvents(function () { return _this._setCollapseState(location, update); }); }; IndexTreeModel.prototype._setCollapseState = function (location, update) { var _a = this.getTreeNodeWithListIndex(location), node = _a.node, listIndex = _a.listIndex, revealed = _a.revealed; var result = this._setListNodeCollapseState(node, listIndex, revealed, update); if (node !== this.root && this.autoExpandSingleChildren && result && !isCollapsibleStateUpdate(update) && node.collapsible && !node.collapsed && !update.recursive) { var onlyVisibleChildIndex = -1; for (var i = 0; i < node.children.length; i++) { var child = node.children[i]; if (child.visible) { if (onlyVisibleChildIndex > -1) { onlyVisibleChildIndex = -1; break; } else { onlyVisibleChildIndex = i; } } } if (onlyVisibleChildIndex > -1) { this._setCollapseState(__spreadArrays(location, [onlyVisibleChildIndex]), update); } } return result; }; IndexTreeModel.prototype._setListNodeCollapseState = function (node, listIndex, revealed, update) { var result = this._setNodeCollapseState(node, update, false); if (!revealed || !node.visible || !result) { return result; } var previousRenderNodeCount = node.renderNodeCount; var toInsert = this.updateNodeAfterCollapseChange(node); var deleteCount = previousRenderNodeCount - (listIndex === -1 ? 0 : 1); this.list.splice(listIndex + 1, deleteCount, toInsert.slice(1)); return result; }; IndexTreeModel.prototype._setNodeCollapseState = function (node, update, deep) { var 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: node, deep: deep }); } } if (!isCollapsibleStateUpdate(update) && update.recursive) { for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; result = this._setNodeCollapseState(child, update, true) || result; } } return result; }; IndexTreeModel.prototype.expandTo = function (location) { var _this = this; this.eventBufferer.bufferEvents(function () { var 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 }); } } }); }; IndexTreeModel.prototype.refilter = function () { var previousRenderNodeCount = this.root.renderNodeCount; var toInsert = this.updateNodeAfterFilterChange(this.root); this.list.splice(0, previousRenderNodeCount, toInsert); }; IndexTreeModel.prototype.createTreeNode = function (treeElement, parent, parentVisibility, revealed, treeListElements, onDidCreateNode) { var _this = this; var node = { parent: 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, visible: true, filterData: undefined }; var visibility = this._filterNode(node, parentVisibility); if (revealed) { treeListElements.push(node); } var childElements = iterator_1.Iterator.from(treeElement.children); var childRevealed = revealed && visibility !== 0 /* Hidden */ && !node.collapsed; var childNodes = iterator_1.Iterator.map(childElements, function (el) { return _this.createTreeNode(el, node, visibility, childRevealed, treeListElements, onDidCreateNode); }); var visibleChildrenCount = 0; var renderNodeCount = 1; iterator_1.Iterator.forEach(childNodes, function (child) { 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; }; IndexTreeModel.prototype.updateNodeAfterCollapseChange = function (node) { var previousRenderNodeCount = node.renderNodeCount; var result = []; this._updateNodeAfterCollapseChange(node, result); this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount); return result; }; IndexTreeModel.prototype._updateNodeAfterCollapseChange = function (node, result) { if (node.visible === false) { return 0; } result.push(node); node.renderNodeCount = 1; if (!node.collapsed) { for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; node.renderNodeCount += this._updateNodeAfterCollapseChange(child, result); } } this._onDidChangeRenderNodeCount.fire(node); return node.renderNodeCount; }; IndexTreeModel.prototype.updateNodeAfterFilterChange = function (node) { var previousRenderNodeCount = node.renderNodeCount; var result = []; this._updateNodeAfterFilterChange(node, node.visible ? 1 /* Visible */ : 0 /* Hidden */, result); this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount); return result; }; IndexTreeModel.prototype._updateNodeAfterFilterChange = function (node, parentVisibility, result, revealed) { if (revealed === void 0) { revealed = true; } var 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); } } var resultStartLength = result.length; node.renderNodeCount = node === this.root ? 0 : 1; var hasVisibleDescendants = false; if (!node.collapsed || visibility !== 0 /* Hidden */) { var visibleChildIndex = 0; for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; hasVisibleDescendants = this._updateNodeAfterFilterChange(child, visibility, result, revealed && !node.collapsed) || hasVisibleDescendants; if (child.visible) { child.visibleChildIndex = visibleChildIndex++; } } node.visibleChildrenCount = visibleChildIndex; } else { node.visibleChildrenCount = 0; } if (node !== this.root) { node.visible = visibility === 2 /* Recurse */ ? hasVisibleDescendants : (visibility === 1 /* Visible */); } if (!node.visible) { node.renderNodeCount = 0; if (revealed) { result.pop(); } } else if (!node.collapsed) { node.renderNodeCount += result.length - resultStartLength; } this._onDidChangeRenderNodeCount.fire(node); return node.visible; }; IndexTreeModel.prototype._updateAncestorsRenderNodeCount = function (node, diff) { if (diff === 0) { return; } while (node) { node.renderNodeCount += diff; this._onDidChangeRenderNodeCount.fire(node); node = node.parent; } }; IndexTreeModel.prototype._filterNode = function (node, parentVisibility) { var 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 IndexTreeModel.prototype.hasTreeNode = function (location, node) { if (node === void 0) { node = this.root; } if (!location || location.length === 0) { return true; } var index = location[0], rest = location.slice(1); if (index < 0 || index > node.children.length) { return false; } return this.hasTreeNode(rest, node.children[index]); }; // cheap IndexTreeModel.prototype.getTreeNode = function (location, node) { if (node === void 0) { node = this.root; } if (!location || location.length === 0) { return node; } var index = location[0], rest = location.slice(1); 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 IndexTreeModel.prototype.getTreeNodeWithListIndex = function (location) { if (location.length === 0) { return { node: this.root, listIndex: -1, revealed: true, visible: false }; } var _a = this.getParentNodeWithListIndex(location), parentNode = _a.parentNode, listIndex = _a.listIndex, revealed = _a.revealed, visible = _a.visible; var index = location[location.length - 1]; if (index < 0 || index > parentNode.children.length) { throw new tree_1.TreeError(this.user, 'Invalid tree location'); } var node = parentNode.children[index]; return { node: node, listIndex: listIndex, revealed: revealed, visible: visible && node.visible }; }; IndexTreeModel.prototype.getParentNodeWithListIndex = function (location, node, listIndex, revealed, visible) { if (node === void 0) { node = this.root; } if (listIndex === void 0) { listIndex = 0; } if (revealed === void 0) { revealed = true; } if (visible === void 0) { visible = true; } var index = location[0], rest = location.slice(1); if (index < 0 || index > node.children.length) { throw new tree_1.TreeError(this.user, 'Invalid tree location'); } // TODO@joao perf! for (var 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: listIndex, revealed: revealed, visible: visible }; } return this.getParentNodeWithListIndex(rest, node.children[index], listIndex + 1, revealed, visible); }; IndexTreeModel.prototype.getNode = function (location) { if (location === void 0) { location = []; } return this.getTreeNode(location); }; // TODO@joao perf! IndexTreeModel.prototype.getNodeLocation = function (node) { var location = []; var indexTreeNode = node; // typing woes while (indexTreeNode.parent) { location.push(indexTreeNode.parent.children.indexOf(indexTreeNode)); indexTreeNode = indexTreeNode.parent; } return location.reverse(); }; IndexTreeModel.prototype.getParentNodeLocation = function (location) { if (location.length === 0) { return undefined; } else if (location.length === 1) { return []; } else { return arrays_1.tail2(location)[0]; } }; return IndexTreeModel; }()); 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. *--------------------------------------------------------------------------------------------*/ var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; 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; }; define(__m[130/*vs/base/browser/ui/tree/objectTreeModel*/], __M([0/*require*/,1/*exports*/,54/*vs/base/common/iterator*/,129/*vs/base/browser/ui/tree/indexTreeModel*/,99/*vs/base/browser/ui/tree/tree*/,19/*vs/base/common/arrays*/]), function (require, exports, iterator_1, indexTreeModel_1, tree_1, arrays_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ObjectTreeModel = /** @class */ (function () { function ObjectTreeModel(user, list, options) { if (options === void 0) { options = {}; } this.user = user; 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: function (a, b) { return options.sorter.compare(a.element, b.element); } }; } this.identityProvider = options.identityProvider; } ObjectTreeModel.prototype.setChildren = function (element, children, onDidCreateNode, onDidDeleteNode) { var location = this.getElementLocation(element); this._setChildren(location, this.preserveCollapseState(children), onDidCreateNode, onDidDeleteNode); }; ObjectTreeModel.prototype._setChildren = function (location, children, onDidCreateNode, onDidDeleteNode) { var _this = this; var insertedElements = new Set(); var insertedElementIds = new Set(); var _onDidCreateNode = function (node) { insertedElements.add(node.element); _this.nodes.set(node.element, node); if (_this.identityProvider) { var id = _this.identityProvider.getId(node.element).toString(); insertedElementIds.add(id); _this.nodesByIdentity.set(id, node); } if (onDidCreateNode) { onDidCreateNode(node); } }; var _onDidDeleteNode = function (node) { if (!insertedElements.has(node.element)) { _this.nodes.delete(node.element); } if (_this.identityProvider) { var id = _this.identityProvider.getId(node.element).toString(); if (!insertedElementIds.has(id)) { _this.nodesByIdentity.delete(id); } } if (onDidDeleteNode) { onDidDeleteNode(node); } }; this.model.splice(__spreadArrays(location, [0]), Number.MAX_VALUE, children, _onDidCreateNode, _onDidDeleteNode); }; ObjectTreeModel.prototype.preserveCollapseState = function (elements) { var _this = this; var iterator = elements ? iterator_1.getSequenceIterator(elements) : iterator_1.Iterator.empty(); if (this.sorter) { iterator = iterator_1.Iterator.fromArray(arrays_1.mergeSort(iterator_1.Iterator.collect(iterator), this.sorter.compare.bind(this.sorter))); } return iterator_1.Iterator.map(iterator, function (treeElement) { var node = _this.nodes.get(treeElement.element); if (!node && _this.identityProvider) { var id = _this.identityProvider.getId(treeElement.element).toString(); node = _this.nodesByIdentity.get(id); } if (!node) { return __assign(__assign({}, treeElement), { children: _this.preserveCollapseState(treeElement.children) }); } var collapsible = typeof treeElement.collapsible === 'boolean' ? treeElement.collapsible : node.collapsible; var collapsed = typeof treeElement.collapsed !== 'undefined' ? treeElement.collapsed : node.collapsed; return __assign(__assign({}, treeElement), { collapsible: collapsible, collapsed: collapsed, children: _this.preserveCollapseState(treeElement.children) }); }); }; ObjectTreeModel.prototype.rerender = function (element) { var location = this.getElementLocation(element); this.model.rerender(location); }; ObjectTreeModel.prototype.has = function (element) { return this.nodes.has(element); }; ObjectTreeModel.prototype.getListIndex = function (element) { var location = this.getElementLocation(element); return this.model.getListIndex(location); }; ObjectTreeModel.prototype.getListRenderCount = function (element) { var location = this.getElementLocation(element); return this.model.getListRenderCount(location); }; ObjectTreeModel.prototype.isCollapsible = function (element) { var location = this.getElementLocation(element); return this.model.isCollapsible(location); }; ObjectTreeModel.prototype.setCollapsible = function (element, collapsible) { var location = this.getElementLocation(element); return this.model.setCollapsible(location, collapsible); }; ObjectTreeModel.prototype.isCollapsed = function (element) { var location = this.getElementLocation(element); return this.model.isCollapsed(location); }; ObjectTreeModel.prototype.setCollapsed = function (element, collapsed, recursive) { var location = this.getElementLocation(element); return this.model.setCollapsed(location, collapsed, recursive); }; ObjectTreeModel.prototype.expandTo = function (element) { var location = this.getElementLocation(element); this.model.expandTo(location); }; ObjectTreeModel.prototype.refilter = function () { this.model.refilter(); }; ObjectTreeModel.prototype.getNode = function (element) { if (element === void 0) { element = null; } if (element === null) { return this.model.getNode(this.model.rootRef); } var node = this.nodes.get(element); if (!node) { throw new tree_1.TreeError(this.user, "Tree element not found: " + element); } return node; }; ObjectTreeModel.prototype.getNodeLocation = function (node) { return node.element; }; ObjectTreeModel.prototype.getParentNodeLocation = function (element) { if (element === null) { throw new tree_1.TreeError(this.user, "Invalid getParentNodeLocation call"); } var node = this.nodes.get(element); if (!node) { throw new tree_1.TreeError(this.user, "Tree element not found: " + element); } var location = this.model.getNodeLocation(node); var parentLocation = this.model.getParentNodeLocation(location); var parent = this.model.getNode(parentLocation); return parent.element; }; ObjectTreeModel.prototype.getElementLocation = function (element) { if (element === null) { return []; } var node = this.nodes.get(element); if (!node) { throw new tree_1.TreeError(this.user, "Tree element not found: " + element); } return this.model.getNodeLocation(node); }; return ObjectTreeModel; }()); 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[243/*vs/base/browser/ui/tree/compressedObjectTreeModel*/], __M([0/*require*/,1/*exports*/,54/*vs/base/common/iterator*/,4/*vs/base/common/event*/,99/*vs/base/browser/ui/tree/tree*/,130/*vs/base/browser/ui/tree/objectTreeModel*/]), function (require, exports, iterator_1, event_1, tree_1, objectTreeModel_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function noCompress(element) { var elements = [element.element]; var incompressible = element.incompressible || false; return { element: { elements: elements, incompressible: incompressible }, children: iterator_1.Iterator.map(iterator_1.Iterator.from(element.children), noCompress), collapsible: element.collapsible, collapsed: element.collapsed }; } // Exported only for test reasons, do not use directly function compress(element) { var elements = [element.element]; var incompressible = element.incompressible || false; var childrenIterator; var children; while (true) { childrenIterator = iterator_1.Iterator.from(element.children); children = iterator_1.Iterator.collect(childrenIterator, 2); if (children.length !== 1) { break; } element = children[0]; if (element.incompressible) { break; } elements.push(element.element); } return { element: { elements: elements, incompressible: incompressible }, children: iterator_1.Iterator.map(iterator_1.Iterator.concat(iterator_1.Iterator.fromArray(children), childrenIterator), compress), collapsible: element.collapsible, collapsed: element.collapsed }; } exports.compress = compress; function _decompress(element, index) { if (index === void 0) { index = 0; } var children; if (index < element.element.elements.length - 1) { children = iterator_1.Iterator.single(_decompress(element, index + 1)); } else { children = iterator_1.Iterator.map(iterator_1.Iterator.from(element.children), function (el) { return _decompress(el, 0); }); } if (index === 0 && element.element.incompressible) { return { element: element.element.elements[index], children: children, incompressible: true, collapsible: element.collapsible, collapsed: element.collapsed }; } return { element: element.element.elements[index], children: 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 __assign(__assign({}, treeElement), { children: children }); } return __assign(__assign({}, treeElement), { children: iterator_1.Iterator.map(iterator_1.Iterator.from(treeElement.children), function (e) { return splice(e, element, children); }) }); } // Exported only for test reasons, do not use directly var CompressedObjectTreeModel = /** @class */ (function () { function CompressedObjectTreeModel(user, list, options) { if (options === void 0) { options = {}; } this.user = user; this.nodes = new Map(); this.model = new objectTreeModel_1.ObjectTreeModel(user, list, options); this.enabled = typeof options.compressionEnabled === 'undefined' ? true : options.compressionEnabled; } Object.defineProperty(CompressedObjectTreeModel.prototype, "onDidSplice", { get: function () { return this.model.onDidSplice; }, enumerable: true, configurable: true }); Object.defineProperty(CompressedObjectTreeModel.prototype, "onDidChangeCollapseState", { get: function () { return this.model.onDidChangeCollapseState; }, enumerable: true, configurable: true }); CompressedObjectTreeModel.prototype.setChildren = function (element, children) { if (element === null) { var compressedChildren = iterator_1.Iterator.map(iterator_1.Iterator.from(children), this.enabled ? compress : noCompress); this._setChildren(null, compressedChildren); return; } var compressedNode = this.nodes.get(element); if (!compressedNode) { throw new Error('Unknown compressed tree node'); } var node = this.model.getNode(compressedNode); var compressedParentNode = this.model.getParentNodeLocation(compressedNode); var parent = this.model.getNode(compressedParentNode); var decompressedElement = decompress(node); var splicedElement = splice(decompressedElement, element, iterator_1.Iterator.from(children)); var recompressedElement = (this.enabled ? compress : noCompress)(splicedElement); var parentChildren = parent.children .map(function (child) { return child === node ? recompressedElement : child; }); this._setChildren(parent.element, parentChildren); }; CompressedObjectTreeModel.prototype.setCompressionEnabled = function (enabled) { if (enabled === this.enabled) { return; } this.enabled = enabled; var root = this.model.getNode(); var rootChildren = iterator_1.Iterator.from(root.children); var decompressedRootChildren = iterator_1.Iterator.map(rootChildren, decompress); var recompressedRootChildren = iterator_1.Iterator.map(decompressedRootChildren, enabled ? compress : noCompress); this._setChildren(null, recompressedRootChildren); }; CompressedObjectTreeModel.prototype._setChildren = function (node, children) { var _this = this; var insertedElements = new Set(); var _onDidCreateNode = function (node) { for (var _i = 0, _a = node.element.elements; _i < _a.length; _i++) { var element = _a[_i]; insertedElements.add(element); _this.nodes.set(element, node.element); } }; var _onDidDeleteNode = function (node) { for (var _i = 0, _a = node.element.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!insertedElements.has(element)) { _this.nodes.delete(element); } } }; this.model.setChildren(node, children, _onDidCreateNode, _onDidDeleteNode); }; CompressedObjectTreeModel.prototype.has = function (element) { return this.nodes.has(element); }; CompressedObjectTreeModel.prototype.getListIndex = function (location) { var node = this.getCompressedNode(location); return this.model.getListIndex(node); }; CompressedObjectTreeModel.prototype.getListRenderCount = function (location) { var node = this.getCompressedNode(location); return this.model.getListRenderCount(node); }; CompressedObjectTreeModel.prototype.getNode = function (location) { if (typeof location === 'undefined') { return this.model.getNode(); } var node = this.getCompressedNode(location); return this.model.getNode(node); }; // TODO: review this CompressedObjectTreeModel.prototype.getNodeLocation = function (node) { var compressedNode = this.model.getNodeLocation(node); if (compressedNode === null) { return null; } return compressedNode.elements[compressedNode.elements.length - 1]; }; // TODO: review this CompressedObjectTreeModel.prototype.getParentNodeLocation = function (location) { var compressedNode = this.getCompressedNode(location); var parentNode = this.model.getParentNodeLocation(compressedNode); if (parentNode === null) { return null; } return parentNode.elements[parentNode.elements.length - 1]; }; CompressedObjectTreeModel.prototype.isCollapsible = function (location) { var compressedNode = this.getCompressedNode(location); return this.model.isCollapsible(compressedNode); }; CompressedObjectTreeModel.prototype.setCollapsible = function (location, collapsible) { var compressedNode = this.getCompressedNode(location); return this.model.setCollapsible(compressedNode, collapsible); }; CompressedObjectTreeModel.prototype.isCollapsed = function (location) { var compressedNode = this.getCompressedNode(location); return this.model.isCollapsed(compressedNode); }; CompressedObjectTreeModel.prototype.setCollapsed = function (location, collapsed, recursive) { var compressedNode = this.getCompressedNode(location); return this.model.setCollapsed(compressedNode, collapsed, recursive); }; CompressedObjectTreeModel.prototype.expandTo = function (location) { var compressedNode = this.getCompressedNode(location); this.model.expandTo(compressedNode); }; CompressedObjectTreeModel.prototype.rerender = function (location) { var compressedNode = this.getCompressedNode(location); this.model.rerender(compressedNode); }; CompressedObjectTreeModel.prototype.refilter = function () { this.model.refilter(); }; CompressedObjectTreeModel.prototype.getCompressedNode = function (element) { if (element === null) { return null; } var node = this.nodes.get(element); if (!node) { throw new tree_1.TreeError(this.user, "Tree element not found: " + element); } return node; }; return CompressedObjectTreeModel; }()); exports.CompressedObjectTreeModel = CompressedObjectTreeModel; exports.DefaultElementMapper = function (elements) { return elements[elements.length - 1]; }; var CompressedTreeNodeWrapper = /** @class */ (function () { function CompressedTreeNodeWrapper(unwrapper, node) { this.unwrapper = unwrapper; this.node = node; } Object.defineProperty(CompressedTreeNodeWrapper.prototype, "element", { get: function () { return this.node.element === null ? null : this.unwrapper(this.node.element); }, enumerable: true, configurable: true }); Object.defineProperty(CompressedTreeNodeWrapper.prototype, "children", { get: function () { var _this = this; return this.node.children.map(function (node) { return new CompressedTreeNodeWrapper(_this.unwrapper, node); }); }, enumerable: true, configurable: true }); Object.defineProperty(CompressedTreeNodeWrapper.prototype, "depth", { get: function () { return this.node.depth; }, enumerable: true, configurable: true }); Object.defineProperty(CompressedTreeNodeWrapper.prototype, "visibleChildrenCount", { get: function () { return this.node.visibleChildrenCount; }, enumerable: true, configurable: true }); Object.defineProperty(CompressedTreeNodeWrapper.prototype, "visibleChildIndex", { get: function () { return this.node.visibleChildIndex; }, enumerable: true, configurable: true }); Object.defineProperty(CompressedTreeNodeWrapper.prototype, "collapsible", { get: function () { return this.node.collapsible; }, enumerable: true, configurable: true }); Object.defineProperty(CompressedTreeNodeWrapper.prototype, "collapsed", { get: function () { return this.node.collapsed; }, enumerable: true, configurable: true }); Object.defineProperty(CompressedTreeNodeWrapper.prototype, "visible", { get: function () { return this.node.visible; }, enumerable: true, configurable: true }); Object.defineProperty(CompressedTreeNodeWrapper.prototype, "filterData", { get: function () { return this.node.filterData; }, enumerable: true, configurable: true }); return CompressedTreeNodeWrapper; }()); function mapList(nodeMapper, list) { return { splice: function (start, deleteCount, toInsert) { list.splice(start, deleteCount, toInsert.map(function (node) { return nodeMapper.map(node); })); } }; } function mapOptions(compressedNodeUnwrapper, options) { return __assign(__assign({}, options), { sorter: options.sorter && { compare: function (node, otherNode) { return options.sorter.compare(node.elements[0], otherNode.elements[0]); } }, identityProvider: options.identityProvider && { getId: function (node) { return options.identityProvider.getId(compressedNodeUnwrapper(node)); } }, filter: options.filter && { filter: function (node, parentVisibility) { return options.filter.filter(compressedNodeUnwrapper(node), parentVisibility); } } }); } var CompressibleObjectTreeModel = /** @class */ (function () { function CompressibleObjectTreeModel(user, list, options) { var _this = this; if (options === void 0) { options = {}; } this.elementMapper = options.elementMapper || exports.DefaultElementMapper; var compressedNodeUnwrapper = function (node) { return _this.elementMapper(node.elements); }; this.nodeMapper = new tree_1.WeakMapper(function (node) { return new CompressedTreeNodeWrapper(compressedNodeUnwrapper, node); }); this.model = new CompressedObjectTreeModel(user, mapList(this.nodeMapper, list), mapOptions(compressedNodeUnwrapper, options)); } Object.defineProperty(CompressibleObjectTreeModel.prototype, "onDidSplice", { get: function () { var _this = this; return event_1.Event.map(this.model.onDidSplice, function (_a) { var insertedNodes = _a.insertedNodes, deletedNodes = _a.deletedNodes; return ({ insertedNodes: insertedNodes.map(function (node) { return _this.nodeMapper.map(node); }), deletedNodes: deletedNodes.map(function (node) { return _this.nodeMapper.map(node); }), }); }); }, enumerable: true, configurable: true }); Object.defineProperty(CompressibleObjectTreeModel.prototype, "onDidChangeCollapseState", { get: function () { var _this = this; return event_1.Event.map(this.model.onDidChangeCollapseState, function (_a) { var node = _a.node, deep = _a.deep; return ({ node: _this.nodeMapper.map(node), deep: deep }); }); }, enumerable: true, configurable: true }); CompressibleObjectTreeModel.prototype.setChildren = function (element, children) { this.model.setChildren(element, children); }; CompressibleObjectTreeModel.prototype.setCompressionEnabled = function (enabled) { this.model.setCompressionEnabled(enabled); }; CompressibleObjectTreeModel.prototype.has = function (location) { return this.model.has(location); }; CompressibleObjectTreeModel.prototype.getListIndex = function (location) { return this.model.getListIndex(location); }; CompressibleObjectTreeModel.prototype.getListRenderCount = function (location) { return this.model.getListRenderCount(location); }; CompressibleObjectTreeModel.prototype.getNode = function (location) { return this.nodeMapper.map(this.model.getNode(location)); }; CompressibleObjectTreeModel.prototype.getNodeLocation = function (node) { return node.element; }; CompressibleObjectTreeModel.prototype.getParentNodeLocation = function (location) { return this.model.getParentNodeLocation(location); }; CompressibleObjectTreeModel.prototype.isCollapsible = function (location) { return this.model.isCollapsible(location); }; CompressibleObjectTreeModel.prototype.setCollapsible = function (location, collapsed) { return this.model.setCollapsible(location, collapsed); }; CompressibleObjectTreeModel.prototype.isCollapsed = function (location) { return this.model.isCollapsed(location); }; CompressibleObjectTreeModel.prototype.setCollapsed = function (location, collapsed, recursive) { return this.model.setCollapsed(location, collapsed, recursive); }; CompressibleObjectTreeModel.prototype.expandTo = function (location) { return this.model.expandTo(location); }; CompressibleObjectTreeModel.prototype.rerender = function (location) { return this.model.rerender(location); }; CompressibleObjectTreeModel.prototype.refilter = function () { return this.model.refilter(); }; CompressibleObjectTreeModel.prototype.getCompressedTreeNode = function (location) { if (location === void 0) { location = null; } return this.model.getNode(location); }; return CompressibleObjectTreeModel; }()); exports.CompressibleObjectTreeModel = CompressibleObjectTreeModel; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; define(__m[55/*vs/base/common/actions*/], __M([0/*require*/,1/*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 }); var Action = /** @class */ (function (_super) { __extends(Action, _super); function Action(id, label, cssClass, enabled, actionCallback) { if (label === void 0) { label = ''; } if (cssClass === void 0) { cssClass = ''; } if (enabled === void 0) { enabled = true; } var _this = _super.call(this) || this; _this._onDidChange = _this._register(new event_1.Emitter()); _this.onDidChange = _this._onDidChange.event; _this._enabled = true; _this._checked = false; _this._id = id; _this._label = label; _this._cssClass = cssClass; _this._enabled = enabled; _this._actionCallback = actionCallback; return _this; } Object.defineProperty(Action.prototype, "id", { get: function () { return this._id; }, enumerable: true, configurable: true }); Object.defineProperty(Action.prototype, "label", { get: function () { return this._label; }, set: function (value) { this._setLabel(value); }, enumerable: true, configurable: true }); Action.prototype._setLabel = function (value) { if (this._label !== value) { this._label = value; this._onDidChange.fire({ label: value }); } }; Object.defineProperty(Action.prototype, "tooltip", { get: function () { return this._tooltip || ''; }, set: function (value) { this._setTooltip(value); }, enumerable: true, configurable: true }); Action.prototype._setTooltip = function (value) { if (this._tooltip !== value) { this._tooltip = value; this._onDidChange.fire({ tooltip: value }); } }; Object.defineProperty(Action.prototype, "class", { get: function () { return this._cssClass; }, set: function (value) { this._setClass(value); }, enumerable: true, configurable: true }); Action.prototype._setClass = function (value) { if (this._cssClass !== value) { this._cssClass = value; this._onDidChange.fire({ class: value }); } }; Object.defineProperty(Action.prototype, "enabled", { get: function () { return this._enabled; }, set: function (value) { this._setEnabled(value); }, enumerable: true, configurable: true }); Action.prototype._setEnabled = function (value) { if (this._enabled !== value) { this._enabled = value; this._onDidChange.fire({ enabled: value }); } }; Object.defineProperty(Action.prototype, "checked", { get: function () { return this._checked; }, set: function (value) { this._setChecked(value); }, enumerable: true, configurable: true }); Action.prototype._setChecked = function (value) { if (this._checked !== value) { this._checked = value; this._onDidChange.fire({ checked: value }); } }; Action.prototype.run = function (event, _data) { if (this._actionCallback) { return this._actionCallback(event); } return Promise.resolve(true); }; return Action; }(lifecycle_1.Disposable)); exports.Action = Action; var ActionRunner = /** @class */ (function (_super) { __extends(ActionRunner, _super); function ActionRunner() { var _this = _super !== null && _super.apply(this, arguments) || this; _this._onDidBeforeRun = _this._register(new event_1.Emitter()); _this.onDidBeforeRun = _this._onDidBeforeRun.event; _this._onDidRun = _this._register(new event_1.Emitter()); _this.onDidRun = _this._onDidRun.event; return _this; } ActionRunner.prototype.run = function (action, context) { return __awaiter(this, void 0, void 0, function () { var result, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!action.enabled) { return [2 /*return*/, Promise.resolve(null)]; } this._onDidBeforeRun.fire({ action: action }); _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, this.runAction(action, context)]; case 2: result = _a.sent(); this._onDidRun.fire({ action: action, result: result }); return [3 /*break*/, 4]; case 3: error_1 = _a.sent(); this._onDidRun.fire({ action: action, error: error_1 }); return [3 /*break*/, 4]; case 4: return [2 /*return*/]; } }); }); }; ActionRunner.prototype.runAction = function (action, context) { var res = context ? action.run(context) : action.run(); return Promise.resolve(res); }; return ActionRunner; }(lifecycle_1.Disposable)); exports.ActionRunner = ActionRunner; }); /*--------------------------------------------------------------------------------------------- * 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/base/common/cancellation*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/]), function (require, exports, event_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var shortcutEvent = Object.freeze(function (callback, context) { var handle = setTimeout(callback.bind(context), 0); return { dispose: function () { 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 = {})); var MutableToken = /** @class */ (function () { function MutableToken() { this._isCancelled = false; this._emitter = null; } MutableToken.prototype.cancel = function () { if (!this._isCancelled) { this._isCancelled = true; if (this._emitter) { this._emitter.fire(undefined); this.dispose(); } } }; Object.defineProperty(MutableToken.prototype, "isCancellationRequested", { get: function () { return this._isCancelled; }, enumerable: true, configurable: true }); Object.defineProperty(MutableToken.prototype, "onCancellationRequested", { get: function () { if (this._isCancelled) { return shortcutEvent; } if (!this._emitter) { this._emitter = new event_1.Emitter(); } return this._emitter.event; }, enumerable: true, configurable: true }); MutableToken.prototype.dispose = function () { if (this._emitter) { this._emitter.dispose(); this._emitter = null; } }; return MutableToken; }()); var CancellationTokenSource = /** @class */ (function () { function CancellationTokenSource(parent) { this._token = undefined; this._parentListener = undefined; this._parentListener = parent && parent.onCancellationRequested(this.cancel, this); } Object.defineProperty(CancellationTokenSource.prototype, "token", { get: function () { if (!this._token) { // be lazy and create the token only when // actually needed this._token = new MutableToken(); } return this._token; }, enumerable: true, configurable: true }); CancellationTokenSource.prototype.cancel = function () { 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(); } }; CancellationTokenSource.prototype.dispose = function (cancel) { if (cancel === void 0) { 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(); } }; return CancellationTokenSource; }()); 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. *--------------------------------------------------------------------------------------------*/ define(__m[15/*vs/base/common/async*/], __M([0/*require*/,1/*exports*/,26/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/]), function (require, exports, cancellation_1, errors, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isThenable(obj) { return obj && typeof obj.then === 'function'; } exports.isThenable = isThenable; function createCancelablePromise(callback) { var source = new cancellation_1.CancellationTokenSource(); var thenable = callback(source.token); var promise = new Promise(function (resolve, reject) { source.token.onCancellationRequested(function () { reject(errors.canceled()); }); Promise.resolve(thenable).then(function (value) { source.dispose(); resolve(value); }, function (err) { source.dispose(); reject(err); }); }); return new /** @class */ (function () { function class_1() { } class_1.prototype.cancel = function () { source.cancel(); }; class_1.prototype.then = function (resolve, reject) { return promise.then(resolve, reject); }; class_1.prototype.catch = function (reject) { return this.then(undefined, reject); }; class_1.prototype.finally = function (onfinally) { return promise.finally(onfinally); }; return class_1; }()); } exports.createCancelablePromise = createCancelablePromise; function raceCancellation(promise, token, defaultValue) { return Promise.race([promise, new Promise(function (resolve) { return token.onCancellationRequested(function () { return resolve(defaultValue); }); })]); } exports.raceCancellation = raceCancellation; /** * A helper to delay 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(); }); * } */ var Delayer = /** @class */ (function () { function Delayer(defaultDelay) { this.defaultDelay = defaultDelay; this.timeout = null; this.completionPromise = null; this.doResolve = null; this.doReject = null; this.task = null; } Delayer.prototype.trigger = function (task, delay) { var _this = this; if (delay === void 0) { delay = this.defaultDelay; } this.task = task; this.cancelTimeout(); if (!this.completionPromise) { this.completionPromise = new Promise(function (c, e) { _this.doResolve = c; _this.doReject = e; }).then(function () { _this.completionPromise = null; _this.doResolve = null; if (_this.task) { var task_1 = _this.task; _this.task = null; return task_1(); } return undefined; }); } this.timeout = setTimeout(function () { _this.timeout = null; if (_this.doResolve) { _this.doResolve(null); } }, delay); return this.completionPromise; }; Delayer.prototype.isTriggered = function () { return this.timeout !== null; }; Delayer.prototype.cancel = function () { this.cancelTimeout(); if (this.completionPromise) { if (this.doReject) { this.doReject(errors.canceled()); } this.completionPromise = null; } }; Delayer.prototype.cancelTimeout = function () { if (this.timeout !== null) { clearTimeout(this.timeout); this.timeout = null; } }; Delayer.prototype.dispose = function () { this.cancelTimeout(); }; return Delayer; }()); exports.Delayer = Delayer; function timeout(millis, token) { if (!token) { return createCancelablePromise(function (token) { return timeout(millis, token); }); } return new Promise(function (resolve, reject) { var handle = setTimeout(resolve, millis); token.onCancellationRequested(function () { clearTimeout(handle); reject(errors.canceled()); }); }); } exports.timeout = timeout; function disposableTimeout(handler, timeout) { if (timeout === void 0) { timeout = 0; } var timer = setTimeout(handler, timeout); return lifecycle_1.toDisposable(function () { return clearTimeout(timer); }); } exports.disposableTimeout = disposableTimeout; function first(promiseFactories, shouldStop, defaultValue) { if (shouldStop === void 0) { shouldStop = function (t) { return !!t; }; } if (defaultValue === void 0) { defaultValue = null; } var index = 0; var len = promiseFactories.length; var loop = function () { if (index >= len) { return Promise.resolve(defaultValue); } var factory = promiseFactories[index++]; var promise = Promise.resolve(factory()); return promise.then(function (result) { if (shouldStop(result)) { return Promise.resolve(result); } return loop(); }); }; return loop(); } exports.first = first; var TimeoutTimer = /** @class */ (function () { function TimeoutTimer(runner, timeout) { this._token = -1; if (typeof runner === 'function' && typeof timeout === 'number') { this.setIfNotSet(runner, timeout); } } TimeoutTimer.prototype.dispose = function () { this.cancel(); }; TimeoutTimer.prototype.cancel = function () { if (this._token !== -1) { clearTimeout(this._token); this._token = -1; } }; TimeoutTimer.prototype.cancelAndSet = function (runner, timeout) { var _this = this; this.cancel(); this._token = setTimeout(function () { _this._token = -1; runner(); }, timeout); }; TimeoutTimer.prototype.setIfNotSet = function (runner, timeout) { var _this = this; if (this._token !== -1) { // timer is already set return; } this._token = setTimeout(function () { _this._token = -1; runner(); }, timeout); }; return TimeoutTimer; }()); exports.TimeoutTimer = TimeoutTimer; var IntervalTimer = /** @class */ (function () { function IntervalTimer() { this._token = -1; } IntervalTimer.prototype.dispose = function () { this.cancel(); }; IntervalTimer.prototype.cancel = function () { if (this._token !== -1) { clearInterval(this._token); this._token = -1; } }; IntervalTimer.prototype.cancelAndSet = function (runner, interval) { this.cancel(); this._token = setInterval(function () { runner(); }, interval); }; return IntervalTimer; }()); exports.IntervalTimer = IntervalTimer; var RunOnceScheduler = /** @class */ (function () { function RunOnceScheduler(runner, timeout) { this.timeoutToken = -1; this.runner = runner; this.timeout = timeout; this.timeoutHandler = this.onTimeout.bind(this); } /** * Dispose RunOnceScheduler */ RunOnceScheduler.prototype.dispose = function () { this.cancel(); this.runner = null; }; /** * Cancel current scheduled runner (if any). */ RunOnceScheduler.prototype.cancel = function () { if (this.isScheduled()) { clearTimeout(this.timeoutToken); this.timeoutToken = -1; } }; /** * Cancel previous runner (if any) & schedule a new runner. */ RunOnceScheduler.prototype.schedule = function (delay) { if (delay === void 0) { delay = this.timeout; } this.cancel(); this.timeoutToken = setTimeout(this.timeoutHandler, delay); }; /** * Returns true if scheduled. */ RunOnceScheduler.prototype.isScheduled = function () { return this.timeoutToken !== -1; }; RunOnceScheduler.prototype.onTimeout = function () { this.timeoutToken = -1; if (this.runner) { this.doRun(); } }; RunOnceScheduler.prototype.doRun = function () { if (this.runner) { this.runner(); } }; return RunOnceScheduler; }()); exports.RunOnceScheduler = RunOnceScheduler; (function () { if (typeof requestIdleCallback !== 'function' || typeof cancelIdleCallback !== 'function') { var dummyIdle_1 = Object.freeze({ didTimeout: true, timeRemaining: function () { return 15; } }); exports.runWhenIdle = function (runner) { var handle = setTimeout(function () { return runner(dummyIdle_1); }); var disposed = false; return { dispose: function () { if (disposed) { return; } disposed = true; clearTimeout(handle); } }; }; } else { exports.runWhenIdle = function (runner, timeout) { var handle = requestIdleCallback(runner, typeof timeout === 'number' ? { timeout: timeout } : undefined); var disposed = false; return { dispose: function () { 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/ */ var IdleValue = /** @class */ (function () { function IdleValue(executor) { var _this = this; this._didRun = false; this._executor = function () { try { _this._value = executor(); } catch (err) { _this._error = err; } finally { _this._didRun = true; } }; this._handle = exports.runWhenIdle(function () { return _this._executor(); }); } IdleValue.prototype.dispose = function () { this._handle.dispose(); }; IdleValue.prototype.getValue = function () { if (!this._didRun) { this._handle.dispose(); this._executor(); } if (this._error) { throw this._error; } return this._value; }; return IdleValue; }()); exports.IdleValue = IdleValue; }); /*--------------------------------------------------------------------------------------------- * 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/base/browser/ui/scrollbar/scrollbarVisibilityController*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/]), function (require, exports, async_1, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ScrollbarVisibilityController = /** @class */ (function (_super) { __extends(ScrollbarVisibilityController, _super); function ScrollbarVisibilityController(visibility, visibleClassName, invisibleClassName) { var _this = _super.call(this) || this; _this._visibility = visibility; _this._visibleClassName = visibleClassName; _this._invisibleClassName = invisibleClassName; _this._domNode = null; _this._isVisible = false; _this._isNeeded = false; _this._shouldBeVisible = false; _this._revealTimer = _this._register(new async_1.TimeoutTimer()); return _this; } // ----------------- Hide / Reveal ScrollbarVisibilityController.prototype.applyVisibilitySetting = function (shouldBeVisible) { if (this._visibility === 2 /* Hidden */) { return false; } if (this._visibility === 3 /* Visible */) { return true; } return shouldBeVisible; }; ScrollbarVisibilityController.prototype.setShouldBeVisible = function (rawShouldBeVisible) { var shouldBeVisible = this.applyVisibilitySetting(rawShouldBeVisible); if (this._shouldBeVisible !== shouldBeVisible) { this._shouldBeVisible = shouldBeVisible; this.ensureVisibility(); } }; ScrollbarVisibilityController.prototype.setIsNeeded = function (isNeeded) { if (this._isNeeded !== isNeeded) { this._isNeeded = isNeeded; this.ensureVisibility(); } }; ScrollbarVisibilityController.prototype.setDomNode = function (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); }; ScrollbarVisibilityController.prototype.ensureVisibility = function () { if (!this._isNeeded) { // Nothing to be rendered this._hide(false); return; } if (this._shouldBeVisible) { this._reveal(); } else { this._hide(true); } }; ScrollbarVisibilityController.prototype._reveal = function () { var _this = this; if (this._isVisible) { return; } this._isVisible = true; // The CSS animation doesn't play otherwise this._revealTimer.setIfNotSet(function () { if (_this._domNode) { _this._domNode.setClassName(_this._visibleClassName); } }, 0); }; ScrollbarVisibilityController.prototype._hide = function (withFadeAway) { this._revealTimer.cancel(); if (!this._isVisible) { return; } this._isVisible = false; if (this._domNode) { this._domNode.setClassName(this._invisibleClassName + (withFadeAway ? ' fade' : '')); } }; return ScrollbarVisibilityController; }(lifecycle_1.Disposable)); 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[38/*vs/base/common/map*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function values(forEachable) { var result = []; forEachable.forEach(function (value) { return result.push(value); }); return result; } exports.values = values; function keys(map) { var result = []; map.forEach(function (_value, key) { return result.push(key); }); return result; } exports.keys = keys; var StringIterator = /** @class */ (function () { function StringIterator() { this._value = ''; this._pos = 0; } StringIterator.prototype.reset = function (key) { this._value = key; this._pos = 0; return this; }; StringIterator.prototype.next = function () { this._pos += 1; return this; }; StringIterator.prototype.hasNext = function () { return this._pos < this._value.length - 1; }; StringIterator.prototype.cmp = function (a) { var aCode = a.charCodeAt(0); var thisCode = this._value.charCodeAt(this._pos); return aCode - thisCode; }; StringIterator.prototype.value = function () { return this._value[this._pos]; }; return StringIterator; }()); exports.StringIterator = StringIterator; var PathIterator = /** @class */ (function () { function PathIterator(_splitOnBackslash) { if (_splitOnBackslash === void 0) { _splitOnBackslash = true; } this._splitOnBackslash = _splitOnBackslash; } PathIterator.prototype.reset = function (key) { this._value = key.replace(/\\$|\/$/, ''); this._from = 0; this._to = 0; return this.next(); }; PathIterator.prototype.hasNext = function () { return this._to < this._value.length; }; PathIterator.prototype.next = function () { // this._data = key.split(/[\\/]/).filter(s => !!s); this._from = this._to; var justSeps = true; for (; this._to < this._value.length; this._to++) { var 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; }; PathIterator.prototype.cmp = function (a) { var aPos = 0; var aLen = a.length; var thisPos = this._from; while (aPos < aLen && thisPos < this._to) { var cmp = a.charCodeAt(aPos) - this._value.charCodeAt(thisPos); if (cmp !== 0) { return cmp; } aPos += 1; thisPos += 1; } if (aLen === this._to - this._from) { return 0; } else if (aPos < aLen) { return -1; } else { return 1; } }; PathIterator.prototype.value = function () { return this._value.substring(this._from, this._to); }; return PathIterator; }()); exports.PathIterator = PathIterator; var TernarySearchTreeNode = /** @class */ (function () { function TernarySearchTreeNode() { } return TernarySearchTreeNode; }()); var TernarySearchTree = /** @class */ (function () { function TernarySearchTree(segments) { this._iter = segments; } TernarySearchTree.forPaths = function () { return new TernarySearchTree(new PathIterator()); }; TernarySearchTree.forStrings = function () { return new TernarySearchTree(new StringIterator()); }; TernarySearchTree.prototype.clear = function () { this._root = undefined; }; TernarySearchTree.prototype.set = function (key, element) { var iter = this._iter.reset(key); var node; if (!this._root) { this._root = new TernarySearchTreeNode(); this._root.segment = iter.value(); } node = this._root; while (true) { var val = iter.cmp(node.segment); if (val > 0) { // left if (!node.left) { node.left = new TernarySearchTreeNode(); node.left.segment = iter.value(); } node = node.left; } else if (val < 0) { // right if (!node.right) { node.right = new TernarySearchTreeNode(); node.right.segment = iter.value(); } node = node.right; } else if (iter.hasNext()) { // mid iter.next(); if (!node.mid) { node.mid = new TernarySearchTreeNode(); node.mid.segment = iter.value(); } node = node.mid; } else { break; } } var oldElement = node.value; node.value = element; node.key = key; return oldElement; }; TernarySearchTree.prototype.get = function (key) { var iter = this._iter.reset(key); var node = this._root; while (node) { var 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 ? node.value : undefined; }; TernarySearchTree.prototype.findSubstr = function (key) { var iter = this._iter.reset(key); var node = this._root; var candidate = undefined; while (node) { var 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; }; TernarySearchTree.prototype.forEach = function (callback) { this._forEach(this._root, callback); }; TernarySearchTree.prototype._forEach = function (node, callback) { if (node) { // left this._forEach(node.left, callback); // node if (node.value) { // callback(node.value, this._iter.join(parts)); callback(node.value, node.key); } // mid this._forEach(node.mid, callback); // right this._forEach(node.right, callback); } }; return TernarySearchTree; }()); exports.TernarySearchTree = TernarySearchTree; var ResourceMap = /** @class */ (function () { function ResourceMap() { this.map = new Map(); this.ignoreCase = false; // in the future this should be an uri-comparator } ResourceMap.prototype.set = function (resource, value) { this.map.set(this.toKey(resource), value); }; ResourceMap.prototype.get = function (resource) { return this.map.get(this.toKey(resource)); }; ResourceMap.prototype.toKey = function (resource) { var key = resource.toString(); if (this.ignoreCase) { key = key.toLowerCase(); } return key; }; return ResourceMap; }()); exports.ResourceMap = ResourceMap; var LinkedMap = /** @class */ (function () { function LinkedMap() { this._map = new Map(); this._head = undefined; this._tail = undefined; this._size = 0; } LinkedMap.prototype.clear = function () { this._map.clear(); this._head = undefined; this._tail = undefined; this._size = 0; }; Object.defineProperty(LinkedMap.prototype, "size", { get: function () { return this._size; }, enumerable: true, configurable: true }); LinkedMap.prototype.get = function (key, touch) { if (touch === void 0) { touch = 0 /* None */; } var item = this._map.get(key); if (!item) { return undefined; } if (touch !== 0 /* None */) { this.touch(item, touch); } return item.value; }; LinkedMap.prototype.set = function (key, value, touch) { if (touch === void 0) { touch = 0 /* None */; } var item = this._map.get(key); if (item) { item.value = value; if (touch !== 0 /* None */) { this.touch(item, touch); } } else { item = { key: key, value: 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++; } }; LinkedMap.prototype.delete = function (key) { return !!this.remove(key); }; LinkedMap.prototype.remove = function (key) { var item = this._map.get(key); if (!item) { return undefined; } this._map.delete(key); this.removeItem(item); this._size--; return item.value; }; LinkedMap.prototype.forEach = function (callbackfn, thisArg) { var current = this._head; while (current) { if (thisArg) { callbackfn.bind(thisArg)(current.value, current.key, this); } else { callbackfn(current.value, current.key, this); } current = current.next; } }; /* VS Code / Monaco editor runs on es5 which has no Symbol.iterator keys(): IterableIterator { const current = this._head; const iterator: IterableIterator = { [Symbol.iterator]() { return iterator; }, next():IteratorResult { if (current) { const result = { value: current.key, done: false }; current = current.next; return result; } else { return { value: undefined, done: true }; } } }; return iterator; } values(): IterableIterator { const current = this._head; const iterator: IterableIterator = { [Symbol.iterator]() { return iterator; }, next():IteratorResult { if (current) { const result = { value: current.value, done: false }; current = current.next; return result; } else { return { value: undefined, done: true }; } } }; return iterator; } */ LinkedMap.prototype.trimOld = function (newSize) { if (newSize >= this.size) { return; } if (newSize === 0) { this.clear(); return; } var current = this._head; var 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; } }; LinkedMap.prototype.addItemFirst = function (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; }; LinkedMap.prototype.addItemLast = function (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; }; LinkedMap.prototype.removeItem = function (item) { if (item === this._head && item === this._tail) { this._head = undefined; this._tail = undefined; } else if (item === this._head) { // This can only happend if size === 1 which is handle // 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 happend if size === 1 which is handle // by the case above. if (!item.previous) { throw new Error('Invalid list'); } item.previous.next = undefined; this._tail = item.previous; } else { var next = item.next; var previous = item.previous; if (!next || !previous) { throw new Error('Invalid list'); } next.previous = previous; previous.next = next; } item.next = undefined; item.previous = undefined; }; LinkedMap.prototype.touch = function (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; } var next = item.next; var 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; } else if (touch === 2 /* AsNew */) { if (item === this._tail) { return; } var next = item.next; var 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; } }; LinkedMap.prototype.toJSON = function () { var data = []; this.forEach(function (value, key) { data.push([key, value]); }); return data; }; return LinkedMap; }()); exports.LinkedMap = LinkedMap; var LRUCache = /** @class */ (function (_super) { __extends(LRUCache, _super); function LRUCache(limit, ratio) { if (ratio === void 0) { ratio = 1; } var _this = _super.call(this) || this; _this._limit = limit; _this._ratio = Math.min(Math.max(0, ratio), 1); return _this; } LRUCache.prototype.get = function (key) { return _super.prototype.get.call(this, key, 2 /* AsNew */); }; LRUCache.prototype.peek = function (key) { return _super.prototype.get.call(this, key, 0 /* None */); }; LRUCache.prototype.set = function (key, value) { _super.prototype.set.call(this, key, value, 2 /* AsNew */); this.checkTrim(); }; LRUCache.prototype.checkTrim = function () { if (this.size > this._limit) { this.trimOld(Math.round(this._limit * this._ratio)); } }; return LRUCache; }(LinkedMap)); exports.LRUCache = LRUCache; }); /** * marked - a markdown parser * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed) * https://github.com/markedjs/marked */ // BEGIN MONACOCHANGE var __marked_exports; // END MONACOCHANGE ;(function(root) { 'use strict'; /** * Block-Level Grammar */ var block = { newline: /^\n+/, code: /^( {4}[^\n]+\n*)+/, fences: noop, hr: /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/, heading: /^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/, nptable: noop, blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/, list: /^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, html: '^ {0,3}(?:' // optional indentation + '<(script|pre|style)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)' // (1) + '|comment[^\\n]*(\\n+|$)' // (2) + '|<\\?[\\s\\S]*?\\?>\\n*' // (3) + '|\\n*' // (4) + '|\\n*' // (5) + '|)[\\s\\S]*?(?:\\n{2,}|$)' // (6) + '|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) open tag + '|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) closing tag + ')', def: /^ {0,3}\[(label)\]: *\n? *]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/, table: noop, lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/, paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading| {0,3}>|<\/?(?:tag)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)/, text: /^[^\n]+/ }; block._label = /(?!\s*\])(?:\\[\[\]]|[^\[\]])+/; block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/; block.def = edit(block.def) .replace('label', block._label) .replace('title', block._title) .getRegex(); block.bullet = /(?:[*+-]|\d{1,9}\.)/; block.item = /^( *)(bull) ?[^\n]*(?:\n(?!\1bull ?)[^\n]*)*/; block.item = edit(block.item, 'gm') .replace(/bull/g, block.bullet) .getRegex(); block.list = edit(block.list) .replace(/bull/g, block.bullet) .replace('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))') .replace('def', '\\n+(?=' + block.def.source + ')') .getRegex(); block._tag = 'address|article|aside|base|basefont|blockquote|body|caption' + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' + '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr' + '|track|ul'; block._comment = //; block.html = edit(block.html, 'i') .replace('comment', block._comment) .replace('tag', block._tag) .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/) .getRegex(); block.paragraph = edit(block.paragraph) .replace('hr', block.hr) .replace('heading', block.heading) .replace('lheading', block.lheading) .replace('tag', block._tag) // pars can be interrupted by type (6) html blocks .getRegex(); block.blockquote = edit(block.blockquote) .replace('paragraph', block.paragraph) .getRegex(); /** * Normal Block Grammar */ block.normal = merge({}, block); /** * GFM Block Grammar */ block.gfm = merge({}, block.normal, { fences: /^ {0,3}(`{3,}|~{3,})([^`\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/, paragraph: /^/, heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/ }); block.gfm.paragraph = edit(block.paragraph) .replace('(?!', '(?!' + block.gfm.fences.source.replace('\\1', '\\2') + '|' + block.list.source.replace('\\1', '\\3') + '|') .getRegex(); /** * GFM + Tables Block Grammar */ block.tables = merge({}, block.gfm, { nptable: /^ *([^|\n ].*\|.*)\n *([-:]+ *\|[-| :]*)(?:\n((?:.*[^>\n ].*(?:\n|$))*)\n*|$)/, table: /^ *\|(.+)\n *\|?( *[-:]+[-| :]*)(?:\n((?: *[^>\n ].*(?:\n|$))*)\n*|$)/ }); /** * Pedantic grammar */ block.pedantic = merge({}, block.normal, { html: edit( '^ *(?:comment *(?:\\n|\\s*$)' + '|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)' // closed tag + '|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))') .replace('comment', block._comment) .replace(/tag/g, '(?!(?:' + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b') .getRegex(), def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/ }); /** * Block Lexer */ function Lexer(options) { this.tokens = []; this.tokens.links = Object.create(null); this.options = options || marked.defaults; this.rules = block.normal; if (this.options.pedantic) { this.rules = block.pedantic; } else if (this.options.gfm) { if (this.options.tables) { this.rules = block.tables; } else { this.rules = block.gfm; } } } /** * Expose Block Rules */ Lexer.rules = block; /** * Static Lex Method */ Lexer.lex = function(src, options) { var lexer = new Lexer(options); return lexer.lex(src); }; /** * Preprocessing */ Lexer.prototype.lex = function(src) { src = src .replace(/\r\n|\r/g, '\n') .replace(/\t/g, ' ') .replace(/\u00a0/g, ' ') .replace(/\u2424/g, '\n'); return this.token(src, true); }; /** * Lexing */ Lexer.prototype.token = function(src, top) { src = src.replace(/^ +$/gm, ''); var next, loose, cap, bull, b, item, listStart, listItems, t, space, i, tag, l, isordered, istask, ischecked; while (src) { // newline if (cap = this.rules.newline.exec(src)) { src = src.substring(cap[0].length); if (cap[0].length > 1) { this.tokens.push({ type: 'space' }); } } // code if (cap = this.rules.code.exec(src)) { src = src.substring(cap[0].length); cap = cap[0].replace(/^ {4}/gm, ''); this.tokens.push({ type: 'code', text: !this.options.pedantic ? rtrim(cap, '\n') : cap }); continue; } // fences (gfm) if (cap = this.rules.fences.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'code', lang: cap[2] ? cap[2].trim() : cap[2], text: cap[3] || '' }); continue; } // heading if (cap = this.rules.heading.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'heading', depth: cap[1].length, text: cap[2] }); continue; } // table no leading pipe (gfm) if (cap = this.rules.nptable.exec(src)) { item = { type: 'table', header: splitCells(cap[1].replace(/^ *| *\| *$/g, '')), align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : [] }; if (item.header.length === item.align.length) { src = src.substring(cap[0].length); for (i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = 'right'; } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = 'center'; } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = 'left'; } else { item.align[i] = null; } } for (i = 0; i < item.cells.length; i++) { item.cells[i] = splitCells(item.cells[i], item.header.length); } this.tokens.push(item); continue; } } // hr if (cap = this.rules.hr.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'hr' }); continue; } // blockquote if (cap = this.rules.blockquote.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'blockquote_start' }); cap = cap[0].replace(/^ *> ?/gm, ''); // Pass `top` to keep the current // "toplevel" state. This is exactly // how markdown.pl works. this.token(cap, top); this.tokens.push({ type: 'blockquote_end' }); continue; } // list if (cap = this.rules.list.exec(src)) { src = src.substring(cap[0].length); bull = cap[2]; isordered = bull.length > 1; listStart = { type: 'list_start', ordered: isordered, start: isordered ? +bull : '', loose: false }; this.tokens.push(listStart); // Get each top-level item. cap = cap[0].match(this.rules.item); listItems = []; next = false; l = cap.length; i = 0; for (; i < l; i++) { item = cap[i]; // Remove the list item's bullet // so it is seen as the next token. space = item.length; item = item.replace(/^ *([*+-]|\d+\.) */, ''); // Outdent whatever the // list item contains. Hacky. if (~item.indexOf('\n ')) { space -= item.length; item = !this.options.pedantic ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') : item.replace(/^ {1,4}/gm, ''); } // Determine whether the next list item belongs here. // Backpedal if it does not belong in this list. if (i !== l - 1) { b = block.bullet.exec(cap[i + 1])[0]; if (bull.length > 1 ? b.length === 1 : (b.length > 1 || (this.options.smartLists && b !== bull))) { src = cap.slice(i + 1).join('\n') + src; i = l - 1; } } // Determine whether item is loose or not. // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ // for discount behavior. loose = next || /\n\n(?!\s*$)/.test(item); if (i !== l - 1) { next = item.charAt(item.length - 1) === '\n'; if (!loose) loose = next; } if (loose) { listStart.loose = true; } // Check for task list items istask = /^\[[ xX]\] /.test(item); ischecked = undefined; if (istask) { ischecked = item[1] !== ' '; item = item.replace(/^\[[ xX]\] +/, ''); } t = { type: 'list_item_start', task: istask, checked: ischecked, loose: loose }; listItems.push(t); this.tokens.push(t); // Recurse. this.token(item, false); this.tokens.push({ type: 'list_item_end' }); } if (listStart.loose) { l = listItems.length; i = 0; for (; i < l; i++) { listItems[i].loose = true; } } this.tokens.push({ type: 'list_end' }); continue; } // html if (cap = this.rules.html.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: this.options.sanitize ? 'paragraph' : 'html', pre: !this.options.sanitizer && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'), text: cap[0] }); continue; } // def if (top && (cap = this.rules.def.exec(src))) { src = src.substring(cap[0].length); if (cap[3]) cap[3] = cap[3].substring(1, cap[3].length - 1); tag = cap[1].toLowerCase().replace(/\s+/g, ' '); if (!this.tokens.links[tag]) { this.tokens.links[tag] = { href: cap[2], title: cap[3] }; } continue; } // table (gfm) if (cap = this.rules.table.exec(src)) { item = { type: 'table', header: splitCells(cap[1].replace(/^ *| *\| *$/g, '')), align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : [] }; if (item.header.length === item.align.length) { src = src.substring(cap[0].length); for (i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = 'right'; } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = 'center'; } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = 'left'; } else { item.align[i] = null; } } for (i = 0; i < item.cells.length; i++) { item.cells[i] = splitCells( item.cells[i].replace(/^ *\| *| *\| *$/g, ''), item.header.length); } this.tokens.push(item); continue; } } // lheading if (cap = this.rules.lheading.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'heading', depth: cap[2] === '=' ? 1 : 2, text: cap[1] }); continue; } // top-level paragraph if (top && (cap = this.rules.paragraph.exec(src))) { src = src.substring(cap[0].length); this.tokens.push({ type: 'paragraph', text: cap[1].charAt(cap[1].length - 1) === '\n' ? cap[1].slice(0, -1) : cap[1] }); continue; } // text if (cap = this.rules.text.exec(src)) { // Top-level should never reach here. src = src.substring(cap[0].length); this.tokens.push({ type: 'text', text: cap[0] }); continue; } if (src) { throw new Error('Infinite loop on byte: ' + src.charCodeAt(0)); } } return this.tokens; }; /** * Inline-Level Grammar */ var inline = { escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/, url: noop, tag: '^comment' + '|^' // self-closing tag + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. + '|^' // declaration, e.g. + '|^', // CDATA section link: /^!?\[(label)\]\(href(?:\s+(title))?\s*\)/, reflink: /^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/, nolink: /^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/, strong: /^__([^\s_])__(?!_)|^\*\*([^\s*])\*\*(?!\*)|^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)/, em: /^_([^\s_])_(?!_)|^\*([^\s*"<\[])\*(?!\*)|^_([^\s][\s\S]*?[^\s_])_(?!_|[^\spunctuation])|^_([^\s_][\s\S]*?[^\s])_(?!_|[^\spunctuation])|^\*([^\s"<\[][\s\S]*?[^\s*])\*(?!\*)|^\*([^\s*"<\[][\s\S]*?[^\s])\*(?!\*)/, code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/, br: /^( {2,}|\\)\n(?!\s*$)/, del: noop, text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\?@\\[^_{|}~'; inline.em = edit(inline.em).replace(/punctuation/g, inline._punctuation).getRegex(); inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g; inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/; inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/; inline.autolink = edit(inline.autolink) .replace('scheme', inline._scheme) .replace('email', inline._email) .getRegex(); inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/; inline.tag = edit(inline.tag) .replace('comment', block._comment) .replace('attribute', inline._attribute) .getRegex(); inline._label = /(?:\[[^\[\]]*\]|\\[\[\]]?|`[^`]*`|`(?!`)|[^\[\]\\`])*?/; inline._href = /\s*(<(?:\\[<>]?|[^\s<>\\])*>|[^\s\x00-\x1f]*)/; inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/; inline.link = edit(inline.link) .replace('label', inline._label) .replace('href', inline._href) .replace('title', inline._title) .getRegex(); inline.reflink = edit(inline.reflink) .replace('label', inline._label) .getRegex(); /** * Normal Inline Grammar */ inline.normal = merge({}, inline); /** * Pedantic Inline Grammar */ inline.pedantic = merge({}, inline.normal, { strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/, link: edit(/^!?\[(label)\]\((.*?)\)/) .replace('label', inline._label) .getRegex(), reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/) .replace('label', inline._label) .getRegex() }); /** * GFM Inline Grammar */ inline.gfm = merge({}, inline.normal, { escape: edit(inline.escape).replace('])', '~|])').getRegex(), _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/, url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, _backpedal: /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/, del: /^~+(?=\S)([\s\S]*?\S)~+/, text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\/i.test(cap[0])) { this.inLink = false; } if (!this.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { this.inRawBlock = true; } else if (this.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { this.inRawBlock = false; } src = src.substring(cap[0].length); out += this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]) : cap[0]; continue; } // link if (cap = this.rules.link.exec(src)) { var lastParenIndex = findClosingBracket(cap[2], '()'); if (lastParenIndex > -1) { var linkLen = cap[0].length - (cap[2].length - lastParenIndex) - (cap[3] || '').length; cap[2] = cap[2].substring(0, lastParenIndex); cap[0] = cap[0].substring(0, linkLen).trim(); cap[3] = ''; } src = src.substring(cap[0].length); this.inLink = true; href = cap[2]; if (this.options.pedantic) { link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href); if (link) { href = link[1]; title = link[3]; } else { title = ''; } } else { title = cap[3] ? cap[3].slice(1, -1) : ''; } href = href.trim().replace(/^<([\s\S]*)>$/, '$1'); out += this.outputLink(cap, { href: InlineLexer.escapes(href), title: InlineLexer.escapes(title) }); this.inLink = false; continue; } // reflink, nolink if ((cap = this.rules.reflink.exec(src)) || (cap = this.rules.nolink.exec(src))) { src = src.substring(cap[0].length); link = (cap[2] || cap[1]).replace(/\s+/g, ' '); link = this.links[link.toLowerCase()]; if (!link || !link.href) { out += cap[0].charAt(0); src = cap[0].substring(1) + src; continue; } this.inLink = true; out += this.outputLink(cap, link); this.inLink = false; continue; } // strong if (cap = this.rules.strong.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.strong(this.output(cap[4] || cap[3] || cap[2] || cap[1])); continue; } // em if (cap = this.rules.em.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.em(this.output(cap[6] || cap[5] || cap[4] || cap[3] || cap[2] || cap[1])); continue; } // code if (cap = this.rules.code.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.codespan(escape(cap[2].trim(), true)); continue; } // br if (cap = this.rules.br.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.br(); continue; } // del (gfm) if (cap = this.rules.del.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.del(this.output(cap[1])); continue; } // autolink if (cap = this.rules.autolink.exec(src)) { src = src.substring(cap[0].length); if (cap[2] === '@') { text = escape(this.mangle(cap[1])); href = 'mailto:' + text; } else { text = escape(cap[1]); href = text; } out += this.renderer.link(href, null, text); continue; } // url (gfm) if (!this.inLink && (cap = this.rules.url.exec(src))) { if (cap[2] === '@') { text = escape(cap[0]); href = 'mailto:' + text; } else { // do extended autolink path validation do { prevCapZero = cap[0]; cap[0] = this.rules._backpedal.exec(cap[0])[0]; } while (prevCapZero !== cap[0]); text = escape(cap[0]); if (cap[1] === 'www.') { href = 'http://' + text; } else { href = text; } } src = src.substring(cap[0].length); out += this.renderer.link(href, null, text); continue; } // text if (cap = this.rules.text.exec(src)) { src = src.substring(cap[0].length); if (this.inRawBlock) { out += this.renderer.text(cap[0]); } else { out += this.renderer.text(escape(this.smartypants(cap[0]))); } continue; } if (src) { throw new Error('Infinite loop on byte: ' + src.charCodeAt(0)); } } return out; }; InlineLexer.escapes = function(text) { return text ? text.replace(InlineLexer.rules._escapes, '$1') : text; }; /** * Compile Link */ InlineLexer.prototype.outputLink = function(cap, link) { var href = link.href, title = link.title ? escape(link.title) : null; return cap[0].charAt(0) !== '!' ? this.renderer.link(href, title, this.output(cap[1])) : this.renderer.image(href, title, escape(cap[1])); }; /** * Smartypants Transformations */ InlineLexer.prototype.smartypants = function(text) { if (!this.options.smartypants) return text; return text // em-dashes .replace(/---/g, '\u2014') // en-dashes .replace(/--/g, '\u2013') // opening singles .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018') // closing singles & apostrophes .replace(/'/g, '\u2019') // opening doubles .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c') // closing doubles .replace(/"/g, '\u201d') // ellipses .replace(/\.{3}/g, '\u2026'); }; /** * Mangle Links */ InlineLexer.prototype.mangle = function(text) { if (!this.options.mangle) return text; var out = '', l = text.length, i = 0, ch; for (; i < l; i++) { ch = text.charCodeAt(i); if (Math.random() > 0.5) { ch = 'x' + ch.toString(16); } out += '&#' + ch + ';'; } return out; }; /** * Renderer */ function Renderer(options) { this.options = options || marked.defaults; } Renderer.prototype.code = function(code, infostring, escaped) { var lang = (infostring || '').match(/\S*/)[0]; if (this.options.highlight) { var out = this.options.highlight(code, lang); if (out != null && out !== code) { escaped = true; code = out; } } if (!lang) { return '
'
      + (escaped ? code : escape(code, true))
      + '
'; } return '
'
    + (escaped ? code : escape(code, true))
    + '
\n'; }; Renderer.prototype.blockquote = function(quote) { return '
\n' + quote + '
\n'; }; Renderer.prototype.html = function(html) { return html; }; Renderer.prototype.heading = function(text, level, raw, slugger) { if (this.options.headerIds) { return '' + text + '\n'; } // ignore IDs return '' + text + '\n'; }; Renderer.prototype.hr = function() { return this.options.xhtml ? '
\n' : '
\n'; }; Renderer.prototype.list = function(body, ordered, start) { var type = ordered ? 'ol' : 'ul', startatt = (ordered && start !== 1) ? (' start="' + start + '"') : ''; return '<' + type + startatt + '>\n' + body + '\n'; }; Renderer.prototype.listitem = function(text) { return '
  • ' + text + '
  • \n'; }; Renderer.prototype.checkbox = function(checked) { return ' '; }; Renderer.prototype.paragraph = function(text) { return '

    ' + text + '

    \n'; }; Renderer.prototype.table = function(header, body) { if (body) body = '' + body + ''; return '\n' + '\n' + header + '\n' + body + '
    \n'; }; Renderer.prototype.tablerow = function(content) { return '\n' + content + '\n'; }; Renderer.prototype.tablecell = function(content, flags) { var type = flags.header ? 'th' : 'td'; var tag = flags.align ? '<' + type + ' align="' + flags.align + '">' : '<' + type + '>'; return tag + content + '\n'; }; // span level renderer Renderer.prototype.strong = function(text) { return '' + text + ''; }; Renderer.prototype.em = function(text) { return '' + text + ''; }; Renderer.prototype.codespan = function(text) { return '' + text + ''; }; Renderer.prototype.br = function() { return this.options.xhtml ? '
    ' : '
    '; }; Renderer.prototype.del = function(text) { return '' + text + ''; }; Renderer.prototype.link = function(href, title, text) { href = cleanUrl(this.options.sanitize, this.options.baseUrl, href); if (href === null) { return text; } var out = ''; return out; }; Renderer.prototype.image = function(href, title, text) { href = cleanUrl(this.options.sanitize, this.options.baseUrl, href); if (href === null) { return text; } var out = '' + text + '' : '>'; return out; }; Renderer.prototype.text = function(text) { return text; }; /** * TextRenderer * returns only the textual part of the token */ function TextRenderer() {} // no need for block level renderers TextRenderer.prototype.strong = TextRenderer.prototype.em = TextRenderer.prototype.codespan = TextRenderer.prototype.del = TextRenderer.prototype.text = function (text) { return text; }; TextRenderer.prototype.link = TextRenderer.prototype.image = function(href, title, text) { return '' + text; }; TextRenderer.prototype.br = function() { return ''; }; /** * Parsing & Compiling */ function Parser(options) { this.tokens = []; this.token = null; this.options = options || marked.defaults; this.options.renderer = this.options.renderer || new Renderer(); this.renderer = this.options.renderer; this.renderer.options = this.options; this.slugger = new Slugger(); } /** * Static Parse Method */ Parser.parse = function(src, options) { var parser = new Parser(options); return parser.parse(src); }; /** * Parse Loop */ Parser.prototype.parse = function(src) { this.inline = new InlineLexer(src.links, this.options); // use an InlineLexer with a TextRenderer to extract pure text this.inlineText = new InlineLexer( src.links, merge({}, this.options, {renderer: new TextRenderer()}) ); this.tokens = src.reverse(); var out = ''; while (this.next()) { out += this.tok(); } return out; }; /** * Next Token */ Parser.prototype.next = function() { return this.token = this.tokens.pop(); }; /** * Preview Next Token */ Parser.prototype.peek = function() { return this.tokens[this.tokens.length - 1] || 0; }; /** * Parse Text Tokens */ Parser.prototype.parseText = function() { var body = this.token.text; while (this.peek().type === 'text') { body += '\n' + this.next().text; } return this.inline.output(body); }; /** * Parse Current Token */ Parser.prototype.tok = function() { switch (this.token.type) { case 'space': { return ''; } case 'hr': { return this.renderer.hr(); } case 'heading': { return this.renderer.heading( this.inline.output(this.token.text), this.token.depth, unescape(this.inlineText.output(this.token.text)), this.slugger); } case 'code': { return this.renderer.code(this.token.text, this.token.lang, this.token.escaped); } case 'table': { var header = '', body = '', i, row, cell, j; // header cell = ''; for (i = 0; i < this.token.header.length; i++) { cell += this.renderer.tablecell( this.inline.output(this.token.header[i]), { header: true, align: this.token.align[i] } ); } header += this.renderer.tablerow(cell); for (i = 0; i < this.token.cells.length; i++) { row = this.token.cells[i]; cell = ''; for (j = 0; j < row.length; j++) { cell += this.renderer.tablecell( this.inline.output(row[j]), { header: false, align: this.token.align[j] } ); } body += this.renderer.tablerow(cell); } return this.renderer.table(header, body); } case 'blockquote_start': { body = ''; while (this.next().type !== 'blockquote_end') { body += this.tok(); } return this.renderer.blockquote(body); } case 'list_start': { body = ''; var ordered = this.token.ordered, start = this.token.start; while (this.next().type !== 'list_end') { body += this.tok(); } return this.renderer.list(body, ordered, start); } case 'list_item_start': { body = ''; var loose = this.token.loose; var checked = this.token.checked; var task = this.token.task; if (this.token.task) { body += this.renderer.checkbox(checked); } while (this.next().type !== 'list_item_end') { body += !loose && this.token.type === 'text' ? this.parseText() : this.tok(); } return this.renderer.listitem(body, task, checked); } case 'html': { // TODO parse inline content if parameter markdown=1 return this.renderer.html(this.token.text); } case 'paragraph': { return this.renderer.paragraph(this.inline.output(this.token.text)); } case 'text': { return this.renderer.paragraph(this.parseText()); } default: { var errMsg = 'Token with "' + this.token.type + '" type was not found.'; if (this.options.silent) { console.log(errMsg); } else { throw new Error(errMsg); } } } }; /** * Slugger generates header id */ function Slugger () { this.seen = {}; } /** * Convert string to unique id */ Slugger.prototype.slug = function (value) { var slug = value .toLowerCase() .trim() .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '') .replace(/\s/g, '-'); if (this.seen.hasOwnProperty(slug)) { var originalSlug = slug; do { this.seen[originalSlug]++; slug = originalSlug + '-' + this.seen[originalSlug]; } while (this.seen.hasOwnProperty(slug)); } this.seen[slug] = 0; return slug; }; /** * Helpers */ function escape(html, encode) { if (encode) { if (escape.escapeTest.test(html)) { return html.replace(escape.escapeReplace, function (ch) { return escape.replacements[ch]; }); } } else { if (escape.escapeTestNoEncode.test(html)) { return html.replace(escape.escapeReplaceNoEncode, function (ch) { return escape.replacements[ch]; }); } } return html; } escape.escapeTest = /[&<>"']/; escape.escapeReplace = /[&<>"']/g; escape.replacements = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; escape.escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/; escape.escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g; function unescape(html) { // explicitly match decimal, hex, and named HTML entities return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, function(_, n) { n = n.toLowerCase(); if (n === 'colon') return ':'; if (n.charAt(0) === '#') { return n.charAt(1) === 'x' ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1)); } return ''; }); } function edit(regex, opt) { regex = regex.source || regex; opt = opt || ''; return { replace: function(name, val) { val = val.source || val; val = val.replace(/(^|[^\[])\^/g, '$1'); regex = regex.replace(name, val); return this; }, getRegex: function() { return new RegExp(regex, opt); } }; } function cleanUrl(sanitize, base, href) { if (sanitize) { try { var prot = decodeURIComponent(unescape(href)) .replace(/[^\w:]/g, '') .toLowerCase(); } catch (e) { return null; } if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) { return null; } } if (base && !originIndependentUrl.test(href)) { href = resolveUrl(base, href); } try { href = encodeURI(href).replace(/%25/g, '%'); } catch (e) { return null; } return href; } function resolveUrl(base, href) { if (!baseUrls[' ' + base]) { // we can ignore everything in base after the last slash of its path component, // but we might need to add _that_ // https://tools.ietf.org/html/rfc3986#section-3 if (/^[^:]+:\/*[^/]*$/.test(base)) { baseUrls[' ' + base] = base + '/'; } else { baseUrls[' ' + base] = rtrim(base, '/', true); } } base = baseUrls[' ' + base]; if (href.slice(0, 2) === '//') { return base.replace(/:[\s\S]*/, ':') + href; } else if (href.charAt(0) === '/') { return base.replace(/(:\/*[^/]*)[\s\S]*/, '$1') + href; } else { return base + href; } } var baseUrls = {}; var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i; function noop() {} noop.exec = noop; function merge(obj) { var i = 1, target, key; for (; i < arguments.length; i++) { target = arguments[i]; for (key in target) { if (Object.prototype.hasOwnProperty.call(target, key)) { obj[key] = target[key]; } } } return obj; } function splitCells(tableRow, count) { // ensure that every cell-delimiting pipe has a space // before it to distinguish it from an escaped pipe var row = tableRow.replace(/\|/g, function (match, offset, str) { var escaped = false, curr = offset; while (--curr >= 0 && str[curr] === '\\') escaped = !escaped; if (escaped) { // odd number of slashes means | is escaped // so we leave it alone return '|'; } else { // add space before unescaped | return ' |'; } }), cells = row.split(/ \|/), i = 0; if (cells.length > count) { cells.splice(count); } else { while (cells.length < count) cells.push(''); } for (; i < cells.length; i++) { // leading or trailing whitespace is ignored per the gfm spec cells[i] = cells[i].trim().replace(/\\\|/g, '|'); } return cells; } // Remove trailing 'c's. Equivalent to str.replace(/c*$/, ''). // /c*$/ is vulnerable to REDOS. // invert: Remove suffix of non-c chars instead. Default falsey. function rtrim(str, c, invert) { if (str.length === 0) { return ''; } // Length of suffix matching the invert condition. var suffLen = 0; // Step left until we fail to match the invert condition. while (suffLen < str.length) { var currChar = str.charAt(str.length - suffLen - 1); if (currChar === c && !invert) { suffLen++; } else if (currChar !== c && invert) { suffLen++; } else { break; } } return str.substr(0, str.length - suffLen); } function findClosingBracket(str, b) { if (str.indexOf(b[1]) === -1) { return -1; } var level = 0; for (var i = 0; i < str.length; i++) { if (str[i] === '\\') { i++; } else if (str[i] === b[0]) { level++; } else if (str[i] === b[1]) { level--; if (level < 0) { return i; } } } return -1; } /** * 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 (callback || typeof opt === 'function') { if (!callback) { callback = opt; opt = null; } opt = merge({}, marked.defaults, opt || {}); var highlight = opt.highlight, tokens, pending, i = 0; try { tokens = Lexer.lex(src, opt); } catch (e) { return callback(e); } pending = tokens.length; var done = function(err) { if (err) { opt.highlight = highlight; return callback(err); } var out; try { 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 (!pending) return done(); for (; i < tokens.length; i++) { (function(token) { if (token.type !== 'code') { return --pending || done(); } return highlight(token.text, token.lang, function(err, code) { if (err) return done(err); if (code == null || code === token.text) { return --pending || done(); } token.text = code; token.escaped = true; --pending || done(); }); })(tokens[i]); } return; } try { if (opt) opt = merge({}, marked.defaults, opt); return Parser.parse(Lexer.lex(src, opt), opt); } catch (e) { e.message += '\nPlease report this to https://github.com/markedjs/marked.'; if ((opt || marked.defaults).silent) { return '

    An error occurred:

    '
            + escape(e.message + '', true)
            + '
    '; } throw e; } } /** * Options */ marked.options = marked.setOptions = function(opt) { merge(marked.defaults, opt); return marked; }; marked.getDefaults = function () { return { baseUrl: null, breaks: false, gfm: true, headerIds: true, headerPrefix: '', highlight: null, langPrefix: 'language-', mangle: true, pedantic: false, renderer: new Renderer(), sanitize: false, sanitizer: null, silent: false, smartLists: false, smartypants: false, tables: true, xhtml: false }; }; marked.defaults = marked.getDefaults(); /** * Expose */ marked.Parser = Parser; marked.parser = Parser.parse; marked.Renderer = Renderer; marked.TextRenderer = TextRenderer; marked.Lexer = Lexer; marked.lexer = Lexer.lex; marked.InlineLexer = InlineLexer; marked.inlineLexer = InlineLexer.output; marked.Slugger = Slugger; marked.parse = marked; // BEGIN MONACOCHANGE // if (typeof module !== 'undefined' && typeof exports === 'object') { // module.exports = marked; // } else if (typeof define === 'function' && define.amd) { // define(function() { return marked; }); // } else { // root.marked = marked; // } // })(this || (typeof window !== 'undefined' ? window : global)); __marked_exports = marked; }).call(this); // ESM-comment-begin define("vs/base/common/marked/marked", function() { return __marked_exports; }); // ESM-comment-end // ESM-uncomment-begin // export var marked = __marked_exports; // export var Parser = __marked_exports.Parser; // export var parser = __marked_exports.parser; // export var Renderer = __marked_exports.Renderer; // export var TextRenderer = __marked_exports.TextRenderer; // export var Lexer = __marked_exports.Lexer; // export var lexer = __marked_exports.lexer; // export var InlineLexer = __marked_exports.InlineLexer; // export var inlineLexer = __marked_exports.inlineLexer; // export var parse = __marked_exports.parse; // ESM-uncomment-end // END MONACOCHANGE /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[131/*vs/base/common/numbers*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function clamp(value, min, max) { return Math.min(Math.max(value, min), max); } exports.clamp = clamp; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[16/*vs/base/common/platform*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LANGUAGE_DEFAULT = 'en'; var _isWindows = false; var _isMacintosh = false; var _isLinux = false; var _isNative = false; var _isWeb = false; var _isIOS = false; var _locale = undefined; var _language = LANGUAGE_DEFAULT; var _translationsConfigFile = undefined; var _userAgent = undefined; var isElectronRenderer = (typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions.electron !== 'undefined' && process.type === 'renderer'); // OS detection if (typeof navigator === 'object' && !isElectronRenderer) { _userAgent = navigator.userAgent; _isWindows = _userAgent.indexOf('Windows') >= 0; _isMacintosh = _userAgent.indexOf('Macintosh') >= 0; _isIOS = _userAgent.indexOf('Macintosh') >= 0 && !!navigator.maxTouchPoints && navigator.maxTouchPoints > 0; _isLinux = _userAgent.indexOf('Linux') >= 0; _isWeb = true; _locale = navigator.language; _language = _locale; } else if (typeof process === 'object') { _isWindows = (process.platform === 'win32'); _isMacintosh = (process.platform === 'darwin'); _isLinux = (process.platform === 'linux'); _locale = LANGUAGE_DEFAULT; _language = LANGUAGE_DEFAULT; var rawNlsConfig = process.env['VSCODE_NLS_CONFIG']; if (rawNlsConfig) { try { var nlsConfig = JSON.parse(rawNlsConfig); var resolved = nlsConfig.availableLanguages['*']; _locale = nlsConfig.locale; // VSCode's default language is 'en' _language = resolved ? resolved : LANGUAGE_DEFAULT; _translationsConfigFile = nlsConfig._translationsConfigFile; } catch (e) { } } _isNative = true; } var _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; var _globals = (typeof self === 'object' ? self : typeof global === 'object' ? global : {}); exports.globals = _globals; exports.setImmediate = (function defineSetImmediate() { if (exports.globals.setImmediate) { return exports.globals.setImmediate.bind(exports.globals); } if (typeof exports.globals.postMessage === 'function' && !exports.globals.importScripts) { var pending_1 = []; exports.globals.addEventListener('message', function (e) { if (e.data && e.data.vscodeSetImmediateId) { for (var i = 0, len = pending_1.length; i < len; i++) { var candidate = pending_1[i]; if (candidate.id === e.data.vscodeSetImmediateId) { pending_1.splice(i, 1); candidate.callback(); return; } } } }); var lastId_1 = 0; return function (callback) { var myId = ++lastId_1; pending_1.push({ id: myId, callback: callback }); exports.globals.postMessage({ vscodeSetImmediateId: myId }, '*'); }; } if (typeof process !== 'undefined' && typeof process.nextTick === 'function') { return process.nextTick.bind(process); } var _promise = Promise.resolve(); return function (callback) { return _promise.then(callback); }; })(); exports.OS = (_isMacintosh ? 2 /* Macintosh */ : (_isWindows ? 1 /* Windows */ : 3 /* Linux */)); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[88/*vs/base/browser/canIUse*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,16/*vs/base/common/platform*/]), function (require, exports, browser, platform) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * 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)), richText: (function () { if (browser.isIE) { return false; } if (browser.isEdge) { var index = navigator.userAgent.indexOf('Edge/'); var version = parseInt(navigator.userAgent.substring(index + 5, navigator.userAgent.indexOf('.', index)), 10); if (!version || (version >= 12 && version <= 16)) { return false; } } return true; })() }, keyboard: (function () { if (platform.isNative || browser.isStandalone) { return 0 /* Always */; } if (navigator.keyboard || browser.isSafari) { return 1 /* FullScreen */; } return 2 /* None */; })(), touch: 'ontouchstart' in window || navigator.maxTouchPoints > 0 || window.navigator.msMaxTouchPoints > 0, pointerEvents: window.PointerEvent && ('ontouchstart' in window || window.navigator.maxTouchPoints > 0 || navigator.maxTouchPoints > 0 || window.navigator.msMaxTouchPoints > 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[56/*vs/base/browser/keyboardEvent*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,36/*vs/base/common/keyCodes*/,16/*vs/base/common/platform*/]), function (require, exports, browser, keyCodes_1, platform) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var KEY_CODE_MAP = new Array(230); var INVERSE_KEY_CODE_MAP = new Array(112 /* MAX_VALUE */); (function () { for (var i = 0; i < INVERSE_KEY_CODE_MAP.length; i++) { INVERSE_KEY_CODE_MAP[i] = -1; } function define(code, keyCode) { KEY_CODE_MAP[code] = keyCode; INVERSE_KEY_CODE_MAP[keyCode] = code; } define(3, 7 /* PauseBreak */); // VK_CANCEL 0x03 Control-break processing define(8, 1 /* Backspace */); define(9, 2 /* Tab */); define(13, 3 /* Enter */); define(16, 4 /* Shift */); define(17, 5 /* Ctrl */); define(18, 6 /* Alt */); define(19, 7 /* PauseBreak */); define(20, 8 /* CapsLock */); define(27, 9 /* Escape */); define(32, 10 /* Space */); define(33, 11 /* PageUp */); define(34, 12 /* PageDown */); define(35, 13 /* End */); define(36, 14 /* Home */); define(37, 15 /* LeftArrow */); define(38, 16 /* UpArrow */); define(39, 17 /* RightArrow */); define(40, 18 /* DownArrow */); define(45, 19 /* Insert */); define(46, 20 /* Delete */); define(48, 21 /* KEY_0 */); define(49, 22 /* KEY_1 */); define(50, 23 /* KEY_2 */); define(51, 24 /* KEY_3 */); define(52, 25 /* KEY_4 */); define(53, 26 /* KEY_5 */); define(54, 27 /* KEY_6 */); define(55, 28 /* KEY_7 */); define(56, 29 /* KEY_8 */); define(57, 30 /* KEY_9 */); define(65, 31 /* KEY_A */); define(66, 32 /* KEY_B */); define(67, 33 /* KEY_C */); define(68, 34 /* KEY_D */); define(69, 35 /* KEY_E */); define(70, 36 /* KEY_F */); define(71, 37 /* KEY_G */); define(72, 38 /* KEY_H */); define(73, 39 /* KEY_I */); define(74, 40 /* KEY_J */); define(75, 41 /* KEY_K */); define(76, 42 /* KEY_L */); define(77, 43 /* KEY_M */); define(78, 44 /* KEY_N */); define(79, 45 /* KEY_O */); define(80, 46 /* KEY_P */); define(81, 47 /* KEY_Q */); define(82, 48 /* KEY_R */); define(83, 49 /* KEY_S */); define(84, 50 /* KEY_T */); define(85, 51 /* KEY_U */); define(86, 52 /* KEY_V */); define(87, 53 /* KEY_W */); define(88, 54 /* KEY_X */); define(89, 55 /* KEY_Y */); define(90, 56 /* KEY_Z */); define(93, 58 /* ContextMenu */); define(96, 93 /* NUMPAD_0 */); define(97, 94 /* NUMPAD_1 */); define(98, 95 /* NUMPAD_2 */); define(99, 96 /* NUMPAD_3 */); define(100, 97 /* NUMPAD_4 */); define(101, 98 /* NUMPAD_5 */); define(102, 99 /* NUMPAD_6 */); define(103, 100 /* NUMPAD_7 */); define(104, 101 /* NUMPAD_8 */); define(105, 102 /* NUMPAD_9 */); define(106, 103 /* NUMPAD_MULTIPLY */); define(107, 104 /* NUMPAD_ADD */); define(108, 105 /* NUMPAD_SEPARATOR */); define(109, 106 /* NUMPAD_SUBTRACT */); define(110, 107 /* NUMPAD_DECIMAL */); define(111, 108 /* NUMPAD_DIVIDE */); define(112, 59 /* F1 */); define(113, 60 /* F2 */); define(114, 61 /* F3 */); define(115, 62 /* F4 */); define(116, 63 /* F5 */); define(117, 64 /* F6 */); define(118, 65 /* F7 */); define(119, 66 /* F8 */); define(120, 67 /* F9 */); define(121, 68 /* F10 */); define(122, 69 /* F11 */); define(123, 70 /* F12 */); define(124, 71 /* F13 */); define(125, 72 /* F14 */); define(126, 73 /* F15 */); define(127, 74 /* F16 */); define(128, 75 /* F17 */); define(129, 76 /* F18 */); define(130, 77 /* F19 */); define(144, 78 /* NumLock */); define(145, 79 /* ScrollLock */); define(186, 80 /* US_SEMICOLON */); define(187, 81 /* US_EQUAL */); define(188, 82 /* US_COMMA */); define(189, 83 /* US_MINUS */); define(190, 84 /* US_DOT */); define(191, 85 /* US_SLASH */); define(192, 86 /* US_BACKTICK */); define(193, 110 /* ABNT_C1 */); define(194, 111 /* ABNT_C2 */); define(219, 87 /* US_OPEN_SQUARE_BRACKET */); define(220, 88 /* US_BACKSLASH */); define(221, 89 /* US_CLOSE_SQUARE_BRACKET */); define(222, 90 /* US_QUOTE */); define(223, 91 /* OEM_8 */); define(226, 92 /* OEM_102 */); /** * https://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html * If an Input Method Editor is processing key input and the event is keydown, return 229. */ define(229, 109 /* KEY_IN_COMPOSITION */); if (browser.isIE) { define(91, 57 /* Meta */); } else if (browser.isFirefox) { define(59, 80 /* US_SEMICOLON */); define(107, 81 /* US_EQUAL */); define(109, 83 /* US_MINUS */); if (platform.isMacintosh) { define(224, 57 /* Meta */); } } else if (browser.isWebKit) { define(91, 57 /* Meta */); if (platform.isMacintosh) { // the two meta keys in the Mac have different key codes (91 and 93) define(93, 57 /* Meta */); } else { define(92, 57 /* Meta */); } } })(); function extractKeyCode(e) { if (e.charCode) { // "keypress" events mostly var char = String.fromCharCode(e.charCode).toUpperCase(); return keyCodes_1.KeyCodeUtils.fromString(char); } return KEY_CODE_MAP[e.keyCode] || 0 /* Unknown */; } var ctrlKeyMod = (platform.isMacintosh ? 256 /* WinCtrl */ : 2048 /* CtrlCmd */); var altKeyMod = 512 /* Alt */; var shiftKeyMod = 1024 /* Shift */; var metaKeyMod = (platform.isMacintosh ? 2048 /* CtrlCmd */ : 256 /* WinCtrl */); var StandardKeyboardEvent = /** @class */ (function () { function StandardKeyboardEvent(source) { this._standardKeyboardEventBrand = true; var 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}`); } StandardKeyboardEvent.prototype.preventDefault = function () { if (this.browserEvent && this.browserEvent.preventDefault) { this.browserEvent.preventDefault(); } }; StandardKeyboardEvent.prototype.stopPropagation = function () { if (this.browserEvent && this.browserEvent.stopPropagation) { this.browserEvent.stopPropagation(); } }; StandardKeyboardEvent.prototype.toKeybinding = function () { return this._asRuntimeKeybinding; }; StandardKeyboardEvent.prototype.equals = function (other) { return this._asKeybinding === other; }; StandardKeyboardEvent.prototype._computeKeybinding = function () { var key = 0 /* Unknown */; if (this.keyCode !== 5 /* Ctrl */ && this.keyCode !== 4 /* Shift */ && this.keyCode !== 6 /* Alt */ && this.keyCode !== 57 /* Meta */) { key = this.keyCode; } var 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; }; StandardKeyboardEvent.prototype._computeRuntimeKeybinding = function () { var key = 0 /* Unknown */; if (this.keyCode !== 5 /* Ctrl */ && this.keyCode !== 4 /* Shift */ && this.keyCode !== 6 /* Alt */ && this.keyCode !== 57 /* Meta */) { key = this.keyCode; } return new keyCodes_1.SimpleKeybinding(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key); }; return StandardKeyboardEvent; }()); 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[45/*vs/base/browser/mouseEvent*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,174/*vs/base/browser/iframe*/,16/*vs/base/common/platform*/]), function (require, exports, browser, iframe_1, platform) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var StandardMouseEvent = /** @class */ (function () { function StandardMouseEvent(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. var iframeOffsets = iframe_1.IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(self, e.view); this.posx -= iframeOffsets.left; this.posy -= iframeOffsets.top; } StandardMouseEvent.prototype.preventDefault = function () { if (this.browserEvent.preventDefault) { this.browserEvent.preventDefault(); } }; StandardMouseEvent.prototype.stopPropagation = function () { if (this.browserEvent.stopPropagation) { this.browserEvent.stopPropagation(); } }; return StandardMouseEvent; }()); exports.StandardMouseEvent = StandardMouseEvent; var DragMouseEvent = /** @class */ (function (_super) { __extends(DragMouseEvent, _super); function DragMouseEvent(e) { var _this = _super.call(this, e) || this; _this.dataTransfer = e.dataTransfer; return _this; } return DragMouseEvent; }(StandardMouseEvent)); exports.DragMouseEvent = DragMouseEvent; var StandardWheelEvent = /** @class */ (function () { function StandardWheelEvent(e, deltaX, deltaY) { if (deltaX === void 0) { deltaX = 0; } if (deltaY === void 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 var e1 = e; var 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 var ev = e; if (ev.deltaMode === ev.DOM_DELTA_LINE) { // the deltas are expressed in lines 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 var ev = e; if (ev.deltaMode === ev.DOM_DELTA_LINE) { // the deltas are expressed in lines 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; } } } StandardWheelEvent.prototype.preventDefault = function () { if (this.browserEvent) { if (this.browserEvent.preventDefault) { this.browserEvent.preventDefault(); } } }; StandardWheelEvent.prototype.stopPropagation = function () { if (this.browserEvent) { if (this.browserEvent.stopPropagation) { this.browserEvent.stopPropagation(); } } }; return StandardWheelEvent; }()); 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[245/*vs/base/common/process*/], __M([0/*require*/,1/*exports*/,16/*vs/base/common/platform*/]), function (require, exports, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var safeProcess = (typeof process === 'undefined') ? { cwd: function () { return '/'; }, env: Object.create(null), get platform() { return platform_1.isWindows ? 'win32' : platform_1.isMacintosh ? 'darwin' : 'linux'; }, nextTick: function (callback) { return platform_1.setImmediate(callback); } } : process; exports.cwd = safeProcess.cwd; exports.env = safeProcess.env; 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[77/*vs/base/common/path*/], __M([0/*require*/,1/*exports*/,245/*vs/base/common/process*/]), function (require, exports, process) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CHAR_UPPERCASE_A = 65; /* A */ var CHAR_LOWERCASE_A = 97; /* a */ var CHAR_UPPERCASE_Z = 90; /* Z */ var CHAR_LOWERCASE_Z = 122; /* z */ var CHAR_DOT = 46; /* . */ var CHAR_FORWARD_SLASH = 47; /* / */ var CHAR_BACKWARD_SLASH = 92; /* \ */ var CHAR_COLON = 58; /* : */ var CHAR_QUESTION_MARK = 63; /* ? */ var ErrorInvalidArgType = /** @class */ (function (_super) { __extends(ErrorInvalidArgType, _super); function ErrorInvalidArgType(name, expected, actual) { var _this = this; // determiner: 'must be' or 'must not be' var determiner; if (typeof expected === 'string' && expected.indexOf('not ') === 0) { determiner = 'must not be'; expected = expected.replace(/^not /, ''); } else { determiner = 'must be'; } var type = name.indexOf('.') !== -1 ? 'property' : 'argument'; var msg = "The \"" + name + "\" " + type + " " + determiner + " of type " + expected; msg += ". Received type " + typeof actual; _this = _super.call(this, msg) || this; _this.code = 'ERR_INVALID_ARG_TYPE'; return _this; } return ErrorInvalidArgType; }(Error)); 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) { var res = ''; var lastSegmentLength = 0; var lastSlash = -1; var dots = 0; var code; for (var 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 (lastSlash !== i - 1 && 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) { var 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 === 2 || res.length === 1) { res = ''; lastSegmentLength = 0; lastSlash = i; dots = 0; continue; } } if (allowAboveRoot) { if (res.length > 0) { res += separator + ".."; } else { res = '..'; } 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) { var dir = pathObject.dir || pathObject.root; var base = pathObject.base || ((pathObject.name || '') + (pathObject.ext || '')); if (!dir) { return base; } if (dir === pathObject.root) { return dir + base; } return dir + sep + base; } exports.win32 = { // path.resolve([from ...], to) resolve: function () { var pathSegments = []; for (var _i = 0; _i < arguments.length; _i++) { pathSegments[_i] = arguments[_i]; } var resolvedDevice = ''; var resolvedTail = ''; var resolvedAbsolute = false; for (var i = pathSegments.length - 1; i >= -1; i--) { var path = void 0; if (i >= 0) { path = pathSegments[i]; } else if (!resolvedDevice) { 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, 3).toLowerCase() !== resolvedDevice.toLowerCase() + '\\') { path = resolvedDevice + '\\'; } } validateString(path, 'path'); // Skip empty entries if (path.length === 0) { continue; } var len = path.length; var rootEnd = 0; var device = ''; var isAbsolute = false; var code = path.charCodeAt(0); // Try to match a root if (len > 1) { 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 var j = 2; var last = j; // Match 1 or more non-path separators for (; j < len; ++j) { if (isPathSeparator(path.charCodeAt(j))) { break; } } if (j < len && j !== last) { var firstPart = path.slice(last, j); // Matched! last = j; // Match 1 or more path separators for (; j < len; ++j) { if (!isPathSeparator(path.charCodeAt(j))) { break; } } if (j < len && j !== last) { // Matched! last = j; // Match 1 or more non-path separators for (; j < len; ++j) { if (isPathSeparator(path.charCodeAt(j))) { break; } } if (j === len) { // We matched a UNC root only device = '\\\\' + firstPart + '\\' + path.slice(last); rootEnd = j; } else 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)) { // Possible device root if (path.charCodeAt(1) === CHAR_COLON) { device = path.slice(0, 2); rootEnd = 2; if (len > 2) { if (isPathSeparator(path.charCodeAt(2))) { // Treat separator following drive name as an absolute path // indicator isAbsolute = true; rootEnd = 3; } } } } } else if (isPathSeparator(code)) { // `path` contains just a path separator rootEnd = 1; isAbsolute = true; } if (device.length > 0 && resolvedDevice.length > 0 && device.toLowerCase() !== resolvedDevice.toLowerCase()) { // This path points to another device so it is not applicable continue; } if (resolvedDevice.length === 0 && device.length > 0) { resolvedDevice = device; } if (!resolvedAbsolute) { resolvedTail = path.slice(rootEnd) + '\\' + resolvedTail; resolvedAbsolute = isAbsolute; } if (resolvedDevice.length > 0 && resolvedAbsolute) { 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 (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) || '.'; }, normalize: function (path) { validateString(path, 'path'); var len = path.length; if (len === 0) { return '.'; } var rootEnd = 0; var device; var isAbsolute = false; var code = path.charCodeAt(0); // Try to match a root if (len > 1) { 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 var j = 2; var last = j; // Match 1 or more non-path separators for (; j < len; ++j) { if (isPathSeparator(path.charCodeAt(j))) { break; } } if (j < len && j !== last) { var firstPart = path.slice(last, j); // Matched! last = j; // Match 1 or more path separators for (; j < len; ++j) { if (!isPathSeparator(path.charCodeAt(j))) { break; } } if (j < len && j !== last) { // Matched! last = j; // Match 1 or more non-path separators for (; j < len; ++j) { if (isPathSeparator(path.charCodeAt(j))) { break; } } 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) + '\\'; } else 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)) { // Possible device root if (path.charCodeAt(1) === CHAR_COLON) { device = path.slice(0, 2); rootEnd = 2; if (len > 2) { if (isPathSeparator(path.charCodeAt(2))) { // Treat separator following drive name as an absolute path // indicator isAbsolute = true; rootEnd = 3; } } } } } else if (isPathSeparator(code)) { // `path` contains just a path separator, exit early to avoid unnecessary // work return '\\'; } var tail; if (rootEnd < len) { tail = normalizeString(path.slice(rootEnd), !isAbsolute, '\\', isPathSeparator); } else { tail = ''; } if (tail.length === 0 && !isAbsolute) { tail = '.'; } if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) { tail += '\\'; } if (device === undefined) { if (isAbsolute) { if (tail.length > 0) { return '\\' + tail; } else { return '\\'; } } else if (tail.length > 0) { return tail; } else { return ''; } } else if (isAbsolute) { if (tail.length > 0) { return device + '\\' + tail; } else { return device + '\\'; } } else if (tail.length > 0) { return device + tail; } else { return device; } }, isAbsolute: function (path) { validateString(path, 'path'); var len = path.length; if (len === 0) { return false; } var code = path.charCodeAt(0); if (isPathSeparator(code)) { return true; } else if (isWindowsDeviceRoot(code)) { // Possible device root if (len > 2 && path.charCodeAt(1) === CHAR_COLON) { if (isPathSeparator(path.charCodeAt(2))) { return true; } } } return false; }, join: function () { var paths = []; for (var _i = 0; _i < arguments.length; _i++) { paths[_i] = arguments[_i]; } if (paths.length === 0) { return '.'; } var joined; var firstPart; for (var i = 0; i < paths.length; ++i) { var arg = paths[i]; validateString(arg, 'path'); if (arg.length > 0) { if (joined === undefined) { joined = firstPart = arg; } else { joined += '\\' + arg; } } } if (joined === undefined) { return '.'; } // Make sure that the joined path doesn't start with two slashes, because // normalize() will mistake it for an UNC path then. // // This step is skipped when it is very clear that the user actually // intended to point at an UNC path. This is assumed when the first // non-empty string arguments starts with exactly two slashes followed by // at least one more non-slash character. // // Note that for normalize() to treat a path as an UNC path it needs to // have at least 2 components, so we don't filter for that here. // This means that the user can use join to construct UNC paths from // a server name and a share name; for example: // path.join('//server', 'share') -> '\\\\server\\share\\') var needsReplace = true; var slashCount = 0; if (typeof firstPart === 'string' && isPathSeparator(firstPart.charCodeAt(0))) { ++slashCount; var firstLen = firstPart.length; if (firstLen > 1) { if (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 for (; slashCount < joined.length; ++slashCount) { if (!isPathSeparator(joined.charCodeAt(slashCount))) { break; } } // 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: function (from, to) { validateString(from, 'from'); validateString(to, 'to'); if (from === to) { return ''; } var fromOrig = exports.win32.resolve(from); var toOrig = exports.win32.resolve(to); if (fromOrig === toOrig) { return ''; } from = fromOrig.toLowerCase(); to = toOrig.toLowerCase(); if (from === to) { return ''; } // Trim any leading backslashes var fromStart = 0; for (; fromStart < from.length; ++fromStart) { if (from.charCodeAt(fromStart) !== CHAR_BACKWARD_SLASH) { break; } } // Trim trailing backslashes (applicable to UNC paths only) var fromEnd = from.length; for (; fromEnd - 1 > fromStart; --fromEnd) { if (from.charCodeAt(fromEnd - 1) !== CHAR_BACKWARD_SLASH) { break; } } var fromLen = (fromEnd - fromStart); // Trim any leading backslashes var toStart = 0; for (; toStart < to.length; ++toStart) { if (to.charCodeAt(toStart) !== CHAR_BACKWARD_SLASH) { break; } } // Trim trailing backslashes (applicable to UNC paths only) var toEnd = to.length; for (; toEnd - 1 > toStart; --toEnd) { if (to.charCodeAt(toEnd - 1) !== CHAR_BACKWARD_SLASH) { break; } } var toLen = (toEnd - toStart); // Compare paths to find the longest common path from root var length = (fromLen < toLen ? fromLen : toLen); var lastCommonSep = -1; var i = 0; for (; i <= length; ++i) { if (i === length) { 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); } else 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; } } break; } var fromCode = from.charCodeAt(fromStart + i); var toCode = to.charCodeAt(toStart + i); if (fromCode !== toCode) { 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 && lastCommonSep === -1) { return toOrig; } var out = ''; if (lastCommonSep === -1) { lastCommonSep = 0; } // 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) { if (out.length === 0) { out += '..'; } else { out += '\\..'; } } } // 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 + lastCommonSep, toEnd); } else { toStart += lastCommonSep; if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) { ++toStart; } return toOrig.slice(toStart, toEnd); } }, toNamespacedPath: function (path) { // Note: this will *probably* throw somewhere. if (typeof path !== 'string') { return path; } if (path.length === 0) { return ''; } var resolvedPath = exports.win32.resolve(path); if (resolvedPath.length >= 3) { if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) { // Possible UNC root if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) { var 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))) { // Possible device root if (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: function (path) { validateString(path, 'path'); var len = path.length; if (len === 0) { return '.'; } var rootEnd = -1; var end = -1; var matchedSlash = true; var offset = 0; var code = path.charCodeAt(0); // Try to match a root if (len > 1) { if (isPathSeparator(code)) { // Possible UNC root rootEnd = offset = 1; if (isPathSeparator(path.charCodeAt(1))) { // Matched double path separator at beginning var j = 2; var last = j; // Match 1 or more non-path separators for (; j < len; ++j) { if (isPathSeparator(path.charCodeAt(j))) { break; } } if (j < len && j !== last) { // Matched! last = j; // Match 1 or more path separators for (; j < len; ++j) { if (!isPathSeparator(path.charCodeAt(j))) { break; } } if (j < len && j !== last) { // Matched! last = j; // Match 1 or more non-path separators for (; j < len; ++j) { if (isPathSeparator(path.charCodeAt(j))) { break; } } 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; } } } } } else if (isWindowsDeviceRoot(code)) { // Possible device root if (path.charCodeAt(1) === CHAR_COLON) { rootEnd = offset = 2; if (len > 2) { if (isPathSeparator(path.charCodeAt(2))) { rootEnd = offset = 3; } } } } } else if (isPathSeparator(code)) { // `path` contains just a path separator, exit early to avoid // unnecessary work return path; } for (var 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 '.'; } else { end = rootEnd; } } return path.slice(0, end); }, basename: function (path, ext) { if (ext !== undefined) { validateString(ext, 'ext'); } validateString(path, 'path'); var start = 0; var end = -1; var matchedSlash = true; var 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) { var drive = path.charCodeAt(0); if (isWindowsDeviceRoot(drive)) { if (path.charCodeAt(1) === CHAR_COLON) { start = 2; } } } if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { if (ext.length === path.length && ext === path) { return ''; } var extIdx = ext.length - 1; var firstNonSlashEnd = -1; for (i = path.length - 1; i >= start; --i) { var 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); } else { 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: function (path) { validateString(path, 'path'); var start = 0; var startDot = -1; var startPart = 0; var end = -1; var matchedSlash = true; // Track the state of characters (if any) we see before our first dot and // after any path separator we find var 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 (var i = path.length - 1; i >= start; --i) { var 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: function (pathObject) { if (pathObject === null || typeof pathObject !== 'object') { throw new ErrorInvalidArgType('pathObject', 'Object', pathObject); } return _format('\\', pathObject); }, parse: function (path) { validateString(path, 'path'); var ret = { root: '', dir: '', base: '', ext: '', name: '' }; if (path.length === 0) { return ret; } var len = path.length; var rootEnd = 0; var code = path.charCodeAt(0); // Try to match a root if (len > 1) { if (isPathSeparator(code)) { // Possible UNC root rootEnd = 1; if (isPathSeparator(path.charCodeAt(1))) { // Matched double path separator at beginning var j = 2; var last = j; // Match 1 or more non-path separators for (; j < len; ++j) { if (isPathSeparator(path.charCodeAt(j))) { break; } } if (j < len && j !== last) { // Matched! last = j; // Match 1 or more path separators for (; j < len; ++j) { if (!isPathSeparator(path.charCodeAt(j))) { break; } } if (j < len && j !== last) { // Matched! last = j; // Match 1 or more non-path separators for (; j < len; ++j) { if (isPathSeparator(path.charCodeAt(j))) { break; } } 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)) { // Possible device root if (path.charCodeAt(1) === CHAR_COLON) { rootEnd = 2; if (len > 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; } } else { // `path` contains just a drive root, exit early to avoid // unnecessary work ret.root = ret.dir = path; return ret; } } } } else if (isPathSeparator(code)) { // `path` contains just a path separator, exit early to avoid // unnecessary work ret.root = ret.dir = path; return ret; } if (rootEnd > 0) { ret.root = path.slice(0, rootEnd); } var startDot = -1; var startPart = rootEnd; var end = -1; var matchedSlash = true; var i = path.length - 1; // Track the state of characters (if any) we see before our first dot and // after any path separator we find var 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 (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)) { if (end !== -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: function () { var pathSegments = []; for (var _i = 0; _i < arguments.length; _i++) { pathSegments[_i] = arguments[_i]; } var resolvedPath = ''; var resolvedAbsolute = false; for (var i = pathSegments.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = void 0; if (i >= 0) { path = pathSegments[i]; } else { path = 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) { if (resolvedPath.length > 0) { return '/' + resolvedPath; } else { return '/'; } } else if (resolvedPath.length > 0) { return resolvedPath; } else { return '.'; } }, normalize: function (path) { validateString(path, 'path'); if (path.length === 0) { return '.'; } var isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; var trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH; // Normalize the path path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator); if (path.length === 0 && !isAbsolute) { path = '.'; } if (path.length > 0 && trailingSeparator) { path += '/'; } if (isAbsolute) { return '/' + path; } return path; }, isAbsolute: function (path) { validateString(path, 'path'); return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH; }, join: function () { var paths = []; for (var _i = 0; _i < arguments.length; _i++) { paths[_i] = arguments[_i]; } if (paths.length === 0) { return '.'; } var joined; for (var i = 0; i < paths.length; ++i) { var arg = arguments[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: function (from, to) { validateString(from, 'from'); validateString(to, 'to'); if (from === to) { return ''; } from = exports.posix.resolve(from); to = exports.posix.resolve(to); if (from === to) { return ''; } // Trim any leading backslashes var fromStart = 1; for (; fromStart < from.length; ++fromStart) { if (from.charCodeAt(fromStart) !== CHAR_FORWARD_SLASH) { break; } } var fromEnd = from.length; var fromLen = (fromEnd - fromStart); // Trim any leading backslashes var toStart = 1; for (; toStart < to.length; ++toStart) { if (to.charCodeAt(toStart) !== CHAR_FORWARD_SLASH) { break; } } var toEnd = to.length; var toLen = (toEnd - toStart); // Compare paths to find the longest common path from root var length = (fromLen < toLen ? fromLen : toLen); var lastCommonSep = -1; var i = 0; for (; i <= length; ++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); } else 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'; to='/' lastCommonSep = 0; } } break; } var fromCode = from.charCodeAt(fromStart + i); var toCode = to.charCodeAt(toStart + i); if (fromCode !== toCode) { break; } else if (fromCode === CHAR_FORWARD_SLASH) { lastCommonSep = i; } } var 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) { if (out.length === 0) { out += '..'; } else { out += '/..'; } } } // Lastly, append the rest of the destination (`to`) path that comes after // the common path parts if (out.length > 0) { return out + to.slice(toStart + lastCommonSep); } else { toStart += lastCommonSep; if (to.charCodeAt(toStart) === CHAR_FORWARD_SLASH) { ++toStart; } return to.slice(toStart); } }, toNamespacedPath: function (path) { // Non-op on posix systems return path; }, dirname: function (path) { validateString(path, 'path'); if (path.length === 0) { return '.'; } var hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; var end = -1; var matchedSlash = true; for (var 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: function (path, ext) { if (ext !== undefined) { validateString(ext, 'ext'); } validateString(path, 'path'); var start = 0; var end = -1; var matchedSlash = true; var i; if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { if (ext.length === path.length && ext === path) { return ''; } var extIdx = ext.length - 1; var firstNonSlashEnd = -1; for (i = path.length - 1; i >= 0; --i) { var 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); } else { 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: function (path) { validateString(path, 'path'); var startDot = -1; var startPart = 0; var end = -1; var matchedSlash = true; // Track the state of characters (if any) we see before our first dot and // after any path separator we find var preDotState = 0; for (var i = path.length - 1; i >= 0; --i) { var 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: function (pathObject) { if (pathObject === null || typeof pathObject !== 'object') { throw new ErrorInvalidArgType('pathObject', 'Object', pathObject); } return _format('/', pathObject); }, parse: function (path) { validateString(path, 'path'); var ret = { root: '', dir: '', base: '', ext: '', name: '' }; if (path.length === 0) { return ret; } var isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; var start; if (isAbsolute) { ret.root = '/'; start = 1; } else { start = 0; } var startDot = -1; var startPart = 0; var end = -1; var matchedSlash = true; var i = path.length - 1; // Track the state of characters (if any) we see before our first dot and // after any path separator we find var preDotState = 0; // Get non-dir info for (; i >= start; --i) { var 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)) { if (end !== -1) { if (startPart === 0 && isAbsolute) { ret.base = ret.name = path.slice(1, end); } else { ret.base = ret.name = path.slice(startPart, end); } } } else { if (startPart === 0 && isAbsolute) { ret.name = path.slice(1, startDot); ret.base = path.slice(1, end); } else { ret.name = path.slice(startPart, startDot); ret.base = path.slice(startPart, 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.join = (process.platform === 'win32' ? exports.win32.join : exports.posix.join); 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[103/*vs/base/common/range*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 }; } var start = Math.max(one.start, other.start); var end = Math.min(one.end, other.end); if (end - start <= 0) { return { start: 0, end: 0 }; } return { start: start, end: 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) { var result = []; var first = { start: one.start, end: Math.min(other.start, one.end) }; var 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[246/*vs/base/browser/ui/list/rangeMap*/], __M([0/*require*/,1/*exports*/,103/*vs/base/common/range*/]), function (require, exports, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Returns the intersection between a ranged group and a range. * Returns `[]` if the intersection is empty. */ function groupIntersect(range, groups) { var result = []; for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) { var r = groups_1[_i]; if (range.start >= r.range.end) { continue; } if (range.end < r.range.start) { break; } var 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(_a, much) { var start = _a.start, end = _a.end; 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) { var result = []; var previousGroup = null; for (var _i = 0, groups_2 = groups; _i < groups_2.length; _i++) { var group = groups_2[_i]; var start = group.range.start; var end = group.range.end; var size = group.size; if (previousGroup && size === previousGroup.size) { previousGroup.range.end = end; continue; } previousGroup = { range: { start: start, end: end }, size: size }; result.push(previousGroup); } return result; } exports.consolidate = consolidate; /** * Concatenates several collections of ranged groups into a single * collection. */ function concat() { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { groups[_i] = arguments[_i]; } return consolidate(groups.reduce(function (r, g) { return r.concat(g); }, [])); } var RangeMap = /** @class */ (function () { function RangeMap() { this.groups = []; this._size = 0; } RangeMap.prototype.splice = function (index, deleteCount, items) { if (items === void 0) { items = []; } var diff = items.length - deleteCount; var before = groupIntersect({ start: 0, end: index }, this.groups); var after = groupIntersect({ start: index + deleteCount, end: Number.POSITIVE_INFINITY }, this.groups) .map(function (g) { return ({ range: shift(g.range, diff), size: g.size }); }); var middle = items.map(function (item, i) { return ({ range: { start: index + i, end: index + i + 1 }, size: item.size }); }); this.groups = concat(before, middle, after); this._size = this.groups.reduce(function (t, g) { return t + (g.size * (g.range.end - g.range.start)); }, 0); }; Object.defineProperty(RangeMap.prototype, "count", { /** * Returns the number of items in the range map. */ get: function () { var len = this.groups.length; if (!len) { return 0; } return this.groups[len - 1].range.end; }, enumerable: true, configurable: true }); Object.defineProperty(RangeMap.prototype, "size", { /** * Returns the sum of the sizes of all items in the range map. */ get: function () { return this._size; }, enumerable: true, configurable: true }); /** * Returns the index of the item at the given position. */ RangeMap.prototype.indexAt = function (position) { if (position < 0) { return -1; } var index = 0; var size = 0; for (var _i = 0, _a = this.groups; _i < _a.length; _i++) { var group = _a[_i]; var count = group.range.end - group.range.start; var 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. */ RangeMap.prototype.indexAfter = function (position) { return Math.min(this.indexAt(position) + 1, this.count); }; /** * Returns the start position of the item at the given index. */ RangeMap.prototype.positionAt = function (index) { if (index < 0) { return -1; } var position = 0; var count = 0; for (var _i = 0, _a = this.groups; _i < _a.length; _i++) { var group = _a[_i]; var groupCount = group.range.end - group.range.start; var newCount = count + groupCount; if (index < newCount) { return position + ((index - count) * group.size); } position += groupCount * group.size; count = newCount; } return -1; }; return RangeMap; }()); 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[176/*vs/base/common/scrollable*/], __M([0/*require*/,1/*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 }); var ScrollState = /** @class */ (function () { function ScrollState(width, scrollWidth, scrollLeft, height, scrollHeight, scrollTop) { width = width | 0; scrollWidth = scrollWidth | 0; scrollLeft = scrollLeft | 0; height = height | 0; scrollHeight = scrollHeight | 0; scrollTop = scrollTop | 0; 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; } ScrollState.prototype.equals = function (other) { return (this.width === other.width && this.scrollWidth === other.scrollWidth && this.scrollLeft === other.scrollLeft && this.height === other.height && this.scrollHeight === other.scrollHeight && this.scrollTop === other.scrollTop); }; ScrollState.prototype.withScrollDimensions = function (update) { return new ScrollState((typeof update.width !== 'undefined' ? update.width : this.width), (typeof update.scrollWidth !== 'undefined' ? update.scrollWidth : this.scrollWidth), this.scrollLeft, (typeof update.height !== 'undefined' ? update.height : this.height), (typeof update.scrollHeight !== 'undefined' ? update.scrollHeight : this.scrollHeight), this.scrollTop); }; ScrollState.prototype.withScrollPosition = function (update) { return new ScrollState(this.width, this.scrollWidth, (typeof update.scrollLeft !== 'undefined' ? update.scrollLeft : this.scrollLeft), this.height, this.scrollHeight, (typeof update.scrollTop !== 'undefined' ? update.scrollTop : this.scrollTop)); }; ScrollState.prototype.createScrollEvent = function (previous) { var widthChanged = (this.width !== previous.width); var scrollWidthChanged = (this.scrollWidth !== previous.scrollWidth); var scrollLeftChanged = (this.scrollLeft !== previous.scrollLeft); var heightChanged = (this.height !== previous.height); var scrollHeightChanged = (this.scrollHeight !== previous.scrollHeight); var scrollTopChanged = (this.scrollTop !== previous.scrollTop); return { width: this.width, scrollWidth: this.scrollWidth, scrollLeft: this.scrollLeft, height: this.height, scrollHeight: this.scrollHeight, scrollTop: this.scrollTop, widthChanged: widthChanged, scrollWidthChanged: scrollWidthChanged, scrollLeftChanged: scrollLeftChanged, heightChanged: heightChanged, scrollHeightChanged: scrollHeightChanged, scrollTopChanged: scrollTopChanged, }; }; return ScrollState; }()); exports.ScrollState = ScrollState; var Scrollable = /** @class */ (function (_super) { __extends(Scrollable, _super); function Scrollable(smoothScrollDuration, scheduleAtNextAnimationFrame) { var _this = _super.call(this) || this; _this._onScroll = _this._register(new event_1.Emitter()); _this.onScroll = _this._onScroll.event; _this._smoothScrollDuration = smoothScrollDuration; _this._scheduleAtNextAnimationFrame = scheduleAtNextAnimationFrame; _this._state = new ScrollState(0, 0, 0, 0, 0, 0); _this._smoothScrolling = null; return _this; } Scrollable.prototype.dispose = function () { if (this._smoothScrolling) { this._smoothScrolling.dispose(); this._smoothScrolling = null; } _super.prototype.dispose.call(this); }; Scrollable.prototype.setSmoothScrollDuration = function (smoothScrollDuration) { this._smoothScrollDuration = smoothScrollDuration; }; Scrollable.prototype.validateScrollPosition = function (scrollPosition) { return this._state.withScrollPosition(scrollPosition); }; Scrollable.prototype.getScrollDimensions = function () { return this._state; }; Scrollable.prototype.setScrollDimensions = function (dimensions) { var newState = this._state.withScrollDimensions(dimensions); this._setState(newState); // 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. */ Scrollable.prototype.getFutureScrollPosition = function () { 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. */ Scrollable.prototype.getCurrentScrollPosition = function () { return this._state; }; Scrollable.prototype.setScrollPositionNow = function (update) { // no smooth scrolling requested var newState = this._state.withScrollPosition(update); // Terminate any outstanding smooth scrolling if (this._smoothScrolling) { this._smoothScrolling.dispose(); this._smoothScrolling = null; } this._setState(newState); }; Scrollable.prototype.setScrollPositionSmooth = function (update) { var _this = this; 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` var 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; } var newSmoothScrolling = this._smoothScrolling.combine(this._state, validTarget, this._smoothScrollDuration); this._smoothScrolling.dispose(); this._smoothScrolling = newSmoothScrolling; } else { // Validate `update` var validTarget = this._state.withScrollPosition(update); this._smoothScrolling = SmoothScrollingOperation.start(this._state, validTarget, this._smoothScrollDuration); } // Begin smooth scrolling animation this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(function () { if (!_this._smoothScrolling) { return; } _this._smoothScrolling.animationFrameDisposable = null; _this._performSmoothScrolling(); }); }; Scrollable.prototype._performSmoothScrolling = function () { var _this = this; if (!this._smoothScrolling) { return; } var update = this._smoothScrolling.tick(); var newState = this._state.withScrollPosition(update); this._setState(newState); if (update.isDone) { this._smoothScrolling.dispose(); this._smoothScrolling = null; return; } // Continue smooth scrolling animation this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(function () { if (!_this._smoothScrolling) { return; } _this._smoothScrolling.animationFrameDisposable = null; _this._performSmoothScrolling(); }); }; Scrollable.prototype._setState = function (newState) { var oldState = this._state; if (oldState.equals(newState)) { // no change return; } this._state = newState; this._onScroll.fire(this._state.createScrollEvent(oldState)); }; return Scrollable; }(lifecycle_1.Disposable)); exports.Scrollable = Scrollable; var SmoothScrollingUpdate = /** @class */ (function () { function SmoothScrollingUpdate(scrollLeft, scrollTop, isDone) { this.scrollLeft = scrollLeft; this.scrollTop = scrollTop; this.isDone = isDone; } return SmoothScrollingUpdate; }()); exports.SmoothScrollingUpdate = SmoothScrollingUpdate; function createEaseOutCubic(from, to) { var 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)); }; } var SmoothScrollingOperation = /** @class */ (function () { function SmoothScrollingOperation(from, to, startTime, duration) { this.from = from; this.to = to; this.duration = duration; this._startTime = startTime; this.animationFrameDisposable = null; this._initAnimations(); } SmoothScrollingOperation.prototype._initAnimations = function () { 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); }; SmoothScrollingOperation.prototype._initAnimation = function (from, to, viewportSize) { var delta = Math.abs(from - to); if (delta > 2.5 * viewportSize) { var stop1 = void 0, stop2 = void 0; 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); }; SmoothScrollingOperation.prototype.dispose = function () { if (this.animationFrameDisposable !== null) { this.animationFrameDisposable.dispose(); this.animationFrameDisposable = null; } }; SmoothScrollingOperation.prototype.acceptScrollDimensions = function (state) { this.to = state.withScrollPosition(this.to); this._initAnimations(); }; SmoothScrollingOperation.prototype.tick = function () { return this._tick(Date.now()); }; SmoothScrollingOperation.prototype._tick = function (now) { var completion = (now - this._startTime) / this.duration; if (completion < 1) { var newScrollLeft = this.scrollLeft(completion); var newScrollTop = this.scrollTop(completion); return new SmoothScrollingUpdate(newScrollLeft, newScrollTop, false); } return new SmoothScrollingUpdate(this.to.scrollLeft, this.to.scrollTop, true); }; SmoothScrollingOperation.prototype.combine = function (from, to, duration) { return SmoothScrollingOperation.start(from, to, duration); }; SmoothScrollingOperation.start = function (from, to, duration) { // +10 / -10 : pretend the animation already started for a quicker response to a scroll request duration = duration + 10; var startTime = Date.now() - 10; return new SmoothScrollingOperation(from, to, startTime, duration); }; return SmoothScrollingOperation; }()); 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[132/*vs/base/common/stopwatch*/], __M([0/*require*/,1/*exports*/,16/*vs/base/common/platform*/]), function (require, exports, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var hasPerformanceNow = (platform_1.globals.performance && typeof platform_1.globals.performance.now === 'function'); var StopWatch = /** @class */ (function () { function StopWatch(highResolution) { this._highResolution = hasPerformanceNow && highResolution; this._startTime = this._now(); this._stopTime = -1; } StopWatch.create = function (highResolution) { if (highResolution === void 0) { highResolution = true; } return new StopWatch(highResolution); }; StopWatch.prototype.stop = function () { this._stopTime = this._now(); }; StopWatch.prototype.elapsed = function () { if (this._stopTime !== -1) { return this._stopTime - this._startTime; } return this._now() - this._startTime; }; StopWatch.prototype._now = function () { return this._highResolution ? platform_1.globals.performance.now() : new Date().getTime(); }; return StopWatch; }()); exports.StopWatch = StopWatch; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[5/*vs/base/common/strings*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isFalsyOrWhitespace(str) { if (!str || typeof str !== 'string') { return true; } return str.trim().length === 0; } exports.isFalsyOrWhitespace = isFalsyOrWhitespace; /** * @returns the provided number with the given number of preceding zeros. */ function pad(n, l, char) { if (char === void 0) { char = '0'; } var str = '' + n; var r = [str]; for (var i = str.length; i < l; i++) { r.push(char); } return r.reverse().join(''); } exports.pad = pad; var _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) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } if (args.length === 0) { return value; } return value.replace(_formatRegexp, function (match, group) { var 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) { if (needle === void 0) { needle = ' '; } var 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; } var needleLen = needle.length; if (needleLen === 0 || haystack.length === 0) { return haystack; } var 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; } var needleLen = needle.length, haystackLen = haystack.length; if (needleLen === 0 || haystackLen === 0) { return haystack; } var 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; /** * Determines if haystack starts with needle. */ function startsWith(haystack, needle) { if (haystack.length < needle.length) { return false; } if (haystack === needle) { return true; } for (var i = 0; i < needle.length; i++) { if (haystack[i] !== needle[i]) { return false; } } return true; } exports.startsWith = startsWith; /** * Determines if haystack ends with needle. */ function endsWith(haystack, needle) { var diff = haystack.length - needle.length; if (diff > 0) { return haystack.indexOf(needle, diff) === diff; } else if (diff === 0) { return haystack === needle; } else { return false; } } exports.endsWith = endsWith; function createRegExp(searchString, isRegex, options) { if (options === void 0) { 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'; } } var 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. var 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.unicode ? 'u' : ''); } exports.regExpFlags = regExpFlags; /** * Returns first index of the string that is not whitespace. * If string is empty or contains only whitespaces, returns -1 */ function firstNonWhitespaceIndex(str) { for (var i = 0, len = str.length; i < len; i++) { var 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, end) { if (start === void 0) { start = 0; } if (end === void 0) { end = str.length; } for (var i = start; i < end; i++) { var 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) { if (startIndex === void 0) { startIndex = str.length - 1; } for (var i = startIndex; i >= 0; i--) { var 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 compareIgnoreCase(a, b) { var len = Math.min(a.length, b.length); for (var i = 0; i < len; i++) { var codeA = a.charCodeAt(i); var codeB = b.charCodeAt(i); if (codeA === codeB) { // equal continue; } if (isUpperAsciiLetter(codeA)) { codeA += 32; } if (isUpperAsciiLetter(codeB)) { codeB += 32; } var diff = codeA - codeB; if (diff === 0) { // equal -> ignoreCase continue; } else if (isLowerAsciiLetter(codeA) && isLowerAsciiLetter(codeB)) { // return diff; } else { return compare(a.toLowerCase(), b.toLowerCase()); } } if (a.length < b.length) { return -1; } else if (a.length > b.length) { return 1; } else { return 0; } } exports.compareIgnoreCase = compareIgnoreCase; function isLowerAsciiLetter(code) { return code >= 97 /* a */ && code <= 122 /* z */; } exports.isLowerAsciiLetter = isLowerAsciiLetter; function isUpperAsciiLetter(code) { return code >= 65 /* A */ && code <= 90 /* Z */; } exports.isUpperAsciiLetter = isUpperAsciiLetter; function isAsciiLetter(code) { return isLowerAsciiLetter(code) || isUpperAsciiLetter(code); } function equalsIgnoreCase(a, b) { return a.length === b.length && doEqualsIgnoreCase(a, b); } exports.equalsIgnoreCase = equalsIgnoreCase; function doEqualsIgnoreCase(a, b, stopAt) { if (stopAt === void 0) { stopAt = a.length; } for (var i = 0; i < stopAt; i++) { var codeA = a.charCodeAt(i); var codeB = b.charCodeAt(i); if (codeA === codeB) { continue; } // a-z A-Z if (isAsciiLetter(codeA) && isAsciiLetter(codeB)) { var diff = Math.abs(codeA - codeB); if (diff !== 0 && diff !== 32) { return false; } } // Any other charcode else { if (String.fromCharCode(codeA).toLowerCase() !== String.fromCharCode(codeB).toLowerCase()) { return false; } } } return true; } function startsWithIgnoreCase(str, candidate) { var candidateLength = candidate.length; if (candidate.length > str.length) { return false; } return doEqualsIgnoreCase(str, candidate, candidateLength); } exports.startsWithIgnoreCase = startsWithIgnoreCase; /** * @returns the length of the common prefix of the two strings. */ function commonPrefixLength(a, b) { var 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) { var i, len = Math.min(a.length, b.length); var aLastIndex = a.length - 1; var 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; // --- unicode // http://en.wikipedia.org/wiki/Surrogate_pair // Returns the code point starting at a specified index in a string // Code points U+0000 to U+D7FF and U+E000 to U+FFFF are represented on a single character // Code points U+10000 to U+10FFFF are represented on two consecutive characters //export function getUnicodePoint(str:string, index:number, len:number):number { // const chrCode = str.charCodeAt(index); // if (0xD800 <= chrCode && chrCode <= 0xDBFF && index + 1 < len) { // const nextChrCode = str.charCodeAt(index + 1); // if (0xDC00 <= nextChrCode && nextChrCode <= 0xDFFF) { // return (chrCode - 0xD800) << 10 + (nextChrCode - 0xDC00) + 0x10000; // } // } // return chrCode; //} function isHighSurrogate(charCode) { return (0xD800 <= charCode && charCode <= 0xDBFF); } exports.isHighSurrogate = isHighSurrogate; function isLowSurrogate(charCode) { return (0xDC00 <= charCode && charCode <= 0xDFFF); } exports.isLowSurrogate = isLowSurrogate; /** * get the code point that begins at offset `offset` */ function getNextCodePoint(str, len, offset) { var charCode = str.charCodeAt(offset); if (isHighSurrogate(charCode) && offset + 1 < len) { var nextCharCode = str.charCodeAt(offset + 1); if (isLowSurrogate(nextCharCode)) { return ((charCode - 0xD800) << 10) + (nextCharCode - 0xDC00) + 0x10000; } } return charCode; } exports.getNextCodePoint = getNextCodePoint; /** * get the code point that ends right before offset `offset` */ function getPrevCodePoint(str, offset) { var charCode = str.charCodeAt(offset - 1); if (isLowSurrogate(charCode) && offset > 1) { var prevCharCode = str.charCodeAt(offset - 2); if (isHighSurrogate(prevCharCode)) { return ((prevCharCode - 0xD800) << 10) + (charCode - 0xDC00) + 0x10000; } } return charCode; } function nextCharLength(str, offset) { var graphemeBreakTree = GraphemeBreakTree.getInstance(); var initialOffset = offset; var len = str.length; var initialCodePoint = getNextCodePoint(str, len, offset); offset += (initialCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); var graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(initialCodePoint); while (offset < len) { var nextCodePoint = getNextCodePoint(str, len, offset); var nextGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(nextCodePoint); if (breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) { break; } offset += (nextCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); graphemeBreakType = nextGraphemeBreakType; } return (offset - initialOffset); } exports.nextCharLength = nextCharLength; function prevCharLength(str, offset) { var graphemeBreakTree = GraphemeBreakTree.getInstance(); var initialOffset = offset; var initialCodePoint = getPrevCodePoint(str, offset); offset -= (initialCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); var graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(initialCodePoint); while (offset > 0) { var prevCodePoint = getPrevCodePoint(str, offset); var prevGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(prevCodePoint); if (breakBetweenGraphemeBreakType(prevGraphemeBreakType, graphemeBreakType)) { break; } offset -= (prevCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); graphemeBreakType = prevGraphemeBreakType; } return (initialOffset - offset); } exports.prevCharLength = prevCharLength; /** * Generated using https://github.com/alexandrudima/unicode-utils/blob/master/generate-rtl-test.js */ var CONTAINS_RTL = /(?:[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u0710\u0712-\u072F\u074D-\u07A5\u07B1-\u07EA\u07F4\u07F5\u07FA-\u0815\u081A\u0824\u0828\u0830-\u0858\u085E-\u08BD\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFD3D\uFD50-\uFDFC\uFE70-\uFEFC]|\uD802[\uDC00-\uDD1B\uDD20-\uDE00\uDE10-\uDE33\uDE40-\uDEE4\uDEEB-\uDF35\uDF40-\uDFFF]|\uD803[\uDC00-\uDCFF]|\uD83A[\uDC00-\uDCCF\uDD00-\uDD43\uDD50-\uDFFF]|\uD83B[\uDC00-\uDEBB])/; /** * Returns true if `str` contains any Unicode character that is classified as "R" or "AL". */ function containsRTL(str) { return CONTAINS_RTL.test(str); } exports.containsRTL = containsRTL; /** * Generated using https://github.com/alexandrudima/unicode-utils/blob/master/generate-emoji-test.js */ var CONTAINS_EMOJI = /(?:[\u231A\u231B\u23F0\u23F3\u2600-\u27BF\u2B50\u2B55]|\uD83C[\uDDE6-\uDDFF\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F\uDE80-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD00-\uDDFF\uDE70-\uDE73\uDE78-\uDE82\uDE90-\uDE95])/; function containsEmoji(str) { return CONTAINS_EMOJI.test(str); } exports.containsEmoji = containsEmoji; var 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; function containsFullWidthCharacter(str) { for (var i = 0, len = str.length; i < len; i++) { if (isFullWidthCharacter(str.charCodeAt(i))) { return true; } } return false; } exports.containsFullWidthCharacter = containsFullWidthCharacter; function isFullWidthCharacter(charCode) { // Do a cheap trick to better support wrapping of wide characters, treat them as 2 columns // http://jrgraphix.net/research/unicode_blocks.php // 2E80 — 2EFF CJK Radicals Supplement // 2F00 — 2FDF Kangxi Radicals // 2FF0 — 2FFF Ideographic Description Characters // 3000 — 303F CJK Symbols and Punctuation // 3040 — 309F Hiragana // 30A0 — 30FF Katakana // 3100 — 312F Bopomofo // 3130 — 318F Hangul Compatibility Jamo // 3190 — 319F Kanbun // 31A0 — 31BF Bopomofo Extended // 31F0 — 31FF Katakana Phonetic Extensions // 3200 — 32FF Enclosed CJK Letters and Months // 3300 — 33FF CJK Compatibility // 3400 — 4DBF CJK Unified Ideographs Extension A // 4DC0 — 4DFF Yijing Hexagram Symbols // 4E00 — 9FFF CJK Unified Ideographs // A000 — A48F Yi Syllables // A490 — A4CF Yi Radicals // AC00 — D7AF Hangul Syllables // [IGNORE] D800 — DB7F High Surrogates // [IGNORE] DB80 — DBFF High Private Use Surrogates // [IGNORE] DC00 — DFFF Low Surrogates // [IGNORE] E000 — F8FF Private Use Area // F900 — FAFF CJK Compatibility Ideographs // [IGNORE] FB00 — FB4F Alphabetic Presentation Forms // [IGNORE] FB50 — FDFF Arabic Presentation Forms-A // [IGNORE] FE00 — FE0F Variation Selectors // [IGNORE] FE20 — FE2F Combining Half Marks // [IGNORE] FE30 — FE4F CJK Compatibility Forms // [IGNORE] FE50 — FE6F Small Form Variants // [IGNORE] FE70 — FEFF Arabic Presentation Forms-B // FF00 — FFEF Halfwidth and Fullwidth Forms // [https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms] // of which FF01 - FF5E fullwidth ASCII of 21 to 7E // [IGNORE] and FF65 - FFDC halfwidth of Katakana and Hangul // [IGNORE] FFF0 — FFFF Specials charCode = +charCode; // @perf return ((charCode >= 0x2E80 && charCode <= 0xD7AF) || (charCode >= 0xF900 && charCode <= 0xFAFF) || (charCode >= 0xFF01 && charCode <= 0xFF5E)); } exports.isFullWidthCharacter = isFullWidthCharacter; /** * A fast function (therefore imprecise) to check if code points are emojis. * Generated using https://github.com/alexandrudima/unicode-utils/blob/master/generate-emoji-test.js */ function isEmojiImprecise(x) { return ((x >= 0x1F1E6 && x <= 0x1F1FF) || (x >= 9728 && x <= 10175) || (x >= 127744 && x <= 128591) || (x >= 128640 && x <= 128764) || (x >= 128992 && x <= 129003) || (x >= 129280 && x <= 129535) || (x >= 129648 && x <= 129651) || (x >= 129656 && x <= 129666) || (x >= 129680 && x <= 129685)); } 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 safeBtoa(str) { return btoa(encodeURIComponent(str)); // we use encodeURIComponent because btoa fails for non Latin 1 values } exports.safeBtoa = safeBtoa; function repeat(s, count) { var result = ''; for (var i = 0; i < count; i++) { result += s; } return result; } exports.repeat = repeat; function containsUppercaseCharacter(target, ignoreEscapedChars) { if (ignoreEscapedChars === void 0) { 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) { var LETTERS_CNT = (90 /* Z */ - 65 /* A */ + 1); n = n % (2 * LETTERS_CNT); if (n < LETTERS_CNT) { return String.fromCharCode(97 /* a */ + n); } return String.fromCharCode(65 /* A */ + n - LETTERS_CNT); } exports.singleLetterHash = singleLetterHash; //#region Unicode Grapheme Break function getGraphemeBreakType(codePoint) { var graphemeBreakTree = GraphemeBreakTree.getInstance(); return graphemeBreakTree.getGraphemeBreakType(codePoint); } exports.getGraphemeBreakType = getGraphemeBreakType; function breakBetweenGraphemeBreakType(breakTypeA, breakTypeB) { // http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules // !!! Let's make the common case a bit faster if (breakTypeA === 0 /* Other */) { // see https://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakTest-13.0.0d10.html#table return (breakTypeB !== 5 /* Extend */ && breakTypeB !== 7 /* SpacingMark */); } // Do not break between a CR and LF. Otherwise, break before and after controls. // GB3 CR × LF // GB4 (Control | CR | LF) ÷ // GB5 ÷ (Control | CR | LF) if (breakTypeA === 2 /* CR */) { if (breakTypeB === 3 /* LF */) { return false; // GB3 } } if (breakTypeA === 4 /* Control */ || breakTypeA === 2 /* CR */ || breakTypeA === 3 /* LF */) { return true; // GB4 } if (breakTypeB === 4 /* Control */ || breakTypeB === 2 /* CR */ || breakTypeB === 3 /* LF */) { return true; // GB5 } // Do not break Hangul syllable sequences. // GB6 L × (L | V | LV | LVT) // GB7 (LV | V) × (V | T) // GB8 (LVT | T) × T if (breakTypeA === 8 /* L */) { if (breakTypeB === 8 /* L */ || breakTypeB === 9 /* V */ || breakTypeB === 11 /* LV */ || breakTypeB === 12 /* LVT */) { return false; // GB6 } } if (breakTypeA === 11 /* LV */ || breakTypeA === 9 /* V */) { if (breakTypeB === 9 /* V */ || breakTypeB === 10 /* T */) { return false; // GB7 } } if (breakTypeA === 12 /* LVT */ || breakTypeA === 10 /* T */) { if (breakTypeB === 10 /* T */) { return false; // GB8 } } // Do not break before extending characters or ZWJ. // GB9 × (Extend | ZWJ) if (breakTypeB === 5 /* Extend */ || breakTypeB === 13 /* ZWJ */) { return false; // GB9 } // The GB9a and GB9b rules only apply to extended grapheme clusters: // Do not break before SpacingMarks, or after Prepend characters. // GB9a × SpacingMark // GB9b Prepend × if (breakTypeB === 7 /* SpacingMark */) { return false; // GB9a } if (breakTypeA === 1 /* Prepend */) { return false; // GB9b } // Do not break within emoji modifier sequences or emoji zwj sequences. // GB11 \p{Extended_Pictographic} Extend* ZWJ × \p{Extended_Pictographic} if (breakTypeA === 13 /* ZWJ */ && breakTypeB === 14 /* Extended_Pictographic */) { // Note: we are not implementing the rule entirely here to avoid introducing states return false; // GB11 } // GB12 sot (RI RI)* RI × RI // GB13 [^RI] (RI RI)* RI × RI if (breakTypeA === 6 /* Regional_Indicator */ && breakTypeB === 6 /* Regional_Indicator */) { // Note: we are not implementing the rule entirely here to avoid introducing states return false; // GB12 & GB13 } // GB999 Any ÷ Any return true; } exports.breakBetweenGraphemeBreakType = breakBetweenGraphemeBreakType; var GraphemeBreakTree = /** @class */ (function () { function GraphemeBreakTree() { this._data = getGraphemeBreakRawData(); } GraphemeBreakTree.getInstance = function () { if (!GraphemeBreakTree._INSTANCE) { GraphemeBreakTree._INSTANCE = new GraphemeBreakTree(); } return GraphemeBreakTree._INSTANCE; }; GraphemeBreakTree.prototype.getGraphemeBreakType = function (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 */; } var data = this._data; var nodeCount = data.length / 3; var 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; return GraphemeBreakTree; }()); function getGraphemeBreakRawData() { // generated using https://github.com/alexandrudima/unicode-utils/blob/master/generate-grapheme-break.js return JSON.parse('[0,0,0,51592,51592,11,44424,44424,11,72251,72254,5,7150,7150,7,48008,48008,11,55176,55176,11,128420,128420,14,3276,3277,5,9979,9980,14,46216,46216,11,49800,49800,11,53384,53384,11,70726,70726,5,122915,122916,5,129320,129327,14,2558,2558,5,5906,5908,5,9762,9763,14,43360,43388,8,45320,45320,11,47112,47112,11,48904,48904,11,50696,50696,11,52488,52488,11,54280,54280,11,70082,70083,1,71350,71350,7,73111,73111,5,127892,127893,14,128726,128727,14,129473,129474,14,2027,2035,5,2901,2902,5,3784,3789,5,6754,6754,5,8418,8420,5,9877,9877,14,11088,11088,14,44008,44008,5,44872,44872,11,45768,45768,11,46664,46664,11,47560,47560,11,48456,48456,11,49352,49352,11,50248,50248,11,51144,51144,11,52040,52040,11,52936,52936,11,53832,53832,11,54728,54728,11,69811,69814,5,70459,70460,5,71096,71099,7,71998,71998,5,72874,72880,5,119149,119149,7,127374,127374,14,128335,128335,14,128482,128482,14,128765,128767,14,129399,129400,14,129680,129685,14,1476,1477,5,2377,2380,7,2759,2760,5,3137,3140,7,3458,3459,7,4153,4154,5,6432,6434,5,6978,6978,5,7675,7679,5,9723,9726,14,9823,9823,14,9919,9923,14,10035,10036,14,42736,42737,5,43596,43596,5,44200,44200,11,44648,44648,11,45096,45096,11,45544,45544,11,45992,45992,11,46440,46440,11,46888,46888,11,47336,47336,11,47784,47784,11,48232,48232,11,48680,48680,11,49128,49128,11,49576,49576,11,50024,50024,11,50472,50472,11,50920,50920,11,51368,51368,11,51816,51816,11,52264,52264,11,52712,52712,11,53160,53160,11,53608,53608,11,54056,54056,11,54504,54504,11,54952,54952,11,68108,68111,5,69933,69940,5,70197,70197,7,70498,70499,7,70845,70845,5,71229,71229,5,71727,71735,5,72154,72155,5,72344,72345,5,73023,73029,5,94095,94098,5,121403,121452,5,126981,127182,14,127538,127546,14,127990,127990,14,128391,128391,14,128445,128449,14,128500,128505,14,128752,128752,14,129160,129167,14,129356,129356,14,129432,129442,14,129648,129651,14,129751,131069,14,173,173,4,1757,1757,1,2274,2274,1,2494,2494,5,2641,2641,5,2876,2876,5,3014,3016,7,3262,3262,7,3393,3396,5,3570,3571,7,3968,3972,5,4228,4228,7,6086,6086,5,6679,6680,5,6912,6915,5,7080,7081,5,7380,7392,5,8252,8252,14,9096,9096,14,9748,9749,14,9784,9786,14,9833,9850,14,9890,9894,14,9938,9938,14,9999,9999,14,10085,10087,14,12349,12349,14,43136,43137,7,43454,43456,7,43755,43755,7,44088,44088,11,44312,44312,11,44536,44536,11,44760,44760,11,44984,44984,11,45208,45208,11,45432,45432,11,45656,45656,11,45880,45880,11,46104,46104,11,46328,46328,11,46552,46552,11,46776,46776,11,47000,47000,11,47224,47224,11,47448,47448,11,47672,47672,11,47896,47896,11,48120,48120,11,48344,48344,11,48568,48568,11,48792,48792,11,49016,49016,11,49240,49240,11,49464,49464,11,49688,49688,11,49912,49912,11,50136,50136,11,50360,50360,11,50584,50584,11,50808,50808,11,51032,51032,11,51256,51256,11,51480,51480,11,51704,51704,11,51928,51928,11,52152,52152,11,52376,52376,11,52600,52600,11,52824,52824,11,53048,53048,11,53272,53272,11,53496,53496,11,53720,53720,11,53944,53944,11,54168,54168,11,54392,54392,11,54616,54616,11,54840,54840,11,55064,55064,11,65438,65439,5,69633,69633,5,69837,69837,1,70018,70018,7,70188,70190,7,70368,70370,7,70465,70468,7,70712,70719,5,70835,70840,5,70850,70851,5,71132,71133,5,71340,71340,7,71458,71461,5,71985,71989,7,72002,72002,7,72193,72202,5,72281,72283,5,72766,72766,7,72885,72886,5,73104,73105,5,92912,92916,5,113824,113827,4,119173,119179,5,121505,121519,5,125136,125142,5,127279,127279,14,127489,127490,14,127570,127743,14,127900,127901,14,128254,128254,14,128369,128370,14,128400,128400,14,128425,128432,14,128468,128475,14,128489,128494,14,128715,128720,14,128745,128745,14,128759,128760,14,129004,129023,14,129296,129304,14,129340,129342,14,129388,129392,14,129404,129407,14,129454,129455,14,129485,129487,14,129659,129663,14,129719,129727,14,917536,917631,5,13,13,2,1160,1161,5,1564,1564,4,1807,1807,1,2085,2087,5,2363,2363,7,2402,2403,5,2507,2508,7,2622,2624,7,2691,2691,7,2786,2787,5,2881,2884,5,3006,3006,5,3072,3072,5,3170,3171,5,3267,3268,7,3330,3331,7,3406,3406,1,3538,3540,5,3655,3662,5,3897,3897,5,4038,4038,5,4184,4185,5,4352,4447,8,6068,6069,5,6155,6157,5,6448,6449,7,6742,6742,5,6783,6783,5,6966,6970,5,7042,7042,7,7143,7143,7,7212,7219,5,7412,7412,5,8206,8207,4,8294,8303,4,8596,8601,14,9410,9410,14,9742,9742,14,9757,9757,14,9770,9770,14,9794,9794,14,9828,9828,14,9855,9855,14,9882,9882,14,9900,9903,14,9929,9933,14,9963,9967,14,9987,9988,14,10006,10006,14,10062,10062,14,10175,10175,14,11744,11775,5,42607,42607,5,43043,43044,7,43263,43263,5,43444,43445,7,43569,43570,5,43698,43700,5,43766,43766,5,44032,44032,11,44144,44144,11,44256,44256,11,44368,44368,11,44480,44480,11,44592,44592,11,44704,44704,11,44816,44816,11,44928,44928,11,45040,45040,11,45152,45152,11,45264,45264,11,45376,45376,11,45488,45488,11,45600,45600,11,45712,45712,11,45824,45824,11,45936,45936,11,46048,46048,11,46160,46160,11,46272,46272,11,46384,46384,11,46496,46496,11,46608,46608,11,46720,46720,11,46832,46832,11,46944,46944,11,47056,47056,11,47168,47168,11,47280,47280,11,47392,47392,11,47504,47504,11,47616,47616,11,47728,47728,11,47840,47840,11,47952,47952,11,48064,48064,11,48176,48176,11,48288,48288,11,48400,48400,11,48512,48512,11,48624,48624,11,48736,48736,11,48848,48848,11,48960,48960,11,49072,49072,11,49184,49184,11,49296,49296,11,49408,49408,11,49520,49520,11,49632,49632,11,49744,49744,11,49856,49856,11,49968,49968,11,50080,50080,11,50192,50192,11,50304,50304,11,50416,50416,11,50528,50528,11,50640,50640,11,50752,50752,11,50864,50864,11,50976,50976,11,51088,51088,11,51200,51200,11,51312,51312,11,51424,51424,11,51536,51536,11,51648,51648,11,51760,51760,11,51872,51872,11,51984,51984,11,52096,52096,11,52208,52208,11,52320,52320,11,52432,52432,11,52544,52544,11,52656,52656,11,52768,52768,11,52880,52880,11,52992,52992,11,53104,53104,11,53216,53216,11,53328,53328,11,53440,53440,11,53552,53552,11,53664,53664,11,53776,53776,11,53888,53888,11,54000,54000,11,54112,54112,11,54224,54224,11,54336,54336,11,54448,54448,11,54560,54560,11,54672,54672,11,54784,54784,11,54896,54896,11,55008,55008,11,55120,55120,11,64286,64286,5,66272,66272,5,68900,68903,5,69762,69762,7,69817,69818,5,69927,69931,5,70003,70003,5,70070,70078,5,70094,70094,7,70194,70195,7,70206,70206,5,70400,70401,5,70463,70463,7,70475,70477,7,70512,70516,5,70722,70724,5,70832,70832,5,70842,70842,5,70847,70848,5,71088,71089,7,71102,71102,7,71219,71226,5,71231,71232,5,71342,71343,7,71453,71455,5,71463,71467,5,71737,71738,5,71995,71996,5,72000,72000,7,72145,72147,7,72160,72160,5,72249,72249,7,72273,72278,5,72330,72342,5,72752,72758,5,72850,72871,5,72882,72883,5,73018,73018,5,73031,73031,5,73109,73109,5,73461,73462,7,94031,94031,5,94192,94193,7,119142,119142,7,119155,119162,4,119362,119364,5,121476,121476,5,122888,122904,5,123184,123190,5,126976,126979,14,127184,127231,14,127344,127345,14,127405,127461,14,127514,127514,14,127561,127567,14,127778,127779,14,127896,127896,14,127985,127986,14,127995,127999,5,128326,128328,14,128360,128366,14,128378,128378,14,128394,128397,14,128405,128406,14,128422,128423,14,128435,128443,14,128453,128464,14,128479,128480,14,128484,128487,14,128496,128498,14,128640,128709,14,128723,128724,14,128736,128741,14,128747,128748,14,128755,128755,14,128762,128762,14,128981,128991,14,129096,129103,14,129292,129292,14,129311,129311,14,129329,129330,14,129344,129349,14,129360,129374,14,129394,129394,14,129402,129402,14,129413,129425,14,129445,129450,14,129466,129471,14,129483,129483,14,129511,129535,14,129653,129655,14,129667,129670,14,129705,129711,14,129731,129743,14,917505,917505,4,917760,917999,5,10,10,3,127,159,4,768,879,5,1471,1471,5,1536,1541,1,1648,1648,5,1767,1768,5,1840,1866,5,2070,2073,5,2137,2139,5,2307,2307,7,2366,2368,7,2382,2383,7,2434,2435,7,2497,2500,5,2519,2519,5,2563,2563,7,2631,2632,5,2677,2677,5,2750,2752,7,2763,2764,7,2817,2817,5,2879,2879,5,2891,2892,7,2914,2915,5,3008,3008,5,3021,3021,5,3076,3076,5,3146,3149,5,3202,3203,7,3264,3265,7,3271,3272,7,3298,3299,5,3390,3390,5,3402,3404,7,3426,3427,5,3535,3535,5,3544,3550,7,3635,3635,7,3763,3763,7,3893,3893,5,3953,3966,5,3981,3991,5,4145,4145,7,4157,4158,5,4209,4212,5,4237,4237,5,4520,4607,10,5970,5971,5,6071,6077,5,6089,6099,5,6277,6278,5,6439,6440,5,6451,6456,7,6683,6683,5,6744,6750,5,6765,6770,7,6846,6846,5,6964,6964,5,6972,6972,5,7019,7027,5,7074,7077,5,7083,7085,5,7146,7148,7,7154,7155,7,7222,7223,5,7394,7400,5,7416,7417,5,8204,8204,5,8233,8233,4,8288,8292,4,8413,8416,5,8482,8482,14,8986,8987,14,9193,9203,14,9654,9654,14,9733,9733,14,9745,9745,14,9752,9752,14,9760,9760,14,9766,9766,14,9774,9775,14,9792,9792,14,9800,9811,14,9825,9826,14,9831,9831,14,9852,9853,14,9872,9873,14,9880,9880,14,9885,9887,14,9896,9897,14,9906,9916,14,9926,9927,14,9936,9936,14,9941,9960,14,9974,9974,14,9982,9985,14,9992,9997,14,10002,10002,14,10017,10017,14,10055,10055,14,10071,10071,14,10145,10145,14,11013,11015,14,11503,11505,5,12334,12335,5,12951,12951,14,42612,42621,5,43014,43014,5,43047,43047,7,43204,43205,5,43335,43345,5,43395,43395,7,43450,43451,7,43561,43566,5,43573,43574,5,43644,43644,5,43710,43711,5,43758,43759,7,44005,44005,5,44012,44012,7,44060,44060,11,44116,44116,11,44172,44172,11,44228,44228,11,44284,44284,11,44340,44340,11,44396,44396,11,44452,44452,11,44508,44508,11,44564,44564,11,44620,44620,11,44676,44676,11,44732,44732,11,44788,44788,11,44844,44844,11,44900,44900,11,44956,44956,11,45012,45012,11,45068,45068,11,45124,45124,11,45180,45180,11,45236,45236,11,45292,45292,11,45348,45348,11,45404,45404,11,45460,45460,11,45516,45516,11,45572,45572,11,45628,45628,11,45684,45684,11,45740,45740,11,45796,45796,11,45852,45852,11,45908,45908,11,45964,45964,11,46020,46020,11,46076,46076,11,46132,46132,11,46188,46188,11,46244,46244,11,46300,46300,11,46356,46356,11,46412,46412,11,46468,46468,11,46524,46524,11,46580,46580,11,46636,46636,11,46692,46692,11,46748,46748,11,46804,46804,11,46860,46860,11,46916,46916,11,46972,46972,11,47028,47028,11,47084,47084,11,47140,47140,11,47196,47196,11,47252,47252,11,47308,47308,11,47364,47364,11,47420,47420,11,47476,47476,11,47532,47532,11,47588,47588,11,47644,47644,11,47700,47700,11,47756,47756,11,47812,47812,11,47868,47868,11,47924,47924,11,47980,47980,11,48036,48036,11,48092,48092,11,48148,48148,11,48204,48204,11,48260,48260,11,48316,48316,11,48372,48372,11,48428,48428,11,48484,48484,11,48540,48540,11,48596,48596,11,48652,48652,11,48708,48708,11,48764,48764,11,48820,48820,11,48876,48876,11,48932,48932,11,48988,48988,11,49044,49044,11,49100,49100,11,49156,49156,11,49212,49212,11,49268,49268,11,49324,49324,11,49380,49380,11,49436,49436,11,49492,49492,11,49548,49548,11,49604,49604,11,49660,49660,11,49716,49716,11,49772,49772,11,49828,49828,11,49884,49884,11,49940,49940,11,49996,49996,11,50052,50052,11,50108,50108,11,50164,50164,11,50220,50220,11,50276,50276,11,50332,50332,11,50388,50388,11,50444,50444,11,50500,50500,11,50556,50556,11,50612,50612,11,50668,50668,11,50724,50724,11,50780,50780,11,50836,50836,11,50892,50892,11,50948,50948,11,51004,51004,11,51060,51060,11,51116,51116,11,51172,51172,11,51228,51228,11,51284,51284,11,51340,51340,11,51396,51396,11,51452,51452,11,51508,51508,11,51564,51564,11,51620,51620,11,51676,51676,11,51732,51732,11,51788,51788,11,51844,51844,11,51900,51900,11,51956,51956,11,52012,52012,11,52068,52068,11,52124,52124,11,52180,52180,11,52236,52236,11,52292,52292,11,52348,52348,11,52404,52404,11,52460,52460,11,52516,52516,11,52572,52572,11,52628,52628,11,52684,52684,11,52740,52740,11,52796,52796,11,52852,52852,11,52908,52908,11,52964,52964,11,53020,53020,11,53076,53076,11,53132,53132,11,53188,53188,11,53244,53244,11,53300,53300,11,53356,53356,11,53412,53412,11,53468,53468,11,53524,53524,11,53580,53580,11,53636,53636,11,53692,53692,11,53748,53748,11,53804,53804,11,53860,53860,11,53916,53916,11,53972,53972,11,54028,54028,11,54084,54084,11,54140,54140,11,54196,54196,11,54252,54252,11,54308,54308,11,54364,54364,11,54420,54420,11,54476,54476,11,54532,54532,11,54588,54588,11,54644,54644,11,54700,54700,11,54756,54756,11,54812,54812,11,54868,54868,11,54924,54924,11,54980,54980,11,55036,55036,11,55092,55092,11,55148,55148,11,55216,55238,9,65056,65071,5,65529,65531,4,68097,68099,5,68159,68159,5,69446,69456,5,69688,69702,5,69808,69810,7,69815,69816,7,69821,69821,1,69888,69890,5,69932,69932,7,69957,69958,7,70016,70017,5,70067,70069,7,70079,70080,7,70089,70092,5,70095,70095,5,70191,70193,5,70196,70196,5,70198,70199,5,70367,70367,5,70371,70378,5,70402,70403,7,70462,70462,5,70464,70464,5,70471,70472,7,70487,70487,5,70502,70508,5,70709,70711,7,70720,70721,7,70725,70725,7,70750,70750,5,70833,70834,7,70841,70841,7,70843,70844,7,70846,70846,7,70849,70849,7,71087,71087,5,71090,71093,5,71100,71101,5,71103,71104,5,71216,71218,7,71227,71228,7,71230,71230,7,71339,71339,5,71341,71341,5,71344,71349,5,71351,71351,5,71456,71457,7,71462,71462,7,71724,71726,7,71736,71736,7,71984,71984,5,71991,71992,7,71997,71997,7,71999,71999,1,72001,72001,1,72003,72003,5,72148,72151,5,72156,72159,7,72164,72164,7,72243,72248,5,72250,72250,1,72263,72263,5,72279,72280,7,72324,72329,1,72343,72343,7,72751,72751,7,72760,72765,5,72767,72767,5,72873,72873,7,72881,72881,7,72884,72884,7,73009,73014,5,73020,73021,5,73030,73030,1,73098,73102,7,73107,73108,7,73110,73110,7,73459,73460,5,78896,78904,4,92976,92982,5,94033,94087,7,94180,94180,5,113821,113822,5,119141,119141,5,119143,119145,5,119150,119154,5,119163,119170,5,119210,119213,5,121344,121398,5,121461,121461,5,121499,121503,5,122880,122886,5,122907,122913,5,122918,122922,5,123628,123631,5,125252,125258,5,126980,126980,14,127183,127183,14,127245,127247,14,127340,127343,14,127358,127359,14,127377,127386,14,127462,127487,6,127491,127503,14,127535,127535,14,127548,127551,14,127568,127569,14,127744,127777,14,127780,127891,14,127894,127895,14,127897,127899,14,127902,127984,14,127987,127989,14,127991,127994,14,128000,128253,14,128255,128317,14,128329,128334,14,128336,128359,14,128367,128368,14,128371,128377,14,128379,128390,14,128392,128393,14,128398,128399,14,128401,128404,14,128407,128419,14,128421,128421,14,128424,128424,14,128433,128434,14,128444,128444,14,128450,128452,14,128465,128467,14,128476,128478,14,128481,128481,14,128483,128483,14,128488,128488,14,128495,128495,14,128499,128499,14,128506,128591,14,128710,128714,14,128721,128722,14,128725,128725,14,128728,128735,14,128742,128744,14,128746,128746,14,128749,128751,14,128753,128754,14,128756,128758,14,128761,128761,14,128763,128764,14,128884,128895,14,128992,129003,14,129036,129039,14,129114,129119,14,129198,129279,14,129293,129295,14,129305,129310,14,129312,129319,14,129328,129328,14,129331,129338,14,129343,129343,14,129351,129355,14,129357,129359,14,129375,129387,14,129393,129393,14,129395,129398,14,129401,129401,14,129403,129403,14,129408,129412,14,129426,129431,14,129443,129444,14,129451,129453,14,129456,129465,14,129472,129472,14,129475,129482,14,129484,129484,14,129488,129510,14,129536,129647,14,129652,129652,14,129656,129658,14,129664,129666,14,129671,129679,14,129686,129704,14,129712,129718,14,129728,129730,14,129744,129750,14,917504,917504,4,917506,917535,4,917632,917759,4,918000,921599,4,0,9,4,11,12,4,14,31,4,169,169,14,174,174,14,1155,1159,5,1425,1469,5,1473,1474,5,1479,1479,5,1552,1562,5,1611,1631,5,1750,1756,5,1759,1764,5,1770,1773,5,1809,1809,5,1958,1968,5,2045,2045,5,2075,2083,5,2089,2093,5,2259,2273,5,2275,2306,5,2362,2362,5,2364,2364,5,2369,2376,5,2381,2381,5,2385,2391,5,2433,2433,5,2492,2492,5,2495,2496,7,2503,2504,7,2509,2509,5,2530,2531,5,2561,2562,5,2620,2620,5,2625,2626,5,2635,2637,5,2672,2673,5,2689,2690,5,2748,2748,5,2753,2757,5,2761,2761,7,2765,2765,5,2810,2815,5,2818,2819,7,2878,2878,5,2880,2880,7,2887,2888,7,2893,2893,5,2903,2903,5,2946,2946,5,3007,3007,7,3009,3010,7,3018,3020,7,3031,3031,5,3073,3075,7,3134,3136,5,3142,3144,5,3157,3158,5,3201,3201,5,3260,3260,5,3263,3263,5,3266,3266,5,3270,3270,5,3274,3275,7,3285,3286,5,3328,3329,5,3387,3388,5,3391,3392,7,3398,3400,7,3405,3405,5,3415,3415,5,3457,3457,5,3530,3530,5,3536,3537,7,3542,3542,5,3551,3551,5,3633,3633,5,3636,3642,5,3761,3761,5,3764,3772,5,3864,3865,5,3895,3895,5,3902,3903,7,3967,3967,7,3974,3975,5,3993,4028,5,4141,4144,5,4146,4151,5,4155,4156,7,4182,4183,7,4190,4192,5,4226,4226,5,4229,4230,5,4253,4253,5,4448,4519,9,4957,4959,5,5938,5940,5,6002,6003,5,6070,6070,7,6078,6085,7,6087,6088,7,6109,6109,5,6158,6158,4,6313,6313,5,6435,6438,7,6441,6443,7,6450,6450,5,6457,6459,5,6681,6682,7,6741,6741,7,6743,6743,7,6752,6752,5,6757,6764,5,6771,6780,5,6832,6845,5,6847,6848,5,6916,6916,7,6965,6965,5,6971,6971,7,6973,6977,7,6979,6980,7,7040,7041,5,7073,7073,7,7078,7079,7,7082,7082,7,7142,7142,5,7144,7145,5,7149,7149,5,7151,7153,5,7204,7211,7,7220,7221,7,7376,7378,5,7393,7393,7,7405,7405,5,7415,7415,7,7616,7673,5,8203,8203,4,8205,8205,13,8232,8232,4,8234,8238,4,8265,8265,14,8293,8293,4,8400,8412,5,8417,8417,5,8421,8432,5,8505,8505,14,8617,8618,14,9000,9000,14,9167,9167,14,9208,9210,14,9642,9643,14,9664,9664,14,9728,9732,14,9735,9741,14,9743,9744,14,9746,9746,14,9750,9751,14,9753,9756,14,9758,9759,14,9761,9761,14,9764,9765,14,9767,9769,14,9771,9773,14,9776,9783,14,9787,9791,14,9793,9793,14,9795,9799,14,9812,9822,14,9824,9824,14,9827,9827,14,9829,9830,14,9832,9832,14,9851,9851,14,9854,9854,14,9856,9861,14,9874,9876,14,9878,9879,14,9881,9881,14,9883,9884,14,9888,9889,14,9895,9895,14,9898,9899,14,9904,9905,14,9917,9918,14,9924,9925,14,9928,9928,14,9934,9935,14,9937,9937,14,9939,9940,14,9961,9962,14,9968,9973,14,9975,9978,14,9981,9981,14,9986,9986,14,9989,9989,14,9998,9998,14,10000,10001,14,10004,10004,14,10013,10013,14,10024,10024,14,10052,10052,14,10060,10060,14,10067,10069,14,10083,10084,14,10133,10135,14,10160,10160,14,10548,10549,14,11035,11036,14,11093,11093,14,11647,11647,5,12330,12333,5,12336,12336,14,12441,12442,5,12953,12953,14,42608,42610,5,42654,42655,5,43010,43010,5,43019,43019,5,43045,43046,5,43052,43052,5,43188,43203,7,43232,43249,5,43302,43309,5,43346,43347,7,43392,43394,5,43443,43443,5,43446,43449,5,43452,43453,5,43493,43493,5,43567,43568,7,43571,43572,7,43587,43587,5,43597,43597,7,43696,43696,5,43703,43704,5,43713,43713,5,43756,43757,5,43765,43765,7,44003,44004,7,44006,44007,7,44009,44010,7,44013,44013,5,44033,44059,12,44061,44087,12,44089,44115,12,44117,44143,12,44145,44171,12,44173,44199,12,44201,44227,12,44229,44255,12,44257,44283,12,44285,44311,12,44313,44339,12,44341,44367,12,44369,44395,12,44397,44423,12,44425,44451,12,44453,44479,12,44481,44507,12,44509,44535,12,44537,44563,12,44565,44591,12,44593,44619,12,44621,44647,12,44649,44675,12,44677,44703,12,44705,44731,12,44733,44759,12,44761,44787,12,44789,44815,12,44817,44843,12,44845,44871,12,44873,44899,12,44901,44927,12,44929,44955,12,44957,44983,12,44985,45011,12,45013,45039,12,45041,45067,12,45069,45095,12,45097,45123,12,45125,45151,12,45153,45179,12,45181,45207,12,45209,45235,12,45237,45263,12,45265,45291,12,45293,45319,12,45321,45347,12,45349,45375,12,45377,45403,12,45405,45431,12,45433,45459,12,45461,45487,12,45489,45515,12,45517,45543,12,45545,45571,12,45573,45599,12,45601,45627,12,45629,45655,12,45657,45683,12,45685,45711,12,45713,45739,12,45741,45767,12,45769,45795,12,45797,45823,12,45825,45851,12,45853,45879,12,45881,45907,12,45909,45935,12,45937,45963,12,45965,45991,12,45993,46019,12,46021,46047,12,46049,46075,12,46077,46103,12,46105,46131,12,46133,46159,12,46161,46187,12,46189,46215,12,46217,46243,12,46245,46271,12,46273,46299,12,46301,46327,12,46329,46355,12,46357,46383,12,46385,46411,12,46413,46439,12,46441,46467,12,46469,46495,12,46497,46523,12,46525,46551,12,46553,46579,12,46581,46607,12,46609,46635,12,46637,46663,12,46665,46691,12,46693,46719,12,46721,46747,12,46749,46775,12,46777,46803,12,46805,46831,12,46833,46859,12,46861,46887,12,46889,46915,12,46917,46943,12,46945,46971,12,46973,46999,12,47001,47027,12,47029,47055,12,47057,47083,12,47085,47111,12,47113,47139,12,47141,47167,12,47169,47195,12,47197,47223,12,47225,47251,12,47253,47279,12,47281,47307,12,47309,47335,12,47337,47363,12,47365,47391,12,47393,47419,12,47421,47447,12,47449,47475,12,47477,47503,12,47505,47531,12,47533,47559,12,47561,47587,12,47589,47615,12,47617,47643,12,47645,47671,12,47673,47699,12,47701,47727,12,47729,47755,12,47757,47783,12,47785,47811,12,47813,47839,12,47841,47867,12,47869,47895,12,47897,47923,12,47925,47951,12,47953,47979,12,47981,48007,12,48009,48035,12,48037,48063,12,48065,48091,12,48093,48119,12,48121,48147,12,48149,48175,12,48177,48203,12,48205,48231,12,48233,48259,12,48261,48287,12,48289,48315,12,48317,48343,12,48345,48371,12,48373,48399,12,48401,48427,12,48429,48455,12,48457,48483,12,48485,48511,12,48513,48539,12,48541,48567,12,48569,48595,12,48597,48623,12,48625,48651,12,48653,48679,12,48681,48707,12,48709,48735,12,48737,48763,12,48765,48791,12,48793,48819,12,48821,48847,12,48849,48875,12,48877,48903,12,48905,48931,12,48933,48959,12,48961,48987,12,48989,49015,12,49017,49043,12,49045,49071,12,49073,49099,12,49101,49127,12,49129,49155,12,49157,49183,12,49185,49211,12,49213,49239,12,49241,49267,12,49269,49295,12,49297,49323,12,49325,49351,12,49353,49379,12,49381,49407,12,49409,49435,12,49437,49463,12,49465,49491,12,49493,49519,12,49521,49547,12,49549,49575,12,49577,49603,12,49605,49631,12,49633,49659,12,49661,49687,12,49689,49715,12,49717,49743,12,49745,49771,12,49773,49799,12,49801,49827,12,49829,49855,12,49857,49883,12,49885,49911,12,49913,49939,12,49941,49967,12,49969,49995,12,49997,50023,12,50025,50051,12,50053,50079,12,50081,50107,12,50109,50135,12,50137,50163,12,50165,50191,12,50193,50219,12,50221,50247,12,50249,50275,12,50277,50303,12,50305,50331,12,50333,50359,12,50361,50387,12,50389,50415,12,50417,50443,12,50445,50471,12,50473,50499,12,50501,50527,12,50529,50555,12,50557,50583,12,50585,50611,12,50613,50639,12,50641,50667,12,50669,50695,12,50697,50723,12,50725,50751,12,50753,50779,12,50781,50807,12,50809,50835,12,50837,50863,12,50865,50891,12,50893,50919,12,50921,50947,12,50949,50975,12,50977,51003,12,51005,51031,12,51033,51059,12,51061,51087,12,51089,51115,12,51117,51143,12,51145,51171,12,51173,51199,12,51201,51227,12,51229,51255,12,51257,51283,12,51285,51311,12,51313,51339,12,51341,51367,12,51369,51395,12,51397,51423,12,51425,51451,12,51453,51479,12,51481,51507,12,51509,51535,12,51537,51563,12,51565,51591,12,51593,51619,12,51621,51647,12,51649,51675,12,51677,51703,12,51705,51731,12,51733,51759,12,51761,51787,12,51789,51815,12,51817,51843,12,51845,51871,12,51873,51899,12,51901,51927,12,51929,51955,12,51957,51983,12,51985,52011,12,52013,52039,12,52041,52067,12,52069,52095,12,52097,52123,12,52125,52151,12,52153,52179,12,52181,52207,12,52209,52235,12,52237,52263,12,52265,52291,12,52293,52319,12,52321,52347,12,52349,52375,12,52377,52403,12,52405,52431,12,52433,52459,12,52461,52487,12,52489,52515,12,52517,52543,12,52545,52571,12,52573,52599,12,52601,52627,12,52629,52655,12,52657,52683,12,52685,52711,12,52713,52739,12,52741,52767,12,52769,52795,12,52797,52823,12,52825,52851,12,52853,52879,12,52881,52907,12,52909,52935,12,52937,52963,12,52965,52991,12,52993,53019,12,53021,53047,12,53049,53075,12,53077,53103,12,53105,53131,12,53133,53159,12,53161,53187,12,53189,53215,12,53217,53243,12,53245,53271,12,53273,53299,12,53301,53327,12,53329,53355,12,53357,53383,12,53385,53411,12,53413,53439,12,53441,53467,12,53469,53495,12,53497,53523,12,53525,53551,12,53553,53579,12,53581,53607,12,53609,53635,12,53637,53663,12,53665,53691,12,53693,53719,12,53721,53747,12,53749,53775,12,53777,53803,12,53805,53831,12,53833,53859,12,53861,53887,12,53889,53915,12,53917,53943,12,53945,53971,12,53973,53999,12,54001,54027,12,54029,54055,12,54057,54083,12,54085,54111,12,54113,54139,12,54141,54167,12,54169,54195,12,54197,54223,12,54225,54251,12,54253,54279,12,54281,54307,12,54309,54335,12,54337,54363,12,54365,54391,12,54393,54419,12,54421,54447,12,54449,54475,12,54477,54503,12,54505,54531,12,54533,54559,12,54561,54587,12,54589,54615,12,54617,54643,12,54645,54671,12,54673,54699,12,54701,54727,12,54729,54755,12,54757,54783,12,54785,54811,12,54813,54839,12,54841,54867,12,54869,54895,12,54897,54923,12,54925,54951,12,54953,54979,12,54981,55007,12,55009,55035,12,55037,55063,12,55065,55091,12,55093,55119,12,55121,55147,12,55149,55175,12,55177,55203,12,55243,55291,10,65024,65039,5,65279,65279,4,65520,65528,4,66045,66045,5,66422,66426,5,68101,68102,5,68152,68154,5,68325,68326,5,69291,69292,5,69632,69632,7,69634,69634,7,69759,69761,5]'); } }); //#endregion define(__m[177/*vs/base/common/extpath*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,77/*vs/base/common/path*/]), function (require, exports, strings_1, path_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * 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; function isEqualOrParent(path, candidate, ignoreCase, separator) { if (separator === void 0) { separator = path_1.sep; } if (path === candidate) { return true; } if (!path || !candidate) { return false; } if (candidate.length > path.length) { return false; } if (ignoreCase) { var beginsWith = strings_1.startsWithIgnoreCase(path, candidate); if (!beginsWith) { return false; } if (candidate.length === path.length) { return true; // same path, different casing } var sepOffset = candidate.length; if (candidate.charAt(candidate.length - 1) === separator) { sepOffset--; // adjust the expected sep offset in case our candidate already ends in separator character } return path.charAt(sepOffset) === separator; } if (candidate.charAt(candidate.length - 1) !== separator) { candidate += separator; } return path.indexOf(candidate) === 0; } exports.isEqualOrParent = isEqualOrParent; function isWindowsDriveLetter(char0) { return char0 >= 65 /* A */ && char0 <= 90 /* Z */ || char0 >= 97 /* a */ && char0 <= 122 /* z */; } exports.isWindowsDriveLetter = isWindowsDriveLetter; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[61/*vs/base/common/filters*/], __M([0/*require*/,1/*exports*/,38/*vs/base/common/map*/,5/*vs/base/common/strings*/]), function (require, exports, map_1, strings) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // 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() { var filter = []; for (var _i = 0; _i < arguments.length; _i++) { filter[_i] = arguments[_i]; } return function (word, wordToMatchAgainst) { for (var i = 0, len = filter.length; i < len; i++) { var match = filter[i](word, wordToMatchAgainst); if (match) { return match; } } return null; }; } exports.or = or; exports.matchesPrefix = _matchesPrefix.bind(undefined, true); function _matchesPrefix(ignoreCase, word, wordToMatchAgainst) { if (!wordToMatchAgainst || wordToMatchAgainst.length < word.length) { return null; } var 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) { var 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]) { var 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 */); } var wordSeparators = new Set(); '`~!@#$%^&*()-=+[{]}\\|;:\'",.<>/?' .split('') .forEach(function (s) { return wordSeparators.add(s.charCodeAt(0)); }); 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 (var i = start; i < camelCaseWord.length; i++) { var 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 { var result = null; var 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) { var upper = 0, lower = 0, alpha = 0, numeric = 0, code = 0; for (var 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++; } } var upperPercent = upper / word.length; var lowerPercent = lower / word.length; var alphaPercent = alpha / word.length; var numericPercent = numeric / word.length; return { upperPercent: upperPercent, lowerPercent: lowerPercent, alphaPercent: alphaPercent, numericPercent: numericPercent }; } function isUpperCaseWord(analysis) { var upperPercent = analysis.upperPercent, lowerPercent = analysis.lowerPercent; return lowerPercent === 0 && upperPercent > 0.6; } function isCamelCaseWord(analysis) { var upperPercent = analysis.upperPercent, lowerPercent = analysis.lowerPercent, alphaPercent = analysis.alphaPercent, numericPercent = analysis.numericPercent; 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) { var upper = 0, lower = 0, code = 0, whitespace = 0; for (var 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; } var analysis = analyzeCamelCaseWord(camelCaseWord); if (!isCamelCaseWord(analysis)) { if (!isUpperCaseWord(analysis)) { return null; } camelCaseWord = camelCaseWord.toLowerCase(); } var result = null; var 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; // Fuzzy var fuzzyContiguousFilter = or(exports.matchesPrefix, matchesCamelCase, matchesContiguousSubString); var fuzzySeparateFilter = or(exports.matchesPrefix, matchesCamelCase, matchesSubString); var fuzzyRegExpCache = new map_1.LRUCache(10000); // bounded to 10000 elements function matchesFuzzy(word, wordToMatchAgainst, enableSeparateSubstringMatching) { if (enableSeparateSubstringMatching === void 0) { enableSeparateSubstringMatching = false; } if (typeof word !== 'string' || typeof wordToMatchAgainst !== 'string') { return null; // return early for invalid input } // Form RegExp for wildcard matches var regexp = fuzzyRegExpCache.get(word); if (!regexp) { regexp = new RegExp(strings.convertSimple2RegExpPattern(word), 'i'); fuzzyRegExpCache.set(word, regexp); } // RegExp Filter var 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) { var result = fuzzyScore(pattern, lowPattern, 0, word, lowWord, 0, true); if (result) { return result; } var matches = 0; var score = 0; var idx = _wordPos; for (var patternPos = 0; patternPos < lowPattern.length && patternPos < _maxLen; ++patternPos) { var wordPos = lowWord.indexOf(lowPattern.charAt(patternPos), idx); if (wordPos >= 0) { score += 1; matches += Math.pow(2, wordPos); idx = wordPos + 1; } else if (matches !== 0) { // once we have started matching things // we need to match the remaining pattern // characters break; } } return [score, matches, _wordPos]; } exports.anyScore = anyScore; //#region --- fuzzyScore --- function createMatches(score) { if (typeof score === 'undefined') { return []; } var matches = score[1].toString(2); var wordStart = score[2]; var res = []; for (var pos = wordStart; pos < _maxLen; pos++) { if (matches[matches.length - (pos + 1)] === '1') { var 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; var _maxLen = 128; function initTable() { var table = []; var row = [0]; for (var i = 1; i <= _maxLen; i++) { row.push(-i); } for (var i = 0; i <= _maxLen; i++) { var thisRow = row.slice(0); thisRow[0] = -i; table.push(thisRow); } return table; } var _table = initTable(); var _scores = initTable(); var _arrows = initTable(); var _debug = false; function printTable(table, pattern, patternLen, word, wordLen) { function pad(s, n, pad) { if (pad === void 0) { pad = ' '; } while (s.length < n) { s = pad + s; } return s; } var ret = " | |" + word.split('').map(function (c) { return pad(c, 3); }).join('|') + "\n"; for (var i = 0; i <= patternLen; i++) { if (i === 0) { ret += ' |'; } else { ret += pattern[i - 1] + "|"; } ret += table[i].slice(0, wordLen + 1).map(function (n) { return 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(_scores, pattern, pattern.length, word, word.length)); } function isSeparatorAtPos(value, index) { if (index < 0 || index >= value.length) { return false; } var code = value.charCodeAt(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 */: return true; default: return false; } } function isWhitespaceAtPos(value, index) { if (index < 0 || index >= value.length) { return false; } var 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) { while (patternPos < patternLen && wordPos < wordLen) { if (patternLow[patternPos] === wordLow[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 = Object.freeze([-100, 0, 0]); function isDefault(score) { return !score || (score[0] === -100 && score[1] === 0 && score[2] === 0); } FuzzyScore.isDefault = isDefault; })(FuzzyScore = exports.FuzzyScore || (exports.FuzzyScore = {})); function fuzzyScore(pattern, patternLow, patternStart, word, wordLow, wordStart, firstMatchCanBeWeak) { var patternLen = pattern.length > _maxLen ? _maxLen : pattern.length; var 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)) { return undefined; } var row = 1; var column = 1; var patternPos = patternStart; var wordPos = wordStart; // There will be a match, fill in tables for (row = 1, patternPos = patternStart; patternPos < patternLen; row++, patternPos++) { for (column = 1, wordPos = wordStart; wordPos < wordLen; column++, wordPos++) { var score = _doScore(pattern, patternLow, patternPos, patternStart, word, wordLow, wordPos); _scores[row][column] = score; var diag = _table[row - 1][column - 1] + (score > 1 ? 1 : score); var top_1 = _table[row - 1][column] + -1; var left = _table[row][column - 1] + -1; if (left >= top_1) { // left or diag if (left > diag) { _table[row][column] = left; _arrows[row][column] = 4 /* Left */; } else if (left === diag) { _table[row][column] = left; _arrows[row][column] = 4 /* Left */ | 2 /* Diag */; } else { _table[row][column] = diag; _arrows[row][column] = 2 /* Diag */; } } else { // top or diag if (top_1 > diag) { _table[row][column] = top_1; _arrows[row][column] = 1 /* Top */; } else if (top_1 === diag) { _table[row][column] = top_1; _arrows[row][column] = 1 /* Top */ | 2 /* Diag */; } else { _table[row][column] = diag; _arrows[row][column] = 2 /* Diag */; } } } } if (_debug) { printTables(pattern, patternStart, word, wordStart); } _matchesCount = 0; _topScore = -100; _wordStart = wordStart; _firstMatchCanBeWeak = firstMatchCanBeWeak; _findAllMatches2(row - 1, column - 1, patternLen === wordLen ? 1 : 0, 0, false); if (_matchesCount === 0) { return undefined; } return [_topScore, _topMatch2, wordStart]; } exports.fuzzyScore = fuzzyScore; function _doScore(pattern, patternLow, patternPos, patternStart, word, wordLow, wordPos) { if (patternLow[patternPos] !== wordLow[wordPos]) { return -1; } if (wordPos === (patternPos - patternStart)) { // common prefix: `foobar <-> foobaz` // ^^^^^ if (pattern[patternPos] === word[wordPos]) { return 7; } else { return 5; } } else if (isUpperCaseAtPos(wordPos, word, wordLow) && (wordPos === 0 || !isUpperCaseAtPos(wordPos - 1, word, wordLow))) { // hitting upper-case: `foo <-> forOthers` // ^^ ^ if (pattern[patternPos] === word[wordPos]) { return 7; } else { return 5; } } else if (isSeparatorAtPos(wordLow, wordPos) && (wordPos === 0 || !isSeparatorAtPos(wordLow, wordPos - 1))) { // hitting a separator: `. <-> foo.bar` // ^ return 5; } else if (isSeparatorAtPos(wordLow, wordPos - 1) || isWhitespaceAtPos(wordLow, wordPos - 1)) { // post separator: `foo <-> bar_foo` // ^^^ return 5; } else { return 1; } } var _matchesCount = 0; var _topMatch2 = 0; var _topScore = 0; var _wordStart = 0; var _firstMatchCanBeWeak = false; function _findAllMatches2(row, column, total, matches, lastMatched) { if (_matchesCount >= 10 || total < -25) { // stop when having already 10 results, or // when a potential alignment as already 5 gaps return; } var simpleMatchCount = 0; while (row > 0 && column > 0) { var score = _scores[row][column]; var arrow = _arrows[row][column]; if (arrow === 4 /* Left */) { // left -> no match, skip a word character column -= 1; if (lastMatched) { total -= 5; // new gap penalty } else if (matches !== 0) { total -= 1; // gap penalty after first match } lastMatched = false; simpleMatchCount = 0; } else if (arrow & 2 /* Diag */) { if (arrow & 4 /* Left */) { // left _findAllMatches2(row, column - 1, matches !== 0 ? total - 1 : total, // gap penalty after first match matches, lastMatched); } // diag total += score; row -= 1; column -= 1; lastMatched = true; // match -> set a 1 at the word pos matches += Math.pow(2, (column + _wordStart)); // count simple matches and boost a row of // simple matches when they yield in a // strong match. if (score === 1) { simpleMatchCount += 1; if (row === 0 && !_firstMatchCanBeWeak) { // when the first match is a weak // match we discard it return undefined; } } else { // boost total += 1 + (simpleMatchCount * (score - 1)); simpleMatchCount = 0; } } else { return undefined; } } total -= column >= 3 ? 9 : column * 3; // late start penalty // dynamically keep track of the current top score // and insert the current best score at head, the rest at tail _matchesCount += 1; if (total > _topScore) { _topScore = total; _topMatch2 = matches; } } //#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) { var 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`. var tries = Math.min(7, pattern.length - 1); for (var movingPatternPos = patternPos + 1; movingPatternPos < tries; movingPatternPos++) { var newPattern = nextTypoPermutation(pattern, movingPatternPos); if (newPattern) { var 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; } var swap1 = pattern[patternPos]; var swap2 = pattern[patternPos + 1]; if (swap1 === swap2) { return undefined; } return pattern.slice(0, patternPos) + swap2 + swap1 + pattern.slice(patternPos + 2); } }); //#endregion /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[178/*vs/base/common/glob*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,5/*vs/base/common/strings*/,177/*vs/base/common/extpath*/,77/*vs/base/common/path*/,38/*vs/base/common/map*/,15/*vs/base/common/async*/]), function (require, exports, arrays, strings, extpath, paths, map_1, async_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var GLOBSTAR = '**'; var GLOB_SPLIT = '/'; var PATH_REGEX = '[/\\\\]'; // any slash or backslash var NO_PATH_REGEX = '[^/\\\\]'; // any non-slash and non-backslash var 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 []; } var segments = []; var inBraces = false; var inBrackets = false; var curVal = ''; for (var _i = 0, pattern_1 = pattern; _i < pattern_1.length; _i++) { var char = pattern_1[_i]; 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 ''; } var regEx = ''; // Split up into segments for each slash found var segments = splitGlobAware(pattern, GLOB_SPLIT); // Special case where we only have globstars if (segments.every(function (s) { return s === GLOBSTAR; })) { regEx = '.*'; } // Build regex over segments else { var previousSegmentWasGlobStar_1 = false; segments.forEach(function (segment, index) { // Globstar is special if (segment === GLOBSTAR) { // if we have more than one globstar after another, just ignore it if (!previousSegmentWasGlobStar_1) { regEx += starsToRegExp(2); previousSegmentWasGlobStar_1 = true; } return; } // States var inBraces = false; var braceVal = ''; var inBrackets = false; var bracketVal = ''; for (var _i = 0, segment_1 = segment; _i < segment_1.length; _i++) { var char = segment_1[_i]; // 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 */) { var res = void 0; // range operator if (char === '-') { res = char; } // negation operator (only valid on first index in bracket) else if ((char === '^' || char === '!') && !bracketVal) { res = '^'; } // glob split matching is not allowed within character ranges // see http://man7.org/linux/man-pages/man7/glob.7.html else if (char === GLOB_SPLIT) { res = ''; } // anything else gets escaped else { res = strings.escapeRegExpCharacters(char); } bracketVal += res; continue; } switch (char) { case '{': inBraces = true; continue; case '[': inBrackets = true; continue; case '}': var choices = splitGlobAware(braceVal, ','); // Converts {foo,bar} => [foo|bar] var braceRegExp = "(?:" + choices.map(function (c) { return parseRegExp(c); }).join('|') + ")"; regEx += braceRegExp; inBraces = false; braceVal = ''; break; case ']': regEx += ('[' + bracketVal + ']'); inBrackets = false; bracketVal = ''; break; case '?': regEx += NO_PATH_REGEX; // 1 ? matches any single character except path separator (/ and \) continue; case '*': regEx += starsToRegExp(1); continue; default: regEx += strings.escapeRegExpCharacters(char); } } // Tail: Add the slash we had split on if there is more to come and the remaining pattern is not a globstar // For example if pattern: some/**/*.js we want the "/" after some to be included in the RegEx to prevent // a folder called "something" to match as well. // However, if pattern: some/**, we tolerate that we also match on "something" because our globstar behaviour // is to match 0-N segments. if (index < segments.length - 1 && (segments[index + 1] !== GLOBSTAR || index + 2 < segments.length)) { regEx += PATH_REGEX; } // reset state previousSegmentWasGlobStar_1 = false; }); } return regEx; } // regexes to check for trival glob patterns that just check for String#endsWith var T1 = /^\*\*\/\*\.[\w\.-]+$/; // **/*.something var T2 = /^\*\*\/([\w\.-]+)\/?$/; // **/something var T3 = /^{\*\*\/[\*\.]?[\w\.-]+\/?(,\*\*\/[\*\.]?[\w\.-]+\/?)*}$/; // {**/*.something,**/*.else} or {**/package.json,**/project.json} var T3_2 = /^{\*\*\/[\*\.]?[\w\.-]+(\/(\*\*)?)?(,\*\*\/[\*\.]?[\w\.-]+(\/(\*\*)?)?)*}$/; // Like T3, with optional trailing /** var T4 = /^\*\*((\/[\w\.-]+)+)\/?$/; // **/something/else var T5 = /^([\w\.-]+(\/[\w\.-]+)*)\/?$/; // something/else var CACHE = new map_1.LRUCache(10000); // bounded to 10000 elements var FALSE = function () { return false; }; var NULL = function () { return null; }; function parsePattern(arg1, options) { if (!arg1) { return NULL; } // Handle IRelativePattern var pattern; if (typeof arg1 !== 'string') { pattern = arg1.pattern; } else { pattern = arg1; } // Whitespace trimming pattern = pattern.trim(); // Check cache var patternKey = pattern + "_" + !!options.trimForExclusions; var parsedPattern = CACHE.get(patternKey); if (parsedPattern) { return wrapRelativePattern(parsedPattern, arg1); } // Check for Trivias var match; if (T1.test(pattern)) { // common pattern: **/*.txt just need endsWith check var base_1 = pattern.substr(4); // '**/*'.length === 4 parsedPattern = function (path, basename) { return typeof path === 'string' && strings.endsWith(path, base_1) ? pattern : null; }; } else if (match = T2.exec(trimForExclusions(pattern, options))) { // common pattern: **/some.txt just need basename check parsedPattern = trivia2(match[1], pattern); } else if ((options.trimForExclusions ? T3_2 : T3).test(pattern)) { // repetition of common patterns (see above) {**/*.txt,**/*.png} parsedPattern = trivia3(pattern, options); } else if (match = T4.exec(trimForExclusions(pattern, options))) { // common pattern: **/something/else just need endsWith check parsedPattern = trivia4and5(match[1].substr(1), pattern, true); } else if (match = T5.exec(trimForExclusions(pattern, options))) { // common pattern: something/else just need equals check parsedPattern = trivia4and5(match[1], pattern, false); } // Otherwise convert to pattern else { parsedPattern = toRegExp(pattern); } // Cache CACHE.set(patternKey, parsedPattern); return wrapRelativePattern(parsedPattern, arg1); } function wrapRelativePattern(parsedPattern, arg2) { if (typeof arg2 === 'string') { return parsedPattern; } return function (path, basename) { if (!extpath.isEqualOrParent(path, arg2.base)) { return null; } return parsedPattern(paths.relative(arg2.base, path), basename); }; } function trimForExclusions(pattern, options) { return options.trimForExclusions && strings.endsWith(pattern, '/**') ? pattern.substr(0, pattern.length - 2) : pattern; // dropping **, tailing / is dropped later } // common pattern: **/some.txt just need basename check function trivia2(base, originalPattern) { var slashBase = "/" + base; var backslashBase = "\\" + base; var parsedPattern = function (path, basename) { if (typeof path !== 'string') { return null; } if (basename) { return basename === base ? originalPattern : null; } return path === base || strings.endsWith(path, slashBase) || strings.endsWith(path, backslashBase) ? originalPattern : null; }; var 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) { var parsedPatterns = aggregateBasenameMatches(pattern.slice(1, -1).split(',') .map(function (pattern) { return parsePattern(pattern, options); }) .filter(function (pattern) { return pattern !== NULL; }), pattern); var n = parsedPatterns.length; if (!n) { return NULL; } if (n === 1) { return parsedPatterns[0]; } var parsedPattern = function (path, basename) { for (var i = 0, n_1 = parsedPatterns.length; i < n_1; i++) { if (parsedPatterns[i](path, basename)) { return pattern; } } return null; }; var withBasenames = arrays.first(parsedPatterns, function (pattern) { return !!pattern.allBasenames; }); if (withBasenames) { parsedPattern.allBasenames = withBasenames.allBasenames; } var allPaths = parsedPatterns.reduce(function (all, current) { return 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(path, pattern, matchPathEnds) { var nativePath = paths.sep !== paths.posix.sep ? path.replace(ALL_FORWARD_SLASHES, paths.sep) : path; var nativePathEnd = paths.sep + nativePath; var parsedPattern = matchPathEnds ? function (path, basename) { return typeof path === 'string' && (path === nativePath || strings.endsWith(path, nativePathEnd)) ? pattern : null; } : function (path, basename) { return typeof path === 'string' && path === nativePath ? pattern : null; }; parsedPattern.allPaths = [(matchPathEnds ? '*/' : './') + path]; return parsedPattern; } function toRegExp(pattern) { try { var regExp_1 = new RegExp("^" + parseRegExp(pattern) + "$"); return function (path, basename) { regExp_1.lastIndex = 0; // reset RegExp to its initial state to reuse it! return typeof path === 'string' && regExp_1.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 (options === void 0) { options = {}; } if (!arg1) { return FALSE; } // Glob with String if (typeof arg1 === 'string' || isRelativePattern(arg1)) { var parsedPattern_1 = parsePattern(arg1, options); if (parsedPattern_1 === NULL) { return FALSE; } var resultPattern = function (path, basename) { return !!parsedPattern_1(path, basename); }; if (parsedPattern_1.allBasenames) { resultPattern.allBasenames = parsedPattern_1.allBasenames; } if (parsedPattern_1.allPaths) { resultPattern.allPaths = parsedPattern_1.allPaths; } return resultPattern; } // Glob with Expression return parsedExpression(arg1, options); } exports.parse = parse; function isRelativePattern(obj) { var rp = obj; return rp && typeof rp.base === 'string' && typeof rp.pattern === 'string'; } exports.isRelativePattern = isRelativePattern; function parsedExpression(expression, options) { var parsedPatterns = aggregateBasenameMatches(Object.getOwnPropertyNames(expression) .map(function (pattern) { return parseExpressionPattern(pattern, expression[pattern], options); }) .filter(function (pattern) { return pattern !== NULL; })); var n = parsedPatterns.length; if (!n) { return NULL; } if (!parsedPatterns.some(function (parsedPattern) { return !!parsedPattern.requiresSiblings; })) { if (n === 1) { return parsedPatterns[0]; } var resultExpression_1 = function (path, basename) { for (var i = 0, n_2 = parsedPatterns.length; i < n_2; i++) { // Pattern matches path var result = parsedPatterns[i](path, basename); if (result) { return result; } } return null; }; var withBasenames_1 = arrays.first(parsedPatterns, function (pattern) { return !!pattern.allBasenames; }); if (withBasenames_1) { resultExpression_1.allBasenames = withBasenames_1.allBasenames; } var allPaths_1 = parsedPatterns.reduce(function (all, current) { return current.allPaths ? all.concat(current.allPaths) : all; }, []); if (allPaths_1.length) { resultExpression_1.allPaths = allPaths_1; } return resultExpression_1; } var resultExpression = function (path, basename, hasSibling) { var name = undefined; for (var i = 0, n_3 = parsedPatterns.length; i < n_3; i++) { // Pattern matches path var parsedPattern = parsedPatterns[i]; if (parsedPattern.requiresSiblings && hasSibling) { if (!basename) { basename = paths.basename(path); } if (!name) { name = basename.substr(0, basename.length - paths.extname(path).length); } } var result = parsedPattern(path, basename, name, hasSibling); if (result) { return result; } } return null; }; var withBasenames = arrays.first(parsedPatterns, function (pattern) { return !!pattern.allBasenames; }); if (withBasenames) { resultExpression.allBasenames = withBasenames.allBasenames; } var allPaths = parsedPatterns.reduce(function (all, current) { return 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 } var parsedPattern = parsePattern(pattern, options); if (parsedPattern === NULL) { return NULL; } // Expression Pattern is if (typeof value === 'boolean') { return parsedPattern; } // Expression Pattern is if (value) { var when_1 = value.when; if (typeof when_1 === 'string') { var result = function (path, basename, name, hasSibling) { if (!hasSibling || !parsedPattern(path, basename)) { return null; } var clausePattern = when_1.replace('$(basename)', name); var matched = hasSibling(clausePattern); return async_1.isThenable(matched) ? matched.then(function (m) { return m ? pattern : null; }) : matched ? pattern : null; }; result.requiresSiblings = true; return result; } } // Expression is Anything return parsedPattern; } function aggregateBasenameMatches(parsedPatterns, result) { var basenamePatterns = parsedPatterns.filter(function (parsedPattern) { return !!parsedPattern.basenames; }); if (basenamePatterns.length < 2) { return parsedPatterns; } var basenames = basenamePatterns.reduce(function (all, current) { var basenames = current.basenames; return basenames ? all.concat(basenames) : all; }, []); var patterns; if (result) { patterns = []; for (var i = 0, n = basenames.length; i < n; i++) { patterns.push(result); } } else { patterns = basenamePatterns.reduce(function (all, current) { var patterns = current.patterns; return patterns ? all.concat(patterns) : all; }, []); } var aggregate = function (path, basename) { if (typeof path !== 'string') { return null; } if (!basename) { var i = void 0; for (i = path.length; i > 0; i--) { var ch = path.charCodeAt(i - 1); if (ch === 47 /* Slash */ || ch === 92 /* Backslash */) { break; } } basename = path.substr(i); } var index = basenames.indexOf(basename); return index !== -1 ? patterns[index] : null; }; aggregate.basenames = basenames; aggregate.patterns = patterns; aggregate.allBasenames = basenames; var aggregatedPatterns = parsedPatterns.filter(function (parsedPattern) { return !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[247/*vs/base/common/search*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/]), function (require, exports, strings) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function buildReplaceStringWithCasePreserved(matches, pattern) { if (matches && (matches[0] !== '')) { var containsHyphens = validateSpecificSpecialCharacter(matches, pattern, '-'); var 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])) { return pattern[0].toUpperCase() + pattern.substr(1); } else { // we don't understand its pattern yet. return pattern; } } else { return pattern; } } exports.buildReplaceStringWithCasePreserved = buildReplaceStringWithCasePreserved; function validateSpecificSpecialCharacter(matches, pattern, specialCharacter) { var 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) { var splitPatternAtSpecialCharacter = pattern.split(specialCharacter); var splitMatchAtSpecialCharacter = matches[0].split(specialCharacter); var replaceString = ''; splitPatternAtSpecialCharacter.forEach(function (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[21/*vs/base/common/types*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = { number: 'number', string: 'string', undefined: 'undefined', object: 'object', function: 'function' }; /** * @returns whether the provided parameter is a JavaScript Array or not. */ function isArray(array) { if (Array.isArray) { return Array.isArray(array); } if (array && typeof (array.length) === _typeof.number && array.constructor === Array) { return true; } return false; } exports.isArray = isArray; /** * @returns whether the provided parameter is a JavaScript String or not. */ function isString(str) { if (typeof (str) === _typeof.string || str instanceof String) { return true; } return false; } 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 === _typeof.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) { if ((typeof (obj) === _typeof.number || obj instanceof Number) && !isNaN(obj)) { return true; } return false; } 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) === _typeof.undefined; } exports.isUndefined = isUndefined; /** * @returns whether the provided parameter is undefined or null. */ function isUndefinedOrNull(obj) { return isUndefined(obj) || obj === null; } exports.isUndefinedOrNull = isUndefinedOrNull; function assertType(condition, type) { if (!condition) { throw new Error(type ? "Unexpected type, expected '" + type + "'" : 'Unexpected type'); } } exports.assertType = assertType; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * @returns whether the provided parameter is an empty JavaScript Object or not. */ function isEmptyObject(obj) { if (!isObject(obj)) { return false; } for (var key in obj) { if (hasOwnProperty.call(obj, key)) { return false; } } return true; } exports.isEmptyObject = isEmptyObject; /** * @returns whether the provided parameter is a JavaScript Function or not. */ function isFunction(obj) { return typeof obj === _typeof.function; } exports.isFunction = isFunction; function validateConstraints(args, constraints) { var len = Math.min(args.length, constraints.length); for (var 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) { var res = []; var 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) { var methods = []; for (var _i = 0, _a = getAllPropertyNames(obj); _i < _a.length; _i++) { var prop = _a[_i]; if (typeof obj[prop] === 'function') { methods.push(prop); } } return methods; } exports.getAllMethodNames = getAllMethodNames; function createProxyObject(methodNames, invoke) { var createProxyMethod = function (method) { return function () { var args = Array.prototype.slice.call(arguments, 0); return invoke(method, args); }; }; var result = {}; for (var _i = 0, methodNames_1 = methodNames; _i < methodNames_1.length; _i++) { var methodName = methodNames_1[_i]; 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; /** * Converts undefined to null, passes all other values through. */ function withUndefinedAsNull(x) { return typeof x === 'undefined' ? null : x; } exports.withUndefinedAsNull = withUndefinedAsNull; }); /*--------------------------------------------------------------------------------------------- * 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/base/common/objects*/], __M([0/*require*/,1/*exports*/,21/*vs/base/common/types*/]), function (require, exports, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function deepClone(obj) { if (!obj || typeof obj !== 'object') { return obj; } if (obj instanceof RegExp) { // See https://github.com/Microsoft/TypeScript/issues/10990 return obj; } var result = Array.isArray(obj) ? [] : {}; Object.keys(obj).forEach(function (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; } var stack = [obj]; while (stack.length > 0) { var obj_1 = stack.shift(); Object.freeze(obj_1); for (var key in obj_1) { if (_hasOwnProperty.call(obj_1, key)) { var prop = obj_1[key]; if (typeof prop === 'object' && !Object.isFrozen(prop)) { stack.push(prop); } } } } return obj; } exports.deepFreeze = deepFreeze; var _hasOwnProperty = Object.prototype.hasOwnProperty; function cloneAndChange(obj, changer) { return _cloneAndChange(obj, changer, new Set()); } exports.cloneAndChange = cloneAndChange; function _cloneAndChange(obj, changer, seen) { if (types_1.isUndefinedOrNull(obj)) { return obj; } var changed = changer(obj); if (typeof changed !== 'undefined') { return changed; } if (types_1.isArray(obj)) { var r1 = []; for (var _i = 0, obj_2 = obj; _i < obj_2.length; _i++) { var e = obj_2[_i]; r1.push(_cloneAndChange(e, changer, seen)); } return r1; } if (types_1.isObject(obj)) { if (seen.has(obj)) { throw new Error('Cannot clone recursive data-structure'); } seen.add(obj); var r2 = {}; for (var 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) { if (overwrite === void 0) { overwrite = true; } if (!types_1.isObject(destination)) { return source; } if (types_1.isObject(source)) { Object.keys(source).forEach(function (key) { if (key in destination) { if (overwrite) { if (types_1.isObject(destination[key]) && 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 assign(destination) { var sources = []; for (var _i = 1; _i < arguments.length; _i++) { sources[_i - 1] = arguments[_i]; } sources.forEach(function (source) { return Object.keys(source).forEach(function (key) { return destination[key] = source[key]; }); }); return destination; } exports.assign = assign; 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; } var i; var 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 { var oneKeys = []; for (key in one) { oneKeys.push(key); } oneKeys.sort(); var 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) { var 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[133/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/], __M([0/*require*/,1/*exports*/,31/*vs/base/common/objects*/,100/*vs/base/common/codicons*/,5/*vs/base/common/strings*/]), function (require, exports, objects, codicons_1, strings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var HighlightedLabel = /** @class */ (function () { function HighlightedLabel(container, supportCodicons) { this.supportCodicons = supportCodicons; this.text = ''; this.title = ''; this.highlights = []; this.didEverRender = false; this.domNode = document.createElement('span'); this.domNode.className = 'monaco-highlighted-label'; container.appendChild(this.domNode); } Object.defineProperty(HighlightedLabel.prototype, "element", { get: function () { return this.domNode; }, enumerable: true, configurable: true }); HighlightedLabel.prototype.set = function (text, highlights, title, escapeNewLines) { if (highlights === void 0) { highlights = []; } if (title === void 0) { title = ''; } 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; } if (!Array.isArray(highlights)) { highlights = []; } this.text = text; this.title = title; this.highlights = highlights; this.render(); }; HighlightedLabel.prototype.render = function () { var htmlContent = ''; var pos = 0; for (var _i = 0, _a = this.highlights; _i < _a.length; _i++) { var highlight = _a[_i]; if (highlight.end === highlight.start) { continue; } if (pos < highlight.start) { htmlContent += ''; var substring_1 = this.text.substring(pos, highlight.start); htmlContent += this.supportCodicons ? codicons_1.renderCodicons(strings_1.escape(substring_1)) : strings_1.escape(substring_1); htmlContent += ''; pos = highlight.end; } if (highlight.extraClasses) { htmlContent += ""; } else { htmlContent += ""; } var substring = this.text.substring(highlight.start, highlight.end); htmlContent += this.supportCodicons ? codicons_1.renderCodicons(strings_1.escape(substring)) : strings_1.escape(substring); htmlContent += ''; pos = highlight.end; } if (pos < this.text.length) { htmlContent += ''; var substring = this.text.substring(pos); htmlContent += this.supportCodicons ? codicons_1.renderCodicons(strings_1.escape(substring)) : strings_1.escape(substring); htmlContent += ''; } this.domNode.innerHTML = htmlContent; if (this.title) { this.domNode.title = this.title; } else { this.domNode.removeAttribute('title'); } this.didEverRender = true; }; HighlightedLabel.escapeNewLines = function (text, highlights) { var total = 0; var extra = 0; return text.replace(/\r\n|\r|\n/g, function (match, offset) { extra = match === '\r\n' ? -1 : 0; offset += total; for (var _i = 0, highlights_1 = highlights; _i < highlights_1.length; _i++) { var highlight = highlights_1[_i]; if (highlight.end <= offset) { continue; } if (highlight.start >= offset) { highlight.start += extra; } if (highlight.end >= offset) { highlight.end += extra; } } total += extra; return '\u23CE'; }); }; return HighlightedLabel; }()); 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[179/*vs/base/common/uint*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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([0/*require*/,1/*exports*/,16/*vs/base/common/platform*/]), function (require, exports, platform_1) { "use strict"; var _a; Object.defineProperty(exports, "__esModule", { value: true }); var _schemePattern = /^\w[\w\d+.-]*$/; var _singleSlashStart = /^\//; var _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; } var _empty = ''; var _slash = '/'; var _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. * * foo://example.com:8042/over/there?name=ferret#nose * \_/ \______________/\_________/ \_________/ \__/ * | | | | | * scheme authority path query fragment * | _____________________|__ * / \ / \ * urn:example:animal:ferret:nose */ var URI = /** @class */ (function () { /** * @internal */ function URI(schemeOrData, authority, path, query, fragment, _strict) { if (_strict === void 0) { _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); } } URI.isUri = function (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 === 'function' && typeof thing.with === 'function' && typeof thing.toString === 'function'; }; Object.defineProperty(URI.prototype, "fsPath", { // ---- 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: function () { // if (this.scheme !== 'file') { // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`); // } return _makeFsPath(this); }, enumerable: true, configurable: true }); // ---- modify to new ------------------------- URI.prototype.with = function (change) { if (!change) { return this; } var scheme = change.scheme, authority = change.authority, path = change.path, query = change.query, fragment = change.fragment; if (scheme === undefined) { scheme = this.scheme; } else if (scheme === null) { scheme = _empty; } if (authority === undefined) { authority = this.authority; } else if (authority === null) { authority = _empty; } if (path === undefined) { path = this.path; } else if (path === null) { path = _empty; } if (query === undefined) { query = this.query; } else if (query === null) { query = _empty; } if (fragment === undefined) { fragment = this.fragment; } else if (fragment === null) { fragment = _empty; } if (scheme === this.scheme && authority === this.authority && path === this.path && query === this.query && fragment === this.fragment) { return this; } return new _URI(scheme, authority, path, query, fragment); }; // ---- parse & validate ------------------------ /** * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`, * `file:///usr/home`, or `scheme:with/path`. * * @param value A string which represents an URI (see `URI#toString`). */ URI.parse = function (value, _strict) { if (_strict === void 0) { _strict = false; } var 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`) */ URI.file = function (path) { var 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) { var 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); }; URI.from = function (components) { return new _URI(components.scheme, components.authority, components.path, components.query, components.fragment); }; // ---- 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` */ URI.prototype.toString = function (skipEncoding) { if (skipEncoding === void 0) { skipEncoding = false; } return _asFormatted(this, skipEncoding); }; URI.prototype.toJSON = function () { return this; }; URI.revive = function (data) { if (!data) { return data; } else if (data instanceof URI) { return data; } else { var result = new _URI(data); result._formatted = data.external; result._fsPath = data._sep === _pathSepMarker ? data.fsPath : null; return result; } }; return URI; }()); exports.URI = URI; var _pathSepMarker = platform_1.isWindows ? 1 : undefined; // eslint-disable-next-line @typescript-eslint/class-name-casing var _URI = /** @class */ (function (_super) { __extends(_URI, _super); function _URI() { var _this = _super !== null && _super.apply(this, arguments) || this; _this._formatted = null; _this._fsPath = null; return _this; } Object.defineProperty(_URI.prototype, "fsPath", { get: function () { if (!this._fsPath) { this._fsPath = _makeFsPath(this); } return this._fsPath; }, enumerable: true, configurable: true }); _URI.prototype.toString = function (skipEncoding) { if (skipEncoding === void 0) { 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); } }; _URI.prototype.toJSON = function () { var res = { $mid: 1 }; // 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; }; return _URI; }(URI)); // reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2 var encodeTable = (_a = {}, _a[58 /* Colon */] = '%3A', _a[47 /* Slash */] = '%2F', _a[63 /* QuestionMark */] = '%3F', _a[35 /* Hash */] = '%23', _a[91 /* OpenSquareBracket */] = '%5B', _a[93 /* CloseSquareBracket */] = '%5D', _a[64 /* AtSign */] = '%40', _a[33 /* ExclamationMark */] = '%21', _a[36 /* DollarSign */] = '%24', _a[38 /* Ampersand */] = '%26', _a[39 /* SingleQuote */] = '%27', _a[40 /* OpenParen */] = '%28', _a[41 /* CloseParen */] = '%29', _a[42 /* Asterisk */] = '%2A', _a[43 /* Plus */] = '%2B', _a[44 /* Comma */] = '%2C', _a[59 /* Semicolon */] = '%3B', _a[61 /* Equals */] = '%3D', _a[32 /* Space */] = '%20', _a); function encodeURIComponentFast(uriComponent, allowSlash) { var res = undefined; var nativeEncodePos = -1; for (var pos = 0; pos < uriComponent.length; pos++) { var 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 var 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) { var res = undefined; for (var pos = 0; pos < path.length; pos++) { var 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 _makeFsPath(uri) { var 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 */) { // windows drive letter: file:///c:/far/boo value = uri.path[1].toLowerCase() + uri.path.substr(2); } else { // other path value = uri.path; } if (platform_1.isWindows) { value = value.replace(/\//g, '\\'); } return value; } /** * Create the external version of a uri */ function _asFormatted(uri, skipEncoding) { var encoder = !skipEncoding ? encodeURIComponentFast : encodeURIComponentMinimal; var res = ''; var scheme = uri.scheme, authority = uri.authority, path = uri.path, query = uri.query, fragment = uri.fragment; if (scheme) { res += scheme; res += ':'; } if (authority || scheme === 'file') { res += _slash; res += _slash; } if (authority) { var idx = authority.indexOf('@'); if (idx !== -1) { // @ var 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 */) { var 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 */) { var 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; } } } var _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g; function percentDecode(str) { if (!str.match(_rEncodedAsHex)) { return str; } return str.replace(_rEncodedAsHex, function (match) { return 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[180/*vs/base/common/marshalling*/], __M([0/*require*/,1/*exports*/,25/*vs/base/common/uri*/]), function (require, exports, uri_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function parse(text) { var data = JSON.parse(text); data = revive(data); return data; } exports.parse = parse; function revive(obj, depth) { if (depth === void 0) { depth = 0; } if (!obj || depth > 200) { return obj; } if (typeof obj === 'object') { switch (obj.$mid) { case 1: return uri_1.URI.revive(obj); case 2: return new RegExp(obj.source, obj.flags); } // walk object (or array) for (var key in obj) { if (Object.hasOwnProperty.call(obj, key)) { obj[key] = revive(obj[key], depth + 1); } } } return obj; } exports.revive = revive; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[46/*vs/base/common/network*/], __M([0/*require*/,1/*exports*/,25/*vs/base/common/uri*/,16/*vs/base/common/platform*/]), function (require, exports, uri_1, platform) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 = exports.Schemas || (exports.Schemas = {})); var RemoteAuthoritiesImpl = /** @class */ (function () { function RemoteAuthoritiesImpl() { this._hosts = Object.create(null); this._ports = Object.create(null); this._connectionTokens = Object.create(null); this._preferredWebSchema = 'http'; this._delegate = null; } RemoteAuthoritiesImpl.prototype.setPreferredWebSchema = function (schema) { this._preferredWebSchema = schema; }; RemoteAuthoritiesImpl.prototype.rewrite = function (uri) { if (this._delegate) { return this._delegate(uri); } var authority = uri.authority; var host = this._hosts[authority]; if (host && host.indexOf(':') !== -1) { host = "[" + host + "]"; } var port = this._ports[authority]; var connectionToken = this._connectionTokens[authority]; var query = "path=" + encodeURIComponent(uri.path); if (typeof connectionToken === 'string') { query += "&tkn=" + encodeURIComponent(connectionToken); } return uri_1.URI.from({ scheme: platform.isWeb ? this._preferredWebSchema : Schemas.vscodeRemoteResource, authority: host + ":" + port, path: "/vscode-remote-resource", query: query }); }; return RemoteAuthoritiesImpl; }()); exports.RemoteAuthorities = new RemoteAuthoritiesImpl(); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[6/*vs/base/browser/dom*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,52/*vs/base/browser/event*/,56/*vs/base/browser/keyboardEvent*/,45/*vs/base/browser/mouseEvent*/,15/*vs/base/common/async*/,10/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,19/*vs/base/common/arrays*/,46/*vs/base/common/network*/,88/*vs/base/browser/canIUse*/]), function (require, exports, browser, event_1, keyboardEvent_1, mouseEvent_1, async_1, errors_1, event_2, lifecycle_1, platform, arrays_1, network_1, canIUse_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function clearNode(node) { while (node.firstChild) { node.removeChild(node.firstChild); } } exports.clearNode = clearNode; function removeNode(node) { if (node.parentNode) { node.parentNode.removeChild(node); } } exports.removeNode = removeNode; function isInDOM(node) { while (node) { if (node === document.body) { return true; } node = node.parentNode || node.host; } return false; } exports.isInDOM = isInDOM; var _manualClassList = new /** @class */ (function () { function class_1() { this._lastStart = -1; this._lastEnd = -1; } class_1.prototype._findClassName = function (node, className) { var classes = node.className; if (!classes) { this._lastStart = -1; return; } className = className.trim(); var classesLen = classes.length, classLen = className.length; if (classLen === 0) { this._lastStart = -1; return; } if (classesLen < classLen) { this._lastStart = -1; return; } if (classes === className) { this._lastStart = 0; this._lastEnd = classesLen; return; } var idx = -1, idxEnd; while ((idx = classes.indexOf(className, idx + 1)) >= 0) { idxEnd = idx + classLen; // a class that is followed by another class if ((idx === 0 || classes.charCodeAt(idx - 1) === 32 /* Space */) && classes.charCodeAt(idxEnd) === 32 /* Space */) { this._lastStart = idx; this._lastEnd = idxEnd + 1; return; } // last class if (idx > 0 && classes.charCodeAt(idx - 1) === 32 /* Space */ && idxEnd === classesLen) { this._lastStart = idx - 1; this._lastEnd = idxEnd; return; } // equal - duplicate of cmp above if (idx === 0 && idxEnd === classesLen) { this._lastStart = 0; this._lastEnd = idxEnd; return; } } this._lastStart = -1; }; class_1.prototype.hasClass = function (node, className) { this._findClassName(node, className); return this._lastStart !== -1; }; class_1.prototype.addClasses = function (node) { var _this = this; var classNames = []; for (var _i = 1; _i < arguments.length; _i++) { classNames[_i - 1] = arguments[_i]; } classNames.forEach(function (nameValue) { return nameValue.split(' ').forEach(function (name) { return _this.addClass(node, name); }); }); }; class_1.prototype.addClass = function (node, className) { if (!node.className) { // doesn't have it for sure node.className = className; } else { this._findClassName(node, className); // see if it's already there if (this._lastStart === -1) { node.className = node.className + ' ' + className; } } }; class_1.prototype.removeClass = function (node, className) { this._findClassName(node, className); if (this._lastStart === -1) { return; // Prevent styles invalidation if not necessary } else { node.className = node.className.substring(0, this._lastStart) + node.className.substring(this._lastEnd); } }; class_1.prototype.removeClasses = function (node) { var _this = this; var classNames = []; for (var _i = 1; _i < arguments.length; _i++) { classNames[_i - 1] = arguments[_i]; } classNames.forEach(function (nameValue) { return nameValue.split(' ').forEach(function (name) { return _this.removeClass(node, name); }); }); }; class_1.prototype.toggleClass = function (node, className, shouldHaveIt) { this._findClassName(node, className); if (this._lastStart !== -1 && (shouldHaveIt === undefined || !shouldHaveIt)) { this.removeClass(node, className); } if (this._lastStart === -1 && (shouldHaveIt === undefined || shouldHaveIt)) { this.addClass(node, className); } }; return class_1; }()); var _nativeClassList = new /** @class */ (function () { function class_2() { } class_2.prototype.hasClass = function (node, className) { return Boolean(className) && node.classList && node.classList.contains(className); }; class_2.prototype.addClasses = function (node) { var _this = this; var classNames = []; for (var _i = 1; _i < arguments.length; _i++) { classNames[_i - 1] = arguments[_i]; } classNames.forEach(function (nameValue) { return nameValue.split(' ').forEach(function (name) { return _this.addClass(node, name); }); }); }; class_2.prototype.addClass = function (node, className) { if (className && node.classList) { node.classList.add(className); } }; class_2.prototype.removeClass = function (node, className) { if (className && node.classList) { node.classList.remove(className); } }; class_2.prototype.removeClasses = function (node) { var _this = this; var classNames = []; for (var _i = 1; _i < arguments.length; _i++) { classNames[_i - 1] = arguments[_i]; } classNames.forEach(function (nameValue) { return nameValue.split(' ').forEach(function (name) { return _this.removeClass(node, name); }); }); }; class_2.prototype.toggleClass = function (node, className, shouldHaveIt) { if (node.classList) { node.classList.toggle(className, shouldHaveIt); } }; return class_2; }()); // In IE11 there is only partial support for `classList` which makes us keep our // custom implementation. Otherwise use the native implementation, see: http://caniuse.com/#search=classlist var _classList = browser.isIE ? _manualClassList : _nativeClassList; exports.hasClass = _classList.hasClass.bind(_classList); exports.addClass = _classList.addClass.bind(_classList); exports.addClasses = _classList.addClasses.bind(_classList); exports.removeClass = _classList.removeClass.bind(_classList); exports.removeClasses = _classList.removeClasses.bind(_classList); exports.toggleClass = _classList.toggleClass.bind(_classList); var DomListener = /** @class */ (function () { function DomListener(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); } DomListener.prototype.dispose = function () { 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; }; return DomListener; }()); 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)); }; } exports.addStandardDisposableListener = function addStandardDisposableListener(node, type, handler, useCapture) { var 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.addStandardDisposableGenericMouseDownListner = function addStandardDisposableListener(node, handler, useCapture) { var wrapHandler = _wrapAsStandardMouseEvent(handler); return addDisposableGenericMouseDownListner(node, wrapHandler, useCapture); }; 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', function (e) { // Mouse out bubbles, so this is an attempt to ignore faux mouse outs coming from children elements var 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', function (e) { // Mouse out bubbles, so this is an attempt to ignore faux mouse outs coming from children elements var toElement = (e.relatedTarget); while (toElement && toElement !== node) { toElement = toElement.parentNode; } if (toElement === node) { return; } handler(e); }); } exports.addDisposableNonBubblingPointerOutListener = addDisposableNonBubblingPointerOutListener; var _animationFrame = null; function doRequestAnimationFrame(callback) { if (!_animationFrame) { var emulatedRequestAnimationFrame = function (callback) { return setTimeout(function () { return callback(new Date().getTime()); }, 0); }; _animationFrame = (self.requestAnimationFrame || self.msRequestAnimationFrame || self.webkitRequestAnimationFrame || self.mozRequestAnimationFrame || self.oRequestAnimationFrame || emulatedRequestAnimationFrame); } return _animationFrame.call(self, callback); } var AnimationFrameQueueItem = /** @class */ (function () { function AnimationFrameQueueItem(runner, priority) { if (priority === void 0) { priority = 0; } this._runner = runner; this.priority = priority; this._canceled = false; } AnimationFrameQueueItem.prototype.dispose = function () { this._canceled = true; }; AnimationFrameQueueItem.prototype.execute = function () { if (this._canceled) { return; } try { this._runner(); } catch (e) { errors_1.onUnexpectedError(e); } }; // Sort by priority (largest to lowest) AnimationFrameQueueItem.sort = function (a, b) { return b.priority - a.priority; }; return AnimationFrameQueueItem; }()); (function () { /** * The runners scheduled at the next animation frame */ var NEXT_QUEUE = []; /** * The runners scheduled at the current animation frame */ var CURRENT_QUEUE = null; /** * A flag to keep track if the native requestAnimationFrame was already called */ var animFrameRequested = false; /** * A flag to indicate if currently handling a native requestAnimationFrame callback */ var inAnimationFrameRunner = false; var animationFrameRunner = function () { animFrameRequested = false; CURRENT_QUEUE = NEXT_QUEUE; NEXT_QUEUE = []; inAnimationFrameRunner = true; while (CURRENT_QUEUE.length > 0) { CURRENT_QUEUE.sort(AnimationFrameQueueItem.sort); var top_1 = CURRENT_QUEUE.shift(); top_1.execute(); } inAnimationFrameRunner = false; }; exports.scheduleAtNextAnimationFrame = function (runner, priority) { if (priority === void 0) { priority = 0; } var item = new AnimationFrameQueueItem(runner, priority); NEXT_QUEUE.push(item); if (!animFrameRequested) { animFrameRequested = true; doRequestAnimationFrame(animationFrameRunner); } return item; }; exports.runAtThisOrScheduleAtNextAnimationFrame = function (runner, priority) { if (inAnimationFrameRunner) { var item = new AnimationFrameQueueItem(runner, priority); CURRENT_QUEUE.push(item); return item; } else { return exports.scheduleAtNextAnimationFrame(runner, priority); } }; })(); var MINIMUM_TIME_MS = 16; var DEFAULT_EVENT_MERGER = function (lastEvent, currentEvent) { return currentEvent; }; var TimeoutThrottledDomListener = /** @class */ (function (_super) { __extends(TimeoutThrottledDomListener, _super); function TimeoutThrottledDomListener(node, type, handler, eventMerger, minimumTimeMs) { if (eventMerger === void 0) { eventMerger = DEFAULT_EVENT_MERGER; } if (minimumTimeMs === void 0) { minimumTimeMs = MINIMUM_TIME_MS; } var _this = _super.call(this) || this; var lastEvent = null; var lastHandlerTime = 0; var timeout = _this._register(new async_1.TimeoutTimer()); var invokeHandler = function () { lastHandlerTime = (new Date()).getTime(); handler(lastEvent); lastEvent = null; }; _this._register(addDisposableListener(node, type, function (e) { lastEvent = eventMerger(lastEvent, e); var elapsedTime = (new Date()).getTime() - lastHandlerTime; if (elapsedTime >= minimumTimeMs) { timeout.cancel(); invokeHandler(); } else { timeout.setIfNotSet(invokeHandler, minimumTimeMs - elapsedTime); } })); return _this; } return TimeoutThrottledDomListener; }(lifecycle_1.Disposable)); 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) { var width = window.visualViewport.width; var height = window.visualViewport.height - (browser.isStandalone // in PWA mode, the visual viewport always includes the safe-area-inset-bottom (which is for the home indicator) // even when you are using the onscreen monitor, the visual viewport will include the area between system statusbar and the onscreen keyboard // plus the area between onscreen keyboard and the bottom bezel, which is 20px on iOS. ? (20 + 4) // + 4px for body margin : 0); return new Dimension(width, 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; var SizeUtils = /** @class */ (function () { function SizeUtils() { } // Adapted from WinJS // Converts a CSS positioning string for the specified element to pixels. SizeUtils.convertToPixels = function (element, value) { return parseFloat(value) || 0; }; SizeUtils.getDimension = function (element, cssPropertyName, jsPropertyName) { var computedStyle = getComputedStyle(element); var value = '0'; if (computedStyle) { if (computedStyle.getPropertyValue) { value = computedStyle.getPropertyValue(cssPropertyName); } else { // IE8 value = computedStyle.getAttribute(jsPropertyName); } } return SizeUtils.convertToPixels(element, value); }; SizeUtils.getBorderLeftWidth = function (element) { return SizeUtils.getDimension(element, 'border-left-width', 'borderLeftWidth'); }; SizeUtils.getBorderRightWidth = function (element) { return SizeUtils.getDimension(element, 'border-right-width', 'borderRightWidth'); }; SizeUtils.getBorderTopWidth = function (element) { return SizeUtils.getDimension(element, 'border-top-width', 'borderTopWidth'); }; SizeUtils.getBorderBottomWidth = function (element) { return SizeUtils.getDimension(element, 'border-bottom-width', 'borderBottomWidth'); }; SizeUtils.getPaddingLeft = function (element) { return SizeUtils.getDimension(element, 'padding-left', 'paddingLeft'); }; SizeUtils.getPaddingRight = function (element) { return SizeUtils.getDimension(element, 'padding-right', 'paddingRight'); }; SizeUtils.getPaddingTop = function (element) { return SizeUtils.getDimension(element, 'padding-top', 'paddingTop'); }; SizeUtils.getPaddingBottom = function (element) { return SizeUtils.getDimension(element, 'padding-bottom', 'paddingBottom'); }; SizeUtils.getMarginLeft = function (element) { return SizeUtils.getDimension(element, 'margin-left', 'marginLeft'); }; SizeUtils.getMarginTop = function (element) { return SizeUtils.getDimension(element, 'margin-top', 'marginTop'); }; SizeUtils.getMarginRight = function (element) { return SizeUtils.getDimension(element, 'margin-right', 'marginRight'); }; SizeUtils.getMarginBottom = function (element) { return SizeUtils.getDimension(element, 'margin-bottom', 'marginBottom'); }; return SizeUtils; }()); // ---------------------------------------------------------------------------------------- // Position & Dimension var Dimension = /** @class */ (function () { function Dimension(width, height) { this.width = width; this.height = height; } return Dimension; }()); exports.Dimension = Dimension; function getTopLeftOffset(element) { // Adapted from WinJS.Utilities.getPosition // and added borders to the mix var offsetParent = element.offsetParent; var top = element.offsetTop; var left = element.offsetLeft; while ((element = element.parentNode) !== null && element !== document.body && element !== document.documentElement) { top -= element.scrollTop; var 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; /** * Returns the position of a dom node relative to the entire page. */ function getDomNodePagePosition(domNode) { var 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 */ (function () { function class_3() { } Object.defineProperty(class_3.prototype, "scrollX", { get: function () { if (typeof window.scrollX === 'number') { // modern browsers return window.scrollX; } else { return document.body.scrollLeft + document.documentElement.scrollLeft; } }, enumerable: true, configurable: true }); Object.defineProperty(class_3.prototype, "scrollY", { get: function () { if (typeof window.scrollY === 'number') { // modern browsers return window.scrollY; } else { return document.body.scrollTop + document.documentElement.scrollTop; } }, enumerable: true, configurable: true }); return class_3; }()); // Adapted from WinJS // Gets the width of the element, including margins. function getTotalWidth(element) { var margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element); return element.offsetWidth + margin; } exports.getTotalWidth = getTotalWidth; function getContentWidth(element) { var border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element); var 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) { var border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element); var 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) { var 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 (exports.hasClass(node, clazz)) { return node; } if (stopAtClazzOrNode) { if (typeof stopAtClazzOrNode === 'string') { if (exports.hasClass(node, stopAtClazzOrNode)) { return null; } } else { if (node === stopAtClazzOrNode) { return null; } } } node = node.parentNode; } return null; } exports.findParentWithClass = findParentWithClass; 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 createStyleSheet(container) { if (container === void 0) { container = document.getElementsByTagName('head')[0]; } var style = document.createElement('style'); style.type = 'text/css'; style.media = 'screen'; container.appendChild(style); return style; } exports.createStyleSheet = createStyleSheet; var _sharedStyleSheet = null; function getSharedStyleSheet() { if (!_sharedStyleSheet) { _sharedStyleSheet = createStyleSheet(); } return _sharedStyleSheet; } function getDynamicStyleSheetRules(style) { if (style && style.sheet && style.sheet.rules) { // Chrome, IE return style.sheet.rules; } if (style && style.sheet && style.sheet.cssRules) { // FF return style.sheet.cssRules; } return []; } function createCSSRule(selector, cssText, style) { if (style === void 0) { style = getSharedStyleSheet(); } if (!style || !cssText) { return; } style.sheet.insertRule(selector + '{' + cssText + '}', 0); } exports.createCSSRule = createCSSRule; function removeCSSRulesContainingSelector(ruleName, style) { if (style === void 0) { style = getSharedStyleSheet(); } if (!style) { return; } var rules = getDynamicStyleSheetRules(style); var toDelete = []; for (var i = 0; i < rules.length; i++) { var rule = rules[i]; if (rule.selectorText.indexOf(ruleName) !== -1) { toDelete.push(i); } } for (var 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', DBLCLICK: 'dblclick', MOUSE_UP: 'mouseup', MOUSE_DOWN: 'mousedown', MOUSE_OVER: 'mouseover', MOUSE_MOVE: 'mousemove', MOUSE_OUT: 'mouseout', MOUSE_ENTER: 'mouseenter', MOUSE_LEAVE: 'mouseleave', POINTER_UP: 'pointerup', POINTER_DOWN: 'pointerdown', POINTER_MOVE: 'pointermove', CONTEXT_MENU: 'contextmenu', WHEEL: 'wheel', // Keyboard KEY_DOWN: 'keydown', KEY_PRESS: 'keypress', KEY_UP: 'keyup', // HTML Document LOAD: 'load', BEFORE_UNLOAD: 'beforeunload', UNLOAD: 'unload', ABORT: 'abort', ERROR: 'error', RESIZE: 'resize', SCROLL: 'scroll', FULLSCREEN_CHANGE: 'fullscreenchange', WK_FULLSCREEN_CHANGE: 'webkitfullscreenchange', // Form SELECT: 'select', CHANGE: 'change', SUBMIT: 'submit', RESET: 'reset', FOCUS: 'focus', FOCUS_IN: 'focusin', FOCUS_OUT: 'focusout', BLUR: 'blur', INPUT: 'input', // Local Storage STORAGE: 'storage', // Drag DRAG_START: 'dragstart', DRAG: 'drag', DRAG_ENTER: 'dragenter', DRAG_LEAVE: 'dragleave', DRAG_OVER: 'dragover', DROP: 'drop', DRAG_END: 'dragend', // Animation ANIMATION_START: browser.isWebKit ? 'webkitAnimationStart' : 'animationstart', ANIMATION_END: browser.isWebKit ? 'webkitAnimationEnd' : 'animationend', ANIMATION_ITERATION: browser.isWebKit ? 'webkitAnimationIteration' : 'animationiteration' }; exports.EventHelper = { stop: function (e, cancelBubble) { if (e.preventDefault) { e.preventDefault(); } else { // IE8 e.returnValue = false; } if (cancelBubble) { if (e.stopPropagation) { e.stopPropagation(); } else { // IE8 e.cancelBubble = true; } } } }; function saveParentsScrollTop(node) { var r = []; for (var 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 (var i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) { if (node.scrollTop !== state[i]) { node.scrollTop = state[i]; } node = node.parentNode; } } exports.restoreParentsScrollTop = restoreParentsScrollTop; var FocusTracker = /** @class */ (function (_super) { __extends(FocusTracker, _super); function FocusTracker(element) { var _this = _super.call(this) || this; _this._onDidFocus = _this._register(new event_2.Emitter()); _this.onDidFocus = _this._onDidFocus.event; _this._onDidBlur = _this._register(new event_2.Emitter()); _this.onDidBlur = _this._onDidBlur.event; var hasFocus = isAncestor(document.activeElement, element); var loosingFocus = false; var onFocus = function () { loosingFocus = false; if (!hasFocus) { hasFocus = true; _this._onDidFocus.fire(); } }; var onBlur = function () { if (hasFocus) { loosingFocus = true; window.setTimeout(function () { if (loosingFocus) { loosingFocus = false; hasFocus = false; _this._onDidBlur.fire(); } }, 0); } }; _this._refreshStateHandler = function () { var currentNodeHasFocus = isAncestor(document.activeElement, element); if (currentNodeHasFocus !== hasFocus) { if (hasFocus) { onBlur(); } else { onFocus(); } } }; _this._register(event_1.domEvent(element, exports.EventType.FOCUS, true)(onFocus)); _this._register(event_1.domEvent(element, exports.EventType.BLUR, true)(onBlur)); return _this; } return FocusTracker; }(lifecycle_1.Disposable)); function trackFocus(element) { return new FocusTracker(element); } exports.trackFocus = trackFocus; function append(parent) { var children = []; for (var _i = 1; _i < arguments.length; _i++) { children[_i - 1] = arguments[_i]; } children.forEach(function (child) { return parent.appendChild(child); }); return children[children.length - 1]; } exports.append = append; var 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) { var children = []; for (var _i = 3; _i < arguments.length; _i++) { children[_i - 3] = arguments[_i]; } var match = SELECTOR_REGEX.exec(description); if (!match) { throw new Error('Bad use of emmet'); } attrs = __assign({}, (attrs || {})); var tagName = match[1] || 'div'; var 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(function (name) { var 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); } }); arrays_1.coalesce(children) .forEach(function (child) { if (child instanceof Node) { result.appendChild(child); } else { result.appendChild(document.createTextNode(child)); } }); return result; } function $(description, attrs) { var children = []; for (var _i = 2; _i < arguments.length; _i++) { children[_i - 2] = arguments[_i]; } return _$.apply(void 0, __spreadArrays([Namespace.HTML, description, attrs], children)); } exports.$ = $; $.SVG = function (description, attrs) { var children = []; for (var _i = 2; _i < arguments.length; _i++) { children[_i - 2] = arguments[_i]; } return _$.apply(void 0, __spreadArrays([Namespace.SVG, description, attrs], children)); }; function show() { var elements = []; for (var _i = 0; _i < arguments.length; _i++) { elements[_i] = arguments[_i]; } for (var _a = 0, elements_1 = elements; _a < elements_1.length; _a++) { var element = elements_1[_a]; element.style.display = ''; element.removeAttribute('aria-hidden'); } } exports.show = show; function hide() { var elements = []; for (var _i = 0; _i < arguments.length; _i++) { elements[_i] = arguments[_i]; } for (var _a = 0, elements_2 = elements; _a < elements_2.length; _a++) { var element = elements_2[_a]; element.style.display = 'none'; element.setAttribute('aria-hidden', 'true'); } } exports.hide = hide; function findParentWithAttribute(node, attribute) { while (node && node.nodeType === node.ELEMENT_NODE) { if (node instanceof HTMLElement && node.hasAttribute(attribute)) { return node; } node = node.parentNode; } return null; } function removeTabIndexAndUpdateFocus(node) { if (!node || !node.hasAttribute('tabIndex')) { return; } // If we are the currently focused element and tabIndex is removed, // standard DOM behavior is to move focus to the element. We // typically never want that, rather put focus to the closest element // in the hierarchy of the parent DOM nodes. if (document.activeElement === node) { var parentFocusable = findParentWithAttribute(node.parentElement, 'tabIndex'); if (parentFocusable) { parentFocusable.focus(); } } node.removeAttribute('tabindex'); } exports.removeTabIndexAndUpdateFocus = removeTabIndexAndUpdateFocus; 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) { var screenPx = window.devicePixelRatio * cssPx; return Math.max(1, Math.floor(screenPx)) / window.devicePixelRatio; } exports.computeScreenAwareSize = computeScreenAwareSize; /** * 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) { if (platform.isNative || browser.isEdgeWebView) { // In VSCode, window.open() always returns null... // The same is true for a WebView (see https://github.com/Microsoft/monaco-editor/issues/628) window.open(url); } else { var newTab = window.open(); if (newTab) { newTab.opener = null; newTab.location.href = url; } } } exports.windowOpenNoOpener = windowOpenNoOpener; function animate(fn) { var step = function () { fn(); stepDisposable = exports.scheduleAtNextAnimationFrame(step); }; var stepDisposable = exports.scheduleAtNextAnimationFrame(step); return lifecycle_1.toDisposable(function () { return stepDisposable.dispose(); }); } exports.animate = animate; network_1.RemoteAuthorities.setPreferredWebSchema(/^https:/.test(window.location.href) ? 'https' : 'http'); function asDomUri(uri) { if (!uri) { return uri; } if (network_1.Schemas.vscodeRemote === uri.scheme) { return network_1.RemoteAuthorities.rewrite(uri); } return uri; } exports.asDomUri = asDomUri; /** * returns url('...') */ function asCSSUrl(uri) { if (!uri) { return "url('')"; } return "url('" + asDomUri(uri).toString(true).replace(/'/g, '%27') + "')"; } exports.asCSSUrl = asCSSUrl; }); /*--------------------------------------------------------------------------------------------- * 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/base/browser/fastDomNode*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/]), function (require, exports, dom) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var FastDomNode = /** @class */ (function () { function FastDomNode(domNode) { this.domNode = domNode; this._maxWidth = -1; this._width = -1; this._height = -1; this._top = -1; this._left = -1; this._bottom = -1; this._right = -1; this._fontFamily = ''; this._fontWeight = ''; this._fontSize = -1; this._fontFeatureSettings = ''; this._lineHeight = -1; this._letterSpacing = -100; this._className = ''; this._display = ''; this._position = ''; this._visibility = ''; this._backgroundColor = ''; this._layerHint = false; this._contain = 'none'; } FastDomNode.prototype.setMaxWidth = function (maxWidth) { if (this._maxWidth === maxWidth) { return; } this._maxWidth = maxWidth; this.domNode.style.maxWidth = this._maxWidth + 'px'; }; FastDomNode.prototype.setWidth = function (width) { if (this._width === width) { return; } this._width = width; this.domNode.style.width = this._width + 'px'; }; FastDomNode.prototype.setHeight = function (height) { if (this._height === height) { return; } this._height = height; this.domNode.style.height = this._height + 'px'; }; FastDomNode.prototype.setTop = function (top) { if (this._top === top) { return; } this._top = top; this.domNode.style.top = this._top + 'px'; }; FastDomNode.prototype.unsetTop = function () { if (this._top === -1) { return; } this._top = -1; this.domNode.style.top = ''; }; FastDomNode.prototype.setLeft = function (left) { if (this._left === left) { return; } this._left = left; this.domNode.style.left = this._left + 'px'; }; FastDomNode.prototype.setBottom = function (bottom) { if (this._bottom === bottom) { return; } this._bottom = bottom; this.domNode.style.bottom = this._bottom + 'px'; }; FastDomNode.prototype.setRight = function (right) { if (this._right === right) { return; } this._right = right; this.domNode.style.right = this._right + 'px'; }; FastDomNode.prototype.setFontFamily = function (fontFamily) { if (this._fontFamily === fontFamily) { return; } this._fontFamily = fontFamily; this.domNode.style.fontFamily = this._fontFamily; }; FastDomNode.prototype.setFontWeight = function (fontWeight) { if (this._fontWeight === fontWeight) { return; } this._fontWeight = fontWeight; this.domNode.style.fontWeight = this._fontWeight; }; FastDomNode.prototype.setFontSize = function (fontSize) { if (this._fontSize === fontSize) { return; } this._fontSize = fontSize; this.domNode.style.fontSize = this._fontSize + 'px'; }; FastDomNode.prototype.setFontFeatureSettings = function (fontFeatureSettings) { if (this._fontFeatureSettings === fontFeatureSettings) { return; } this._fontFeatureSettings = fontFeatureSettings; this.domNode.style.fontFeatureSettings = this._fontFeatureSettings; }; FastDomNode.prototype.setLineHeight = function (lineHeight) { if (this._lineHeight === lineHeight) { return; } this._lineHeight = lineHeight; this.domNode.style.lineHeight = this._lineHeight + 'px'; }; FastDomNode.prototype.setLetterSpacing = function (letterSpacing) { if (this._letterSpacing === letterSpacing) { return; } this._letterSpacing = letterSpacing; this.domNode.style.letterSpacing = this._letterSpacing + 'px'; }; FastDomNode.prototype.setClassName = function (className) { if (this._className === className) { return; } this._className = className; this.domNode.className = this._className; }; FastDomNode.prototype.toggleClassName = function (className, shouldHaveIt) { dom.toggleClass(this.domNode, className, shouldHaveIt); this._className = this.domNode.className; }; FastDomNode.prototype.setDisplay = function (display) { if (this._display === display) { return; } this._display = display; this.domNode.style.display = this._display; }; FastDomNode.prototype.setPosition = function (position) { if (this._position === position) { return; } this._position = position; this.domNode.style.position = this._position; }; FastDomNode.prototype.setVisibility = function (visibility) { if (this._visibility === visibility) { return; } this._visibility = visibility; this.domNode.style.visibility = this._visibility; }; FastDomNode.prototype.setBackgroundColor = function (backgroundColor) { if (this._backgroundColor === backgroundColor) { return; } this._backgroundColor = backgroundColor; this.domNode.style.backgroundColor = this._backgroundColor; }; FastDomNode.prototype.setLayerHinting = function (layerHint) { if (this._layerHint === layerHint) { return; } this._layerHint = layerHint; this.domNode.style.transform = this._layerHint ? 'translate3d(0px, 0px, 0px)' : ''; }; FastDomNode.prototype.setContain = function (contain) { if (this._contain === contain) { return; } this._contain = contain; this.domNode.style.contain = this._contain; }; FastDomNode.prototype.setAttribute = function (name, value) { this.domNode.setAttribute(name, value); }; FastDomNode.prototype.removeAttribute = function (name) { this.domNode.removeAttribute(name); }; FastDomNode.prototype.appendChild = function (child) { this.domNode.appendChild(child.domNode); }; FastDomNode.prototype.removeChild = function (child) { this.domNode.removeChild(child.domNode); }; return FastDomNode; }()); exports.FastDomNode = FastDomNode; function createFastDomNode(domNode) { return new FastDomNode(domNode); } exports.createFastDomNode = createFastDomNode; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[134/*vs/base/browser/formattedTextRenderer*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/]), function (require, exports, DOM) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function renderText(text, options) { if (options === void 0) { options = {}; } var element = createElement(options); element.textContent = text; return element; } exports.renderText = renderText; function renderFormattedText(formattedText, options) { if (options === void 0) { options = {}; } var element = createElement(options); _renderFormattedText(element, parseFormattedText(formattedText), options.actionHandler); return element; } exports.renderFormattedText = renderFormattedText; function createElement(options) { var tagName = options.inline ? 'span' : 'div'; var element = document.createElement(tagName); if (options.className) { element.className = options.className; } return element; } exports.createElement = createElement; var StringStream = /** @class */ (function () { function StringStream(source) { this.source = source; this.index = 0; } StringStream.prototype.eos = function () { return this.index >= this.source.length; }; StringStream.prototype.next = function () { var next = this.peek(); this.advance(); return next; }; StringStream.prototype.peek = function () { return this.source[this.index]; }; StringStream.prototype.advance = function () { this.index++; }; return StringStream; }()); function _renderFormattedText(element, treeNode, actionHandler) { var 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 === 5 /* Action */ && actionHandler) { var a = document.createElement('a'); a.href = '#'; actionHandler.disposeables.add(DOM.addStandardDisposableListener(a, 'click', function (event) { actionHandler.callback(String(treeNode.index), event); })); child = a; } else if (treeNode.type === 7 /* 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(function (nodeChild) { _renderFormattedText(child, nodeChild, actionHandler); }); } } function parseFormattedText(content) { var root = { type: 1 /* Root */, children: [] }; var actionViewItemIndex = 0; var current = root; var stack = []; var stream = new StringStream(content); while (!stream.eos()) { var next = stream.next(); var isEscapedFormatType = (next === '\\' && formatTagType(stream.peek()) !== 0 /* Invalid */); if (isEscapedFormatType) { next = stream.next(); // unread the backslash if it escapes a format tag type } if (!isEscapedFormatType && isFormatTag(next) && next === stream.peek()) { stream.advance(); if (current.type === 2 /* Text */) { current = stack.pop(); } var type = formatTagType(next); if (current.type === type || (current.type === 5 /* Action */ && type === 6 /* ActionClose */)) { current = stack.pop(); } else { var 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: 7 /* NewLine */ }); } else { if (current.type !== 2 /* Text */) { var 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) { return formatTagType(char) !== 0 /* Invalid */; } function formatTagType(char) { switch (char) { case '*': return 3 /* Bold */; case '_': return 4 /* Italics */; case '[': return 5 /* Action */; case ']': return 6 /* ActionClose */; 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[78/*vs/base/browser/globalMouseMoveMonitor*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,16/*vs/base/common/platform*/,24/*vs/base/browser/browser*/,174/*vs/base/browser/iframe*/,45/*vs/base/browser/mouseEvent*/,2/*vs/base/common/lifecycle*/,88/*vs/base/browser/canIUse*/]), function (require, exports, dom, platform, browser, iframe_1, mouseEvent_1, lifecycle_1, canIUse_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function standardMouseMoveMerger(lastEvent, currentEvent) { var ev = new mouseEvent_1.StandardMouseEvent(currentEvent); ev.preventDefault(); return { leftButton: ev.leftButton, buttons: ev.buttons, posx: ev.posx, posy: ev.posy }; } exports.standardMouseMoveMerger = standardMouseMoveMerger; var GlobalMouseMoveMonitor = /** @class */ (function () { function GlobalMouseMoveMonitor() { this._hooks = new lifecycle_1.DisposableStore(); this._mouseMoveEventMerger = null; this._mouseMoveCallback = null; this._onStopCallback = null; } GlobalMouseMoveMonitor.prototype.dispose = function () { this.stopMonitoring(false); this._hooks.dispose(); }; GlobalMouseMoveMonitor.prototype.stopMonitoring = function (invokeStopCallback) { if (!this.isMonitoring()) { // Not monitoring return; } // Unhook this._hooks.clear(); this._mouseMoveEventMerger = null; this._mouseMoveCallback = null; var onStopCallback = this._onStopCallback; this._onStopCallback = null; if (invokeStopCallback && onStopCallback) { onStopCallback(); } }; GlobalMouseMoveMonitor.prototype.isMonitoring = function () { return !!this._mouseMoveEventMerger; }; GlobalMouseMoveMonitor.prototype.startMonitoring = function (initialElement, initialButtons, mouseMoveEventMerger, mouseMoveCallback, onStopCallback) { var _this = this; if (this.isMonitoring()) { // I am already hooked return; } this._mouseMoveEventMerger = mouseMoveEventMerger; this._mouseMoveCallback = mouseMoveCallback; this._onStopCallback = onStopCallback; var windowChain = iframe_1.IframeUtils.getSameOriginWindowChain(); var mouseMove = platform.isIOS && canIUse_1.BrowserFeatures.pointerEvents ? 'pointermove' : 'mousemove'; var mouseUp = platform.isIOS && canIUse_1.BrowserFeatures.pointerEvents ? 'pointerup' : 'mouseup'; var listenTo = windowChain.map(function (element) { return element.window.document; }); var shadowRoot = dom.getShadowRoot(initialElement); if (shadowRoot) { listenTo.unshift(shadowRoot); } for (var _i = 0, listenTo_1 = listenTo; _i < listenTo_1.length; _i++) { var element = listenTo_1[_i]; this._hooks.add(dom.addDisposableThrottledListener(element, mouseMove, function (data) { if (!browser.isIE && data.buttons !== initialButtons) { // Buttons state has changed in the meantime _this.stopMonitoring(true); return; } _this._mouseMoveCallback(data); }, function (lastEvent, currentEvent) { return _this._mouseMoveEventMerger(lastEvent, currentEvent); })); this._hooks.add(dom.addDisposableListener(element, mouseUp, function (e) { return _this.stopMonitoring(true); })); } if (iframe_1.IframeUtils.hasDifferentOriginAncestor()) { var 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', function (browserEvent) { var 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', function (browserEvent) { var 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', function (browserEvent) { _this.stopMonitoring(true); })); } }; return GlobalMouseMoveMonitor; }()); 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. *--------------------------------------------------------------------------------------------*/ define(__m[248/*vs/base/browser/markdownRenderer*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,134/*vs/base/browser/formattedTextRenderer*/,10/*vs/base/common/errors*/,75/*vs/base/common/htmlContent*/,127/*vs/base/common/idGenerator*/,612/*vs/base/common/marked/marked*/,613/*vs/base/common/insane/insane*/,180/*vs/base/common/marshalling*/,31/*vs/base/common/objects*/,5/*vs/base/common/strings*/,25/*vs/base/common/uri*/,46/*vs/base/common/network*/,100/*vs/base/common/codicons*/]), function (require, exports, DOM, formattedTextRenderer_1, errors_1, htmlContent_1, idGenerator_1, marked, insane_1, marshalling_1, objects_1, strings_1, uri_1, network_1, codicons_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Create html nodes for the given content element. */ function renderMarkdown(markdown, options) { if (options === void 0) { options = {}; } var element = formattedTextRenderer_1.createElement(options); var _uriMassage = function (part) { var data; try { data = marshalling_1.parse(decodeURIComponent(part)); } catch (e) { // ignore } if (!data) { return part; } data = objects_1.cloneAndChange(data, function (value) { if (markdown.uris && markdown.uris[value]) { return uri_1.URI.revive(markdown.uris[value]); } else { return undefined; } }); return encodeURIComponent(JSON.stringify(data)); }; var _href = function (href, isDomUri) { var data = markdown.uris && markdown.uris[href]; if (!data) { return href; // no uri exists } var uri = uri_1.URI.revive(data); if (uri_1.URI.parse(href).toString() === uri.toString()) { return href; // no tranformation performed } if (isDomUri) { uri = DOM.asDomUri(uri); } if (uri.query) { uri = uri.with({ query: _uriMassage(uri.query) }); } return uri.toString(true); }; // signal to code-block render that the // element has been created var signalInnerHTML; var withInnerHTML = new Promise(function (c) { return signalInnerHTML = c; }); var renderer = new marked.Renderer(); renderer.image = function (href, title, text) { var _a; var dimensions = []; var attributes = []; if (href) { (_a = htmlContent_1.parseHrefAndDimensions(href), href = _a.href, dimensions = _a.dimensions); href = _href(href, true); 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 = function (href, title, text) { // Remove markdown escapes. Workaround for https://github.com/chjj/marked/issues/829 if (href === text) { // raw link case text = htmlContent_1.removeMarkdownEscapes(text); } href = _href(href, false); title = htmlContent_1.removeMarkdownEscapes(title); href = 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 = function (text) { return "

    " + (markdown.supportThemeIcons ? codicons_1.renderCodicons(text) : text) + "

    "; }; if (options.codeBlockRenderer) { renderer.code = function (code, lang) { var value = options.codeBlockRenderer(lang, code); // when code-block rendering is async we return sync // but update the node with the real result later. var id = idGenerator_1.defaultGenerator.nextId(); var promise = Promise.all([value, withInnerHTML]).then(function (values) { var strValue = values[0]; var span = element.querySelector("div[data-code=\"" + id + "\"]"); if (span) { span.innerHTML = strValue; } }).catch(function (err) { // ignore }); if (options.codeBlockRenderCallback) { promise.then(options.codeBlockRenderCallback); } return "
    " + strings_1.escape(code) + "
    "; }; } var actionHandler = options.actionHandler; if (actionHandler) { actionHandler.disposeables.add(DOM.addStandardDisposableListener(element, 'click', function (event) { var target = event.target; if (target.tagName !== 'A') { target = target.parentElement; if (!target || target.tagName !== 'A') { return; } } try { var href = target.dataset['href']; if (href) { actionHandler.callback(href, event); } } catch (err) { errors_1.onUnexpectedError(err); } finally { event.preventDefault(); } })); } var markedOptions = { sanitize: true, renderer: renderer }; var allowedSchemes = [network_1.Schemas.http, network_1.Schemas.https, network_1.Schemas.mailto, network_1.Schemas.data, network_1.Schemas.file, network_1.Schemas.vscodeRemote, network_1.Schemas.vscodeRemoteResource]; if (markdown.isTrusted) { allowedSchemes.push(network_1.Schemas.command); } var renderedMarkdown = marked.parse(markdown.supportThemeIcons ? codicons_1.markdownEscapeEscapedCodicons(markdown.value) : markdown.value, markedOptions); element.innerHTML = insane_1.insane(renderedMarkdown, { allowedSchemes: allowedSchemes, allowedAttributes: { 'a': ['href', 'name', 'target', 'data-href'], 'iframe': ['allowfullscreen', 'frameborder', 'src'], 'img': ['src', 'title', 'alt', 'width', 'height'], 'div': ['class', 'data-code'], 'span': ['class'] } }); signalInnerHTML(); return element; } exports.renderMarkdown = renderMarkdown; }); /*--------------------------------------------------------------------------------------------- * 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([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,6/*vs/base/browser/dom*/,101/*vs/base/common/decorators*/]), function (require, exports, arrays, lifecycle_1, DomUtils, decorators_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 = {})); var Gesture = /** @class */ (function (_super) { __extends(Gesture, _super); function Gesture() { var _this = _super.call(this) || this; _this.dispatched = false; _this.activeTouches = {}; _this.handle = null; _this.targets = []; _this.ignoreTargets = []; _this._lastSetTapCountTime = 0; _this._register(DomUtils.addDisposableListener(document, 'touchstart', function (e) { return _this.onTouchStart(e); })); _this._register(DomUtils.addDisposableListener(document, 'touchend', function (e) { return _this.onTouchEnd(e); })); _this._register(DomUtils.addDisposableListener(document, 'touchmove', function (e) { return _this.onTouchMove(e); })); return _this; } Gesture.addTarget = function (element) { if (!Gesture.isTouchDevice()) { return lifecycle_1.Disposable.None; } if (!Gesture.INSTANCE) { Gesture.INSTANCE = new Gesture(); } Gesture.INSTANCE.targets.push(element); return { dispose: function () { Gesture.INSTANCE.targets = Gesture.INSTANCE.targets.filter(function (t) { return t !== element; }); } }; }; Gesture.ignoreTarget = function (element) { if (!Gesture.isTouchDevice()) { return lifecycle_1.Disposable.None; } if (!Gesture.INSTANCE) { Gesture.INSTANCE = new Gesture(); } Gesture.INSTANCE.ignoreTargets.push(element); return { dispose: function () { Gesture.INSTANCE.ignoreTargets = Gesture.INSTANCE.ignoreTargets.filter(function (t) { return t !== element; }); } }; }; Gesture.isTouchDevice = function () { return 'ontouchstart' in window || navigator.maxTouchPoints > 0 || window.navigator.msMaxTouchPoints > 0; }; Gesture.prototype.dispose = function () { if (this.handle) { this.handle.dispose(); this.handle = null; } _super.prototype.dispose.call(this); }; Gesture.prototype.onTouchStart = function (e) { var 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 (var i = 0, len = e.targetTouches.length; i < len; i++) { var 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] }; var 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; } }; Gesture.prototype.onTouchEnd = function (e) { var timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based. var activeTouchCount = Object.keys(this.activeTouches).length; var _loop_1 = function (i, len) { var touch = e.changedTouches.item(i); if (!this_1.activeTouches.hasOwnProperty(String(touch.identifier))) { console.warn('move of an UNKNOWN touch', touch); return "continue"; } var data = this_1.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) { var evt = this_1.newGestureEvent(EventType.Tap, data.initialTarget); evt.pageX = arrays.tail(data.rollingPageX); evt.pageY = arrays.tail(data.rollingPageY); this_1.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) { var evt = this_1.newGestureEvent(EventType.Contextmenu, data.initialTarget); evt.pageX = arrays.tail(data.rollingPageX); evt.pageY = arrays.tail(data.rollingPageY); this_1.dispatchEvent(evt); } else if (activeTouchCount === 1) { var finalX = arrays.tail(data.rollingPageX); var finalY = arrays.tail(data.rollingPageY); var deltaT = arrays.tail(data.rollingTimestamps) - data.rollingTimestamps[0]; var deltaX = finalX - data.rollingPageX[0]; var deltaY = finalY - data.rollingPageY[0]; // We need to get all the dispatch targets on the start of the inertia event var dispatchTo = this_1.targets.filter(function (t) { return data.initialTarget instanceof Node && t.contains(data.initialTarget); }); this_1.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_1.dispatchEvent(this_1.newGestureEvent(EventType.End, data.initialTarget)); // forget about this touch delete this_1.activeTouches[touch.identifier]; }; var this_1 = this; for (var i = 0, len = e.changedTouches.length; i < len; i++) { _loop_1(i, len); } if (this.dispatched) { e.preventDefault(); e.stopPropagation(); this.dispatched = false; } }; Gesture.prototype.newGestureEvent = function (type, initialTarget) { var event = document.createEvent('CustomEvent'); event.initEvent(type, false, true); event.initialTarget = initialTarget; event.tapCount = 0; return event; }; Gesture.prototype.dispatchEvent = function (event) { var _this = this; if (event.type === EventType.Tap) { var currentTime = (new Date()).getTime(); var 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 (var i = 0; i < this.ignoreTargets.length; i++) { if (event.initialTarget instanceof Node && this.ignoreTargets[i].contains(event.initialTarget)) { return; } } this.targets.forEach(function (target) { if (event.initialTarget instanceof Node && target.contains(event.initialTarget)) { target.dispatchEvent(event); _this.dispatched = true; } }); }; Gesture.prototype.inertia = function (dispatchTo, t1, vX, dirX, x, vY, dirY, y) { var _this = this; this.handle = DomUtils.scheduleAtNextAnimationFrame(function () { var now = Date.now(); // velocity: old speed + accel_over_time var 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 var evt = _this.newGestureEvent(EventType.Change); evt.translationX = delta_pos_x; evt.translationY = delta_pos_y; dispatchTo.forEach(function (d) { return d.dispatchEvent(evt); }); if (!stopped) { _this.inertia(dispatchTo, now, vX, dirX, x + delta_pos_x, vY, dirY, y + delta_pos_y); } }); }; Gesture.prototype.onTouchMove = function (e) { var timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based. for (var i = 0, len = e.changedTouches.length; i < len; i++) { var touch = e.changedTouches.item(i); if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) { console.warn('end of an UNKNOWN touch', touch); continue; } var data = this.activeTouches[touch.identifier]; var 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); return Gesture; }(lifecycle_1.Disposable)); 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[249/*vs/base/browser/ui/list/rowCache*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/]), function (require, exports, dom_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 } } var RowCache = /** @class */ (function () { function RowCache(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. */ RowCache.prototype.alloc = function (templateId) { var result = this.getTemplateCache(templateId).pop(); if (!result) { var domNode = dom_1.$('.monaco-list-row'); var renderer = this.getRenderer(templateId); var templateData = renderer.renderTemplate(domNode); result = { domNode: domNode, templateId: templateId, templateData: templateData }; } return result; }; /** * Releases the row for eventual reuse. */ RowCache.prototype.release = function (row) { if (!row) { return; } this.releaseRow(row); }; RowCache.prototype.releaseRow = function (row) { var domNode = row.domNode, templateId = row.templateId; if (domNode) { dom_1.removeClass(domNode, 'scrolling'); removeFromParent(domNode); } var cache = this.getTemplateCache(templateId); cache.push(row); }; RowCache.prototype.getTemplateCache = function (templateId) { var result = this.cache.get(templateId); if (!result) { result = []; this.cache.set(templateId, result); } return result; }; RowCache.prototype.dispose = function () { var _this = this; this.cache.forEach(function (cachedRows, templateId) { for (var _i = 0, cachedRows_1 = cachedRows; _i < cachedRows_1.length; _i++) { var cachedRow = cachedRows_1[_i]; var renderer = _this.getRenderer(templateId); renderer.disposeTemplate(cachedRow.templateData); cachedRow.domNode = null; cachedRow.templateData = null; } }); this.cache.clear(); }; RowCache.prototype.getRenderer = function (templateId) { var renderer = this.renderers.get(templateId); if (!renderer) { throw new Error("No renderer found for " + templateId); } return renderer; }; return RowCache; }()); 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[47/*vs/base/browser/ui/widget*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,56/*vs/base/browser/keyboardEvent*/,45/*vs/base/browser/mouseEvent*/,2/*vs/base/common/lifecycle*/,57/*vs/base/browser/touch*/]), function (require, exports, dom, keyboardEvent_1, mouseEvent_1, lifecycle_1, touch_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Widget = /** @class */ (function (_super) { __extends(Widget, _super); function Widget() { return _super !== null && _super.apply(this, arguments) || this; } Widget.prototype.onclick = function (domNode, listener) { this._register(dom.addDisposableListener(domNode, dom.EventType.CLICK, function (e) { return listener(new mouseEvent_1.StandardMouseEvent(e)); })); }; Widget.prototype.onmousedown = function (domNode, listener) { this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_DOWN, function (e) { return listener(new mouseEvent_1.StandardMouseEvent(e)); })); }; Widget.prototype.onmouseover = function (domNode, listener) { this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_OVER, function (e) { return listener(new mouseEvent_1.StandardMouseEvent(e)); })); }; Widget.prototype.onnonbubblingmouseout = function (domNode, listener) { this._register(dom.addDisposableNonBubblingMouseOutListener(domNode, function (e) { return listener(new mouseEvent_1.StandardMouseEvent(e)); })); }; Widget.prototype.onkeydown = function (domNode, listener) { this._register(dom.addDisposableListener(domNode, dom.EventType.KEY_DOWN, function (e) { return listener(new keyboardEvent_1.StandardKeyboardEvent(e)); })); }; Widget.prototype.onkeyup = function (domNode, listener) { this._register(dom.addDisposableListener(domNode, dom.EventType.KEY_UP, function (e) { return listener(new keyboardEvent_1.StandardKeyboardEvent(e)); })); }; Widget.prototype.oninput = function (domNode, listener) { this._register(dom.addDisposableListener(domNode, dom.EventType.INPUT, listener)); }; Widget.prototype.onblur = function (domNode, listener) { this._register(dom.addDisposableListener(domNode, dom.EventType.BLUR, listener)); }; Widget.prototype.onfocus = function (domNode, listener) { this._register(dom.addDisposableListener(domNode, dom.EventType.FOCUS, listener)); }; Widget.prototype.ignoreGesture = function (domNode) { touch_1.Gesture.ignoreTarget(domNode); }; return Widget; }(lifecycle_1.Disposable)); 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[135/*vs/base/browser/ui/scrollbar/scrollbarArrow*/], __M([0/*require*/,1/*exports*/,78/*vs/base/browser/globalMouseMoveMonitor*/,47/*vs/base/browser/ui/widget*/,15/*vs/base/common/async*/]), function (require, exports, globalMouseMoveMonitor_1, widget_1, async_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * The arrow image size. */ exports.ARROW_IMG_SIZE = 11; var ScrollbarArrow = /** @class */ (function (_super) { __extends(ScrollbarArrow, _super); function ScrollbarArrow(opts) { var _this = _super.call(this) || this; _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.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, function (e) { return _this._arrowMouseDown(e); }); _this.onmousedown(_this.domNode, function (e) { return _this._arrowMouseDown(e); }); _this._mousedownRepeatTimer = _this._register(new async_1.IntervalTimer()); _this._mousedownScheduleRepeatTimer = _this._register(new async_1.TimeoutTimer()); return _this; } ScrollbarArrow.prototype._arrowMouseDown = function (e) { var _this = this; var scheduleRepeater = function () { _this._mousedownRepeatTimer.cancelAndSet(function () { return _this._onActivate(); }, 1000 / 24); }; this._onActivate(); this._mousedownRepeatTimer.cancel(); this._mousedownScheduleRepeatTimer.cancelAndSet(scheduleRepeater, 200); this._mouseMoveMonitor.startMonitoring(e.target, e.buttons, globalMouseMoveMonitor_1.standardMouseMoveMerger, function (mouseMoveData) { /* Intentional empty */ }, function () { _this._mousedownRepeatTimer.cancel(); _this._mousedownScheduleRepeatTimer.cancel(); }); e.preventDefault(); }; return ScrollbarArrow; }(widget_1.Widget)); 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[181/*vs/base/browser/ui/scrollbar/abstractScrollbar*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,28/*vs/base/browser/fastDomNode*/,78/*vs/base/browser/globalMouseMoveMonitor*/,135/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,244/*vs/base/browser/ui/scrollbar/scrollbarVisibilityController*/,47/*vs/base/browser/ui/widget*/,16/*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 }); /** * The orthogonal distance to the slider at which dragging "resets". This implements "snapping" */ var MOUSE_DRAG_RESET_DISTANCE = 140; var AbstractScrollbar = /** @class */ (function (_super) { __extends(AbstractScrollbar, _super); function AbstractScrollbar(opts) { var _this = _super.call(this) || this; _this._lazyRender = opts.lazyRender; _this._host = opts.host; _this._scrollable = opts.scrollable; _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 = 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, function (e) { return _this._domNodeMouseDown(e); }); return _this; } // ----------------- creation /** * Creates the dom node for an arrow & adds it to the container */ AbstractScrollbar.prototype._createArrow = function (opts) { var 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 */ AbstractScrollbar.prototype._createSlider = function (top, left, width, height) { var _this = this; this.slider = 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, function (e) { if (e.leftButton) { e.preventDefault(); _this._sliderMouseDown(e, function () { }); } }); this.onclick(this.slider.domNode, function (e) { if (e.leftButton) { e.stopPropagation(); } }); }; // ----------------- Update state AbstractScrollbar.prototype._onElementSize = function (visibleSize) { if (this._scrollbarState.setVisibleSize(visibleSize)) { this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()); this._shouldRender = true; if (!this._lazyRender) { this.render(); } } return this._shouldRender; }; AbstractScrollbar.prototype._onElementScrollSize = function (elementScrollSize) { if (this._scrollbarState.setScrollSize(elementScrollSize)) { this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()); this._shouldRender = true; if (!this._lazyRender) { this.render(); } } return this._shouldRender; }; AbstractScrollbar.prototype._onElementScrollPosition = function (elementScrollPosition) { if (this._scrollbarState.setScrollPosition(elementScrollPosition)) { this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()); this._shouldRender = true; if (!this._lazyRender) { this.render(); } } return this._shouldRender; }; // ----------------- rendering AbstractScrollbar.prototype.beginReveal = function () { this._visibilityController.setShouldBeVisible(true); }; AbstractScrollbar.prototype.beginHide = function () { this._visibilityController.setShouldBeVisible(false); }; AbstractScrollbar.prototype.render = function () { 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 AbstractScrollbar.prototype._domNodeMouseDown = function (e) { if (e.target !== this.domNode.domNode) { return; } this._onMouseDown(e); }; AbstractScrollbar.prototype.delegateMouseDown = function (e) { var domTop = this.domNode.domNode.getClientRects()[0].top; var sliderStart = domTop + this._scrollbarState.getSliderPosition(); var sliderStop = domTop + this._scrollbarState.getSliderPosition() + this._scrollbarState.getSliderSize(); var 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, function () { }); } } else { // Act as if it was a mouse down on the scrollbar this._onMouseDown(e); } }; AbstractScrollbar.prototype._onMouseDown = function (e) { var offsetX; var 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 { var domNodePosition = dom.getDomNodePagePosition(this.domNode.domNode); offsetX = e.posx - domNodePosition.left; offsetY = e.posy - domNodePosition.top; } this._setDesiredScrollPositionNow(this._scrollbarState.getDesiredScrollPositionFromOffset(this._mouseDownRelativePosition(offsetX, offsetY))); if (e.leftButton) { e.preventDefault(); this._sliderMouseDown(e, function () { }); } }; AbstractScrollbar.prototype._sliderMouseDown = function (e, onDragFinished) { var _this = this; var initialMousePosition = this._sliderMousePosition(e); var initialMouseOrthogonalPosition = this._sliderOrthogonalMousePosition(e); var initialScrollbarState = this._scrollbarState.clone(); this.slider.toggleClassName('active', true); this._mouseMoveMonitor.startMonitoring(e.target, e.buttons, globalMouseMoveMonitor_1.standardMouseMoveMerger, function (mouseMoveData) { var mouseOrthogonalPosition = _this._sliderOrthogonalMousePosition(mouseMoveData); var 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; } var mousePosition = _this._sliderMousePosition(mouseMoveData); var mouseDelta = mousePosition - initialMousePosition; _this._setDesiredScrollPositionNow(initialScrollbarState.getDesiredScrollPositionFromDelta(mouseDelta)); }, function () { _this.slider.toggleClassName('active', false); _this._host.onDragEnd(); onDragFinished(); }); this._host.onDragStart(); }; AbstractScrollbar.prototype._setDesiredScrollPositionNow = function (_desiredScrollPosition) { var desiredScrollPosition = {}; this.writeScrollPosition(desiredScrollPosition, _desiredScrollPosition); this._scrollable.setScrollPositionNow(desiredScrollPosition); }; return AbstractScrollbar; }(widget_1.Widget)); 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[250/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/], __M([0/*require*/,1/*exports*/,45/*vs/base/browser/mouseEvent*/,181/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,135/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,175/*vs/base/browser/ui/scrollbar/scrollbarState*/]), function (require, exports, mouseEvent_1, abstractScrollbar_1, scrollbarArrow_1, scrollbarState_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var HorizontalScrollbar = /** @class */ (function (_super) { __extends(HorizontalScrollbar, _super); function HorizontalScrollbar(scrollable, options, host) { var _this = this; var scrollDimensions = scrollable.getScrollDimensions(); var scrollPosition = scrollable.getCurrentScrollPosition(); _this = _super.call(this, { 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 }) || this; if (options.horizontalHasArrows) { var arrowDelta = (options.arrowSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2; var scrollbarDelta = (options.horizontalScrollbarSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2; _this._createArrow({ className: 'left-arrow', top: scrollbarDelta, left: arrowDelta, bottom: undefined, right: undefined, bgWidth: options.arrowSize, bgHeight: options.horizontalScrollbarSize, onActivate: function () { return _this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, 1, 0)); }, }); _this._createArrow({ className: 'right-arrow', top: scrollbarDelta, left: undefined, bottom: undefined, right: arrowDelta, bgWidth: options.arrowSize, bgHeight: options.horizontalScrollbarSize, onActivate: function () { return _this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, -1, 0)); }, }); } _this._createSlider(Math.floor((options.horizontalScrollbarSize - options.horizontalSliderSize) / 2), 0, undefined, options.horizontalSliderSize); return _this; } HorizontalScrollbar.prototype._updateSlider = function (sliderSize, sliderPosition) { this.slider.setWidth(sliderSize); this.slider.setLeft(sliderPosition); }; HorizontalScrollbar.prototype._renderDomNode = function (largeSize, smallSize) { this.domNode.setWidth(largeSize); this.domNode.setHeight(smallSize); this.domNode.setLeft(0); this.domNode.setBottom(0); }; HorizontalScrollbar.prototype.onDidScroll = function (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; }; HorizontalScrollbar.prototype._mouseDownRelativePosition = function (offsetX, offsetY) { return offsetX; }; HorizontalScrollbar.prototype._sliderMousePosition = function (e) { return e.posx; }; HorizontalScrollbar.prototype._sliderOrthogonalMousePosition = function (e) { return e.posy; }; HorizontalScrollbar.prototype.writeScrollPosition = function (target, scrollPosition) { target.scrollLeft = scrollPosition; }; return HorizontalScrollbar; }(abstractScrollbar_1.AbstractScrollbar)); 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[251/*vs/base/browser/ui/scrollbar/verticalScrollbar*/], __M([0/*require*/,1/*exports*/,45/*vs/base/browser/mouseEvent*/,181/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,135/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,175/*vs/base/browser/ui/scrollbar/scrollbarState*/]), function (require, exports, mouseEvent_1, abstractScrollbar_1, scrollbarArrow_1, scrollbarState_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var VerticalScrollbar = /** @class */ (function (_super) { __extends(VerticalScrollbar, _super); function VerticalScrollbar(scrollable, options, host) { var _this = this; var scrollDimensions = scrollable.getScrollDimensions(); var scrollPosition = scrollable.getCurrentScrollPosition(); _this = _super.call(this, { 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 }) || this; if (options.verticalHasArrows) { var arrowDelta = (options.arrowSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2; var scrollbarDelta = (options.verticalScrollbarSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2; _this._createArrow({ className: 'up-arrow', top: arrowDelta, left: scrollbarDelta, bottom: undefined, right: undefined, bgWidth: options.verticalScrollbarSize, bgHeight: options.arrowSize, onActivate: function () { return _this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, 0, 1)); }, }); _this._createArrow({ className: 'down-arrow', top: undefined, left: scrollbarDelta, bottom: arrowDelta, right: undefined, bgWidth: options.verticalScrollbarSize, bgHeight: options.arrowSize, onActivate: function () { return _this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, 0, -1)); }, }); } _this._createSlider(0, Math.floor((options.verticalScrollbarSize - options.verticalSliderSize) / 2), options.verticalSliderSize, undefined); return _this; } VerticalScrollbar.prototype._updateSlider = function (sliderSize, sliderPosition) { this.slider.setHeight(sliderSize); this.slider.setTop(sliderPosition); }; VerticalScrollbar.prototype._renderDomNode = function (largeSize, smallSize) { this.domNode.setWidth(smallSize); this.domNode.setHeight(largeSize); this.domNode.setRight(0); this.domNode.setTop(0); }; VerticalScrollbar.prototype.onDidScroll = function (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; }; VerticalScrollbar.prototype._mouseDownRelativePosition = function (offsetX, offsetY) { return offsetY; }; VerticalScrollbar.prototype._sliderMousePosition = function (e) { return e.posy; }; VerticalScrollbar.prototype._sliderOrthogonalMousePosition = function (e) { return e.posx; }; VerticalScrollbar.prototype.writeScrollPosition = function (target, scrollPosition) { target.scrollTop = scrollPosition; }; return VerticalScrollbar; }(abstractScrollbar_1.AbstractScrollbar)); 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. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[39/*vs/base/common/resources*/], __M([0/*require*/,1/*exports*/,177/*vs/base/common/extpath*/,77/*vs/base/common/path*/,25/*vs/base/common/uri*/,5/*vs/base/common/strings*/,46/*vs/base/common/network*/,16/*vs/base/common/platform*/]), function (require, exports, extpath, paths, uri_1, strings_1, network_1, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function hasToIgnoreCase(resource) { // 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 resource && resource.scheme === network_1.Schemas.file ? !platform_1.isLinux : true; } exports.hasToIgnoreCase = hasToIgnoreCase; function basenameOrAuthority(resource) { return basename(resource) || resource.authority; } exports.basenameOrAuthority = basenameOrAuthority; /** * Tests wheter the two authorities are the same */ function isEqualAuthority(a1, a2) { return a1 === a2 || strings_1.equalsIgnoreCase(a1, a2); } exports.isEqualAuthority = isEqualAuthority; function isEqual(first, second, ignoreCase) { if (ignoreCase === void 0) { ignoreCase = hasToIgnoreCase(first); } if (first === second) { return true; } if (!first || !second) { return false; } if (first.scheme !== second.scheme || !isEqualAuthority(first.authority, second.authority)) { return false; } var p1 = first.path || '/', p2 = second.path || '/'; return p1 === p2 || ignoreCase && strings_1.equalsIgnoreCase(p1 || '/', p2 || '/'); } exports.isEqual = isEqual; function basename(resource) { return paths.posix.basename(resource.path); } exports.basename = basename; /** * Return a URI representing the directory of a URI path. * * @param resource The input URI. * @returns The URI representing the directory of the input URI. */ function dirname(resource) { if (resource.path.length === 0) { return resource; } if (resource.scheme === network_1.Schemas.file) { return uri_1.URI.file(paths.dirname(originalFSPath(resource))); } var 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 }); } exports.dirname = dirname; /** * Join a URI path with path fragments and normalizes the resulting path. * * @param resource The input URI. * @param pathFragment The path fragment to add to the URI path. * @returns The resulting URI. */ function joinPath(resource) { var _a; var pathFragment = []; for (var _i = 1; _i < arguments.length; _i++) { pathFragment[_i - 1] = arguments[_i]; } var joinedPath; if (resource.scheme === network_1.Schemas.file) { joinedPath = uri_1.URI.file(paths.join.apply(paths, __spreadArrays([originalFSPath(resource)], pathFragment))).path; } else { joinedPath = (_a = paths.posix).join.apply(_a, __spreadArrays([resource.path || '/'], pathFragment)); } return resource.with({ path: joinedPath }); } exports.joinPath = joinPath; /** * Normalizes the path part of a URI: Resolves `.` and `..` elements with directory names. * * @param resource The URI to normalize the path. * @returns The URI with the normalized path. */ function normalizePath(resource) { if (!resource.path.length) { return resource; } var 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 }); } exports.normalizePath = normalizePath; /** * Returns the fsPath of an URI where the drive letter is not normalized. * See #56403. */ function originalFSPath(uri) { var value; var uriPath = uri.path; if (uri.authority && uriPath.length > 1 && uri.scheme === network_1.Schemas.file) { // unc path: file://shares/c$/far/boo value = "//" + uri.authority + uriPath; } else if (platform_1.isWindows && uriPath.charCodeAt(0) === 47 /* Slash */ && extpath.isWindowsDriveLetter(uriPath.charCodeAt(1)) && uriPath.charCodeAt(2) === 58 /* Colon */) { value = uriPath.substr(1); } else { // other path value = uriPath; } if (platform_1.isWindows) { value = value.replace(/\//g, '\\'); } return value; } exports.originalFSPath = originalFSPath; /** * Returns a relative path between two URIs. If the URIs don't have the same schema or authority, `undefined` is returned. * The returned relative path always uses forward slashes. */ function relativePath(from, to, ignoreCase) { if (ignoreCase === void 0) { ignoreCase = hasToIgnoreCase(from); } if (from.scheme !== to.scheme || !isEqualAuthority(from.authority, to.authority)) { return undefined; } if (from.scheme === network_1.Schemas.file) { var relativePath_1 = paths.relative(from.path, to.path); return platform_1.isWindows ? extpath.toSlashes(relativePath_1) : relativePath_1; } var fromPath = from.path || '/', toPath = to.path || '/'; if (ignoreCase) { // make casing of fromPath match toPath var i = 0; for (var 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); } exports.relativePath = relativePath; /** * 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) { var 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 var meta = dataUri.path.substring(dataUri.path.indexOf(';') + 1, dataUri.path.lastIndexOf(';')); meta.split(';').forEach(function (property) { var _a = property.split(':'), key = _a[0], value = _a[1]; 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 var 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[136/*vs/base/common/labels*/], __M([0/*require*/,1/*exports*/,25/*vs/base/common/uri*/,77/*vs/base/common/path*/,5/*vs/base/common/strings*/,46/*vs/base/common/network*/,16/*vs/base/common/platform*/,39/*vs/base/common/resources*/]), function (require, exports, uri_1, path_1, strings_1, network_1, platform_1, resources_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * @deprecated use LabelService instead */ function getPathLabel(resource, userHomeProvider, rootProvider) { if (typeof resource === 'string') { resource = uri_1.URI.file(resource); } // return early if we can resolve a relative path label from the root if (rootProvider) { var baseResource = rootProvider.getWorkspaceFolder(resource); if (baseResource) { var hasMultipleRoots = rootProvider.getWorkspace().folders.length > 1; var pathLabel = void 0; if (resources_1.isEqual(baseResource.uri, resource)) { pathLabel = ''; // no label if paths are identical } else { pathLabel = resources_1.relativePath(baseResource.uri, resource); } if (hasMultipleRoots) { var rootName = baseResource.name ? baseResource.name : resources_1.basename(baseResource.uri); pathLabel = pathLabel ? (rootName + ' • ' + pathLabel) : rootName; // always show root basename if there are multiple } return pathLabel; } } // return if the resource is neither file:// nor untitled:// and no baseResource was provided if (resource.scheme !== network_1.Schemas.file && resource.scheme !== network_1.Schemas.untitled) { return resource.with({ query: null, fragment: null }).toString(true); } // convert c:\something => C:\something if (hasDriveLetter(resource.fsPath)) { return path_1.normalize(normalizeDriveLetter(resource.fsPath)); } // normalize and tildify (macOS, Linux only) var res = path_1.normalize(resource.fsPath); if (!platform_1.isWindows && userHomeProvider) { res = tildify(res, userHomeProvider.userHome); } return res; } exports.getPathLabel = getPathLabel; function getBaseLabel(resource) { if (!resource) { return undefined; } if (typeof resource === 'string') { resource = uri_1.URI.file(resource); } var base = 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 (hasDriveLetter(base)) { return normalizeDriveLetter(base); } return base; } exports.getBaseLabel = getBaseLabel; function hasDriveLetter(path) { return !!(platform_1.isWindows && path && path[1] === ':'); } function normalizeDriveLetter(path) { if (hasDriveLetter(path)) { return path.charAt(0).toUpperCase() + path.slice(1); } return path; } exports.normalizeDriveLetter = normalizeDriveLetter; var normalizedUserHomeCached = Object.create(null); function tildify(path, userHome) { if (platform_1.isWindows || !path || !userHome) { return path; // unsupported } // Keep a normalized user home path as cache to prevent accumulated string creation var normalizedUserHome = normalizedUserHomeCached.original === userHome ? normalizedUserHomeCached.normalized : undefined; if (!normalizedUserHome) { normalizedUserHome = "" + strings_1.rtrim(userHome, path_1.posix.sep) + path_1.posix.sep; normalizedUserHomeCached = { original: userHome, normalized: normalizedUserHome }; } // Linux: case sensitive, macOS: case insensitive if (platform_1.isLinux ? strings_1.startsWith(path, normalizedUserHome) : strings_1.startsWithIgnoreCase(path, normalizedUserHome)) { path = "~/" + path.substr(normalizedUserHome.length); } return path; } exports.tildify = tildify; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[252/*vs/base/common/mime*/], __M([0/*require*/,1/*exports*/,77/*vs/base/common/path*/,5/*vs/base/common/strings*/,178/*vs/base/common/glob*/,46/*vs/base/common/network*/,39/*vs/base/common/resources*/]), function (require, exports, path_1, strings_1, glob_1, network_1, resources_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MIME_TEXT = 'text/plain'; exports.MIME_UNKNOWN = 'application/unknown'; var registeredAssociations = []; var nonUserRegisteredAssociations = []; var userRegisteredAssociations = []; /** * Associate a text mime to the registry. */ function registerTextMime(association, warnOnOverwrite) { if (warnOnOverwrite === void 0) { warnOnOverwrite = false; } // Register var associationItem = toTextMimeAssociationItem(association); registeredAssociations.push(associationItem); if (!associationItem.userConfigured) { nonUserRegisteredAssociations.push(associationItem); } else { userRegisteredAssociations.push(associationItem); } // Check for conflicts unless this is a user configured association if (warnOnOverwrite && !associationItem.userConfigured) { registeredAssociations.forEach(function (a) { if (a.mime === associationItem.mime || a.userConfigured) { return; // same mime or userConfigured is ok } if (associationItem.extension && a.extension === associationItem.extension) { console.warn("Overwriting extension <<" + associationItem.extension + ">> to now point to mime <<" + associationItem.mime + ">>"); } if (associationItem.filename && a.filename === associationItem.filename) { console.warn("Overwriting filename <<" + associationItem.filename + ">> to now point to mime <<" + associationItem.mime + ">>"); } if (associationItem.filepattern && a.filepattern === associationItem.filepattern) { console.warn("Overwriting filepattern <<" + associationItem.filepattern + ">> to now point to mime <<" + associationItem.mime + ">>"); } if (associationItem.firstline && a.firstline === associationItem.firstline) { console.warn("Overwriting firstline <<" + associationItem.firstline + ">> to now point to mime <<" + associationItem.mime + ">>"); } }); } } exports.registerTextMime = registerTextMime; function toTextMimeAssociationItem(association) { return { id: association.id, mime: association.mime, filename: association.filename, extension: association.extension, filepattern: association.filepattern, firstline: association.firstline, userConfigured: association.userConfigured, filenameLowercase: association.filename ? association.filename.toLowerCase() : undefined, extensionLowercase: association.extension ? association.extension.toLowerCase() : undefined, filepatternLowercase: association.filepattern ? association.filepattern.toLowerCase() : undefined, filepatternOnPath: association.filepattern ? association.filepattern.indexOf(path_1.posix.sep) >= 0 : false }; } /** * Given a file, return the best matching mime type for it */ function guessMimeTypes(resource, firstLine) { var path; if (resource) { switch (resource.scheme) { case network_1.Schemas.file: path = resource.fsPath; break; case network_1.Schemas.data: var metadata = resources_1.DataUri.parseMetaData(resource); path = metadata.get(resources_1.DataUri.META_DATA_LABEL); break; default: path = resource.path; } } if (!path) { return [exports.MIME_UNKNOWN]; } path = path.toLowerCase(); var filename = path_1.basename(path); // 1.) User configured mappings have highest priority var configuredMime = guessMimeTypeByPath(path, filename, userRegisteredAssociations); if (configuredMime) { return [configuredMime, exports.MIME_TEXT]; } // 2.) Registered mappings have middle priority var registeredMime = guessMimeTypeByPath(path, filename, nonUserRegisteredAssociations); if (registeredMime) { return [registeredMime, exports.MIME_TEXT]; } // 3.) Firstline has lowest priority if (firstLine) { var firstlineMime = guessMimeTypeByFirstline(firstLine); if (firstlineMime) { return [firstlineMime, exports.MIME_TEXT]; } } return [exports.MIME_UNKNOWN]; } exports.guessMimeTypes = guessMimeTypes; function guessMimeTypeByPath(path, filename, associations) { var filenameMatch = null; var patternMatch = null; var extensionMatch = null; // We want to prioritize associations based on the order they are registered so that the last registered // association wins over all other. This is for https://github.com/Microsoft/vscode/issues/20074 for (var i = associations.length - 1; i >= 0; i--) { var 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) { var target = association.filepatternOnPath ? path : filename; // match on full path if pattern contains path separator if (glob_1.match(association.filepatternLowercase, target)) { patternMatch = association; } } } // Longest extension match if (association.extension) { if (!extensionMatch || association.extension.length > extensionMatch.extension.length) { if (strings_1.endsWith(filename, association.extensionLowercase)) { extensionMatch = association; } } } } // 1.) Exact name match has second highest prio if (filenameMatch) { return filenameMatch.mime; } // 2.) Match on pattern if (patternMatch) { return patternMatch.mime; } // 3.) Match on extension comes next if (extensionMatch) { return extensionMatch.mime; } return null; } function guessMimeTypeByFirstline(firstLine) { if (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 (var i = registeredAssociations.length - 1; i >= 0; i--) { var association = registeredAssociations[i]; if (!association.firstline) { continue; } var matches = firstLine.match(association.firstline); if (matches && matches.length > 0) { return association.mime; } } } 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[182/*vs/base/common/worker/simpleWorker*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,21/*vs/base/common/types*/]), function (require, exports, errors_1, lifecycle_1, platform_1, types) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var INITIALIZE = '$initialize'; var 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; var SimpleWorkerProtocol = /** @class */ (function () { function SimpleWorkerProtocol(handler) { this._workerId = -1; this._handler = handler; this._lastSentReq = 0; this._pendingReplies = Object.create(null); } SimpleWorkerProtocol.prototype.setWorkerId = function (workerId) { this._workerId = workerId; }; SimpleWorkerProtocol.prototype.sendMessage = function (method, args) { var _this = this; var req = String(++this._lastSentReq); return new Promise(function (resolve, reject) { _this._pendingReplies[req] = { resolve: resolve, reject: reject }; _this._send({ vsWorker: _this._workerId, req: req, method: method, args: args }); }); }; SimpleWorkerProtocol.prototype.handleMessage = function (message) { if (!message || !message.vsWorker) { return; } if (this._workerId !== -1 && message.vsWorker !== this._workerId) { return; } this._handleMessage(message); }; SimpleWorkerProtocol.prototype._handleMessage = function (msg) { var _this = this; if (msg.seq) { var replyMessage = msg; if (!this._pendingReplies[replyMessage.seq]) { console.warn('Got reply to unknown seq'); return; } var reply = this._pendingReplies[replyMessage.seq]; delete this._pendingReplies[replyMessage.seq]; if (replyMessage.err) { var err = replyMessage.err; if (replyMessage.err.$isError) { err = new Error(); err.name = replyMessage.err.name; err.message = replyMessage.err.message; err.stack = replyMessage.err.stack; } reply.reject(err); return; } reply.resolve(replyMessage.res); return; } var requestMessage = msg; var req = requestMessage.req; var result = this._handler.handleMessage(requestMessage.method, requestMessage.args); result.then(function (r) { _this._send({ vsWorker: _this._workerId, seq: req, res: r, err: undefined }); }, function (e) { if (e.detail instanceof Error) { // Loading errors have a detail property that points to the actual error e.detail = errors_1.transformErrorForSerialization(e.detail); } _this._send({ vsWorker: _this._workerId, seq: req, res: undefined, err: errors_1.transformErrorForSerialization(e) }); }); }; SimpleWorkerProtocol.prototype._send = function (msg) { var transfer = []; if (msg.req) { var m = msg; for (var i = 0; i < m.args.length; i++) { if (m.args[i] instanceof ArrayBuffer) { transfer.push(m.args[i]); } } } else { var m = msg; if (m.res instanceof ArrayBuffer) { transfer.push(m.res); } } this._handler.sendMessage(msg, transfer); }; return SimpleWorkerProtocol; }()); /** * Main thread side */ var SimpleWorkerClient = /** @class */ (function (_super) { __extends(SimpleWorkerClient, _super); function SimpleWorkerClient(workerFactory, moduleId, host) { var _this = _super.call(this) || this; var lazyProxyReject = null; _this._worker = _this._register(workerFactory.create('vs/base/common/worker/simpleWorker', function (msg) { _this._protocol.handleMessage(msg); }, function (err) { // in Firefox, web workers fail lazily :( // we will reject the proxy if (lazyProxyReject) { lazyProxyReject(err); } })); _this._protocol = new SimpleWorkerProtocol({ sendMessage: function (msg, transfer) { _this._worker.postMessage(msg, transfer); }, handleMessage: function (method, args) { if (typeof host[method] !== 'function') { return Promise.reject(new Error('Missing method ' + method + ' on main thread host.')); } try { return Promise.resolve(host[method].apply(host, args)); } catch (e) { return Promise.reject(e); } } }); _this._protocol.setWorkerId(_this._worker.getId()); // Gather loader configuration var loaderConfiguration = null; if (typeof self.require !== 'undefined' && typeof self.require.getConfig === 'function') { // Get the configuration from the Monaco AMD Loader loaderConfiguration = self.require.getConfig(); } else if (typeof self.requirejs !== 'undefined') { // Get the configuration from requirejs loaderConfiguration = self.requirejs.s.contexts._.config; } var 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 var proxyMethodRequest = function (method, args) { return _this._request(method, args); }; _this._lazyProxy = new Promise(function (resolve, reject) { lazyProxyReject = reject; _this._onModuleLoaded.then(function (availableMethods) { resolve(types.createProxyObject(availableMethods, proxyMethodRequest)); }, function (e) { reject(e); _this._onError('Worker failed to load ' + moduleId, e); }); }); return _this; } SimpleWorkerClient.prototype.getProxyObject = function () { return this._lazyProxy; }; SimpleWorkerClient.prototype._request = function (method, args) { var _this = this; return new Promise(function (resolve, reject) { _this._onModuleLoaded.then(function () { _this._protocol.sendMessage(method, args).then(resolve, reject); }, reject); }); }; SimpleWorkerClient.prototype._onError = function (message, error) { console.error(message); console.info(error); }; return SimpleWorkerClient; }(lifecycle_1.Disposable)); exports.SimpleWorkerClient = SimpleWorkerClient; /** * Worker side */ var SimpleWorkerServer = /** @class */ (function () { function SimpleWorkerServer(postMessage, requestHandlerFactory) { var _this = this; this._requestHandlerFactory = requestHandlerFactory; this._requestHandler = null; this._protocol = new SimpleWorkerProtocol({ sendMessage: function (msg, transfer) { postMessage(msg, transfer); }, handleMessage: function (method, args) { return _this._handleMessage(method, args); } }); } SimpleWorkerServer.prototype.onmessage = function (msg) { this._protocol.handleMessage(msg); }; SimpleWorkerServer.prototype._handleMessage = function (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); } }; SimpleWorkerServer.prototype.initialize = function (workerId, loaderConfig, moduleId, hostMethods) { var _this = this; this._protocol.setWorkerId(workerId); var proxyMethodRequest = function (method, args) { return _this._protocol.sendMessage(method, args); }; var hostProxy = types.createProxyObject(hostMethods, proxyMethodRequest); if (this._requestHandlerFactory) { // static request handler this._requestHandler = this._requestHandlerFactory(hostProxy); return Promise.resolve(types.getAllMethodNames(this._requestHandler)); } if (loaderConfig) { // Remove 'baseUrl', handling it is beyond scope for now if (typeof loaderConfig.baseUrl !== 'undefined') { delete loaderConfig['baseUrl']; } if (typeof loaderConfig.paths !== 'undefined') { if (typeof loaderConfig.paths.vs !== 'undefined') { delete loaderConfig.paths['vs']; } } // Since this is in a web worker, enable catching errors loaderConfig.catchError = true; self.require.config(loaderConfig); } return new Promise(function (resolve, reject) { // Use the global require to be sure to get the global config self.require([moduleId], function (module) { _this._requestHandler = module.create(hostProxy); if (!_this._requestHandler) { reject(new Error("No RequestHandler!")); return; } resolve(types.getAllMethodNames(_this._requestHandler)); }, reject); }); }; return SimpleWorkerServer; }()); 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[253/*vs/base/parts/quickopen/browser/quickOpenViewer*/], __M([0/*require*/,1/*exports*/,21/*vs/base/common/types*/]), function (require, exports, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DataSource = /** @class */ (function () { function DataSource(arg) { this.modelProvider = types_1.isFunction(arg.getModel) ? arg : { getModel: function () { return arg; } }; } DataSource.prototype.getId = function (tree, element) { if (!element) { return null; } var model = this.modelProvider.getModel(); return model === element ? '__root__' : model.dataSource.getId(element); }; DataSource.prototype.hasChildren = function (tree, element) { var model = this.modelProvider.getModel(); return !!(model && model === element && model.entries.length > 0); }; DataSource.prototype.getChildren = function (tree, element) { var model = this.modelProvider.getModel(); return Promise.resolve(model === element ? model.entries : []); }; DataSource.prototype.getParent = function (tree, element) { return Promise.resolve(null); }; return DataSource; }()); exports.DataSource = DataSource; var AccessibilityProvider = /** @class */ (function () { function AccessibilityProvider(modelProvider) { this.modelProvider = modelProvider; } AccessibilityProvider.prototype.getAriaLabel = function (tree, element) { var model = this.modelProvider.getModel(); return model.accessibilityProvider ? model.accessibilityProvider.getAriaLabel(element) : null; }; AccessibilityProvider.prototype.getPosInSet = function (tree, element) { var model = this.modelProvider.getModel(); var i = 0; if (model.filter) { for (var _i = 0, _a = model.entries; _i < _a.length; _i++) { var entry = _a[_i]; if (model.filter.isVisible(entry)) { i++; } if (entry === element) { break; } } } else { i = model.entries.indexOf(element) + 1; } return String(i); }; AccessibilityProvider.prototype.getSetSize = function () { var model = this.modelProvider.getModel(); var n = 0; if (model.filter) { for (var _i = 0, _a = model.entries; _i < _a.length; _i++) { var entry = _a[_i]; if (model.filter.isVisible(entry)) { n++; } } } else { n = model.entries.length; } return String(n); }; return AccessibilityProvider; }()); exports.AccessibilityProvider = AccessibilityProvider; var Filter = /** @class */ (function () { function Filter(modelProvider) { this.modelProvider = modelProvider; } Filter.prototype.isVisible = function (tree, element) { var model = this.modelProvider.getModel(); if (!model.filter) { return true; } return model.filter.isVisible(element); }; return Filter; }()); exports.Filter = Filter; var Renderer = /** @class */ (function () { function Renderer(modelProvider, styles) { this.modelProvider = modelProvider; this.styles = styles; } Renderer.prototype.updateStyles = function (styles) { this.styles = styles; }; Renderer.prototype.getHeight = function (tree, element) { var model = this.modelProvider.getModel(); return model.renderer.getHeight(element); }; Renderer.prototype.getTemplateId = function (tree, element) { var model = this.modelProvider.getModel(); return model.renderer.getTemplateId(element); }; Renderer.prototype.renderTemplate = function (tree, templateId, container) { var model = this.modelProvider.getModel(); return model.renderer.renderTemplate(templateId, container, this.styles); }; Renderer.prototype.renderElement = function (tree, element, templateId, templateData) { var model = this.modelProvider.getModel(); model.renderer.renderElement(element, templateId, templateData, this.styles); }; Renderer.prototype.disposeTemplate = function (tree, templateId, templateData) { var model = this.modelProvider.getModel(); model.renderer.disposeTemplate(templateId, templateData); }; return Renderer; }()); exports.Renderer = Renderer; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[254/*vs/base/parts/tree/browser/tree*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ContextMenuEvent = /** @class */ (function () { function ContextMenuEvent(posx, posy, target) { this._posx = posx; this._posy = posy; this._target = target; } ContextMenuEvent.prototype.preventDefault = function () { // no-op }; ContextMenuEvent.prototype.stopPropagation = function () { // no-op }; Object.defineProperty(ContextMenuEvent.prototype, "target", { get: function () { return this._target; }, enumerable: true, configurable: true }); return ContextMenuEvent; }()); exports.ContextMenuEvent = ContextMenuEvent; var MouseContextMenuEvent = /** @class */ (function (_super) { __extends(MouseContextMenuEvent, _super); function MouseContextMenuEvent(originalEvent) { var _this = _super.call(this, originalEvent.posx, originalEvent.posy, originalEvent.target) || this; _this.originalEvent = originalEvent; return _this; } MouseContextMenuEvent.prototype.preventDefault = function () { this.originalEvent.preventDefault(); }; MouseContextMenuEvent.prototype.stopPropagation = function () { this.originalEvent.stopPropagation(); }; return MouseContextMenuEvent; }(ContextMenuEvent)); exports.MouseContextMenuEvent = MouseContextMenuEvent; var KeyboardContextMenuEvent = /** @class */ (function (_super) { __extends(KeyboardContextMenuEvent, _super); function KeyboardContextMenuEvent(posx, posy, originalEvent) { var _this = _super.call(this, posx, posy, originalEvent.target) || this; _this.originalEvent = originalEvent; return _this; } KeyboardContextMenuEvent.prototype.preventDefault = function () { this.originalEvent.preventDefault(); }; KeyboardContextMenuEvent.prototype.stopPropagation = function () { this.originalEvent.stopPropagation(); }; return KeyboardContextMenuEvent; }(ContextMenuEvent)); exports.KeyboardContextMenuEvent = KeyboardContextMenuEvent; }); define(__m[137/*vs/base/parts/tree/browser/treeDefaults*/], __M([0/*require*/,1/*exports*/,16/*vs/base/common/platform*/,10/*vs/base/common/errors*/,6/*vs/base/browser/dom*/,36/*vs/base/common/keyCodes*/]), function (require, exports, platform, errors, dom, keyCodes_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var KeybindingDispatcher = /** @class */ (function () { function KeybindingDispatcher() { this._arr = []; } KeybindingDispatcher.prototype.set = function (keybinding, callback) { this._arr.push({ keybinding: keyCodes_1.createKeybinding(keybinding, platform.OS), callback: callback }); }; KeybindingDispatcher.prototype.dispatch = function (keybinding) { // Loop from the last to the first to handle overwrites for (var i = this._arr.length - 1; i >= 0; i--) { var item = this._arr[i]; if (keybinding.toChord().equals(item.keybinding)) { return item.callback; } } return null; }; return KeybindingDispatcher; }()); exports.KeybindingDispatcher = KeybindingDispatcher; var DefaultController = /** @class */ (function () { function DefaultController(options) { var _this = this; if (options === void 0) { options = { clickBehavior: 0 /* ON_MOUSE_DOWN */, keyboardSupport: true, openMode: 0 /* SINGLE_CLICK */ }; } this.options = options; this.downKeyBindingDispatcher = new KeybindingDispatcher(); this.upKeyBindingDispatcher = new KeybindingDispatcher(); if (typeof options.keyboardSupport !== 'boolean' || options.keyboardSupport) { this.downKeyBindingDispatcher.set(16 /* UpArrow */, function (t, e) { return _this.onUp(t, e); }); this.downKeyBindingDispatcher.set(18 /* DownArrow */, function (t, e) { return _this.onDown(t, e); }); this.downKeyBindingDispatcher.set(15 /* LeftArrow */, function (t, e) { return _this.onLeft(t, e); }); this.downKeyBindingDispatcher.set(17 /* RightArrow */, function (t, e) { return _this.onRight(t, e); }); if (platform.isMacintosh) { this.downKeyBindingDispatcher.set(2048 /* CtrlCmd */ | 16 /* UpArrow */, function (t, e) { return _this.onLeft(t, e); }); this.downKeyBindingDispatcher.set(256 /* WinCtrl */ | 44 /* KEY_N */, function (t, e) { return _this.onDown(t, e); }); this.downKeyBindingDispatcher.set(256 /* WinCtrl */ | 46 /* KEY_P */, function (t, e) { return _this.onUp(t, e); }); } this.downKeyBindingDispatcher.set(11 /* PageUp */, function (t, e) { return _this.onPageUp(t, e); }); this.downKeyBindingDispatcher.set(12 /* PageDown */, function (t, e) { return _this.onPageDown(t, e); }); this.downKeyBindingDispatcher.set(14 /* Home */, function (t, e) { return _this.onHome(t, e); }); this.downKeyBindingDispatcher.set(13 /* End */, function (t, e) { return _this.onEnd(t, e); }); this.downKeyBindingDispatcher.set(10 /* Space */, function (t, e) { return _this.onSpace(t, e); }); this.downKeyBindingDispatcher.set(9 /* Escape */, function (t, e) { return _this.onEscape(t, e); }); this.upKeyBindingDispatcher.set(3 /* Enter */, this.onEnter.bind(this)); this.upKeyBindingDispatcher.set(2048 /* CtrlCmd */ | 3 /* Enter */, this.onEnter.bind(this)); } } DefaultController.prototype.onMouseDown = function (tree, element, event, origin) { if (origin === void 0) { origin = 'mouse'; } if (this.options.clickBehavior === 0 /* ON_MOUSE_DOWN */ && (event.leftButton || event.middleButton)) { if (event.target) { if (event.target.tagName && event.target.tagName.toLowerCase() === 'input') { return false; // Ignore event if target is a form input field (avoids browser specific issues) } if (dom.findParentWithClass(event.target, 'scrollbar', 'monaco-tree')) { return false; } if (dom.findParentWithClass(event.target, 'monaco-action-bar', 'row')) { // TODO@Joao not very nice way of checking for the action bar (implicit knowledge) return false; // Ignore event if target is over an action bar of the row } } // Propagate to onLeftClick now return this.onLeftClick(tree, element, event, origin); } return false; }; DefaultController.prototype.onClick = function (tree, element, event) { var isMac = platform.isMacintosh; // A Ctrl click on the Mac is a context menu event if (isMac && event.ctrlKey) { event.preventDefault(); event.stopPropagation(); return false; } if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') { return false; // Ignore event if target is a form input field (avoids browser specific issues) } if (this.options.clickBehavior === 0 /* ON_MOUSE_DOWN */ && (event.leftButton || event.middleButton)) { return false; // Already handled by onMouseDown } return this.onLeftClick(tree, element, event); }; DefaultController.prototype.onLeftClick = function (tree, element, eventish, origin) { if (origin === void 0) { origin = 'mouse'; } var event = eventish; var payload = { origin: origin, originalEvent: eventish, didClickOnTwistie: this.isClickOnTwistie(event) }; if (tree.getInput() === element) { tree.clearFocus(payload); tree.clearSelection(payload); } else { var isSingleMouseDown = eventish && event.browserEvent && event.browserEvent.type === 'mousedown' && event.browserEvent.detail === 1; if (!isSingleMouseDown) { eventish.preventDefault(); // we cannot preventDefault onMouseDown with single click because this would break DND otherwise } eventish.stopPropagation(); tree.domFocus(); tree.setSelection([element], payload); tree.setFocus(element, payload); if (this.shouldToggleExpansion(element, event, origin)) { if (tree.isExpanded(element)) { tree.collapse(element).then(undefined, errors.onUnexpectedError); } else { tree.expand(element).then(undefined, errors.onUnexpectedError); } } } return true; }; DefaultController.prototype.shouldToggleExpansion = function (element, event, origin) { var isDoubleClick = (origin === 'mouse' && event.detail === 2); return this.openOnSingleClick || isDoubleClick || this.isClickOnTwistie(event); }; Object.defineProperty(DefaultController.prototype, "openOnSingleClick", { get: function () { return this.options.openMode === 0 /* SINGLE_CLICK */; }, enumerable: true, configurable: true }); DefaultController.prototype.isClickOnTwistie = function (event) { var element = event.target; if (!dom.hasClass(element, 'content')) { return false; } var twistieStyle = window.getComputedStyle(element, ':before'); if (twistieStyle.backgroundImage === 'none' || twistieStyle.display === 'none') { return false; } var twistieWidth = parseInt(twistieStyle.width) + parseInt(twistieStyle.paddingRight); return event.browserEvent.offsetX <= twistieWidth; }; DefaultController.prototype.onContextMenu = function (tree, element, event) { if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') { return false; // allow context menu on input fields } // Prevent native context menu from showing up if (event) { event.preventDefault(); event.stopPropagation(); } return false; }; DefaultController.prototype.onTap = function (tree, element, event) { var target = event.initialTarget; if (target && target.tagName && target.tagName.toLowerCase() === 'input') { return false; // Ignore event if target is a form input field (avoids browser specific issues) } return this.onLeftClick(tree, element, event, 'touch'); }; DefaultController.prototype.onKeyDown = function (tree, event) { return this.onKey(this.downKeyBindingDispatcher, tree, event); }; DefaultController.prototype.onKeyUp = function (tree, event) { return this.onKey(this.upKeyBindingDispatcher, tree, event); }; DefaultController.prototype.onKey = function (bindings, tree, event) { var handler = bindings.dispatch(event.toKeybinding()); if (handler) { // TODO: TS 3.1 upgrade. Why are we checking against void? if (handler(tree, event)) { event.preventDefault(); event.stopPropagation(); return true; } } return false; }; DefaultController.prototype.onUp = function (tree, event) { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { tree.focusPrevious(1, payload); tree.reveal(tree.getFocus()).then(undefined, errors.onUnexpectedError); } return true; }; DefaultController.prototype.onPageUp = function (tree, event) { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { tree.focusPreviousPage(payload); tree.reveal(tree.getFocus()).then(undefined, errors.onUnexpectedError); } return true; }; DefaultController.prototype.onDown = function (tree, event) { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { tree.focusNext(1, payload); tree.reveal(tree.getFocus()).then(undefined, errors.onUnexpectedError); } return true; }; DefaultController.prototype.onPageDown = function (tree, event) { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { tree.focusNextPage(payload); tree.reveal(tree.getFocus()).then(undefined, errors.onUnexpectedError); } return true; }; DefaultController.prototype.onHome = function (tree, event) { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { tree.focusFirst(payload); tree.reveal(tree.getFocus()).then(undefined, errors.onUnexpectedError); } return true; }; DefaultController.prototype.onEnd = function (tree, event) { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { tree.focusLast(payload); tree.reveal(tree.getFocus()).then(undefined, errors.onUnexpectedError); } return true; }; DefaultController.prototype.onLeft = function (tree, event) { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { var focus_1 = tree.getFocus(); tree.collapse(focus_1).then(function (didCollapse) { if (focus_1 && !didCollapse) { tree.focusParent(payload); return tree.reveal(tree.getFocus()); } return undefined; }).then(undefined, errors.onUnexpectedError); } return true; }; DefaultController.prototype.onRight = function (tree, event) { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { var focus_2 = tree.getFocus(); tree.expand(focus_2).then(function (didExpand) { if (focus_2 && !didExpand) { tree.focusFirstChild(payload); return tree.reveal(tree.getFocus()); } return undefined; }).then(undefined, errors.onUnexpectedError); } return true; }; DefaultController.prototype.onEnter = function (tree, event) { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { return false; } var focus = tree.getFocus(); if (focus) { tree.setSelection([focus], payload); } return true; }; DefaultController.prototype.onSpace = function (tree, event) { if (tree.getHighlight()) { return false; } var focus = tree.getFocus(); if (focus) { tree.toggleExpansion(focus); } return true; }; DefaultController.prototype.onEscape = function (tree, event) { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); return true; } if (tree.getSelection().length) { tree.clearSelection(payload); return true; } if (tree.getFocus()) { tree.clearFocus(payload); return true; } return false; }; return DefaultController; }()); exports.DefaultController = DefaultController; var DefaultDragAndDrop = /** @class */ (function () { function DefaultDragAndDrop() { } DefaultDragAndDrop.prototype.getDragURI = function (tree, element) { return null; }; DefaultDragAndDrop.prototype.onDragStart = function (tree, data, originalEvent) { return; }; DefaultDragAndDrop.prototype.onDragOver = function (tree, data, targetElement, originalEvent) { return null; }; DefaultDragAndDrop.prototype.drop = function (tree, data, targetElement, originalEvent) { return; }; return DefaultDragAndDrop; }()); exports.DefaultDragAndDrop = DefaultDragAndDrop; var DefaultFilter = /** @class */ (function () { function DefaultFilter() { } DefaultFilter.prototype.isVisible = function (tree, element) { return true; }; return DefaultFilter; }()); exports.DefaultFilter = DefaultFilter; var DefaultAccessibilityProvider = /** @class */ (function () { function DefaultAccessibilityProvider() { } DefaultAccessibilityProvider.prototype.getAriaLabel = function (tree, element) { return null; }; return DefaultAccessibilityProvider; }()); exports.DefaultAccessibilityProvider = DefaultAccessibilityProvider; var DefaultTreestyler = /** @class */ (function () { function DefaultTreestyler(styleElement, selectorSuffix) { this.styleElement = styleElement; this.selectorSuffix = selectorSuffix; } DefaultTreestyler.prototype.style = function (styles) { var suffix = this.selectorSuffix ? "." + this.selectorSuffix : ''; var content = []; if (styles.listFocusBackground) { content.push(".monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.focused:not(.highlighted) { background-color: " + styles.listFocusBackground + "; }"); } if (styles.listFocusForeground) { content.push(".monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.focused:not(.highlighted) { color: " + styles.listFocusForeground + "; }"); } if (styles.listActiveSelectionBackground) { content.push(".monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { background-color: " + styles.listActiveSelectionBackground + "; }"); } if (styles.listActiveSelectionForeground) { content.push(".monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { color: " + styles.listActiveSelectionForeground + "; }"); } if (styles.listFocusAndSelectionBackground) { content.push("\n\t\t\t\t.monaco-tree-drag-image,\n\t\t\t\t.monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.focused.selected:not(.highlighted) { background-color: " + styles.listFocusAndSelectionBackground + "; }\n\t\t\t"); } if (styles.listFocusAndSelectionForeground) { content.push("\n\t\t\t\t.monaco-tree-drag-image,\n\t\t\t\t.monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.focused.selected:not(.highlighted) { color: " + styles.listFocusAndSelectionForeground + "; }\n\t\t\t"); } if (styles.listInactiveSelectionBackground) { content.push(".monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { background-color: " + styles.listInactiveSelectionBackground + "; }"); } if (styles.listInactiveSelectionForeground) { content.push(".monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { color: " + styles.listInactiveSelectionForeground + "; }"); } if (styles.listHoverBackground) { content.push(".monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row:hover:not(.highlighted):not(.selected):not(.focused) { background-color: " + styles.listHoverBackground + "; }"); } if (styles.listHoverForeground) { content.push(".monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row:hover:not(.highlighted):not(.selected):not(.focused) { color: " + styles.listHoverForeground + "; }"); } if (styles.listDropBackground) { content.push("\n\t\t\t\t.monaco-tree" + suffix + " .monaco-tree-wrapper.drop-target,\n\t\t\t\t.monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row.drop-target { background-color: " + styles.listDropBackground + " !important; color: inherit !important; }\n\t\t\t"); } if (styles.listFocusOutline) { content.push("\n\t\t\t\t.monaco-tree-drag-image\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{ border: 1px solid " + styles.listFocusOutline + "; background: #000; }\n\t\t\t\t.monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row \t\t\t\t\t\t\t\t\t\t\t\t\t\t{ border: 1px solid transparent; }\n\t\t\t\t.monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.focused:not(.highlighted) \t\t\t\t\t\t{ border: 1px dotted " + styles.listFocusOutline + "; }\n\t\t\t\t.monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) \t\t\t\t\t\t{ border: 1px solid " + styles.listFocusOutline + "; }\n\t\t\t\t.monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) \t\t\t\t\t\t\t{ border: 1px solid " + styles.listFocusOutline + "; }\n\t\t\t\t.monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row:hover:not(.highlighted):not(.selected):not(.focused) \t{ border: 1px dashed " + styles.listFocusOutline + "; }\n\t\t\t\t.monaco-tree" + suffix + " .monaco-tree-wrapper.drop-target,\n\t\t\t\t.monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row.drop-target\t\t\t\t\t\t\t\t\t\t\t\t{ border: 1px dashed " + styles.listFocusOutline + "; }\n\t\t\t"); } var newStyles = content.join('\n'); if (newStyles !== this.styleElement.innerHTML) { this.styleElement.innerHTML = newStyles; } }; return DefaultTreestyler; }()); exports.DefaultTreestyler = DefaultTreestyler; }); define(__m[255/*vs/base/parts/tree/browser/treeDnd*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ElementsDragAndDropData = /** @class */ (function () { function ElementsDragAndDropData(elements) { this.elements = elements; } ElementsDragAndDropData.prototype.update = function (dataTransfer) { // no-op }; ElementsDragAndDropData.prototype.getData = function () { return this.elements; }; return ElementsDragAndDropData; }()); exports.ElementsDragAndDropData = ElementsDragAndDropData; var ExternalElementsDragAndDropData = /** @class */ (function () { function ExternalElementsDragAndDropData(elements) { this.elements = elements; } ExternalElementsDragAndDropData.prototype.update = function (dataTransfer) { // no-op }; ExternalElementsDragAndDropData.prototype.getData = function () { return this.elements; }; return ExternalElementsDragAndDropData; }()); exports.ExternalElementsDragAndDropData = ExternalElementsDragAndDropData; var DesktopDragAndDropData = /** @class */ (function () { function DesktopDragAndDropData() { this.types = []; this.files = []; } DesktopDragAndDropData.prototype.update = function (dataTransfer) { if (dataTransfer.types) { this.types = []; Array.prototype.push.apply(this.types, dataTransfer.types); } if (dataTransfer.files) { this.files = []; Array.prototype.push.apply(this.files, dataTransfer.files); this.files = this.files.filter(function (f) { return f.size || f.type; }); } }; DesktopDragAndDropData.prototype.getData = function () { return { types: this.types, files: this.files }; }; return DesktopDragAndDropData; }()); exports.DesktopDragAndDropData = DesktopDragAndDropData; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[256/*vs/base/parts/tree/browser/treeModel*/], __M([0/*require*/,1/*exports*/,124/*vs/base/common/assert*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,4/*vs/base/common/event*/]), function (require, exports, Assert, errors_1, lifecycle_1, event_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LockData = /** @class */ (function () { function LockData(item) { this._onDispose = new event_1.Emitter(); this.onDispose = this._onDispose.event; this._item = item; } Object.defineProperty(LockData.prototype, "item", { get: function () { return this._item; }, enumerable: true, configurable: true }); LockData.prototype.dispose = function () { if (this._onDispose) { this._onDispose.fire(); this._onDispose.dispose(); this._onDispose = undefined; } }; return LockData; }()); exports.LockData = LockData; var Lock = /** @class */ (function () { function Lock() { this.locks = Object.create({}); } Lock.prototype.isLocked = function (item) { return !!this.locks[item.id]; }; Lock.prototype.run = function (item, fn) { var _this = this; var lock = this.getLock(item); if (lock) { return new Promise(function (c, e) { event_1.Event.once(lock.onDispose)(function () { return _this.run(item, fn).then(c, e); }); }); } var result; return new Promise(function (c, e) { if (item.isDisposed()) { return e(new Error('Item is disposed.')); } var lock = _this.locks[item.id] = new LockData(item); result = fn().then(function (r) { delete _this.locks[item.id]; lock.dispose(); return r; }).then(c, e); return result; }); }; Lock.prototype.getLock = function (item) { var key; for (key in this.locks) { var lock = this.locks[key]; if (item.intersects(lock.item)) { return lock; } } return null; }; return Lock; }()); exports.Lock = Lock; var ItemRegistry = /** @class */ (function () { function ItemRegistry() { this._isDisposed = false; this._onDidRevealItem = new event_1.EventMultiplexer(); this.onDidRevealItem = this._onDidRevealItem.event; this._onExpandItem = new event_1.EventMultiplexer(); this.onExpandItem = this._onExpandItem.event; this._onDidExpandItem = new event_1.EventMultiplexer(); this.onDidExpandItem = this._onDidExpandItem.event; this._onCollapseItem = new event_1.EventMultiplexer(); this.onCollapseItem = this._onCollapseItem.event; this._onDidCollapseItem = new event_1.EventMultiplexer(); this.onDidCollapseItem = this._onDidCollapseItem.event; this._onDidAddTraitItem = new event_1.EventMultiplexer(); this.onDidAddTraitItem = this._onDidAddTraitItem.event; this._onDidRemoveTraitItem = new event_1.EventMultiplexer(); this.onDidRemoveTraitItem = this._onDidRemoveTraitItem.event; this._onDidRefreshItem = new event_1.EventMultiplexer(); this.onDidRefreshItem = this._onDidRefreshItem.event; this._onRefreshItemChildren = new event_1.EventMultiplexer(); this.onRefreshItemChildren = this._onRefreshItemChildren.event; this._onDidRefreshItemChildren = new event_1.EventMultiplexer(); this.onDidRefreshItemChildren = this._onDidRefreshItemChildren.event; this._onDidDisposeItem = new event_1.EventMultiplexer(); this.onDidDisposeItem = this._onDidDisposeItem.event; this.items = {}; } ItemRegistry.prototype.register = function (item) { Assert.ok(!this.isRegistered(item.id), 'item already registered: ' + item.id); var disposable = lifecycle_1.combinedDisposable(this._onDidRevealItem.add(item.onDidReveal), this._onExpandItem.add(item.onExpand), this._onDidExpandItem.add(item.onDidExpand), this._onCollapseItem.add(item.onCollapse), this._onDidCollapseItem.add(item.onDidCollapse), this._onDidAddTraitItem.add(item.onDidAddTrait), this._onDidRemoveTraitItem.add(item.onDidRemoveTrait), this._onDidRefreshItem.add(item.onDidRefresh), this._onRefreshItemChildren.add(item.onRefreshChildren), this._onDidRefreshItemChildren.add(item.onDidRefreshChildren), this._onDidDisposeItem.add(item.onDidDispose)); this.items[item.id] = { item: item, disposable: disposable }; }; ItemRegistry.prototype.deregister = function (item) { Assert.ok(this.isRegistered(item.id), 'item not registered: ' + item.id); this.items[item.id].disposable.dispose(); delete this.items[item.id]; }; ItemRegistry.prototype.isRegistered = function (id) { return this.items.hasOwnProperty(id); }; ItemRegistry.prototype.getItem = function (id) { var result = this.items[id]; return result ? result.item : null; }; ItemRegistry.prototype.dispose = function () { this.items = {}; this._onDidRevealItem.dispose(); this._onExpandItem.dispose(); this._onDidExpandItem.dispose(); this._onCollapseItem.dispose(); this._onDidCollapseItem.dispose(); this._onDidAddTraitItem.dispose(); this._onDidRemoveTraitItem.dispose(); this._onDidRefreshItem.dispose(); this._onRefreshItemChildren.dispose(); this._onDidRefreshItemChildren.dispose(); this._isDisposed = true; }; ItemRegistry.prototype.isDisposed = function () { return this._isDisposed; }; return ItemRegistry; }()); exports.ItemRegistry = ItemRegistry; var Item = /** @class */ (function () { function Item(id, registry, context, lock, element) { this._onDidCreate = new event_1.Emitter(); this._onDidReveal = new event_1.Emitter(); this.onDidReveal = this._onDidReveal.event; this._onExpand = new event_1.Emitter(); this.onExpand = this._onExpand.event; this._onDidExpand = new event_1.Emitter(); this.onDidExpand = this._onDidExpand.event; this._onCollapse = new event_1.Emitter(); this.onCollapse = this._onCollapse.event; this._onDidCollapse = new event_1.Emitter(); this.onDidCollapse = this._onDidCollapse.event; this._onDidAddTrait = new event_1.Emitter(); this.onDidAddTrait = this._onDidAddTrait.event; this._onDidRemoveTrait = new event_1.Emitter(); this.onDidRemoveTrait = this._onDidRemoveTrait.event; this._onDidRefresh = new event_1.Emitter(); this.onDidRefresh = this._onDidRefresh.event; this._onRefreshChildren = new event_1.Emitter(); this.onRefreshChildren = this._onRefreshChildren.event; this._onDidRefreshChildren = new event_1.Emitter(); this.onDidRefreshChildren = this._onDidRefreshChildren.event; this._onDidDispose = new event_1.Emitter(); this.onDidDispose = this._onDidDispose.event; this.registry = registry; this.context = context; this.lock = lock; this.element = element; this.id = id; this.registry.register(this); this.doesHaveChildren = this.context.dataSource.hasChildren(this.context.tree, this.element); this.needsChildrenRefresh = true; this.parent = null; this.previous = null; this.next = null; this.firstChild = null; this.lastChild = null; this.traits = {}; this.depth = 0; this.expanded = !!(this.context.dataSource.shouldAutoexpand && this.context.dataSource.shouldAutoexpand(this.context.tree, element)); this._onDidCreate.fire(this); this.visible = this._isVisible(); this.height = this._getHeight(); this._isDisposed = false; } Item.prototype.getElement = function () { return this.element; }; Item.prototype.hasChildren = function () { return this.doesHaveChildren; }; Item.prototype.getDepth = function () { return this.depth; }; Item.prototype.isVisible = function () { return this.visible; }; Item.prototype.setVisible = function (value) { this.visible = value; }; Item.prototype.isExpanded = function () { return this.expanded; }; /* protected */ Item.prototype._setExpanded = function (value) { this.expanded = value; }; Item.prototype.reveal = function (relativeTop) { if (relativeTop === void 0) { relativeTop = null; } var eventData = { item: this, relativeTop: relativeTop }; this._onDidReveal.fire(eventData); }; Item.prototype.expand = function () { var _this = this; if (this.isExpanded() || !this.doesHaveChildren || this.lock.isLocked(this)) { return Promise.resolve(false); } var result = this.lock.run(this, function () { if (_this.isExpanded() || !_this.doesHaveChildren) { return Promise.resolve(false); } var eventData = { item: _this }; var result; _this._onExpand.fire(eventData); if (_this.needsChildrenRefresh) { result = _this.refreshChildren(false, true, true); } else { result = Promise.resolve(null); } return result.then(function () { _this._setExpanded(true); _this._onDidExpand.fire(eventData); return true; }); }); return result.then(function (r) { if (_this.isDisposed()) { return false; } // Auto expand single child folders if (_this.context.options.autoExpandSingleChildren && r && _this.firstChild !== null && _this.firstChild === _this.lastChild && _this.firstChild.isVisible()) { return _this.firstChild.expand().then(function () { return true; }); } return r; }); }; Item.prototype.collapse = function (recursive) { var _this = this; if (recursive === void 0) { recursive = false; } if (recursive) { var collapseChildrenPromise_1 = Promise.resolve(null); this.forEachChild(function (child) { collapseChildrenPromise_1 = collapseChildrenPromise_1.then(function () { return child.collapse(true); }); }); return collapseChildrenPromise_1.then(function () { return _this.collapse(false); }); } else { if (!this.isExpanded() || this.lock.isLocked(this)) { return Promise.resolve(false); } return this.lock.run(this, function () { var eventData = { item: _this }; _this._onCollapse.fire(eventData); _this._setExpanded(false); _this._onDidCollapse.fire(eventData); return Promise.resolve(true); }); } }; Item.prototype.addTrait = function (trait) { var eventData = { item: this, trait: trait }; this.traits[trait] = true; this._onDidAddTrait.fire(eventData); }; Item.prototype.removeTrait = function (trait) { var eventData = { item: this, trait: trait }; delete this.traits[trait]; this._onDidRemoveTrait.fire(eventData); }; Item.prototype.hasTrait = function (trait) { return this.traits[trait] || false; }; Item.prototype.getAllTraits = function () { var result = []; var trait; for (trait in this.traits) { if (this.traits.hasOwnProperty(trait) && this.traits[trait]) { result.push(trait); } } return result; }; Item.prototype.getHeight = function () { return this.height; }; Item.prototype.refreshChildren = function (recursive, safe, force) { var _this = this; if (safe === void 0) { safe = false; } if (force === void 0) { force = false; } if (!force && !this.isExpanded()) { var setNeedsChildrenRefresh_1 = function (item) { item.needsChildrenRefresh = true; item.forEachChild(setNeedsChildrenRefresh_1); }; setNeedsChildrenRefresh_1(this); return Promise.resolve(this); } this.needsChildrenRefresh = false; var doRefresh = function () { var eventData = { item: _this, isNested: safe }; _this._onRefreshChildren.fire(eventData); var childrenPromise; if (_this.doesHaveChildren) { childrenPromise = _this.context.dataSource.getChildren(_this.context.tree, _this.element); } else { childrenPromise = Promise.resolve([]); } var result = childrenPromise.then(function (elements) { if (_this.isDisposed() || _this.registry.isDisposed()) { return Promise.resolve(null); } if (!Array.isArray(elements)) { return Promise.reject(new Error('Please return an array of children.')); } elements = !elements ? [] : elements.slice(0); elements = _this.sort(elements); var staleItems = {}; while (_this.firstChild !== null) { staleItems[_this.firstChild.id] = _this.firstChild; _this.removeChild(_this.firstChild); } for (var i = 0, len = elements.length; i < len; i++) { var element = elements[i]; var id = _this.context.dataSource.getId(_this.context.tree, element); var item = staleItems[id] || new Item(id, _this.registry, _this.context, _this.lock, element); item.element = element; if (recursive) { item.needsChildrenRefresh = recursive; } delete staleItems[id]; _this.addChild(item); } for (var staleItemId in staleItems) { if (staleItems.hasOwnProperty(staleItemId)) { staleItems[staleItemId].dispose(); } } if (recursive) { return Promise.all(_this.mapEachChild(function (child) { return child.doRefresh(recursive, true); })); } else { return Promise.all(_this.mapEachChild(function (child) { if (child.isExpanded() && child.needsChildrenRefresh) { return child.doRefresh(recursive, true); } else { child.updateVisibility(); return Promise.resolve(null); } })); } }); return result .then(undefined, errors_1.onUnexpectedError) .then(function () { return _this._onDidRefreshChildren.fire(eventData); }); }; return safe ? doRefresh() : this.lock.run(this, doRefresh); }; Item.prototype.doRefresh = function (recursive, safe) { if (safe === void 0) { safe = false; } this.doesHaveChildren = this.context.dataSource.hasChildren(this.context.tree, this.element); this.height = this._getHeight(); this.updateVisibility(); this._onDidRefresh.fire(this); return this.refreshChildren(recursive, safe); }; Item.prototype.updateVisibility = function () { this.setVisible(this._isVisible()); }; Item.prototype.refresh = function (recursive) { return this.doRefresh(recursive); }; Item.prototype.getNavigator = function () { return new TreeNavigator(this); }; Item.prototype.intersects = function (other) { return this.isAncestorOf(other) || other.isAncestorOf(this); }; Item.prototype.isAncestorOf = function (startItem) { var item = startItem; while (item) { if (item.id === this.id) { return true; } item = item.parent; } return false; }; Item.prototype.addChild = function (item, afterItem) { if (afterItem === void 0) { afterItem = this.lastChild; } var isEmpty = this.firstChild === null; var atHead = afterItem === null; var atTail = afterItem === this.lastChild; if (isEmpty) { this.firstChild = this.lastChild = item; item.next = item.previous = null; } else if (atHead) { if (!this.firstChild) { throw new Error('Invalid tree state'); } this.firstChild.previous = item; item.next = this.firstChild; item.previous = null; this.firstChild = item; } else if (atTail) { if (!this.lastChild) { throw new Error('Invalid tree state'); } this.lastChild.next = item; item.next = null; item.previous = this.lastChild; this.lastChild = item; } else { item.previous = afterItem; if (!afterItem) { throw new Error('Invalid tree state'); } item.next = afterItem.next; if (!afterItem.next) { throw new Error('Invalid tree state'); } afterItem.next.previous = item; afterItem.next = item; } item.parent = this; item.depth = this.depth + 1; }; Item.prototype.removeChild = function (item) { var isFirstChild = this.firstChild === item; var isLastChild = this.lastChild === item; if (isFirstChild && isLastChild) { this.firstChild = this.lastChild = null; } else if (isFirstChild) { if (!item.next) { throw new Error('Invalid tree state'); } item.next.previous = null; this.firstChild = item.next; } else if (isLastChild) { if (!item.previous) { throw new Error('Invalid tree state'); } item.previous.next = null; this.lastChild = item.previous; } else { if (!item.next) { throw new Error('Invalid tree state'); } item.next.previous = item.previous; if (!item.previous) { throw new Error('Invalid tree state'); } item.previous.next = item.next; } item.parent = null; item.depth = NaN; }; Item.prototype.forEachChild = function (fn) { var child = this.firstChild; var next; while (child) { next = child.next; fn(child); child = next; } }; Item.prototype.mapEachChild = function (fn) { var result = []; this.forEachChild(function (child) { result.push(fn(child)); }); return result; }; Item.prototype.sort = function (elements) { var _this = this; var sorter = this.context.sorter; if (sorter) { return elements.sort(function (element, otherElement) { return sorter.compare(_this.context.tree, element, otherElement); }); } return elements; }; /* protected */ Item.prototype._getHeight = function () { if (!this.context.renderer) { return 0; } return this.context.renderer.getHeight(this.context.tree, this.element); }; /* protected */ Item.prototype._isVisible = function () { if (!this.context.filter) { return false; } return this.context.filter.isVisible(this.context.tree, this.element); }; Item.prototype.isDisposed = function () { return this._isDisposed; }; Item.prototype.dispose = function () { this.forEachChild(function (child) { return child.dispose(); }); this.parent = null; this.previous = null; this.next = null; this.firstChild = null; this.lastChild = null; this._onDidDispose.fire(this); this.registry.deregister(this); this._onDidCreate.dispose(); this._onDidReveal.dispose(); this._onExpand.dispose(); this._onDidExpand.dispose(); this._onCollapse.dispose(); this._onDidCollapse.dispose(); this._onDidAddTrait.dispose(); this._onDidRemoveTrait.dispose(); this._onDidRefresh.dispose(); this._onRefreshChildren.dispose(); this._onDidRefreshChildren.dispose(); this._onDidDispose.dispose(); this._isDisposed = true; }; return Item; }()); exports.Item = Item; var RootItem = /** @class */ (function (_super) { __extends(RootItem, _super); function RootItem(id, registry, context, lock, element) { return _super.call(this, id, registry, context, lock, element) || this; } RootItem.prototype.isVisible = function () { return false; }; RootItem.prototype.setVisible = function (value) { // no-op }; RootItem.prototype.isExpanded = function () { return true; }; /* protected */ RootItem.prototype._setExpanded = function (value) { // no-op }; /* protected */ RootItem.prototype._getHeight = function () { return 0; }; /* protected */ RootItem.prototype._isVisible = function () { return false; }; return RootItem; }(Item)); var TreeNavigator = /** @class */ (function () { function TreeNavigator(item, subTreeOnly) { if (subTreeOnly === void 0) { subTreeOnly = true; } this.item = item; this.start = subTreeOnly ? item : null; } TreeNavigator.lastDescendantOf = function (item) { if (!item) { return null; } if (item instanceof RootItem) { return TreeNavigator.lastDescendantOf(item.lastChild); } if (!item.isVisible()) { return TreeNavigator.lastDescendantOf(item.previous); } if (!item.isExpanded() || item.lastChild === null) { return item; } return TreeNavigator.lastDescendantOf(item.lastChild); }; TreeNavigator.prototype.current = function () { return this.item || null; }; TreeNavigator.prototype.next = function () { if (this.item) { do { if ((this.item instanceof RootItem || (this.item.isVisible() && this.item.isExpanded())) && this.item.firstChild) { this.item = this.item.firstChild; } else if (this.item === this.start) { this.item = null; } else { // select next brother, next uncle, next great-uncle, etc... while (this.item && this.item !== this.start && !this.item.next) { this.item = this.item.parent; } if (this.item === this.start) { this.item = null; } this.item = !this.item ? null : this.item.next; } } while (this.item && !this.item.isVisible()); } return this.item || null; }; TreeNavigator.prototype.previous = function () { if (this.item) { do { var previous = TreeNavigator.lastDescendantOf(this.item.previous); if (previous) { this.item = previous; } else if (this.item.parent && this.item.parent !== this.start && this.item.parent.isVisible()) { this.item = this.item.parent; } else { this.item = null; } } while (this.item && !this.item.isVisible()); } return this.item || null; }; TreeNavigator.prototype.parent = function () { if (this.item) { var parent_1 = this.item.parent; if (parent_1 && parent_1 !== this.start && parent_1.isVisible()) { this.item = parent_1; } else { this.item = null; } } return this.item || null; }; TreeNavigator.prototype.first = function () { this.item = this.start; this.next(); return this.item || null; }; TreeNavigator.prototype.last = function () { return TreeNavigator.lastDescendantOf(this.start); }; return TreeNavigator; }()); exports.TreeNavigator = TreeNavigator; var TreeModel = /** @class */ (function () { function TreeModel(context) { this.registry = new ItemRegistry(); this.registryDisposable = lifecycle_1.Disposable.None; this._onSetInput = new event_1.Emitter(); this.onSetInput = this._onSetInput.event; this._onDidSetInput = new event_1.Emitter(); this.onDidSetInput = this._onDidSetInput.event; this._onRefresh = new event_1.Emitter(); this.onRefresh = this._onRefresh.event; this._onDidRefresh = new event_1.Emitter(); this.onDidRefresh = this._onDidRefresh.event; this._onDidHighlight = new event_1.Emitter(); this.onDidHighlight = this._onDidHighlight.event; this._onDidSelect = new event_1.Emitter(); this.onDidSelect = this._onDidSelect.event; this._onDidFocus = new event_1.Emitter(); this.onDidFocus = this._onDidFocus.event; this._onDidRevealItem = new event_1.Relay(); this.onDidRevealItem = this._onDidRevealItem.event; this._onExpandItem = new event_1.Relay(); this.onExpandItem = this._onExpandItem.event; this._onDidExpandItem = new event_1.Relay(); this.onDidExpandItem = this._onDidExpandItem.event; this._onCollapseItem = new event_1.Relay(); this.onCollapseItem = this._onCollapseItem.event; this._onDidCollapseItem = new event_1.Relay(); this.onDidCollapseItem = this._onDidCollapseItem.event; this._onDidAddTraitItem = new event_1.Relay(); this.onDidAddTraitItem = this._onDidAddTraitItem.event; this._onDidRemoveTraitItem = new event_1.Relay(); this.onDidRemoveTraitItem = this._onDidRemoveTraitItem.event; this._onDidRefreshItem = new event_1.Relay(); this.onDidRefreshItem = this._onDidRefreshItem.event; this._onRefreshItemChildren = new event_1.Relay(); this.onRefreshItemChildren = this._onRefreshItemChildren.event; this._onDidRefreshItemChildren = new event_1.Relay(); this.onDidRefreshItemChildren = this._onDidRefreshItemChildren.event; this._onDidDisposeItem = new event_1.Relay(); this.context = context; this.input = null; this.traitsToItems = {}; } TreeModel.prototype.setInput = function (element) { var _this = this; var eventData = { item: this.input }; this._onSetInput.fire(eventData); this.setSelection([]); this.setFocus(); this.setHighlight(); this.lock = new Lock(); if (this.input) { this.input.dispose(); } if (this.registry) { this.registry.dispose(); this.registryDisposable.dispose(); } this.registry = new ItemRegistry(); this._onDidRevealItem.input = this.registry.onDidRevealItem; this._onExpandItem.input = this.registry.onExpandItem; this._onDidExpandItem.input = this.registry.onDidExpandItem; this._onCollapseItem.input = this.registry.onCollapseItem; this._onDidCollapseItem.input = this.registry.onDidCollapseItem; this._onDidAddTraitItem.input = this.registry.onDidAddTraitItem; this._onDidRemoveTraitItem.input = this.registry.onDidRemoveTraitItem; this._onDidRefreshItem.input = this.registry.onDidRefreshItem; this._onRefreshItemChildren.input = this.registry.onRefreshItemChildren; this._onDidRefreshItemChildren.input = this.registry.onDidRefreshItemChildren; this._onDidDisposeItem.input = this.registry.onDidDisposeItem; this.registryDisposable = this.registry .onDidDisposeItem(function (item) { return item.getAllTraits().forEach(function (trait) { return delete _this.traitsToItems[trait][item.id]; }); }); var id = this.context.dataSource.getId(this.context.tree, element); this.input = new RootItem(id, this.registry, this.context, this.lock, element); eventData = { item: this.input }; this._onDidSetInput.fire(eventData); return this.refresh(this.input); }; TreeModel.prototype.getInput = function () { return this.input ? this.input.getElement() : null; }; TreeModel.prototype.refresh = function (element, recursive) { var _this = this; if (element === void 0) { element = null; } if (recursive === void 0) { recursive = true; } var item = this.getItem(element); if (!item) { return Promise.resolve(null); } var eventData = { item: item, recursive: recursive }; this._onRefresh.fire(eventData); return item.refresh(recursive).then(function () { _this._onDidRefresh.fire(eventData); }); }; TreeModel.prototype.expand = function (element) { var item = this.getItem(element); if (!item) { return Promise.resolve(false); } return item.expand(); }; TreeModel.prototype.collapse = function (element, recursive) { if (recursive === void 0) { recursive = false; } var item = this.getItem(element); if (!item) { return Promise.resolve(false); } return item.collapse(recursive); }; TreeModel.prototype.toggleExpansion = function (element, recursive) { if (recursive === void 0) { recursive = false; } return this.isExpanded(element) ? this.collapse(element, recursive) : this.expand(element); }; TreeModel.prototype.isExpanded = function (element) { var item = this.getItem(element); if (!item) { return false; } return item.isExpanded(); }; TreeModel.prototype.reveal = function (element, relativeTop) { var _this = this; if (relativeTop === void 0) { relativeTop = null; } return this.resolveUnknownParentChain(element).then(function (chain) { var result = Promise.resolve(null); chain.forEach(function (e) { result = result.then(function () { return _this.expand(e); }); }); return result; }).then(function () { var item = _this.getItem(element); if (item) { return item.reveal(relativeTop); } }); }; TreeModel.prototype.resolveUnknownParentChain = function (element) { var _this = this; return this.context.dataSource.getParent(this.context.tree, element).then(function (parent) { if (!parent) { return Promise.resolve([]); } return _this.resolveUnknownParentChain(parent).then(function (result) { result.push(parent); return result; }); }); }; TreeModel.prototype.setHighlight = function (element, eventPayload) { this.setTraits('highlighted', element ? [element] : []); var eventData = { highlight: this.getHighlight(), payload: eventPayload }; this._onDidHighlight.fire(eventData); }; TreeModel.prototype.getHighlight = function (includeHidden) { if (includeHidden === void 0) { includeHidden = false; } var result = this.getElementsWithTrait('highlighted', includeHidden); return result.length === 0 ? null : result[0]; }; TreeModel.prototype.setSelection = function (elements, eventPayload) { this.setTraits('selected', elements); var eventData = { selection: this.getSelection(), payload: eventPayload }; this._onDidSelect.fire(eventData); }; TreeModel.prototype.getSelection = function (includeHidden) { if (includeHidden === void 0) { includeHidden = false; } return this.getElementsWithTrait('selected', includeHidden); }; TreeModel.prototype.setFocus = function (element, eventPayload) { this.setTraits('focused', element ? [element] : []); var eventData = { focus: this.getFocus(), payload: eventPayload }; this._onDidFocus.fire(eventData); }; TreeModel.prototype.getFocus = function (includeHidden) { if (includeHidden === void 0) { includeHidden = false; } var result = this.getElementsWithTrait('focused', includeHidden); return result.length === 0 ? null : result[0]; }; TreeModel.prototype.focusNext = function (count, eventPayload) { if (count === void 0) { count = 1; } var item = this.getFocus() || this.input; var nextItem; var nav = this.getNavigator(item, false); for (var i = 0; i < count; i++) { nextItem = nav.next(); if (!nextItem) { break; } item = nextItem; } this.setFocus(item, eventPayload); }; TreeModel.prototype.focusPrevious = function (count, eventPayload) { if (count === void 0) { count = 1; } var item = this.getFocus() || this.input; var previousItem; var nav = this.getNavigator(item, false); for (var i = 0; i < count; i++) { previousItem = nav.previous(); if (!previousItem) { break; } item = previousItem; } this.setFocus(item, eventPayload); }; TreeModel.prototype.focusParent = function (eventPayload) { var item = this.getFocus() || this.input; var nav = this.getNavigator(item, false); var parent = nav.parent(); if (parent) { this.setFocus(parent, eventPayload); } }; TreeModel.prototype.focusFirstChild = function (eventPayload) { var item = this.getItem(this.getFocus() || this.input); var nav = this.getNavigator(item, false); var next = nav.next(); var parent = nav.parent(); if (parent === item) { this.setFocus(next, eventPayload); } }; TreeModel.prototype.focusFirst = function (eventPayload, from) { this.focusNth(0, eventPayload, from); }; TreeModel.prototype.focusNth = function (index, eventPayload, from) { var navItem = this.getParent(from); var nav = this.getNavigator(navItem); var item = nav.first(); for (var i = 0; i < index; i++) { item = nav.next(); } if (item) { this.setFocus(item, eventPayload); } }; TreeModel.prototype.focusLast = function (eventPayload, from) { var navItem = this.getParent(from); var item; if (from && navItem) { item = navItem.lastChild; } else { var nav = this.getNavigator(navItem); item = nav.last(); } if (item) { this.setFocus(item, eventPayload); } }; TreeModel.prototype.getParent = function (from) { if (from) { var fromItem = this.getItem(from); if (fromItem && fromItem.parent) { return fromItem.parent; } } return this.getItem(this.input); }; TreeModel.prototype.getNavigator = function (element, subTreeOnly) { if (element === void 0) { element = null; } if (subTreeOnly === void 0) { subTreeOnly = true; } return new TreeNavigator(this.getItem(element), subTreeOnly); }; TreeModel.prototype.getItem = function (element) { if (element === void 0) { element = null; } if (element === null) { return this.input; } else if (element instanceof Item) { return element; } else if (typeof element === 'string') { return this.registry.getItem(element); } else { return this.registry.getItem(this.context.dataSource.getId(this.context.tree, element)); } }; TreeModel.prototype.removeTraits = function (trait, elements) { var items = this.traitsToItems[trait] || {}; var item; var id; if (elements.length === 0) { for (id in items) { if (items.hasOwnProperty(id)) { item = items[id]; item.removeTrait(trait); } } delete this.traitsToItems[trait]; } else { for (var i = 0, len = elements.length; i < len; i++) { item = this.getItem(elements[i]); if (item) { item.removeTrait(trait); delete items[item.id]; } } } }; TreeModel.prototype.setTraits = function (trait, elements) { if (elements.length === 0) { this.removeTraits(trait, elements); } else { var items = {}; var item = void 0; for (var i = 0, len = elements.length; i < len; i++) { item = this.getItem(elements[i]); if (item) { items[item.id] = item; } } var traitItems = this.traitsToItems[trait] || {}; var itemsToRemoveTrait = []; var id = void 0; for (id in traitItems) { if (traitItems.hasOwnProperty(id)) { if (items.hasOwnProperty(id)) { delete items[id]; } else { itemsToRemoveTrait.push(traitItems[id]); } } } for (var i = 0, len = itemsToRemoveTrait.length; i < len; i++) { item = itemsToRemoveTrait[i]; item.removeTrait(trait); delete traitItems[item.id]; } for (id in items) { if (items.hasOwnProperty(id)) { item = items[id]; item.addTrait(trait); traitItems[id] = item; } } this.traitsToItems[trait] = traitItems; } }; TreeModel.prototype.getElementsWithTrait = function (trait, includeHidden) { var elements = []; var items = this.traitsToItems[trait] || {}; var id; for (id in items) { if (items.hasOwnProperty(id) && (items[id].isVisible() || includeHidden)) { elements.push(items[id].getElement()); } } return elements; }; TreeModel.prototype.dispose = function () { this.registry.dispose(); this._onSetInput.dispose(); this._onDidSetInput.dispose(); this._onRefresh.dispose(); this._onDidRefresh.dispose(); this._onDidHighlight.dispose(); this._onDidSelect.dispose(); this._onDidFocus.dispose(); this._onDidRevealItem.dispose(); this._onExpandItem.dispose(); this._onDidExpandItem.dispose(); this._onCollapseItem.dispose(); this._onDidCollapseItem.dispose(); this._onDidAddTraitItem.dispose(); this._onDidRemoveTraitItem.dispose(); this._onDidRefreshItem.dispose(); this._onRefreshItemChildren.dispose(); this._onDidRefreshItemChildren.dispose(); this._onDidDisposeItem.dispose(); }; return TreeModel; }()); exports.TreeModel = TreeModel; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[257/*vs/base/parts/tree/browser/treeViewModel*/], __M([0/*require*/,1/*exports*/,54/*vs/base/common/iterator*/]), function (require, exports, iterator_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var HeightMap = /** @class */ (function () { function HeightMap() { this.heightMap = []; this.indexes = {}; } HeightMap.prototype.getContentHeight = function () { var last = this.heightMap[this.heightMap.length - 1]; return !last ? 0 : last.top + last.height; }; HeightMap.prototype.onInsertItems = function (iterator, afterItemId) { if (afterItemId === void 0) { afterItemId = null; } var item = null; var viewItem; var i, j; var totalSize; var sizeDiff = 0; if (afterItemId === null) { i = 0; totalSize = 0; } else { i = this.indexes[afterItemId] + 1; viewItem = this.heightMap[i - 1]; if (!viewItem) { console.error('view item doesnt exist'); return undefined; } totalSize = viewItem.top + viewItem.height; } var boundSplice = this.heightMap.splice.bind(this.heightMap, i, 0); var itemsToInsert = []; while (item = iterator.next()) { viewItem = this.createViewItem(item); viewItem.top = totalSize + sizeDiff; this.indexes[item.id] = i++; itemsToInsert.push(viewItem); sizeDiff += viewItem.height; } boundSplice.apply(this.heightMap, itemsToInsert); for (j = i; j < this.heightMap.length; j++) { viewItem = this.heightMap[j]; viewItem.top += sizeDiff; this.indexes[viewItem.model.id] = j; } for (j = itemsToInsert.length - 1; j >= 0; j--) { this.onInsertItem(itemsToInsert[j]); } for (j = this.heightMap.length - 1; j >= i; j--) { this.onRefreshItem(this.heightMap[j]); } return sizeDiff; }; HeightMap.prototype.onInsertItem = function (item) { // noop }; // Contiguous items HeightMap.prototype.onRemoveItems = function (iterator) { var itemId = null; var viewItem; var startIndex = null; var i = 0; var sizeDiff = 0; while (itemId = iterator.next()) { i = this.indexes[itemId]; viewItem = this.heightMap[i]; if (!viewItem) { console.error('view item doesnt exist'); return; } sizeDiff -= viewItem.height; delete this.indexes[itemId]; this.onRemoveItem(viewItem); if (startIndex === null) { startIndex = i; } } if (sizeDiff === 0 || startIndex === null) { return; } this.heightMap.splice(startIndex, i - startIndex + 1); for (i = startIndex; i < this.heightMap.length; i++) { viewItem = this.heightMap[i]; viewItem.top += sizeDiff; this.indexes[viewItem.model.id] = i; this.onRefreshItem(viewItem); } }; HeightMap.prototype.onRemoveItem = function (item) { // noop }; HeightMap.prototype.onRefreshItemSet = function (items) { var _this = this; var sortedItems = items.sort(function (a, b) { return _this.indexes[a.id] - _this.indexes[b.id]; }); this.onRefreshItems(new iterator_1.ArrayIterator(sortedItems)); }; // Ordered, but not necessarily contiguous items HeightMap.prototype.onRefreshItems = function (iterator) { var item = null; var viewItem; var newHeight; var i, j = null; var cummDiff = 0; while (item = iterator.next()) { i = this.indexes[item.id]; for (; cummDiff !== 0 && j !== null && j < i; j++) { viewItem = this.heightMap[j]; viewItem.top += cummDiff; this.onRefreshItem(viewItem); } viewItem = this.heightMap[i]; newHeight = item.getHeight(); viewItem.top += cummDiff; cummDiff += newHeight - viewItem.height; viewItem.height = newHeight; this.onRefreshItem(viewItem, true); j = i + 1; } if (cummDiff !== 0 && j !== null) { for (; j < this.heightMap.length; j++) { viewItem = this.heightMap[j]; viewItem.top += cummDiff; this.onRefreshItem(viewItem); } } }; HeightMap.prototype.onRefreshItem = function (item, needsRender) { if (needsRender === void 0) { needsRender = false; } // noop }; HeightMap.prototype.indexAt = function (position) { var left = 0; var right = this.heightMap.length; var center; var item; // Binary search while (left < right) { center = Math.floor((left + right) / 2); item = this.heightMap[center]; if (position < item.top) { right = center; } else if (position >= item.top + item.height) { if (left === center) { break; } left = center; } else { return center; } } return this.heightMap.length; }; HeightMap.prototype.indexAfter = function (position) { return Math.min(this.indexAt(position) + 1, this.heightMap.length); }; HeightMap.prototype.itemAtIndex = function (index) { return this.heightMap[index]; }; HeightMap.prototype.itemAfter = function (item) { return this.heightMap[this.indexes[item.model.id] + 1] || null; }; HeightMap.prototype.createViewItem = function (item) { throw new Error('not implemented'); }; HeightMap.prototype.dispose = function () { this.heightMap = []; this.indexes = {}; }; return HeightMap; }()); exports.HeightMap = HeightMap; }); /*--------------------------------------------------------------------------------------------- * 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/base/worker/defaultWorkerFactory*/], __M([0/*require*/,1/*exports*/,16/*vs/base/common/platform*/,182/*vs/base/common/worker/simpleWorker*/]), function (require, exports, platform_1, simpleWorker_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function getWorker(workerId, label) { // Option for hosts to overwrite the worker script (used in the standalone editor) if (platform_1.globals.MonacoEnvironment) { if (typeof platform_1.globals.MonacoEnvironment.getWorker === 'function') { return platform_1.globals.MonacoEnvironment.getWorker(workerId, label); } if (typeof platform_1.globals.MonacoEnvironment.getWorkerUrl === 'function') { return new Worker(platform_1.globals.MonacoEnvironment.getWorkerUrl(workerId, label)); } } // ESM-comment-begin if (typeof require === 'function') { // check if the JS lives on a different origin var workerMain = require.toUrl('./' + workerId); var workerUrl = getWorkerBootstrapUrl(workerMain, label); return new Worker(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)) { var currentUrl = String(window.location); var currentOrigin = currentUrl.substr(0, currentUrl.length - window.location.hash.length - window.location.search.length - window.location.pathname.length); if (scriptPath.substring(0, currentOrigin.length) !== currentOrigin) { // this is the cross-origin case // i.e. the webpage is running at a different origin than where the scripts are loaded from var myPath = 'vs/base/worker/defaultWorkerFactory.js'; var workerBaseUrl = require.toUrl(myPath).slice(0, -myPath.length); var js = "/*" + label + "*/self.MonacoEnvironment={baseUrl: '" + workerBaseUrl + "'};importScripts('" + scriptPath + "');/*" + label + "*/"; var url = "data:text/javascript;charset=utf-8," + encodeURIComponent(js); return url; } } 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. */ var WebWorker = /** @class */ (function () { function WebWorker(moduleId, id, label, onMessageCallback, onErrorCallback) { this.id = id; var workerOrPromise = getWorker('workerMain.js', label); if (isPromiseLike(workerOrPromise)) { this.worker = workerOrPromise; } else { this.worker = Promise.resolve(workerOrPromise); } this.postMessage(moduleId, []); this.worker.then(function (w) { w.onmessage = function (ev) { onMessageCallback(ev.data); }; w.onmessageerror = onErrorCallback; if (typeof w.addEventListener === 'function') { w.addEventListener('error', onErrorCallback); } }); } WebWorker.prototype.getId = function () { return this.id; }; WebWorker.prototype.postMessage = function (message, transfer) { if (this.worker) { this.worker.then(function (w) { return w.postMessage(message, transfer); }); } }; WebWorker.prototype.dispose = function () { if (this.worker) { this.worker.then(function (w) { return w.terminate(); }); } this.worker = null; }; return WebWorker; }()); var DefaultWorkerFactory = /** @class */ (function () { function DefaultWorkerFactory(label) { this._label = label; this._webWorkerFailedBeforeError = false; } DefaultWorkerFactory.prototype.create = function (moduleId, onMessageCallback, onErrorCallback) { var _this = this; var workerId = (++DefaultWorkerFactory.LAST_WORKER_ID); if (this._webWorkerFailedBeforeError) { throw this._webWorkerFailedBeforeError; } return new WebWorker(moduleId, workerId, this._label || 'anonymous' + workerId, onMessageCallback, function (err) { simpleWorker_1.logOnceWebWorkerWarning(err); _this._webWorkerFailedBeforeError = err; onErrorCallback(err); }); }; DefaultWorkerFactory.LAST_WORKER_ID = 0; return DefaultWorkerFactory; }()); exports.DefaultWorkerFactory = DefaultWorkerFactory; }); define(__m[259/*vs/css!vs/base/browser/ui/actionbar/actionbar*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[260/*vs/css!vs/base/browser/ui/aria/aria*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[261/*vs/css!vs/base/browser/ui/checkbox/checkbox*/], __M([9/*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[138/*vs/base/browser/ui/checkbox/checkbox*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,47/*vs/base/browser/ui/widget*/,27/*vs/base/common/color*/,4/*vs/base/common/event*/,31/*vs/base/common/objects*/,261/*vs/css!vs/base/browser/ui/checkbox/checkbox*/]), function (require, exports, DOM, widget_1, color_1, event_1, objects) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var defaultOpts = { inputActiveOptionBorder: color_1.Color.fromHex('#007ACC00'), inputActiveOptionBackground: color_1.Color.fromHex('#0E639C50') }; var Checkbox = /** @class */ (function (_super) { __extends(Checkbox, _super); function Checkbox(opts) { var _this = _super.call(this) || this; _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 = objects.deepClone(opts); objects.mixin(_this._opts, defaultOpts, false); _this._checked = _this._opts.isChecked; _this.domNode = document.createElement('div'); _this.domNode.title = _this._opts.title; _this.domNode.className = 'monaco-custom-checkbox codicon ' + (_this._opts.actionClassName || '') + ' ' + (_this._checked ? 'checked' : 'unchecked'); _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, function (ev) { _this.checked = !_this._checked; _this._onChange.fire(false); ev.preventDefault(); }); _this.ignoreGesture(_this.domNode); _this.onkeydown(_this.domNode, function (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); }); return _this; } Object.defineProperty(Checkbox.prototype, "enabled", { get: function () { return this.domNode.getAttribute('aria-disabled') !== 'true'; }, enumerable: true, configurable: true }); Checkbox.prototype.focus = function () { this.domNode.focus(); }; Object.defineProperty(Checkbox.prototype, "checked", { get: function () { return this._checked; }, set: function (newIsChecked) { this._checked = newIsChecked; this.domNode.setAttribute('aria-checked', String(this._checked)); if (this._checked) { this.domNode.classList.add('checked'); } else { this.domNode.classList.remove('checked'); } this.applyStyles(); }, enumerable: true, configurable: true }); Checkbox.prototype.width = function () { return 2 /*marginleft*/ + 2 /*border*/ + 2 /*padding*/ + 16 /* icon width */; }; Checkbox.prototype.style = function (styles) { if (styles.inputActiveOptionBorder) { this._opts.inputActiveOptionBorder = styles.inputActiveOptionBorder; } if (styles.inputActiveOptionBackground) { this._opts.inputActiveOptionBackground = styles.inputActiveOptionBackground; } this.applyStyles(); }; Checkbox.prototype.applyStyles = function () { if (this.domNode) { this.domNode.style.borderColor = this._checked && this._opts.inputActiveOptionBorder ? this._opts.inputActiveOptionBorder.toString() : 'transparent'; this.domNode.style.backgroundColor = this._checked && this._opts.inputActiveOptionBackground ? this._opts.inputActiveOptionBackground.toString() : 'transparent'; } }; Checkbox.prototype.enable = function () { this.domNode.tabIndex = 0; this.domNode.setAttribute('aria-disabled', String(false)); }; Checkbox.prototype.disable = function () { DOM.removeTabIndexAndUpdateFocus(this.domNode); this.domNode.setAttribute('aria-disabled', String(true)); }; return Checkbox; }(widget_1.Widget)); exports.Checkbox = Checkbox; }); define(__m[262/*vs/css!vs/base/browser/ui/codiconLabel/codicon/codicon*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[263/*vs/css!vs/base/browser/ui/codiconLabel/codicon/codicon-animations*/], __M([9/*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[183/*vs/base/browser/ui/codiconLabel/codiconLabel*/], __M([0/*require*/,1/*exports*/,262/*vs/css!vs/base/browser/ui/codiconLabel/codicon/codicon*/,263/*vs/css!vs/base/browser/ui/codiconLabel/codicon/codicon-animations*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); }); define(__m[264/*vs/css!vs/base/browser/ui/contextview/contextview*/], __M([9/*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[265/*vs/base/browser/ui/contextview/contextview*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,16/*vs/base/common/platform*/,2/*vs/base/common/lifecycle*/,103/*vs/base/common/range*/,88/*vs/base/browser/canIUse*/,264/*vs/css!vs/base/browser/ui/contextview/contextview*/]), function (require, exports, DOM, platform, lifecycle_1, range_1, canIUse_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * 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) { var anchorEnd = anchor.offset + anchor.size; if (anchor.position === 0 /* Before */) { if (viewSize <= viewportSize - anchorEnd) { return anchorEnd; // happy case, lay it out after the anchor } if (viewSize <= anchor.offset) { return anchor.offset - 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 <= anchor.offset) { return anchor.offset - viewSize; // happy case, lay it out before the anchor } if (viewSize <= viewportSize - anchorEnd) { return anchorEnd; // ok case, lay it out after the anchor } return 0; // sad case, lay it over the anchor } } exports.layout = layout; var ContextView = /** @class */ (function (_super) { __extends(ContextView, _super); function ContextView(container) { var _this = _super.call(this) || this; _this.container = null; _this.delegate = null; _this.toDisposeOnClean = lifecycle_1.Disposable.None; _this.toDisposeOnSetContainer = lifecycle_1.Disposable.None; _this.view = DOM.$('.context-view'); DOM.hide(_this.view); _this.setContainer(container); _this._register(lifecycle_1.toDisposable(function () { return _this.setContainer(null); })); return _this; } ContextView.prototype.setContainer = function (container) { var _this = this; if (this.container) { this.toDisposeOnSetContainer.dispose(); this.container.removeChild(this.view); this.container = null; } if (container) { this.container = container; this.container.appendChild(this.view); var toDisposeOnSetContainer_1 = new lifecycle_1.DisposableStore(); ContextView.BUBBLE_UP_EVENTS.forEach(function (event) { toDisposeOnSetContainer_1.add(DOM.addStandardDisposableListener(_this.container, event, function (e) { _this.onDOMEvent(e, false); })); }); ContextView.BUBBLE_DOWN_EVENTS.forEach(function (event) { toDisposeOnSetContainer_1.add(DOM.addStandardDisposableListener(_this.container, event, function (e) { _this.onDOMEvent(e, true); }, true)); }); this.toDisposeOnSetContainer = toDisposeOnSetContainer_1; } }; ContextView.prototype.show = function (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'; 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(); } }; ContextView.prototype.layout = function () { 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(); }; ContextView.prototype.doLayout = function () { // Check that we still have a delegate - this.delegate.layout may have hidden if (!this.isVisible()) { return; } // Get anchor var anchor = this.delegate.getAnchor(); // Compute around var around; // Get the element's position and size (to anchor the view) if (DOM.isHTMLElement(anchor)) { var 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 }; } var viewSizeWidth = DOM.getTotalWidth(this.view); var viewSizeHeight = DOM.getTotalHeight(this.view); var anchorPosition = this.delegate.anchorPosition || 0 /* BELOW */; var anchorAlignment = this.delegate.anchorAlignment || 0 /* LEFT */; var verticalAnchor = { offset: around.top - window.pageYOffset, size: around.height, position: anchorPosition === 0 /* BELOW */ ? 0 /* Before */ : 1 /* After */ }; var horizontalAnchor; if (anchorAlignment === 0 /* LEFT */) { horizontalAnchor = { offset: around.left, size: 0, position: 0 /* Before */ }; } else { horizontalAnchor = { offset: around.left + around.width, size: 0, position: 1 /* After */ }; } var top = layout(window.innerHeight, viewSizeHeight, verticalAnchor) + window.pageYOffset; // if view intersects vertically with anchor, shift it horizontally if (range_1.Range.intersects({ start: top, end: top + viewSizeHeight }, { start: verticalAnchor.offset, end: verticalAnchor.offset + verticalAnchor.size })) { horizontalAnchor.size = around.width; if (anchorAlignment === 1 /* RIGHT */) { horizontalAnchor.offset = around.left; } } var left = layout(window.innerWidth, viewSizeWidth, horizontalAnchor); DOM.removeClasses(this.view, 'top', 'bottom', 'left', 'right'); DOM.addClass(this.view, anchorPosition === 0 /* BELOW */ ? 'bottom' : 'top'); DOM.addClass(this.view, anchorAlignment === 0 /* LEFT */ ? 'left' : 'right'); var containerPosition = DOM.getDomNodePagePosition(this.container); this.view.style.top = top - containerPosition.top + "px"; this.view.style.left = left - containerPosition.left + "px"; this.view.style.width = 'initial'; }; ContextView.prototype.hide = function (data) { var 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); }; ContextView.prototype.isVisible = function () { return !!this.delegate; }; ContextView.prototype.onDOMEvent = function (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(); } } }; ContextView.prototype.dispose = function () { this.hide(); _super.prototype.dispose.call(this); }; ContextView.BUBBLE_UP_EVENTS = ['click', 'keydown', 'focus', 'blur']; ContextView.BUBBLE_DOWN_EVENTS = ['click']; return ContextView; }(lifecycle_1.Disposable)); exports.ContextView = ContextView; }); define(__m[266/*vs/css!vs/base/browser/ui/countBadge/countBadge*/], __M([9/*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[267/*vs/base/browser/ui/countBadge/countBadge*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,5/*vs/base/common/strings*/,27/*vs/base/common/color*/,31/*vs/base/common/objects*/,266/*vs/css!vs/base/browser/ui/countBadge/countBadge*/]), function (require, exports, dom_1, strings_1, color_1, objects_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var defaultOpts = { badgeBackground: color_1.Color.fromHex('#4D4D4D'), badgeForeground: color_1.Color.fromHex('#FFFFFF') }; var CountBadge = /** @class */ (function () { function CountBadge(container, options) { this.count = 0; this.options = options || Object.create(null); objects_1.mixin(this.options, defaultOpts, false); this.badgeBackground = this.options.badgeBackground; this.badgeForeground = this.options.badgeForeground; this.badgeBorder = this.options.badgeBorder; this.element = dom_1.append(container, dom_1.$('.monaco-count-badge')); this.countFormat = this.options.countFormat || '{0}'; this.titleFormat = this.options.titleFormat || ''; this.setCount(this.options.count || 0); } CountBadge.prototype.setCount = function (count) { this.count = count; this.render(); }; CountBadge.prototype.setTitleFormat = function (titleFormat) { this.titleFormat = titleFormat; this.render(); }; CountBadge.prototype.render = function () { this.element.textContent = strings_1.format(this.countFormat, this.count); this.element.title = strings_1.format(this.titleFormat, this.count); this.applyStyles(); }; CountBadge.prototype.style = function (styles) { this.badgeBackground = styles.badgeBackground; this.badgeForeground = styles.badgeForeground; this.badgeBorder = styles.badgeBorder; this.applyStyles(); }; CountBadge.prototype.applyStyles = function () { if (this.element) { var background = this.badgeBackground ? this.badgeBackground.toString() : ''; var foreground = this.badgeForeground ? this.badgeForeground.toString() : ''; var 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; } }; return CountBadge; }()); exports.CountBadge = CountBadge; }); define(__m[184/*vs/css!vs/base/browser/ui/findinput/findInput*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[268/*vs/css!vs/base/browser/ui/iconLabel/iconlabel*/], __M([9/*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[139/*vs/base/browser/ui/iconLabel/iconLabel*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,133/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,2/*vs/base/common/lifecycle*/,103/*vs/base/common/range*/,31/*vs/base/common/objects*/,268/*vs/css!vs/base/browser/ui/iconLabel/iconlabel*/]), function (require, exports, dom, highlightedLabel_1, lifecycle_1, range_1, objects_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var FastLabelNode = /** @class */ (function () { function FastLabelNode(_element) { this._element = _element; } Object.defineProperty(FastLabelNode.prototype, "element", { get: function () { return this._element; }, enumerable: true, configurable: true }); Object.defineProperty(FastLabelNode.prototype, "textContent", { set: function (content) { if (this.disposed || content === this._textContent) { return; } this._textContent = content; this._element.textContent = content; }, enumerable: true, configurable: true }); Object.defineProperty(FastLabelNode.prototype, "className", { set: function (className) { if (this.disposed || className === this._className) { return; } this._className = className; this._element.className = className; }, enumerable: true, configurable: true }); Object.defineProperty(FastLabelNode.prototype, "title", { set: function (title) { if (this.disposed || title === this._title) { return; } this._title = title; if (this._title) { this._element.title = title; } else { this._element.removeAttribute('title'); } }, enumerable: true, configurable: true }); Object.defineProperty(FastLabelNode.prototype, "empty", { set: function (empty) { if (this.disposed || empty === this._empty) { return; } this._empty = empty; this._element.style.marginLeft = empty ? '0' : ''; }, enumerable: true, configurable: true }); FastLabelNode.prototype.dispose = function () { this.disposed = true; }; return FastLabelNode; }()); var IconLabel = /** @class */ (function (_super) { __extends(IconLabel, _super); function IconLabel(container, options) { var _this = _super.call(this) || this; _this.domNode = _this._register(new FastLabelNode(dom.append(container, dom.$('.monaco-icon-label')))); var labelContainer = dom.append(_this.domNode.element, dom.$('.monaco-icon-label-container')); var nameContainer = dom.append(labelContainer, dom.$('span.monaco-icon-name-container')); _this.descriptionContainer = _this._register(new FastLabelNode(dom.append(labelContainer, dom.$('span.monaco-icon-description-container')))); if (options === null || options === void 0 ? void 0 : options.supportHighlights) { _this.nameNode = new LabelWithHighlights(nameContainer, !!options.supportCodicons); } else { _this.nameNode = new Label(nameContainer); } if (options === null || options === void 0 ? void 0 : options.supportDescriptionHighlights) { _this.descriptionNodeFactory = function () { return new highlightedLabel_1.HighlightedLabel(dom.append(_this.descriptionContainer.element, dom.$('span.label-description')), !!options.supportCodicons); }; } else { _this.descriptionNodeFactory = function () { return _this._register(new FastLabelNode(dom.append(_this.descriptionContainer.element, dom.$('span.label-description')))); }; } return _this; } IconLabel.prototype.setLabel = function (label, description, options) { var classes = ['monaco-icon-label']; if (options) { if (options.extraClasses) { classes.push.apply(classes, options.extraClasses); } if (options.italic) { classes.push('italic'); } } this.domNode.className = classes.join(' '); this.domNode.title = (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); if (options === null || options === void 0 ? void 0 : options.descriptionTitle) { this.descriptionNode.element.title = options.descriptionTitle; } else { this.descriptionNode.element.removeAttribute('title'); } } else { this.descriptionNode.textContent = description || ''; this.descriptionNode.title = (options === null || options === void 0 ? void 0 : options.descriptionTitle) || ''; this.descriptionNode.empty = !description; } } }; return IconLabel; }(lifecycle_1.Disposable)); exports.IconLabel = IconLabel; var Label = /** @class */ (function () { function Label(container) { this.container = container; this.label = undefined; this.singleLabel = undefined; } Label.prototype.setLabel = function (label, options) { if (this.label === label && objects_1.equals(this.options, options)) { return; } this.label = label; this.options = options; if (typeof label === 'string') { if (!this.singleLabel) { this.container.innerHTML = ''; dom.removeClass(this.container, '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.innerHTML = ''; dom.addClass(this.container, 'multiple'); this.singleLabel = undefined; for (var i = 0; i < label.length; i++) { var l = label[i]; var 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: id, 'data-icon-label-count': label.length, 'data-icon-label-index': i }, l)); if (i < label.length - 1) { dom.append(this.container, dom.$('span.label-separator', undefined, (options === null || options === void 0 ? void 0 : options.separator) || '/')); } } } }; return Label; }()); function splitMatches(labels, separator, matches) { if (!matches) { return undefined; } var labelStart = 0; return labels.map(function (label) { var labelRange = { start: labelStart, end: labelStart + label.length }; var result = matches .map(function (match) { return range_1.Range.intersect(labelRange, match); }) .filter(function (range) { return !range_1.Range.isEmpty(range); }) .map(function (_a) { var start = _a.start, end = _a.end; return ({ start: start - labelStart, end: end - labelStart }); }); labelStart = labelRange.end + separator.length; return result; }); } var LabelWithHighlights = /** @class */ (function () { function LabelWithHighlights(container, supportCodicons) { this.container = container; this.supportCodicons = supportCodicons; this.label = undefined; this.singleLabel = undefined; } LabelWithHighlights.prototype.setLabel = function (label, options) { if (this.label === label && objects_1.equals(this.options, options)) { return; } this.label = label; this.options = options; if (typeof label === 'string') { if (!this.singleLabel) { this.container.innerHTML = ''; dom.removeClass(this.container, 'multiple'); this.singleLabel = new highlightedLabel_1.HighlightedLabel(dom.append(this.container, dom.$('a.label-name', { id: options === null || options === void 0 ? void 0 : options.domId })), this.supportCodicons); } this.singleLabel.set(label, options === null || options === void 0 ? void 0 : options.matches, options === null || options === void 0 ? void 0 : options.title, options === null || options === void 0 ? void 0 : options.labelEscapeNewLines); } else { this.container.innerHTML = ''; dom.addClass(this.container, 'multiple'); this.singleLabel = undefined; var separator = (options === null || options === void 0 ? void 0 : options.separator) || '/'; var matches = splitMatches(label, separator, options === null || options === void 0 ? void 0 : options.matches); for (var i = 0; i < label.length; i++) { var l = label[i]; var m = matches ? matches[i] : undefined; var id = (options === null || options === void 0 ? void 0 : options.domId) && (options === null || options === void 0 ? void 0 : options.domId) + "_" + i; var name_1 = dom.$('a.label-name', { id: id, 'data-icon-label-count': label.length, 'data-icon-label-index': i }); var highlightedLabel = new highlightedLabel_1.HighlightedLabel(dom.append(this.container, name_1), this.supportCodicons); highlightedLabel.set(l, m, options === null || options === void 0 ? void 0 : options.title, options === null || options === void 0 ? void 0 : options.labelEscapeNewLines); if (i < label.length - 1) { dom.append(name_1, dom.$('span.label-separator', undefined, separator)); } } } }; return LabelWithHighlights; }()); }); define(__m[269/*vs/css!vs/base/browser/ui/inputbox/inputBox*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[270/*vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[271/*vs/css!vs/base/browser/ui/list/list*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[272/*vs/css!vs/base/browser/ui/menu/menu*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[273/*vs/css!vs/base/browser/ui/progressbar/progressbar*/], __M([9/*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[274/*vs/base/browser/ui/progressbar/progressbar*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,27/*vs/base/common/color*/,31/*vs/base/common/objects*/,6/*vs/base/browser/dom*/,15/*vs/base/common/async*/,273/*vs/css!vs/base/browser/ui/progressbar/progressbar*/]), function (require, exports, lifecycle_1, color_1, objects_1, dom_1, async_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var css_done = 'done'; var css_active = 'active'; var css_infinite = 'infinite'; var css_discrete = 'discrete'; var css_progress_container = 'monaco-progress-container'; var css_progress_bit = 'progress-bit'; var defaultOpts = { progressBarBackground: color_1.Color.fromHex('#0E70C0') }; /** * A progress bar with support for infinite or discrete progress. */ var ProgressBar = /** @class */ (function (_super) { __extends(ProgressBar, _super); function ProgressBar(container, options) { var _this = _super.call(this) || this; _this.options = options || Object.create(null); objects_1.mixin(_this.options, defaultOpts, false); _this.workedVal = 0; _this.progressBarBackground = _this.options.progressBarBackground; _this._register(_this.showDelayedScheduler = new async_1.RunOnceScheduler(function () { return dom_1.show(_this.element); }, 0)); _this.create(container); return _this; } ProgressBar.prototype.create = function (container) { this.element = document.createElement('div'); dom_1.addClass(this.element, css_progress_container); container.appendChild(this.element); this.bit = document.createElement('div'); dom_1.addClass(this.bit, css_progress_bit); this.element.appendChild(this.bit); this.applyStyles(); }; ProgressBar.prototype.off = function () { this.bit.style.width = 'inherit'; this.bit.style.opacity = '1'; dom_1.removeClasses(this.element, css_active, css_infinite, css_discrete); this.workedVal = 0; this.totalWork = undefined; }; /** * Stops the progressbar from showing any progress instantly without fading out. */ ProgressBar.prototype.stop = function () { return this.doDone(false); }; ProgressBar.prototype.doDone = function (delayed) { var _this = this; dom_1.addClass(this.element, css_done); // let it grow to 100% width and hide afterwards if (!dom_1.hasClass(this.element, css_infinite)) { this.bit.style.width = 'inherit'; if (delayed) { setTimeout(function () { return _this.off(); }, 200); } else { this.off(); } } // let it fade out and hide afterwards else { this.bit.style.opacity = '0'; if (delayed) { setTimeout(function () { return _this.off(); }, 200); } else { this.off(); } } return this; }; ProgressBar.prototype.hide = function () { dom_1.hide(this.element); this.showDelayedScheduler.cancel(); }; ProgressBar.prototype.style = function (styles) { this.progressBarBackground = styles.progressBarBackground; this.applyStyles(); }; ProgressBar.prototype.applyStyles = function () { if (this.bit) { var background = this.progressBarBackground ? this.progressBarBackground.toString() : ''; this.bit.style.backgroundColor = background; } }; return ProgressBar; }(lifecycle_1.Disposable)); exports.ProgressBar = ProgressBar; }); define(__m[275/*vs/css!vs/base/browser/ui/sash/sash*/], __M([9/*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. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[104/*vs/base/browser/ui/sash/sash*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,24/*vs/base/browser/browser*/,16/*vs/base/common/platform*/,21/*vs/base/common/types*/,57/*vs/base/browser/touch*/,45/*vs/base/browser/mouseEvent*/,4/*vs/base/common/event*/,6/*vs/base/browser/dom*/,52/*vs/base/browser/event*/,275/*vs/css!vs/base/browser/ui/sash/sash*/]), function (require, exports, lifecycle_1, browser_1, platform_1, types, touch_1, mouseEvent_1, event_1, dom_1, event_2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DEBUG = false; var Sash = /** @class */ (function (_super) { __extends(Sash, _super); function Sash(container, layoutProvider, options) { if (options === void 0) { options = {}; } var _this = _super.call(this) || this; _this._state = 3 /* Enabled */; _this._onDidEnablementChange = _this._register(new event_1.Emitter()); _this.onDidEnablementChange = _this._onDidEnablementChange.event; _this._onDidStart = _this._register(new event_1.Emitter()); _this.onDidStart = _this._onDidStart.event; _this._onDidChange = _this._register(new event_1.Emitter()); _this.onDidChange = _this._onDidChange.event; _this._onDidReset = _this._register(new event_1.Emitter()); _this.onDidReset = _this._onDidReset.event; _this._onDidEnd = _this._register(new event_1.Emitter()); _this.onDidEnd = _this._onDidEnd.event; _this.linkedSash = undefined; _this.orthogonalStartSashDisposables = _this._register(new lifecycle_1.DisposableStore()); _this.orthogonalEndSashDisposables = _this._register(new lifecycle_1.DisposableStore()); _this.el = dom_1.append(container, dom_1.$('.monaco-sash')); if (platform_1.isMacintosh) { dom_1.addClass(_this.el, 'mac'); } _this._register(event_2.domEvent(_this.el, 'mousedown')(_this.onMouseDown, _this)); _this._register(event_2.domEvent(_this.el, 'dblclick')(_this.onMouseDoubleClick, _this)); _this._register(touch_1.Gesture.addTarget(_this.el)); _this._register(event_2.domEvent(_this.el, touch_1.EventType.Start)(_this.onTouchStart, _this)); if (browser_1.isIPad) { // see also https://ux.stackexchange.com/questions/39023/what-is-the-optimum-button-size-of-touch-screen-applications dom_1.addClass(_this.el, 'touch'); } _this.setOrientation(options.orientation || 0 /* VERTICAL */); _this.hidden = false; _this.layoutProvider = layoutProvider; _this.orthogonalStartSash = options.orthogonalStartSash; _this.orthogonalEndSash = options.orthogonalEndSash; dom_1.toggleClass(_this.el, 'debug', DEBUG); return _this; } Object.defineProperty(Sash.prototype, "state", { get: function () { return this._state; }, set: function (state) { if (this._state === state) { return; } dom_1.toggleClass(this.el, 'disabled', state === 0 /* Disabled */); dom_1.toggleClass(this.el, 'minimum', state === 1 /* Minimum */); dom_1.toggleClass(this.el, 'maximum', state === 2 /* Maximum */); this._state = state; this._onDidEnablementChange.fire(state); }, enumerable: true, configurable: true }); Object.defineProperty(Sash.prototype, "orthogonalStartSash", { get: function () { return this._orthogonalStartSash; }, set: function (sash) { this.orthogonalStartSashDisposables.clear(); if (sash) { this.orthogonalStartSashDisposables.add(sash.onDidEnablementChange(this.onOrthogonalStartSashEnablementChange, this)); this.onOrthogonalStartSashEnablementChange(sash.state); } else { this.onOrthogonalStartSashEnablementChange(0 /* Disabled */); } this._orthogonalStartSash = sash; }, enumerable: true, configurable: true }); Object.defineProperty(Sash.prototype, "orthogonalEndSash", { get: function () { return this._orthogonalEndSash; }, set: function (sash) { this.orthogonalEndSashDisposables.clear(); if (sash) { this.orthogonalEndSashDisposables.add(sash.onDidEnablementChange(this.onOrthogonalEndSashEnablementChange, this)); this.onOrthogonalEndSashEnablementChange(sash.state); } else { this.onOrthogonalEndSashEnablementChange(0 /* Disabled */); } this._orthogonalEndSash = sash; }, enumerable: true, configurable: true }); Sash.prototype.setOrientation = function (orientation) { this.orientation = orientation; if (this.orientation === 1 /* HORIZONTAL */) { dom_1.addClass(this.el, 'horizontal'); dom_1.removeClass(this.el, 'vertical'); } else { dom_1.removeClass(this.el, 'horizontal'); dom_1.addClass(this.el, 'vertical'); } if (this.layoutProvider) { this.layout(); } }; Sash.prototype.onMouseDown = function (e) { var _this = this; dom_1.EventHelper.stop(e, false); var isMultisashResize = false; if (!e.__orthogonalSashEvent) { var orthogonalSash = this.getOrthogonalSash(e); if (orthogonalSash) { isMultisashResize = true; e.__orthogonalSashEvent = true; orthogonalSash.onMouseDown(e); } } if (this.linkedSash && !e.__linkedSashEvent) { e.__linkedSashEvent = true; this.linkedSash.onMouseDown(e); } if (!this.state) { return; } // Select both iframes and webviews; internally Electron nests an iframe // in its component, but this isn't queryable. var iframes = __spreadArrays(dom_1.getElementsByTagName('iframe'), dom_1.getElementsByTagName('webview')); for (var _i = 0, iframes_1 = iframes; _i < iframes_1.length; _i++) { var iframe = iframes_1[_i]; iframe.style.pointerEvents = 'none'; // disable mouse events on iframes as long as we drag the sash } var mouseDownEvent = new mouseEvent_1.StandardMouseEvent(e); var startX = mouseDownEvent.posx; var startY = mouseDownEvent.posy; var altKey = mouseDownEvent.altKey; var startEvent = { startX: startX, currentX: startX, startY: startY, currentY: startY, altKey: altKey }; dom_1.addClass(this.el, 'active'); this._onDidStart.fire(startEvent); // fix https://github.com/Microsoft/vscode/issues/21675 var style = dom_1.createStyleSheet(this.el); var updateStyle = function () { var cursor = ''; if (isMultisashResize) { cursor = 'all-scroll'; } else if (_this.orientation === 1 /* HORIZONTAL */) { if (_this.state === 1 /* Minimum */) { cursor = 's-resize'; } else if (_this.state === 2 /* Maximum */) { cursor = 'n-resize'; } else { cursor = platform_1.isMacintosh ? 'row-resize' : 'ns-resize'; } } else { if (_this.state === 1 /* Minimum */) { cursor = 'e-resize'; } else if (_this.state === 2 /* Maximum */) { cursor = 'w-resize'; } else { cursor = platform_1.isMacintosh ? 'col-resize' : 'ew-resize'; } } style.innerHTML = "* { cursor: " + cursor + " !important; }"; }; var disposables = new lifecycle_1.DisposableStore(); updateStyle(); if (!isMultisashResize) { this.onDidEnablementChange(updateStyle, null, disposables); } var onMouseMove = function (e) { dom_1.EventHelper.stop(e, false); var mouseMoveEvent = new mouseEvent_1.StandardMouseEvent(e); var event = { startX: startX, currentX: mouseMoveEvent.posx, startY: startY, currentY: mouseMoveEvent.posy, altKey: altKey }; _this._onDidChange.fire(event); }; var onMouseUp = function (e) { dom_1.EventHelper.stop(e, false); _this.el.removeChild(style); dom_1.removeClass(_this.el, 'active'); _this._onDidEnd.fire(); disposables.dispose(); for (var _i = 0, iframes_2 = iframes; _i < iframes_2.length; _i++) { var iframe = iframes_2[_i]; iframe.style.pointerEvents = 'auto'; } }; event_2.domEvent(window, 'mousemove')(onMouseMove, null, disposables); event_2.domEvent(window, 'mouseup')(onMouseUp, null, disposables); }; Sash.prototype.onMouseDoubleClick = function (e) { var orthogonalSash = this.getOrthogonalSash(e); if (orthogonalSash) { orthogonalSash._onDidReset.fire(); } if (this.linkedSash) { this.linkedSash._onDidReset.fire(); } this._onDidReset.fire(); }; Sash.prototype.onTouchStart = function (event) { var _this = this; dom_1.EventHelper.stop(event); var listeners = []; var startX = event.pageX; var startY = event.pageY; var altKey = event.altKey; this._onDidStart.fire({ startX: startX, currentX: startX, startY: startY, currentY: startY, altKey: altKey }); listeners.push(dom_1.addDisposableListener(this.el, touch_1.EventType.Change, function (event) { if (types.isNumber(event.pageX) && types.isNumber(event.pageY)) { _this._onDidChange.fire({ startX: startX, currentX: event.pageX, startY: startY, currentY: event.pageY, altKey: altKey }); } })); listeners.push(dom_1.addDisposableListener(this.el, touch_1.EventType.End, function (event) { _this._onDidEnd.fire(); lifecycle_1.dispose(listeners); })); }; Sash.prototype.layout = function () { var size = browser_1.isIPad ? 20 : 4; if (this.orientation === 0 /* VERTICAL */) { var verticalProvider = this.layoutProvider; this.el.style.left = verticalProvider.getVerticalSashLeft(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 { var horizontalProvider = this.layoutProvider; this.el.style.top = horizontalProvider.getHorizontalSashTop(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'; } } }; Sash.prototype.hide = function () { this.hidden = true; this.el.style.display = 'none'; this.el.setAttribute('aria-hidden', 'true'); }; Sash.prototype.onOrthogonalStartSashEnablementChange = function (state) { dom_1.toggleClass(this.el, 'orthogonal-start', state !== 0 /* Disabled */); }; Sash.prototype.onOrthogonalEndSashEnablementChange = function (state) { dom_1.toggleClass(this.el, 'orthogonal-end', state !== 0 /* Disabled */); }; Sash.prototype.getOrthogonalSash = function (e) { if (this.orientation === 0 /* VERTICAL */) { if (e.offsetY <= 4) { return this.orthogonalStartSash; } else if (e.offsetY >= this.el.clientHeight - 4) { return this.orthogonalEndSash; } } else { if (e.offsetX <= 4) { return this.orthogonalStartSash; } else if (e.offsetX >= this.el.clientWidth - 4) { return this.orthogonalEndSash; } } return undefined; }; Sash.prototype.dispose = function () { _super.prototype.dispose.call(this); this.el.remove(); }; return Sash; }(lifecycle_1.Disposable)); exports.Sash = Sash; }); define(__m[276/*vs/css!vs/base/browser/ui/scrollbar/media/scrollbars*/], __M([9/*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[53/*vs/base/browser/ui/scrollbar/scrollableElement*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,6/*vs/base/browser/dom*/,28/*vs/base/browser/fastDomNode*/,45/*vs/base/browser/mouseEvent*/,250/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/,251/*vs/base/browser/ui/scrollbar/verticalScrollbar*/,47/*vs/base/browser/ui/widget*/,15/*vs/base/common/async*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,176/*vs/base/common/scrollable*/,276/*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 }); var HIDE_TIMEOUT = 500; var SCROLL_WHEEL_SENSITIVITY = 50; var SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED = true; var MouseWheelClassifierItem = /** @class */ (function () { function MouseWheelClassifierItem(timestamp, deltaX, deltaY) { this.timestamp = timestamp; this.deltaX = deltaX; this.deltaY = deltaY; this.score = 0; } return MouseWheelClassifierItem; }()); var MouseWheelClassifier = /** @class */ (function () { function MouseWheelClassifier() { this._capacity = 5; this._memory = []; this._front = -1; this._rear = -1; } MouseWheelClassifier.prototype.isPhysicalMouseWheel = function () { if (this._front === -1 && this._rear === -1) { // no elements return false; } // 0.5 * last + 0.25 * 2nd last + 0.125 * 3rd last + ... var remainingInfluence = 1; var score = 0; var iteration = 1; var index = this._rear; do { var 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); }; MouseWheelClassifier.prototype.accept = function (timestamp, deltaX, deltaY) { var 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. */ MouseWheelClassifier.prototype._computeScore = function (item) { if (Math.abs(item.deltaX) > 0 && Math.abs(item.deltaY) > 0) { // both axes exercised => definitely not a physical mouse wheel return 1; } var score = 0.5; var 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 (Math.abs(item.deltaX - Math.round(item.deltaX)) > 0 || Math.abs(item.deltaY - Math.round(item.deltaY)) > 0) { // non-integer deltas => indicator that this is not a physical mouse wheel score += 0.25; } return Math.min(Math.max(score, 0), 1); }; MouseWheelClassifier.INSTANCE = new MouseWheelClassifier(); return MouseWheelClassifier; }()); exports.MouseWheelClassifier = MouseWheelClassifier; var AbstractScrollableElement = /** @class */ (function (_super) { __extends(AbstractScrollableElement, _super); function AbstractScrollableElement(element, options, scrollable) { var _this = _super.call(this) || this; _this._onScroll = _this._register(new event_1.Emitter()); _this.onScroll = _this._onScroll.event; element.style.overflow = 'hidden'; _this._options = resolveOptions(options); _this._scrollable = scrollable; _this._register(_this._scrollable.onScroll(function (e) { _this._onDidScroll(e); _this._onScroll.fire(e); })); var scrollbarHost = { onMouseWheel: function (mouseWheelEvent) { return _this._onMouseWheel(mouseWheelEvent); }, onDragStart: function () { return _this._onDragStart(); }, onDragEnd: function () { return _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 = fastDomNode_1.createFastDomNode(document.createElement('div')); _this._leftShadowDomNode.setClassName('shadow'); _this._domNode.appendChild(_this._leftShadowDomNode.domNode); _this._topShadowDomNode = fastDomNode_1.createFastDomNode(document.createElement('div')); _this._topShadowDomNode.setClassName('shadow'); _this._domNode.appendChild(_this._topShadowDomNode.domNode); _this._topLeftShadowDomNode = fastDomNode_1.createFastDomNode(document.createElement('div')); _this._topLeftShadowDomNode.setClassName('shadow top-left-corner'); _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, function (e) { return _this._onMouseOver(e); }); _this.onnonbubblingmouseout(_this._listenOnDomNode, function (e) { return _this._onMouseOut(e); }); _this._hideTimeout = _this._register(new async_1.TimeoutTimer()); _this._isDragging = false; _this._mouseIsOver = false; _this._shouldRender = true; _this._revealOnScroll = true; return _this; } AbstractScrollableElement.prototype.dispose = function () { this._mouseWheelToDispose = lifecycle_1.dispose(this._mouseWheelToDispose); _super.prototype.dispose.call(this); }; /** * Get the generated 'scrollable' dom node */ AbstractScrollableElement.prototype.getDomNode = function () { return this._domNode; }; AbstractScrollableElement.prototype.getOverviewRulerLayoutInfo = function () { 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. */ AbstractScrollableElement.prototype.delegateVerticalScrollbarMouseDown = function (browserEvent) { this._verticalScrollbar.delegateMouseDown(browserEvent); }; AbstractScrollableElement.prototype.getScrollDimensions = function () { return this._scrollable.getScrollDimensions(); }; AbstractScrollableElement.prototype.setScrollDimensions = function (dimensions) { this._scrollable.setScrollDimensions(dimensions); }; /** * Update the class name of the scrollable element. */ AbstractScrollableElement.prototype.updateClassName = function (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. * Really this is Editor.IEditorScrollbarOptions, but base shouldn't * depend on Editor. */ AbstractScrollableElement.prototype.updateOptions = function (newOptions) { var massagedOptions = resolveOptions(newOptions); this._options.handleMouseWheel = massagedOptions.handleMouseWheel; this._options.mouseWheelScrollSensitivity = massagedOptions.mouseWheelScrollSensitivity; this._options.fastScrollSensitivity = massagedOptions.fastScrollSensitivity; this._setListeningToMouseWheel(this._options.handleMouseWheel); if (!this._options.lazyRender) { this._render(); } }; // -------------------- mouse wheel scrolling -------------------- AbstractScrollableElement.prototype._setListeningToMouseWheel = function (shouldListen) { var _this = this; var isListening = (this._mouseWheelToDispose.length > 0); if (isListening === shouldListen) { // No change return; } // Stop listening (if necessary) this._mouseWheelToDispose = lifecycle_1.dispose(this._mouseWheelToDispose); // Start listening (if necessary) if (shouldListen) { var onMouseWheel = function (browserEvent) { _this._onMouseWheel(new mouseEvent_1.StandardWheelEvent(browserEvent)); }; this._mouseWheelToDispose.push(dom.addDisposableListener(this._listenOnDomNode, browser_1.isEdgeOrIE ? 'mousewheel' : 'wheel', onMouseWheel, { passive: false })); } }; AbstractScrollableElement.prototype._onMouseWheel = function (e) { var _a; var classifier = MouseWheelClassifier.INSTANCE; if (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED) { classifier.accept(Date.now(), e.deltaX, e.deltaY); } // console.log(`${Date.now()}, ${e.deltaY}, ${e.deltaX}`); if (e.deltaY || e.deltaX) { var deltaY = e.deltaY * this._options.mouseWheelScrollSensitivity; var deltaX = e.deltaX * this._options.mouseWheelScrollSensitivity; if (this._options.flipAxes) { _a = [deltaX, deltaY], deltaY = _a[0], deltaX = _a[1]; } // Convert vertical scrolling to horizontal if shift is held, this // is handled at a higher level on Mac var 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; } var futureScrollPosition = this._scrollable.getFutureScrollPosition(); var desiredScrollPosition = {}; if (deltaY) { var desiredScrollTop = futureScrollPosition.scrollTop - SCROLL_WHEEL_SENSITIVITY * deltaY; this._verticalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollTop); } if (deltaX) { var desiredScrollLeft = futureScrollPosition.scrollLeft - SCROLL_WHEEL_SENSITIVITY * deltaX; this._horizontalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollLeft); } // Check that we are scrolling towards a location which is valid desiredScrollPosition = this._scrollable.validateScrollPosition(desiredScrollPosition); if (futureScrollPosition.scrollLeft !== desiredScrollPosition.scrollLeft || futureScrollPosition.scrollTop !== desiredScrollPosition.scrollTop) { var canPerformSmoothScroll = (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED && this._options.mouseWheelSmoothScroll && classifier.isPhysicalMouseWheel()); if (canPerformSmoothScroll) { this._scrollable.setScrollPositionSmooth(desiredScrollPosition); } else { this._scrollable.setScrollPositionNow(desiredScrollPosition); } this._shouldRender = true; } } if (this._options.alwaysConsumeMouseWheel || this._shouldRender) { e.preventDefault(); e.stopPropagation(); } }; AbstractScrollableElement.prototype._onDidScroll = function (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`. */ AbstractScrollableElement.prototype.renderNow = function () { if (!this._options.lazyRender) { throw new Error('Please use `lazyRender` together with `renderNow`!'); } this._render(); }; AbstractScrollableElement.prototype._render = function () { if (!this._shouldRender) { return; } this._shouldRender = false; this._horizontalScrollbar.render(); this._verticalScrollbar.render(); if (this._options.useShadows) { var scrollState = this._scrollable.getCurrentScrollPosition(); var enableTop = scrollState.scrollTop > 0; var enableLeft = scrollState.scrollLeft > 0; this._leftShadowDomNode.setClassName('shadow' + (enableLeft ? ' left' : '')); this._topShadowDomNode.setClassName('shadow' + (enableTop ? ' top' : '')); this._topLeftShadowDomNode.setClassName('shadow top-left-corner' + (enableTop ? ' top' : '') + (enableLeft ? ' left' : '')); } }; // -------------------- fade in / fade out -------------------- AbstractScrollableElement.prototype._onDragStart = function () { this._isDragging = true; this._reveal(); }; AbstractScrollableElement.prototype._onDragEnd = function () { this._isDragging = false; this._hide(); }; AbstractScrollableElement.prototype._onMouseOut = function (e) { this._mouseIsOver = false; this._hide(); }; AbstractScrollableElement.prototype._onMouseOver = function (e) { this._mouseIsOver = true; this._reveal(); }; AbstractScrollableElement.prototype._reveal = function () { this._verticalScrollbar.beginReveal(); this._horizontalScrollbar.beginReveal(); this._scheduleHide(); }; AbstractScrollableElement.prototype._hide = function () { if (!this._mouseIsOver && !this._isDragging) { this._verticalScrollbar.beginHide(); this._horizontalScrollbar.beginHide(); } }; AbstractScrollableElement.prototype._scheduleHide = function () { var _this = this; if (!this._mouseIsOver && !this._isDragging) { this._hideTimeout.cancelAndSet(function () { return _this._hide(); }, HIDE_TIMEOUT); } }; return AbstractScrollableElement; }(widget_1.Widget)); exports.AbstractScrollableElement = AbstractScrollableElement; var ScrollableElement = /** @class */ (function (_super) { __extends(ScrollableElement, _super); function ScrollableElement(element, options) { var _this = this; options = options || {}; options.mouseWheelSmoothScroll = false; var scrollable = new scrollable_1.Scrollable(0, function (callback) { return dom.scheduleAtNextAnimationFrame(callback); }); _this = _super.call(this, element, options, scrollable) || this; _this._register(scrollable); return _this; } ScrollableElement.prototype.setScrollPosition = function (update) { this._scrollable.setScrollPositionNow(update); }; ScrollableElement.prototype.getScrollPosition = function () { return this._scrollable.getCurrentScrollPosition(); }; return ScrollableElement; }(AbstractScrollableElement)); exports.ScrollableElement = ScrollableElement; var SmoothScrollableElement = /** @class */ (function (_super) { __extends(SmoothScrollableElement, _super); function SmoothScrollableElement(element, options, scrollable) { return _super.call(this, element, options, scrollable) || this; } return SmoothScrollableElement; }(AbstractScrollableElement)); exports.SmoothScrollableElement = SmoothScrollableElement; var DomScrollableElement = /** @class */ (function (_super) { __extends(DomScrollableElement, _super); function DomScrollableElement(element, options) { var _this = _super.call(this, element, options) || this; _this._element = element; _this.onScroll(function (e) { if (e.scrollTopChanged) { _this._element.scrollTop = e.scrollTop; } if (e.scrollLeftChanged) { _this._element.scrollLeft = e.scrollLeft; } }); _this.scanDomNode(); return _this; } DomScrollableElement.prototype.scanDomNode = function () { // 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, }); }; return DomScrollableElement; }(ScrollableElement)); exports.DomScrollableElement = DomScrollableElement; function resolveOptions(opts) { var 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), 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), 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) }; 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. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[140/*vs/base/browser/ui/list/listView*/], __M([0/*require*/,1/*exports*/,31/*vs/base/common/objects*/,2/*vs/base/common/lifecycle*/,57/*vs/base/browser/touch*/,6/*vs/base/browser/dom*/,4/*vs/base/common/event*/,52/*vs/base/browser/event*/,53/*vs/base/browser/ui/scrollbar/scrollableElement*/,246/*vs/base/browser/ui/list/rangeMap*/,249/*vs/base/browser/ui/list/rowCache*/,101/*vs/base/common/decorators*/,103/*vs/base/common/range*/,19/*vs/base/common/arrays*/,98/*vs/base/browser/dnd*/,15/*vs/base/common/async*/,24/*vs/base/browser/browser*/]), function (require, exports, objects_1, lifecycle_1, touch_1, DOM, event_1, event_2, scrollableElement_1, rangeMap_1, rowCache_1, decorators_1, range_1, arrays_1, dnd_1, async_1, browser_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DefaultOptions = { useShadows: true, verticalScrollMode: 1 /* Auto */, setRowLineHeight: true, supportDynamicHeights: false, dnd: { getDragElements: function (e) { return [e]; }, getDragURI: function () { return null; }, onDragStart: function () { }, onDragOver: function () { return false; }, drop: function () { } }, horizontalScrolling: false }; var ElementsDragAndDropData = /** @class */ (function () { function ElementsDragAndDropData(elements) { this.elements = elements; } ElementsDragAndDropData.prototype.update = function () { }; ElementsDragAndDropData.prototype.getData = function () { return this.elements; }; return ElementsDragAndDropData; }()); exports.ElementsDragAndDropData = ElementsDragAndDropData; var ExternalElementsDragAndDropData = /** @class */ (function () { function ExternalElementsDragAndDropData(elements) { this.elements = elements; } ExternalElementsDragAndDropData.prototype.update = function () { }; ExternalElementsDragAndDropData.prototype.getData = function () { return this.elements; }; return ExternalElementsDragAndDropData; }()); exports.ExternalElementsDragAndDropData = ExternalElementsDragAndDropData; var DesktopDragAndDropData = /** @class */ (function () { function DesktopDragAndDropData() { this.types = []; this.files = []; } DesktopDragAndDropData.prototype.update = function (dataTransfer) { var _a; if (dataTransfer.types) { (_a = this.types).splice.apply(_a, __spreadArrays([0, this.types.length], dataTransfer.types)); } if (dataTransfer.files) { this.files.splice(0, this.files.length); for (var i = 0; i < dataTransfer.files.length; i++) { var file = dataTransfer.files.item(i); if (file && (file.size || file.type)) { this.files.push(file); } } } }; DesktopDragAndDropData.prototype.getData = function () { return { types: this.types, files: this.files }; }; return DesktopDragAndDropData; }()); exports.DesktopDragAndDropData = DesktopDragAndDropData; function equalsDragFeedback(f1, f2) { if (Array.isArray(f1) && Array.isArray(f2)) { return arrays_1.equals(f1, f2); } return f1 === f2; } var ListView = /** @class */ (function () { function ListView(container, virtualDelegate, renderers, options) { var _this = this; if (options === void 0) { options = DefaultOptions; } this.virtualDelegate = virtualDelegate; this.domId = "list_id_" + ++ListView.InstanceCount; this.renderers = new Map(); this.renderWidth = 0; this._scrollHeight = 0; this.scrollableElementUpdateDisposable = null; this.scrollableElementWidthDelayer = new async_1.Delayer(50); this.splicing = false; this.dragOverAnimationStopDisposable = lifecycle_1.Disposable.None; this.dragOverMouseY = 0; this.canDrop = false; this.currentDragFeedbackDisposable = lifecycle_1.Disposable.None; this.onDragLeaveTimeout = lifecycle_1.Disposable.None; this.disposables = new lifecycle_1.DisposableStore(); this._onDidChangeContentHeight = new event_1.Emitter(); 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 (var _i = 0, renderers_1 = renderers; _i < renderers_1.length; _i++) { var renderer = renderers_1[_i]; 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'; DOM.addClass(this.domNode, this.domId); this.domNode.tabIndex = 0; DOM.toggleClass(this.domNode, 'mouse-support', typeof options.mouseSupport === 'boolean' ? options.mouseSupport : true); this.horizontalScrolling = objects_1.getOrDefault(options, function (o) { return o.horizontalScrolling; }, DefaultOptions.horizontalScrolling); DOM.toggleClass(this.domNode, 'horizontal-scrolling', this.horizontalScrolling); this.additionalScrollHeight = typeof options.additionalScrollHeight === 'undefined' ? 0 : options.additionalScrollHeight; this.ariaProvider = options.ariaProvider || { getSetSize: function (e, i, length) { return length; }, getPosInSet: function (_, index) { return index + 1; } }; this.rowsContainer = document.createElement('div'); this.rowsContainer.className = 'monaco-list-rows'; this.rowsContainer.style.transform = 'translate3d(0px, 0px, 0px)'; this.disposables.add(touch_1.Gesture.addTarget(this.rowsContainer)); this.scrollableElement = this.disposables.add(new scrollableElement_1.ScrollableElement(this.rowsContainer, { alwaysConsumeMouseWheel: true, horizontal: this.horizontalScrolling ? 1 /* Auto */ : 2 /* Hidden */, vertical: objects_1.getOrDefault(options, function (o) { return o.verticalScrollMode; }, DefaultOptions.verticalScrollMode), useShadows: objects_1.getOrDefault(options, function (o) { return o.useShadows; }, DefaultOptions.useShadows) })); this.domNode.appendChild(this.scrollableElement.getDomNode()); container.appendChild(this.domNode); this.scrollableElement.onScroll(this.onScroll, this, this.disposables); event_2.domEvent(this.rowsContainer, touch_1.EventType.Change)(this.onTouchChange, this, this.disposables); // Prevent the monaco-scrollable-element from scrolling // https://github.com/Microsoft/vscode/issues/44181 event_2.domEvent(this.scrollableElement.getDomNode(), 'scroll')(function (e) { return e.target.scrollTop = 0; }, null, this.disposables); event_1.Event.map(event_2.domEvent(this.domNode, 'dragover'), function (e) { return _this.toDragEvent(e); })(this.onDragOver, this, this.disposables); event_1.Event.map(event_2.domEvent(this.domNode, 'drop'), function (e) { return _this.toDragEvent(e); })(this.onDrop, this, this.disposables); event_2.domEvent(this.domNode, 'dragleave')(this.onDragLeave, this, this.disposables); event_2.domEvent(window, 'dragend')(this.onDragEnd, this, this.disposables); this.setRowLineHeight = objects_1.getOrDefault(options, function (o) { return o.setRowLineHeight; }, DefaultOptions.setRowLineHeight); this.supportDynamicHeights = objects_1.getOrDefault(options, function (o) { return o.supportDynamicHeights; }, DefaultOptions.supportDynamicHeights); this.dnd = objects_1.getOrDefault(options, function (o) { return o.dnd; }, DefaultOptions.dnd); this.layout(); } Object.defineProperty(ListView.prototype, "contentHeight", { get: function () { return this.rangeMap.size; }, enumerable: true, configurable: true }); ListView.prototype.splice = function (start, deleteCount, elements) { if (elements === void 0) { 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); } }; ListView.prototype._splice = function (start, deleteCount, elements) { var _a; var _this = this; if (elements === void 0) { elements = []; } var previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight); var deleteRange = { start: start, end: start + deleteCount }; var removeRange = range_1.Range.intersect(previousRenderRange, deleteRange); for (var i = removeRange.start; i < removeRange.end; i++) { this.removeItemFromDOM(i); } var previousRestRange = { start: start + deleteCount, end: this.items.length }; var previousRenderedRestRange = range_1.Range.intersect(previousRestRange, previousRenderRange); var previousUnrenderedRestRanges = range_1.Range.relativeComplement(previousRestRange, previousRenderRange); var inserted = elements.map(function (element) { return ({ id: String(_this.itemId++), element: 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 }); }); var 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); this.items = inserted; deleted = []; } else { this.rangeMap.splice(start, deleteCount, inserted); deleted = (_a = this.items).splice.apply(_a, __spreadArrays([start, deleteCount], inserted)); } var delta = elements.length - deleteCount; var renderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight); var renderedRestRange = rangeMap_1.shift(previousRenderedRestRange, delta); var updateRange = range_1.Range.intersect(renderRange, renderedRestRange); for (var i = updateRange.start; i < updateRange.end; i++) { this.updateItemInDOM(this.items[i], i); } var removeRanges = range_1.Range.relativeComplement(renderedRestRange, renderRange); for (var _i = 0, removeRanges_1 = removeRanges; _i < removeRanges_1.length; _i++) { var range = removeRanges_1[_i]; for (var i = range.start; i < range.end; i++) { this.removeItemFromDOM(i); } } var unrenderedRestRanges = previousUnrenderedRestRanges.map(function (r) { return rangeMap_1.shift(r, delta); }); var elementsRange = { start: start, end: start + elements.length }; var insertRanges = __spreadArrays([elementsRange], unrenderedRestRanges).map(function (r) { return range_1.Range.intersect(renderRange, r); }); var beforeElement = this.getNextToLastElement(insertRanges); for (var _b = 0, insertRanges_1 = insertRanges; _b < insertRanges_1.length; _b++) { var range = insertRanges_1[_b]; for (var i = range.start; i < range.end; i++) { this.insertItemInDOM(i, beforeElement); } } this.eventuallyUpdateScrollDimensions(); if (this.supportDynamicHeights) { this._rerender(this.scrollTop, this.renderHeight); } return deleted.map(function (i) { return i.element; }); }; ListView.prototype.eventuallyUpdateScrollDimensions = function () { var _this = this; this._scrollHeight = this.contentHeight; this.rowsContainer.style.height = this._scrollHeight + "px"; if (!this.scrollableElementUpdateDisposable) { this.scrollableElementUpdateDisposable = DOM.scheduleAtNextAnimationFrame(function () { _this.scrollableElement.setScrollDimensions({ scrollHeight: _this.scrollHeight }); _this.updateScrollWidth(); _this.scrollableElementUpdateDisposable = null; }); } }; ListView.prototype.eventuallyUpdateScrollWidth = function () { var _this = this; if (!this.horizontalScrolling) { return; } this.scrollableElementWidthDelayer.trigger(function () { return _this.updateScrollWidth(); }); }; ListView.prototype.updateScrollWidth = function () { if (!this.horizontalScrolling) { return; } if (this.items.length === 0) { this.scrollableElement.setScrollDimensions({ scrollWidth: 0 }); } var scrollWidth = 0; for (var _i = 0, _a = this.items; _i < _a.length; _i++) { var item = _a[_i]; if (typeof item.width !== 'undefined') { scrollWidth = Math.max(scrollWidth, item.width); } } this.scrollWidth = scrollWidth; this.scrollableElement.setScrollDimensions({ scrollWidth: scrollWidth + 10 }); }; ListView.prototype.rerender = function () { if (!this.supportDynamicHeights) { return; } for (var _i = 0, _a = this.items; _i < _a.length; _i++) { var item = _a[_i]; item.lastDynamicHeightWidth = undefined; } this._rerender(this.lastRenderTop, this.lastRenderHeight); }; Object.defineProperty(ListView.prototype, "length", { get: function () { return this.items.length; }, enumerable: true, configurable: true }); Object.defineProperty(ListView.prototype, "renderHeight", { get: function () { var scrollDimensions = this.scrollableElement.getScrollDimensions(); return scrollDimensions.height; }, enumerable: true, configurable: true }); ListView.prototype.element = function (index) { return this.items[index].element; }; ListView.prototype.domElement = function (index) { var row = this.items[index].row; return row && row.domNode; }; ListView.prototype.elementHeight = function (index) { return this.items[index].size; }; ListView.prototype.elementTop = function (index) { return this.rangeMap.positionAt(index); }; ListView.prototype.indexAt = function (position) { return this.rangeMap.indexAt(position); }; ListView.prototype.indexAfter = function (position) { return this.rangeMap.indexAfter(position); }; ListView.prototype.layout = function (height, width) { var scrollDimensions = { height: typeof height === 'number' ? height : DOM.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 : DOM.getContentWidth(this.domNode) }); } } }; // Render ListView.prototype.render = function (renderTop, renderHeight, renderLeft, scrollWidth) { var previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight); var renderRange = this.getRenderRange(renderTop, renderHeight); var rangesToInsert = range_1.Range.relativeComplement(renderRange, previousRenderRange); var rangesToRemove = range_1.Range.relativeComplement(previousRenderRange, renderRange); var beforeElement = this.getNextToLastElement(rangesToInsert); for (var _i = 0, rangesToInsert_1 = rangesToInsert; _i < rangesToInsert_1.length; _i++) { var range = rangesToInsert_1[_i]; for (var i = range.start; i < range.end; i++) { this.insertItemInDOM(i, beforeElement); } } for (var _a = 0, rangesToRemove_1 = rangesToRemove; _a < rangesToRemove_1.length; _a++) { var range = rangesToRemove_1[_a]; for (var i = range.start; i < range.end; i++) { this.removeItemFromDOM(i); } } this.rowsContainer.style.left = "-" + renderLeft + "px"; this.rowsContainer.style.top = "-" + renderTop + "px"; if (this.horizontalScrolling) { this.rowsContainer.style.width = Math.max(scrollWidth, this.renderWidth) + "px"; } this.lastRenderTop = renderTop; this.lastRenderHeight = renderHeight; }; // DOM operations ListView.prototype.insertItemInDOM = function (index, beforeElement) { var _this = this; var item = this.items[index]; if (!item.row) { item.row = this.cache.alloc(item.templateId); var role = this.ariaProvider.getRole ? this.ariaProvider.getRole(item.element) : 'treeitem'; item.row.domNode.setAttribute('role', role); var checked = this.ariaProvider.isChecked ? this.ariaProvider.isChecked(item.element) : undefined; 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); var 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); } var uri = this.dnd.getDragURI(item.element); item.dragStartDisposable.dispose(); item.row.domNode.draggable = !!uri; if (uri) { var onDragStart = event_2.domEvent(item.row.domNode, 'dragstart'); item.dragStartDisposable = onDragStart(function (event) { return _this.onDragStart(item.element, uri, event); }); } if (this.horizontalScrolling) { this.measureItemWidth(item); this.eventuallyUpdateScrollWidth(); } }; ListView.prototype.measureItemWidth = function (item) { if (!item.row || !item.row.domNode) { return; } item.row.domNode.style.width = browser_1.isFirefox ? '-moz-fit-content' : 'fit-content'; item.width = DOM.getContentWidth(item.row.domNode); var 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 = ''; }; ListView.prototype.updateItemInDOM = function (item, index) { item.row.domNode.style.top = this.elementTop(index) + "px"; item.row.domNode.style.height = item.size + "px"; if (this.setRowLineHeight) { item.row.domNode.style.lineHeight = item.size + "px"; } item.row.domNode.setAttribute('data-index', "" + index); item.row.domNode.setAttribute('data-last-element', index === this.length - 1 ? 'true' : 'false'); item.row.domNode.setAttribute('aria-setsize', String(this.ariaProvider.getSetSize(item.element, index, this.length))); item.row.domNode.setAttribute('aria-posinset', String(this.ariaProvider.getPosInSet(item.element, index))); item.row.domNode.setAttribute('id', this.getElementDomId(index)); DOM.toggleClass(item.row.domNode, 'drop-target', item.dropTarget); }; ListView.prototype.removeItemFromDOM = function (index) { var item = this.items[index]; item.dragStartDisposable.dispose(); var 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(); } }; ListView.prototype.getScrollTop = function () { var scrollPosition = this.scrollableElement.getScrollPosition(); return scrollPosition.scrollTop; }; ListView.prototype.setScrollTop = function (scrollTop) { if (this.scrollableElementUpdateDisposable) { this.scrollableElementUpdateDisposable.dispose(); this.scrollableElementUpdateDisposable = null; this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight }); } this.scrollableElement.setScrollPosition({ scrollTop: scrollTop }); }; Object.defineProperty(ListView.prototype, "scrollTop", { get: function () { return this.getScrollTop(); }, set: function (scrollTop) { this.setScrollTop(scrollTop); }, enumerable: true, configurable: true }); Object.defineProperty(ListView.prototype, "scrollHeight", { get: function () { return this._scrollHeight + (this.horizontalScrolling ? 10 : 0) + this.additionalScrollHeight; }, enumerable: true, configurable: true }); Object.defineProperty(ListView.prototype, "onMouseClick", { // Events get: function () { var _this = this; return event_1.Event.map(event_2.domEvent(this.domNode, 'click'), function (e) { return _this.toMouseEvent(e); }); }, enumerable: true, configurable: true }); Object.defineProperty(ListView.prototype, "onMouseDblClick", { get: function () { var _this = this; return event_1.Event.map(event_2.domEvent(this.domNode, 'dblclick'), function (e) { return _this.toMouseEvent(e); }); }, enumerable: true, configurable: true }); Object.defineProperty(ListView.prototype, "onMouseMiddleClick", { get: function () { var _this = this; return event_1.Event.filter(event_1.Event.map(event_2.domEvent(this.domNode, 'auxclick'), function (e) { return _this.toMouseEvent(e); }), function (e) { return e.browserEvent.button === 1; }); }, enumerable: true, configurable: true }); Object.defineProperty(ListView.prototype, "onMouseDown", { get: function () { var _this = this; return event_1.Event.map(event_2.domEvent(this.domNode, 'mousedown'), function (e) { return _this.toMouseEvent(e); }); }, enumerable: true, configurable: true }); Object.defineProperty(ListView.prototype, "onContextMenu", { get: function () { var _this = this; return event_1.Event.map(event_2.domEvent(this.domNode, 'contextmenu'), function (e) { return _this.toMouseEvent(e); }); }, enumerable: true, configurable: true }); Object.defineProperty(ListView.prototype, "onTouchStart", { get: function () { var _this = this; return event_1.Event.map(event_2.domEvent(this.domNode, 'touchstart'), function (e) { return _this.toTouchEvent(e); }); }, enumerable: true, configurable: true }); Object.defineProperty(ListView.prototype, "onTap", { get: function () { var _this = this; return event_1.Event.map(event_2.domEvent(this.rowsContainer, touch_1.EventType.Tap), function (e) { return _this.toGestureEvent(e); }); }, enumerable: true, configurable: true }); ListView.prototype.toMouseEvent = function (browserEvent) { var index = this.getItemIndexFromEventTarget(browserEvent.target || null); var item = typeof index === 'undefined' ? undefined : this.items[index]; var element = item && item.element; return { browserEvent: browserEvent, index: index, element: element }; }; ListView.prototype.toTouchEvent = function (browserEvent) { var index = this.getItemIndexFromEventTarget(browserEvent.target || null); var item = typeof index === 'undefined' ? undefined : this.items[index]; var element = item && item.element; return { browserEvent: browserEvent, index: index, element: element }; }; ListView.prototype.toGestureEvent = function (browserEvent) { var index = this.getItemIndexFromEventTarget(browserEvent.initialTarget || null); var item = typeof index === 'undefined' ? undefined : this.items[index]; var element = item && item.element; return { browserEvent: browserEvent, index: index, element: element }; }; ListView.prototype.toDragEvent = function (browserEvent) { var index = this.getItemIndexFromEventTarget(browserEvent.target || null); var item = typeof index === 'undefined' ? undefined : this.items[index]; var element = item && item.element; return { browserEvent: browserEvent, index: index, element: element }; }; ListView.prototype.onScroll = function (e) { try { this.render(e.scrollTop, e.height, e.scrollLeft, e.scrollWidth); if (this.supportDynamicHeights) { this._rerender(e.scrollTop, e.height); } } catch (err) { console.error('Got bad scroll event:', e); throw err; } }; ListView.prototype.onTouchChange = function (event) { event.preventDefault(); event.stopPropagation(); this.scrollTop -= event.translationY; }; // DND ListView.prototype.onDragStart = function (element, uri, event) { if (!event.dataTransfer) { return; } var elements = this.dnd.getDragElements(element); event.dataTransfer.effectAllowed = 'copyMove'; event.dataTransfer.setData(dnd_1.DataTransfers.RESOURCES, JSON.stringify([uri])); if (event.dataTransfer.setDragImage) { var label = void 0; if (this.dnd.getDragLabel) { label = this.dnd.getDragLabel(elements, event); } if (typeof label === 'undefined') { label = String(elements.length); } var dragImage_1 = DOM.$('.monaco-drag-image'); dragImage_1.textContent = label; document.body.appendChild(dragImage_1); event.dataTransfer.setDragImage(dragImage_1, -10, -10); setTimeout(function () { return document.body.removeChild(dragImage_1); }, 0); } this.currentDragData = new ElementsDragAndDropData(elements); dnd_1.StaticDND.CurrentDragAndDropData = new ExternalElementsDragAndDropData(elements); if (this.dnd.onDragStart) { this.dnd.onDragStart(this.currentDragData, event); } }; ListView.prototype.onDragOver = function (event) { var _this = this; 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 DesktopDragAndDropData(); } } var 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'; var 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 = arrays_1.distinct(feedback).filter(function (i) { return i >= -1 && i < _this.length; }).sort(function (a, b) { return 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 DOM.addClass(this.domNode, 'drop-target'); DOM.addClass(this.rowsContainer, 'drop-target'); this.currentDragFeedbackDisposable = lifecycle_1.toDisposable(function () { DOM.removeClass(_this.domNode, 'drop-target'); DOM.removeClass(_this.rowsContainer, 'drop-target'); }); } else { for (var _i = 0, feedback_1 = feedback; _i < feedback_1.length; _i++) { var index = feedback_1[_i]; var item = this.items[index]; item.dropTarget = true; if (item.row && item.row.domNode) { DOM.addClass(item.row.domNode, 'drop-target'); } } this.currentDragFeedbackDisposable = lifecycle_1.toDisposable(function () { for (var _i = 0, feedback_2 = feedback; _i < feedback_2.length; _i++) { var index = feedback_2[_i]; var item = _this.items[index]; item.dropTarget = false; if (item.row && item.row.domNode) { DOM.removeClass(item.row.domNode, 'drop-target'); } } }); } return true; }; ListView.prototype.onDragLeave = function () { var _this = this; this.onDragLeaveTimeout.dispose(); this.onDragLeaveTimeout = async_1.disposableTimeout(function () { return _this.clearDragOverFeedback(); }, 100); }; ListView.prototype.onDrop = function (event) { if (!this.canDrop) { return; } var 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); }; ListView.prototype.onDragEnd = function (event) { this.canDrop = false; this.teardownDragAndDropScrollTopAnimation(); this.clearDragOverFeedback(); this.currentDragData = undefined; dnd_1.StaticDND.CurrentDragAndDropData = undefined; if (this.dnd.onDragEnd) { this.dnd.onDragEnd(event); } }; ListView.prototype.clearDragOverFeedback = function () { this.currentDragFeedback = undefined; this.currentDragFeedbackDisposable.dispose(); this.currentDragFeedbackDisposable = lifecycle_1.Disposable.None; }; // DND scroll top animation ListView.prototype.setupDragAndDropScrollTopAnimation = function (event) { var _this = this; if (!this.dragOverAnimationDisposable) { var viewTop = DOM.getTopLeftOffset(this.domNode).top; this.dragOverAnimationDisposable = DOM.animate(this.animateDragAndDropScrollTop.bind(this, viewTop)); } this.dragOverAnimationStopDisposable.dispose(); this.dragOverAnimationStopDisposable = async_1.disposableTimeout(function () { if (_this.dragOverAnimationDisposable) { _this.dragOverAnimationDisposable.dispose(); _this.dragOverAnimationDisposable = undefined; } }, 1000); this.dragOverMouseY = event.pageY; }; ListView.prototype.animateDragAndDropScrollTop = function (viewTop) { if (this.dragOverMouseY === undefined) { return; } var diff = this.dragOverMouseY - viewTop; var 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))); } }; ListView.prototype.teardownDragAndDropScrollTopAnimation = function () { this.dragOverAnimationStopDisposable.dispose(); if (this.dragOverAnimationDisposable) { this.dragOverAnimationDisposable.dispose(); this.dragOverAnimationDisposable = undefined; } }; // Util ListView.prototype.getItemIndexFromEventTarget = function (target) { var element = target; while (element instanceof HTMLElement && element !== this.rowsContainer) { var rawIndex = element.getAttribute('data-index'); if (rawIndex) { var index = Number(rawIndex); if (!isNaN(index)) { return index; } } element = element.parentElement; } return undefined; }; ListView.prototype.getRenderRange = function (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. */ ListView.prototype._rerender = function (renderTop, renderHeight) { var 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 var anchorElementIndex; var 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; } var heightDiff = 0; while (true) { var renderRange = this.getRenderRange(renderTop, renderHeight); var didChange = false; for (var i = renderRange.start; i < renderRange.end; i++) { var 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(); } var unrenderRanges = range_1.Range.relativeComplement(previousRenderRange, renderRange); for (var _i = 0, unrenderRanges_1 = unrenderRanges; _i < unrenderRanges_1.length; _i++) { var range = unrenderRanges_1[_i]; for (var i = range.start; i < range.end; i++) { if (this.items[i].row) { this.removeItemFromDOM(i); } } } var renderRanges = range_1.Range.relativeComplement(renderRange, previousRenderRange); for (var _a = 0, renderRanges_1 = renderRanges; _a < renderRanges_1.length; _a++) { var range = renderRanges_1[_a]; for (var i = range.start; i < range.end; i++) { var afterIndex = i + 1; var beforeRow = afterIndex < this.items.length ? this.items[afterIndex].row : null; var beforeElement = beforeRow ? beforeRow.domNode : null; this.insertItemInDOM(i, beforeElement); } } for (var i = renderRange.start; i < renderRange.end; i++) { if (this.items[i].row) { this.updateItemInDOM(this.items[i], i); } } if (typeof anchorElementIndex === 'number') { this.scrollTop = this.elementTop(anchorElementIndex) - anchorElementTopDelta; } this._onDidChangeContentHeight.fire(this.contentHeight); return; } } }; ListView.prototype.probeDynamicHeight = function (index) { var item = this.items[index]; if (!item.hasDynamicHeight || item.lastDynamicHeightWidth === this.renderWidth) { return 0; } var size = item.size; var row = this.cache.alloc(item.templateId); row.domNode.style.height = ''; this.rowsContainer.appendChild(row.domNode); var 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; }; ListView.prototype.getNextToLastElement = function (ranges) { var lastRange = ranges[ranges.length - 1]; if (!lastRange) { return null; } var nextToLastItem = this.items[lastRange.end]; if (!nextToLastItem) { return null; } if (!nextToLastItem.row) { return null; } return nextToLastItem.row.domNode; }; ListView.prototype.getElementDomId = function (index) { return this.domId + "_" + index; }; // Dispose ListView.prototype.dispose = function () { if (this.items) { for (var _i = 0, _a = this.items; _i < _a.length; _i++) { var item = _a[_i]; if (item.row) { var renderer = this.renderers.get(item.row.templateId); if (renderer) { renderer.disposeTemplate(item.row.templateData); } } } this.items = []; } if (this.domNode && this.domNode.parentNode) { this.domNode.parentNode.removeChild(this.domNode); } 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); return ListView; }()); 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[277/*vs/base/parts/tree/browser/treeView*/], __M([0/*require*/,1/*exports*/,16/*vs/base/common/platform*/,24/*vs/base/browser/browser*/,2/*vs/base/common/lifecycle*/,6/*vs/base/browser/dom*/,126/*vs/base/common/diff/diff*/,57/*vs/base/browser/touch*/,5/*vs/base/common/strings*/,45/*vs/base/browser/mouseEvent*/,56/*vs/base/browser/keyboardEvent*/,255/*vs/base/parts/tree/browser/treeDnd*/,54/*vs/base/common/iterator*/,53/*vs/base/browser/ui/scrollbar/scrollableElement*/,257/*vs/base/parts/tree/browser/treeViewModel*/,254/*vs/base/parts/tree/browser/tree*/,4/*vs/base/common/event*/,98/*vs/base/browser/dnd*/,137/*vs/base/parts/tree/browser/treeDefaults*/,15/*vs/base/common/async*/]), function (require, exports, Platform, Browser, Lifecycle, DOM, Diff, Touch, strings, Mouse, Keyboard, dnd, iterator_1, scrollableElement_1, treeViewModel_1, _, event_1, dnd_1, treeDefaults_1, async_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function removeFromParent(element) { try { element.parentElement.removeChild(element); } catch (e) { // this will throw if this happens due to a blur event, nasty business } } var RowCache = /** @class */ (function () { function RowCache(context) { this.context = context; this._cache = { '': [] }; } RowCache.prototype.alloc = function (templateId) { var result = this.cache(templateId).pop(); if (!result) { var content = document.createElement('div'); content.className = 'content'; var row = document.createElement('div'); row.appendChild(content); var templateData = null; try { templateData = this.context.renderer.renderTemplate(this.context.tree, templateId, content); } catch (err) { console.error('Tree usage error: exception while rendering template'); console.error(err); } result = { element: row, templateId: templateId, templateData: templateData }; } return result; }; RowCache.prototype.release = function (templateId, row) { removeFromParent(row.element); this.cache(templateId).push(row); }; RowCache.prototype.cache = function (templateId) { return this._cache[templateId] || (this._cache[templateId] = []); }; RowCache.prototype.garbageCollect = function () { var _this = this; if (this._cache) { Object.keys(this._cache).forEach(function (templateId) { _this._cache[templateId].forEach(function (cachedRow) { _this.context.renderer.disposeTemplate(_this.context.tree, templateId, cachedRow.templateData); cachedRow.element = null; cachedRow.templateData = null; }); delete _this._cache[templateId]; }); } }; RowCache.prototype.dispose = function () { this.garbageCollect(); this._cache = null; }; return RowCache; }()); exports.RowCache = RowCache; var ViewItem = /** @class */ (function () { function ViewItem(context, model) { var _this = this; this.width = 0; this.needsRender = false; this.uri = null; this.unbindDragStart = Lifecycle.Disposable.None; this._draggable = false; this.context = context; this.model = model; this.id = this.model.id; this.row = null; this.top = 0; this.height = model.getHeight(); this._styles = {}; model.getAllTraits().forEach(function (t) { return _this._styles[t] = true; }); if (model.isExpanded()) { this.addClass('expanded'); } } Object.defineProperty(ViewItem.prototype, "expanded", { set: function (value) { value ? this.addClass('expanded') : this.removeClass('expanded'); }, enumerable: true, configurable: true }); Object.defineProperty(ViewItem.prototype, "loading", { set: function (value) { value ? this.addClass('codicon-loading') : this.removeClass('codicon-loading'); }, enumerable: true, configurable: true }); Object.defineProperty(ViewItem.prototype, "draggable", { get: function () { return this._draggable; }, set: function (value) { this._draggable = value; this.render(true); }, enumerable: true, configurable: true }); Object.defineProperty(ViewItem.prototype, "dropTarget", { set: function (value) { value ? this.addClass('drop-target') : this.removeClass('drop-target'); }, enumerable: true, configurable: true }); Object.defineProperty(ViewItem.prototype, "element", { get: function () { return (this.row && this.row.element); }, enumerable: true, configurable: true }); Object.defineProperty(ViewItem.prototype, "templateId", { get: function () { return this._templateId || (this._templateId = (this.context.renderer.getTemplateId && this.context.renderer.getTemplateId(this.context.tree, this.model.getElement()))); }, enumerable: true, configurable: true }); ViewItem.prototype.addClass = function (name) { this._styles[name] = true; this.render(true); }; ViewItem.prototype.removeClass = function (name) { delete this._styles[name]; // is this slow? this.render(true); }; ViewItem.prototype.render = function (skipUserRender) { var _this = this; if (skipUserRender === void 0) { skipUserRender = false; } if (!this.model || !this.element) { return; } var classes = ['monaco-tree-row']; classes.push.apply(classes, Object.keys(this._styles)); if (this.model.hasChildren()) { classes.push('has-children'); } this.element.className = classes.join(' '); this.element.draggable = this.draggable; this.element.style.height = this.height + 'px'; // ARIA this.element.setAttribute('role', 'treeitem'); var accessibility = this.context.accessibilityProvider; var ariaLabel = accessibility.getAriaLabel(this.context.tree, this.model.getElement()); if (ariaLabel) { this.element.setAttribute('aria-label', ariaLabel); } if (accessibility.getPosInSet && accessibility.getSetSize) { this.element.setAttribute('aria-setsize', accessibility.getSetSize()); this.element.setAttribute('aria-posinset', accessibility.getPosInSet(this.context.tree, this.model.getElement())); } if (this.model.hasTrait('focused')) { var base64Id = strings.safeBtoa(this.model.id); this.element.setAttribute('aria-selected', 'true'); this.element.setAttribute('id', base64Id); } else { this.element.setAttribute('aria-selected', 'false'); this.element.removeAttribute('id'); } if (this.model.hasChildren()) { this.element.setAttribute('aria-expanded', String(!!this._styles['expanded'])); } else { this.element.removeAttribute('aria-expanded'); } this.element.setAttribute('aria-level', String(this.model.getDepth())); if (this.context.options.paddingOnRow) { this.element.style.paddingLeft = this.context.options.twistiePixels + ((this.model.getDepth() - 1) * this.context.options.indentPixels) + 'px'; } else { this.element.style.paddingLeft = ((this.model.getDepth() - 1) * this.context.options.indentPixels) + 'px'; this.row.element.firstElementChild.style.paddingLeft = this.context.options.twistiePixels + 'px'; } var uri = this.context.dnd.getDragURI(this.context.tree, this.model.getElement()); if (uri !== this.uri) { if (this.unbindDragStart) { this.unbindDragStart.dispose(); } if (uri) { this.uri = uri; this.draggable = true; this.unbindDragStart = DOM.addDisposableListener(this.element, 'dragstart', function (e) { _this.onDragStart(e); }); } else { this.uri = null; } } if (!skipUserRender && this.element) { var paddingLeft = 0; if (this.context.horizontalScrolling) { var style = window.getComputedStyle(this.element); paddingLeft = parseFloat(style.paddingLeft); } if (this.context.horizontalScrolling) { this.element.style.width = Browser.isFirefox ? '-moz-fit-content' : 'fit-content'; } try { this.context.renderer.renderElement(this.context.tree, this.model.getElement(), this.templateId, this.row.templateData); } catch (err) { console.error('Tree usage error: exception while rendering element'); console.error(err); } if (this.context.horizontalScrolling) { this.width = DOM.getContentWidth(this.element) + paddingLeft; this.element.style.width = ''; } } }; ViewItem.prototype.insertInDOM = function (container, afterElement) { if (!this.row) { this.row = this.context.cache.alloc(this.templateId); // used in reverse lookup from HTMLElement to Item this.element[TreeView.BINDING] = this; } if (this.element.parentElement) { return; } if (afterElement === null) { container.appendChild(this.element); } else { try { container.insertBefore(this.element, afterElement); } catch (e) { console.warn('Failed to locate previous tree element'); container.appendChild(this.element); } } this.render(); }; ViewItem.prototype.removeFromDOM = function () { if (!this.row) { return; } this.unbindDragStart.dispose(); this.uri = null; this.element[TreeView.BINDING] = null; this.context.cache.release(this.templateId, this.row); this.row = null; }; ViewItem.prototype.dispose = function () { this.row = null; }; return ViewItem; }()); exports.ViewItem = ViewItem; var RootViewItem = /** @class */ (function (_super) { __extends(RootViewItem, _super); function RootViewItem(context, model, wrapper) { var _this = _super.call(this, context, model) || this; _this.row = { element: wrapper, templateData: null, templateId: null }; return _this; } RootViewItem.prototype.render = function () { if (!this.model || !this.element) { return; } var classes = ['monaco-tree-wrapper']; classes.push.apply(classes, Object.keys(this._styles)); if (this.model.hasChildren()) { classes.push('has-children'); } this.element.className = classes.join(' '); }; RootViewItem.prototype.insertInDOM = function (container, afterElement) { // noop }; RootViewItem.prototype.removeFromDOM = function () { // noop }; return RootViewItem; }(ViewItem)); function reactionEquals(one, other) { if (!one && !other) { return true; } else if (!one || !other) { return false; } else if (one.accept !== other.accept) { return false; } else if (one.bubble !== other.bubble) { return false; } else if (one.effect !== other.effect) { return false; } else { return true; } } var TreeView = /** @class */ (function (_super) { __extends(TreeView, _super); function TreeView(context, container) { var _this = _super.call(this) || this; _this.model = null; _this.lastPointerType = ''; _this.lastClickTimeStamp = 0; _this.contentWidthUpdateDelayer = new async_1.Delayer(50); _this.isRefreshing = false; _this.refreshingPreviousChildrenIds = {}; _this.currentDragAndDropData = null; _this.currentDropTarget = null; _this.currentDropTargets = null; _this.currentDropDisposable = Lifecycle.Disposable.None; _this.gestureDisposable = Lifecycle.Disposable.None; _this.dragAndDropScrollInterval = null; _this.dragAndDropScrollTimeout = null; _this.dragAndDropMouseY = null; _this.highlightedItemWasDraggable = false; _this.onHiddenScrollTop = null; _this._onDOMFocus = new event_1.Emitter(); _this.onDOMFocus = _this._onDOMFocus.event; _this._onDOMBlur = new event_1.Emitter(); _this._onDidScroll = new event_1.Emitter(); TreeView.counter++; _this.instance = TreeView.counter; var horizontalScrollMode = typeof context.options.horizontalScrollMode === 'undefined' ? 2 /* Hidden */ : context.options.horizontalScrollMode; _this.horizontalScrolling = horizontalScrollMode !== 2 /* Hidden */; _this.context = { dataSource: context.dataSource, renderer: context.renderer, controller: context.controller, dnd: context.dnd, filter: context.filter, sorter: context.sorter, tree: context.tree, accessibilityProvider: context.accessibilityProvider, options: context.options, cache: new RowCache(context), horizontalScrolling: _this.horizontalScrolling }; _this.modelListeners = []; _this.viewListeners = []; _this.items = {}; _this.domNode = document.createElement('div'); _this.domNode.className = "monaco-tree no-focused-item monaco-tree-instance-" + _this.instance; // to allow direct tabbing into the tree instead of first focusing the tree _this.domNode.tabIndex = context.options.preventRootFocus ? -1 : 0; _this.styleElement = DOM.createStyleSheet(_this.domNode); _this.treeStyler = context.styler || new treeDefaults_1.DefaultTreestyler(_this.styleElement, "monaco-tree-instance-" + _this.instance); // ARIA _this.domNode.setAttribute('role', 'tree'); if (_this.context.options.ariaLabel) { _this.domNode.setAttribute('aria-label', _this.context.options.ariaLabel); } if (_this.context.options.alwaysFocused) { DOM.addClass(_this.domNode, 'focused'); } if (!_this.context.options.paddingOnRow) { DOM.addClass(_this.domNode, 'no-row-padding'); } _this.wrapper = document.createElement('div'); _this.wrapper.className = 'monaco-tree-wrapper'; _this.scrollableElement = new scrollableElement_1.ScrollableElement(_this.wrapper, { alwaysConsumeMouseWheel: true, horizontal: horizontalScrollMode, vertical: (typeof context.options.verticalScrollMode !== 'undefined' ? context.options.verticalScrollMode : 1 /* Auto */), useShadows: context.options.useShadows }); _this.scrollableElement.onScroll(function (e) { _this.render(e.scrollTop, e.height, e.scrollLeft, e.width, e.scrollWidth); _this._onDidScroll.fire(); }); if (Browser.isIE) { _this.wrapper.style.msTouchAction = 'none'; _this.wrapper.style.msContentZooming = 'none'; } else { _this.gestureDisposable = Touch.Gesture.addTarget(_this.wrapper); } _this.rowsContainer = document.createElement('div'); _this.rowsContainer.className = 'monaco-tree-rows'; if (context.options.showTwistie) { _this.rowsContainer.className += ' show-twisties'; } var focusTracker = DOM.trackFocus(_this.domNode); _this.viewListeners.push(focusTracker.onDidFocus(function () { return _this.onFocus(); })); _this.viewListeners.push(focusTracker.onDidBlur(function () { return _this.onBlur(); })); _this.viewListeners.push(focusTracker); _this.viewListeners.push(DOM.addDisposableListener(_this.domNode, 'keydown', function (e) { return _this.onKeyDown(e); })); _this.viewListeners.push(DOM.addDisposableListener(_this.domNode, 'keyup', function (e) { return _this.onKeyUp(e); })); _this.viewListeners.push(DOM.addDisposableListener(_this.domNode, 'mousedown', function (e) { return _this.onMouseDown(e); })); _this.viewListeners.push(DOM.addDisposableListener(_this.domNode, 'mouseup', function (e) { return _this.onMouseUp(e); })); _this.viewListeners.push(DOM.addDisposableListener(_this.wrapper, 'auxclick', function (e) { if (e && e.button === 1) { _this.onMouseMiddleClick(e); } })); _this.viewListeners.push(DOM.addDisposableListener(_this.wrapper, 'click', function (e) { return _this.onClick(e); })); _this.viewListeners.push(DOM.addDisposableListener(_this.domNode, 'contextmenu', function (e) { return _this.onContextMenu(e); })); _this.viewListeners.push(DOM.addDisposableListener(_this.wrapper, Touch.EventType.Tap, function (e) { return _this.onTap(e); })); _this.viewListeners.push(DOM.addDisposableListener(_this.wrapper, Touch.EventType.Change, function (e) { return _this.onTouchChange(e); })); if (Browser.isIE) { _this.viewListeners.push(DOM.addDisposableListener(_this.wrapper, 'MSPointerDown', function (e) { return _this.onMsPointerDown(e); })); _this.viewListeners.push(DOM.addDisposableListener(_this.wrapper, 'MSGestureTap', function (e) { return _this.onMsGestureTap(e); })); // these events come too fast, we throttle them _this.viewListeners.push(DOM.addDisposableThrottledListener(_this.wrapper, 'MSGestureChange', function (e) { return _this.onThrottledMsGestureChange(e); }, function (lastEvent, event) { event.stopPropagation(); event.preventDefault(); var result = { translationY: event.translationY, translationX: event.translationX }; if (lastEvent) { result.translationY += lastEvent.translationY; result.translationX += lastEvent.translationX; } return result; })); } _this.viewListeners.push(DOM.addDisposableListener(window, 'dragover', function (e) { return _this.onDragOver(e); })); _this.viewListeners.push(DOM.addDisposableListener(_this.wrapper, 'drop', function (e) { return _this.onDrop(e); })); _this.viewListeners.push(DOM.addDisposableListener(window, 'dragend', function (e) { return _this.onDragEnd(e); })); _this.viewListeners.push(DOM.addDisposableListener(window, 'dragleave', function (e) { return _this.onDragOver(e); })); _this.wrapper.appendChild(_this.rowsContainer); _this.domNode.appendChild(_this.scrollableElement.getDomNode()); container.appendChild(_this.domNode); _this.lastRenderTop = 0; _this.lastRenderHeight = 0; _this.didJustPressContextMenuKey = false; _this.currentDropTarget = null; _this.currentDropTargets = []; _this.shouldInvalidateDropReaction = false; _this.dragAndDropScrollInterval = null; _this.dragAndDropScrollTimeout = null; _this.onRowsChanged(); _this.layout(); _this.setupMSGesture(); _this.applyStyles(context.options); return _this; } TreeView.prototype.applyStyles = function (styles) { this.treeStyler.style(styles); }; TreeView.prototype.createViewItem = function (item) { return new ViewItem(this.context, item); }; TreeView.prototype.getHTMLElement = function () { return this.domNode; }; TreeView.prototype.focus = function () { this.domNode.focus(); }; TreeView.prototype.isFocused = function () { return document.activeElement === this.domNode; }; TreeView.prototype.blur = function () { this.domNode.blur(); }; TreeView.prototype.setupMSGesture = function () { var _this = this; if (window.MSGesture) { this.msGesture = new MSGesture(); setTimeout(function () { return _this.msGesture.target = _this.wrapper; }, 100); // TODO@joh, TODO@IETeam } }; TreeView.prototype.isTreeVisible = function () { return this.onHiddenScrollTop === null; }; TreeView.prototype.layout = function (height, width) { if (!this.isTreeVisible()) { return; } this.viewHeight = height || DOM.getContentHeight(this.wrapper); // render this.scrollHeight = this.getContentHeight(); if (this.horizontalScrolling) { this.viewWidth = width || DOM.getContentWidth(this.wrapper); } }; TreeView.prototype.render = function (scrollTop, viewHeight, scrollLeft, viewWidth, scrollWidth) { var i; var stop; var renderTop = scrollTop; var renderBottom = scrollTop + viewHeight; var thisRenderBottom = this.lastRenderTop + this.lastRenderHeight; // when view scrolls down, start rendering from the renderBottom for (i = this.indexAfter(renderBottom) - 1, stop = this.indexAt(Math.max(thisRenderBottom, renderTop)); i >= stop; i--) { this.insertItemInDOM(this.itemAtIndex(i)); } // when view scrolls up, start rendering from either this.renderTop or renderBottom for (i = Math.min(this.indexAt(this.lastRenderTop), this.indexAfter(renderBottom)) - 1, stop = this.indexAt(renderTop); i >= stop; i--) { this.insertItemInDOM(this.itemAtIndex(i)); } // when view scrolls down, start unrendering from renderTop for (i = this.indexAt(this.lastRenderTop), stop = Math.min(this.indexAt(renderTop), this.indexAfter(thisRenderBottom)); i < stop; i++) { this.removeItemFromDOM(this.itemAtIndex(i)); } // when view scrolls up, start unrendering from either renderBottom this.renderTop for (i = Math.max(this.indexAfter(renderBottom), this.indexAt(this.lastRenderTop)), stop = this.indexAfter(thisRenderBottom); i < stop; i++) { this.removeItemFromDOM(this.itemAtIndex(i)); } var topItem = this.itemAtIndex(this.indexAt(renderTop)); if (topItem) { this.rowsContainer.style.top = (topItem.top - renderTop) + 'px'; } if (this.horizontalScrolling) { this.rowsContainer.style.left = -scrollLeft + 'px'; this.rowsContainer.style.width = Math.max(scrollWidth, viewWidth) + "px"; } this.lastRenderTop = renderTop; this.lastRenderHeight = renderBottom - renderTop; }; TreeView.prototype.setModel = function (newModel) { this.releaseModel(); this.model = newModel; this.model.onRefresh(this.onRefreshing, this, this.modelListeners); this.model.onDidRefresh(this.onRefreshed, this, this.modelListeners); this.model.onSetInput(this.onClearingInput, this, this.modelListeners); this.model.onDidSetInput(this.onSetInput, this, this.modelListeners); this.model.onDidFocus(this.onModelFocusChange, this, this.modelListeners); this.model.onRefreshItemChildren(this.onItemChildrenRefreshing, this, this.modelListeners); this.model.onDidRefreshItemChildren(this.onItemChildrenRefreshed, this, this.modelListeners); this.model.onDidRefreshItem(this.onItemRefresh, this, this.modelListeners); this.model.onExpandItem(this.onItemExpanding, this, this.modelListeners); this.model.onDidExpandItem(this.onItemExpanded, this, this.modelListeners); this.model.onCollapseItem(this.onItemCollapsing, this, this.modelListeners); this.model.onDidRevealItem(this.onItemReveal, this, this.modelListeners); this.model.onDidAddTraitItem(this.onItemAddTrait, this, this.modelListeners); this.model.onDidRemoveTraitItem(this.onItemRemoveTrait, this, this.modelListeners); }; TreeView.prototype.onRefreshing = function () { this.isRefreshing = true; }; TreeView.prototype.onRefreshed = function () { this.isRefreshing = false; this.onRowsChanged(); }; TreeView.prototype.onRowsChanged = function (scrollTop) { if (scrollTop === void 0) { scrollTop = this.scrollTop; } if (this.isRefreshing) { return; } this.scrollTop = scrollTop; this.updateScrollWidth(); }; TreeView.prototype.updateScrollWidth = function () { var _this = this; if (!this.horizontalScrolling) { return; } this.contentWidthUpdateDelayer.trigger(function () { var keys = Object.keys(_this.items); var scrollWidth = 0; for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { var key = keys_1[_i]; scrollWidth = Math.max(scrollWidth, _this.items[key].width); } _this.scrollWidth = scrollWidth + 10 /* scrollbar */; }); }; TreeView.prototype.focusNextPage = function (eventPayload) { var _this = this; var lastPageIndex = this.indexAt(this.scrollTop + this.viewHeight); lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1; var lastPageElement = this.itemAtIndex(lastPageIndex).model.getElement(); var currentlyFocusedElement = this.model.getFocus(); if (currentlyFocusedElement !== lastPageElement) { this.model.setFocus(lastPageElement, eventPayload); } else { var previousScrollTop = this.scrollTop; this.scrollTop += this.viewHeight; if (this.scrollTop !== previousScrollTop) { // Let the scroll event listener run setTimeout(function () { _this.focusNextPage(eventPayload); }, 0); } } }; TreeView.prototype.focusPreviousPage = function (eventPayload) { var _this = this; var firstPageIndex; if (this.scrollTop === 0) { firstPageIndex = this.indexAt(this.scrollTop); } else { firstPageIndex = this.indexAfter(this.scrollTop - 1); } var firstPageElement = this.itemAtIndex(firstPageIndex).model.getElement(); var currentlyFocusedElement = this.model.getFocus(); if (currentlyFocusedElement !== firstPageElement) { this.model.setFocus(firstPageElement, eventPayload); } else { var previousScrollTop = this.scrollTop; this.scrollTop -= this.viewHeight; if (this.scrollTop !== previousScrollTop) { // Let the scroll event listener run setTimeout(function () { _this.focusPreviousPage(eventPayload); }, 0); } } }; Object.defineProperty(TreeView.prototype, "viewHeight", { get: function () { var scrollDimensions = this.scrollableElement.getScrollDimensions(); return scrollDimensions.height; }, set: function (height) { this.scrollableElement.setScrollDimensions({ height: height }); }, enumerable: true, configurable: true }); Object.defineProperty(TreeView.prototype, "scrollHeight", { set: function (scrollHeight) { scrollHeight = scrollHeight + (this.horizontalScrolling ? 10 : 0); this.scrollableElement.setScrollDimensions({ scrollHeight: scrollHeight }); }, enumerable: true, configurable: true }); Object.defineProperty(TreeView.prototype, "viewWidth", { get: function () { var scrollDimensions = this.scrollableElement.getScrollDimensions(); return scrollDimensions.width; }, set: function (viewWidth) { this.scrollableElement.setScrollDimensions({ width: viewWidth }); }, enumerable: true, configurable: true }); Object.defineProperty(TreeView.prototype, "scrollWidth", { set: function (scrollWidth) { this.scrollableElement.setScrollDimensions({ scrollWidth: scrollWidth }); }, enumerable: true, configurable: true }); Object.defineProperty(TreeView.prototype, "scrollTop", { get: function () { var scrollPosition = this.scrollableElement.getScrollPosition(); return scrollPosition.scrollTop; }, set: function (scrollTop) { var scrollHeight = this.getContentHeight() + (this.horizontalScrolling ? 10 : 0); this.scrollableElement.setScrollDimensions({ scrollHeight: scrollHeight }); this.scrollableElement.setScrollPosition({ scrollTop: scrollTop }); }, enumerable: true, configurable: true }); // Events TreeView.prototype.onClearingInput = function (e) { var item = e.item; if (item) { this.onRemoveItems(new iterator_1.MappedIterator(item.getNavigator(), function (item) { return item && item.id; })); this.onRowsChanged(); } }; TreeView.prototype.onSetInput = function (e) { this.context.cache.garbageCollect(); this.inputItem = new RootViewItem(this.context, e.item, this.wrapper); }; TreeView.prototype.onItemChildrenRefreshing = function (e) { var item = e.item; var viewItem = this.items[item.id]; if (viewItem && this.context.options.showLoading) { viewItem.loadingTimer = setTimeout(function () { viewItem.loadingTimer = 0; viewItem.loading = true; }, TreeView.LOADING_DECORATION_DELAY); } if (!e.isNested) { var childrenIds = []; var navigator_1 = item.getNavigator(); var childItem = void 0; while (childItem = navigator_1.next()) { childrenIds.push(childItem.id); } this.refreshingPreviousChildrenIds[item.id] = childrenIds; } }; TreeView.prototype.onItemChildrenRefreshed = function (e) { var _this = this; var item = e.item; var viewItem = this.items[item.id]; if (viewItem) { if (viewItem.loadingTimer) { clearTimeout(viewItem.loadingTimer); viewItem.loadingTimer = 0; } viewItem.loading = false; } if (!e.isNested) { var previousChildrenIds_1 = this.refreshingPreviousChildrenIds[item.id]; var afterModelItems_1 = []; var navigator_2 = item.getNavigator(); var childItem = void 0; while (childItem = navigator_2.next()) { afterModelItems_1.push(childItem); } var skipDiff = Math.abs(previousChildrenIds_1.length - afterModelItems_1.length) > 1000; var diff = []; var doToInsertItemsAlreadyExist = false; if (!skipDiff) { var lcs = new Diff.LcsDiff({ getElements: function () { return previousChildrenIds_1; } }, { getElements: function () { return afterModelItems_1.map(function (item) { return item.id; }); } }, null); diff = lcs.ComputeDiff(false).changes; // this means that the result of the diff algorithm would result // in inserting items that were already registered. this can only // happen if the data provider returns bad ids OR if the sorting // of the elements has changed doToInsertItemsAlreadyExist = diff.some(function (d) { if (d.modifiedLength > 0) { for (var i = d.modifiedStart, len = d.modifiedStart + d.modifiedLength; i < len; i++) { if (_this.items.hasOwnProperty(afterModelItems_1[i].id)) { return true; } } } return false; }); } // 50 is an optimization number, at some point we're better off // just replacing everything if (!skipDiff && !doToInsertItemsAlreadyExist && diff.length < 50) { for (var _i = 0, diff_1 = diff; _i < diff_1.length; _i++) { var diffChange = diff_1[_i]; if (diffChange.originalLength > 0) { this.onRemoveItems(new iterator_1.ArrayIterator(previousChildrenIds_1, diffChange.originalStart, diffChange.originalStart + diffChange.originalLength)); } if (diffChange.modifiedLength > 0) { var beforeItem = afterModelItems_1[diffChange.modifiedStart - 1] || item; beforeItem = beforeItem.getDepth() > 0 ? beforeItem : null; this.onInsertItems(new iterator_1.ArrayIterator(afterModelItems_1, diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength), beforeItem ? beforeItem.id : null); } } } else if (skipDiff || diff.length) { this.onRemoveItems(new iterator_1.ArrayIterator(previousChildrenIds_1)); this.onInsertItems(new iterator_1.ArrayIterator(afterModelItems_1), item.getDepth() > 0 ? item.id : null); } if (skipDiff || diff.length) { this.onRowsChanged(); } } }; TreeView.prototype.onItemRefresh = function (item) { this.onItemsRefresh([item]); }; TreeView.prototype.onItemsRefresh = function (items) { var _this = this; this.onRefreshItemSet(items.filter(function (item) { return _this.items.hasOwnProperty(item.id); })); this.onRowsChanged(); }; TreeView.prototype.onItemExpanding = function (e) { var viewItem = this.items[e.item.id]; if (viewItem) { viewItem.expanded = true; } }; TreeView.prototype.onItemExpanded = function (e) { var item = e.item; var viewItem = this.items[item.id]; if (viewItem) { viewItem.expanded = true; var height = this.onInsertItems(item.getNavigator(), item.id) || 0; var scrollTop = this.scrollTop; if (viewItem.top + viewItem.height <= this.scrollTop) { scrollTop += height; } this.onRowsChanged(scrollTop); } }; TreeView.prototype.onItemCollapsing = function (e) { var item = e.item; var viewItem = this.items[item.id]; if (viewItem) { viewItem.expanded = false; this.onRemoveItems(new iterator_1.MappedIterator(item.getNavigator(), function (item) { return item && item.id; })); this.onRowsChanged(); } }; TreeView.prototype.onItemReveal = function (e) { var item = e.item; var relativeTop = e.relativeTop; var viewItem = this.items[item.id]; if (viewItem) { if (relativeTop !== null) { relativeTop = relativeTop < 0 ? 0 : relativeTop; relativeTop = relativeTop > 1 ? 1 : relativeTop; // y = mx + b var m = viewItem.height - this.viewHeight; this.scrollTop = m * relativeTop + viewItem.top; } else { var viewItemBottom = viewItem.top + viewItem.height; var wrapperBottom = this.scrollTop + this.viewHeight; if (viewItem.top < this.scrollTop) { this.scrollTop = viewItem.top; } else if (viewItemBottom >= wrapperBottom) { this.scrollTop = viewItemBottom - this.viewHeight; } } } }; TreeView.prototype.onItemAddTrait = function (e) { var item = e.item; var trait = e.trait; var viewItem = this.items[item.id]; if (viewItem) { viewItem.addClass(trait); } if (trait === 'highlighted') { DOM.addClass(this.domNode, trait); // Ugly Firefox fix: input fields can't be selected if parent nodes are draggable if (viewItem) { this.highlightedItemWasDraggable = !!viewItem.draggable; if (viewItem.draggable) { viewItem.draggable = false; } } } }; TreeView.prototype.onItemRemoveTrait = function (e) { var item = e.item; var trait = e.trait; var viewItem = this.items[item.id]; if (viewItem) { viewItem.removeClass(trait); } if (trait === 'highlighted') { DOM.removeClass(this.domNode, trait); // Ugly Firefox fix: input fields can't be selected if parent nodes are draggable if (this.highlightedItemWasDraggable) { viewItem.draggable = true; } this.highlightedItemWasDraggable = false; } }; TreeView.prototype.onModelFocusChange = function () { var focus = this.model && this.model.getFocus(); DOM.toggleClass(this.domNode, 'no-focused-item', !focus); // ARIA if (focus) { this.domNode.setAttribute('aria-activedescendant', strings.safeBtoa(this.context.dataSource.getId(this.context.tree, focus))); } else { this.domNode.removeAttribute('aria-activedescendant'); } }; // HeightMap "events" TreeView.prototype.onInsertItem = function (item) { var _this = this; item.onDragStart = function (e) { _this.onDragStart(item, e); }; item.needsRender = true; this.refreshViewItem(item); this.items[item.id] = item; }; TreeView.prototype.onRefreshItem = function (item, needsRender) { if (needsRender === void 0) { needsRender = false; } item.needsRender = item.needsRender || needsRender; this.refreshViewItem(item); }; TreeView.prototype.onRemoveItem = function (item) { this.removeItemFromDOM(item); item.dispose(); delete this.items[item.id]; }; // ViewItem refresh TreeView.prototype.refreshViewItem = function (item) { item.render(); if (this.shouldBeRendered(item)) { this.insertItemInDOM(item); } else { this.removeItemFromDOM(item); } }; // DOM Events TreeView.prototype.onClick = function (e) { if (this.lastPointerType && this.lastPointerType !== 'mouse') { return; } var event = new Mouse.StandardMouseEvent(e); var item = this.getItemAround(event.target); if (!item) { return; } if (Browser.isIE && Date.now() - this.lastClickTimeStamp < 300) { // IE10+ doesn't set the detail property correctly. While IE10 simply // counts the number of clicks, IE11 reports always 1. To align with // other browser, we set the value to 2 if clicks events come in a 300ms // sequence. event.detail = 2; } this.lastClickTimeStamp = Date.now(); this.context.controller.onClick(this.context.tree, item.model.getElement(), event); }; TreeView.prototype.onMouseMiddleClick = function (e) { if (!this.context.controller.onMouseMiddleClick) { return; } var event = new Mouse.StandardMouseEvent(e); var item = this.getItemAround(event.target); if (!item) { return; } this.context.controller.onMouseMiddleClick(this.context.tree, item.model.getElement(), event); }; TreeView.prototype.onMouseDown = function (e) { this.didJustPressContextMenuKey = false; if (!this.context.controller.onMouseDown) { return; } if (this.lastPointerType && this.lastPointerType !== 'mouse') { return; } var event = new Mouse.StandardMouseEvent(e); if (event.ctrlKey && Platform.isNative && Platform.isMacintosh) { return; } var item = this.getItemAround(event.target); if (!item) { return; } this.context.controller.onMouseDown(this.context.tree, item.model.getElement(), event); }; TreeView.prototype.onMouseUp = function (e) { if (!this.context.controller.onMouseUp) { return; } if (this.lastPointerType && this.lastPointerType !== 'mouse') { return; } var event = new Mouse.StandardMouseEvent(e); if (event.ctrlKey && Platform.isNative && Platform.isMacintosh) { return; } var item = this.getItemAround(event.target); if (!item) { return; } this.context.controller.onMouseUp(this.context.tree, item.model.getElement(), event); }; TreeView.prototype.onTap = function (e) { var item = this.getItemAround(e.initialTarget); if (!item) { return; } this.context.controller.onTap(this.context.tree, item.model.getElement(), e); }; TreeView.prototype.onTouchChange = function (event) { event.preventDefault(); event.stopPropagation(); this.scrollTop -= event.translationY; }; TreeView.prototype.onContextMenu = function (event) { var resultEvent; var element; if (event instanceof KeyboardEvent || this.didJustPressContextMenuKey) { this.didJustPressContextMenuKey = false; var keyboardEvent = new Keyboard.StandardKeyboardEvent(event); element = this.model.getFocus(); var position = void 0; if (!element) { element = this.model.getInput(); position = DOM.getDomNodePagePosition(this.inputItem.element); } else { var id = this.context.dataSource.getId(this.context.tree, element); var viewItem = this.items[id]; position = DOM.getDomNodePagePosition(viewItem.element); } resultEvent = new _.KeyboardContextMenuEvent(position.left + position.width, position.top, keyboardEvent); } else { var mouseEvent = new Mouse.StandardMouseEvent(event); var item = this.getItemAround(mouseEvent.target); if (!item) { return; } element = item.model.getElement(); resultEvent = new _.MouseContextMenuEvent(mouseEvent); } this.context.controller.onContextMenu(this.context.tree, element, resultEvent); }; TreeView.prototype.onKeyDown = function (e) { var event = new Keyboard.StandardKeyboardEvent(e); this.didJustPressContextMenuKey = event.keyCode === 58 /* ContextMenu */ || (event.shiftKey && event.keyCode === 68 /* F10 */); if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') { return; // Ignore event if target is a form input field (avoids browser specific issues) } if (this.didJustPressContextMenuKey) { event.preventDefault(); event.stopPropagation(); } this.context.controller.onKeyDown(this.context.tree, event); }; TreeView.prototype.onKeyUp = function (e) { if (this.didJustPressContextMenuKey) { this.onContextMenu(e); } this.didJustPressContextMenuKey = false; this.context.controller.onKeyUp(this.context.tree, new Keyboard.StandardKeyboardEvent(e)); }; TreeView.prototype.onDragStart = function (item, e) { if (this.model.getHighlight()) { return; } var element = item.model.getElement(); var selection = this.model.getSelection(); var elements; if (selection.indexOf(element) > -1) { elements = selection; } else { elements = [element]; } e.dataTransfer.effectAllowed = 'copyMove'; e.dataTransfer.setData(dnd_1.DataTransfers.RESOURCES, JSON.stringify([item.uri])); if (e.dataTransfer.setDragImage) { var label = void 0; if (this.context.dnd.getDragLabel) { label = this.context.dnd.getDragLabel(this.context.tree, elements); } else { label = String(elements.length); } var dragImage_1 = document.createElement('div'); dragImage_1.className = 'monaco-tree-drag-image'; dragImage_1.textContent = label; document.body.appendChild(dragImage_1); e.dataTransfer.setDragImage(dragImage_1, -10, -10); setTimeout(function () { return document.body.removeChild(dragImage_1); }, 0); } this.currentDragAndDropData = new dnd.ElementsDragAndDropData(elements); dnd_1.StaticDND.CurrentDragAndDropData = new dnd.ExternalElementsDragAndDropData(elements); this.context.dnd.onDragStart(this.context.tree, this.currentDragAndDropData, new Mouse.DragMouseEvent(e)); }; TreeView.prototype.setupDragAndDropScrollInterval = function () { var _this = this; var viewTop = DOM.getTopLeftOffset(this.wrapper).top; if (!this.dragAndDropScrollInterval) { this.dragAndDropScrollInterval = window.setInterval(function () { if (_this.dragAndDropMouseY === null) { return; } var diff = _this.dragAndDropMouseY - viewTop; var scrollDiff = 0; var upperLimit = _this.viewHeight - 35; if (diff < 35) { scrollDiff = Math.max(-14, 0.2 * (diff - 35)); } else if (diff > upperLimit) { scrollDiff = Math.min(14, 0.2 * (diff - upperLimit)); } _this.scrollTop += scrollDiff; }, 10); this.cancelDragAndDropScrollTimeout(); this.dragAndDropScrollTimeout = window.setTimeout(function () { _this.cancelDragAndDropScrollInterval(); _this.dragAndDropScrollTimeout = null; }, 1000); } }; TreeView.prototype.cancelDragAndDropScrollInterval = function () { if (this.dragAndDropScrollInterval) { window.clearInterval(this.dragAndDropScrollInterval); this.dragAndDropScrollInterval = null; } this.cancelDragAndDropScrollTimeout(); }; TreeView.prototype.cancelDragAndDropScrollTimeout = function () { if (this.dragAndDropScrollTimeout) { window.clearTimeout(this.dragAndDropScrollTimeout); this.dragAndDropScrollTimeout = null; } }; TreeView.prototype.onDragOver = function (e) { var _this = this; e.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome) var event = new Mouse.DragMouseEvent(e); var viewItem = this.getItemAround(event.target); if (!viewItem || (event.posx === 0 && event.posy === 0 && event.browserEvent.type === DOM.EventType.DRAG_LEAVE)) { // dragging outside of tree if (this.currentDropTarget) { // clear previously hovered element feedback this.currentDropTargets.forEach(function (i) { return i.dropTarget = false; }); this.currentDropTargets = []; this.currentDropDisposable.dispose(); } this.cancelDragAndDropScrollInterval(); this.currentDropTarget = null; this.currentDropElement = null; this.dragAndDropMouseY = null; return false; } // dragging inside the tree this.setupDragAndDropScrollInterval(); this.dragAndDropMouseY = event.posy; if (!this.currentDragAndDropData) { // just started dragging if (dnd_1.StaticDND.CurrentDragAndDropData) { this.currentDragAndDropData = dnd_1.StaticDND.CurrentDragAndDropData; } else { if (!event.dataTransfer.types) { return false; } this.currentDragAndDropData = new dnd.DesktopDragAndDropData(); } } this.currentDragAndDropData.update(event.browserEvent.dataTransfer); var element; var item = viewItem.model; var reaction; // check the bubble up behavior do { element = item ? item.getElement() : this.model.getInput(); reaction = this.context.dnd.onDragOver(this.context.tree, this.currentDragAndDropData, element, event); if (!reaction || reaction.bubble !== 1 /* BUBBLE_UP */) { break; } item = item && item.parent; } while (item); if (!item) { this.currentDropElement = null; return false; } var canDrop = reaction && reaction.accept; if (canDrop) { this.currentDropElement = item.getElement(); event.preventDefault(); event.dataTransfer.dropEffect = reaction.effect === 0 /* COPY */ ? 'copy' : 'move'; } else { this.currentDropElement = null; } // item is the model item where drop() should be called // can be null var currentDropTarget = item.id === this.inputItem.id ? this.inputItem : this.items[item.id]; if (this.shouldInvalidateDropReaction || this.currentDropTarget !== currentDropTarget || !reactionEquals(this.currentDropElementReaction, reaction)) { this.shouldInvalidateDropReaction = false; if (this.currentDropTarget) { this.currentDropTargets.forEach(function (i) { return i.dropTarget = false; }); this.currentDropTargets = []; this.currentDropDisposable.dispose(); } this.currentDropTarget = currentDropTarget; this.currentDropElementReaction = reaction; if (canDrop) { // setup hover feedback for drop target if (this.currentDropTarget) { this.currentDropTarget.dropTarget = true; this.currentDropTargets.push(this.currentDropTarget); } if (reaction.bubble === 0 /* BUBBLE_DOWN */) { var nav = item.getNavigator(); var child = void 0; while (child = nav.next()) { viewItem = this.items[child.id]; if (viewItem) { viewItem.dropTarget = true; this.currentDropTargets.push(viewItem); } } } if (reaction.autoExpand) { var timeoutPromise_1 = async_1.timeout(500); this.currentDropDisposable = Lifecycle.toDisposable(function () { return timeoutPromise_1.cancel(); }); timeoutPromise_1 .then(function () { return _this.context.tree.expand(_this.currentDropElement); }) .then(function () { return _this.shouldInvalidateDropReaction = true; }); } } } return true; }; TreeView.prototype.onDrop = function (e) { if (this.currentDropElement) { var event_2 = new Mouse.DragMouseEvent(e); event_2.preventDefault(); this.currentDragAndDropData.update(event_2.browserEvent.dataTransfer); this.context.dnd.drop(this.context.tree, this.currentDragAndDropData, this.currentDropElement, event_2); this.onDragEnd(e); } this.cancelDragAndDropScrollInterval(); }; TreeView.prototype.onDragEnd = function (e) { if (this.currentDropTarget) { this.currentDropTargets.forEach(function (i) { return i.dropTarget = false; }); this.currentDropTargets = []; } this.currentDropDisposable.dispose(); this.cancelDragAndDropScrollInterval(); this.currentDragAndDropData = null; dnd_1.StaticDND.CurrentDragAndDropData = undefined; this.currentDropElement = null; this.currentDropTarget = null; this.dragAndDropMouseY = null; }; TreeView.prototype.onFocus = function () { if (!this.context.options.alwaysFocused) { DOM.addClass(this.domNode, 'focused'); } this._onDOMFocus.fire(); }; TreeView.prototype.onBlur = function () { if (!this.context.options.alwaysFocused) { DOM.removeClass(this.domNode, 'focused'); } this.domNode.removeAttribute('aria-activedescendant'); // ARIA this._onDOMBlur.fire(); }; // MS specific DOM Events TreeView.prototype.onMsPointerDown = function (event) { if (!this.msGesture) { return; } // Circumvent IE11 breaking change in e.pointerType & TypeScript's stale definitions var pointerType = event.pointerType; if (pointerType === (event.MSPOINTER_TYPE_MOUSE || 'mouse')) { this.lastPointerType = 'mouse'; return; } else if (pointerType === (event.MSPOINTER_TYPE_TOUCH || 'touch')) { this.lastPointerType = 'touch'; } else { return; } event.stopPropagation(); event.preventDefault(); this.msGesture.addPointer(event.pointerId); }; TreeView.prototype.onThrottledMsGestureChange = function (event) { this.scrollTop -= event.translationY; }; TreeView.prototype.onMsGestureTap = function (event) { event.initialTarget = document.elementFromPoint(event.clientX, event.clientY); this.onTap(event); }; // DOM changes TreeView.prototype.insertItemInDOM = function (item) { var elementAfter = null; var itemAfter = this.itemAfter(item); if (itemAfter && itemAfter.element) { elementAfter = itemAfter.element; } item.insertInDOM(this.rowsContainer, elementAfter); }; TreeView.prototype.removeItemFromDOM = function (item) { if (!item) { return; } item.removeFromDOM(); }; // Helpers TreeView.prototype.shouldBeRendered = function (item) { return item.top < this.lastRenderTop + this.lastRenderHeight && item.top + item.height > this.lastRenderTop; }; TreeView.prototype.getItemAround = function (element) { var candidate = this.inputItem; var el = element; do { if (el[TreeView.BINDING]) { candidate = el[TreeView.BINDING]; } if (el === this.wrapper || el === this.domNode) { return candidate; } if (el === this.scrollableElement.getDomNode() || el === document.body) { return undefined; } } while (el = el.parentElement); return undefined; }; // Cleanup TreeView.prototype.releaseModel = function () { if (this.model) { this.modelListeners = Lifecycle.dispose(this.modelListeners); this.model = null; } }; TreeView.prototype.dispose = function () { var _this = this; // TODO@joao: improve this.scrollableElement.dispose(); this.releaseModel(); this.viewListeners = Lifecycle.dispose(this.viewListeners); this._onDOMFocus.dispose(); this._onDOMBlur.dispose(); if (this.domNode.parentNode) { this.domNode.parentNode.removeChild(this.domNode); } if (this.items) { Object.keys(this.items).forEach(function (key) { return _this.items[key].removeFromDOM(); }); } if (this.context.cache) { this.context.cache.dispose(); } this.gestureDisposable.dispose(); _super.prototype.dispose.call(this); }; TreeView.BINDING = 'monaco-tree-row'; TreeView.LOADING_DECORATION_DELAY = 800; TreeView.counter = 0; return TreeView; }(treeViewModel_1.HeightMap)); exports.TreeView = TreeView; }); define(__m[278/*vs/css!vs/base/browser/ui/splitview/splitview*/], __M([9/*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. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[279/*vs/base/browser/ui/splitview/splitview*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,4/*vs/base/common/event*/,21/*vs/base/common/types*/,6/*vs/base/browser/dom*/,131/*vs/base/common/numbers*/,19/*vs/base/common/arrays*/,104/*vs/base/browser/ui/sash/sash*/,27/*vs/base/common/color*/,52/*vs/base/browser/event*/,278/*vs/css!vs/base/browser/ui/splitview/splitview*/]), function (require, exports, lifecycle_1, event_1, types, dom, numbers_1, arrays_1, sash_1, color_1, event_2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var defaultStyles = { separatorBorder: color_1.Color.transparent }; var ViewItem = /** @class */ (function () { function ViewItem(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; dom.addClass(container, 'visible'); } else { this._size = 0; this._cachedVisibleSize = size.cachedVisibleSize; } } Object.defineProperty(ViewItem.prototype, "size", { get: function () { return this._size; }, set: function (size) { this._size = size; }, enumerable: true, configurable: true }); Object.defineProperty(ViewItem.prototype, "visible", { get: function () { return typeof this._cachedVisibleSize === 'undefined'; }, enumerable: true, configurable: true }); ViewItem.prototype.setVisible = function (visible, size) { if (visible === this.visible) { return; } if (visible) { this.size = numbers_1.clamp(this._cachedVisibleSize, this.viewMinimumSize, this.viewMaximumSize); this._cachedVisibleSize = undefined; } else { this._cachedVisibleSize = typeof size === 'number' ? size : this.size; this.size = 0; } dom.toggleClass(this.container, 'visible', visible); if (this.view.setVisible) { this.view.setVisible(visible); } }; Object.defineProperty(ViewItem.prototype, "minimumSize", { get: function () { return this.visible ? this.view.minimumSize : 0; }, enumerable: true, configurable: true }); Object.defineProperty(ViewItem.prototype, "viewMinimumSize", { get: function () { return this.view.minimumSize; }, enumerable: true, configurable: true }); Object.defineProperty(ViewItem.prototype, "maximumSize", { get: function () { return this.visible ? this.view.maximumSize : 0; }, enumerable: true, configurable: true }); Object.defineProperty(ViewItem.prototype, "viewMaximumSize", { get: function () { return this.view.maximumSize; }, enumerable: true, configurable: true }); Object.defineProperty(ViewItem.prototype, "priority", { get: function () { return this.view.priority; }, enumerable: true, configurable: true }); Object.defineProperty(ViewItem.prototype, "snap", { get: function () { return !!this.view.snap; }, enumerable: true, configurable: true }); Object.defineProperty(ViewItem.prototype, "enabled", { set: function (enabled) { this.container.style.pointerEvents = enabled ? null : 'none'; }, enumerable: true, configurable: true }); ViewItem.prototype.layout = function (offset, layoutContext) { this.layoutContainer(offset); this.view.layout(this.size, offset, layoutContext); }; ViewItem.prototype.dispose = function () { this.disposable.dispose(); return this.view; }; return ViewItem; }()); var VerticalViewItem = /** @class */ (function (_super) { __extends(VerticalViewItem, _super); function VerticalViewItem() { return _super !== null && _super.apply(this, arguments) || this; } VerticalViewItem.prototype.layoutContainer = function (offset) { this.container.style.top = offset + "px"; this.container.style.height = this.size + "px"; }; return VerticalViewItem; }(ViewItem)); var HorizontalViewItem = /** @class */ (function (_super) { __extends(HorizontalViewItem, _super); function HorizontalViewItem() { return _super !== null && _super.apply(this, arguments) || this; } HorizontalViewItem.prototype.layoutContainer = function (offset) { this.container.style.left = offset + "px"; this.container.style.width = this.size + "px"; }; return HorizontalViewItem; }(ViewItem)); var State; (function (State) { State[State["Idle"] = 0] = "Idle"; State[State["Busy"] = 1] = "Busy"; })(State || (State = {})); var Sizing; (function (Sizing) { Sizing.Distribute = { type: 'distribute' }; function Split(index) { return { type: 'split', index: index }; } Sizing.Split = Split; function Invisible(cachedVisibleSize) { return { type: 'invisible', cachedVisibleSize: cachedVisibleSize }; } Sizing.Invisible = Invisible; })(Sizing = exports.Sizing || (exports.Sizing = {})); var SplitView = /** @class */ (function (_super) { __extends(SplitView, _super); function SplitView(container, options) { if (options === void 0) { options = {}; } var _this = _super.call(this) || this; _this.size = 0; _this.contentSize = 0; _this.proportions = undefined; _this.viewItems = []; _this.sashItems = []; _this.state = State.Idle; _this._onDidSashChange = _this._register(new event_1.Emitter()); _this.onDidSashChange = _this._onDidSashChange.event; _this._onDidSashReset = _this._register(new event_1.Emitter()); _this._startSnappingEnabled = true; _this._endSnappingEnabled = true; _this.orientation = types.isUndefined(options.orientation) ? 0 /* VERTICAL */ : options.orientation; _this.inverseAltBehavior = !!options.inverseAltBehavior; _this.proportionalLayout = types.isUndefined(options.proportionalLayout) ? true : !!options.proportionalLayout; _this.el = document.createElement('div'); dom.addClass(_this.el, 'monaco-split-view2'); dom.addClass(_this.el, _this.orientation === 0 /* VERTICAL */ ? 'vertical' : 'horizontal'); container.appendChild(_this.el); _this.sashContainer = dom.append(_this.el, dom.$('.sash-container')); _this.viewContainer = dom.append(_this.el, dom.$('.split-view-container')); _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(function (viewDescriptor, index) { var sizing = types.isUndefined(viewDescriptor.visible) || viewDescriptor.visible ? viewDescriptor.size : { type: 'invisible', cachedVisibleSize: viewDescriptor.size }; var view = viewDescriptor.view; _this.doAddView(view, sizing, index, true); }); // Initialize content size and proportions for first layout _this.contentSize = _this.viewItems.reduce(function (r, i) { return r + i.size; }, 0); _this.saveProportions(); } return _this; } Object.defineProperty(SplitView.prototype, "orthogonalStartSash", { get: function () { return this._orthogonalStartSash; }, set: function (sash) { for (var _i = 0, _a = this.sashItems; _i < _a.length; _i++) { var sashItem = _a[_i]; sashItem.sash.orthogonalStartSash = sash; } this._orthogonalStartSash = sash; }, enumerable: true, configurable: true }); Object.defineProperty(SplitView.prototype, "orthogonalEndSash", { get: function () { return this._orthogonalEndSash; }, set: function (sash) { for (var _i = 0, _a = this.sashItems; _i < _a.length; _i++) { var sashItem = _a[_i]; sashItem.sash.orthogonalEndSash = sash; } this._orthogonalEndSash = sash; }, enumerable: true, configurable: true }); Object.defineProperty(SplitView.prototype, "startSnappingEnabled", { get: function () { return this._startSnappingEnabled; }, set: function (startSnappingEnabled) { if (this._startSnappingEnabled === startSnappingEnabled) { return; } this._startSnappingEnabled = startSnappingEnabled; this.updateSashEnablement(); }, enumerable: true, configurable: true }); Object.defineProperty(SplitView.prototype, "endSnappingEnabled", { get: function () { return this._endSnappingEnabled; }, set: function (endSnappingEnabled) { if (this._endSnappingEnabled === endSnappingEnabled) { return; } this._endSnappingEnabled = endSnappingEnabled; this.updateSashEnablement(); }, enumerable: true, configurable: true }); SplitView.prototype.style = function (styles) { if (styles.separatorBorder.isTransparent()) { dom.removeClass(this.el, 'separator-border'); this.el.style.removeProperty('--separator-border'); } else { dom.addClass(this.el, 'separator-border'); this.el.style.setProperty('--separator-border', styles.separatorBorder.toString()); } }; SplitView.prototype.addView = function (view, size, index) { if (index === void 0) { index = this.viewItems.length; } this.doAddView(view, size, index, false); }; SplitView.prototype.layout = function (size, layoutContext) { var _this = this; var previousSize = Math.max(this.size, this.contentSize); this.size = size; this.layoutContext = layoutContext; if (!this.proportions) { var indexes = arrays_1.range(this.viewItems.length); var lowPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].priority === 1 /* Low */; }); var highPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].priority === 2 /* High */; }); this.resize(this.viewItems.length - 1, size - previousSize, undefined, lowPriorityIndexes, highPriorityIndexes); } else { for (var i = 0; i < this.viewItems.length; i++) { var item = this.viewItems[i]; item.size = numbers_1.clamp(Math.round(this.proportions[i] * size), item.minimumSize, item.maximumSize); } } this.distributeEmptySpace(); this.layoutViews(); }; SplitView.prototype.saveProportions = function () { var _this = this; if (this.proportionalLayout && this.contentSize > 0) { this.proportions = this.viewItems.map(function (i) { return i.size / _this.contentSize; }); } }; SplitView.prototype.onSashStart = function (_a) { var _this = this; var sash = _a.sash, start = _a.start, alt = _a.alt; for (var _i = 0, _b = this.viewItems; _i < _b.length; _i++) { var item = _b[_i]; item.enabled = false; } var index = arrays_1.firstIndex(this.sashItems, function (item) { return item.sash === sash; }); // This way, we can press Alt while we resize a sash, macOS style! var disposable = lifecycle_1.combinedDisposable(event_2.domEvent(document.body, 'keydown')(function (e) { return resetSashDragState(_this.sashDragState.current, e.altKey); }), event_2.domEvent(document.body, 'keyup')(function () { return resetSashDragState(_this.sashDragState.current, false); })); var resetSashDragState = function (start, alt) { var sizes = _this.viewItems.map(function (i) { return i.size; }); var minDelta = Number.NEGATIVE_INFINITY; var 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 var isLastSash = index === _this.sashItems.length - 1; if (isLastSash) { var viewItem = _this.viewItems[index]; minDelta = (viewItem.minimumSize - viewItem.size) / 2; maxDelta = (viewItem.maximumSize - viewItem.size) / 2; } else { var viewItem = _this.viewItems[index + 1]; minDelta = (viewItem.size - viewItem.maximumSize) / 2; maxDelta = (viewItem.size - viewItem.minimumSize) / 2; } } var snapBefore; var snapAfter; if (!alt) { var upIndexes = arrays_1.range(index, -1); var downIndexes = arrays_1.range(index + 1, _this.viewItems.length); var minDeltaUp = upIndexes.reduce(function (r, i) { return r + (_this.viewItems[i].minimumSize - sizes[i]); }, 0); var maxDeltaUp = upIndexes.reduce(function (r, i) { return r + (_this.viewItems[i].viewMaximumSize - sizes[i]); }, 0); var maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce(function (r, i) { return r + (sizes[i] - _this.viewItems[i].minimumSize); }, 0); var minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce(function (r, i) { return r + (sizes[i] - _this.viewItems[i].viewMaximumSize); }, 0); var minDelta_1 = Math.max(minDeltaUp, minDeltaDown); var maxDelta_1 = Math.min(maxDeltaDown, maxDeltaUp); var snapBeforeIndex = _this.findFirstSnapIndex(upIndexes); var snapAfterIndex = _this.findFirstSnapIndex(downIndexes); if (typeof snapBeforeIndex === 'number') { var viewItem = _this.viewItems[snapBeforeIndex]; var halfSize = Math.floor(viewItem.viewMinimumSize / 2); snapBefore = { index: snapBeforeIndex, limitDelta: viewItem.visible ? minDelta_1 - halfSize : minDelta_1 + halfSize, size: viewItem.size }; } if (typeof snapAfterIndex === 'number') { var viewItem = _this.viewItems[snapAfterIndex]; var halfSize = Math.floor(viewItem.viewMinimumSize / 2); snapAfter = { index: snapAfterIndex, limitDelta: viewItem.visible ? maxDelta_1 + halfSize : maxDelta_1 - halfSize, size: viewItem.size }; } } _this.sashDragState = { start: start, current: start, index: index, sizes: sizes, minDelta: minDelta, maxDelta: maxDelta, alt: alt, snapBefore: snapBefore, snapAfter: snapAfter, disposable: disposable }; }; resetSashDragState(start, alt); }; SplitView.prototype.onSashChange = function (_a) { var current = _a.current; var _b = this.sashDragState, index = _b.index, start = _b.start, sizes = _b.sizes, alt = _b.alt, minDelta = _b.minDelta, maxDelta = _b.maxDelta, snapBefore = _b.snapBefore, snapAfter = _b.snapAfter; this.sashDragState.current = current; var delta = current - start; var newDelta = this.resize(index, delta, sizes, undefined, undefined, minDelta, maxDelta, snapBefore, snapAfter); if (alt) { var isLastSash = index === this.sashItems.length - 1; var newSizes = this.viewItems.map(function (i) { return i.size; }); var viewItemIndex = isLastSash ? index : index + 1; var viewItem = this.viewItems[viewItemIndex]; var newMinDelta = viewItem.size - viewItem.maximumSize; var newMaxDelta = viewItem.size - viewItem.minimumSize; var resizeIndex = isLastSash ? index - 1 : index + 1; this.resize(resizeIndex, -newDelta, newSizes, undefined, undefined, newMinDelta, newMaxDelta); } this.distributeEmptySpace(); this.layoutViews(); }; SplitView.prototype.onSashEnd = function (index) { this._onDidSashChange.fire(index); this.sashDragState.disposable.dispose(); this.saveProportions(); for (var _i = 0, _a = this.viewItems; _i < _a.length; _i++) { var item = _a[_i]; item.enabled = true; } }; SplitView.prototype.onViewChange = function (item, size) { var index = this.viewItems.indexOf(item); if (index < 0 || index >= this.viewItems.length) { return; } size = typeof size === 'number' ? size : item.size; size = 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); } }; SplitView.prototype.resizeView = function (index, size) { var _this = this; if (this.state !== State.Idle) { throw new Error('Cant modify splitview'); } this.state = State.Busy; if (index < 0 || index >= this.viewItems.length) { return; } var indexes = arrays_1.range(this.viewItems.length).filter(function (i) { return i !== index; }); var lowPriorityIndexes = __spreadArrays(indexes.filter(function (i) { return _this.viewItems[i].priority === 1 /* Low */; }), [index]); var highPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].priority === 2 /* High */; }); var item = this.viewItems[index]; size = Math.round(size); size = numbers_1.clamp(size, item.minimumSize, Math.min(item.maximumSize, this.size)); item.size = size; this.relayout(lowPriorityIndexes, highPriorityIndexes); this.state = State.Idle; }; SplitView.prototype.distributeViewSizes = function () { var _this = this; var flexibleViewItems = []; var flexibleSize = 0; for (var _i = 0, _a = this.viewItems; _i < _a.length; _i++) { var item = _a[_i]; if (item.maximumSize - item.minimumSize > 0) { flexibleViewItems.push(item); flexibleSize += item.size; } } var size = Math.floor(flexibleSize / flexibleViewItems.length); for (var _b = 0, flexibleViewItems_1 = flexibleViewItems; _b < flexibleViewItems_1.length; _b++) { var item = flexibleViewItems_1[_b]; item.size = numbers_1.clamp(size, item.minimumSize, item.maximumSize); } var indexes = arrays_1.range(this.viewItems.length); var lowPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].priority === 1 /* Low */; }); var highPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].priority === 2 /* High */; }); this.relayout(lowPriorityIndexes, highPriorityIndexes); }; SplitView.prototype.getViewSize = function (index) { if (index < 0 || index >= this.viewItems.length) { return -1; } return this.viewItems[index].size; }; SplitView.prototype.doAddView = function (view, size, index, skipLayout) { var _this = this; if (index === void 0) { index = this.viewItems.length; } if (this.state !== State.Idle) { throw new Error('Cant modify splitview'); } this.state = State.Busy; // Add view var container = dom.$('.split-view-view'); if (index === this.viewItems.length) { this.viewContainer.appendChild(container); } else { this.viewContainer.insertBefore(container, this.viewContainer.children.item(index)); } var onChangeDisposable = view.onDidChange(function (size) { return _this.onViewChange(item, size); }); var containerDisposable = lifecycle_1.toDisposable(function () { return _this.viewContainer.removeChild(container); }); var disposable = lifecycle_1.combinedDisposable(onChangeDisposable, containerDisposable); var 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; } var 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) { var orientation_1 = this.orientation === 0 /* VERTICAL */ ? 1 /* HORIZONTAL */ : 0 /* VERTICAL */; var layoutProvider = this.orientation === 0 /* VERTICAL */ ? { getHorizontalSashTop: function (sash) { return _this.getSashPosition(sash); } } : { getVerticalSashLeft: function (sash) { return _this.getSashPosition(sash); } }; var sash_2 = new sash_1.Sash(this.sashContainer, layoutProvider, { orientation: orientation_1, orthogonalStartSash: this.orthogonalStartSash, orthogonalEndSash: this.orthogonalEndSash }); var sashEventMapper = this.orientation === 0 /* VERTICAL */ ? function (e) { return ({ sash: sash_2, start: e.startY, current: e.currentY, alt: e.altKey }); } : function (e) { return ({ sash: sash_2, start: e.startX, current: e.currentX, alt: e.altKey }); }; var onStart = event_1.Event.map(sash_2.onDidStart, sashEventMapper); var onStartDisposable = onStart(this.onSashStart, this); var onChange = event_1.Event.map(sash_2.onDidChange, sashEventMapper); var onChangeDisposable_1 = onChange(this.onSashChange, this); var onEnd = event_1.Event.map(sash_2.onDidEnd, function () { return arrays_1.firstIndex(_this.sashItems, function (item) { return item.sash === sash_2; }); }); var onEndDisposable = onEnd(this.onSashEnd, this); var onDidResetDisposable = sash_2.onDidReset(function () { var index = arrays_1.firstIndex(_this.sashItems, function (item) { return item.sash === sash_2; }); var upIndexes = arrays_1.range(index, -1); var downIndexes = arrays_1.range(index + 1, _this.viewItems.length); var snapBeforeIndex = _this.findFirstSnapIndex(upIndexes); var 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); }); var disposable_1 = lifecycle_1.combinedDisposable(onStartDisposable, onChangeDisposable_1, onEndDisposable, onDidResetDisposable, sash_2); var sashItem = { sash: sash_2, disposable: disposable_1 }; this.sashItems.splice(index - 1, 0, sashItem); } container.appendChild(view.element); var 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(); } }; SplitView.prototype.relayout = function (lowPriorityIndexes, highPriorityIndexes) { var contentSize = this.viewItems.reduce(function (r, i) { return r + i.size; }, 0); this.resize(this.viewItems.length - 1, this.size - contentSize, undefined, lowPriorityIndexes, highPriorityIndexes); this.distributeEmptySpace(); this.layoutViews(); this.saveProportions(); }; SplitView.prototype.resize = function (index, delta, sizes, lowPriorityIndexes, highPriorityIndexes, overloadMinDelta, overloadMaxDelta, snapBefore, snapAfter) { var _this = this; if (sizes === void 0) { sizes = this.viewItems.map(function (i) { return i.size; }); } if (overloadMinDelta === void 0) { overloadMinDelta = Number.NEGATIVE_INFINITY; } if (overloadMaxDelta === void 0) { overloadMaxDelta = Number.POSITIVE_INFINITY; } if (index < 0 || index >= this.viewItems.length) { return 0; } var upIndexes = arrays_1.range(index, -1); var downIndexes = arrays_1.range(index + 1, this.viewItems.length); if (highPriorityIndexes) { for (var _i = 0, highPriorityIndexes_1 = highPriorityIndexes; _i < highPriorityIndexes_1.length; _i++) { var index_1 = highPriorityIndexes_1[_i]; arrays_1.pushToStart(upIndexes, index_1); arrays_1.pushToStart(downIndexes, index_1); } } if (lowPriorityIndexes) { for (var _a = 0, lowPriorityIndexes_1 = lowPriorityIndexes; _a < lowPriorityIndexes_1.length; _a++) { var index_2 = lowPriorityIndexes_1[_a]; arrays_1.pushToEnd(upIndexes, index_2); arrays_1.pushToEnd(downIndexes, index_2); } } var upItems = upIndexes.map(function (i) { return _this.viewItems[i]; }); var upSizes = upIndexes.map(function (i) { return sizes[i]; }); var downItems = downIndexes.map(function (i) { return _this.viewItems[i]; }); var downSizes = downIndexes.map(function (i) { return sizes[i]; }); var minDeltaUp = upIndexes.reduce(function (r, i) { return r + (_this.viewItems[i].minimumSize - sizes[i]); }, 0); var maxDeltaUp = upIndexes.reduce(function (r, i) { return r + (_this.viewItems[i].maximumSize - sizes[i]); }, 0); var maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce(function (r, i) { return r + (sizes[i] - _this.viewItems[i].minimumSize); }, 0); var minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce(function (r, i) { return r + (sizes[i] - _this.viewItems[i].maximumSize); }, 0); var minDelta = Math.max(minDeltaUp, minDeltaDown, overloadMinDelta); var maxDelta = Math.min(maxDeltaDown, maxDeltaUp, overloadMaxDelta); var snapped = false; if (snapBefore) { var snapView = this.viewItems[snapBefore.index]; var visible = delta >= snapBefore.limitDelta; snapped = visible !== snapView.visible; snapView.setVisible(visible, snapBefore.size); } if (!snapped && snapAfter) { var snapView = this.viewItems[snapAfter.index]; var 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 = numbers_1.clamp(delta, minDelta, maxDelta); for (var i = 0, deltaUp = delta; i < upItems.length; i++) { var item = upItems[i]; var size = numbers_1.clamp(upSizes[i] + deltaUp, item.minimumSize, item.maximumSize); var viewDelta = size - upSizes[i]; deltaUp -= viewDelta; item.size = size; } for (var i = 0, deltaDown = delta; i < downItems.length; i++) { var item = downItems[i]; var size = numbers_1.clamp(downSizes[i] - deltaDown, item.minimumSize, item.maximumSize); var viewDelta = size - downSizes[i]; deltaDown += viewDelta; item.size = size; } return delta; }; SplitView.prototype.distributeEmptySpace = function (lowPriorityIndex) { var _this = this; var contentSize = this.viewItems.reduce(function (r, i) { return r + i.size; }, 0); var emptyDelta = this.size - contentSize; var indexes = arrays_1.range(this.viewItems.length - 1, -1); var lowPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].priority === 1 /* Low */; }); var highPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].priority === 2 /* High */; }); for (var _i = 0, highPriorityIndexes_2 = highPriorityIndexes; _i < highPriorityIndexes_2.length; _i++) { var index = highPriorityIndexes_2[_i]; arrays_1.pushToStart(indexes, index); } for (var _a = 0, lowPriorityIndexes_2 = lowPriorityIndexes; _a < lowPriorityIndexes_2.length; _a++) { var index = lowPriorityIndexes_2[_a]; arrays_1.pushToEnd(indexes, index); } if (typeof lowPriorityIndex === 'number') { arrays_1.pushToEnd(indexes, lowPriorityIndex); } for (var i = 0; emptyDelta !== 0 && i < indexes.length; i++) { var item = this.viewItems[indexes[i]]; var size = numbers_1.clamp(item.size + emptyDelta, item.minimumSize, item.maximumSize); var viewDelta = size - item.size; emptyDelta -= viewDelta; item.size = size; } }; SplitView.prototype.layoutViews = function () { // Save new content size this.contentSize = this.viewItems.reduce(function (r, i) { return r + i.size; }, 0); // Layout views var offset = 0; for (var _i = 0, _a = this.viewItems; _i < _a.length; _i++) { var viewItem = _a[_i]; viewItem.layout(offset, this.layoutContext); offset += viewItem.size; } // Layout sashes this.sashItems.forEach(function (item) { return item.sash.layout(); }); this.updateSashEnablement(); }; SplitView.prototype.updateSashEnablement = function () { var previous = false; var collapsesDown = this.viewItems.map(function (i) { return previous = (i.size - i.minimumSize > 0) || previous; }); previous = false; var expandsDown = this.viewItems.map(function (i) { return previous = (i.maximumSize - i.size > 0) || previous; }); var reverseViews = __spreadArrays(this.viewItems).reverse(); previous = false; var collapsesUp = reverseViews.map(function (i) { return previous = (i.size - i.minimumSize > 0) || previous; }).reverse(); previous = false; var expandsUp = reverseViews.map(function (i) { return previous = (i.maximumSize - i.size > 0) || previous; }).reverse(); var position = 0; for (var index = 0; index < this.sashItems.length; index++) { var sash = this.sashItems[index].sash; var viewItem = this.viewItems[index]; position += viewItem.size; var min = !(collapsesDown[index] && expandsUp[index + 1]); var max = !(expandsDown[index] && collapsesUp[index + 1]); if (min && max) { var upIndexes = arrays_1.range(index, -1); var downIndexes = arrays_1.range(index + 1, this.viewItems.length); var snapBeforeIndex = this.findFirstSnapIndex(upIndexes); var snapAfterIndex = this.findFirstSnapIndex(downIndexes); var snappedBefore = typeof snapBeforeIndex === 'number' && !this.viewItems[snapBeforeIndex].visible; var snappedAfter = typeof snapAfterIndex === 'number' && !this.viewItems[snapAfterIndex].visible; if (snappedBefore && collapsesUp[index] && (position > 0 || this.startSnappingEnabled)) { sash.state = 1 /* Minimum */; } else if (snappedAfter && collapsesDown[index] && (position < this.contentSize || this.endSnappingEnabled)) { sash.state = 2 /* Maximum */; } else { sash.state = 0 /* Disabled */; } } else if (min && !max) { sash.state = 1 /* Minimum */; } else if (!min && max) { sash.state = 2 /* Maximum */; } else { sash.state = 3 /* Enabled */; } } }; SplitView.prototype.getSashPosition = function (sash) { var position = 0; for (var i = 0; i < this.sashItems.length; i++) { position += this.viewItems[i].size; if (this.sashItems[i].sash === sash) { return Math.min(position, this.contentSize - 2); } } return 0; }; SplitView.prototype.findFirstSnapIndex = function (indexes) { // visible views first for (var _i = 0, indexes_1 = indexes; _i < indexes_1.length; _i++) { var index = indexes_1[_i]; var viewItem = this.viewItems[index]; if (!viewItem.visible) { continue; } if (viewItem.snap) { return index; } } // then, hidden views for (var _a = 0, indexes_2 = indexes; _a < indexes_2.length; _a++) { var index = indexes_2[_a]; var viewItem = this.viewItems[index]; if (viewItem.visible && viewItem.maximumSize - viewItem.minimumSize > 0) { return undefined; } if (!viewItem.visible && viewItem.snap) { return index; } } return undefined; }; SplitView.prototype.dispose = function () { _super.prototype.dispose.call(this); this.viewItems.forEach(function (i) { return i.dispose(); }); this.viewItems = []; this.sashItems.forEach(function (i) { return i.disposable.dispose(); }); this.sashItems = []; }; return SplitView; }(lifecycle_1.Disposable)); exports.SplitView = SplitView; }); define(__m[280/*vs/css!vs/base/browser/ui/tree/media/tree*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[281/*vs/css!vs/base/parts/quickopen/browser/quickopen*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[282/*vs/css!vs/base/parts/tree/browser/tree*/], __M([9/*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[283/*vs/base/parts/tree/browser/treeImpl*/], __M([0/*require*/,1/*exports*/,137/*vs/base/parts/tree/browser/treeDefaults*/,256/*vs/base/parts/tree/browser/treeModel*/,277/*vs/base/parts/tree/browser/treeView*/,4/*vs/base/common/event*/,27/*vs/base/common/color*/,31/*vs/base/common/objects*/,282/*vs/css!vs/base/parts/tree/browser/tree*/]), function (require, exports, TreeDefaults, Model, View, event_1, color_1, objects_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var TreeContext = /** @class */ (function () { function TreeContext(tree, configuration, options) { if (options === void 0) { options = {}; } this.tree = tree; this.configuration = configuration; this.options = options; if (!configuration.dataSource) { throw new Error('You must provide a Data Source to the tree.'); } this.dataSource = configuration.dataSource; this.renderer = configuration.renderer; this.controller = configuration.controller || new TreeDefaults.DefaultController({ clickBehavior: 1 /* ON_MOUSE_UP */, keyboardSupport: typeof options.keyboardSupport !== 'boolean' || options.keyboardSupport }); this.dnd = configuration.dnd || new TreeDefaults.DefaultDragAndDrop(); this.filter = configuration.filter || new TreeDefaults.DefaultFilter(); this.sorter = configuration.sorter; this.accessibilityProvider = configuration.accessibilityProvider || new TreeDefaults.DefaultAccessibilityProvider(); this.styler = configuration.styler; } return TreeContext; }()); exports.TreeContext = TreeContext; var defaultStyles = { listFocusBackground: color_1.Color.fromHex('#073655'), listActiveSelectionBackground: color_1.Color.fromHex('#0E639C'), listActiveSelectionForeground: color_1.Color.fromHex('#FFFFFF'), listFocusAndSelectionBackground: color_1.Color.fromHex('#094771'), listFocusAndSelectionForeground: color_1.Color.fromHex('#FFFFFF'), listInactiveSelectionBackground: color_1.Color.fromHex('#3F3F46'), listHoverBackground: color_1.Color.fromHex('#2A2D2E'), listDropBackground: color_1.Color.fromHex('#383B3D') }; var Tree = /** @class */ (function () { function Tree(container, configuration, options) { if (options === void 0) { options = {}; } this._onDidChangeFocus = new event_1.Relay(); this.onDidChangeFocus = this._onDidChangeFocus.event; this._onDidChangeSelection = new event_1.Relay(); this.onDidChangeSelection = this._onDidChangeSelection.event; this._onHighlightChange = new event_1.Relay(); this._onDidExpandItem = new event_1.Relay(); this._onDidCollapseItem = new event_1.Relay(); this._onDispose = new event_1.Emitter(); this.onDidDispose = this._onDispose.event; this.container = container; objects_1.mixin(options, defaultStyles, false); options.twistiePixels = typeof options.twistiePixels === 'number' ? options.twistiePixels : 32; options.showTwistie = options.showTwistie === false ? false : true; options.indentPixels = typeof options.indentPixels === 'number' ? options.indentPixels : 12; options.alwaysFocused = options.alwaysFocused === true ? true : false; options.useShadows = options.useShadows === false ? false : true; options.paddingOnRow = options.paddingOnRow === false ? false : true; options.showLoading = options.showLoading === false ? false : true; this.context = new TreeContext(this, configuration, options); this.model = new Model.TreeModel(this.context); this.view = new View.TreeView(this.context, this.container); this.view.setModel(this.model); this._onDidChangeFocus.input = this.model.onDidFocus; this._onDidChangeSelection.input = this.model.onDidSelect; this._onHighlightChange.input = this.model.onDidHighlight; this._onDidExpandItem.input = this.model.onDidExpandItem; this._onDidCollapseItem.input = this.model.onDidCollapseItem; } Tree.prototype.style = function (styles) { this.view.applyStyles(styles); }; Object.defineProperty(Tree.prototype, "onDidFocus", { get: function () { return this.view.onDOMFocus; }, enumerable: true, configurable: true }); Tree.prototype.getHTMLElement = function () { return this.view.getHTMLElement(); }; Tree.prototype.layout = function (height, width) { this.view.layout(height, width); }; Tree.prototype.domFocus = function () { this.view.focus(); }; Tree.prototype.isDOMFocused = function () { return this.view.isFocused(); }; Tree.prototype.domBlur = function () { this.view.blur(); }; Tree.prototype.setInput = function (element) { return this.model.setInput(element); }; Tree.prototype.getInput = function () { return this.model.getInput(); }; Tree.prototype.expand = function (element) { return this.model.expand(element); }; Tree.prototype.collapse = function (element, recursive) { if (recursive === void 0) { recursive = false; } return this.model.collapse(element, recursive); }; Tree.prototype.toggleExpansion = function (element, recursive) { if (recursive === void 0) { recursive = false; } return this.model.toggleExpansion(element, recursive); }; Tree.prototype.isExpanded = function (element) { return this.model.isExpanded(element); }; Tree.prototype.reveal = function (element, relativeTop) { if (relativeTop === void 0) { relativeTop = null; } return this.model.reveal(element, relativeTop); }; Tree.prototype.getHighlight = function () { return this.model.getHighlight(); }; Tree.prototype.clearHighlight = function (eventPayload) { this.model.setHighlight(null, eventPayload); }; Tree.prototype.setSelection = function (elements, eventPayload) { this.model.setSelection(elements, eventPayload); }; Tree.prototype.getSelection = function () { return this.model.getSelection(); }; Tree.prototype.clearSelection = function (eventPayload) { this.model.setSelection([], eventPayload); }; Tree.prototype.setFocus = function (element, eventPayload) { this.model.setFocus(element, eventPayload); }; Tree.prototype.getFocus = function () { return this.model.getFocus(); }; Tree.prototype.focusNext = function (count, eventPayload) { this.model.focusNext(count, eventPayload); }; Tree.prototype.focusPrevious = function (count, eventPayload) { this.model.focusPrevious(count, eventPayload); }; Tree.prototype.focusParent = function (eventPayload) { this.model.focusParent(eventPayload); }; Tree.prototype.focusFirstChild = function (eventPayload) { this.model.focusFirstChild(eventPayload); }; Tree.prototype.focusFirst = function (eventPayload, from) { this.model.focusFirst(eventPayload, from); }; Tree.prototype.focusNth = function (index, eventPayload) { this.model.focusNth(index, eventPayload); }; Tree.prototype.focusLast = function (eventPayload, from) { this.model.focusLast(eventPayload, from); }; Tree.prototype.focusNextPage = function (eventPayload) { this.view.focusNextPage(eventPayload); }; Tree.prototype.focusPreviousPage = function (eventPayload) { this.view.focusPreviousPage(eventPayload); }; Tree.prototype.clearFocus = function (eventPayload) { this.model.setFocus(null, eventPayload); }; Tree.prototype.dispose = function () { this._onDispose.fire(); this.model.dispose(); this.view.dispose(); this._onDidChangeFocus.dispose(); this._onDidChangeSelection.dispose(); this._onHighlightChange.dispose(); this._onDidExpandItem.dispose(); this._onDidCollapseItem.dispose(); this._onDispose.dispose(); }; return Tree; }()); exports.Tree = Tree; }); define(__m[284/*vs/css!vs/editor/browser/controller/textAreaHandler*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[285/*vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[286/*vs/css!vs/editor/browser/viewParts/decorations/decorations*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[287/*vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[288/*vs/css!vs/editor/browser/viewParts/indentGuides/indentGuides*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[289/*vs/css!vs/editor/browser/viewParts/lineNumbers/lineNumbers*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[290/*vs/css!vs/editor/browser/viewParts/lines/viewLines*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[291/*vs/css!vs/editor/browser/viewParts/linesDecorations/linesDecorations*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[292/*vs/css!vs/editor/browser/viewParts/marginDecorations/marginDecorations*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[293/*vs/css!vs/editor/browser/viewParts/minimap/minimap*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[294/*vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[295/*vs/css!vs/editor/browser/viewParts/rulers/rulers*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[296/*vs/css!vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[297/*vs/css!vs/editor/browser/viewParts/selections/selections*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[298/*vs/css!vs/editor/browser/viewParts/viewCursors/viewCursors*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[299/*vs/css!vs/editor/browser/widget/media/diffEditor*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[300/*vs/css!vs/editor/browser/widget/media/diffReview*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[301/*vs/css!vs/editor/browser/widget/media/editor*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[302/*vs/css!vs/editor/contrib/bracketMatching/bracketMatching*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[303/*vs/css!vs/editor/contrib/clipboard/clipboard*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[304/*vs/css!vs/editor/contrib/codeAction/lightBulbWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[305/*vs/css!vs/editor/contrib/codelens/codelensWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[306/*vs/css!vs/editor/contrib/colorPicker/colorPicker*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[307/*vs/css!vs/editor/contrib/dnd/dnd*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[308/*vs/css!vs/editor/contrib/documentSymbols/media/outlineTree*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[309/*vs/css!vs/editor/contrib/documentSymbols/media/symbol-icons*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[310/*vs/css!vs/editor/contrib/find/findWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[311/*vs/css!vs/editor/contrib/folding/folding*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[312/*vs/css!vs/editor/contrib/gotoError/media/gotoErrorWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[313/*vs/css!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[314/*vs/css!vs/editor/contrib/gotoSymbol/peek/referencesWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[315/*vs/css!vs/editor/contrib/hover/hover*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[316/*vs/css!vs/editor/contrib/links/links*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[317/*vs/css!vs/editor/contrib/message/messageController*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[318/*vs/css!vs/editor/contrib/parameterHints/parameterHints*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[319/*vs/css!vs/editor/contrib/peekView/media/peekViewWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[320/*vs/css!vs/editor/contrib/rename/renameInputField*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[321/*vs/css!vs/editor/contrib/snippet/snippetSession*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[322/*vs/css!vs/editor/contrib/suggest/media/suggest*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[323/*vs/css!vs/editor/contrib/suggest/media/suggestStatusBar*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[324/*vs/css!vs/editor/contrib/zoneWidget/zoneWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[325/*vs/css!vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[326/*vs/css!vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[327/*vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[328/*vs/css!vs/editor/standalone/browser/quickOpen/editorQuickOpen*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[329/*vs/css!vs/editor/standalone/browser/quickOpen/gotoLine*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[330/*vs/css!vs/editor/standalone/browser/quickOpen/quickOutline*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[331/*vs/css!vs/editor/standalone/browser/standalone-tokens*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[332/*vs/css!vs/platform/contextview/browser/contextMenuHandler*/], __M([9/*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[333/*vs/editor/browser/config/charWidthReader*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CharWidthRequest = /** @class */ (function () { function CharWidthRequest(chr, type) { this.chr = chr; this.type = type; this.width = 0; } CharWidthRequest.prototype.fulfill = function (width) { this.width = width; }; return CharWidthRequest; }()); exports.CharWidthRequest = CharWidthRequest; var DomCharWidthReader = /** @class */ (function () { function DomCharWidthReader(bareFontInfo, requests) { this._bareFontInfo = bareFontInfo; this._requests = requests; this._container = null; this._testElements = null; } DomCharWidthReader.prototype.read = function () { // 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; }; DomCharWidthReader.prototype._createDomElements = function () { var container = document.createElement('div'); container.style.position = 'absolute'; container.style.top = '-50000px'; container.style.width = '50000px'; var regularDomNode = document.createElement('div'); regularDomNode.style.fontFamily = this._bareFontInfo.getMassagedFontFamily(); regularDomNode.style.fontWeight = this._bareFontInfo.fontWeight; regularDomNode.style.fontSize = this._bareFontInfo.fontSize + 'px'; regularDomNode.style.fontFeatureSettings = this._bareFontInfo.fontFeatureSettings; regularDomNode.style.lineHeight = this._bareFontInfo.lineHeight + 'px'; regularDomNode.style.letterSpacing = this._bareFontInfo.letterSpacing + 'px'; container.appendChild(regularDomNode); var boldDomNode = document.createElement('div'); boldDomNode.style.fontFamily = this._bareFontInfo.getMassagedFontFamily(); boldDomNode.style.fontWeight = 'bold'; boldDomNode.style.fontSize = this._bareFontInfo.fontSize + 'px'; boldDomNode.style.fontFeatureSettings = this._bareFontInfo.fontFeatureSettings; boldDomNode.style.lineHeight = this._bareFontInfo.lineHeight + 'px'; boldDomNode.style.letterSpacing = this._bareFontInfo.letterSpacing + 'px'; container.appendChild(boldDomNode); var italicDomNode = document.createElement('div'); italicDomNode.style.fontFamily = this._bareFontInfo.getMassagedFontFamily(); italicDomNode.style.fontWeight = this._bareFontInfo.fontWeight; italicDomNode.style.fontSize = this._bareFontInfo.fontSize + 'px'; italicDomNode.style.fontFeatureSettings = this._bareFontInfo.fontFeatureSettings; italicDomNode.style.lineHeight = this._bareFontInfo.lineHeight + 'px'; italicDomNode.style.letterSpacing = this._bareFontInfo.letterSpacing + 'px'; italicDomNode.style.fontStyle = 'italic'; container.appendChild(italicDomNode); var testElements = []; for (var _i = 0, _a = this._requests; _i < _a.length; _i++) { var request = _a[_i]; var parent_1 = void 0; if (request.type === 0 /* Regular */) { parent_1 = regularDomNode; } if (request.type === 2 /* Bold */) { parent_1 = boldDomNode; } if (request.type === 1 /* Italic */) { parent_1 = italicDomNode; } parent_1.appendChild(document.createElement('br')); var testElement = document.createElement('span'); DomCharWidthReader._render(testElement, request); parent_1.appendChild(testElement); testElements.push(testElement); } this._container = container; this._testElements = testElements; }; DomCharWidthReader._render = function (testElement, request) { if (request.chr === ' ') { var htmlString = ' '; // Repeat character 256 (2^8) times for (var i = 0; i < 8; i++) { htmlString += htmlString; } testElement.innerHTML = htmlString; } else { var testString = request.chr; // Repeat character 256 (2^8) times for (var i = 0; i < 8; i++) { testString += testString; } testElement.textContent = testString; } }; DomCharWidthReader.prototype._readFromDomElements = function () { for (var i = 0, len = this._requests.length; i < len; i++) { var request = this._requests[i]; var testElement = this._testElements[i]; request.fulfill(testElement.offsetWidth / 256); } }; return DomCharWidthReader; }()); function readCharWidths(bareFontInfo, requests) { var 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[185/*vs/editor/browser/config/elementSizeObserver*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,6/*vs/base/browser/dom*/]), function (require, exports, lifecycle_1, dom) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ElementSizeObserver = /** @class */ (function (_super) { __extends(ElementSizeObserver, _super); function ElementSizeObserver(referenceDomElement, dimension, changeCallback) { var _this = _super.call(this) || this; _this.referenceDomElement = referenceDomElement; _this.changeCallback = changeCallback; _this.width = -1; _this.height = -1; _this.mutationObserver = null; _this.windowSizeListener = null; _this.measureReferenceDomElement(false, dimension); return _this; } ElementSizeObserver.prototype.dispose = function () { this.stopObserving(); _super.prototype.dispose.call(this); }; ElementSizeObserver.prototype.getWidth = function () { return this.width; }; ElementSizeObserver.prototype.getHeight = function () { return this.height; }; ElementSizeObserver.prototype.startObserving = function () { var _this = this; if (!this.mutationObserver && this.referenceDomElement) { this.mutationObserver = new MutationObserver(function () { return _this._onDidMutate(); }); this.mutationObserver.observe(this.referenceDomElement, { attributes: true, }); } if (!this.windowSizeListener) { this.windowSizeListener = dom.addDisposableListener(window, 'resize', function () { return _this._onDidResizeWindow(); }); } }; ElementSizeObserver.prototype.stopObserving = function () { if (this.mutationObserver) { this.mutationObserver.disconnect(); this.mutationObserver = null; } if (this.windowSizeListener) { this.windowSizeListener.dispose(); this.windowSizeListener = null; } }; ElementSizeObserver.prototype.observe = function (dimension) { this.measureReferenceDomElement(true, dimension); }; ElementSizeObserver.prototype._onDidMutate = function () { this.measureReferenceDomElement(true); }; ElementSizeObserver.prototype._onDidResizeWindow = function () { this.measureReferenceDomElement(true); }; ElementSizeObserver.prototype.measureReferenceDomElement = function (callChangeCallback, dimension) { var observedWidth = 0; var observedHeight = 0; if (dimension) { observedWidth = dimension.width; observedHeight = dimension.height; } else if (this.referenceDomElement) { observedWidth = this.referenceDomElement.clientWidth; observedHeight = this.referenceDomElement.clientHeight; } observedWidth = Math.max(5, observedWidth); observedHeight = Math.max(5, observedHeight); if (this.width !== observedWidth || this.height !== observedHeight) { this.width = observedWidth; this.height = observedHeight; if (callChangeCallback) { this.changeCallback(); } } }; return ElementSizeObserver; }(lifecycle_1.Disposable)); 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[141/*vs/editor/browser/editorDom*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,78/*vs/base/browser/globalMouseMoveMonitor*/,45/*vs/base/browser/mouseEvent*/,2/*vs/base/common/lifecycle*/]), function (require, exports, dom, globalMouseMoveMonitor_1, mouseEvent_1, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Coordinates relative to the whole document (e.g. mouse event's pageX and pageY) */ var PageCoordinates = /** @class */ (function () { function PageCoordinates(x, y) { this.x = x; this.y = y; } PageCoordinates.prototype.toClientCoordinates = function () { return new ClientCoordinates(this.x - dom.StandardWindow.scrollX, this.y - dom.StandardWindow.scrollY); }; return PageCoordinates; }()); 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. */ var ClientCoordinates = /** @class */ (function () { function ClientCoordinates(clientX, clientY) { this.clientX = clientX; this.clientY = clientY; } ClientCoordinates.prototype.toPageCoordinates = function () { return new PageCoordinates(this.clientX + dom.StandardWindow.scrollX, this.clientY + dom.StandardWindow.scrollY); }; return ClientCoordinates; }()); exports.ClientCoordinates = ClientCoordinates; /** * The position of the editor in the page. */ var EditorPagePosition = /** @class */ (function () { function EditorPagePosition(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; } return EditorPagePosition; }()); exports.EditorPagePosition = EditorPagePosition; function createEditorPagePosition(editorViewDomNode) { var editorPos = dom.getDomNodePagePosition(editorViewDomNode); return new EditorPagePosition(editorPos.left, editorPos.top, editorPos.width, editorPos.height); } exports.createEditorPagePosition = createEditorPagePosition; var EditorMouseEvent = /** @class */ (function (_super) { __extends(EditorMouseEvent, _super); function EditorMouseEvent(e, editorViewDomNode) { var _this = _super.call(this, e) || this; _this.pos = new PageCoordinates(_this.posx, _this.posy); _this.editorPos = createEditorPagePosition(editorViewDomNode); return _this; } return EditorMouseEvent; }(mouseEvent_1.StandardMouseEvent)); exports.EditorMouseEvent = EditorMouseEvent; var EditorMouseEventFactory = /** @class */ (function () { function EditorMouseEventFactory(editorViewDomNode) { this._editorViewDomNode = editorViewDomNode; } EditorMouseEventFactory.prototype._create = function (e) { return new EditorMouseEvent(e, this._editorViewDomNode); }; EditorMouseEventFactory.prototype.onContextMenu = function (target, callback) { var _this = this; return dom.addDisposableListener(target, 'contextmenu', function (e) { callback(_this._create(e)); }); }; EditorMouseEventFactory.prototype.onMouseUp = function (target, callback) { var _this = this; return dom.addDisposableListener(target, 'mouseup', function (e) { callback(_this._create(e)); }); }; EditorMouseEventFactory.prototype.onMouseDown = function (target, callback) { var _this = this; return dom.addDisposableListener(target, 'mousedown', function (e) { callback(_this._create(e)); }); }; EditorMouseEventFactory.prototype.onMouseLeave = function (target, callback) { var _this = this; return dom.addDisposableNonBubblingMouseOutListener(target, function (e) { callback(_this._create(e)); }); }; EditorMouseEventFactory.prototype.onMouseMoveThrottled = function (target, callback, merger, minimumTimeMs) { var _this = this; var myMerger = function (lastEvent, currentEvent) { return merger(lastEvent, _this._create(currentEvent)); }; return dom.addDisposableThrottledListener(target, 'mousemove', callback, myMerger, minimumTimeMs); }; return EditorMouseEventFactory; }()); exports.EditorMouseEventFactory = EditorMouseEventFactory; var EditorPointerEventFactory = /** @class */ (function () { function EditorPointerEventFactory(editorViewDomNode) { this._editorViewDomNode = editorViewDomNode; } EditorPointerEventFactory.prototype._create = function (e) { return new EditorMouseEvent(e, this._editorViewDomNode); }; EditorPointerEventFactory.prototype.onPointerUp = function (target, callback) { var _this = this; return dom.addDisposableListener(target, 'pointerup', function (e) { callback(_this._create(e)); }); }; EditorPointerEventFactory.prototype.onPointerDown = function (target, callback) { var _this = this; return dom.addDisposableListener(target, 'pointerdown', function (e) { callback(_this._create(e)); }); }; EditorPointerEventFactory.prototype.onPointerLeave = function (target, callback) { var _this = this; return dom.addDisposableNonBubblingPointerOutListener(target, function (e) { callback(_this._create(e)); }); }; EditorPointerEventFactory.prototype.onPointerMoveThrottled = function (target, callback, merger, minimumTimeMs) { var _this = this; var myMerger = function (lastEvent, currentEvent) { return merger(lastEvent, _this._create(currentEvent)); }; return dom.addDisposableThrottledListener(target, 'pointermove', callback, myMerger, minimumTimeMs); }; return EditorPointerEventFactory; }()); exports.EditorPointerEventFactory = EditorPointerEventFactory; var GlobalEditorMouseMoveMonitor = /** @class */ (function (_super) { __extends(GlobalEditorMouseMoveMonitor, _super); function GlobalEditorMouseMoveMonitor(editorViewDomNode) { var _this = _super.call(this) || this; _this._editorViewDomNode = editorViewDomNode; _this._globalMouseMoveMonitor = _this._register(new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor()); _this._keydownListener = null; return _this; } GlobalEditorMouseMoveMonitor.prototype.startMonitoring = function (initialElement, initialButtons, merger, mouseMoveCallback, onStopCallback) { var _this = this; // 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', function (e) { var kb = e.toKeybinding(); if (kb.isModifierKey()) { // Allow modifier keys return; } _this._globalMouseMoveMonitor.stopMonitoring(true); }, true); var myMerger = function (lastEvent, currentEvent) { return merger(lastEvent, new EditorMouseEvent(currentEvent, _this._editorViewDomNode)); }; this._globalMouseMoveMonitor.startMonitoring(initialElement, initialButtons, myMerger, mouseMoveCallback, function () { _this._keydownListener.dispose(); onStopCallback(); }); }; return GlobalEditorMouseMoveMonitor; }(lifecycle_1.Disposable)); exports.GlobalEditorMouseMoveMonitor = GlobalEditorMouseMoveMonitor; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[334/*vs/editor/browser/services/abstractCodeEditorService*/], __M([0/*require*/,1/*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 }); var AbstractCodeEditorService = /** @class */ (function (_super) { __extends(AbstractCodeEditorService, _super); function AbstractCodeEditorService() { var _this = _super.call(this) || this; _this._onCodeEditorAdd = _this._register(new event_1.Emitter()); _this.onCodeEditorAdd = _this._onCodeEditorAdd.event; _this._onCodeEditorRemove = _this._register(new event_1.Emitter()); _this.onCodeEditorRemove = _this._onCodeEditorRemove.event; _this._onDiffEditorAdd = _this._register(new event_1.Emitter()); _this._onDiffEditorRemove = _this._register(new event_1.Emitter()); _this._codeEditors = Object.create(null); _this._diffEditors = Object.create(null); return _this; } AbstractCodeEditorService.prototype.addCodeEditor = function (editor) { this._codeEditors[editor.getId()] = editor; this._onCodeEditorAdd.fire(editor); }; AbstractCodeEditorService.prototype.removeCodeEditor = function (editor) { if (delete this._codeEditors[editor.getId()]) { this._onCodeEditorRemove.fire(editor); } }; AbstractCodeEditorService.prototype.listCodeEditors = function () { var _this = this; return Object.keys(this._codeEditors).map(function (id) { return _this._codeEditors[id]; }); }; AbstractCodeEditorService.prototype.addDiffEditor = function (editor) { this._diffEditors[editor.getId()] = editor; this._onDiffEditorAdd.fire(editor); }; AbstractCodeEditorService.prototype.removeDiffEditor = function (editor) { if (delete this._diffEditors[editor.getId()]) { this._onDiffEditorRemove.fire(editor); } }; AbstractCodeEditorService.prototype.listDiffEditors = function () { var _this = this; return Object.keys(this._diffEditors).map(function (id) { return _this._diffEditors[id]; }); }; AbstractCodeEditorService.prototype.getFocusedCodeEditor = function () { var editorWithWidgetFocus = null; var editors = this.listCodeEditors(); for (var _i = 0, editors_1 = editors; _i < editors_1.length; _i++) { var editor = editors_1[_i]; if (editor.hasTextFocus()) { // bingo! return editor; } if (editor.hasWidgetFocus()) { editorWithWidgetFocus = editor; } } return editorWithWidgetFocus; }; return AbstractCodeEditorService; }(lifecycle_1.Disposable)); exports.AbstractCodeEditorService = AbstractCodeEditorService; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[186/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.allCharCodes = (function () { var v = []; for (var i = 32 /* START_CH_CODE */; i <= 126 /* END_CH_CODE */; i++) { v.push(i); } v.push(65533 /* UNKNOWN_CODE */); return v; })(); exports.getCharIndex = function (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; }; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[335/*vs/editor/browser/viewParts/minimap/minimapCharRenderer*/], __M([0/*require*/,1/*exports*/,186/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/]), function (require, exports, minimapCharSheet_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MinimapCharRenderer = /** @class */ (function () { function MinimapCharRenderer(charData, scale) { this.scale = scale; this.charDataNormal = MinimapCharRenderer.soften(charData, 12 / 15); this.charDataLight = MinimapCharRenderer.soften(charData, 50 / 60); } MinimapCharRenderer.soften = function (input, ratio) { var result = new Uint8ClampedArray(input.length); for (var i = 0, len = input.length; i < len; i++) { result[i] = input[i] * ratio; } return result; }; MinimapCharRenderer.prototype.renderChar = function (target, dx, dy, chCode, color, backgroundColor, fontScale, useLighterFont) { var charWidth = 1 /* BASE_CHAR_WIDTH */ * this.scale; var charHeight = 2 /* BASE_CHAR_HEIGHT */ * this.scale; if (dx + charWidth > target.width || dy + charHeight > target.height) { console.warn('bad render request outside image data'); return; } var charData = useLighterFont ? this.charDataLight : this.charDataNormal; var charIndex = minimapCharSheet_1.getCharIndex(chCode, fontScale); var destWidth = target.width * 4 /* RGBA_CHANNELS_CNT */; var backgroundR = backgroundColor.r; var backgroundG = backgroundColor.g; var backgroundB = backgroundColor.b; var deltaR = color.r - backgroundR; var deltaG = color.g - backgroundG; var deltaB = color.b - backgroundB; var dest = target.data; var sourceOffset = charIndex * charWidth * charHeight; var row = dy * destWidth + dx * 4 /* RGBA_CHANNELS_CNT */; for (var y = 0; y < charHeight; y++) { var column = row; for (var x = 0; x < charWidth; x++) { var c = charData[sourceOffset++] / 255; dest[column++] = backgroundR + deltaR * c; dest[column++] = backgroundG + deltaG * c; dest[column++] = backgroundB + deltaB * c; column++; } row += destWidth; } }; MinimapCharRenderer.prototype.blockRenderChar = function (target, dx, dy, color, backgroundColor, useLighterFont) { var charWidth = 1 /* BASE_CHAR_WIDTH */ * this.scale; var charHeight = 2 /* BASE_CHAR_HEIGHT */ * this.scale; if (dx + charWidth > target.width || dy + charHeight > target.height) { console.warn('bad render request outside image data'); return; } var destWidth = target.width * 4 /* RGBA_CHANNELS_CNT */; var c = 0.5; var backgroundR = backgroundColor.r; var backgroundG = backgroundColor.g; var backgroundB = backgroundColor.b; var deltaR = color.r - backgroundR; var deltaG = color.g - backgroundG; var deltaB = color.b - backgroundB; var colorR = backgroundR + deltaR * c; var colorG = backgroundG + deltaG * c; var colorB = backgroundB + deltaB * c; var dest = target.data; var row = dy * destWidth + dx * 4 /* RGBA_CHANNELS_CNT */; for (var y = 0; y < charHeight; y++) { var column = row; for (var x = 0; x < charWidth; x++) { dest[column++] = colorR; dest[column++] = colorG; dest[column++] = colorB; column++; } row += destWidth; } }; return MinimapCharRenderer; }()); 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[336/*vs/editor/browser/viewParts/minimap/minimapPreBaked*/], __M([0/*require*/,1/*exports*/,102/*vs/base/common/functional*/]), function (require, exports, functional_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var 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 }; var decodeData = function (str) { var output = new Uint8ClampedArray(str.length / 2); for (var 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: functional_1.once(function () { return decodeData('0000511D6300CF609C709645A78432005642574171487021003C451900274D35D762755E8B629C5BA856AF57BA649530C167D1512A272A3F6038604460398526BCA2A968DB6F8957C768BE5FBE2FB467CF5D8D5B795DC7625B5DFF50DE64C466DB2FC47CD860A65E9A2EB96CB54CE06DA763AB2EA26860524D3763536601005116008177A8705E53AB738E6A982F88BAA35B5F5B626D9C636B449B737E5B7B678598869A662F6B5B8542706C704C80736A607578685B70594A49715A4522E792'); }), 2: functional_1.once(function () { return 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[337/*vs/editor/browser/viewParts/minimap/minimapCharRendererFactory*/], __M([0/*require*/,1/*exports*/,335/*vs/editor/browser/viewParts/minimap/minimapCharRenderer*/,186/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/,336/*vs/editor/browser/viewParts/minimap/minimapPreBaked*/]), function (require, exports, minimapCharRenderer_1, minimapCharSheet_1, minimapPreBaked_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * 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. */ var MinimapCharRendererFactory = /** @class */ (function () { function MinimapCharRendererFactory() { } /** * Creates a new character renderer factory with the given scale. */ MinimapCharRendererFactory.create = function (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; } var 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. */ MinimapCharRendererFactory.createSampleData = function (fontFamily) { var canvas = document.createElement('canvas'); var 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'; var x = 0; for (var _i = 0, allCharCodes_1 = minimapCharSheet_1.allCharCodes; _i < allCharCodes_1.length; _i++) { var code = allCharCodes_1[_i]; 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. */ MinimapCharRendererFactory.createFromSampleData = function (source, scale) { var 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'); } var charData = MinimapCharRendererFactory._downsample(source, scale); return new minimapCharRenderer_1.MinimapCharRenderer(charData, scale); }; MinimapCharRendererFactory._downsampleChar = function (source, sourceOffset, dest, destOffset, scale) { var width = 1 /* BASE_CHAR_WIDTH */ * scale; var height = 2 /* BASE_CHAR_HEIGHT */ * scale; var targetIndex = destOffset; var 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 (var 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) var sourceY1 = (y / height) * 16 /* SAMPLED_CHAR_HEIGHT */; var sourceY2 = ((y + 1) / height) * 16 /* SAMPLED_CHAR_HEIGHT */; for (var x = 0; x < width; x++) { var sourceX1 = (x / width) * 10 /* SAMPLED_CHAR_WIDTH */; var sourceX2 = ((x + 1) / width) * 10 /* SAMPLED_CHAR_WIDTH */; // 2. Sample all of them, summing them up and weighting them. Similar // to bilinear interpolation. var value = 0; var samples = 0; for (var sy = sourceY1; sy < sourceY2; sy++) { var sourceRow = sourceOffset + Math.floor(sy) * 3840 /* RGBA_SAMPLED_ROW_WIDTH */; var yBalance = 1 - (sy - Math.floor(sy)); for (var sx = sourceX1; sx < sourceX2; sx++) { var xBalance = 1 - (sx - Math.floor(sx)); var sourceIndex = sourceRow + Math.floor(sx) * 4 /* RGBA_CHANNELS_CNT */; var weight = xBalance * yBalance; samples += weight; value += ((source[sourceIndex] * source[sourceIndex + 3]) / 255) * weight; } } var final = value / samples; brightest = Math.max(brightest, final); dest[targetIndex++] = final; } } return brightest; }; MinimapCharRendererFactory._downsample = function (data, scale) { var pixelsPerCharacter = 2 /* BASE_CHAR_HEIGHT */ * scale * 1 /* BASE_CHAR_WIDTH */ * scale; var resultLen = pixelsPerCharacter * 96 /* CHAR_COUNT */; var result = new Uint8ClampedArray(resultLen); var resultOffset = 0; var sourceOffset = 0; var brightest = 0; for (var 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) { var adjust = 255 / brightest; for (var i = 0; i < resultLen; i++) { result[i] *= adjust; } } return result; }; return MinimapCharRendererFactory; }()); 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[105/*vs/editor/common/config/editorZoom*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/]), function (require, exports, event_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EditorZoom = new /** @class */ (function () { function class_1() { this._zoomLevel = 0; this._onDidChangeZoomLevel = new event_1.Emitter(); this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event; } class_1.prototype.getZoomLevel = function () { return this._zoomLevel; }; class_1.prototype.setZoomLevel = function (zoomLevel) { zoomLevel = Math.min(Math.max(-5, zoomLevel), 20); if (this._zoomLevel === zoomLevel) { return; } this._zoomLevel = zoomLevel; this._onDidChangeZoomLevel.fire(this._zoomLevel); }; return class_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[142/*vs/editor/common/config/fontInfo*/], __M([0/*require*/,1/*exports*/,16/*vs/base/common/platform*/,105/*vs/editor/common/config/editorZoom*/]), function (require, exports, platform, editorZoom_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Determined from empirical observations. * @internal */ var GOLDEN_LINE_HEIGHT_RATIO = platform.isMacintosh ? 1.5 : 1.35; /** * @internal */ var MINIMUM_LINE_HEIGHT = 8; var BareFontInfo = /** @class */ (function () { /** * @internal */ function BareFontInfo(opts) { this.zoomLevel = opts.zoomLevel; 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 */ BareFontInfo.createFromValidatedSettings = function (options, zoomLevel, ignoreEditorZoom) { var fontFamily = options.get(33 /* fontFamily */); var fontWeight = options.get(37 /* fontWeight */); var fontSize = options.get(36 /* fontSize */); var fontFeatureSettings = options.get(35 /* fontLigatures */); var lineHeight = options.get(49 /* lineHeight */); var letterSpacing = options.get(46 /* letterSpacing */); return BareFontInfo._create(fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, zoomLevel, ignoreEditorZoom); }; /** * @internal */ BareFontInfo._create = function (fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, zoomLevel, ignoreEditorZoom) { if (lineHeight === 0) { lineHeight = Math.round(GOLDEN_LINE_HEIGHT_RATIO * fontSize); } else if (lineHeight < MINIMUM_LINE_HEIGHT) { lineHeight = MINIMUM_LINE_HEIGHT; } var editorZoomLevelMultiplier = 1 + (ignoreEditorZoom ? 0 : editorZoom_1.EditorZoom.getZoomLevel() * 0.1); fontSize *= editorZoomLevelMultiplier; lineHeight *= editorZoomLevelMultiplier; return new BareFontInfo({ zoomLevel: zoomLevel, fontFamily: fontFamily, fontWeight: fontWeight, fontSize: fontSize, fontFeatureSettings: fontFeatureSettings, lineHeight: lineHeight, letterSpacing: letterSpacing }); }; /** * @internal */ BareFontInfo.prototype.getId = function () { return this.zoomLevel + '-' + this.fontFamily + '-' + this.fontWeight + '-' + this.fontSize + '-' + this.fontFeatureSettings + '-' + this.lineHeight + '-' + this.letterSpacing; }; /** * @internal */ BareFontInfo.prototype.getMassagedFontFamily = function () { if (/[,"']/.test(this.fontFamily)) { // Looks like the font family might be already escaped return this.fontFamily; } if (/[+ ]/.test(this.fontFamily)) { // Wrap a font family using + or with quotes return "\"" + this.fontFamily + "\""; } return this.fontFamily; }; return BareFontInfo; }()); exports.BareFontInfo = BareFontInfo; var FontInfo = /** @class */ (function (_super) { __extends(FontInfo, _super); /** * @internal */ function FontInfo(opts, isTrusted) { var _this = _super.call(this, opts) || this; _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.maxDigitWidth = opts.maxDigitWidth; return _this; } /** * @internal */ FontInfo.prototype.equals = function (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.maxDigitWidth === other.maxDigitWidth); }; return FontInfo; }(BareFontInfo)); 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[79/*vs/editor/common/core/characterClassifier*/], __M([0/*require*/,1/*exports*/,179/*vs/base/common/uint*/]), function (require, exports, uint_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * A fast character classifier that uses a compact array for ASCII values. */ var CharacterClassifier = /** @class */ (function () { function CharacterClassifier(_defaultValue) { var defaultValue = uint_1.toUint8(_defaultValue); this._defaultValue = defaultValue; this._asciiMap = CharacterClassifier._createAsciiMap(defaultValue); this._map = new Map(); } CharacterClassifier._createAsciiMap = function (defaultValue) { var asciiMap = new Uint8Array(256); for (var i = 0; i < 256; i++) { asciiMap[i] = defaultValue; } return asciiMap; }; CharacterClassifier.prototype.set = function (charCode, _value) { var value = uint_1.toUint8(_value); if (charCode >= 0 && charCode < 256) { this._asciiMap[charCode] = value; } else { this._map.set(charCode, value); } }; CharacterClassifier.prototype.get = function (charCode) { if (charCode >= 0 && charCode < 256) { return this._asciiMap[charCode]; } else { return (this._map.get(charCode) || this._defaultValue); } }; return CharacterClassifier; }()); exports.CharacterClassifier = CharacterClassifier; var CharacterSet = /** @class */ (function () { function CharacterSet() { this._actual = new CharacterClassifier(0 /* False */); } CharacterSet.prototype.add = function (charCode) { this._actual.set(charCode, 1 /* True */); }; CharacterSet.prototype.has = function (charCode) { return (this._actual.get(charCode) === 1 /* True */); }; return CharacterSet; }()); 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[89/*vs/editor/common/controller/wordCharacterClassifier*/], __M([0/*require*/,1/*exports*/,79/*vs/editor/common/core/characterClassifier*/]), function (require, exports, characterClassifier_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var WordCharacterClassifier = /** @class */ (function (_super) { __extends(WordCharacterClassifier, _super); function WordCharacterClassifier(wordSeparators) { var _this = _super.call(this, 0 /* Regular */) || this; for (var 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 */); return _this; } return WordCharacterClassifier; }(characterClassifier_1.CharacterClassifier)); exports.WordCharacterClassifier = WordCharacterClassifier; function once(computeFn) { var cache = {}; // TODO@Alex unbounded cache return function (input) { if (!cache.hasOwnProperty(input)) { cache[input] = computeFn(input); } return cache[input]; }; } exports.getMapForWordSeparators = once(function (input) { return new WordCharacterClassifier(input); }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[13/*vs/editor/common/core/position*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * A position in the editor. */ var Position = /** @class */ (function () { function Position(lineNumber, column) { this.lineNumber = lineNumber; this.column = column; } /** * Create a new position from this position. * * @param newLineNumber new line number * @param newColumn new column */ Position.prototype.with = function (newLineNumber, newColumn) { if (newLineNumber === void 0) { newLineNumber = this.lineNumber; } if (newColumn === void 0) { 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 */ Position.prototype.delta = function (deltaLineNumber, deltaColumn) { if (deltaLineNumber === void 0) { deltaLineNumber = 0; } if (deltaColumn === void 0) { deltaColumn = 0; } return this.with(this.lineNumber + deltaLineNumber, this.column + deltaColumn); }; /** * Test if this position equals other position */ Position.prototype.equals = function (other) { return Position.equals(this, other); }; /** * Test if position `a` equals position `b` */ Position.equals = function (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. */ Position.prototype.isBefore = function (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. */ Position.isBefore = function (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. */ Position.prototype.isBeforeOrEqual = function (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. */ Position.isBeforeOrEqual = function (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 */ Position.compare = function (a, b) { var aLineNumber = a.lineNumber | 0; var bLineNumber = b.lineNumber | 0; if (aLineNumber === bLineNumber) { var aColumn = a.column | 0; var bColumn = b.column | 0; return aColumn - bColumn; } return aLineNumber - bLineNumber; }; /** * Clone this position. */ Position.prototype.clone = function () { return new Position(this.lineNumber, this.column); }; /** * Convert to a human-readable representation. */ Position.prototype.toString = function () { return '(' + this.lineNumber + ',' + this.column + ')'; }; // --- /** * Create a `Position` from an `IPosition`. */ Position.lift = function (pos) { return new Position(pos.lineNumber, pos.column); }; /** * Test if `obj` is an `IPosition`. */ Position.isIPosition = function (obj) { return (obj && (typeof obj.lineNumber === 'number') && (typeof obj.column === 'number')); }; return Position; }()); exports.Position = Position; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[3/*vs/editor/common/core/range*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/]), function (require, exports, position_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * A range in the editor. (startLineNumber,startColumn) is <= (endLineNumber,endColumn) */ var Range = /** @class */ (function () { function Range(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. */ Range.prototype.isEmpty = function () { return Range.isEmpty(this); }; /** * Test if `range` is empty. */ Range.isEmpty = function (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. */ Range.prototype.containsPosition = function (position) { return Range.containsPosition(this, position); }; /** * Test if `position` is in `range`. If the position is at the edges, will return true. */ Range.containsPosition = function (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. */ Range.prototype.containsRange = function (range) { return Range.containsRange(this, range); }; /** * Test if `otherRange` is in `range`. If the ranges are equal, will return true. */ Range.containsRange = function (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. */ Range.prototype.strictContainsRange = function (range) { return Range.strictContainsRange(this, range); }; /** * Test if `otherRange` is strinctly in `range` (must start after, and end before). If the ranges are equal, will return false. */ Range.strictContainsRange = function (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. */ Range.prototype.plusRange = function (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. */ Range.plusRange = function (a, b) { var startLineNumber; var startColumn; var endLineNumber; var 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. */ Range.prototype.intersectRanges = function (range) { return Range.intersectRanges(this, range); }; /** * A intersection of the two ranges. */ Range.intersectRanges = function (a, b) { var resultStartLineNumber = a.startLineNumber; var resultStartColumn = a.startColumn; var resultEndLineNumber = a.endLineNumber; var resultEndColumn = a.endColumn; var otherStartLineNumber = b.startLineNumber; var otherStartColumn = b.startColumn; var otherEndLineNumber = b.endLineNumber; var 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. */ Range.prototype.equalsRange = function (other) { return Range.equalsRange(this, other); }; /** * Test if range `a` equals `b`. */ Range.equalsRange = function (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) */ Range.prototype.getEndPosition = function () { return new position_1.Position(this.endLineNumber, this.endColumn); }; /** * Return the start position (which will be before or equal to the end position) */ Range.prototype.getStartPosition = function () { return new position_1.Position(this.startLineNumber, this.startColumn); }; /** * Transform to a user presentable string representation. */ Range.prototype.toString = function () { 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. */ Range.prototype.setEndPosition = function (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. */ Range.prototype.setStartPosition = function (startLineNumber, startColumn) { return new Range(startLineNumber, startColumn, this.endLineNumber, this.endColumn); }; /** * Create a new empty range using this range's start position. */ Range.prototype.collapseToStart = function () { return Range.collapseToStart(this); }; /** * Create a new empty range using this range's start position. */ Range.collapseToStart = function (range) { return new Range(range.startLineNumber, range.startColumn, range.startLineNumber, range.startColumn); }; // --- Range.fromPositions = function (start, end) { if (end === void 0) { end = start; } return new Range(start.lineNumber, start.column, end.lineNumber, end.column); }; Range.lift = function (range) { if (!range) { return null; } return new Range(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn); }; /** * Test if `obj` is an `IRange`. */ Range.isIRange = function (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. */ Range.areIntersectingOrTouching = function (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. */ Range.areIntersecting = function (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 */ Range.compareRangesUsingStarts = function (a, b) { if (a && b) { var aStartLineNumber = a.startLineNumber | 0; var bStartLineNumber = b.startLineNumber | 0; if (aStartLineNumber === bStartLineNumber) { var aStartColumn = a.startColumn | 0; var bStartColumn = b.startColumn | 0; if (aStartColumn === bStartColumn) { var aEndLineNumber = a.endLineNumber | 0; var bEndLineNumber = b.endLineNumber | 0; if (aEndLineNumber === bEndLineNumber) { var aEndColumn = a.endColumn | 0; var bEndColumn = b.endColumn | 0; return aEndColumn - bEndColumn; } return aEndLineNumber - bEndLineNumber; } return aStartColumn - bStartColumn; } return aStartLineNumber - bStartLineNumber; } var aExists = (a ? 1 : 0); var 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 */ Range.compareRangesUsingEnds = function (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. */ Range.spansMultipleLines = function (range) { return range.endLineNumber > range.startLineNumber; }; return Range; }()); exports.Range = Range; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[187/*vs/editor/browser/controller/textAreaState*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings, position_1, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var TextAreaState = /** @class */ (function () { function TextAreaState(value, selectionStart, selectionEnd, selectionStartPosition, selectionEndPosition) { this.value = value; this.selectionStart = selectionStart; this.selectionEnd = selectionEnd; this.selectionStartPosition = selectionStartPosition; this.selectionEndPosition = selectionEndPosition; } TextAreaState.prototype.toString = function () { return '[ <' + this.value + '>, selectionStart: ' + this.selectionStart + ', selectionEnd: ' + this.selectionEnd + ']'; }; TextAreaState.readFromTextArea = function (textArea) { return new TextAreaState(textArea.getValue(), textArea.getSelectionStart(), textArea.getSelectionEnd(), null, null); }; TextAreaState.prototype.collapseSelection = function () { return new TextAreaState(this.value, this.value.length, this.value.length, null, null); }; TextAreaState.prototype.writeToTextArea = function (reason, textArea, select) { // console.log(Date.now() + ': writeToTextArea ' + reason + ': ' + this.toString()); textArea.setValue(reason, this.value); if (select) { textArea.setSelectionRange(reason, this.selectionStart, this.selectionEnd); } }; TextAreaState.prototype.deduceEditorPosition = function (offset) { if (offset <= this.selectionStart) { var str = this.value.substring(offset, this.selectionStart); return this._finishDeduceEditorPosition(this.selectionStartPosition, str, -1); } if (offset >= this.selectionEnd) { var str = this.value.substring(this.selectionEnd, offset); return this._finishDeduceEditorPosition(this.selectionEndPosition, str, 1); } var str1 = this.value.substring(this.selectionStart, offset); if (str1.indexOf(String.fromCharCode(8230)) === -1) { return this._finishDeduceEditorPosition(this.selectionStartPosition, str1, 1); } var str2 = this.value.substring(offset, this.selectionEnd); return this._finishDeduceEditorPosition(this.selectionEndPosition, str2, -1); }; TextAreaState.prototype._finishDeduceEditorPosition = function (anchor, deltaText, signum) { var lineFeedCnt = 0; var lastLineFeedIndex = -1; while ((lastLineFeedIndex = deltaText.indexOf('\n', lastLineFeedIndex + 1)) !== -1) { lineFeedCnt++; } return [anchor, signum * deltaText.length, lineFeedCnt]; }; TextAreaState.selectedText = function (text) { return new TextAreaState(text, 0, text.length, null, null); }; TextAreaState.deduceInput = function (previousState, currentState, couldBeEmojiInput) { if (!previousState) { // This is the EMPTY state return { text: '', replaceCharCnt: 0 }; } // console.log('------------------------deduceInput'); // console.log('PREVIOUS STATE: ' + previousState.toString()); // console.log('CURRENT STATE: ' + currentState.toString()); var previousValue = previousState.value; var previousSelectionStart = previousState.selectionStart; var previousSelectionEnd = previousState.selectionEnd; var currentValue = currentState.value; var currentSelectionStart = currentState.selectionStart; var currentSelectionEnd = currentState.selectionEnd; // Strip the previous suffix from the value (without interfering with the current selection) var previousSuffix = previousValue.substring(previousSelectionEnd); var currentSuffix = currentValue.substring(currentSelectionEnd); var suffixLength = strings.commonSuffixLength(previousSuffix, currentSuffix); currentValue = currentValue.substring(0, currentValue.length - suffixLength); previousValue = previousValue.substring(0, previousValue.length - suffixLength); var previousPrefix = previousValue.substring(0, previousSelectionStart); var currentPrefix = currentValue.substring(0, currentSelectionStart); var prefixLength = strings.commonPrefixLength(previousPrefix, currentPrefix); currentValue = currentValue.substring(prefixLength); previousValue = previousValue.substring(prefixLength); currentSelectionStart -= prefixLength; previousSelectionStart -= prefixLength; currentSelectionEnd -= prefixLength; previousSelectionEnd -= prefixLength; // console.log('AFTER DIFFING PREVIOUS STATE: <' + previousValue + '>, selectionStart: ' + previousSelectionStart + ', selectionEnd: ' + previousSelectionEnd); // console.log('AFTER DIFFING CURRENT STATE: <' + currentValue + '>, selectionStart: ' + currentSelectionStart + ', selectionEnd: ' + currentSelectionEnd); if (couldBeEmojiInput && currentSelectionStart === currentSelectionEnd && previousValue.length > 0) { // on OSX, emojis from the emoji picker are inserted at random locations // the only hints we can use is that the selection is immediately after the inserted emoji // and that none of the old text has been deleted var potentialEmojiInput = null; if (currentSelectionStart === currentValue.length) { // emoji potentially inserted "somewhere" after the previous selection => it should appear at the end of `currentValue` if (strings.startsWith(currentValue, previousValue)) { // only if all of the old text is accounted for potentialEmojiInput = currentValue.substring(previousValue.length); } } else { // emoji potentially inserted "somewhere" before the previous selection => it should appear at the start of `currentValue` if (strings.endsWith(currentValue, previousValue)) { // only if all of the old text is accounted for potentialEmojiInput = currentValue.substring(0, currentValue.length - previousValue.length); } } if (potentialEmojiInput !== null && potentialEmojiInput.length > 0) { // now we check that this is indeed an emoji // emojis can grow quite long, so a length check is of no help // e.g. 1F3F4 E0067 E0062 E0065 E006E E0067 E007F ; fully-qualified # 🏴󠁧󠁢󠁥󠁮󠁧󠁿 England // Oftentimes, emojis use Variation Selector-16 (U+FE0F), so that is a good hint // http://emojipedia.org/variation-selector-16/ // > An invisible codepoint which specifies that the preceding character // > should be displayed with emoji presentation. Only required if the // > preceding character defaults to text presentation. if (/\uFE0F/.test(potentialEmojiInput) || strings.containsEmoji(potentialEmojiInput)) { return { text: potentialEmojiInput, replaceCharCnt: 0 }; } } } if (currentSelectionStart === currentSelectionEnd) { // composition accept case (noticed in FF + Japanese) // [blahblah] => blahblah| if (previousValue === currentValue && previousSelectionStart === 0 && previousSelectionEnd === previousValue.length && currentSelectionStart === currentValue.length && currentValue.indexOf('\n') === -1) { if (strings.containsFullWidthCharacter(currentValue)) { return { text: '', replaceCharCnt: 0 }; } } // no current selection var replacePreviousCharacters_1 = (previousPrefix.length - prefixLength); // console.log('REMOVE PREVIOUS: ' + (previousPrefix.length - prefixLength) + ' chars'); return { text: currentValue, replaceCharCnt: replacePreviousCharacters_1 }; } // there is a current selection => composition case var replacePreviousCharacters = previousSelectionEnd - previousSelectionStart; return { text: currentValue, replaceCharCnt: replacePreviousCharacters }; }; TextAreaState.EMPTY = new TextAreaState('', 0, 0, null, null); return TextAreaState; }()); exports.TextAreaState = TextAreaState; var PagedScreenReaderStrategy = /** @class */ (function () { function PagedScreenReaderStrategy() { } PagedScreenReaderStrategy._getPageOfLine = function (lineNumber, linesPerPage) { return Math.floor((lineNumber - 1) / linesPerPage); }; PagedScreenReaderStrategy._getRangeForPage = function (page, linesPerPage) { var offset = page * linesPerPage; var startLineNumber = offset + 1; var endLineNumber = offset + linesPerPage; return new range_1.Range(startLineNumber, 1, endLineNumber + 1, 1); }; PagedScreenReaderStrategy.fromEditorSelection = function (previousState, model, selection, linesPerPage, trimLongText) { var selectionStartPage = PagedScreenReaderStrategy._getPageOfLine(selection.startLineNumber, linesPerPage); var selectionStartPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionStartPage, linesPerPage); var selectionEndPage = PagedScreenReaderStrategy._getPageOfLine(selection.endLineNumber, linesPerPage); var selectionEndPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionEndPage, linesPerPage); var pretextRange = selectionStartPageRange.intersectRanges(new range_1.Range(1, 1, selection.startLineNumber, selection.startColumn)); var pretext = model.getValueInRange(pretextRange, 1 /* LF */); var lastLine = model.getLineCount(); var lastLineMaxColumn = model.getLineMaxColumn(lastLine); var posttextRange = selectionEndPageRange.intersectRanges(new range_1.Range(selection.endLineNumber, selection.endColumn, lastLine, lastLineMaxColumn)); var posttext = model.getValueInRange(posttextRange, 1 /* LF */); var text; if (selectionStartPage === selectionEndPage || selectionStartPage + 1 === selectionEndPage) { // take full selection text = model.getValueInRange(selection, 1 /* LF */); } else { var selectionRange1 = selectionStartPageRange.intersectRanges(selection); var 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) { var 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)); }; return PagedScreenReaderStrategy; }()); 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[188/*vs/editor/browser/widget/diffNavigator*/], __M([0/*require*/,1/*exports*/,124/*vs/base/common/assert*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,31/*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 }); var defaultOptions = { followsCaret: true, ignoreCharChanges: true, alwaysRevealFirst: true }; /** * Create a new diff navigator for the provided diff editor. */ var DiffNavigator = /** @class */ (function (_super) { __extends(DiffNavigator, _super); function DiffNavigator(editor, options) { if (options === void 0) { options = {}; } var _this = _super.call(this) || this; _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(function () { return _this.dispose(); })); _this._register(_this._editor.onDidUpdateDiff(function () { return _this._onDiffUpdated(); })); if (_this._options.followsCaret) { _this._register(_this._editor.getModifiedEditor().onDidChangeCursorPosition(function (e) { if (_this.ignoreSelectionChange) { return; } _this.nextIdx = -1; })); } if (_this._options.alwaysRevealFirst) { _this._register(_this._editor.getModifiedEditor().onDidChangeModel(function (e) { _this.revealFirst = true; })); } // init things _this._init(); return _this; } DiffNavigator.prototype._init = function () { var changes = this._editor.getLineChanges(); if (!changes) { return; } }; DiffNavigator.prototype._onDiffUpdated = function () { 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 */); } } }; DiffNavigator.prototype._compute = function (lineChanges) { var _this = this; // new ranges this.ranges = []; if (lineChanges) { // create ranges from changes lineChanges.forEach(function (lineChange) { if (!_this._options.ignoreCharChanges && lineChange.charChanges) { lineChange.charChanges.forEach(function (charChange) { _this.ranges.push({ rhs: true, range: new range_1.Range(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn) }); }); } else { _this.ranges.push({ rhs: true, range: new range_1.Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedStartLineNumber, 1) }); } }); } // sort this.ranges.sort(function (left, right) { if (left.range.getStartPosition().isBeforeOrEqual(right.range.getStartPosition())) { return -1; } else if (right.range.getStartPosition().isBeforeOrEqual(left.range.getStartPosition())) { return 1; } else { return 0; } }); this._onDidUpdate.fire(this); }; DiffNavigator.prototype._initIdx = function (fwd) { var found = false; var position = this._editor.getPosition(); if (!position) { this.nextIdx = 0; return; } for (var i = 0, len = this.ranges.length; i < len && !found; i++) { var 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; } }; DiffNavigator.prototype._move = function (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; } } var info = this.ranges[this.nextIdx]; this.ignoreSelectionChange = true; try { var pos = info.range.getStartPosition(); this._editor.setPosition(pos); this._editor.revealPositionInCenter(pos, scrollType); } finally { this.ignoreSelectionChange = false; } }; DiffNavigator.prototype.canNavigate = function () { return this.ranges && this.ranges.length > 0; }; DiffNavigator.prototype.next = function (scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this._move(true, scrollType); }; DiffNavigator.prototype.previous = function (scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this._move(false, scrollType); }; DiffNavigator.prototype.dispose = function () { _super.prototype.dispose.call(this); this.ranges = []; this.disposed = true; }; return DiffNavigator; }(lifecycle_1.Disposable)); 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[58/*vs/editor/common/core/editOperation*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/]), function (require, exports, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var EditOperation = /** @class */ (function () { function EditOperation() { } EditOperation.insert = function (position, text) { return { range: new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column), text: text, forceMoveMarkers: true }; }; EditOperation.delete = function (range) { return { range: range, text: null }; }; EditOperation.replace = function (range, text) { return { range: range, text: text }; }; EditOperation.replaceMove = function (range, text) { return { range: range, text: text, forceMoveMarkers: true }; }; return EditOperation; }()); 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[338/*vs/editor/common/commands/trimTrailingWhitespaceCommand*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,58/*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 }); var TrimTrailingWhitespaceCommand = /** @class */ (function () { function TrimTrailingWhitespaceCommand(selection, cursors) { this._selection = selection; this._cursors = cursors; this._selectionId = null; } TrimTrailingWhitespaceCommand.prototype.getEditOperations = function (model, builder) { var ops = trimTrailingWhitespace(model, this._cursors); for (var i = 0, len = ops.length; i < len; i++) { var op = ops[i]; builder.addEditOperation(op.range, op.text); } this._selectionId = builder.trackSelection(this._selection); }; TrimTrailingWhitespaceCommand.prototype.computeCursorState = function (model, helper) { return helper.getTrackedSelection(this._selectionId); }; return TrimTrailingWhitespaceCommand; }()); 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(function (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 (var i = cursors.length - 2; i >= 0; i--) { if (cursors[i].lineNumber === cursors[i + 1].lineNumber) { // Remove cursor at `i` cursors.splice(i, 1); } } var r = []; var rLen = 0; var cursorIndex = 0; var cursorLen = cursors.length; for (var lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) { var lineContent = model.getLineContent(lineNumber); var maxLineColumn = lineContent.length + 1; var 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; } var lastNonWhitespaceIndex = strings.lastNonWhitespaceIndex(lineContent); var 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[339/*vs/editor/common/core/rgba*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * A very VM friendly rgba datastructure. * Please don't touch unless you take a look at the IR. */ var RGBA8 = /** @class */ (function () { function RGBA8(r, g, b, a) { this.r = RGBA8._clamp(r); this.g = RGBA8._clamp(g); this.b = RGBA8._clamp(b); this.a = RGBA8._clamp(a); } RGBA8._clamp = function (c) { if (c < 0) { return 0; } if (c > 255) { return 255; } return c | 0; }; RGBA8.Empty = new RGBA8(0, 0, 0, 0); return RGBA8; }()); exports.RGBA8 = RGBA8; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[22/*vs/editor/common/core/selection*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, position_1, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * A selection in the editor. * The selection is a range that has an orientation. */ var Selection = /** @class */ (function (_super) { __extends(Selection, _super); function Selection(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn) { var _this = _super.call(this, selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn) || this; _this.selectionStartLineNumber = selectionStartLineNumber; _this.selectionStartColumn = selectionStartColumn; _this.positionLineNumber = positionLineNumber; _this.positionColumn = positionColumn; return _this; } /** * Transform to a human-readable representation. */ Selection.prototype.toString = function () { return '[' + this.selectionStartLineNumber + ',' + this.selectionStartColumn + ' -> ' + this.positionLineNumber + ',' + this.positionColumn + ']'; }; /** * Test if equals other selection. */ Selection.prototype.equalsSelection = function (other) { return (Selection.selectionsEqual(this, other)); }; /** * Test if the two selections are equal. */ Selection.selectionsEqual = function (a, b) { return (a.selectionStartLineNumber === b.selectionStartLineNumber && a.selectionStartColumn === b.selectionStartColumn && a.positionLineNumber === b.positionLineNumber && a.positionColumn === b.positionColumn); }; /** * Get directions (LTR or RTL). */ Selection.prototype.getDirection = function () { 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`. */ Selection.prototype.setEndPosition = function (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`. */ Selection.prototype.getPosition = function () { return new position_1.Position(this.positionLineNumber, this.positionColumn); }; /** * Create a new selection with a different `selectionStartLineNumber` and `selectionStartColumn`. */ Selection.prototype.setStartPosition = function (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 */ Selection.fromPositions = function (start, end) { if (end === void 0) { end = start; } return new Selection(start.lineNumber, start.column, end.lineNumber, end.column); }; /** * Create a `Selection` from an `ISelection`. */ Selection.liftSelection = function (sel) { return new Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn); }; /** * `a` equals `b`. */ Selection.selectionsArrEqual = function (a, b) { if (a && !b || !a && b) { return false; } if (!a && !b) { return true; } if (a.length !== b.length) { return false; } for (var 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`. */ Selection.isISelection = function (obj) { return (obj && (typeof obj.selectionStartLineNumber === 'number') && (typeof obj.selectionStartColumn === 'number') && (typeof obj.positionLineNumber === 'number') && (typeof obj.positionColumn === 'number')); }; /** * Create with a direction. */ Selection.createWithDirection = function (startLineNumber, startColumn, endLineNumber, endColumn, direction) { if (direction === 0 /* LTR */) { return new Selection(startLineNumber, startColumn, endLineNumber, endColumn); } return new Selection(endLineNumber, endColumn, startLineNumber, startColumn); }; return Selection; }(range_1.Range)); 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[189/*vs/editor/browser/controller/textAreaInput*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,6/*vs/base/browser/dom*/,15/*vs/base/common/async*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,5/*vs/base/common/strings*/,187/*vs/editor/browser/controller/textAreaState*/,22/*vs/editor/common/core/selection*/,88/*vs/base/browser/canIUse*/]), function (require, exports, browser, dom, async_1, event_1, lifecycle_1, platform, strings, textAreaState_1, selection_1, canIUse_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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. */ var InMemoryClipboardMetadataManager = /** @class */ (function () { function InMemoryClipboardMetadataManager() { this._lastState = null; } InMemoryClipboardMetadataManager.prototype.set = function (lastCopiedValue, data) { this._lastState = { lastCopiedValue: lastCopiedValue, data: data }; }; InMemoryClipboardMetadataManager.prototype.get = function (pastedText) { if (this._lastState && this._lastState.lastCopiedValue === pastedText) { // match! return this._lastState.data; } this._lastState = null; return null; }; InMemoryClipboardMetadataManager.INSTANCE = new InMemoryClipboardMetadataManager(); return InMemoryClipboardMetadataManager; }()); /** * Writes screen reader content to the textarea and is able to analyze its input events to generate: * - onCut * - onPaste * - onType * * Composition events are generated for presentation purposes (composition input is reflected in onType). */ var TextAreaInput = /** @class */ (function (_super) { __extends(TextAreaInput, _super); function TextAreaInput(host, textArea) { var _this = _super.call(this) || this; _this.textArea = textArea; _this._onFocus = _this._register(new event_1.Emitter()); _this.onFocus = _this._onFocus.event; _this._onBlur = _this._register(new event_1.Emitter()); _this.onBlur = _this._onBlur.event; _this._onKeyDown = _this._register(new event_1.Emitter()); _this.onKeyDown = _this._onKeyDown.event; _this._onKeyUp = _this._register(new event_1.Emitter()); _this.onKeyUp = _this._onKeyUp.event; _this._onCut = _this._register(new event_1.Emitter()); _this.onCut = _this._onCut.event; _this._onPaste = _this._register(new event_1.Emitter()); _this.onPaste = _this._onPaste.event; _this._onType = _this._register(new event_1.Emitter()); _this.onType = _this._onType.event; _this._onCompositionStart = _this._register(new event_1.Emitter()); _this.onCompositionStart = _this._onCompositionStart.event; _this._onCompositionUpdate = _this._register(new event_1.Emitter()); _this.onCompositionUpdate = _this._onCompositionUpdate.event; _this._onCompositionEnd = _this._register(new event_1.Emitter()); _this.onCompositionEnd = _this._onCompositionEnd.event; _this._onSelectionChangeRequest = _this._register(new event_1.Emitter()); _this.onSelectionChangeRequest = _this._onSelectionChangeRequest.event; _this._host = host; _this._textArea = _this._register(new TextAreaWrapper(textArea)); _this._asyncTriggerCut = _this._register(new async_1.RunOnceScheduler(function () { return _this._onCut.fire(); }, 0)); _this._textAreaState = textAreaState_1.TextAreaState.EMPTY; _this._selectionChangeListener = null; _this.writeScreenReaderContent('ctor'); _this._hasFocus = false; _this._isDoingComposition = false; _this._nextCommand = 0 /* Type */; _this._register(dom.addStandardDisposableListener(textArea.domNode, 'keydown', function (e) { if (_this._isDoingComposition && (e.keyCode === 109 /* KEY_IN_COMPOSITION */ || 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(); } _this._onKeyDown.fire(e); })); _this._register(dom.addStandardDisposableListener(textArea.domNode, 'keyup', function (e) { _this._onKeyUp.fire(e); })); _this._register(dom.addDisposableListener(textArea.domNode, 'compositionstart', function (e) { if (_this._isDoingComposition) { return; } _this._isDoingComposition = true; // In IE we cannot set .value when handling 'compositionstart' because the entire composition will get canceled. if (!browser.isEdgeOrIE) { _this._setAndWriteTextAreaState('compositionstart', textAreaState_1.TextAreaState.EMPTY); } _this._onCompositionStart.fire(); })); /** * Deduce the typed input from a text area's value and the last observed state. */ var deduceInputFromTextAreaValue = function (couldBeEmojiInput) { var oldState = _this._textAreaState; var newState = textAreaState_1.TextAreaState.readFromTextArea(_this._textArea); return [newState, textAreaState_1.TextAreaState.deduceInput(oldState, newState, couldBeEmojiInput)]; }; /** * Deduce the composition input from a string. */ var deduceComposition = function (text) { var oldState = _this._textAreaState; var newState = textAreaState_1.TextAreaState.selectedText(text); var typeInput = { text: newState.value, replaceCharCnt: oldState.selectionEnd - oldState.selectionStart }; return [newState, typeInput]; }; var compositionDataInValid = function (locale) { // https://github.com/Microsoft/monaco-editor/issues/339 // Multi-part Japanese compositions reset cursor in Edge/IE, Chinese and Korean IME don't have this issue. // The reason that we can't use this path for all CJK IME is IE and Edge behave differently when handling Korean IME, // which breaks this path of code. if (browser.isEdgeOrIE && locale === 'ja') { return true; } // https://github.com/Microsoft/monaco-editor/issues/545 // On IE11, we can't trust composition data when typing Chinese as IE11 doesn't emit correct // events when users type numbers in IME. // Chinese: zh-Hans-CN, zh-Hans-SG, zh-Hant-TW, zh-Hant-HK if (browser.isIE && locale.indexOf('zh-Han') === 0) { return true; } return false; }; _this._register(dom.addDisposableListener(textArea.domNode, 'compositionupdate', function (e) { if (compositionDataInValid(e.locale)) { var _a = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/ false), newState_1 = _a[0], typeInput_1 = _a[1]; _this._textAreaState = newState_1; _this._onType.fire(typeInput_1); _this._onCompositionUpdate.fire(e); return; } var _b = deduceComposition(e.data), newState = _b[0], typeInput = _b[1]; _this._textAreaState = newState; _this._onType.fire(typeInput); _this._onCompositionUpdate.fire(e); })); _this._register(dom.addDisposableListener(textArea.domNode, 'compositionend', function (e) { // https://github.com/microsoft/monaco-editor/issues/1663 // On iOS 13.2, Chinese system IME randomly trigger an additional compositionend event with empty data if (!_this._isDoingComposition) { return; } if (compositionDataInValid(e.locale)) { // https://github.com/Microsoft/monaco-editor/issues/339 var _a = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/ false), newState = _a[0], typeInput = _a[1]; _this._textAreaState = newState; _this._onType.fire(typeInput); } else { var _b = deduceComposition(e.data), newState = _b[0], typeInput = _b[1]; _this._textAreaState = newState; _this._onType.fire(typeInput); } // Due to isEdgeOrIE (where the textarea was not cleared initially) and isChrome (the textarea is not updated correctly when composition ends) // we cannot assume the text at the end consists only of the composited text if (browser.isEdgeOrIE || browser.isChrome) { _this._textAreaState = textAreaState_1.TextAreaState.readFromTextArea(_this._textArea); } if (!_this._isDoingComposition) { return; } _this._isDoingComposition = false; _this._onCompositionEnd.fire(); })); _this._register(dom.addDisposableListener(textArea.domNode, 'input', function () { // Pretend here we touched the text area, as the `input` event will most likely // result in a `selectionchange` event which we want to ignore _this._textArea.setIgnoreSelectionChangeTime('received input event'); if (_this._isDoingComposition) { return; } var _a = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/ platform.isMacintosh), newState = _a[0], typeInput = _a[1]; if (typeInput.replaceCharCnt === 0 && typeInput.text.length === 1 && strings.isHighSurrogate(typeInput.text.charCodeAt(0))) { // Ignore invalid input but keep it around for next time return; } _this._textAreaState = newState; if (_this._nextCommand === 0 /* Type */) { if (typeInput.text !== '') { _this._onType.fire(typeInput); } } else { if (typeInput.text !== '' || typeInput.replaceCharCnt !== 0) { _this._firePaste(typeInput.text, null); } _this._nextCommand = 0 /* Type */; } })); // --- Clipboard operations _this._register(dom.addDisposableListener(textArea.domNode, 'cut', function (e) { // Pretend here we touched the text area, as the `cut` event will most likely // result in a `selectionchange` event which we want to ignore _this._textArea.setIgnoreSelectionChangeTime('received cut event'); _this._ensureClipboardGetsEditorSelection(e); _this._asyncTriggerCut.schedule(); })); _this._register(dom.addDisposableListener(textArea.domNode, 'copy', function (e) { _this._ensureClipboardGetsEditorSelection(e); })); _this._register(dom.addDisposableListener(textArea.domNode, 'paste', function (e) { // Pretend here we touched the text area, as the `paste` event will most likely // result in a `selectionchange` event which we want to ignore _this._textArea.setIgnoreSelectionChangeTime('received paste event'); if (ClipboardEventUtils.canUseTextData(e)) { var _a = ClipboardEventUtils.getTextData(e), pastePlainText = _a[0], metadata = _a[1]; if (pastePlainText !== '') { _this._firePaste(pastePlainText, metadata); } } else { if (_this._textArea.getSelectionStart() !== _this._textArea.getSelectionEnd()) { // Clean up the textarea, to get a clean paste _this._setAndWriteTextAreaState('paste', textAreaState_1.TextAreaState.EMPTY); } _this._nextCommand = 1 /* Paste */; } })); _this._register(dom.addDisposableListener(textArea.domNode, 'focus', function () { _this._setHasFocus(true); })); _this._register(dom.addDisposableListener(textArea.domNode, 'blur', function () { _this._setHasFocus(false); })); return _this; } TextAreaInput.prototype._installSelectionChangeListener = function () { // See https://github.com/Microsoft/vscode/issues/27216 // 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 var _this = this; // `selectionchange` events often come multiple times for a single logical change // so throttle multiple `selectionchange` events that burst in a short period of time. var previousSelectionChangeEventTime = 0; return dom.addDisposableListener(document, 'selectionchange', function (e) { if (!_this._hasFocus) { return; } if (_this._isDoingComposition) { return; } if (!browser.isChrome || !platform.isWindows) { // Support only for Chrome on Windows until testing happens on other browsers + OS configurations return; } var now = Date.now(); var delta1 = now - previousSelectionChangeEventTime; previousSelectionChangeEventTime = now; if (delta1 < 5) { // received another `selectionchange` event within 5ms of the previous `selectionchange` event // => ignore it return; } var 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; } var newValue = _this._textArea.getValue(); if (_this._textAreaState.value !== newValue) { // Cannot correlate a position in the textarea with a position in the editor... return; } var newSelectionStart = _this._textArea.getSelectionStart(); var newSelectionEnd = _this._textArea.getSelectionEnd(); if (_this._textAreaState.selectionStart === newSelectionStart && _this._textAreaState.selectionEnd === newSelectionEnd) { // Nothing to do... return; } var _newSelectionStartPosition = _this._textAreaState.deduceEditorPosition(newSelectionStart); var newSelectionStartPosition = _this._host.deduceModelPosition(_newSelectionStartPosition[0], _newSelectionStartPosition[1], _newSelectionStartPosition[2]); var _newSelectionEndPosition = _this._textAreaState.deduceEditorPosition(newSelectionEnd); var newSelectionEndPosition = _this._host.deduceModelPosition(_newSelectionEndPosition[0], _newSelectionEndPosition[1], _newSelectionEndPosition[2]); var newSelection = new selection_1.Selection(newSelectionStartPosition.lineNumber, newSelectionStartPosition.column, newSelectionEndPosition.lineNumber, newSelectionEndPosition.column); _this._onSelectionChangeRequest.fire(newSelection); }); }; TextAreaInput.prototype.dispose = function () { _super.prototype.dispose.call(this); if (this._selectionChangeListener) { this._selectionChangeListener.dispose(); this._selectionChangeListener = null; } }; TextAreaInput.prototype.focusTextArea = function () { // 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(); }; TextAreaInput.prototype.isFocused = function () { return this._hasFocus; }; TextAreaInput.prototype.refreshFocusState = function () { var shadowRoot = dom.getShadowRoot(this.textArea.domNode); if (shadowRoot) { this._setHasFocus(shadowRoot.activeElement === this.textArea.domNode); } else if (dom.isInDOM(this.textArea.domNode)) { this._setHasFocus(document.activeElement === this.textArea.domNode); } else { this._setHasFocus(false); } }; TextAreaInput.prototype._setHasFocus = function (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) { if (browser.isEdge) { // Edge has a bug where setting the selection range while the focus event // is dispatching doesn't work. To reproduce, "tab into" the editor. this._setAndWriteTextAreaState('focusgain', textAreaState_1.TextAreaState.EMPTY); } else { this.writeScreenReaderContent('focusgain'); } } if (this._hasFocus) { this._onFocus.fire(); } else { this._onBlur.fire(); } }; TextAreaInput.prototype._setAndWriteTextAreaState = function (reason, textAreaState) { if (!this._hasFocus) { textAreaState = textAreaState.collapseSelection(); } textAreaState.writeToTextArea(reason, this._textArea, this._hasFocus); this._textAreaState = textAreaState; }; TextAreaInput.prototype.writeScreenReaderContent = function (reason) { if (this._isDoingComposition) { // Do not write to the text area when doing composition return; } this._setAndWriteTextAreaState(reason, this._host.getScreenReaderContent(this._textAreaState)); }; TextAreaInput.prototype._ensureClipboardGetsEditorSelection = function (e) { var dataToCopy = this._host.getDataToCopy(ClipboardEventUtils.canUseTextData(e) && canIUse_1.BrowserFeatures.clipboard.richText); var storedMetadata = { version: 1, isFromEmptySelection: dataToCopy.isFromEmptySelection, multicursorText: dataToCopy.multicursorText, mode: dataToCopy.mode }; InMemoryClipboardMetadataManager.INSTANCE.set( // When writing "LINE\r\n" to the clipboard and then pasting, // Firefox pastes "LINE\n", so let's work around this quirk (browser.isFirefox ? dataToCopy.text.replace(/\r\n/g, '\n') : dataToCopy.text), storedMetadata); if (!ClipboardEventUtils.canUseTextData(e)) { // Looks like an old browser. The strategy is to place the text // we'd like to be copied to the clipboard in the textarea and select it. this._setAndWriteTextAreaState('copy or cut', textAreaState_1.TextAreaState.selectedText(dataToCopy.text)); return; } ClipboardEventUtils.setTextData(e, dataToCopy.text, dataToCopy.html, storedMetadata); }; TextAreaInput.prototype._firePaste = function (text, metadata) { if (!metadata) { // try the in-memory store metadata = InMemoryClipboardMetadataManager.INSTANCE.get(text); } this._onPaste.fire({ text: text, metadata: metadata }); }; return TextAreaInput; }(lifecycle_1.Disposable)); exports.TextAreaInput = TextAreaInput; var ClipboardEventUtils = /** @class */ (function () { function ClipboardEventUtils() { } ClipboardEventUtils.canUseTextData = function (e) { if (e.clipboardData) { return true; } if (window.clipboardData) { return true; } return false; }; ClipboardEventUtils.getTextData = function (e) { if (e.clipboardData) { e.preventDefault(); var text = e.clipboardData.getData('text/plain'); var metadata = null; var rawmetadata = e.clipboardData.getData('vscode-editor-data'); if (typeof rawmetadata === 'string') { try { metadata = JSON.parse(rawmetadata); if (metadata.version !== 1) { metadata = null; } } catch (err) { // no problem! } } return [text, metadata]; } if (window.clipboardData) { e.preventDefault(); var text = window.clipboardData.getData('Text'); return [text, null]; } throw new Error('ClipboardEventUtils.getTextData: Cannot use text data!'); }; ClipboardEventUtils.setTextData = function (e, text, html, metadata) { if (e.clipboardData) { e.clipboardData.setData('text/plain', text); if (typeof html === 'string') { e.clipboardData.setData('text/html', html); } e.clipboardData.setData('vscode-editor-data', JSON.stringify(metadata)); e.preventDefault(); return; } if (window.clipboardData) { window.clipboardData.setData('Text', text); e.preventDefault(); return; } throw new Error('ClipboardEventUtils.setTextData: Cannot use text data!'); }; return ClipboardEventUtils; }()); var TextAreaWrapper = /** @class */ (function (_super) { __extends(TextAreaWrapper, _super); function TextAreaWrapper(_textArea) { var _this = _super.call(this) || this; _this._actual = _textArea; _this._ignoreSelectionChangeTime = 0; return _this; } TextAreaWrapper.prototype.setIgnoreSelectionChangeTime = function (reason) { this._ignoreSelectionChangeTime = Date.now(); }; TextAreaWrapper.prototype.getIgnoreSelectionChangeTime = function () { return this._ignoreSelectionChangeTime; }; TextAreaWrapper.prototype.resetSelectionChangeTime = function () { this._ignoreSelectionChangeTime = 0; }; TextAreaWrapper.prototype.getValue = function () { // console.log('current value: ' + this._textArea.value); return this._actual.domNode.value; }; TextAreaWrapper.prototype.setValue = function (reason, value) { var textArea = this._actual.domNode; if (textArea.value === value) { // No change return; } // console.log('reason: ' + reason + ', current value: ' + textArea.value + ' => new value: ' + value); this.setIgnoreSelectionChangeTime('setValue'); textArea.value = value; }; TextAreaWrapper.prototype.getSelectionStart = function () { return this._actual.domNode.selectionStart; }; TextAreaWrapper.prototype.getSelectionEnd = function () { return this._actual.domNode.selectionEnd; }; TextAreaWrapper.prototype.setSelectionRange = function (reason, selectionStart, selectionEnd) { var textArea = this._actual.domNode; var activeElement = null; var shadowRoot = dom.getShadowRoot(textArea); if (shadowRoot) { activeElement = shadowRoot.activeElement; } else { activeElement = document.activeElement; } var currentIsFocused = (activeElement === textArea); var currentSelectionStart = textArea.selectionStart; var 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 { var 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) } }; return TextAreaWrapper; }(lifecycle_1.Disposable)); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[80/*vs/editor/common/commands/replaceCommand*/], __M([0/*require*/,1/*exports*/,22/*vs/editor/common/core/selection*/]), function (require, exports, selection_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ReplaceCommand = /** @class */ (function () { function ReplaceCommand(range, text, insertsAutoWhitespace) { if (insertsAutoWhitespace === void 0) { insertsAutoWhitespace = false; } this._range = range; this._text = text; this.insertsAutoWhitespace = insertsAutoWhitespace; } ReplaceCommand.prototype.getEditOperations = function (model, builder) { builder.addTrackedEditOperation(this._range, this._text); }; ReplaceCommand.prototype.computeCursorState = function (model, helper) { var inverseEditOperations = helper.getInverseEditOperations(); var srcRange = inverseEditOperations[0].range; return new selection_1.Selection(srcRange.endLineNumber, srcRange.endColumn, srcRange.endLineNumber, srcRange.endColumn); }; return ReplaceCommand; }()); exports.ReplaceCommand = ReplaceCommand; var ReplaceCommandThatSelectsText = /** @class */ (function () { function ReplaceCommandThatSelectsText(range, text) { this._range = range; this._text = text; } ReplaceCommandThatSelectsText.prototype.getEditOperations = function (model, builder) { builder.addTrackedEditOperation(this._range, this._text); }; ReplaceCommandThatSelectsText.prototype.computeCursorState = function (model, helper) { var inverseEditOperations = helper.getInverseEditOperations(); var srcRange = inverseEditOperations[0].range; return new selection_1.Selection(srcRange.startLineNumber, srcRange.startColumn, srcRange.endLineNumber, srcRange.endColumn); }; return ReplaceCommandThatSelectsText; }()); exports.ReplaceCommandThatSelectsText = ReplaceCommandThatSelectsText; var ReplaceCommandWithoutChangingPosition = /** @class */ (function () { function ReplaceCommandWithoutChangingPosition(range, text, insertsAutoWhitespace) { if (insertsAutoWhitespace === void 0) { insertsAutoWhitespace = false; } this._range = range; this._text = text; this.insertsAutoWhitespace = insertsAutoWhitespace; } ReplaceCommandWithoutChangingPosition.prototype.getEditOperations = function (model, builder) { builder.addTrackedEditOperation(this._range, this._text); }; ReplaceCommandWithoutChangingPosition.prototype.computeCursorState = function (model, helper) { var inverseEditOperations = helper.getInverseEditOperations(); var srcRange = inverseEditOperations[0].range; return new selection_1.Selection(srcRange.startLineNumber, srcRange.startColumn, srcRange.startLineNumber, srcRange.startColumn); }; return ReplaceCommandWithoutChangingPosition; }()); exports.ReplaceCommandWithoutChangingPosition = ReplaceCommandWithoutChangingPosition; var ReplaceCommandWithOffsetCursorState = /** @class */ (function () { function ReplaceCommandWithOffsetCursorState(range, text, lineNumberDeltaOffset, columnDeltaOffset, insertsAutoWhitespace) { if (insertsAutoWhitespace === void 0) { insertsAutoWhitespace = false; } this._range = range; this._text = text; this._columnDeltaOffset = columnDeltaOffset; this._lineNumberDeltaOffset = lineNumberDeltaOffset; this.insertsAutoWhitespace = insertsAutoWhitespace; } ReplaceCommandWithOffsetCursorState.prototype.getEditOperations = function (model, builder) { builder.addTrackedEditOperation(this._range, this._text); }; ReplaceCommandWithOffsetCursorState.prototype.computeCursorState = function (model, helper) { var inverseEditOperations = helper.getInverseEditOperations(); var srcRange = inverseEditOperations[0].range; return new selection_1.Selection(srcRange.endLineNumber + this._lineNumberDeltaOffset, srcRange.endColumn + this._columnDeltaOffset, srcRange.endLineNumber + this._lineNumberDeltaOffset, srcRange.endColumn + this._columnDeltaOffset); }; return ReplaceCommandWithOffsetCursorState; }()); exports.ReplaceCommandWithOffsetCursorState = ReplaceCommandWithOffsetCursorState; var ReplaceCommandThatPreservesSelection = /** @class */ (function () { function ReplaceCommandThatPreservesSelection(editRange, text, initialSelection, forceMoveMarkers) { if (forceMoveMarkers === void 0) { forceMoveMarkers = false; } this._range = editRange; this._text = text; this._initialSelection = initialSelection; this._forceMoveMarkers = forceMoveMarkers; this._selectionId = null; } ReplaceCommandThatPreservesSelection.prototype.getEditOperations = function (model, builder) { builder.addTrackedEditOperation(this._range, this._text, this._forceMoveMarkers); this._selectionId = builder.trackSelection(this._initialSelection); }; ReplaceCommandThatPreservesSelection.prototype.computeCursorState = function (model, helper) { return helper.getTrackedSelection(this._selectionId); }; return ReplaceCommandThatPreservesSelection; }()); 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[340/*vs/editor/common/commands/surroundSelectionCommand*/], __M([0/*require*/,1/*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 }); var SurroundSelectionCommand = /** @class */ (function () { function SurroundSelectionCommand(range, charBeforeSelection, charAfterSelection) { this._range = range; this._charBeforeSelection = charBeforeSelection; this._charAfterSelection = charAfterSelection; } SurroundSelectionCommand.prototype.getEditOperations = function (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); }; SurroundSelectionCommand.prototype.computeCursorState = function (model, helper) { var inverseEditOperations = helper.getInverseEditOperations(); var firstOperationRange = inverseEditOperations[0].range; var secondOperationRange = inverseEditOperations[1].range; return new selection_1.Selection(firstOperationRange.endLineNumber, firstOperationRange.endColumn, secondOperationRange.endLineNumber, secondOperationRange.endColumn - this._charAfterSelection.length); }; return SurroundSelectionCommand; }()); 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[106/*vs/editor/common/core/stringBuilder*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/]), function (require, exports, strings) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); if (typeof TextDecoder !== 'undefined') { exports.createStringBuilder = function (capacity) { return new StringBuilder(capacity); }; } else { exports.createStringBuilder = function (capacity) { return new CompatStringBuilder(); }; } var StringBuilder = /** @class */ (function () { function StringBuilder(capacity) { this._decoder = new TextDecoder('UTF-16LE'); this._capacity = capacity | 0; this._buffer = new Uint16Array(this._capacity); this._completedStrings = null; this._bufferLength = 0; } StringBuilder.prototype.reset = function () { this._completedStrings = null; this._bufferLength = 0; }; StringBuilder.prototype.build = function () { if (this._completedStrings !== null) { this._flushBuffer(); return this._completedStrings.join(''); } return this._buildBuffer(); }; StringBuilder.prototype._buildBuffer = function () { if (this._bufferLength === 0) { return ''; } var view = new Uint16Array(this._buffer.buffer, 0, this._bufferLength); return this._decoder.decode(view); }; StringBuilder.prototype._flushBuffer = function () { var bufferString = this._buildBuffer(); this._bufferLength = 0; if (this._completedStrings === null) { this._completedStrings = [bufferString]; } else { this._completedStrings[this._completedStrings.length] = bufferString; } }; StringBuilder.prototype.write1 = function (charCode) { var remainingSpace = this._capacity - this._bufferLength; if (remainingSpace <= 1) { if (remainingSpace === 0 || strings.isHighSurrogate(charCode)) { this._flushBuffer(); } } this._buffer[this._bufferLength++] = charCode; }; StringBuilder.prototype.appendASCII = function (charCode) { if (this._bufferLength === this._capacity) { // buffer is full this._flushBuffer(); } this._buffer[this._bufferLength++] = charCode; }; StringBuilder.prototype.appendASCIIString = function (str) { var 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 (var i = 0; i < strLen; i++) { this._buffer[this._bufferLength++] = str.charCodeAt(i); } }; return StringBuilder; }()); var CompatStringBuilder = /** @class */ (function () { function CompatStringBuilder() { this._pieces = []; this._piecesLen = 0; } CompatStringBuilder.prototype.reset = function () { this._pieces = []; this._piecesLen = 0; }; CompatStringBuilder.prototype.build = function () { return this._pieces.join(''); }; CompatStringBuilder.prototype.write1 = function (charCode) { this._pieces[this._piecesLen++] = String.fromCharCode(charCode); }; CompatStringBuilder.prototype.appendASCII = function (charCode) { this._pieces[this._piecesLen++] = String.fromCharCode(charCode); }; CompatStringBuilder.prototype.appendASCIIString = function (str) { this._pieces[this._piecesLen++] = str; }; return CompatStringBuilder; }()); }); /*--------------------------------------------------------------------------------------------- * 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/view/viewLayer*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,106/*vs/editor/common/core/stringBuilder*/]), function (require, exports, fastDomNode_1, stringBuilder_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var RenderedLinesCollection = /** @class */ (function () { function RenderedLinesCollection(createLine) { this._createLine = createLine; this._set(1, []); } RenderedLinesCollection.prototype.flush = function () { this._set(1, []); }; RenderedLinesCollection.prototype._set = function (rendLineNumberStart, lines) { this._lines = lines; this._rendLineNumberStart = rendLineNumberStart; }; RenderedLinesCollection.prototype._get = function () { return { rendLineNumberStart: this._rendLineNumberStart, lines: this._lines }; }; /** * @returns Inclusive line number that is inside this collection */ RenderedLinesCollection.prototype.getStartLineNumber = function () { return this._rendLineNumberStart; }; /** * @returns Inclusive line number that is inside this collection */ RenderedLinesCollection.prototype.getEndLineNumber = function () { return this._rendLineNumberStart + this._lines.length - 1; }; RenderedLinesCollection.prototype.getCount = function () { return this._lines.length; }; RenderedLinesCollection.prototype.getLine = function (lineNumber) { var 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 */ RenderedLinesCollection.prototype.onLinesDeleted = function (deleteFromLineNumber, deleteToLineNumber) { if (this.getCount() === 0) { // no lines return null; } var startLineNumber = this.getStartLineNumber(); var endLineNumber = this.getEndLineNumber(); if (deleteToLineNumber < startLineNumber) { // deleting above the viewport var deleteCnt = deleteToLineNumber - deleteFromLineNumber + 1; this._rendLineNumberStart -= deleteCnt; return null; } if (deleteFromLineNumber > endLineNumber) { // deleted below the viewport return null; } // Record what needs to be deleted var deleteStartIndex = 0; var deleteCount = 0; for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { var 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 var deleteAboveCount = 0; if (deleteToLineNumber < startLineNumber) { // the entire deleted lines are above deleteAboveCount = deleteToLineNumber - deleteFromLineNumber + 1; } else { deleteAboveCount = startLineNumber - deleteFromLineNumber; } this._rendLineNumberStart -= deleteAboveCount; } var deleted = this._lines.splice(deleteStartIndex, deleteCount); return deleted; }; RenderedLinesCollection.prototype.onLinesChanged = function (changeFromLineNumber, changeToLineNumber) { if (this.getCount() === 0) { // no lines return false; } var startLineNumber = this.getStartLineNumber(); var endLineNumber = this.getEndLineNumber(); var someoneNotified = false; for (var changedLineNumber = changeFromLineNumber; changedLineNumber <= changeToLineNumber; changedLineNumber++) { if (changedLineNumber >= startLineNumber && changedLineNumber <= endLineNumber) { // Notify the line this._lines[changedLineNumber - this._rendLineNumberStart].onContentChanged(); someoneNotified = true; } } return someoneNotified; }; RenderedLinesCollection.prototype.onLinesInserted = function (insertFromLineNumber, insertToLineNumber) { if (this.getCount() === 0) { // no lines return null; } var insertCnt = insertToLineNumber - insertFromLineNumber + 1; var startLineNumber = this.getStartLineNumber(); var 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 var 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 var newLines = []; for (var i = 0; i < insertCnt; i++) { newLines[i] = this._createLine(); } var insertIndex = insertFromLineNumber - this._rendLineNumberStart; var beforeLines = this._lines.slice(0, insertIndex); var afterLines = this._lines.slice(insertIndex, this._lines.length - insertCnt); var deletedLines = this._lines.slice(this._lines.length - insertCnt, this._lines.length); this._lines = beforeLines.concat(newLines).concat(afterLines); return deletedLines; }; RenderedLinesCollection.prototype.onTokensChanged = function (ranges) { if (this.getCount() === 0) { // no lines return false; } var startLineNumber = this.getStartLineNumber(); var endLineNumber = this.getEndLineNumber(); var notifiedSomeone = false; for (var i = 0, len = ranges.length; i < len; i++) { var rng = ranges[i]; if (rng.toLineNumber < startLineNumber || rng.fromLineNumber > endLineNumber) { // range outside viewport continue; } var from = Math.max(startLineNumber, rng.fromLineNumber); var to = Math.min(endLineNumber, rng.toLineNumber); for (var lineNumber = from; lineNumber <= to; lineNumber++) { var lineIndex = lineNumber - this._rendLineNumberStart; this._lines[lineIndex].onTokensChanged(); notifiedSomeone = true; } } return notifiedSomeone; }; return RenderedLinesCollection; }()); exports.RenderedLinesCollection = RenderedLinesCollection; var VisibleLinesCollection = /** @class */ (function () { function VisibleLinesCollection(host) { var _this = this; this._host = host; this.domNode = this._createDomNode(); this._linesCollection = new RenderedLinesCollection(function () { return _this._host.createVisibleLine(); }); } VisibleLinesCollection.prototype._createDomNode = function () { var domNode = 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 VisibleLinesCollection.prototype.onConfigurationChanged = function (e) { if (e.hasChanged(107 /* layoutInfo */)) { return true; } return false; }; VisibleLinesCollection.prototype.onFlushed = function (e) { this._linesCollection.flush(); // No need to clear the dom node because a full .innerHTML will occur in ViewLayerRenderer._render return true; }; VisibleLinesCollection.prototype.onLinesChanged = function (e) { return this._linesCollection.onLinesChanged(e.fromLineNumber, e.toLineNumber); }; VisibleLinesCollection.prototype.onLinesDeleted = function (e) { var deleted = this._linesCollection.onLinesDeleted(e.fromLineNumber, e.toLineNumber); if (deleted) { // Remove from DOM for (var i = 0, len = deleted.length; i < len; i++) { var lineDomNode = deleted[i].getDomNode(); if (lineDomNode) { this.domNode.domNode.removeChild(lineDomNode); } } } return true; }; VisibleLinesCollection.prototype.onLinesInserted = function (e) { var deleted = this._linesCollection.onLinesInserted(e.fromLineNumber, e.toLineNumber); if (deleted) { // Remove from DOM for (var i = 0, len = deleted.length; i < len; i++) { var lineDomNode = deleted[i].getDomNode(); if (lineDomNode) { this.domNode.domNode.removeChild(lineDomNode); } } } return true; }; VisibleLinesCollection.prototype.onScrollChanged = function (e) { return e.scrollTopChanged; }; VisibleLinesCollection.prototype.onTokensChanged = function (e) { return this._linesCollection.onTokensChanged(e.ranges); }; VisibleLinesCollection.prototype.onZonesChanged = function (e) { return true; }; // ---- end view event handlers VisibleLinesCollection.prototype.getStartLineNumber = function () { return this._linesCollection.getStartLineNumber(); }; VisibleLinesCollection.prototype.getEndLineNumber = function () { return this._linesCollection.getEndLineNumber(); }; VisibleLinesCollection.prototype.getVisibleLine = function (lineNumber) { return this._linesCollection.getLine(lineNumber); }; VisibleLinesCollection.prototype.renderLines = function (viewportData) { var inp = this._linesCollection._get(); var renderer = new ViewLayerRenderer(this.domNode.domNode, this._host, viewportData); var 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) var resCtx = renderer.render(ctx, viewportData.startLineNumber, viewportData.endLineNumber, viewportData.relativeVerticalOffset); this._linesCollection._set(resCtx.rendLineNumberStart, resCtx.lines); }; return VisibleLinesCollection; }()); exports.VisibleLinesCollection = VisibleLinesCollection; var ViewLayerRenderer = /** @class */ (function () { function ViewLayerRenderer(domNode, host, viewportData) { this.domNode = domNode; this.host = host; this.viewportData = viewportData; } ViewLayerRenderer.prototype.render = function (inContext, startLineNumber, stopLineNumber, deltaTop) { var 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 (var 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 var fromLineNumber = startLineNumber; var 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 var 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 var fromLineNumber = ctx.rendLineNumberStart + ctx.linesLength; var 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 var fromLineNumber = Math.max(0, stopLineNumber - ctx.rendLineNumberStart + 1); var toLineNumber = ctx.linesLength - 1; var removeCnt = toLineNumber - fromLineNumber + 1; if (removeCnt > 0) { this._removeLinesAfter(ctx, removeCnt); ctx.linesLength -= removeCnt; } } this._finishRendering(ctx, false, deltaTop); return ctx; }; ViewLayerRenderer.prototype._renderUntouchedLines = function (ctx, startIndex, endIndex, deltaTop, deltaLN) { var rendLineNumberStart = ctx.rendLineNumberStart; var lines = ctx.lines; for (var i = startIndex; i <= endIndex; i++) { var lineNumber = rendLineNumberStart + i; lines[i].layoutLine(lineNumber, deltaTop[lineNumber - deltaLN]); } }; ViewLayerRenderer.prototype._insertLinesBefore = function (ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) { var newLines = []; var newLinesLen = 0; for (var lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) { newLines[newLinesLen++] = this.host.createVisibleLine(); } ctx.lines = newLines.concat(ctx.lines); }; ViewLayerRenderer.prototype._removeLinesBefore = function (ctx, removeCount) { for (var i = 0; i < removeCount; i++) { var lineDomNode = ctx.lines[i].getDomNode(); if (lineDomNode) { this.domNode.removeChild(lineDomNode); } } ctx.lines.splice(0, removeCount); }; ViewLayerRenderer.prototype._insertLinesAfter = function (ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) { var newLines = []; var newLinesLen = 0; for (var lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) { newLines[newLinesLen++] = this.host.createVisibleLine(); } ctx.lines = ctx.lines.concat(newLines); }; ViewLayerRenderer.prototype._removeLinesAfter = function (ctx, removeCount) { var removeIndex = ctx.linesLength - removeCount; for (var i = 0; i < removeCount; i++) { var lineDomNode = ctx.lines[removeIndex + i].getDomNode(); if (lineDomNode) { this.domNode.removeChild(lineDomNode); } } ctx.lines.splice(removeIndex, removeCount); }; ViewLayerRenderer.prototype._finishRenderingNewLines = function (ctx, domNodeIsEmpty, newLinesHTML, wasNew) { var lastChild = this.domNode.lastChild; if (domNodeIsEmpty || !lastChild) { this.domNode.innerHTML = newLinesHTML; } else { lastChild.insertAdjacentHTML('afterend', newLinesHTML); } var currChild = this.domNode.lastChild; for (var i = ctx.linesLength - 1; i >= 0; i--) { var line = ctx.lines[i]; if (wasNew[i]) { line.setDomNode(currChild); currChild = currChild.previousSibling; } } }; ViewLayerRenderer.prototype._finishRenderingInvalidLines = function (ctx, invalidLinesHTML, wasInvalid) { var hugeDomNode = document.createElement('div'); hugeDomNode.innerHTML = invalidLinesHTML; for (var i = 0; i < ctx.linesLength; i++) { var line = ctx.lines[i]; if (wasInvalid[i]) { var source = hugeDomNode.firstChild; var lineDomNode = line.getDomNode(); lineDomNode.parentNode.replaceChild(source, lineDomNode); line.setDomNode(source); } } }; ViewLayerRenderer.prototype._finishRendering = function (ctx, domNodeIsEmpty, deltaTop) { var sb = ViewLayerRenderer._sb; var linesLength = ctx.linesLength; var lines = ctx.lines; var rendLineNumberStart = ctx.rendLineNumberStart; var wasNew = []; { sb.reset(); var hadNewLine = false; for (var i = 0; i < linesLength; i++) { var line = lines[i]; wasNew[i] = false; var lineDomNode = line.getDomNode(); if (lineDomNode) { // line is not new continue; } var 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(); var hadInvalidLine = false; var wasInvalid = []; for (var i = 0; i < linesLength; i++) { var line = lines[i]; wasInvalid[i] = false; if (wasNew[i]) { // line was new continue; } var 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._sb = stringBuilder_1.createStringBuilder(100000); return ViewLayerRenderer; }()); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[107/*vs/editor/common/core/token*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Token = /** @class */ (function () { function Token(offset, type, language) { this.offset = offset | 0; // @perf this.type = type; this.language = language; } Token.prototype.toString = function () { return '(' + this.offset + ', ' + this.type + ')'; }; return Token; }()); exports.Token = Token; var TokenizationResult = /** @class */ (function () { function TokenizationResult(tokens, endState) { this.tokens = tokens; this.endState = endState; } return TokenizationResult; }()); exports.TokenizationResult = TokenizationResult; var TokenizationResult2 = /** @class */ (function () { function TokenizationResult2(tokens, endState) { this.tokens = tokens; this.endState = endState; } return TokenizationResult2; }()); exports.TokenizationResult2 = TokenizationResult2; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[341/*vs/editor/common/diff/diffComputer*/], __M([0/*require*/,1/*exports*/,126/*vs/base/common/diff/diff*/,5/*vs/base/common/strings*/]), function (require, exports, diff_1, strings) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MINIMUM_MATCHING_CHARACTER_LENGTH = 3; function computeDiff(originalSequence, modifiedSequence, continueProcessingPredicate, pretty) { var diffAlgo = new diff_1.LcsDiff(originalSequence, modifiedSequence, continueProcessingPredicate); return diffAlgo.ComputeDiff(pretty); } var LineSequence = /** @class */ (function () { function LineSequence(lines) { var startColumns = []; var endColumns = []; for (var i = 0, length_1 = lines.length; i < length_1; i++) { startColumns[i] = getFirstNonBlankColumn(lines[i], 1); endColumns[i] = getLastNonBlankColumn(lines[i], 1); } this.lines = lines; this._startColumns = startColumns; this._endColumns = endColumns; } LineSequence.prototype.getElements = function () { var elements = []; for (var 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; }; LineSequence.prototype.getStartLineNumber = function (i) { return i + 1; }; LineSequence.prototype.getEndLineNumber = function (i) { return i + 1; }; LineSequence.prototype.createCharSequence = function (shouldIgnoreTrimWhitespace, startIndex, endIndex) { var charCodes = []; var lineNumbers = []; var columns = []; var len = 0; for (var index = startIndex; index <= endIndex; index++) { var lineContent = this.lines[index]; var startColumn = (shouldIgnoreTrimWhitespace ? this._startColumns[index] : 1); var endColumn = (shouldIgnoreTrimWhitespace ? this._endColumns[index] : lineContent.length + 1); for (var 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); }; return LineSequence; }()); var CharSequence = /** @class */ (function () { function CharSequence(charCodes, lineNumbers, columns) { this._charCodes = charCodes; this._lineNumbers = lineNumbers; this._columns = columns; } CharSequence.prototype.getElements = function () { return this._charCodes; }; CharSequence.prototype.getStartLineNumber = function (i) { return this._lineNumbers[i]; }; CharSequence.prototype.getStartColumn = function (i) { return this._columns[i]; }; CharSequence.prototype.getEndLineNumber = function (i) { return this._lineNumbers[i]; }; CharSequence.prototype.getEndColumn = function (i) { return this._columns[i] + 1; }; return CharSequence; }()); var CharChange = /** @class */ (function () { function CharChange(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; } CharChange.createFromDiffChange = function (diffChange, originalCharSequence, modifiedCharSequence) { var originalStartLineNumber; var originalStartColumn; var originalEndLineNumber; var originalEndColumn; var modifiedStartLineNumber; var modifiedStartColumn; var modifiedEndLineNumber; var 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); }; return CharChange; }()); function postProcessCharChanges(rawChanges) { if (rawChanges.length <= 1) { return rawChanges; } var result = [rawChanges[0]]; var prevChange = result[0]; for (var i = 1, len = rawChanges.length; i < len; i++) { var currChange = rawChanges[i]; var originalMatchingLength = currChange.originalStart - (prevChange.originalStart + prevChange.originalLength); var modifiedMatchingLength = currChange.modifiedStart - (prevChange.modifiedStart + prevChange.modifiedLength); // Both of the above should be equal, but the continueProcessingPredicate may prevent this from being true var 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; } var LineChange = /** @class */ (function () { function LineChange(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges) { this.originalStartLineNumber = originalStartLineNumber; this.originalEndLineNumber = originalEndLineNumber; this.modifiedStartLineNumber = modifiedStartLineNumber; this.modifiedEndLineNumber = modifiedEndLineNumber; this.charChanges = charChanges; } LineChange.createFromDiffResult = function (shouldIgnoreTrimWhitespace, diffChange, originalLineSequence, modifiedLineSequence, continueCharDiff, shouldComputeCharChanges, shouldPostProcessCharChanges) { var originalStartLineNumber; var originalEndLineNumber; var modifiedStartLineNumber; var modifiedEndLineNumber; var 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... var originalCharSequence = originalLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.originalStart, diffChange.originalStart + diffChange.originalLength - 1); var modifiedCharSequence = modifiedLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength - 1); var rawChanges = computeDiff(originalCharSequence, modifiedCharSequence, continueCharDiff, true).changes; if (shouldPostProcessCharChanges) { rawChanges = postProcessCharChanges(rawChanges); } charChanges = []; for (var i = 0, length_2 = rawChanges.length; i < length_2; i++) { charChanges.push(CharChange.createFromDiffChange(rawChanges[i], originalCharSequence, modifiedCharSequence)); } } return new LineChange(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges); }; return LineChange; }()); var DiffComputer = /** @class */ (function () { function DiffComputer(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... } DiffComputer.prototype.computeDiff = function () { if (this.original.lines.length === 1 && this.original.lines[0].length === 0) { // empty original => fast path 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 }] }] }; } var diffResult = computeDiff(this.original, this.modified, this.continueLineDiff, this.shouldMakePrettyDiff); var rawChanges = diffResult.changes; var quitEarly = diffResult.quitEarly; // The diff is always computed with ignoring trim whitespace // This ensures we get the prettiest diff if (this.shouldIgnoreTrimWhitespace) { var lineChanges = []; for (var i = 0, length_3 = rawChanges.length; i < length_3; 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 var result = []; var originalLineIndex = 0; var modifiedLineIndex = 0; for (var i = -1 /* !!!! */, len = rawChanges.length; i < len; i++) { var nextChange = (i + 1 < len ? rawChanges[i + 1] : null); var originalStop = (nextChange ? nextChange.originalStart : this.originalLines.length); var modifiedStop = (nextChange ? nextChange.modifiedStart : this.modifiedLines.length); while (originalLineIndex < originalStop && modifiedLineIndex < modifiedStop) { var originalLine = this.originalLines[originalLineIndex]; var modifiedLine = this.modifiedLines[modifiedLineIndex]; if (originalLine !== modifiedLine) { // These lines differ only in trim whitespace // Check the leading whitespace { var originalStartColumn = getFirstNonBlankColumn(originalLine, 1); var modifiedStartColumn = getFirstNonBlankColumn(modifiedLine, 1); while (originalStartColumn > 1 && modifiedStartColumn > 1) { var originalChar = originalLine.charCodeAt(originalStartColumn - 2); var 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 { var originalEndColumn = getLastNonBlankColumn(originalLine, 1); var modifiedEndColumn = getLastNonBlankColumn(modifiedLine, 1); var originalMaxColumn = originalLine.length + 1; var modifiedMaxColumn = modifiedLine.length + 1; while (originalEndColumn < originalMaxColumn && modifiedEndColumn < modifiedMaxColumn) { var originalChar = originalLine.charCodeAt(originalEndColumn - 1); var 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 }; }; DiffComputer.prototype._pushTrimWhitespaceCharChange = function (result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) { if (this._mergeTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn)) { // Merged into previous return; } var 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)); }; DiffComputer.prototype._mergeTrimWhitespaceCharChange = function (result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) { var len = result.length; if (len === 0) { return false; } var 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; }; return DiffComputer; }()); exports.DiffComputer = DiffComputer; function getFirstNonBlankColumn(txt, defaultValue) { var r = strings.firstNonWhitespaceIndex(txt); if (r === -1) { return defaultValue; } return r + 1; } function getLastNonBlankColumn(txt, defaultValue) { var r = strings.lastNonWhitespaceIndex(txt); if (r === -1) { return defaultValue; } return r + 2; } function createContinueProcessingPredicate(maximumRuntime) { if (maximumRuntime === 0) { return function () { return true; }; } var startTime = Date.now(); return function () { 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[190/*vs/editor/common/editorAction*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var InternalEditorAction = /** @class */ (function () { function InternalEditorAction(id, label, alias, precondition, run, contextKeyService) { this.id = id; this.label = label; this.alias = alias; this._precondition = precondition; this._run = run; this._contextKeyService = contextKeyService; } InternalEditorAction.prototype.isSupported = function () { return this._contextKeyService.contextMatchesRules(this._precondition); }; InternalEditorAction.prototype.run = function () { if (!this.isSupported()) { return Promise.resolve(undefined); } var r = this._run(); return r ? r : Promise.resolve(undefined); }; return InternalEditorAction; }()); exports.InternalEditorAction = InternalEditorAction; }); define(__m[68/*vs/editor/common/editorCommon*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * @internal */ function isThemeColor(o) { return o && typeof o.id === 'string'; } exports.isThemeColor = isThemeColor; /** * The type of the `IEditor`. */ exports.EditorType = { ICodeEditor: 'vs.editor.ICodeEditor', IDiffEditor: 'vs.editor.IDiffEditor' }; /** * Built-in commands. * @internal */ exports.Handler = { ExecuteCommand: 'executeCommand', ExecuteCommands: 'executeCommands', Type: 'type', ReplacePreviousChar: 'replacePreviousChar', CompositionStart: 'compositionStart', CompositionEnd: 'compositionEnd', Paste: 'paste', Cut: 'cut', Undo: 'undo', Redo: 'redo', }; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[108/*vs/editor/browser/editorBrowser*/], __M([0/*require*/,1/*exports*/,68/*vs/editor/common/editorCommon*/]), function (require, exports, editorCommon) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** *@internal */ function isCodeEditor(thing) { if (thing && typeof thing.getEditorType === 'function') { return thing.getEditorType() === editorCommon.EditorType.ICodeEditor; } else { return false; } } exports.isCodeEditor = isCodeEditor; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[48/*vs/editor/common/model*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * 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 TextModelResolvedOptions = /** @class */ (function () { /** * @internal */ function TextModelResolvedOptions(src) { this.tabSize = Math.max(1, src.tabSize | 0); this.indentSize = src.tabSize | 0; this.insertSpaces = Boolean(src.insertSpaces); this.defaultEOL = src.defaultEOL | 0; this.trimAutoWhitespace = Boolean(src.trimAutoWhitespace); } /** * @internal */ TextModelResolvedOptions.prototype.equals = function (other) { return (this.tabSize === other.tabSize && this.indentSize === other.indentSize && this.insertSpaces === other.insertSpaces && this.defaultEOL === other.defaultEOL && this.trimAutoWhitespace === other.trimAutoWhitespace); }; /** * @internal */ TextModelResolvedOptions.prototype.createChangeEvent = function (newOpts) { return { tabSize: this.tabSize !== newOpts.tabSize, indentSize: this.indentSize !== newOpts.indentSize, insertSpaces: this.insertSpaces !== newOpts.insertSpaces, trimAutoWhitespace: this.trimAutoWhitespace !== newOpts.trimAutoWhitespace, }; }; return TextModelResolvedOptions; }()); exports.TextModelResolvedOptions = TextModelResolvedOptions; var FindMatch = /** @class */ (function () { /** * @internal */ function FindMatch(range, matches) { this.range = range; this.matches = matches; } return FindMatch; }()); exports.FindMatch = FindMatch; /** * @internal */ var ApplyEditsResult = /** @class */ (function () { function ApplyEditsResult(reverseEdits, changes, trimAutoWhitespaceLineNumbers) { this.reverseEdits = reverseEdits; this.changes = changes; this.trimAutoWhitespaceLineNumbers = trimAutoWhitespaceLineNumbers; } return ApplyEditsResult; }()); exports.ApplyEditsResult = ApplyEditsResult; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[342/*vs/editor/common/model/editStack*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/]), function (require, exports, errors_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var EditStackElement = /** @class */ (function () { function EditStackElement(beforeVersionId, beforeCursorState) { this.beforeVersionId = beforeVersionId; this.beforeCursorState = beforeCursorState; this.afterCursorState = null; this.afterVersionId = -1; this.editOperations = []; } EditStackElement.prototype.undo = function (model) { // Apply all operations in reverse order for (var i = this.editOperations.length - 1; i >= 0; i--) { this.editOperations[i] = { operations: model.applyEdits(this.editOperations[i].operations) }; } }; EditStackElement.prototype.redo = function (model) { // Apply all operations for (var i = 0; i < this.editOperations.length; i++) { this.editOperations[i] = { operations: model.applyEdits(this.editOperations[i].operations) }; } }; return EditStackElement; }()); function getModelEOL(model) { var eol = model.getEOL(); if (eol === '\n') { return 0 /* LF */; } else { return 1 /* CRLF */; } } var EOLStackElement = /** @class */ (function () { function EOLStackElement(beforeVersionId, setEOL) { this.beforeVersionId = beforeVersionId; this.beforeCursorState = null; this.afterCursorState = null; this.afterVersionId = -1; this.eol = setEOL; } EOLStackElement.prototype.undo = function (model) { var redoEOL = getModelEOL(model); model.setEOL(this.eol); this.eol = redoEOL; }; EOLStackElement.prototype.redo = function (model) { var undoEOL = getModelEOL(model); model.setEOL(this.eol); this.eol = undoEOL; }; return EOLStackElement; }()); var EditStack = /** @class */ (function () { function EditStack(model) { this.model = model; this.currentOpenStackElement = null; this.past = []; this.future = []; } EditStack.prototype.pushStackElement = function () { if (this.currentOpenStackElement !== null) { this.past.push(this.currentOpenStackElement); this.currentOpenStackElement = null; } }; EditStack.prototype.clear = function () { this.currentOpenStackElement = null; this.past = []; this.future = []; }; EditStack.prototype.pushEOL = function (eol) { // No support for parallel universes :( this.future = []; if (this.currentOpenStackElement) { this.pushStackElement(); } var prevEOL = getModelEOL(this.model); var stackElement = new EOLStackElement(this.model.getAlternativeVersionId(), prevEOL); this.model.setEOL(eol); stackElement.afterVersionId = this.model.getVersionId(); this.currentOpenStackElement = stackElement; this.pushStackElement(); }; EditStack.prototype.pushEditOperation = function (beforeCursorState, editOperations, cursorStateComputer) { // No support for parallel universes :( this.future = []; var stackElement = null; if (this.currentOpenStackElement) { if (this.currentOpenStackElement instanceof EditStackElement) { stackElement = this.currentOpenStackElement; } else { this.pushStackElement(); } } if (!this.currentOpenStackElement) { stackElement = new EditStackElement(this.model.getAlternativeVersionId(), beforeCursorState); this.currentOpenStackElement = stackElement; } var inverseEditOperation = { operations: this.model.applyEdits(editOperations) }; stackElement.editOperations.push(inverseEditOperation); stackElement.afterCursorState = EditStack._computeCursorState(cursorStateComputer, inverseEditOperation.operations); stackElement.afterVersionId = this.model.getVersionId(); return stackElement.afterCursorState; }; EditStack._computeCursorState = function (cursorStateComputer, inverseEditOperations) { try { return cursorStateComputer ? cursorStateComputer(inverseEditOperations) : null; } catch (e) { errors_1.onUnexpectedError(e); return null; } }; EditStack.prototype.undo = function () { this.pushStackElement(); if (this.past.length > 0) { var pastStackElement = this.past.pop(); try { pastStackElement.undo(this.model); } catch (e) { errors_1.onUnexpectedError(e); this.clear(); return null; } this.future.push(pastStackElement); return { selections: pastStackElement.beforeCursorState, recordedVersionId: pastStackElement.beforeVersionId }; } return null; }; EditStack.prototype.canUndo = function () { return (this.past.length > 0) || this.currentOpenStackElement !== null; }; EditStack.prototype.redo = function () { if (this.future.length > 0) { var futureStackElement = this.future.pop(); try { futureStackElement.redo(this.model); } catch (e) { errors_1.onUnexpectedError(e); this.clear(); return null; } this.past.push(futureStackElement); return { selections: futureStackElement.afterCursorState, recordedVersionId: futureStackElement.afterVersionId }; } return null; }; EditStack.prototype.canRedo = function () { return (this.future.length > 0); }; return EditStack; }()); exports.EditStack = EditStack; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[343/*vs/editor/common/model/indentationGuesser*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var SpacesDiffResult = /** @class */ (function () { function SpacesDiffResult() { this.spacesDiff = 0; this.looksLikeAlignment = false; } return SpacesDiffResult; }()); /** * 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 var i; for (i = 0; i < aLength && i < bLength; i++) { var aCharCode = a.charCodeAt(i); var bCharCode = b.charCodeAt(i); if (aCharCode !== bCharCode) { break; } } var aSpacesCnt = 0, aTabsCount = 0; for (var j = i; j < aLength; j++) { var aCharCode = a.charCodeAt(j); if (aCharCode === 32 /* Space */) { aSpacesCnt++; } else { aTabsCount++; } } var bSpacesCnt = 0, bTabsCount = 0; for (var j = i; j < bLength; j++) { var bCharCode = b.charCodeAt(j); if (bCharCode === 32 /* Space */) { bSpacesCnt++; } else { bTabsCount++; } } if (aSpacesCnt > 0 && aTabsCount > 0) { return; } if (bSpacesCnt > 0 && bTabsCount > 0) { return; } var tabsDiff = Math.abs(aTabsCount - bTabsCount); var 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 var linesCount = Math.min(source.getLineCount(), 10000); var linesIndentedWithTabsCount = 0; // number of lines that contain at least one tab in indentation var linesIndentedWithSpacesCount = 0; // number of lines that contain only spaces in indentation var previousLineText = ''; // content of latest line that contained non-whitespace chars var previousLineIndentation = 0; // index at which latest line contained the first non-whitespace char var ALLOWED_TAB_SIZE_GUESSES = [2, 4, 6, 8, 3, 5, 7]; // prefer even guesses for `tabSize`, limit to [2, 8]. var MAX_ALLOWED_TAB_SIZE_GUESS = 8; // max(ALLOWED_TAB_SIZE_GUESSES) = 8 var spacesDiffCount = [0, 0, 0, 0, 0, 0, 0, 0, 0]; // `tabSize` scores var tmp = new SpacesDiffResult(); for (var lineNumber = 1; lineNumber <= linesCount; lineNumber++) { var currentLineLength = source.getLineLength(lineNumber); var 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. var useCurrentLineText = (currentLineLength <= 65536); var currentLineHasContent = false; // does `currentLineText` contain non-whitespace chars var currentLineIndentation = 0; // index at which `currentLineText` contains the first non-whitespace char var currentLineSpacesCount = 0; // count of spaces found in `currentLineText` indentation var currentLineTabsCount = 0; // count of tabs found in `currentLineText` indentation for (var j = 0, lenJ = currentLineLength; j < lenJ; j++) { var 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; } } var currentSpacesDiff = tmp.spacesDiff; if (currentSpacesDiff <= MAX_ALLOWED_TAB_SIZE_GUESS) { spacesDiffCount[currentSpacesDiff]++; } previousLineText = currentLineText; previousLineIndentation = currentLineIndentation; } var insertSpaces = defaultInsertSpaces; if (linesIndentedWithTabsCount !== linesIndentedWithSpacesCount) { insertSpaces = (linesIndentedWithTabsCount < linesIndentedWithSpacesCount); } var tabSize = defaultTabSize; // Guess tabSize only if inserting spaces... if (insertSpaces) { var tabSizeScore_1 = (insertSpaces ? 0 : 0.1 * linesCount); // console.log("score threshold: " + tabSizeScore); ALLOWED_TAB_SIZE_GUESSES.forEach(function (possibleTabSize) { var possibleTabSizeScore = spacesDiffCount[possibleTabSize]; if (possibleTabSizeScore > tabSizeScore_1) { tabSizeScore_1 = 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[344/*vs/editor/common/model/intervalTree*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 getNodeIsInOverviewRuler(node) { return ((node.metadata & 8 /* IsInOverviewRulerMask */) >>> 3 /* IsInOverviewRulerOffset */) === 1; } exports.getNodeIsInOverviewRuler = getNodeIsInOverviewRuler; function setNodeIsInOverviewRuler(node, value) { node.metadata = ((node.metadata & 247 /* IsInOverviewRulerMaskInverse */) | ((value ? 1 : 0) << 3 /* IsInOverviewRulerOffset */)); } function getNodeStickiness(node) { return ((node.metadata & 48 /* StickinessMask */) >>> 4 /* StickinessOffset */); } function _setNodeStickiness(node, stickiness) { node.metadata = ((node.metadata & 207 /* StickinessMaskInverse */) | (stickiness << 4 /* StickinessOffset */)); } function getCollapseOnReplaceEdit(node) { return ((node.metadata & 64 /* CollapseOnReplaceEditMask */) >>> 6 /* CollapseOnReplaceEditOffset */) === 1; } function setCollapseOnReplaceEdit(node, value) { node.metadata = ((node.metadata & 191 /* CollapseOnReplaceEditMaskInverse */) | ((value ? 1 : 0) << 6 /* CollapseOnReplaceEditOffset */)); } var IntervalNode = /** @class */ (function () { function IntervalNode(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 */); setNodeIsInOverviewRuler(this, false); setCollapseOnReplaceEdit(this, false); this.cachedVersionId = 0; this.cachedAbsoluteStart = start; this.cachedAbsoluteEnd = end; this.range = null; setNodeIsVisited(this, false); } IntervalNode.prototype.reset = function (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; }; IntervalNode.prototype.setOptions = function (options) { this.options = options; var className = this.options.className; setNodeIsForValidation(this, (className === "squiggly-error" /* EditorErrorDecoration */ || className === "squiggly-warning" /* EditorWarningDecoration */ || className === "squiggly-info" /* EditorInfoDecoration */)); _setNodeStickiness(this, this.options.stickiness); setNodeIsInOverviewRuler(this, (this.options.overviewRuler && this.options.overviewRuler.color) ? true : false); setCollapseOnReplaceEdit(this, this.options.collapseOnReplaceEdit); }; IntervalNode.prototype.setCachedOffsets = function (absoluteStart, absoluteEnd, cachedVersionId) { if (this.cachedVersionId !== cachedVersionId) { this.range = null; } this.cachedVersionId = cachedVersionId; this.cachedAbsoluteStart = absoluteStart; this.cachedAbsoluteEnd = absoluteEnd; }; IntervalNode.prototype.detach = function () { this.parent = null; this.left = null; this.right = null; }; return IntervalNode; }()); 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 */); var IntervalTree = /** @class */ (function () { function IntervalTree() { this.root = exports.SENTINEL; this.requestNormalizeDelta = false; } IntervalTree.prototype.intervalSearch = function (start, end, filterOwnerId, filterOutValidation, cachedVersionId) { if (this.root === exports.SENTINEL) { return []; } return intervalSearch(this, start, end, filterOwnerId, filterOutValidation, cachedVersionId); }; IntervalTree.prototype.search = function (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! */ IntervalTree.prototype.collectNodesFromOwner = function (ownerId) { return collectNodesFromOwner(this, ownerId); }; /** * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes! */ IntervalTree.prototype.collectNodesPostOrder = function () { return collectNodesPostOrder(this); }; IntervalTree.prototype.insert = function (node) { rbTreeInsert(this, node); this._normalizeDeltaIfNecessary(); }; IntervalTree.prototype.delete = function (node) { rbTreeDelete(this, node); this._normalizeDeltaIfNecessary(); }; IntervalTree.prototype.resolveNode = function (node, cachedVersionId) { var initialNode = node; var delta = 0; while (node !== this.root) { if (node === node.parent.right) { delta += node.parent.delta; } node = node.parent; } var nodeStart = initialNode.start + delta; var nodeEnd = initialNode.end + delta; initialNode.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId); }; IntervalTree.prototype.acceptReplace = function (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 var nodesOfInterest = searchForEditing(this, offset, offset + length); // (2) remove all nodes that are intersecting this edit for (var i = 0, len = nodesOfInterest.length; i < len; i++) { var 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 (var i = 0, len = nodesOfInterest.length; i < len; i++) { var 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(); }; IntervalTree.prototype._normalizeDeltaIfNecessary = function () { if (!this.requestNormalizeDelta) { return; } this.requestNormalizeDelta = false; normalizeDelta(this); }; return IntervalTree; }()); exports.IntervalTree = IntervalTree; //#region Delta Normalization function normalizeDelta(T) { var node = T.root; var 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) { var nodeStickiness = getNodeStickiness(node); var startStickToPreviousCharacter = (nodeStickiness === 0 /* AlwaysGrowsWhenTypingAtEdges */ || nodeStickiness === 2 /* GrowsOnlyWhenTypingBefore */); var endStickToPreviousCharacter = (nodeStickiness === 1 /* NeverGrowsWhenTypingAtEdges */ || nodeStickiness === 2 /* GrowsOnlyWhenTypingBefore */); var deletingCnt = (end - start); var insertingCnt = textLength; var commonLength = Math.min(deletingCnt, insertingCnt); var nodeStart = node.start; var startDone = false; var nodeEnd = node.end; var 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; } { var 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) { var 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; } } { var 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 var 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. var node = T.root; var delta = 0; var nodeMaxEnd = 0; var nodeStart = 0; var nodeEnd = 0; var result = []; var 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. var node = T.root; var delta = 0; var nodeMaxEnd = 0; var nodeStart = 0; var 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) { var node = T.root; var result = []; var 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) { var node = T.root; var result = []; var 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) { var node = T.root; var delta = 0; var nodeStart = 0; var nodeEnd = 0; var result = []; var 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); var 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. var node = T.root; var delta = 0; var nodeMaxEnd = 0; var nodeStart = 0; var nodeEnd = 0; var result = []; var 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); var 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 var x = newNode; while (x !== T.root && getNodeColor(x.parent) === 1 /* Red */) { if (x.parent === x.parent.parent.left) { var 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 { var 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) { var delta = 0; var x = T.root; var zAbsoluteStart = z.start; var zAbsoluteEnd = z.end; while (true) { var 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) { var x; var 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; } var 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 var 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) { var 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) { var 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) { var maxEnd = node.end; if (node.left !== exports.SENTINEL) { var leftMaxEnd = node.left.maxEnd; if (leftMaxEnd > maxEnd) { maxEnd = leftMaxEnd; } } if (node.right !== exports.SENTINEL) { var 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) { var 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[345/*vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var TreeNode = /** @class */ (function () { function TreeNode(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; } TreeNode.prototype.next = function () { if (this.right !== exports.SENTINEL) { return leftest(this.right); } var 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; } }; TreeNode.prototype.prev = function () { if (this.left !== exports.SENTINEL) { return righttest(this.left); } var 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; } }; TreeNode.prototype.detach = function () { this.parent = null; this.left = null; this.right = null; }; return TreeNode; }()); 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) { var 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) { var 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) { var x; var 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; } var 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) { var newSizeLeft = calculateSize(x); var newLFLeft = calculateLF(x); if (newSizeLeft !== x.parent.size_left || newLFLeft !== x.parent.lf_left) { var delta = newSizeLeft - x.parent.size_left; var 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 var 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) { var 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 { var 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) { var delta = 0; var lf_delta = 0; if (x === tree.root) { return; } if (delta === 0) { // go upwards till the node whose left subtree is changed. while (x !== tree.root && x === x.parent.right) { x = x.parent; } if (x === tree.root) { // well, it means we add a node to the end (inorder) return; } // x is the node whose right subtree is changed. x = x.parent; delta = calculateSize(x.left) - x.size_left; lf_delta = calculateLF(x.left) - x.lf_left; x.size_left += delta; x.lf_left += lf_delta; } // go upwards till root. O(logN) while (x !== tree.root && (delta !== 0 || lf_delta !== 0)) { if (x.parent.left === x) { x.parent.size_left += delta; x.parent.lf_left += lf_delta; } x = x.parent; } } exports.recomputeTreeMetadata = recomputeTreeMetadata; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[346/*vs/editor/common/model/textModelEvents*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * An event describing that a model has been reset to a new value. * @internal */ var ModelRawFlush = /** @class */ (function () { function ModelRawFlush() { this.changeType = 1 /* Flush */; } return ModelRawFlush; }()); exports.ModelRawFlush = ModelRawFlush; /** * An event describing that a line has changed in a model. * @internal */ var ModelRawLineChanged = /** @class */ (function () { function ModelRawLineChanged(lineNumber, detail) { this.changeType = 2 /* LineChanged */; this.lineNumber = lineNumber; this.detail = detail; } return ModelRawLineChanged; }()); exports.ModelRawLineChanged = ModelRawLineChanged; /** * An event describing that line(s) have been deleted in a model. * @internal */ var ModelRawLinesDeleted = /** @class */ (function () { function ModelRawLinesDeleted(fromLineNumber, toLineNumber) { this.changeType = 3 /* LinesDeleted */; this.fromLineNumber = fromLineNumber; this.toLineNumber = toLineNumber; } return ModelRawLinesDeleted; }()); exports.ModelRawLinesDeleted = ModelRawLinesDeleted; /** * An event describing that line(s) have been inserted in a model. * @internal */ var ModelRawLinesInserted = /** @class */ (function () { function ModelRawLinesInserted(fromLineNumber, toLineNumber, detail) { this.changeType = 4 /* LinesInserted */; this.fromLineNumber = fromLineNumber; this.toLineNumber = toLineNumber; this.detail = detail; } return ModelRawLinesInserted; }()); exports.ModelRawLinesInserted = ModelRawLinesInserted; /** * An event describing that a model has had its EOL changed. * @internal */ var ModelRawEOLChanged = /** @class */ (function () { function ModelRawEOLChanged() { this.changeType = 5 /* EOLChanged */; } return ModelRawEOLChanged; }()); exports.ModelRawEOLChanged = ModelRawEOLChanged; /** * An event describing a change in the text of a model. * @internal */ var ModelRawContentChangedEvent = /** @class */ (function () { function ModelRawContentChangedEvent(changes, versionId, isUndoing, isRedoing) { this.changes = changes; this.versionId = versionId; this.isUndoing = isUndoing; this.isRedoing = isRedoing; } ModelRawContentChangedEvent.prototype.containsEvent = function (type) { for (var i = 0, len = this.changes.length; i < len; i++) { var change = this.changes[i]; if (change.changeType === type) { return true; } } return false; }; ModelRawContentChangedEvent.merge = function (a, b) { var changes = [].concat(a.changes).concat(b.changes); var versionId = b.versionId; var isUndoing = (a.isUndoing || b.isUndoing); var isRedoing = (a.isRedoing || b.isRedoing); return new ModelRawContentChangedEvent(changes, versionId, isUndoing, isRedoing); }; return ModelRawContentChangedEvent; }()); exports.ModelRawContentChangedEvent = ModelRawContentChangedEvent; /** * @internal */ var InternalModelContentChangeEvent = /** @class */ (function () { function InternalModelContentChangeEvent(rawContentChangedEvent, contentChangedEvent) { this.rawContentChangedEvent = rawContentChangedEvent; this.contentChangedEvent = contentChangedEvent; } InternalModelContentChangeEvent.prototype.merge = function (other) { var rawContentChangedEvent = ModelRawContentChangedEvent.merge(this.rawContentChangedEvent, other.rawContentChangedEvent); var contentChangedEvent = InternalModelContentChangeEvent._mergeChangeEvents(this.contentChangedEvent, other.contentChangedEvent); return new InternalModelContentChangeEvent(rawContentChangedEvent, contentChangedEvent); }; InternalModelContentChangeEvent._mergeChangeEvents = function (a, b) { var changes = [].concat(a.changes).concat(b.changes); var eol = b.eol; var versionId = b.versionId; var isUndoing = (a.isUndoing || b.isUndoing); var isRedoing = (a.isRedoing || b.isRedoing); var isFlush = (a.isFlush || b.isFlush); return { changes: changes, eol: eol, versionId: versionId, isUndoing: isUndoing, isRedoing: isRedoing, isFlush: isFlush }; }; return InternalModelContentChangeEvent; }()); 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[144/*vs/editor/common/model/textModelSearch*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,89/*vs/editor/common/controller/wordCharacterClassifier*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,48/*vs/editor/common/model*/]), function (require, exports, strings, wordCharacterClassifier_1, position_1, range_1, model_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LIMIT_FIND_COUNT = 999; var SearchParams = /** @class */ (function () { function SearchParams(searchString, isRegex, matchCase, wordSeparators) { this.searchString = searchString; this.isRegex = isRegex; this.matchCase = matchCase; this.wordSeparators = wordSeparators; } SearchParams.prototype.parseSearchRequest = function () { if (this.searchString === '') { return null; } // Try to create a RegExp out of the params var multiline; if (this.isRegex) { multiline = isMultilineRegexSource(this.searchString); } else { multiline = (this.searchString.indexOf('\n') >= 0); } var 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; } var canUseSimpleSearch = (!this.isRegex && !multiline); if (canUseSimpleSearch && this.searchString.toLowerCase() !== this.searchString.toUpperCase()) { // casing might make a difference canUseSimpleSearch = this.matchCase; } return new SearchData(regex, this.wordSeparators ? wordCharacterClassifier_1.getMapForWordSeparators(this.wordSeparators) : null, canUseSimpleSearch ? this.searchString : null); }; return SearchParams; }()); exports.SearchParams = SearchParams; function isMultilineRegexSource(searchString) { if (!searchString || searchString.length === 0) { return false; } for (var i = 0, len = searchString.length; i < len; i++) { var chCode = searchString.charCodeAt(i); if (chCode === 92 /* Backslash */) { // move to next char i++; if (i >= len) { // string ends with a \ break; } var nextChCode = searchString.charCodeAt(i); if (nextChCode === 110 /* n */ || nextChCode === 114 /* r */ || nextChCode === 87 /* W */ || nextChCode === 119 /* w */) { return true; } } } return false; } exports.isMultilineRegexSource = isMultilineRegexSource; var SearchData = /** @class */ (function () { function SearchData(regex, wordSeparators, simpleSearch) { this.regex = regex; this.wordSeparators = wordSeparators; this.simpleSearch = simpleSearch; } return SearchData; }()); exports.SearchData = SearchData; function createFindMatch(range, rawMatches, captureMatches) { if (!captureMatches) { return new model_1.FindMatch(range, null); } var matches = []; for (var i = 0, len = rawMatches.length; i < len; i++) { matches[i] = rawMatches[i]; } return new model_1.FindMatch(range, matches); } exports.createFindMatch = createFindMatch; var LineFeedCounter = /** @class */ (function () { function LineFeedCounter(text) { var lineFeedsOffsets = []; var lineFeedsOffsetsLen = 0; for (var i = 0, textLen = text.length; i < textLen; i++) { if (text.charCodeAt(i) === 10 /* LineFeed */) { lineFeedsOffsets[lineFeedsOffsetsLen++] = i; } } this._lineFeedsOffsets = lineFeedsOffsets; } LineFeedCounter.prototype.findLineFeedCountBeforeOffset = function (offset) { var lineFeedsOffsets = this._lineFeedsOffsets; var min = 0; var 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) { var 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; }; return LineFeedCounter; }()); var TextModelSearch = /** @class */ (function () { function TextModelSearch() { } TextModelSearch.findMatches = function (model, searchParams, searchRange, captureMatches, limitResultCount) { var 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 */ TextModelSearch._getMultilineMatchRange = function (model, deltaOffset, text, lfCounter, matchIndex, match0) { var startOffset; var lineFeedCountBeforeMatch = 0; if (lfCounter) { lineFeedCountBeforeMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex); startOffset = deltaOffset + matchIndex + lineFeedCountBeforeMatch /* add as many \r as there were \n */; } else { startOffset = deltaOffset + matchIndex; } var endOffset; if (lfCounter) { var lineFeedCountBeforeEndOfMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex + match0.length); var lineFeedCountInMatch = lineFeedCountBeforeEndOfMatch - lineFeedCountBeforeMatch; endOffset = startOffset + match0.length + lineFeedCountInMatch /* add as many \r as there were \n */; } else { endOffset = startOffset + match0.length; } var startPosition = model.getPositionAt(startOffset); var endPosition = model.getPositionAt(endOffset); return new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column); }; TextModelSearch._doFindMatchesMultiline = function (model, searchRange, searcher, captureMatches, limitResultCount) { var 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` var text = model.getValueInRange(searchRange, 1 /* LF */); var lfCounter = (model.getEOL() === '\r\n' ? new LineFeedCounter(text) : null); var result = []; var counter = 0; var 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; }; TextModelSearch._doFindMatchesLineByLine = function (model, searchRange, searchData, captureMatches, limitResultCount) { var result = []; var resultLen = 0; // Early case for a search range that starts & stops on the same line number if (searchRange.startLineNumber === searchRange.endLineNumber) { var text_1 = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1, searchRange.endColumn - 1); resultLen = this._findMatchesInLine(searchData, text_1, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount); return result; } // Collect results from first line var 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 (var 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) { var text_2 = model.getLineContent(searchRange.endLineNumber).substring(0, searchRange.endColumn - 1); resultLen = this._findMatchesInLine(searchData, text_2, searchRange.endLineNumber, 0, resultLen, result, captureMatches, limitResultCount); } return result; }; TextModelSearch._findMatchesInLine = function (searchData, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) { var wordSeparators = searchData.wordSeparators; if (!captureMatches && searchData.simpleSearch) { var searchString = searchData.simpleSearch; var searchStringLen = searchString.length; var textLength = text.length; var 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; } var searcher = new Searcher(searchData.wordSeparators, searchData.regex); var 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; }; TextModelSearch.findNextMatch = function (model, searchParams, searchStart, captureMatches) { var searchData = searchParams.parseSearchRequest(); if (!searchData) { return null; } var 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); }; TextModelSearch._doFindNextMatchMultiline = function (model, searchStart, searcher, captureMatches) { var searchTextStart = new position_1.Position(searchStart.lineNumber, 1); var deltaOffset = model.getOffsetAt(searchTextStart); var 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` var text = model.getValueInRange(new range_1.Range(searchTextStart.lineNumber, searchTextStart.column, lineCount, model.getLineMaxColumn(lineCount)), 1 /* LF */); var lfCounter = (model.getEOL() === '\r\n' ? new LineFeedCounter(text) : null); searcher.reset(searchStart.column - 1); var 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; }; TextModelSearch._doFindNextMatchLineByLine = function (model, searchStart, searcher, captureMatches) { var lineCount = model.getLineCount(); var startLineNumber = searchStart.lineNumber; // Look in first line var text = model.getLineContent(startLineNumber); var r = this._findFirstMatchInLine(searcher, text, startLineNumber, searchStart.column, captureMatches); if (r) { return r; } for (var i = 1; i <= lineCount; i++) { var lineIndex = (startLineNumber + i - 1) % lineCount; var text_3 = model.getLineContent(lineIndex + 1); var r_1 = this._findFirstMatchInLine(searcher, text_3, lineIndex + 1, 1, captureMatches); if (r_1) { return r_1; } } return null; }; TextModelSearch._findFirstMatchInLine = function (searcher, text, lineNumber, fromColumn, captureMatches) { // Set regex to search from column searcher.reset(fromColumn - 1); var 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; }; TextModelSearch.findPreviousMatch = function (model, searchParams, searchStart, captureMatches) { var searchData = searchParams.parseSearchRequest(); if (!searchData) { return null; } var 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); }; TextModelSearch._doFindPreviousMatchMultiline = function (model, searchStart, searcher, captureMatches) { var 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]; } var 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; }; TextModelSearch._doFindPreviousMatchLineByLine = function (model, searchStart, searcher, captureMatches) { var lineCount = model.getLineCount(); var startLineNumber = searchStart.lineNumber; // Look in first line var text = model.getLineContent(startLineNumber).substring(0, searchStart.column - 1); var r = this._findLastMatchInLine(searcher, text, startLineNumber, captureMatches); if (r) { return r; } for (var i = 1; i <= lineCount; i++) { var lineIndex = (lineCount + startLineNumber - i - 1) % lineCount; var text_4 = model.getLineContent(lineIndex + 1); var r_2 = this._findLastMatchInLine(searcher, text_4, lineIndex + 1, captureMatches); if (r_2) { return r_2; } } return null; }; TextModelSearch._findLastMatchInLine = function (searcher, text, lineNumber, captureMatches) { var bestResult = null; var 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; }; return TextModelSearch; }()); exports.TextModelSearch = TextModelSearch; function leftIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength) { if (matchStartIndex === 0) { // Match starts at start of string return true; } var 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) { var 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; } var 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) { var 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; var Searcher = /** @class */ (function () { function Searcher(wordSeparators, searchRegex) { this._wordSeparators = wordSeparators; this._searchRegex = searchRegex; this._prevMatchStartIndex = -1; this._prevMatchLength = 0; } Searcher.prototype.reset = function (lastIndex) { this._searchRegex.lastIndex = lastIndex; this._prevMatchStartIndex = -1; this._prevMatchLength = 0; }; Searcher.prototype.next = function (text) { var textLength = text.length; var 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; } var matchStartIndex = m.index; var 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 one 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; }; return Searcher; }()); 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[191/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,48/*vs/editor/common/model*/,345/*vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase*/,144/*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 }); // const lfRegex = new RegExp(/\r\n|\r|\n/g); exports.AverageBufferSize = 65535; function createUintArray(arr) { var 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; var LineStarts = /** @class */ (function () { function LineStarts(lineStarts, cr, lf, crlf, isBasicASCII) { this.lineStarts = lineStarts; this.cr = cr; this.lf = lf; this.crlf = crlf; this.isBasicASCII = isBasicASCII; } return LineStarts; }()); exports.LineStarts = LineStarts; function createLineStartsFast(str, readonly) { if (readonly === void 0) { readonly = true; } var r = [0], rLength = 1; for (var i = 0, len = str.length; i < len; i++) { var 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; var rLength = 1; var cr = 0, lf = 0, crlf = 0; var isBasicASCII = true; for (var i = 0, len = str.length; i < len; i++) { var 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; } } } } var result = new LineStarts(createUintArray(r), cr, lf, crlf, isBasicASCII); r.length = 0; return result; } exports.createLineStarts = createLineStarts; var Piece = /** @class */ (function () { function Piece(bufferIndex, start, end, lineFeedCnt, length) { this.bufferIndex = bufferIndex; this.start = start; this.end = end; this.lineFeedCnt = lineFeedCnt; this.length = length; } return Piece; }()); exports.Piece = Piece; var StringBuffer = /** @class */ (function () { function StringBuffer(buffer, lineStarts) { this.buffer = buffer; this.lineStarts = lineStarts; } return StringBuffer; }()); exports.StringBuffer = StringBuffer; var PieceTreeSearchCache = /** @class */ (function () { function PieceTreeSearchCache(limit) { this._limit = limit; this._cache = []; } PieceTreeSearchCache.prototype.get = function (offset) { for (var i = this._cache.length - 1; i >= 0; i--) { var nodePos = this._cache[i]; if (nodePos.nodeStartOffset <= offset && nodePos.nodeStartOffset + nodePos.node.piece.length >= offset) { return nodePos; } } return null; }; PieceTreeSearchCache.prototype.get2 = function (lineNumber) { for (var i = this._cache.length - 1; i >= 0; i--) { var nodePos = this._cache[i]; if (nodePos.nodeStartLineNumber && nodePos.nodeStartLineNumber < lineNumber && nodePos.nodeStartLineNumber + nodePos.node.piece.lineFeedCnt >= lineNumber) { return nodePos; } } return null; }; PieceTreeSearchCache.prototype.set = function (nodePosition) { if (this._cache.length >= this._limit) { this._cache.shift(); } this._cache.push(nodePosition); }; PieceTreeSearchCache.prototype.valdiate = function (offset) { var hasInvalidVal = false; var tmp = this._cache; for (var i = 0; i < tmp.length; i++) { var nodePos = tmp[i]; if (nodePos.node.parent === null || nodePos.nodeStartOffset >= offset) { tmp[i] = null; hasInvalidVal = true; continue; } } if (hasInvalidVal) { var newArr = []; for (var _i = 0, tmp_1 = tmp; _i < tmp_1.length; _i++) { var entry = tmp_1[_i]; if (entry !== null) { newArr.push(entry); } } this._cache = newArr; } }; return PieceTreeSearchCache; }()); var PieceTreeBase = /** @class */ (function () { function PieceTreeBase(chunks, eol, eolNormalized) { this.create(chunks, eol, eolNormalized); } PieceTreeBase.prototype.create = function (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; var lastNode = null; for (var 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); } var piece = new Piece(i + 1, { line: 0, column: 0 }, { line: chunks[i].lineStarts.length - 1, column: chunks[i].buffer.length - chunks[i].lineStarts[chunks[i].lineStarts.length - 1] }, chunks[i].lineStarts.length - 1, chunks[i].buffer.length); this._buffers.push(chunks[i]); lastNode = this.rbInsertRight(lastNode, piece); } } this._searchCache = new PieceTreeSearchCache(1); this._lastVisitedLine = { lineNumber: 0, value: '' }; this.computeBufferMetadata(); }; PieceTreeBase.prototype.normalizeEOL = function (eol) { var _this = this; var averageBufferSize = exports.AverageBufferSize; var min = averageBufferSize - Math.floor(averageBufferSize / 3); var max = min * 2; var tempChunk = ''; var tempChunkLen = 0; var chunks = []; this.iterate(this.root, function (node) { var str = _this.getNodeContent(node); var len = str.length; if (tempChunkLen <= min || tempChunkLen + len < max) { tempChunk += str; tempChunkLen += len; return true; } // flush anyways var 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) { var text = tempChunk.replace(/\r\n|\r|\n/g, eol); chunks.push(new StringBuffer(text, createLineStartsFast(text))); } this.create(chunks, eol, true); }; // #region Buffer API PieceTreeBase.prototype.getEOL = function () { return this._EOL; }; PieceTreeBase.prototype.setEOL = function (newEOL) { this._EOL = newEOL; this._EOLLength = this._EOL.length; this.normalizeEOL(newEOL); }; PieceTreeBase.prototype.getOffsetAt = function (lineNumber, column) { var leftLen = 0; // inorder var 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 var 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; }; PieceTreeBase.prototype.getPositionAt = function (offset) { offset = Math.floor(offset); offset = Math.max(0, offset); var x = this.root; var lfCnt = 0; var 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) { var out = this.getIndexOf(x, offset - x.size_left); lfCnt += x.lf_left + out.index; if (out.index === 0) { var lineStartOffset = this.getOffsetAt(lfCnt + 1, 1); var 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 var lineStartOffset = this.getOffsetAt(lfCnt + 1, 1); var column = originalOffset - offset - lineStartOffset; return new position_1.Position(lfCnt + 1, column + 1); } else { x = x.right; } } } return new position_1.Position(1, 1); }; PieceTreeBase.prototype.getValueInRange = function (range, eol) { if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) { return ''; } var startPosition = this.nodeAt2(range.startLineNumber, range.startColumn); var endPosition = this.nodeAt2(range.endLineNumber, range.endColumn); var 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; }; PieceTreeBase.prototype.getValueInRange2 = function (startPosition, endPosition) { if (startPosition.node === endPosition.node) { var node = startPosition.node; var buffer_1 = this._buffers[node.piece.bufferIndex].buffer; var startOffset_1 = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start); return buffer_1.substring(startOffset_1 + startPosition.remainder, startOffset_1 + endPosition.remainder); } var x = startPosition.node; var buffer = this._buffers[x.piece.bufferIndex].buffer; var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); var ret = buffer.substring(startOffset + startPosition.remainder, startOffset + x.piece.length); x = x.next(); while (x !== rbTreeBase_1.SENTINEL) { var buffer_2 = this._buffers[x.piece.bufferIndex].buffer; var startOffset_2 = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); if (x === endPosition.node) { ret += buffer_2.substring(startOffset_2, startOffset_2 + endPosition.remainder); break; } else { ret += buffer_2.substr(startOffset_2, x.piece.length); } x = x.next(); } return ret; }; PieceTreeBase.prototype.getLinesContent = function () { var _this = this; var lines = []; var linesLength = 0; var currentLine = ''; var danglingCR = false; this.iterate(this.root, function (node) { if (node === rbTreeBase_1.SENTINEL) { return true; } var piece = node.piece; var pieceLength = piece.length; if (pieceLength === 0) { return true; } var buffer = _this._buffers[piece.bufferIndex].buffer; var lineStarts = _this._buffers[piece.bufferIndex].lineStarts; var pieceStartLine = piece.start.line; var pieceEndLine = piece.end.line; var 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 (var 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; }; PieceTreeBase.prototype.getLength = function () { return this._length; }; PieceTreeBase.prototype.getLineCount = function () { return this._lineCnt; }; PieceTreeBase.prototype.getLineContent = function (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; }; PieceTreeBase.prototype.getLineCharCode = function (lineNumber, index) { var nodePos = this.nodeAt2(lineNumber, index + 1); if (nodePos.remainder === nodePos.node.piece.length) { // the char we want to fetch is at the head of next node. var matchingNode = nodePos.node.next(); if (!matchingNode) { return 0; } var buffer = this._buffers[matchingNode.piece.bufferIndex]; var startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start); return buffer.buffer.charCodeAt(startOffset); } else { var buffer = this._buffers[nodePos.node.piece.bufferIndex]; var startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start); var targetOffset = startOffset + nodePos.remainder; return buffer.buffer.charCodeAt(targetOffset); } }; PieceTreeBase.prototype.getLineLength = function (lineNumber) { if (lineNumber === this.getLineCount()) { var startOffset = this.getOffsetAt(lineNumber, 1); return this.getLength() - startOffset; } return this.getOffsetAt(lineNumber + 1, 1) - this.getOffsetAt(lineNumber, 1) - this._EOLLength; }; PieceTreeBase.prototype.findMatchesInNode = function (node, searcher, startLineNumber, startColumn, startCursor, endCursor, searchData, captureMatches, limitResultCount, resultLen, result) { var buffer = this._buffers[node.piece.bufferIndex]; var startOffsetInBuffer = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start); var start = this.offsetInBuffer(node.piece.bufferIndex, startCursor); var end = this.offsetInBuffer(node.piece.bufferIndex, endCursor); var m; // Reset regex to search from the beginning var ret = { line: 0, column: 0 }; var searchText; var offsetInBuffer; if (searcher._wordSeparators) { searchText = buffer.buffer.substring(start, end); offsetInBuffer = function (offset) { return offset + start; }; searcher.reset(-1); } else { searchText = buffer.buffer; offsetInBuffer = function (offset) { return 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); var lineFeedCnt = this.getLineFeedCnt(node.piece.bufferIndex, startCursor, ret); var retStartColumn = ret.line === startCursor.line ? ret.column - startCursor.column + startColumn : ret.column + 1; var retEndColumn = retStartColumn + m[0].length; result[resultLen++] = 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; }; PieceTreeBase.prototype.findMatchesLineByLine = function (searchRange, searchData, captureMatches, limitResultCount) { var result = []; var resultLen = 0; var searcher = new textModelSearch_1.Searcher(searchData.wordSeparators, searchData.regex); var startPosition = this.nodeAt2(searchRange.startLineNumber, searchRange.startColumn); if (startPosition === null) { return []; } var endPosition = this.nodeAt2(searchRange.endLineNumber, searchRange.endColumn); if (endPosition === null) { return []; } var start = this.positionInBuffer(startPosition.node, startPosition.remainder); var 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; } var startLineNumber = searchRange.startLineNumber; var currentNode = startPosition.node; while (currentNode !== endPosition.node) { var lineBreakCnt = this.getLineFeedCnt(currentNode.piece.bufferIndex, start, currentNode.piece.end); if (lineBreakCnt >= 1) { // last line break position var lineStarts = this._buffers[currentNode.piece.bufferIndex].lineStarts; var startOffsetInBuffer = this.offsetInBuffer(currentNode.piece.bufferIndex, currentNode.piece.start); var nextLineStartOffset = lineStarts[start.line + lineBreakCnt]; var startColumn_1 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1; resultLen = this.findMatchesInNode(currentNode, searcher, startLineNumber, startColumn_1, start, this.positionInBuffer(currentNode, nextLineStartOffset - startOffsetInBuffer), searchData, captureMatches, limitResultCount, resultLen, result); if (resultLen >= limitResultCount) { return result; } startLineNumber += lineBreakCnt; } var startColumn_2 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0; // search for the remaining content if (startLineNumber === searchRange.endLineNumber) { var text = this.getLineContent(startLineNumber).substring(startColumn_2, searchRange.endColumn - 1); resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn_2, resultLen, result, captureMatches, limitResultCount); return result; } resultLen = this._findMatchesInLine(searchData, searcher, this.getLineContent(startLineNumber).substr(startColumn_2), startLineNumber, startColumn_2, 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) { var startColumn_3 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0; var text = this.getLineContent(startLineNumber).substring(startColumn_3, searchRange.endColumn - 1); resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn_3, resultLen, result, captureMatches, limitResultCount); return result; } var startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1; resultLen = this.findMatchesInNode(endPosition.node, searcher, startLineNumber, startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result); return result; }; PieceTreeBase.prototype._findMatchesInLine = function (searchData, searcher, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) { var wordSeparators = searchData.wordSeparators; if (!captureMatches && searchData.simpleSearch) { var searchString = searchData.simpleSearch; var searchStringLen = searchString.length; var textLength = text.length; var lastMatchIndex = -searchStringLen; while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) { if (!wordSeparators || 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; } var m; // Reset regex to search from the beginning searcher.reset(0); do { m = searcher.next(text); if (m) { result[resultLen++] = 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 PieceTreeBase.prototype.insert = function (offset, value, eolNormalized) { if (eolNormalized === void 0) { eolNormalized = false; } this._EOLNormalized = this._EOLNormalized && eolNormalized; this._lastVisitedLine.lineNumber = 0; this._lastVisitedLine.value = ''; if (this.root !== rbTreeBase_1.SENTINEL) { var _a = this.nodeAt(offset), node = _a.node, remainder = _a.remainder, nodeStartOffset = _a.nodeStartOffset; var piece = node.piece; var bufferIndex = piece.bufferIndex; var 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.valdiate(offset); } else if (nodeStartOffset + node.piece.length > offset) { // we are inserting into the middle of a node. var nodesToDel = []; var newRightPiece = new Piece(piece.bufferIndex, insertPosInBuffer, piece.end, this.getLineFeedCnt(piece.bufferIndex, insertPosInBuffer, piece.end), this.offsetInBuffer(bufferIndex, piece.end) - this.offsetInBuffer(bufferIndex, insertPosInBuffer)); if (this.shouldCheckCRLF() && this.endWithCR(value)) { var headOfRight = this.nodeCharCodeAt(node, remainder); if (headOfRight === 10 /** \n */) { var 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)) { var tailOfLeft = this.nodeCharCodeAt(node, remainder - 1); if (tailOfLeft === 13 /** \r */) { var 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); } var newPieces = this.createNewPieces(value); if (newRightPiece.length > 0) { this.rbInsertRight(node, newRightPiece); } var tmpNode = node; for (var k = 0; k < newPieces.length; k++) { tmpNode = this.rbInsertRight(tmpNode, newPieces[k]); } this.deleteNodes(nodesToDel); } else { this.insertContentToNodeRight(value, node); } } else { // insert new node var pieces = this.createNewPieces(value); var node = this.rbInsertLeft(null, pieces[0]); for (var 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(); }; PieceTreeBase.prototype.delete = function (offset, cnt) { this._lastVisitedLine.lineNumber = 0; this._lastVisitedLine.value = ''; if (cnt <= 0 || this.root === rbTreeBase_1.SENTINEL) { return; } var startPosition = this.nodeAt(offset); var endPosition = this.nodeAt(offset + cnt); var startNode = startPosition.node; var endNode = endPosition.node; if (startNode === endNode) { var startSplitPosInBuffer_1 = this.positionInBuffer(startNode, startPosition.remainder); var endSplitPosInBuffer_1 = this.positionInBuffer(startNode, endPosition.remainder); if (startPosition.nodeStartOffset === offset) { if (cnt === startNode.piece.length) { // delete node var next = startNode.next(); rbTreeBase_1.rbDelete(this, startNode); this.validateCRLFWithPrevNode(next); this.computeBufferMetadata(); return; } this.deleteNodeHead(startNode, endSplitPosInBuffer_1); this._searchCache.valdiate(offset); this.validateCRLFWithPrevNode(startNode); this.computeBufferMetadata(); return; } if (startPosition.nodeStartOffset + startNode.piece.length === offset + cnt) { this.deleteNodeTail(startNode, startSplitPosInBuffer_1); this.validateCRLFWithNextNode(startNode); this.computeBufferMetadata(); return; } // delete content in the middle, this node will be splitted to nodes this.shrinkNode(startNode, startSplitPosInBuffer_1, endSplitPosInBuffer_1); this.computeBufferMetadata(); return; } var nodesToDel = []; var startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder); this.deleteNodeTail(startNode, startSplitPosInBuffer); this._searchCache.valdiate(offset); if (startNode.piece.length === 0) { nodesToDel.push(startNode); } // update last touched node var endSplitPosInBuffer = this.positionInBuffer(endNode, endPosition.remainder); this.deleteNodeHead(endNode, endSplitPosInBuffer); if (endNode.piece.length === 0) { nodesToDel.push(endNode); } // delete nodes in between var secondNode = startNode.next(); for (var node = secondNode; node !== rbTreeBase_1.SENTINEL && node !== endNode; node = node.next()) { nodesToDel.push(node); } var prev = startNode.piece.length === 0 ? startNode.prev() : startNode; this.deleteNodes(nodesToDel); this.validateCRLFWithNextNode(prev); this.computeBufferMetadata(); }; PieceTreeBase.prototype.insertContentToNodeLeft = function (value, node) { // we are inserting content to the beginning of node var nodesToDel = []; if (this.shouldCheckCRLF() && this.endWithCR(value) && this.startWithLF(node)) { // move `\n` to new node. var piece = node.piece; var newStart = { line: piece.start.line + 1, column: 0 }; var nPiece = new Piece(piece.bufferIndex, newStart, piece.end, this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end), piece.length - 1); node.piece = nPiece; value += '\n'; rbTreeBase_1.updateTreeMetadata(this, node, -1, -1); if (node.piece.length === 0) { nodesToDel.push(node); } } var newPieces = this.createNewPieces(value); var newNode = this.rbInsertLeft(node, newPieces[newPieces.length - 1]); for (var k = newPieces.length - 2; k >= 0; k--) { newNode = this.rbInsertLeft(newNode, newPieces[k]); } this.validateCRLFWithPrevNode(newNode); this.deleteNodes(nodesToDel); }; PieceTreeBase.prototype.insertContentToNodeRight = function (value, node) { // we are inserting to the right of this node. if (this.adjustCarriageReturnFromNext(value, node)) { // move \n to the new node. value += '\n'; } var newPieces = this.createNewPieces(value); var newNode = this.rbInsertRight(node, newPieces[0]); var tmpNode = newNode; for (var k = 1; k < newPieces.length; k++) { tmpNode = this.rbInsertRight(tmpNode, newPieces[k]); } this.validateCRLFWithPrevNode(newNode); }; PieceTreeBase.prototype.positionInBuffer = function (node, remainder, ret) { var piece = node.piece; var bufferIndex = node.piece.bufferIndex; var lineStarts = this._buffers[bufferIndex].lineStarts; var startOffset = lineStarts[piece.start.line] + piece.start.column; var offset = startOffset + remainder; // binary search offset between startOffset and endOffset var low = piece.start.line; var high = piece.end.line; var mid = 0; var midStop = 0; var 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 }; }; PieceTreeBase.prototype.getLineFeedCnt = function (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; } var 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; } var nextLineStartOffset = lineStarts[end.line + 1]; var 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. var previousCharOffset = endOffset - 1; // end.column > 0 so it's okay. var buffer = this._buffers[bufferIndex].buffer; if (buffer.charCodeAt(previousCharOffset) === 13) { return end.line - start.line + 1; } else { return end.line - start.line; } }; PieceTreeBase.prototype.offsetInBuffer = function (bufferIndex, cursor) { var lineStarts = this._buffers[bufferIndex].lineStarts; return lineStarts[cursor.line] + cursor.column; }; PieceTreeBase.prototype.deleteNodes = function (nodes) { for (var i = 0; i < nodes.length; i++) { rbTreeBase_1.rbDelete(this, nodes[i]); } }; PieceTreeBase.prototype.createNewPieces = function (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 var newPieces = []; while (text.length > exports.AverageBufferSize) { var lastChar = text.charCodeAt(exports.AverageBufferSize - 1); var splitText = void 0; 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); } var lineStarts_1 = createLineStartsFast(splitText); newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts_1.length - 1, column: splitText.length - lineStarts_1[lineStarts_1.length - 1] }, lineStarts_1.length - 1, splitText.length)); this._buffers.push(new StringBuffer(splitText, lineStarts_1)); } var lineStarts_2 = createLineStartsFast(text); newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts_2.length - 1, column: text.length - lineStarts_2[lineStarts_2.length - 1] }, lineStarts_2.length - 1, text.length)); this._buffers.push(new StringBuffer(text, lineStarts_2)); return newPieces; } var startOffset = this._buffers[0].buffer.length; var lineStarts = createLineStartsFast(text, false); var 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 (var 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 (var 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; } var endOffset = this._buffers[0].buffer.length; var endIndex = this._buffers[0].lineStarts.length - 1; var endColumn = endOffset - this._buffers[0].lineStarts[endIndex]; var endPos = { line: endIndex, column: endColumn }; var newPiece = new Piece(0, /** todo@peng */ start, endPos, this.getLineFeedCnt(0, start, endPos), endOffset - startOffset); this._lastChangeBufferPos = endPos; return [newPiece]; }; PieceTreeBase.prototype.getLineRawContent = function (lineNumber, endOffset) { if (endOffset === void 0) { endOffset = 0; } var x = this.root; var ret = ''; var cache = this._searchCache.get2(lineNumber); if (cache) { x = cache.node; var prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber - 1); var buffer = this._buffers[x.piece.bufferIndex].buffer; var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); if (cache.nodeStartLineNumber + x.piece.lineFeedCnt === lineNumber) { ret = buffer.substring(startOffset + prevAccumualtedValue, startOffset + x.piece.length); } else { var accumualtedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber); return buffer.substring(startOffset + prevAccumualtedValue, startOffset + accumualtedValue - endOffset); } } else { var nodeStartOffset = 0; var 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) { var prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2); var accumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1); var buffer = this._buffers[x.piece.bufferIndex].buffer; var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); nodeStartOffset += x.size_left; this._searchCache.set({ node: x, nodeStartOffset: nodeStartOffset, nodeStartLineNumber: originalLineNumber - (lineNumber - 1 - x.lf_left) }); return buffer.substring(startOffset + prevAccumualtedValue, startOffset + accumualtedValue - endOffset); } else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) { var prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2); var buffer = this._buffers[x.piece.bufferIndex].buffer; var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); ret = buffer.substring(startOffset + prevAccumualtedValue, 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) { var buffer = this._buffers[x.piece.bufferIndex].buffer; if (x.piece.lineFeedCnt > 0) { var accumualtedValue = this.getAccumulatedValue(x, 0); var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); ret += buffer.substring(startOffset, startOffset + accumualtedValue - endOffset); return ret; } else { var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); ret += buffer.substr(startOffset, x.piece.length); } x = x.next(); } return ret; }; PieceTreeBase.prototype.computeBufferMetadata = function () { var x = this.root; var lfCnt = 1; var 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.valdiate(this._length); }; // #region node operations PieceTreeBase.prototype.getIndexOf = function (node, accumulatedValue) { var piece = node.piece; var pos = this.positionInBuffer(node, accumulatedValue); var 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. var 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 }; }; PieceTreeBase.prototype.getAccumulatedValue = function (node, index) { if (index < 0) { return 0; } var piece = node.piece; var lineStarts = this._buffers[piece.bufferIndex].lineStarts; var 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; } }; PieceTreeBase.prototype.deleteNodeTail = function (node, pos) { var piece = node.piece; var originalLFCnt = piece.lineFeedCnt; var originalEndOffset = this.offsetInBuffer(piece.bufferIndex, piece.end); var newEnd = pos; var newEndOffset = this.offsetInBuffer(piece.bufferIndex, newEnd); var newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd); var lf_delta = newLineFeedCnt - originalLFCnt; var size_delta = newEndOffset - originalEndOffset; var newLength = piece.length + size_delta; node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength); rbTreeBase_1.updateTreeMetadata(this, node, size_delta, lf_delta); }; PieceTreeBase.prototype.deleteNodeHead = function (node, pos) { var piece = node.piece; var originalLFCnt = piece.lineFeedCnt; var originalStartOffset = this.offsetInBuffer(piece.bufferIndex, piece.start); var newStart = pos; var newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end); var newStartOffset = this.offsetInBuffer(piece.bufferIndex, newStart); var lf_delta = newLineFeedCnt - originalLFCnt; var size_delta = originalStartOffset - newStartOffset; var newLength = piece.length + size_delta; node.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength); rbTreeBase_1.updateTreeMetadata(this, node, size_delta, lf_delta); }; PieceTreeBase.prototype.shrinkNode = function (node, start, end) { var piece = node.piece; var originalStartPos = piece.start; var originalEndPos = piece.end; // old piece, originalStartPos, start var oldLength = piece.length; var oldLFCnt = piece.lineFeedCnt; var newEnd = start; var newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd); var newLength = this.offsetInBuffer(piece.bufferIndex, start) - this.offsetInBuffer(piece.bufferIndex, originalStartPos); node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength); rbTreeBase_1.updateTreeMetadata(this, node, newLength - oldLength, newLineFeedCnt - oldLFCnt); // new right piece, end, originalEndPos var newPiece = new Piece(piece.bufferIndex, end, originalEndPos, this.getLineFeedCnt(piece.bufferIndex, end, originalEndPos), this.offsetInBuffer(piece.bufferIndex, originalEndPos) - this.offsetInBuffer(piece.bufferIndex, end)); var newNode = this.rbInsertRight(node, newPiece); this.validateCRLFWithPrevNode(newNode); }; PieceTreeBase.prototype.appendToNode = function (node, value) { if (this.adjustCarriageReturnFromNext(value, node)) { value += '\n'; } var hitCRLF = this.shouldCheckCRLF() && this.startWithLF(value) && this.endWithCR(node); var startOffset = this._buffers[0].buffer.length; this._buffers[0].buffer += value; var lineStarts = createLineStartsFast(value, false); for (var i = 0; i < lineStarts.length; i++) { lineStarts[i] += startOffset; } if (hitCRLF) { var 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)); var endIndex = this._buffers[0].lineStarts.length - 1; var endColumn = this._buffers[0].buffer.length - this._buffers[0].lineStarts[endIndex]; var newEnd = { line: endIndex, column: endColumn }; var newLength = node.piece.length + value.length; var oldLineFeedCnt = node.piece.lineFeedCnt; var newLineFeedCnt = this.getLineFeedCnt(0, node.piece.start, newEnd); var lf_delta = newLineFeedCnt - oldLineFeedCnt; node.piece = new Piece(node.piece.bufferIndex, node.piece.start, newEnd, newLineFeedCnt, newLength); this._lastChangeBufferPos = newEnd; rbTreeBase_1.updateTreeMetadata(this, node, value.length, lf_delta); }; PieceTreeBase.prototype.nodeAt = function (offset) { var x = this.root; var cache = this._searchCache.get(offset); if (cache) { return { node: cache.node, nodeStartOffset: cache.nodeStartOffset, remainder: offset - cache.nodeStartOffset }; } var 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; var ret = { node: x, remainder: offset - x.size_left, nodeStartOffset: 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; }; PieceTreeBase.prototype.nodeAt2 = function (lineNumber, column) { var x = this.root; var 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) { var prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2); var accumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1); nodeStartOffset += x.size_left; return { node: x, remainder: Math.min(prevAccumualtedValue + column - 1, accumualtedValue), nodeStartOffset: nodeStartOffset }; } else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) { var prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2); if (prevAccumualtedValue + column - 1 <= x.piece.length) { return { node: x, remainder: prevAccumualtedValue + column - 1, nodeStartOffset: 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) { var accumualtedValue = this.getAccumulatedValue(x, 0); var nodeStartOffset_1 = this.offsetOfNode(x); return { node: x, remainder: Math.min(column - 1, accumualtedValue), nodeStartOffset: nodeStartOffset_1 }; } else { if (x.piece.length >= column - 1) { var nodeStartOffset_2 = this.offsetOfNode(x); return { node: x, remainder: column - 1, nodeStartOffset: nodeStartOffset_2 }; } else { column -= x.piece.length; } } x = x.next(); } return null; }; PieceTreeBase.prototype.nodeCharCodeAt = function (node, offset) { if (node.piece.lineFeedCnt < 1) { return -1; } var buffer = this._buffers[node.piece.bufferIndex]; var newOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start) + offset; return buffer.buffer.charCodeAt(newOffset); }; PieceTreeBase.prototype.offsetOfNode = function (node) { if (!node) { return 0; } var 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 PieceTreeBase.prototype.shouldCheckCRLF = function () { return !(this._EOLNormalized && this._EOL === '\n'); }; PieceTreeBase.prototype.startWithLF = function (val) { if (typeof val === 'string') { return val.charCodeAt(0) === 10; } if (val === rbTreeBase_1.SENTINEL || val.piece.lineFeedCnt === 0) { return false; } var piece = val.piece; var lineStarts = this._buffers[piece.bufferIndex].lineStarts; var line = piece.start.line; var 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; } var nextLineOffset = lineStarts[line + 1]; if (nextLineOffset > startOffset + 1) { return false; } return this._buffers[piece.bufferIndex].buffer.charCodeAt(startOffset) === 10; }; PieceTreeBase.prototype.endWithCR = function (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; }; PieceTreeBase.prototype.validateCRLFWithPrevNode = function (nextNode) { if (this.shouldCheckCRLF() && this.startWithLF(nextNode)) { var node = nextNode.prev(); if (this.endWithCR(node)) { this.fixCRLF(node, nextNode); } } }; PieceTreeBase.prototype.validateCRLFWithNextNode = function (node) { if (this.shouldCheckCRLF() && this.endWithCR(node)) { var nextNode = node.next(); if (this.startWithLF(nextNode)) { this.fixCRLF(node, nextNode); } } }; PieceTreeBase.prototype.fixCRLF = function (prev, next) { var nodesToDel = []; // update node var lineStarts = this._buffers[prev.piece.bufferIndex].lineStarts; var 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 }; } var prevNewLength = prev.piece.length - 1; var prevNewLFCnt = prev.piece.lineFeedCnt - 1; prev.piece = new Piece(prev.piece.bufferIndex, prev.piece.start, newEnd, prevNewLFCnt, prevNewLength); rbTreeBase_1.updateTreeMetadata(this, prev, -1, -1); if (prev.piece.length === 0) { nodesToDel.push(prev); } // update nextNode var newStart = { line: next.piece.start.line + 1, column: 0 }; var newLength = next.piece.length - 1; var newLineFeedCnt = this.getLineFeedCnt(next.piece.bufferIndex, newStart, next.piece.end); next.piece = new Piece(next.piece.bufferIndex, newStart, next.piece.end, newLineFeedCnt, newLength); rbTreeBase_1.updateTreeMetadata(this, next, -1, -1); if (next.piece.length === 0) { nodesToDel.push(next); } // create new piece which contains \r\n var pieces = this.createNewPieces('\r\n'); this.rbInsertRight(prev, pieces[0]); // delete empty nodes for (var i = 0; i < nodesToDel.length; i++) { rbTreeBase_1.rbDelete(this, nodesToDel[i]); } }; PieceTreeBase.prototype.adjustCarriageReturnFromNext = function (value, node) { if (this.shouldCheckCRLF() && this.endWithCR(value)) { var nextNode = node.next(); if (this.startWithLF(nextNode)) { // move `\n` forward value += '\n'; if (nextNode.piece.length === 1) { rbTreeBase_1.rbDelete(this, nextNode); } else { var piece = nextNode.piece; var newStart = { line: piece.start.line + 1, column: 0 }; var newLength = piece.length - 1; var newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end); nextNode.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength); rbTreeBase_1.updateTreeMetadata(this, nextNode, -1, -1); } return true; } } return false; }; // #endregion // #endregion // #region Tree operations PieceTreeBase.prototype.iterate = function (node, callback) { if (node === rbTreeBase_1.SENTINEL) { return callback(rbTreeBase_1.SENTINEL); } var leftRet = this.iterate(node.left, callback); if (!leftRet) { return leftRet; } return callback(node) && this.iterate(node.right, callback); }; PieceTreeBase.prototype.getNodeContent = function (node) { if (node === rbTreeBase_1.SENTINEL) { return ''; } var buffer = this._buffers[node.piece.bufferIndex]; var currentContent; var piece = node.piece; var startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start); var endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end); currentContent = buffer.buffer.substring(startOffset, endOffset); return currentContent; }; /** * node node * / \ / \ * a b <---- a b * / * z */ PieceTreeBase.prototype.rbInsertRight = function (node, p) { var 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; var 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 { var nextNode = rbTreeBase_1.leftest(node.right); nextNode.left = z; z.parent = nextNode; } rbTreeBase_1.fixInsert(this, z); return z; }; /** * node node * / \ / \ * a b ----> a b * \ * z */ PieceTreeBase.prototype.rbInsertLeft = function (node, p) { var 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 { var prevNode = rbTreeBase_1.righttest(node.left); // a prevNode.right = z; z.parent = prevNode; } rbTreeBase_1.fixInsert(this, z); return z; }; return PieceTreeBase; }()); 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[347/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/,48/*vs/editor/common/model*/,191/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/]), function (require, exports, strings, range_1, model_1, pieceTreeBase_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var PieceTreeTextBuffer = /** @class */ (function () { function PieceTreeTextBuffer(chunks, BOM, eol, containsRTL, isBasicASCII, eolNormalized) { this._BOM = BOM; this._mightContainNonBasicASCII = !isBasicASCII; this._mightContainRTL = containsRTL; this._pieceTree = new pieceTreeBase_1.PieceTreeBase(chunks, eol, eolNormalized); } PieceTreeTextBuffer.prototype.mightContainRTL = function () { return this._mightContainRTL; }; PieceTreeTextBuffer.prototype.mightContainNonBasicASCII = function () { return this._mightContainNonBasicASCII; }; PieceTreeTextBuffer.prototype.getBOM = function () { return this._BOM; }; PieceTreeTextBuffer.prototype.getEOL = function () { return this._pieceTree.getEOL(); }; PieceTreeTextBuffer.prototype.getOffsetAt = function (lineNumber, column) { return this._pieceTree.getOffsetAt(lineNumber, column); }; PieceTreeTextBuffer.prototype.getPositionAt = function (offset) { return this._pieceTree.getPositionAt(offset); }; PieceTreeTextBuffer.prototype.getRangeAt = function (start, length) { var end = start + length; var startPosition = this.getPositionAt(start); var endPosition = this.getPositionAt(end); return new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column); }; PieceTreeTextBuffer.prototype.getValueInRange = function (range, eol) { if (eol === void 0) { eol = 0 /* TextDefined */; } if (range.isEmpty()) { return ''; } var lineEnding = this._getEndOfLine(eol); return this._pieceTree.getValueInRange(range, lineEnding); }; PieceTreeTextBuffer.prototype.getValueLengthInRange = function (range, eol) { if (eol === void 0) { eol = 0 /* TextDefined */; } if (range.isEmpty()) { return 0; } if (range.startLineNumber === range.endLineNumber) { return (range.endColumn - range.startColumn); } var startOffset = this.getOffsetAt(range.startLineNumber, range.startColumn); var endOffset = this.getOffsetAt(range.endLineNumber, range.endColumn); return endOffset - startOffset; }; PieceTreeTextBuffer.prototype.getCharacterCountInRange = function (range, eol) { if (eol === void 0) { eol = 0 /* TextDefined */; } if (this._mightContainNonBasicASCII) { // we must count by iterating var result = 0; var fromLineNumber = range.startLineNumber; var toLineNumber = range.endLineNumber; for (var lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) { var lineContent = this.getLineContent(lineNumber); var fromOffset = (lineNumber === fromLineNumber ? range.startColumn - 1 : 0); var toOffset = (lineNumber === toLineNumber ? range.endColumn - 1 : lineContent.length); for (var 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); }; PieceTreeTextBuffer.prototype.getLength = function () { return this._pieceTree.getLength(); }; PieceTreeTextBuffer.prototype.getLineCount = function () { return this._pieceTree.getLineCount(); }; PieceTreeTextBuffer.prototype.getLinesContent = function () { return this._pieceTree.getLinesContent(); }; PieceTreeTextBuffer.prototype.getLineContent = function (lineNumber) { return this._pieceTree.getLineContent(lineNumber); }; PieceTreeTextBuffer.prototype.getLineCharCode = function (lineNumber, index) { return this._pieceTree.getLineCharCode(lineNumber, index); }; PieceTreeTextBuffer.prototype.getLineLength = function (lineNumber) { return this._pieceTree.getLineLength(lineNumber); }; PieceTreeTextBuffer.prototype.getLineFirstNonWhitespaceColumn = function (lineNumber) { var result = strings.firstNonWhitespaceIndex(this.getLineContent(lineNumber)); if (result === -1) { return 0; } return result + 1; }; PieceTreeTextBuffer.prototype.getLineLastNonWhitespaceColumn = function (lineNumber) { var result = strings.lastNonWhitespaceIndex(this.getLineContent(lineNumber)); if (result === -1) { return 0; } return result + 2; }; PieceTreeTextBuffer.prototype._getEndOfLine = function (eol) { switch (eol) { case 1 /* LF */: return '\n'; case 2 /* CRLF */: return '\r\n'; case 0 /* TextDefined */: return this.getEOL(); } throw new Error('Unknown EOL preference'); }; PieceTreeTextBuffer.prototype.setEOL = function (newEOL) { this._pieceTree.setEOL(newEOL); }; PieceTreeTextBuffer.prototype.applyEdits = function (rawOperations, recordTrimAutoWhitespace) { var mightContainRTL = this._mightContainRTL; var mightContainNonBasicASCII = this._mightContainNonBasicASCII; var canReduceOperations = true; var operations = []; for (var i = 0; i < rawOperations.length; i++) { var op = rawOperations[i]; if (canReduceOperations && op._isTracked) { canReduceOperations = false; } var validatedRange = op.range; if (!mightContainRTL && op.text) { // check if the new inserted text contains RTL mightContainRTL = strings.containsRTL(op.text); } if (!mightContainNonBasicASCII && op.text) { mightContainNonBasicASCII = !strings.isBasicASCII(op.text); } operations[i] = { sortIndex: i, identifier: op.identifier || null, range: validatedRange, rangeOffset: this.getOffsetAt(validatedRange.startLineNumber, validatedRange.startColumn), rangeLength: this.getValueLengthInRange(validatedRange), lines: op.text ? op.text.split(/\r\n|\r|\n/) : null, forceMoveMarkers: Boolean(op.forceMoveMarkers), isAutoWhitespaceEdit: op.isAutoWhitespaceEdit || false }; } // Sort operations ascending operations.sort(PieceTreeTextBuffer._sortOpsAscending); var hasTouchingRanges = false; for (var i = 0, count = operations.length - 1; i < count; i++) { var rangeEnd = operations[i].range.getEndPosition(); var 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 var reverseRanges = PieceTreeTextBuffer._getInverseEditRanges(operations); var newTrimAutoWhitespaceCandidates = []; for (var i = 0; i < operations.length; i++) { var op = operations[i]; var reverseRange = reverseRanges[i]; if (recordTrimAutoWhitespace && op.isAutoWhitespaceEdit && op.range.isEmpty()) { // Record already the future line numbers that might be auto whitespace removal candidates on next edit for (var lineNumber = reverseRange.startLineNumber; lineNumber <= reverseRange.endLineNumber; lineNumber++) { var currentLineContent = ''; if (lineNumber === reverseRange.startLineNumber) { currentLineContent = this.getLineContent(op.range.startLineNumber); if (strings.firstNonWhitespaceIndex(currentLineContent) !== -1) { continue; } } newTrimAutoWhitespaceCandidates.push({ lineNumber: lineNumber, oldContent: currentLineContent }); } } } var reverseOperations = []; for (var i = 0; i < operations.length; i++) { var op = operations[i]; var reverseRange = reverseRanges[i]; reverseOperations[i] = { sortIndex: op.sortIndex, identifier: op.identifier, range: reverseRange, text: this.getValueInRange(op.range), forceMoveMarkers: op.forceMoveMarkers }; } // Can only sort reverse operations when the order is not significant if (!hasTouchingRanges) { reverseOperations.sort(function (a, b) { return a.sortIndex - b.sortIndex; }); } this._mightContainRTL = mightContainRTL; this._mightContainNonBasicASCII = mightContainNonBasicASCII; var contentChanges = this._doApplyEdits(operations); var trimAutoWhitespaceLineNumbers = null; if (recordTrimAutoWhitespace && newTrimAutoWhitespaceCandidates.length > 0) { // sort line numbers auto whitespace removal candidates for next edit descending newTrimAutoWhitespaceCandidates.sort(function (a, b) { return b.lineNumber - a.lineNumber; }); trimAutoWhitespaceLineNumbers = []; for (var i = 0, len = newTrimAutoWhitespaceCandidates.length; i < len; i++) { var lineNumber = newTrimAutoWhitespaceCandidates[i].lineNumber; if (i > 0 && newTrimAutoWhitespaceCandidates[i - 1].lineNumber === lineNumber) { // Do not have the same line number twice continue; } var prevContent = newTrimAutoWhitespaceCandidates[i].oldContent; var lineContent = this.getLineContent(lineNumber); if (lineContent.length === 0 || lineContent === prevContent || strings.firstNonWhitespaceIndex(lineContent) !== -1) { continue; } trimAutoWhitespaceLineNumbers.push(lineNumber); } } 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. */ PieceTreeTextBuffer.prototype._reduceOperations = function (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)]; }; PieceTreeTextBuffer.prototype._toSingleEditOperation = function (operations) { var forceMoveMarkers = false, firstEditRange = operations[0].range, lastEditRange = operations[operations.length - 1].range, entireEditRange = new range_1.Range(firstEditRange.startLineNumber, firstEditRange.startColumn, lastEditRange.endLineNumber, lastEditRange.endColumn), lastEndLineNumber = firstEditRange.startLineNumber, lastEndColumn = firstEditRange.startColumn, result = []; for (var i = 0, len = operations.length; i < len; i++) { var operation = operations[i], range = operation.range; forceMoveMarkers = forceMoveMarkers || operation.forceMoveMarkers; // (1) -- Push old text for (var lineNumber = lastEndLineNumber; lineNumber < range.startLineNumber; lineNumber++) { if (lineNumber === lastEndLineNumber) { result.push(this.getLineContent(lineNumber).substring(lastEndColumn - 1)); } else { result.push('\n'); result.push(this.getLineContent(lineNumber)); } } if (range.startLineNumber === lastEndLineNumber) { result.push(this.getLineContent(range.startLineNumber).substring(lastEndColumn - 1, range.startColumn - 1)); } else { result.push('\n'); result.push(this.getLineContent(range.startLineNumber).substring(0, range.startColumn - 1)); } // (2) -- Push new text if (operation.lines) { for (var j = 0, lenJ = operation.lines.length; j < lenJ; j++) { if (j !== 0) { result.push('\n'); } result.push(operation.lines[j]); } } lastEndLineNumber = operation.range.endLineNumber; lastEndColumn = operation.range.endColumn; } return { sortIndex: 0, identifier: operations[0].identifier, range: entireEditRange, rangeOffset: this.getOffsetAt(entireEditRange.startLineNumber, entireEditRange.startColumn), rangeLength: this.getValueLengthInRange(entireEditRange, 0 /* TextDefined */), lines: result.join('').split('\n'), forceMoveMarkers: forceMoveMarkers, isAutoWhitespaceEdit: false }; }; PieceTreeTextBuffer.prototype._doApplyEdits = function (operations) { operations.sort(PieceTreeTextBuffer._sortOpsDescending); var contentChanges = []; // operations are from bottom to top for (var i = 0; i < operations.length; i++) { var op = operations[i]; var startLineNumber = op.range.startLineNumber; var startColumn = op.range.startColumn; var endLineNumber = op.range.endLineNumber; var endColumn = op.range.endColumn; if (startLineNumber === endLineNumber && startColumn === endColumn && (!op.lines || op.lines.length === 0)) { // no-op continue; } var deletingLinesCnt = endLineNumber - startLineNumber; var insertingLinesCnt = (op.lines ? op.lines.length - 1 : 0); var editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt); var text = (op.lines ? op.lines.join(this.getEOL()) : ''); if (text) { // replacement this._pieceTree.delete(op.rangeOffset, op.rangeLength); this._pieceTree.insert(op.rangeOffset, text, true); } else { // deletion this._pieceTree.delete(op.rangeOffset, op.rangeLength); } if (editingLinesCnt < insertingLinesCnt) { var newLinesContent = []; for (var j = editingLinesCnt + 1; j <= insertingLinesCnt; j++) { newLinesContent.push(op.lines[j]); } newLinesContent[newLinesContent.length - 1] = this.getLineContent(startLineNumber + insertingLinesCnt - 1); } var contentChangeRange = new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn); contentChanges.push({ range: contentChangeRange, rangeLength: op.rangeLength, text: text, rangeOffset: op.rangeOffset, forceMoveMarkers: op.forceMoveMarkers }); } return contentChanges; }; PieceTreeTextBuffer.prototype.findMatchesLineByLine = function (searchRange, searchData, captureMatches, limitResultCount) { return this._pieceTree.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount); }; /** * Assumes `operations` are validated and sorted ascending */ PieceTreeTextBuffer._getInverseEditRanges = function (operations) { var result = []; var prevOpEndLineNumber = 0; var prevOpEndColumn = 0; var prevOp = null; for (var i = 0, len = operations.length; i < len; i++) { var op = operations[i]; var startLineNumber = void 0; var startColumn = void 0; 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; } var resultRange = void 0; if (op.lines && op.lines.length > 0) { // the operation inserts something var lineCount = op.lines.length; var firstLine = op.lines[0]; var lastLine = op.lines[lineCount - 1]; if (lineCount === 1) { // single line insert resultRange = new range_1.Range(startLineNumber, startColumn, startLineNumber, startColumn + firstLine.length); } else { // multi line insert resultRange = new range_1.Range(startLineNumber, startColumn, startLineNumber + lineCount - 1, lastLine.length + 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; }; PieceTreeTextBuffer._sortOpsAscending = function (a, b) { var r = range_1.Range.compareRangesUsingEnds(a.range, b.range); if (r === 0) { return a.sortIndex - b.sortIndex; } return r; }; PieceTreeTextBuffer._sortOpsDescending = function (a, b) { var r = range_1.Range.compareRangesUsingEnds(a.range, b.range); if (r === 0) { return b.sortIndex - a.sortIndex; } return -r; }; return PieceTreeTextBuffer; }()); 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[348/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,191/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/,347/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer*/]), function (require, exports, strings, pieceTreeBase_1, pieceTreeTextBuffer_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var PieceTreeTextBufferFactory = /** @class */ (function () { function PieceTreeTextBufferFactory(_chunks, _bom, _cr, _lf, _crlf, _containsRTL, _isBasicASCII, _normalizeEOL) { this._chunks = _chunks; this._bom = _bom; this._cr = _cr; this._lf = _lf; this._crlf = _crlf; this._containsRTL = _containsRTL; this._isBasicASCII = _isBasicASCII; this._normalizeEOL = _normalizeEOL; } PieceTreeTextBufferFactory.prototype._getEOL = function (defaultEOL) { var totalEOLCount = this._cr + this._lf + this._crlf; var 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'; }; PieceTreeTextBufferFactory.prototype.create = function (defaultEOL) { var eol = this._getEOL(defaultEOL); var 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 (var i = 0, len = chunks.length; i < len; i++) { var str = chunks[i].buffer.replace(/\r\n|\r|\n/g, eol); var newLineStart = pieceTreeBase_1.createLineStartsFast(str); chunks[i] = new pieceTreeBase_1.StringBuffer(str, newLineStart); } } return new pieceTreeTextBuffer_1.PieceTreeTextBuffer(chunks, this._bom, eol, this._containsRTL, this._isBasicASCII, this._normalizeEOL); }; return PieceTreeTextBufferFactory; }()); exports.PieceTreeTextBufferFactory = PieceTreeTextBufferFactory; var PieceTreeTextBufferBuilder = /** @class */ (function () { function PieceTreeTextBufferBuilder() { 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.isBasicASCII = true; } PieceTreeTextBufferBuilder.prototype.acceptChunk = function (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); } } var 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; } }; PieceTreeTextBufferBuilder.prototype._acceptChunk1 = function (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); } }; PieceTreeTextBufferBuilder.prototype._acceptChunk2 = function (chunk) { var lineStarts = 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 is basic ASCII this.containsRTL = strings.containsRTL(chunk); } }; PieceTreeTextBufferBuilder.prototype.finish = function (normalizeEOL) { if (normalizeEOL === void 0) { normalizeEOL = true; } this._finish(); return new PieceTreeTextBufferFactory(this.chunks, this.BOM, this.cr, this.lf, this.crlf, this.containsRTL, this.isBasicASCII, normalizeEOL); }; PieceTreeTextBufferBuilder.prototype._finish = function () { if (this.chunks.length === 0) { this._acceptChunk1('', true); } if (this._hasPreviousChar) { this._hasPreviousChar = false; // recreate last chunk var lastChunk = this.chunks[this.chunks.length - 1]; lastChunk.buffer += String.fromCharCode(this._previousChar); var newLineStarts = pieceTreeBase_1.createLineStartsFast(lastChunk.buffer); lastChunk.lineStarts = newLineStarts; if (this._previousChar === 13 /* CarriageReturn */) { this.cr++; } } }; return PieceTreeTextBufferBuilder; }()); 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[109/*vs/editor/common/model/wordHelper*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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) { if (allowInWords === void 0) { allowInWords = ''; } var source = '(-?\\d*\\.\\d\\w*)|([^'; for (var _i = 0, USUAL_WORD_SEPARATORS_1 = exports.USUAL_WORD_SEPARATORS; _i < USUAL_WORD_SEPARATORS_1.length; _i++) { var sep = USUAL_WORD_SEPARATORS_1[_i]; 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) { var result = exports.DEFAULT_WORD_REGEXP; if (wordDefinition && (wordDefinition instanceof RegExp)) { if (!wordDefinition.global) { var 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; function getWordAtPosFast(column, wordDefinition, text, textOffset) { // find whitespace enclosed text around column and match from there var pos = column - 1 - textOffset; var start = text.lastIndexOf(' ', pos - 1) + 1; wordDefinition.lastIndex = start; var match; while (match = wordDefinition.exec(text)) { var matchIndex = match.index || 0; if (matchIndex <= pos && wordDefinition.lastIndex >= pos) { return { word: match[0], startColumn: textOffset + 1 + matchIndex, endColumn: textOffset + 1 + wordDefinition.lastIndex }; } } return null; } function getWordAtPosSlow(column, wordDefinition, text, textOffset) { // matches all words starting at the beginning // of the input until it finds a match that encloses // the desired column. slow but correct var pos = column - 1 - textOffset; wordDefinition.lastIndex = 0; var match; while (match = wordDefinition.exec(text)) { var matchIndex = match.index || 0; if (matchIndex > pos) { // |nW -> matched only after the pos return null; } else if (wordDefinition.lastIndex >= pos) { // W|W -> match encloses pos return { word: match[0], startColumn: textOffset + 1 + matchIndex, endColumn: textOffset + 1 + wordDefinition.lastIndex }; } } return null; } function getWordAtText(column, wordDefinition, text, textOffset) { // if `words` can contain whitespace character we have to use the slow variant // otherwise we use the fast variant of finding a word wordDefinition.lastIndex = 0; var match = wordDefinition.exec(text); if (!match) { return null; } // todo@joh the `match` could already be the (first) word var ret = match[0].indexOf(' ') >= 0 // did match a word which contains a space character -> use slow word find ? getWordAtPosSlow(column, wordDefinition, text, textOffset) // sane word definition -> use fast word find : getWordAtPosFast(column, wordDefinition, text, textOffset); // both (getWordAtPosFast and getWordAtPosSlow) leave the wordDefinition-RegExp // in an undefined state and to not confuse other users of the wordDefinition // we reset the lastIndex wordDefinition.lastIndex = 0; return ret; } exports.getWordAtText = getWordAtText; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[349/*vs/editor/common/modes/abstractMode*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var FrankensteinMode = /** @class */ (function () { function FrankensteinMode(languageIdentifier) { this._languageIdentifier = languageIdentifier; } FrankensteinMode.prototype.getId = function () { return this._languageIdentifier.language; }; return FrankensteinMode; }()); exports.FrankensteinMode = FrankensteinMode; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[90/*vs/editor/common/modes/languageConfiguration*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * 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 */ var StandardAutoClosingPairConditional = /** @class */ (function () { function StandardAutoClosingPairConditional(source) { this.open = source.open; this.close = source.close; // initially allowed in all tokens this._standardTokenMask = 0; if (Array.isArray(source.notIn)) { for (var i = 0, len = source.notIn.length; i < len; i++) { var notIn = source.notIn[i]; switch (notIn) { case 'string': this._standardTokenMask |= 2 /* String */; break; case 'comment': this._standardTokenMask |= 1 /* Comment */; break; case 'regex': this._standardTokenMask |= 4 /* RegEx */; break; } } } } StandardAutoClosingPairConditional.prototype.isOK = function (standardToken) { return (this._standardTokenMask & standardToken) === 0; }; return StandardAutoClosingPairConditional; }()); exports.StandardAutoClosingPairConditional = StandardAutoClosingPairConditional; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[350/*vs/editor/common/modes/languageSelector*/], __M([0/*require*/,1/*exports*/,178/*vs/base/common/glob*/]), function (require, exports, glob_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function score(selector, candidateUri, candidateLanguage, candidateIsSynchronized) { if (Array.isArray(selector)) { // array -> take max individual value var ret = 0; for (var _i = 0, selector_1 = selector; _i < selector_1.length; _i++) { var filter = selector_1[_i]; var 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 var language = selector.language, pattern = selector.pattern, scheme = selector.scheme, hasAccessToAllModels = selector.hasAccessToAllModels; if (!candidateIsSynchronized && !hasAccessToAllModels) { return 0; } var 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) { if (pattern === candidateUri.fsPath || glob_1.match(pattern, 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[351/*vs/editor/common/modes/linkComputer*/], __M([0/*require*/,1/*exports*/,79/*vs/editor/common/core/characterClassifier*/]), function (require, exports, characterClassifier_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Uint8Matrix = /** @class */ (function () { function Uint8Matrix(rows, cols, defaultValue) { var data = new Uint8Array(rows * cols); for (var i = 0, len = rows * cols; i < len; i++) { data[i] = defaultValue; } this._data = data; this.rows = rows; this.cols = cols; } Uint8Matrix.prototype.get = function (row, col) { return this._data[row * this.cols + col]; }; Uint8Matrix.prototype.set = function (row, col, value) { this._data[row * this.cols + col] = value; }; return Uint8Matrix; }()); exports.Uint8Matrix = Uint8Matrix; var StateMachine = /** @class */ (function () { function StateMachine(edges) { var maxCharCode = 0; var maxState = 0 /* Invalid */; for (var i = 0, len = edges.length; i < len; i++) { var _a = edges[i], from = _a[0], chCode = _a[1], to = _a[2]; if (chCode > maxCharCode) { maxCharCode = chCode; } if (from > maxState) { maxState = from; } if (to > maxState) { maxState = to; } } maxCharCode++; maxState++; var states = new Uint8Matrix(maxState, maxCharCode, 0 /* Invalid */); for (var i = 0, len = edges.length; i < len; i++) { var _b = edges[i], from = _b[0], chCode = _b[1], to = _b[2]; states.set(from, chCode, to); } this._states = states; this._maxCharCode = maxCharCode; } StateMachine.prototype.nextState = function (currentState, chCode) { if (chCode < 0 || chCode >= this._maxCharCode) { return 0 /* Invalid */; } return this._states.get(currentState, chCode); }; return StateMachine; }()); exports.StateMachine = StateMachine; // State machine for http:// or https:// or file:// var _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; } var _classifier = null; function getClassifier() { if (_classifier === null) { _classifier = new characterClassifier_1.CharacterClassifier(0 /* None */); var FORCE_TERMINATION_CHARACTERS = ' \t<>\'\"、。。、,.:;?!@#$%&*‘“〈《「『【〔([{「」}])〕】』」》〉”’`~…'; for (var i = 0; i < FORCE_TERMINATION_CHARACTERS.length; i++) { _classifier.set(FORCE_TERMINATION_CHARACTERS.charCodeAt(i), 1 /* ForceTermination */); } var CANNOT_END_WITH_CHARACTERS = '.,;'; for (var i = 0; i < CANNOT_END_WITH_CHARACTERS.length; i++) { _classifier.set(CANNOT_END_WITH_CHARACTERS.charCodeAt(i), 2 /* CannotEndIn */); } } return _classifier; } var LinkComputer = /** @class */ (function () { function LinkComputer() { } LinkComputer._createLink = function (classifier, line, lineNumber, linkBeginIndex, linkEndIndex) { // Do not allow to end link in certain characters... var lastIncludedCharIndex = linkEndIndex - 1; do { var chCode = line.charCodeAt(lastIncludedCharIndex); var 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) { var charCodeBeforeLink = line.charCodeAt(linkBeginIndex - 1); var 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) }; }; LinkComputer.computeLinks = function (model, stateMachine) { if (stateMachine === void 0) { stateMachine = getStateMachine(); } var classifier = getClassifier(); var result = []; for (var i = 1, lineCount = model.getLineCount(); i <= lineCount; i++) { var line = model.getLineContent(i); var len = line.length; var j = 0; var linkBeginIndex = 0; var linkBeginChCode = 0; var state = 1 /* Start */; var hasOpenParens = false; var hasOpenSquareBracket = false; var hasOpenCurlyBracket = false; while (j < len) { var resetStateMachine = false; var chCode = line.charCodeAt(j); if (state === 13 /* Accept */) { var chClass = void 0; switch (chCode) { case 40 /* OpenParen */: hasOpenParens = true; chClass = 0 /* None */; break; case 41 /* CloseParen */: chClass = (hasOpenParens ? 0 /* None */ : 1 /* ForceTermination */); break; case 91 /* OpenSquareBracket */: hasOpenSquareBracket = true; chClass = 0 /* None */; break; case 93 /* CloseSquareBracket */: 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; 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 */) { var chClass = void 0; 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; }; return LinkComputer; }()); 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[145/*vs/editor/common/modes/supports*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function createScopedLineTokens(context, offset) { var tokenCount = context.getCount(); var tokenIndex = context.findTokenIndexAtOffset(offset); var desiredLanguageId = context.getLanguageId(tokenIndex); var lastTokenIndex = tokenIndex; while (lastTokenIndex + 1 < tokenCount && context.getLanguageId(lastTokenIndex + 1) === desiredLanguageId) { lastTokenIndex++; } var 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; var ScopedLineTokens = /** @class */ (function () { function ScopedLineTokens(actual, languageId, firstTokenIndex, lastTokenIndex, firstCharOffset, lastCharOffset) { this._actual = actual; this.languageId = languageId; this._firstTokenIndex = firstTokenIndex; this._lastTokenIndex = lastTokenIndex; this.firstCharOffset = firstCharOffset; this._lastCharOffset = lastCharOffset; } ScopedLineTokens.prototype.getLineContent = function () { var actualLineContent = this._actual.getLineContent(); return actualLineContent.substring(this.firstCharOffset, this._lastCharOffset); }; ScopedLineTokens.prototype.getActualLineContentBefore = function (offset) { var actualLineContent = this._actual.getLineContent(); return actualLineContent.substring(0, this.firstCharOffset + offset); }; ScopedLineTokens.prototype.getTokenCount = function () { return this._lastTokenIndex - this._firstTokenIndex; }; ScopedLineTokens.prototype.findTokenIndexAtOffset = function (offset) { return this._actual.findTokenIndexAtOffset(offset + this.firstCharOffset) - this._firstTokenIndex; }; ScopedLineTokens.prototype.getStandardTokenType = function (tokenIndex) { return this._actual.getStandardTokenType(tokenIndex + this._firstTokenIndex); }; return ScopedLineTokens; }()); exports.ScopedLineTokens = ScopedLineTokens; function ignoreBracketsInToken(standardTokenType) { return (standardTokenType & 7 /* value */) !== 0; } exports.ignoreBracketsInToken = ignoreBracketsInToken; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[352/*vs/editor/common/modes/supports/characterPair*/], __M([0/*require*/,1/*exports*/,90/*vs/editor/common/modes/languageConfiguration*/]), function (require, exports, languageConfiguration_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CharacterPairSupport = /** @class */ (function () { function CharacterPairSupport(config) { if (config.autoClosingPairs) { this._autoClosingPairs = config.autoClosingPairs.map(function (el) { return new languageConfiguration_1.StandardAutoClosingPairConditional(el); }); } else if (config.brackets) { this._autoClosingPairs = config.brackets.map(function (b) { return new languageConfiguration_1.StandardAutoClosingPairConditional({ open: b[0], close: b[1] }); }); } else { this._autoClosingPairs = []; } if (config.__electricCharacterSupport && config.__electricCharacterSupport.docComment) { var 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; } CharacterPairSupport.prototype.getAutoClosingPairs = function () { return this._autoClosingPairs; }; CharacterPairSupport.prototype.getAutoCloseBeforeSet = function () { return this._autoCloseBefore; }; CharacterPairSupport.shouldAutoClosePair = function (autoClosingPair, context, column) { // Always complete on empty line if (context.getTokenCount() === 0) { return true; } var tokenIndex = context.findTokenIndexAtOffset(column - 2); var standardTokenType = context.getStandardTokenType(tokenIndex); return autoClosingPair.isOK(standardTokenType); }; CharacterPairSupport.prototype.getSurroundingPairs = function () { return this._surroundingPairs; }; CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED = ';:.,=}])> \n\t'; return CharacterPairSupport; }()); exports.CharacterPairSupport = CharacterPairSupport; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[353/*vs/editor/common/modes/supports/indentRules*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var IndentRulesSupport = /** @class */ (function () { function IndentRulesSupport(indentationRules) { this._indentationRules = indentationRules; } IndentRulesSupport.prototype.shouldIncrease = function (text) { if (this._indentationRules) { if (this._indentationRules.increaseIndentPattern && this._indentationRules.increaseIndentPattern.test(text)) { return true; } // if (this._indentationRules.indentNextLinePattern && this._indentationRules.indentNextLinePattern.test(text)) { // return true; // } } return false; }; IndentRulesSupport.prototype.shouldDecrease = function (text) { if (this._indentationRules && this._indentationRules.decreaseIndentPattern && this._indentationRules.decreaseIndentPattern.test(text)) { return true; } return false; }; IndentRulesSupport.prototype.shouldIndentNextLine = function (text) { if (this._indentationRules && this._indentationRules.indentNextLinePattern && this._indentationRules.indentNextLinePattern.test(text)) { return true; } return false; }; IndentRulesSupport.prototype.shouldIgnore = function (text) { // the text matches `unIndentedLinePattern` if (this._indentationRules && this._indentationRules.unIndentedLinePattern && this._indentationRules.unIndentedLinePattern.test(text)) { return true; } return false; }; IndentRulesSupport.prototype.getIndentMetadata = function (text) { var 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; }; return IndentRulesSupport; }()); 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[354/*vs/editor/common/modes/supports/inplaceReplaceSupport*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var BasicInplaceReplace = /** @class */ (function () { function BasicInplaceReplace() { this._defaultValueSet = [ ['true', 'false'], ['True', 'False'], ['Private', 'Public', 'Friend', 'ReadOnly', 'Partial', 'Protected', 'WriteOnly'], ['public', 'protected', 'private'], ]; } BasicInplaceReplace.prototype.navigateValueSet = function (range1, text1, range2, text2, up) { if (range1 && text1) { var result = this.doNavigateValueSet(text1, up); if (result) { return { range: range1, value: result }; } } if (range2 && text2) { var result = this.doNavigateValueSet(text2, up); if (result) { return { range: range2, value: result }; } } return null; }; BasicInplaceReplace.prototype.doNavigateValueSet = function (text, up) { var numberResult = this.numberReplace(text, up); if (numberResult !== null) { return numberResult; } return this.textReplace(text, up); }; BasicInplaceReplace.prototype.numberReplace = function (value, up) { var precision = Math.pow(10, value.length - (value.lastIndexOf('.') + 1)); var n1 = Number(value); var 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; }; BasicInplaceReplace.prototype.textReplace = function (value, up) { return this.valueSetsReplace(this._defaultValueSet, value, up); }; BasicInplaceReplace.prototype.valueSetsReplace = function (valueSets, value, up) { var result = null; for (var i = 0, len = valueSets.length; result === null && i < len; i++) { result = this.valueSetReplace(valueSets[i], value, up); } return result; }; BasicInplaceReplace.prototype.valueSetReplace = function (valueSet, value, up) { var 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; }; BasicInplaceReplace.INSTANCE = new BasicInplaceReplace(); return BasicInplaceReplace; }()); exports.BasicInplaceReplace = BasicInplaceReplace; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[355/*vs/editor/common/modes/supports/onEnter*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,5/*vs/base/common/strings*/,90/*vs/editor/common/modes/languageConfiguration*/]), function (require, exports, errors_1, strings, languageConfiguration_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var OnEnterSupport = /** @class */ (function () { function OnEnterSupport(opts) { var _this = this; opts = opts || {}; opts.brackets = opts.brackets || [ ['(', ')'], ['{', '}'], ['[', ']'] ]; this._brackets = []; opts.brackets.forEach(function (bracket) { var openRegExp = OnEnterSupport._createOpenBracketRegExp(bracket[0]); var 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 || []; } OnEnterSupport.prototype.onEnter = function (autoIndent, oneLineAboveText, beforeEnterText, afterEnterText) { // (1): `regExpRules` if (autoIndent >= 3 /* Advanced */) { for (var i = 0, len = this._regExpRules.length; i < len; i++) { var rule = this._regExpRules[i]; var regResult = [{ reg: rule.beforeText, text: beforeEnterText }, { reg: rule.afterText, text: afterEnterText }, { reg: rule.oneLineAboveText, text: oneLineAboveText }].every(function (obj) { return obj.reg ? obj.reg.test(obj.text) : true; }); if (regResult) { return rule.action; } } } // (2): Special indent-outdent if (autoIndent >= 2 /* Brackets */) { if (beforeEnterText.length > 0 && afterEnterText.length > 0) { for (var i = 0, len = this._brackets.length; i < len; i++) { var 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 (var i = 0, len = this._brackets.length; i < len; i++) { var bracket = this._brackets[i]; if (bracket.openRegExp.test(beforeEnterText)) { return { indentAction: languageConfiguration_1.IndentAction.Indent }; } } } } return null; }; OnEnterSupport._createOpenBracketRegExp = function (bracket) { var str = strings.escapeRegExpCharacters(bracket); if (!/\B/.test(str.charAt(0))) { str = '\\b' + str; } str += '\\s*$'; return OnEnterSupport._safeRegExp(str); }; OnEnterSupport._createCloseBracketRegExp = function (bracket) { var str = strings.escapeRegExpCharacters(bracket); if (!/\B/.test(str.charAt(str.length - 1))) { str = str + '\\b'; } str = '^\\s*' + str; return OnEnterSupport._safeRegExp(str); }; OnEnterSupport._safeRegExp = function (def) { try { return new RegExp(def); } catch (err) { errors_1.onUnexpectedError(err); return null; } }; return OnEnterSupport; }()); 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[146/*vs/editor/common/modes/supports/richEditBrackets*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var RichEditBracket = /** @class */ (function () { function RichEditBracket(languageIdentifier, index, open, close, forwardRegex, reversedRegex) { this.languageIdentifier = languageIdentifier; this.index = index; this.open = open; this.close = close; this.forwardRegex = forwardRegex; this.reversedRegex = reversedRegex; this._openSet = RichEditBracket._toSet(this.open); this._closeSet = RichEditBracket._toSet(this.close); } RichEditBracket.prototype.isOpen = function (text) { return this._openSet.has(text); }; RichEditBracket.prototype.isClose = function (text) { return this._closeSet.has(text); }; RichEditBracket._toSet = function (arr) { var result = new Set(); for (var _i = 0, arr_1 = arr; _i < arr_1.length; _i++) { var element = arr_1[_i]; result.add(element); } return result; }; return RichEditBracket; }()); exports.RichEditBracket = RichEditBracket; function groupFuzzyBrackets(brackets) { var N = brackets.length; brackets = brackets.map(function (b) { return [b[0].toLowerCase(), b[1].toLowerCase()]; }); var group = []; for (var i = 0; i < N; i++) { group[i] = i; } var areOverlapping = function (a, b) { var aOpen = a[0], aClose = a[1]; var bOpen = b[0], bClose = b[1]; return (aOpen === bOpen || aOpen === bClose || aClose === bOpen || aClose === bClose); }; var mergeGroups = function (g1, g2) { var newG = Math.min(g1, g2); var oldG = Math.max(g1, g2); for (var 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 (var i = 0; i < N; i++) { var a = brackets[i]; for (var j = i + 1; j < N; j++) { var b = brackets[j]; if (areOverlapping(a, b)) { mergeGroups(group[i], group[j]); } } } var result = []; for (var g = 0; g < N; g++) { var currentOpen = []; var currentClose = []; for (var i = 0; i < N; i++) { if (group[i] === g) { var _a = brackets[i], open_1 = _a[0], close_1 = _a[1]; currentOpen.push(open_1); currentClose.push(close_1); } } if (currentOpen.length > 0) { result.push({ open: currentOpen, close: currentClose }); } } return result; } var RichEditBrackets = /** @class */ (function () { function RichEditBrackets(languageIdentifier, _brackets) { var brackets = groupFuzzyBrackets(_brackets); this.brackets = brackets.map(function (b, index) { return new RichEditBracket(languageIdentifier, index, b.open, b.close, getRegexForBracketPair(b.open, b.close, brackets, index), getReversedRegexForBracketPair(b.open, b.close, brackets, index)); }); this.forwardRegex = getRegexForBrackets(this.brackets); this.reversedRegex = getReversedRegexForBrackets(this.brackets); this.textIsBracket = {}; this.textIsOpenBracket = {}; this.maxBracketLength = 0; for (var _i = 0, _a = this.brackets; _i < _a.length; _i++) { var bracket = _a[_i]; for (var _b = 0, _c = bracket.open; _b < _c.length; _b++) { var open_2 = _c[_b]; this.textIsBracket[open_2] = bracket; this.textIsOpenBracket[open_2] = true; this.maxBracketLength = Math.max(this.maxBracketLength, open_2.length); } for (var _d = 0, _e = bracket.close; _d < _e.length; _d++) { var close_2 = _e[_d]; this.textIsBracket[close_2] = bracket; this.textIsOpenBracket[close_2] = false; this.maxBracketLength = Math.max(this.maxBracketLength, close_2.length); } } } return RichEditBrackets; }()); exports.RichEditBrackets = RichEditBrackets; function collectSuperstrings(str, brackets, currentIndex, dest) { for (var i = 0, len = brackets.length; i < len; i++) { if (i === currentIndex) { continue; } var bracket = brackets[i]; for (var _i = 0, _a = bracket.open; _i < _a.length; _i++) { var open_3 = _a[_i]; if (open_3.indexOf(str) >= 0) { dest.push(open_3); } } for (var _b = 0, _c = bracket.close; _b < _c.length; _b++) { var close_3 = _c[_b]; if (close_3.indexOf(str) >= 0) { dest.push(close_3); } } } } function lengthcmp(a, b) { return a.length - b.length; } function unique(arr) { if (arr.length <= 1) { return arr; } var result = []; var seen = new Set(); for (var _i = 0, arr_2 = arr; _i < arr_2.length; _i++) { var element = arr_2[_i]; if (seen.has(element)) { continue; } result.push(element); seen.add(element); } return result; } function getRegexForBracketPair(open, close, brackets, currentIndex) { // search in all brackets for other brackets that are a superstring of these brackets var pieces = []; pieces = pieces.concat(open); pieces = pieces.concat(close); for (var i = 0, len = pieces.length; i < len; i++) { collectSuperstrings(pieces[i], brackets, currentIndex, pieces); } pieces = unique(pieces); pieces.sort(lengthcmp); pieces.reverse(); return createBracketOrRegExp(pieces); } function getReversedRegexForBracketPair(open, close, brackets, currentIndex) { // search in all brackets for other brackets that are a superstring of these brackets var pieces = []; pieces = pieces.concat(open); pieces = pieces.concat(close); for (var i = 0, len = pieces.length; i < len; i++) { collectSuperstrings(pieces[i], brackets, currentIndex, pieces); } pieces = unique(pieces); pieces.sort(lengthcmp); pieces.reverse(); return createBracketOrRegExp(pieces.map(toReversedString)); } function getRegexForBrackets(brackets) { var pieces = []; for (var _i = 0, brackets_1 = brackets; _i < brackets_1.length; _i++) { var bracket = brackets_1[_i]; for (var _a = 0, _b = bracket.open; _a < _b.length; _a++) { var open_4 = _b[_a]; pieces.push(open_4); } for (var _c = 0, _d = bracket.close; _c < _d.length; _c++) { var close_4 = _d[_c]; pieces.push(close_4); } } pieces = unique(pieces); return createBracketOrRegExp(pieces); } function getReversedRegexForBrackets(brackets) { var pieces = []; for (var _i = 0, brackets_2 = brackets; _i < brackets_2.length; _i++) { var bracket = brackets_2[_i]; for (var _a = 0, _b = bracket.open; _a < _b.length; _a++) { var open_5 = _b[_a]; pieces.push(open_5); } for (var _c = 0, _d = bracket.close; _c < _d.length; _c++) { var close_5 = _d[_c]; pieces.push(close_5); } } pieces = unique(pieces); return createBracketOrRegExp(pieces.map(toReversedString)); } function prepareBracketForRegExp(str) { // This bracket pair uses letters like e.g. "begin" - "end" var insertWordBoundaries = (/^[\w ]+$/.test(str)); str = strings.escapeRegExpCharacters(str); return (insertWordBoundaries ? "\\b" + str + "\\b" : str); } function createBracketOrRegExp(pieces) { var regexStr = "(" + pieces.map(prepareBracketForRegExp).join(')|(') + ")"; return strings.createRegExp(regexStr, true); } var toReversedString = (function () { function reverse(str) { var reversedStr = ''; for (var i = str.length - 1; i >= 0; i--) { reversedStr += str.charAt(i); } return reversedStr; } var lastInput = null; var lastOutput = null; return function toReversedString(str) { if (lastInput !== str) { lastInput = str; lastOutput = reverse(lastInput); } return lastOutput; }; })(); var BracketsUtils = /** @class */ (function () { function BracketsUtils() { } BracketsUtils._findPrevBracketInText = function (reversedBracketRegex, lineNumber, reversedText, offset) { var m = reversedText.match(reversedBracketRegex); if (!m) { return null; } var matchOffset = reversedText.length - (m.index || 0); var matchLength = m[0].length; var absoluteMatchOffset = offset + matchOffset; return new range_1.Range(lineNumber, absoluteMatchOffset - matchLength + 1, lineNumber, absoluteMatchOffset + 1); }; BracketsUtils.findPrevBracketInRange = function (reversedBracketRegex, lineNumber, lineText, startOffset, endOffset) { // Because JS does not support backwards regex search, we search forwards in a reversed string with a reversed regex ;) var reversedLineText = toReversedString(lineText); var reversedSubstr = reversedLineText.substring(lineText.length - endOffset, lineText.length - startOffset); return this._findPrevBracketInText(reversedBracketRegex, lineNumber, reversedSubstr, startOffset); }; BracketsUtils.findNextBracketInText = function (bracketRegex, lineNumber, text, offset) { var m = text.match(bracketRegex); if (!m) { return null; } var matchOffset = m.index || 0; var matchLength = m[0].length; if (matchLength === 0) { return null; } var absoluteMatchOffset = offset + matchOffset; return new range_1.Range(lineNumber, absoluteMatchOffset + 1, lineNumber, absoluteMatchOffset + 1 + matchLength); }; BracketsUtils.findNextBracketInRange = function (bracketRegex, lineNumber, lineText, startOffset, endOffset) { var substr = lineText.substring(startOffset, endOffset); return this.findNextBracketInText(bracketRegex, lineNumber, substr, startOffset); }; return BracketsUtils; }()); 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[356/*vs/editor/common/modes/supports/electricCharacter*/], __M([0/*require*/,1/*exports*/,145/*vs/editor/common/modes/supports*/,146/*vs/editor/common/modes/supports/richEditBrackets*/]), function (require, exports, supports_1, richEditBrackets_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var BracketElectricCharacterSupport = /** @class */ (function () { function BracketElectricCharacterSupport(richEditBrackets) { this._richEditBrackets = richEditBrackets; } BracketElectricCharacterSupport.prototype.getElectricCharacters = function () { var result = []; if (this._richEditBrackets) { for (var _i = 0, _a = this._richEditBrackets.brackets; _i < _a.length; _i++) { var bracket = _a[_i]; for (var _b = 0, _c = bracket.close; _b < _c.length; _b++) { var close_1 = _c[_b]; var lastChar = close_1.charAt(close_1.length - 1); result.push(lastChar); } } } // Filter duplicate entries result = result.filter(function (item, pos, array) { return array.indexOf(item) === pos; }); return result; }; BracketElectricCharacterSupport.prototype.onElectricCharacter = function (character, context, column) { if (!this._richEditBrackets || this._richEditBrackets.brackets.length === 0) { return null; } var tokenIndex = context.findTokenIndexAtOffset(column - 1); if (supports_1.ignoreBracketsInToken(context.getStandardTokenType(tokenIndex))) { return null; } var reversedBracketRegex = this._richEditBrackets.reversedRegex; var text = context.getLineContent().substring(0, column - 1) + character; var r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(reversedBracketRegex, 1, text, 0, text.length); if (!r) { return null; } var bracketText = text.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase(); var isOpen = this._richEditBrackets.textIsOpenBracket[bracketText]; if (isOpen) { return null; } var 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 }; }; return BracketElectricCharacterSupport; }()); 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[41/*vs/editor/common/modes/languageConfigurationRegistry*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,109/*vs/editor/common/model/wordHelper*/,90/*vs/editor/common/modes/languageConfiguration*/,145/*vs/editor/common/modes/supports*/,352/*vs/editor/common/modes/supports/characterPair*/,356/*vs/editor/common/modes/supports/electricCharacter*/,353/*vs/editor/common/modes/supports/indentRules*/,355/*vs/editor/common/modes/supports/onEnter*/,146/*vs/editor/common/modes/supports/richEditBrackets*/]), function (require, exports, event_1, lifecycle_1, strings, wordHelper_1, languageConfiguration_1, supports_1, characterPair_1, electricCharacter_1, indentRules_1, onEnter_1, richEditBrackets_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var RichEditSupport = /** @class */ (function () { function RichEditSupport(languageIdentifier, previous, rawConf) { this._languageIdentifier = languageIdentifier; this._brackets = null; this._electricCharacter = null; var prev = null; if (previous) { prev = previous._conf; } this._conf = RichEditSupport._mergeConf(prev, rawConf); this._onEnterSupport = (this._conf.brackets || this._conf.indentationRules || this._conf.onEnterRules ? new onEnter_1.OnEnterSupport(this._conf) : null); this.comments = RichEditSupport._handleComments(this._conf); this.characterPair = new characterPair_1.CharacterPairSupport(this._conf); this.wordDefinition = this._conf.wordPattern || wordHelper_1.DEFAULT_WORD_REGEXP; this.indentationRules = this._conf.indentationRules; if (this._conf.indentationRules) { this.indentRulesSupport = new indentRules_1.IndentRulesSupport(this._conf.indentationRules); } else { this.indentRulesSupport = null; } this.foldingRules = this._conf.folding || {}; } Object.defineProperty(RichEditSupport.prototype, "brackets", { get: function () { if (!this._brackets && this._conf.brackets) { this._brackets = new richEditBrackets_1.RichEditBrackets(this._languageIdentifier, this._conf.brackets); } return this._brackets; }, enumerable: true, configurable: true }); Object.defineProperty(RichEditSupport.prototype, "electricCharacter", { get: function () { if (!this._electricCharacter) { this._electricCharacter = new electricCharacter_1.BracketElectricCharacterSupport(this.brackets); } return this._electricCharacter; }, enumerable: true, configurable: true }); RichEditSupport.prototype.onEnter = function (autoIndent, oneLineAboveText, beforeEnterText, afterEnterText) { if (!this._onEnterSupport) { return null; } return this._onEnterSupport.onEnter(autoIndent, oneLineAboveText, beforeEnterText, afterEnterText); }; RichEditSupport._mergeConf = function (prev, current) { return { comments: (prev ? current.comments || prev.comments : current.comments), brackets: (prev ? current.brackets || prev.brackets : current.brackets), wordPattern: (prev ? current.wordPattern || prev.wordPattern : current.wordPattern), indentationRules: (prev ? current.indentationRules || prev.indentationRules : current.indentationRules), onEnterRules: (prev ? current.onEnterRules || prev.onEnterRules : current.onEnterRules), autoClosingPairs: (prev ? current.autoClosingPairs || prev.autoClosingPairs : current.autoClosingPairs), surroundingPairs: (prev ? current.surroundingPairs || prev.surroundingPairs : current.surroundingPairs), autoCloseBefore: (prev ? current.autoCloseBefore || prev.autoCloseBefore : current.autoCloseBefore), folding: (prev ? current.folding || prev.folding : current.folding), __electricCharacterSupport: (prev ? current.__electricCharacterSupport || prev.__electricCharacterSupport : current.__electricCharacterSupport), }; }; RichEditSupport._handleComments = function (conf) { var commentRule = conf.comments; if (!commentRule) { return null; } // comment configuration var comments = {}; if (commentRule.lineComment) { comments.lineCommentToken = commentRule.lineComment; } if (commentRule.blockComment) { var _a = commentRule.blockComment, blockStart = _a[0], blockEnd = _a[1]; comments.blockCommentStartToken = blockStart; comments.blockCommentEndToken = blockEnd; } return comments; }; return RichEditSupport; }()); exports.RichEditSupport = RichEditSupport; var LanguageConfigurationChangeEvent = /** @class */ (function () { function LanguageConfigurationChangeEvent(languageIdentifier) { this.languageIdentifier = languageIdentifier; } return LanguageConfigurationChangeEvent; }()); exports.LanguageConfigurationChangeEvent = LanguageConfigurationChangeEvent; var LanguageConfigurationRegistryImpl = /** @class */ (function () { function LanguageConfigurationRegistryImpl() { this._entries = new Map(); this._onDidChange = new event_1.Emitter(); this.onDidChange = this._onDidChange.event; } LanguageConfigurationRegistryImpl.prototype.register = function (languageIdentifier, configuration) { var _this = this; var previous = this._getRichEditSupport(languageIdentifier.id); var current = new RichEditSupport(languageIdentifier, previous, configuration); this._entries.set(languageIdentifier.id, current); this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageIdentifier)); return lifecycle_1.toDisposable(function () { if (_this._entries.get(languageIdentifier.id) === current) { _this._entries.set(languageIdentifier.id, previous); _this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageIdentifier)); } }); }; LanguageConfigurationRegistryImpl.prototype._getRichEditSupport = function (languageId) { return this._entries.get(languageId); }; // begin electricCharacter LanguageConfigurationRegistryImpl.prototype._getElectricCharacterSupport = function (languageId) { var value = this._getRichEditSupport(languageId); if (!value) { return null; } return value.electricCharacter || null; }; LanguageConfigurationRegistryImpl.prototype.getElectricCharacters = function (languageId) { var electricCharacterSupport = this._getElectricCharacterSupport(languageId); if (!electricCharacterSupport) { return []; } return electricCharacterSupport.getElectricCharacters(); }; /** * Should return opening bracket type to match indentation with */ LanguageConfigurationRegistryImpl.prototype.onElectricCharacter = function (character, context, column) { var scopedLineTokens = supports_1.createScopedLineTokens(context, column - 1); var electricCharacterSupport = this._getElectricCharacterSupport(scopedLineTokens.languageId); if (!electricCharacterSupport) { return null; } return electricCharacterSupport.onElectricCharacter(character, scopedLineTokens, column - scopedLineTokens.firstCharOffset); }; // end electricCharacter LanguageConfigurationRegistryImpl.prototype.getComments = function (languageId) { var value = this._getRichEditSupport(languageId); if (!value) { return null; } return value.comments || null; }; // begin characterPair LanguageConfigurationRegistryImpl.prototype._getCharacterPairSupport = function (languageId) { var value = this._getRichEditSupport(languageId); if (!value) { return null; } return value.characterPair || null; }; LanguageConfigurationRegistryImpl.prototype.getAutoClosingPairs = function (languageId) { var characterPairSupport = this._getCharacterPairSupport(languageId); if (!characterPairSupport) { return []; } return characterPairSupport.getAutoClosingPairs(); }; LanguageConfigurationRegistryImpl.prototype.getAutoCloseBeforeSet = function (languageId) { var characterPairSupport = this._getCharacterPairSupport(languageId); if (!characterPairSupport) { return characterPair_1.CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED; } return characterPairSupport.getAutoCloseBeforeSet(); }; LanguageConfigurationRegistryImpl.prototype.getSurroundingPairs = function (languageId) { var characterPairSupport = this._getCharacterPairSupport(languageId); if (!characterPairSupport) { return []; } return characterPairSupport.getSurroundingPairs(); }; LanguageConfigurationRegistryImpl.prototype.shouldAutoClosePair = function (autoClosingPair, context, column) { var scopedLineTokens = supports_1.createScopedLineTokens(context, column - 1); return characterPair_1.CharacterPairSupport.shouldAutoClosePair(autoClosingPair, scopedLineTokens, column - scopedLineTokens.firstCharOffset); }; // end characterPair LanguageConfigurationRegistryImpl.prototype.getWordDefinition = function (languageId) { var value = this._getRichEditSupport(languageId); if (!value) { return wordHelper_1.ensureValidWordDefinition(null); } return wordHelper_1.ensureValidWordDefinition(value.wordDefinition || null); }; LanguageConfigurationRegistryImpl.prototype.getFoldingRules = function (languageId) { var value = this._getRichEditSupport(languageId); if (!value) { return {}; } return value.foldingRules; }; // begin Indent Rules LanguageConfigurationRegistryImpl.prototype.getIndentRulesSupport = function (languageId) { var value = this._getRichEditSupport(languageId); if (!value) { return null; } return value.indentRulesSupport || null; }; /** * Get nearest preceiding line which doesn't match unIndentPattern or contains all whitespace. * Result: * -1: run into the boundary of embedded languages * 0: every line above are invalid * else: nearest preceding line of the same language */ LanguageConfigurationRegistryImpl.prototype.getPrecedingValidLine = function (model, lineNumber, indentRulesSupport) { var languageID = model.getLanguageIdAtPosition(lineNumber, 0); if (lineNumber > 1) { var lastLineNumber = void 0; var resultLineNumber = -1; for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) { if (model.getLanguageIdAtPosition(lastLineNumber, 0) !== languageID) { return resultLineNumber; } var 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. */ LanguageConfigurationRegistryImpl.prototype.getInheritIndentForLine = function (autoIndent, model, lineNumber, honorIntentialIndent) { if (honorIntentialIndent === void 0) { honorIntentialIndent = true; } if (autoIndent < 4 /* Full */) { return null; } var indentRulesSupport = this.getIndentRulesSupport(model.getLanguageIdentifier().id); if (!indentRulesSupport) { return null; } if (lineNumber <= 1) { return { indentation: '', action: null }; } var precedingUnIgnoredLine = this.getPrecedingValidLine(model, lineNumber, indentRulesSupport); if (precedingUnIgnoredLine < 0) { return null; } else if (precedingUnIgnoredLine < 1) { return { indentation: '', action: null }; } var 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 }; } var previousLine = precedingUnIgnoredLine - 1; var previousLineIndentMetadata = indentRulesSupport.getIndentMetadata(model.getLineContent(previousLine)); if (!(previousLineIndentMetadata & (1 /* INCREASE_MASK */ | 2 /* DECREASE_MASK */)) && (previousLineIndentMetadata & 4 /* INDENT_NEXTLINE_MASK */)) { var stopLine = 0; for (var 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 (var i = precedingUnIgnoredLine; i > 0; i--) { var 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)) { var stopLine = 0; for (var 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 }; } } }; LanguageConfigurationRegistryImpl.prototype.getGoodIndentForLine = function (autoIndent, virtualModel, languageId, lineNumber, indentConverter) { if (autoIndent < 4 /* Full */) { return null; } var richEditSupport = this._getRichEditSupport(languageId); if (!richEditSupport) { return null; } var indentRulesSupport = this.getIndentRulesSupport(languageId); if (!indentRulesSupport) { return null; } var indent = this.getInheritIndentForLine(autoIndent, virtualModel, lineNumber); var lineContent = virtualModel.getLineContent(lineNumber); if (indent) { var inheritLine = indent.line; if (inheritLine !== undefined) { var enterResult = richEditSupport.onEnter(autoIndent, '', virtualModel.getLineContent(inheritLine), ''); if (enterResult) { var 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; }; LanguageConfigurationRegistryImpl.prototype.getIndentForEnter = function (autoIndent, model, range, indentConverter) { if (autoIndent < 4 /* Full */) { return null; } model.forceTokenization(range.startLineNumber); var lineTokens = model.getLineTokens(range.startLineNumber); var scopedLineTokens = supports_1.createScopedLineTokens(lineTokens, range.startColumn - 1); var scopedLineText = scopedLineTokens.getLineContent(); var embeddedLanguage = false; var 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); } var afterEnterText; if (range.isEmpty()) { afterEnterText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset); } else { var endScopedLineTokens = this.getScopedLineTokens(model, range.endLineNumber, range.endColumn); afterEnterText = endScopedLineTokens.getLineContent().substr(range.endColumn - 1 - scopedLineTokens.firstCharOffset); } var indentRulesSupport = this.getIndentRulesSupport(scopedLineTokens.languageId); if (!indentRulesSupport) { return null; } var beforeEnterResult = beforeEnterText; var beforeEnterIndent = strings.getLeadingWhitespace(beforeEnterText); var virtualModel = { getLineTokens: function (lineNumber) { return model.getLineTokens(lineNumber); }, getLanguageIdentifier: function () { return model.getLanguageIdentifier(); }, getLanguageIdAtPosition: function (lineNumber, column) { return model.getLanguageIdAtPosition(lineNumber, column); }, getLineContent: function (lineNumber) { if (lineNumber === range.startLineNumber) { return beforeEnterResult; } else { return model.getLineContent(lineNumber); } } }; var currentLineIndent = strings.getLeadingWhitespace(lineTokens.getLineContent()); var afterEnterAction = this.getInheritIndentForLine(autoIndent, virtualModel, range.startLineNumber + 1); if (!afterEnterAction) { var beforeEnter = embeddedLanguage ? currentLineIndent : beforeEnterIndent; return { beforeEnter: beforeEnter, afterEnter: beforeEnter }; } var 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. */ LanguageConfigurationRegistryImpl.prototype.getIndentActionForType = function (autoIndent, model, range, ch, indentConverter) { if (autoIndent < 4 /* Full */) { return null; } var scopedLineTokens = this.getScopedLineTokens(model, range.startLineNumber, range.startColumn); var indentRulesSupport = this.getIndentRulesSupport(scopedLineTokens.languageId); if (!indentRulesSupport) { return null; } var scopedLineText = scopedLineTokens.getLineContent(); var beforeTypeText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset); // selection support var afterTypeText; if (range.isEmpty()) { afterTypeText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset); } else { var 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 var r = this.getInheritIndentForLine(autoIndent, model, range.startLineNumber, false); if (!r) { return null; } var indentation = r.indentation; if (r.action !== languageConfiguration_1.IndentAction.Indent) { indentation = indentConverter.unshiftIndent(indentation); } return indentation; } return null; }; LanguageConfigurationRegistryImpl.prototype.getIndentMetadata = function (model, lineNumber) { var indentRulesSupport = this.getIndentRulesSupport(model.getLanguageIdentifier().id); if (!indentRulesSupport) { return null; } if (lineNumber < 1 || lineNumber > model.getLineCount()) { return null; } return indentRulesSupport.getIndentMetadata(model.getLineContent(lineNumber)); }; // end Indent Rules // begin onEnter LanguageConfigurationRegistryImpl.prototype.getEnterAction = function (autoIndent, model, range) { var scopedLineTokens = this.getScopedLineTokens(model, range.startLineNumber, range.startColumn); var richEditSupport = this._getRichEditSupport(scopedLineTokens.languageId); if (!richEditSupport) { return null; } var scopedLineText = scopedLineTokens.getLineContent(); var beforeEnterText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset); // selection support var afterEnterText; if (range.isEmpty()) { afterEnterText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset); } else { var endScopedLineTokens = this.getScopedLineTokens(model, range.endLineNumber, range.endColumn); afterEnterText = endScopedLineTokens.getLineContent().substr(range.endColumn - 1 - scopedLineTokens.firstCharOffset); } var oneLineAboveText = ''; if (range.startLineNumber > 1 && scopedLineTokens.firstCharOffset === 0) { // This is not the first line and the entire line belongs to this mode var oneLineAboveScopedLineTokens = this.getScopedLineTokens(model, range.startLineNumber - 1); if (oneLineAboveScopedLineTokens.languageId === scopedLineTokens.languageId) { // The line above ends with text belonging to the same mode oneLineAboveText = oneLineAboveScopedLineTokens.getLineContent(); } } var enterResult = richEditSupport.onEnter(autoIndent, oneLineAboveText, beforeEnterText, afterEnterText); if (!enterResult) { return null; } var indentAction = enterResult.indentAction; var appendText = enterResult.appendText; var 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 = ''; } } var 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 }; }; LanguageConfigurationRegistryImpl.prototype.getIndentationAtPosition = function (model, lineNumber, column) { var lineText = model.getLineContent(lineNumber); var indentation = strings.getLeadingWhitespace(lineText); if (indentation.length > column - 1) { indentation = indentation.substring(0, column - 1); } return indentation; }; LanguageConfigurationRegistryImpl.prototype.getScopedLineTokens = function (model, lineNumber, columnNumber) { model.forceTokenization(lineNumber); var lineTokens = model.getLineTokens(lineNumber); var column = (typeof columnNumber === 'undefined' ? model.getLineMaxColumn(lineNumber) - 1 : columnNumber - 1); return supports_1.createScopedLineTokens(lineTokens, column); }; // end onEnter LanguageConfigurationRegistryImpl.prototype.getBracketsSupport = function (languageId) { var value = this._getRichEditSupport(languageId); if (!value) { return null; } return value.brackets || null; }; return LanguageConfigurationRegistryImpl; }()); exports.LanguageConfigurationRegistryImpl = LanguageConfigurationRegistryImpl; exports.LanguageConfigurationRegistry = new LanguageConfigurationRegistryImpl(); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[357/*vs/editor/common/modes/supports/tokenization*/], __M([0/*require*/,1/*exports*/,27/*vs/base/common/color*/]), function (require, exports, color_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ParsedTokenThemeRule = /** @class */ (function () { function ParsedTokenThemeRule(token, index, fontStyle, foreground, background) { this.token = token; this.index = index; this.fontStyle = fontStyle; this.foreground = foreground; this.background = background; } return ParsedTokenThemeRule; }()); exports.ParsedTokenThemeRule = ParsedTokenThemeRule; /** * Parse a raw theme into rules. */ function parseTokenTheme(source) { if (!source || !Array.isArray(source)) { return []; } var result = [], resultLen = 0; for (var i = 0, len = source.length; i < len; i++) { var entry = source[i]; var fontStyle = -1 /* NotSet */; if (typeof entry.fontStyle === 'string') { fontStyle = 0 /* None */; var segments = entry.fontStyle.split(' '); for (var j = 0, lenJ = segments.length; j < lenJ; j++) { var 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; } } } var foreground = null; if (typeof entry.foreground === 'string') { foreground = entry.foreground; } var 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(function (a, b) { var r = strcmp(a.token, b.token); if (r !== 0) { return r; } return a.index - b.index; }); // Determine defaults var defaultFontStyle = 0 /* None */; var defaultForeground = '000000'; var defaultBackground = 'ffffff'; while (parsedThemeRules.length >= 1 && parsedThemeRules[0].token === '') { var 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; } } var colorMap = new ColorMap(); // start with token colors from custom token themes for (var _i = 0, customTokenColors_1 = customTokenColors; _i < customTokenColors_1.length; _i++) { var color = customTokenColors_1[_i]; colorMap.getId(color); } var foregroundColorId = colorMap.getId(defaultForeground); var backgroundColorId = colorMap.getId(defaultBackground); var defaults = new ThemeTrieElementRule(defaultFontStyle, foregroundColorId, backgroundColorId); var root = new ThemeTrieElement(defaults); for (var i = 0, len = parsedThemeRules.length; i < len; i++) { var rule = parsedThemeRules[i]; root.insert(rule.token, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background)); } return new TokenTheme(colorMap, root); } var colorRegExp = /^#?([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?$/; var ColorMap = /** @class */ (function () { function ColorMap() { this._lastColorId = 0; this._id2color = []; this._color2id = new Map(); } ColorMap.prototype.getId = function (color) { if (color === null) { return 0; } var match = color.match(colorRegExp); if (!match) { throw new Error('Illegal value for token color: ' + color); } color = match[1].toUpperCase(); var 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; }; ColorMap.prototype.getColorMap = function () { return this._id2color.slice(0); }; return ColorMap; }()); exports.ColorMap = ColorMap; var TokenTheme = /** @class */ (function () { function TokenTheme(colorMap, root) { this._colorMap = colorMap; this._root = root; this._cache = new Map(); } TokenTheme.createFromRawTokenTheme = function (source, customTokenColors) { return this.createFromParsedTokenTheme(parseTokenTheme(source), customTokenColors); }; TokenTheme.createFromParsedTokenTheme = function (source, customTokenColors) { return resolveParsedTokenThemeRules(source, customTokenColors); }; TokenTheme.prototype.getColorMap = function () { return this._colorMap.getColorMap(); }; TokenTheme.prototype._match = function (token) { return this._root.match(token); }; TokenTheme.prototype.match = function (languageId, token) { // The cache contains the metadata without the language bits set. var result = this._cache.get(token); if (typeof result === 'undefined') { var rule = this._match(token); var standardToken = toStandardTokenType(token); result = (rule.metadata | (standardToken << 8 /* TOKEN_TYPE_OFFSET */)) >>> 0; this._cache.set(token, result); } return (result | (languageId << 0 /* LANGUAGEID_OFFSET */)) >>> 0; }; return TokenTheme; }()); exports.TokenTheme = TokenTheme; var STANDARD_TOKEN_TYPE_REGEXP = /\b(comment|string|regex|regexp)\b/; function toStandardTokenType(tokenType) { var m = tokenType.match(STANDARD_TOKEN_TYPE_REGEXP); if (!m) { return 0 /* Other */; } switch (m[1]) { case 'comment': return 1 /* Comment */; case 'string': return 2 /* String */; case 'regex': return 4 /* RegEx */; case 'regexp': return 4 /* RegEx */; } throw new Error('Unexpected match for standard token type!'); } exports.toStandardTokenType = toStandardTokenType; function strcmp(a, b) { if (a < b) { return -1; } if (a > b) { return 1; } return 0; } exports.strcmp = strcmp; var ThemeTrieElementRule = /** @class */ (function () { function ThemeTrieElementRule(fontStyle, foreground, background) { this._fontStyle = fontStyle; this._foreground = foreground; this._background = background; this.metadata = ((this._fontStyle << 11 /* FONT_STYLE_OFFSET */) | (this._foreground << 14 /* FOREGROUND_OFFSET */) | (this._background << 23 /* BACKGROUND_OFFSET */)) >>> 0; } ThemeTrieElementRule.prototype.clone = function () { return new ThemeTrieElementRule(this._fontStyle, this._foreground, this._background); }; ThemeTrieElementRule.prototype.acceptOverwrite = function (fontStyle, foreground, background) { if (fontStyle !== -1 /* NotSet */) { this._fontStyle = fontStyle; } if (foreground !== 0 /* None */) { this._foreground = foreground; } if (background !== 0 /* None */) { this._background = background; } this.metadata = ((this._fontStyle << 11 /* FONT_STYLE_OFFSET */) | (this._foreground << 14 /* FOREGROUND_OFFSET */) | (this._background << 23 /* BACKGROUND_OFFSET */)) >>> 0; }; return ThemeTrieElementRule; }()); exports.ThemeTrieElementRule = ThemeTrieElementRule; var ThemeTrieElement = /** @class */ (function () { function ThemeTrieElement(mainRule) { this._mainRule = mainRule; this._children = new Map(); } ThemeTrieElement.prototype.match = function (token) { if (token === '') { return this._mainRule; } var dotIndex = token.indexOf('.'); var head; var tail; if (dotIndex === -1) { head = token; tail = ''; } else { head = token.substring(0, dotIndex); tail = token.substring(dotIndex + 1); } var child = this._children.get(head); if (typeof child !== 'undefined') { return child.match(tail); } return this._mainRule; }; ThemeTrieElement.prototype.insert = function (token, fontStyle, foreground, background) { if (token === '') { // Merge into the main rule this._mainRule.acceptOverwrite(fontStyle, foreground, background); return; } var dotIndex = token.indexOf('.'); var head; var tail; if (dotIndex === -1) { head = token; tail = ''; } else { head = token.substring(0, dotIndex); tail = token.substring(dotIndex + 1); } var 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); }; return ThemeTrieElement; }()); exports.ThemeTrieElement = ThemeTrieElement; function generateTokensCSSForColorMap(colorMap) { var rules = []; for (var i = 1, len = colorMap.length; i < len; i++) { var color = colorMap[i]; rules[i] = ".mtk" + i + " { color: " + color + "; }"; } rules.push('.mtki { font-style: italic; }'); rules.push('.mtkb { font-weight: bold; }'); rules.push('.mtku { text-decoration: underline; text-underline-position: under; }'); return rules.join('\n'); } exports.generateTokensCSSForColorMap = generateTokensCSSForColorMap; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[358/*vs/editor/common/modes/tokenizationRegistry*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/types*/,38/*vs/base/common/map*/]), function (require, exports, event_1, lifecycle_1, types_1, map_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var TokenizationRegistryImpl = /** @class */ (function () { function TokenizationRegistryImpl() { this._map = new Map(); this._promises = new Map(); this._onDidChange = new event_1.Emitter(); this.onDidChange = this._onDidChange.event; this._colorMap = null; } TokenizationRegistryImpl.prototype.fire = function (languages) { this._onDidChange.fire({ changedLanguages: languages, changedColorMap: false }); }; TokenizationRegistryImpl.prototype.register = function (language, support) { var _this = this; this._map.set(language, support); this.fire([language]); return lifecycle_1.toDisposable(function () { if (_this._map.get(language) !== support) { return; } _this._map.delete(language); _this.fire([language]); }); }; TokenizationRegistryImpl.prototype.registerPromise = function (language, supportPromise) { var _this = this; var registration = null; var isDisposed = false; this._promises.set(language, supportPromise.then(function (support) { _this._promises.delete(language); if (isDisposed || !support) { return; } registration = _this.register(language, support); })); return lifecycle_1.toDisposable(function () { isDisposed = true; if (registration) { registration.dispose(); } }); }; TokenizationRegistryImpl.prototype.getPromise = function (language) { var _this = this; var support = this.get(language); if (support) { return Promise.resolve(support); } var promise = this._promises.get(language); if (promise) { return promise.then(function (_) { return _this.get(language); }); } return null; }; TokenizationRegistryImpl.prototype.get = function (language) { return types_1.withUndefinedAsNull(this._map.get(language)); }; TokenizationRegistryImpl.prototype.setColorMap = function (colorMap) { this._colorMap = colorMap; this._onDidChange.fire({ changedLanguages: map_1.keys(this._map), changedColorMap: true }); }; TokenizationRegistryImpl.prototype.getColorMap = function () { return this._colorMap; }; TokenizationRegistryImpl.prototype.getDefaultBackground = function () { if (this._colorMap && this._colorMap.length > 2 /* DefaultBackground */) { return this._colorMap[2 /* DefaultBackground */]; } return null; }; return TokenizationRegistryImpl; }()); exports.TokenizationRegistryImpl = TokenizationRegistryImpl; }); /*! Copyright (c) 2014 Taylor Hakes Copyright (c) 2014 Forbes Lindesay */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory() : typeof define === 'function' && define.amd ? define("vs/editor/common/standalone/promise-polyfill/polyfill", factory) : (factory()); }(this, (function () { 'use strict'; /** * @this {Promise} */ function finallyConstructor(callback) { var constructor = this.constructor; return this.then( function (value) { return constructor.resolve(callback()).then(function () { return value; }); }, function (reason) { return constructor.resolve(callback()).then(function () { return constructor.reject(reason); }); } ); } // Store setTimeout reference so promise-polyfill will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var setTimeoutFunc = setTimeout; function noop() { } // Polyfill for Function.prototype.bind function bind(fn, thisArg) { return function () { fn.apply(thisArg, arguments); }; } /** * @constructor * @param {Function} fn */ function Promise(fn) { if (!(this instanceof Promise)) throw new TypeError('Promises must be constructed via new'); if (typeof fn !== 'function') throw new TypeError('not a function'); /** @type {!number} */ this._state = 0; /** @type {!boolean} */ this._handled = false; /** @type {Promise|undefined} */ this._value = undefined; /** @type {!Array} */ this._deferreds = []; doResolve(fn, this); } function handle(self, deferred) { while (self._state === 3) { self = self._value; } if (self._state === 0) { self._deferreds.push(deferred); return; } self._handled = true; Promise._immediateFn(function () { var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected; if (cb === null) { (self._state === 1 ? resolve : reject)(deferred.promise, self._value); return; } var ret; try { ret = cb(self._value); } catch (e) { reject(deferred.promise, e); return; } resolve(deferred.promise, ret); }); } function resolve(self, newValue) { try { // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.'); if ( newValue && (typeof newValue === 'object' || typeof newValue === 'function') ) { var then = newValue.then; if (newValue instanceof Promise) { self._state = 3; self._value = newValue; finale(self); return; } else if (typeof then === 'function') { doResolve(bind(then, newValue), self); return; } } self._state = 1; self._value = newValue; finale(self); } catch (e) { reject(self, e); } } function reject(self, newValue) { self._state = 2; self._value = newValue; finale(self); } function finale(self) { if (self._state === 2 && self._deferreds.length === 0) { Promise._immediateFn(function () { if (!self._handled) { Promise._unhandledRejectionFn(self._value); } }); } for (var i = 0, len = self._deferreds.length; i < len; i++) { handle(self, self._deferreds[i]); } self._deferreds = null; } /** * @constructor */ function Handler(onFulfilled, onRejected, promise) { this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; this.onRejected = typeof onRejected === 'function' ? onRejected : null; this.promise = promise; } /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function doResolve(fn, self) { var done = false; try { fn( function (value) { if (done) return; done = true; resolve(self, value); }, function (reason) { if (done) return; done = true; reject(self, reason); } ); } catch (ex) { if (done) return; done = true; reject(self, ex); } } Promise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); }; Promise.prototype.then = function (onFulfilled, onRejected) { // @ts-ignore var prom = new this.constructor(noop); handle(this, new Handler(onFulfilled, onRejected, prom)); return prom; }; Promise.prototype['finally'] = finallyConstructor; Promise.all = function (arr) { return new Promise(function (resolve, reject) { if (!arr || typeof arr.length === 'undefined') throw new TypeError('Promise.all accepts an array'); var args = Array.prototype.slice.call(arr); if (args.length === 0) return resolve([]); var remaining = args.length; function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then; if (typeof then === 'function') { then.call( val, function (val) { res(i, val); }, reject ); return; } } args[i] = val; if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex); } } for (var i = 0; i < args.length; i++) { res(i, args[i]); } }); }; Promise.resolve = function (value) { if (value && typeof value === 'object' && value.constructor === Promise) { return value; } return new Promise(function (resolve) { resolve(value); }); }; Promise.reject = function (value) { return new Promise(function (resolve, reject) { reject(value); }); }; Promise.race = function (values) { return new Promise(function (resolve, reject) { for (var i = 0, len = values.length; i < len; i++) { values[i].then(resolve, reject); } }); }; // Use polyfill for setImmediate for performance gains Promise._immediateFn = (typeof setImmediate === 'function' && function (fn) { setImmediate(fn); }) || function (fn) { setTimeoutFunc(fn, 0); }; Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) { if (typeof console !== 'undefined' && console) { console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console } }; /** @suppress {undefinedVars} */ var globalNS = (function () { // the only reliable means to get the global object is // `Function('return this')()` // However, this causes CSP violations in Chrome apps. if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } throw new Error('unable to locate global object'); })(); if (!('Promise' in globalNS)) { globalNS['Promise'] = Promise; } else if (!globalNS.Promise.prototype['finally']) { globalNS.Promise.prototype['finally'] = finallyConstructor; } }))); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[147/*vs/editor/common/standalone/standaloneEnums*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // 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["Snippet"] = 25] = "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["autoClosingOvertype"] = 6] = "autoClosingOvertype"; EditorOption[EditorOption["autoClosingQuotes"] = 7] = "autoClosingQuotes"; EditorOption[EditorOption["autoIndent"] = 8] = "autoIndent"; EditorOption[EditorOption["automaticLayout"] = 9] = "automaticLayout"; EditorOption[EditorOption["autoSurround"] = 10] = "autoSurround"; EditorOption[EditorOption["codeLens"] = 11] = "codeLens"; EditorOption[EditorOption["colorDecorators"] = 12] = "colorDecorators"; EditorOption[EditorOption["comments"] = 13] = "comments"; EditorOption[EditorOption["contextmenu"] = 14] = "contextmenu"; EditorOption[EditorOption["copyWithSyntaxHighlighting"] = 15] = "copyWithSyntaxHighlighting"; EditorOption[EditorOption["cursorBlinking"] = 16] = "cursorBlinking"; EditorOption[EditorOption["cursorSmoothCaretAnimation"] = 17] = "cursorSmoothCaretAnimation"; EditorOption[EditorOption["cursorStyle"] = 18] = "cursorStyle"; EditorOption[EditorOption["cursorSurroundingLines"] = 19] = "cursorSurroundingLines"; EditorOption[EditorOption["cursorSurroundingLinesStyle"] = 20] = "cursorSurroundingLinesStyle"; EditorOption[EditorOption["cursorWidth"] = 21] = "cursorWidth"; EditorOption[EditorOption["disableLayerHinting"] = 22] = "disableLayerHinting"; EditorOption[EditorOption["disableMonospaceOptimizations"] = 23] = "disableMonospaceOptimizations"; EditorOption[EditorOption["dragAndDrop"] = 24] = "dragAndDrop"; EditorOption[EditorOption["emptySelectionClipboard"] = 25] = "emptySelectionClipboard"; EditorOption[EditorOption["extraEditorClassName"] = 26] = "extraEditorClassName"; EditorOption[EditorOption["fastScrollSensitivity"] = 27] = "fastScrollSensitivity"; EditorOption[EditorOption["find"] = 28] = "find"; EditorOption[EditorOption["fixedOverflowWidgets"] = 29] = "fixedOverflowWidgets"; EditorOption[EditorOption["folding"] = 30] = "folding"; EditorOption[EditorOption["foldingStrategy"] = 31] = "foldingStrategy"; EditorOption[EditorOption["foldingHighlight"] = 32] = "foldingHighlight"; EditorOption[EditorOption["fontFamily"] = 33] = "fontFamily"; EditorOption[EditorOption["fontInfo"] = 34] = "fontInfo"; EditorOption[EditorOption["fontLigatures"] = 35] = "fontLigatures"; EditorOption[EditorOption["fontSize"] = 36] = "fontSize"; EditorOption[EditorOption["fontWeight"] = 37] = "fontWeight"; EditorOption[EditorOption["formatOnPaste"] = 38] = "formatOnPaste"; EditorOption[EditorOption["formatOnType"] = 39] = "formatOnType"; EditorOption[EditorOption["glyphMargin"] = 40] = "glyphMargin"; EditorOption[EditorOption["gotoLocation"] = 41] = "gotoLocation"; EditorOption[EditorOption["hideCursorInOverviewRuler"] = 42] = "hideCursorInOverviewRuler"; EditorOption[EditorOption["highlightActiveIndentGuide"] = 43] = "highlightActiveIndentGuide"; EditorOption[EditorOption["hover"] = 44] = "hover"; EditorOption[EditorOption["inDiffEditor"] = 45] = "inDiffEditor"; EditorOption[EditorOption["letterSpacing"] = 46] = "letterSpacing"; EditorOption[EditorOption["lightbulb"] = 47] = "lightbulb"; EditorOption[EditorOption["lineDecorationsWidth"] = 48] = "lineDecorationsWidth"; EditorOption[EditorOption["lineHeight"] = 49] = "lineHeight"; EditorOption[EditorOption["lineNumbers"] = 50] = "lineNumbers"; EditorOption[EditorOption["lineNumbersMinChars"] = 51] = "lineNumbersMinChars"; EditorOption[EditorOption["links"] = 52] = "links"; EditorOption[EditorOption["matchBrackets"] = 53] = "matchBrackets"; EditorOption[EditorOption["minimap"] = 54] = "minimap"; EditorOption[EditorOption["mouseStyle"] = 55] = "mouseStyle"; EditorOption[EditorOption["mouseWheelScrollSensitivity"] = 56] = "mouseWheelScrollSensitivity"; EditorOption[EditorOption["mouseWheelZoom"] = 57] = "mouseWheelZoom"; EditorOption[EditorOption["multiCursorMergeOverlapping"] = 58] = "multiCursorMergeOverlapping"; EditorOption[EditorOption["multiCursorModifier"] = 59] = "multiCursorModifier"; EditorOption[EditorOption["multiCursorPaste"] = 60] = "multiCursorPaste"; EditorOption[EditorOption["occurrencesHighlight"] = 61] = "occurrencesHighlight"; EditorOption[EditorOption["overviewRulerBorder"] = 62] = "overviewRulerBorder"; EditorOption[EditorOption["overviewRulerLanes"] = 63] = "overviewRulerLanes"; EditorOption[EditorOption["parameterHints"] = 64] = "parameterHints"; EditorOption[EditorOption["peekWidgetDefaultFocus"] = 65] = "peekWidgetDefaultFocus"; EditorOption[EditorOption["quickSuggestions"] = 66] = "quickSuggestions"; EditorOption[EditorOption["quickSuggestionsDelay"] = 67] = "quickSuggestionsDelay"; EditorOption[EditorOption["readOnly"] = 68] = "readOnly"; EditorOption[EditorOption["renderControlCharacters"] = 69] = "renderControlCharacters"; EditorOption[EditorOption["renderIndentGuides"] = 70] = "renderIndentGuides"; EditorOption[EditorOption["renderFinalNewline"] = 71] = "renderFinalNewline"; EditorOption[EditorOption["renderLineHighlight"] = 72] = "renderLineHighlight"; EditorOption[EditorOption["renderValidationDecorations"] = 73] = "renderValidationDecorations"; EditorOption[EditorOption["renderWhitespace"] = 74] = "renderWhitespace"; EditorOption[EditorOption["revealHorizontalRightPadding"] = 75] = "revealHorizontalRightPadding"; EditorOption[EditorOption["roundedSelection"] = 76] = "roundedSelection"; EditorOption[EditorOption["rulers"] = 77] = "rulers"; EditorOption[EditorOption["scrollbar"] = 78] = "scrollbar"; EditorOption[EditorOption["scrollBeyondLastColumn"] = 79] = "scrollBeyondLastColumn"; EditorOption[EditorOption["scrollBeyondLastLine"] = 80] = "scrollBeyondLastLine"; EditorOption[EditorOption["selectionClipboard"] = 81] = "selectionClipboard"; EditorOption[EditorOption["selectionHighlight"] = 82] = "selectionHighlight"; EditorOption[EditorOption["selectOnLineNumbers"] = 83] = "selectOnLineNumbers"; EditorOption[EditorOption["showFoldingControls"] = 84] = "showFoldingControls"; EditorOption[EditorOption["showUnused"] = 85] = "showUnused"; EditorOption[EditorOption["snippetSuggestions"] = 86] = "snippetSuggestions"; EditorOption[EditorOption["smoothScrolling"] = 87] = "smoothScrolling"; EditorOption[EditorOption["stopRenderingLineAfter"] = 88] = "stopRenderingLineAfter"; EditorOption[EditorOption["suggest"] = 89] = "suggest"; EditorOption[EditorOption["suggestFontSize"] = 90] = "suggestFontSize"; EditorOption[EditorOption["suggestLineHeight"] = 91] = "suggestLineHeight"; EditorOption[EditorOption["suggestOnTriggerCharacters"] = 92] = "suggestOnTriggerCharacters"; EditorOption[EditorOption["suggestSelection"] = 93] = "suggestSelection"; EditorOption[EditorOption["tabCompletion"] = 94] = "tabCompletion"; EditorOption[EditorOption["useTabStops"] = 95] = "useTabStops"; EditorOption[EditorOption["wordSeparators"] = 96] = "wordSeparators"; EditorOption[EditorOption["wordWrap"] = 97] = "wordWrap"; EditorOption[EditorOption["wordWrapBreakAfterCharacters"] = 98] = "wordWrapBreakAfterCharacters"; EditorOption[EditorOption["wordWrapBreakBeforeCharacters"] = 99] = "wordWrapBreakBeforeCharacters"; EditorOption[EditorOption["wordWrapColumn"] = 100] = "wordWrapColumn"; EditorOption[EditorOption["wordWrapMinified"] = 101] = "wordWrapMinified"; EditorOption[EditorOption["wrappingIndent"] = 102] = "wrappingIndent"; EditorOption[EditorOption["wrappingStrategy"] = 103] = "wrappingStrategy"; EditorOption[EditorOption["editorClassName"] = 104] = "editorClassName"; EditorOption[EditorOption["pixelRatio"] = 105] = "pixelRatio"; EditorOption[EditorOption["tabFocusMode"] = 106] = "tabFocusMode"; EditorOption[EditorOption["layoutInfo"] = 107] = "layoutInfo"; EditorOption[EditorOption["wrappingInfo"] = 108] = "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 = {})); /** * 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) { /** * Placed first to cover the 0 value of the enum. */ KeyCode[KeyCode["Unknown"] = 0] = "Unknown"; KeyCode[KeyCode["Backspace"] = 1] = "Backspace"; KeyCode[KeyCode["Tab"] = 2] = "Tab"; KeyCode[KeyCode["Enter"] = 3] = "Enter"; KeyCode[KeyCode["Shift"] = 4] = "Shift"; KeyCode[KeyCode["Ctrl"] = 5] = "Ctrl"; KeyCode[KeyCode["Alt"] = 6] = "Alt"; KeyCode[KeyCode["PauseBreak"] = 7] = "PauseBreak"; KeyCode[KeyCode["CapsLock"] = 8] = "CapsLock"; KeyCode[KeyCode["Escape"] = 9] = "Escape"; KeyCode[KeyCode["Space"] = 10] = "Space"; KeyCode[KeyCode["PageUp"] = 11] = "PageUp"; KeyCode[KeyCode["PageDown"] = 12] = "PageDown"; KeyCode[KeyCode["End"] = 13] = "End"; KeyCode[KeyCode["Home"] = 14] = "Home"; KeyCode[KeyCode["LeftArrow"] = 15] = "LeftArrow"; KeyCode[KeyCode["UpArrow"] = 16] = "UpArrow"; KeyCode[KeyCode["RightArrow"] = 17] = "RightArrow"; KeyCode[KeyCode["DownArrow"] = 18] = "DownArrow"; KeyCode[KeyCode["Insert"] = 19] = "Insert"; KeyCode[KeyCode["Delete"] = 20] = "Delete"; KeyCode[KeyCode["KEY_0"] = 21] = "KEY_0"; KeyCode[KeyCode["KEY_1"] = 22] = "KEY_1"; KeyCode[KeyCode["KEY_2"] = 23] = "KEY_2"; KeyCode[KeyCode["KEY_3"] = 24] = "KEY_3"; KeyCode[KeyCode["KEY_4"] = 25] = "KEY_4"; KeyCode[KeyCode["KEY_5"] = 26] = "KEY_5"; KeyCode[KeyCode["KEY_6"] = 27] = "KEY_6"; KeyCode[KeyCode["KEY_7"] = 28] = "KEY_7"; KeyCode[KeyCode["KEY_8"] = 29] = "KEY_8"; KeyCode[KeyCode["KEY_9"] = 30] = "KEY_9"; KeyCode[KeyCode["KEY_A"] = 31] = "KEY_A"; KeyCode[KeyCode["KEY_B"] = 32] = "KEY_B"; KeyCode[KeyCode["KEY_C"] = 33] = "KEY_C"; KeyCode[KeyCode["KEY_D"] = 34] = "KEY_D"; KeyCode[KeyCode["KEY_E"] = 35] = "KEY_E"; KeyCode[KeyCode["KEY_F"] = 36] = "KEY_F"; KeyCode[KeyCode["KEY_G"] = 37] = "KEY_G"; KeyCode[KeyCode["KEY_H"] = 38] = "KEY_H"; KeyCode[KeyCode["KEY_I"] = 39] = "KEY_I"; KeyCode[KeyCode["KEY_J"] = 40] = "KEY_J"; KeyCode[KeyCode["KEY_K"] = 41] = "KEY_K"; KeyCode[KeyCode["KEY_L"] = 42] = "KEY_L"; KeyCode[KeyCode["KEY_M"] = 43] = "KEY_M"; KeyCode[KeyCode["KEY_N"] = 44] = "KEY_N"; KeyCode[KeyCode["KEY_O"] = 45] = "KEY_O"; KeyCode[KeyCode["KEY_P"] = 46] = "KEY_P"; KeyCode[KeyCode["KEY_Q"] = 47] = "KEY_Q"; KeyCode[KeyCode["KEY_R"] = 48] = "KEY_R"; KeyCode[KeyCode["KEY_S"] = 49] = "KEY_S"; KeyCode[KeyCode["KEY_T"] = 50] = "KEY_T"; KeyCode[KeyCode["KEY_U"] = 51] = "KEY_U"; KeyCode[KeyCode["KEY_V"] = 52] = "KEY_V"; KeyCode[KeyCode["KEY_W"] = 53] = "KEY_W"; KeyCode[KeyCode["KEY_X"] = 54] = "KEY_X"; KeyCode[KeyCode["KEY_Y"] = 55] = "KEY_Y"; KeyCode[KeyCode["KEY_Z"] = 56] = "KEY_Z"; KeyCode[KeyCode["Meta"] = 57] = "Meta"; KeyCode[KeyCode["ContextMenu"] = 58] = "ContextMenu"; KeyCode[KeyCode["F1"] = 59] = "F1"; KeyCode[KeyCode["F2"] = 60] = "F2"; KeyCode[KeyCode["F3"] = 61] = "F3"; KeyCode[KeyCode["F4"] = 62] = "F4"; KeyCode[KeyCode["F5"] = 63] = "F5"; KeyCode[KeyCode["F6"] = 64] = "F6"; KeyCode[KeyCode["F7"] = 65] = "F7"; KeyCode[KeyCode["F8"] = 66] = "F8"; KeyCode[KeyCode["F9"] = 67] = "F9"; KeyCode[KeyCode["F10"] = 68] = "F10"; KeyCode[KeyCode["F11"] = 69] = "F11"; KeyCode[KeyCode["F12"] = 70] = "F12"; KeyCode[KeyCode["F13"] = 71] = "F13"; KeyCode[KeyCode["F14"] = 72] = "F14"; KeyCode[KeyCode["F15"] = 73] = "F15"; KeyCode[KeyCode["F16"] = 74] = "F16"; KeyCode[KeyCode["F17"] = 75] = "F17"; KeyCode[KeyCode["F18"] = 76] = "F18"; KeyCode[KeyCode["F19"] = 77] = "F19"; KeyCode[KeyCode["NumLock"] = 78] = "NumLock"; KeyCode[KeyCode["ScrollLock"] = 79] = "ScrollLock"; /** * Used for miscellaneous characters; it can vary by keyboard. * For the US standard keyboard, the ';:' key */ KeyCode[KeyCode["US_SEMICOLON"] = 80] = "US_SEMICOLON"; /** * For any country/region, the '+' key * For the US standard keyboard, the '=+' key */ KeyCode[KeyCode["US_EQUAL"] = 81] = "US_EQUAL"; /** * For any country/region, the ',' key * For the US standard keyboard, the ',<' key */ KeyCode[KeyCode["US_COMMA"] = 82] = "US_COMMA"; /** * For any country/region, the '-' key * For the US standard keyboard, the '-_' key */ KeyCode[KeyCode["US_MINUS"] = 83] = "US_MINUS"; /** * For any country/region, the '.' key * For the US standard keyboard, the '.>' key */ KeyCode[KeyCode["US_DOT"] = 84] = "US_DOT"; /** * Used for miscellaneous characters; it can vary by keyboard. * For the US standard keyboard, the '/?' key */ KeyCode[KeyCode["US_SLASH"] = 85] = "US_SLASH"; /** * Used for miscellaneous characters; it can vary by keyboard. * For the US standard keyboard, the '`~' key */ KeyCode[KeyCode["US_BACKTICK"] = 86] = "US_BACKTICK"; /** * Used for miscellaneous characters; it can vary by keyboard. * For the US standard keyboard, the '[{' key */ KeyCode[KeyCode["US_OPEN_SQUARE_BRACKET"] = 87] = "US_OPEN_SQUARE_BRACKET"; /** * Used for miscellaneous characters; it can vary by keyboard. * For the US standard keyboard, the '\|' key */ KeyCode[KeyCode["US_BACKSLASH"] = 88] = "US_BACKSLASH"; /** * Used for miscellaneous characters; it can vary by keyboard. * For the US standard keyboard, the ']}' key */ KeyCode[KeyCode["US_CLOSE_SQUARE_BRACKET"] = 89] = "US_CLOSE_SQUARE_BRACKET"; /** * Used for miscellaneous characters; it can vary by keyboard. * For the US standard keyboard, the ''"' key */ KeyCode[KeyCode["US_QUOTE"] = 90] = "US_QUOTE"; /** * Used for miscellaneous characters; it can vary by keyboard. */ KeyCode[KeyCode["OEM_8"] = 91] = "OEM_8"; /** * Either the angle bracket key or the backslash key on the RT 102-key keyboard. */ KeyCode[KeyCode["OEM_102"] = 92] = "OEM_102"; KeyCode[KeyCode["NUMPAD_0"] = 93] = "NUMPAD_0"; KeyCode[KeyCode["NUMPAD_1"] = 94] = "NUMPAD_1"; KeyCode[KeyCode["NUMPAD_2"] = 95] = "NUMPAD_2"; KeyCode[KeyCode["NUMPAD_3"] = 96] = "NUMPAD_3"; KeyCode[KeyCode["NUMPAD_4"] = 97] = "NUMPAD_4"; KeyCode[KeyCode["NUMPAD_5"] = 98] = "NUMPAD_5"; KeyCode[KeyCode["NUMPAD_6"] = 99] = "NUMPAD_6"; KeyCode[KeyCode["NUMPAD_7"] = 100] = "NUMPAD_7"; KeyCode[KeyCode["NUMPAD_8"] = 101] = "NUMPAD_8"; KeyCode[KeyCode["NUMPAD_9"] = 102] = "NUMPAD_9"; KeyCode[KeyCode["NUMPAD_MULTIPLY"] = 103] = "NUMPAD_MULTIPLY"; KeyCode[KeyCode["NUMPAD_ADD"] = 104] = "NUMPAD_ADD"; KeyCode[KeyCode["NUMPAD_SEPARATOR"] = 105] = "NUMPAD_SEPARATOR"; KeyCode[KeyCode["NUMPAD_SUBTRACT"] = 106] = "NUMPAD_SUBTRACT"; KeyCode[KeyCode["NUMPAD_DECIMAL"] = 107] = "NUMPAD_DECIMAL"; KeyCode[KeyCode["NUMPAD_DIVIDE"] = 108] = "NUMPAD_DIVIDE"; /** * Cover all key codes when IME is processing input. */ KeyCode[KeyCode["KEY_IN_COMPOSITION"] = 109] = "KEY_IN_COMPOSITION"; KeyCode[KeyCode["ABNT_C1"] = 110] = "ABNT_C1"; KeyCode[KeyCode["ABNT_C2"] = 111] = "ABNT_C2"; /** * Placed last to cover the length of the enum. * Please do not depend on this value! */ KeyCode[KeyCode["MAX_VALUE"] = 112] = "MAX_VALUE"; })(KeyCode = exports.KeyCode || (exports.KeyCode = {})); var MarkerSeverity; (function (MarkerSeverity) { MarkerSeverity[MarkerSeverity["Hint"] = 1] = "Hint"; MarkerSeverity[MarkerSeverity["Info"] = 2] = "Info"; MarkerSeverity[MarkerSeverity["Warning"] = 4] = "Warning"; MarkerSeverity[MarkerSeverity["Error"] = 8] = "Error"; })(MarkerSeverity = exports.MarkerSeverity || (exports.MarkerSeverity = {})); var MarkerTag; (function (MarkerTag) { MarkerTag[MarkerTag["Unnecessary"] = 1] = "Unnecessary"; MarkerTag[MarkerTag["Deprecated"] = 2] = "Deprecated"; })(MarkerTag = exports.MarkerTag || (exports.MarkerTag = {})); /** * Position in the minimap to render the decoration. */ var MinimapPosition; (function (MinimapPosition) { MinimapPosition[MinimapPosition["Inline"] = 1] = "Inline"; MinimapPosition[MinimapPosition["Gutter"] = 2] = "Gutter"; })(MinimapPosition = exports.MinimapPosition || (exports.MinimapPosition = {})); /** * Type of hit element with the mouse in the editor. */ var MouseTargetType; (function (MouseTargetType) { /** * Mouse is on top of an unknown element. */ MouseTargetType[MouseTargetType["UNKNOWN"] = 0] = "UNKNOWN"; /** * Mouse is on top of the textarea used for input. */ MouseTargetType[MouseTargetType["TEXTAREA"] = 1] = "TEXTAREA"; /** * Mouse is on top of the glyph margin */ MouseTargetType[MouseTargetType["GUTTER_GLYPH_MARGIN"] = 2] = "GUTTER_GLYPH_MARGIN"; /** * Mouse is on top of the line numbers */ MouseTargetType[MouseTargetType["GUTTER_LINE_NUMBERS"] = 3] = "GUTTER_LINE_NUMBERS"; /** * Mouse is on top of the line decorations */ MouseTargetType[MouseTargetType["GUTTER_LINE_DECORATIONS"] = 4] = "GUTTER_LINE_DECORATIONS"; /** * Mouse is on top of the whitespace left in the gutter by a view zone. */ MouseTargetType[MouseTargetType["GUTTER_VIEW_ZONE"] = 5] = "GUTTER_VIEW_ZONE"; /** * Mouse is on top of text in the content. */ MouseTargetType[MouseTargetType["CONTENT_TEXT"] = 6] = "CONTENT_TEXT"; /** * Mouse is on top of empty space in the content (e.g. after line text or below last line) */ MouseTargetType[MouseTargetType["CONTENT_EMPTY"] = 7] = "CONTENT_EMPTY"; /** * Mouse is on top of a view zone in the content. */ MouseTargetType[MouseTargetType["CONTENT_VIEW_ZONE"] = 8] = "CONTENT_VIEW_ZONE"; /** * Mouse is on top of a content widget. */ MouseTargetType[MouseTargetType["CONTENT_WIDGET"] = 9] = "CONTENT_WIDGET"; /** * Mouse is on top of the decorations overview ruler. */ MouseTargetType[MouseTargetType["OVERVIEW_RULER"] = 10] = "OVERVIEW_RULER"; /** * Mouse is on top of a scrollbar. */ MouseTargetType[MouseTargetType["SCROLLBAR"] = 11] = "SCROLLBAR"; /** * Mouse is on top of an overlay widget. */ MouseTargetType[MouseTargetType["OVERLAY_WIDGET"] = 12] = "OVERLAY_WIDGET"; /** * Mouse is outside of the editor. */ MouseTargetType[MouseTargetType["OUTSIDE_EDITOR"] = 13] = "OUTSIDE_EDITOR"; })(MouseTargetType = exports.MouseTargetType || (exports.MouseTargetType = {})); /** * A positioning preference for rendering overlay widgets. */ var OverlayWidgetPositionPreference; (function (OverlayWidgetPositionPreference) { /** * Position the overlay widget in the top right corner */ OverlayWidgetPositionPreference[OverlayWidgetPositionPreference["TOP_RIGHT_CORNER"] = 0] = "TOP_RIGHT_CORNER"; /** * Position the overlay widget in the bottom right corner */ OverlayWidgetPositionPreference[OverlayWidgetPositionPreference["BOTTOM_RIGHT_CORNER"] = 1] = "BOTTOM_RIGHT_CORNER"; /** * Position the overlay widget in the top center */ OverlayWidgetPositionPreference[OverlayWidgetPositionPreference["TOP_CENTER"] = 2] = "TOP_CENTER"; })(OverlayWidgetPositionPreference = exports.OverlayWidgetPositionPreference || (exports.OverlayWidgetPositionPreference = {})); /** * Vertical Lane in the overview ruler of the editor. */ var OverviewRulerLane; (function (OverviewRulerLane) { OverviewRulerLane[OverviewRulerLane["Left"] = 1] = "Left"; OverviewRulerLane[OverviewRulerLane["Center"] = 2] = "Center"; OverviewRulerLane[OverviewRulerLane["Right"] = 4] = "Right"; OverviewRulerLane[OverviewRulerLane["Full"] = 7] = "Full"; })(OverviewRulerLane = exports.OverviewRulerLane || (exports.OverviewRulerLane = {})); var RenderLineNumbersType; (function (RenderLineNumbersType) { RenderLineNumbersType[RenderLineNumbersType["Off"] = 0] = "Off"; RenderLineNumbersType[RenderLineNumbersType["On"] = 1] = "On"; RenderLineNumbersType[RenderLineNumbersType["Relative"] = 2] = "Relative"; RenderLineNumbersType[RenderLineNumbersType["Interval"] = 3] = "Interval"; RenderLineNumbersType[RenderLineNumbersType["Custom"] = 4] = "Custom"; })(RenderLineNumbersType = exports.RenderLineNumbersType || (exports.RenderLineNumbersType = {})); var RenderMinimap; (function (RenderMinimap) { RenderMinimap[RenderMinimap["None"] = 0] = "None"; RenderMinimap[RenderMinimap["Text"] = 1] = "Text"; RenderMinimap[RenderMinimap["Blocks"] = 2] = "Blocks"; })(RenderMinimap = exports.RenderMinimap || (exports.RenderMinimap = {})); var ScrollType; (function (ScrollType) { ScrollType[ScrollType["Smooth"] = 0] = "Smooth"; ScrollType[ScrollType["Immediate"] = 1] = "Immediate"; })(ScrollType = exports.ScrollType || (exports.ScrollType = {})); var ScrollbarVisibility; (function (ScrollbarVisibility) { ScrollbarVisibility[ScrollbarVisibility["Auto"] = 1] = "Auto"; ScrollbarVisibility[ScrollbarVisibility["Hidden"] = 2] = "Hidden"; ScrollbarVisibility[ScrollbarVisibility["Visible"] = 3] = "Visible"; })(ScrollbarVisibility = exports.ScrollbarVisibility || (exports.ScrollbarVisibility = {})); /** * The direction of a selection. */ var SelectionDirection; (function (SelectionDirection) { /** * The selection starts above where it ends. */ SelectionDirection[SelectionDirection["LTR"] = 0] = "LTR"; /** * The selection starts below where it ends. */ SelectionDirection[SelectionDirection["RTL"] = 1] = "RTL"; })(SelectionDirection = exports.SelectionDirection || (exports.SelectionDirection = {})); var SignatureHelpTriggerKind; (function (SignatureHelpTriggerKind) { SignatureHelpTriggerKind[SignatureHelpTriggerKind["Invoke"] = 1] = "Invoke"; SignatureHelpTriggerKind[SignatureHelpTriggerKind["TriggerCharacter"] = 2] = "TriggerCharacter"; SignatureHelpTriggerKind[SignatureHelpTriggerKind["ContentChange"] = 3] = "ContentChange"; })(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {})); /** * A symbol kind. */ var SymbolKind; (function (SymbolKind) { SymbolKind[SymbolKind["File"] = 0] = "File"; SymbolKind[SymbolKind["Module"] = 1] = "Module"; SymbolKind[SymbolKind["Namespace"] = 2] = "Namespace"; SymbolKind[SymbolKind["Package"] = 3] = "Package"; SymbolKind[SymbolKind["Class"] = 4] = "Class"; SymbolKind[SymbolKind["Method"] = 5] = "Method"; SymbolKind[SymbolKind["Property"] = 6] = "Property"; SymbolKind[SymbolKind["Field"] = 7] = "Field"; SymbolKind[SymbolKind["Constructor"] = 8] = "Constructor"; SymbolKind[SymbolKind["Enum"] = 9] = "Enum"; SymbolKind[SymbolKind["Interface"] = 10] = "Interface"; SymbolKind[SymbolKind["Function"] = 11] = "Function"; SymbolKind[SymbolKind["Variable"] = 12] = "Variable"; SymbolKind[SymbolKind["Constant"] = 13] = "Constant"; SymbolKind[SymbolKind["String"] = 14] = "String"; SymbolKind[SymbolKind["Number"] = 15] = "Number"; SymbolKind[SymbolKind["Boolean"] = 16] = "Boolean"; SymbolKind[SymbolKind["Array"] = 17] = "Array"; SymbolKind[SymbolKind["Object"] = 18] = "Object"; SymbolKind[SymbolKind["Key"] = 19] = "Key"; SymbolKind[SymbolKind["Null"] = 20] = "Null"; SymbolKind[SymbolKind["EnumMember"] = 21] = "EnumMember"; SymbolKind[SymbolKind["Struct"] = 22] = "Struct"; SymbolKind[SymbolKind["Event"] = 23] = "Event"; SymbolKind[SymbolKind["Operator"] = 24] = "Operator"; SymbolKind[SymbolKind["TypeParameter"] = 25] = "TypeParameter"; })(SymbolKind = exports.SymbolKind || (exports.SymbolKind = {})); var SymbolTag; (function (SymbolTag) { SymbolTag[SymbolTag["Deprecated"] = 1] = "Deprecated"; })(SymbolTag = exports.SymbolTag || (exports.SymbolTag = {})); /** * The kind of animation in which the editor's cursor should be rendered. */ var TextEditorCursorBlinkingStyle; (function (TextEditorCursorBlinkingStyle) { /** * Hidden */ TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Hidden"] = 0] = "Hidden"; /** * Blinking */ TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Blink"] = 1] = "Blink"; /** * Blinking with smooth fading */ TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Smooth"] = 2] = "Smooth"; /** * Blinking with prolonged filled state and smooth fading */ TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Phase"] = 3] = "Phase"; /** * Expand collapse animation on the y axis */ TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Expand"] = 4] = "Expand"; /** * No-Blinking */ TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Solid"] = 5] = "Solid"; })(TextEditorCursorBlinkingStyle = exports.TextEditorCursorBlinkingStyle || (exports.TextEditorCursorBlinkingStyle = {})); /** * The style in which the editor's cursor should be rendered. */ var TextEditorCursorStyle; (function (TextEditorCursorStyle) { /** * As a vertical line (sitting between two characters). */ TextEditorCursorStyle[TextEditorCursorStyle["Line"] = 1] = "Line"; /** * As a block (sitting on top of a character). */ TextEditorCursorStyle[TextEditorCursorStyle["Block"] = 2] = "Block"; /** * As a horizontal line (sitting under a character). */ TextEditorCursorStyle[TextEditorCursorStyle["Underline"] = 3] = "Underline"; /** * As a thin vertical line (sitting between two characters). */ TextEditorCursorStyle[TextEditorCursorStyle["LineThin"] = 4] = "LineThin"; /** * As an outlined block (sitting on top of a character). */ TextEditorCursorStyle[TextEditorCursorStyle["BlockOutline"] = 5] = "BlockOutline"; /** * As a thin horizontal line (sitting under a character). */ TextEditorCursorStyle[TextEditorCursorStyle["UnderlineThin"] = 6] = "UnderlineThin"; })(TextEditorCursorStyle = exports.TextEditorCursorStyle || (exports.TextEditorCursorStyle = {})); /** * Describes the behavior of decorations when typing/editing near their edges. * Note: Please do not edit the values, as they very carefully match `DecorationRangeBehavior` */ var TrackedRangeStickiness; (function (TrackedRangeStickiness) { TrackedRangeStickiness[TrackedRangeStickiness["AlwaysGrowsWhenTypingAtEdges"] = 0] = "AlwaysGrowsWhenTypingAtEdges"; TrackedRangeStickiness[TrackedRangeStickiness["NeverGrowsWhenTypingAtEdges"] = 1] = "NeverGrowsWhenTypingAtEdges"; TrackedRangeStickiness[TrackedRangeStickiness["GrowsOnlyWhenTypingBefore"] = 2] = "GrowsOnlyWhenTypingBefore"; TrackedRangeStickiness[TrackedRangeStickiness["GrowsOnlyWhenTypingAfter"] = 3] = "GrowsOnlyWhenTypingAfter"; })(TrackedRangeStickiness = exports.TrackedRangeStickiness || (exports.TrackedRangeStickiness = {})); /** * Describes how to indent wrapped lines. */ var WrappingIndent; (function (WrappingIndent) { /** * No indentation => wrapped lines begin at column 1. */ WrappingIndent[WrappingIndent["None"] = 0] = "None"; /** * Same => wrapped lines get the same indentation as the parent. */ WrappingIndent[WrappingIndent["Same"] = 1] = "Same"; /** * Indent => wrapped lines get +1 indentation toward the parent. */ WrappingIndent[WrappingIndent["Indent"] = 2] = "Indent"; /** * DeepIndent => wrapped lines get +2 indentation toward the parent. */ WrappingIndent[WrappingIndent["DeepIndent"] = 3] = "DeepIndent"; })(WrappingIndent = exports.WrappingIndent || (exports.WrappingIndent = {})); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[192/*vs/editor/common/standalone/standaloneBase*/], __M([0/*require*/,1/*exports*/,26/*vs/base/common/cancellation*/,4/*vs/base/common/event*/,36/*vs/base/common/keyCodes*/,25/*vs/base/common/uri*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,107/*vs/editor/common/core/token*/,147/*vs/editor/common/standalone/standaloneEnums*/,614/*vs/editor/common/standalone/promise-polyfill/polyfill*/]), function (require, exports, cancellation_1, event_1, keyCodes_1, uri_1, position_1, range_1, selection_1, token_1, standaloneEnums) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var KeyMod = /** @class */ (function () { function KeyMod() { } KeyMod.chord = function (firstPart, secondPart) { return keyCodes_1.KeyChord(firstPart, secondPart); }; KeyMod.CtrlCmd = 2048 /* CtrlCmd */; KeyMod.Shift = 1024 /* Shift */; KeyMod.Alt = 512 /* Alt */; KeyMod.WinCtrl = 256 /* WinCtrl */; return KeyMod; }()); exports.KeyMod = KeyMod; function createMonacoBaseAPI() { return { editor: undefined, languages: undefined, CancellationTokenSource: cancellation_1.CancellationTokenSource, Emitter: event_1.Emitter, KeyCode: standaloneEnums.KeyCode, KeyMod: KeyMod, Position: position_1.Position, Range: range_1.Range, Selection: selection_1.Selection, SelectionDirection: standaloneEnums.SelectionDirection, MarkerSeverity: standaloneEnums.MarkerSeverity, MarkerTag: standaloneEnums.MarkerTag, Uri: uri_1.URI, Token: token_1.Token }; } exports.createMonacoBaseAPI = createMonacoBaseAPI; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[193/*vs/editor/common/view/overviewZoneManager*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ColorZone = /** @class */ (function () { function ColorZone(from, to, colorId) { this.from = from | 0; this.to = to | 0; this.colorId = colorId | 0; } ColorZone.compare = function (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; }; return ColorZone; }()); exports.ColorZone = ColorZone; /** * A zone in the overview ruler */ var OverviewRulerZone = /** @class */ (function () { function OverviewRulerZone(startLineNumber, endLineNumber, color) { this.startLineNumber = startLineNumber; this.endLineNumber = endLineNumber; this.color = color; this._colorZone = null; } OverviewRulerZone.compare = function (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; }; OverviewRulerZone.prototype.setColorZone = function (colorZone) { this._colorZone = colorZone; }; OverviewRulerZone.prototype.getColorZones = function () { return this._colorZone; }; return OverviewRulerZone; }()); exports.OverviewRulerZone = OverviewRulerZone; var OverviewZoneManager = /** @class */ (function () { function OverviewZoneManager(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 = []; } OverviewZoneManager.prototype.getId2Color = function () { return this._id2Color; }; OverviewZoneManager.prototype.setZones = function (newZones) { this._zones = newZones; this._zones.sort(OverviewRulerZone.compare); }; OverviewZoneManager.prototype.setLineHeight = function (lineHeight) { if (this._lineHeight === lineHeight) { return false; } this._lineHeight = lineHeight; this._colorZonesInvalid = true; return true; }; OverviewZoneManager.prototype.setPixelRatio = function (pixelRatio) { this._pixelRatio = pixelRatio; this._colorZonesInvalid = true; }; OverviewZoneManager.prototype.getDOMWidth = function () { return this._domWidth; }; OverviewZoneManager.prototype.getCanvasWidth = function () { return this._domWidth * this._pixelRatio; }; OverviewZoneManager.prototype.setDOMWidth = function (width) { if (this._domWidth === width) { return false; } this._domWidth = width; this._colorZonesInvalid = true; return true; }; OverviewZoneManager.prototype.getDOMHeight = function () { return this._domHeight; }; OverviewZoneManager.prototype.getCanvasHeight = function () { return this._domHeight * this._pixelRatio; }; OverviewZoneManager.prototype.setDOMHeight = function (height) { if (this._domHeight === height) { return false; } this._domHeight = height; this._colorZonesInvalid = true; return true; }; OverviewZoneManager.prototype.getOuterHeight = function () { return this._outerHeight; }; OverviewZoneManager.prototype.setOuterHeight = function (outerHeight) { if (this._outerHeight === outerHeight) { return false; } this._outerHeight = outerHeight; this._colorZonesInvalid = true; return true; }; OverviewZoneManager.prototype.resolveColorZones = function () { var colorZonesInvalid = this._colorZonesInvalid; var lineHeight = Math.floor(this._lineHeight); // @perf var totalHeight = Math.floor(this.getCanvasHeight()); // @perf var outerHeight = Math.floor(this._outerHeight); // @perf var heightRatio = totalHeight / outerHeight; var halfMinimumHeight = Math.floor(4 /* MINIMUM_HEIGHT */ * this._pixelRatio / 2); var allColorZones = []; for (var i = 0, len = this._zones.length; i < len; i++) { var zone = this._zones[i]; if (!colorZonesInvalid) { var colorZone_1 = zone.getColorZones(); if (colorZone_1) { allColorZones.push(colorZone_1); continue; } } var y1 = Math.floor(heightRatio * (this._getVerticalOffsetForLine(zone.startLineNumber))); var y2 = Math.floor(heightRatio * (this._getVerticalOffsetForLine(zone.endLineNumber) + lineHeight)); var ycenter = Math.floor((y1 + y2) / 2); var halfHeight = (y2 - ycenter); if (halfHeight < halfMinimumHeight) { halfHeight = halfMinimumHeight; } if (ycenter - halfHeight < 0) { ycenter = halfHeight; } if (ycenter + halfHeight > totalHeight) { ycenter = totalHeight - halfHeight; } var color = zone.color; var colorId = this._color2Id[color]; if (!colorId) { colorId = (++this._lastAssignedId); this._color2Id[color] = colorId; this._id2Color[colorId] = color; } var colorZone = new ColorZone(ycenter - halfHeight, ycenter + halfHeight, colorId); zone.setColorZone(colorZone); allColorZones.push(colorZone); } this._colorZonesInvalid = false; allColorZones.sort(ColorZone.compare); return allColorZones; }; return OverviewZoneManager; }()); 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[91/*vs/editor/common/view/renderingContext*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var RestrictedRenderingContext = /** @class */ (function () { function RestrictedRenderingContext(viewLayout, viewportData) { 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; var vInfo = this._viewLayout.getCurrentViewport(); this.scrollTop = vInfo.top; this.scrollLeft = vInfo.left; this.viewportWidth = vInfo.width; this.viewportHeight = vInfo.height; } RestrictedRenderingContext.prototype.getScrolledTopFromAbsoluteTop = function (absoluteTop) { return absoluteTop - this.scrollTop; }; RestrictedRenderingContext.prototype.getVerticalOffsetForLineNumber = function (lineNumber) { return this._viewLayout.getVerticalOffsetForLineNumber(lineNumber); }; RestrictedRenderingContext.prototype.getDecorationsInViewport = function () { return this.viewportData.getDecorationsInViewport(); }; return RestrictedRenderingContext; }()); exports.RestrictedRenderingContext = RestrictedRenderingContext; var RenderingContext = /** @class */ (function (_super) { __extends(RenderingContext, _super); function RenderingContext(viewLayout, viewportData, viewLines) { var _this = _super.call(this, viewLayout, viewportData) || this; _this._viewLines = viewLines; return _this; } RenderingContext.prototype.linesVisibleRangesForRange = function (range, includeNewLines) { return this._viewLines.linesVisibleRangesForRange(range, includeNewLines); }; RenderingContext.prototype.visibleRangeForPosition = function (position) { return this._viewLines.visibleRangeForPosition(position); }; return RenderingContext; }(RestrictedRenderingContext)); exports.RenderingContext = RenderingContext; var LineVisibleRanges = /** @class */ (function () { function LineVisibleRanges(outsideRenderedLine, lineNumber, ranges) { this.outsideRenderedLine = outsideRenderedLine; this.lineNumber = lineNumber; this.ranges = ranges; } return LineVisibleRanges; }()); exports.LineVisibleRanges = LineVisibleRanges; var HorizontalRange = /** @class */ (function () { function HorizontalRange(left, width) { this.left = Math.round(left); this.width = Math.round(width); } HorizontalRange.prototype.toString = function () { return "[" + this.left + "," + this.width + "]"; }; return HorizontalRange; }()); exports.HorizontalRange = HorizontalRange; var HorizontalPosition = /** @class */ (function () { function HorizontalPosition(outsideRenderedLine, left) { this.outsideRenderedLine = outsideRenderedLine; this.left = Math.round(left); } return HorizontalPosition; }()); exports.HorizontalPosition = HorizontalPosition; var VisibleRanges = /** @class */ (function () { function VisibleRanges(outsideRenderedLine, ranges) { this.outsideRenderedLine = outsideRenderedLine; this.ranges = ranges; } return VisibleRanges; }()); 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[359/*vs/editor/browser/viewParts/lines/rangeUtil*/], __M([0/*require*/,1/*exports*/,91/*vs/editor/common/view/renderingContext*/]), function (require, exports, renderingContext_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var FloatHorizontalRange = /** @class */ (function () { function FloatHorizontalRange(left, width) { this.left = left; this.width = width; } FloatHorizontalRange.prototype.toString = function () { return "[" + this.left + "," + this.width + "]"; }; FloatHorizontalRange.compare = function (a, b) { return a.left - b.left; }; return FloatHorizontalRange; }()); var RangeUtil = /** @class */ (function () { function RangeUtil() { } RangeUtil._createRange = function () { if (!this._handyReadyRange) { this._handyReadyRange = document.createRange(); } return this._handyReadyRange; }; RangeUtil._detachRange = function (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); }; RangeUtil._readClientRects = function (startElement, startOffset, endElement, endOffset, endNode) { var 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); } }; RangeUtil._mergeAdjacentRanges = function (ranges) { if (ranges.length === 1) { // There is nothing to merge return [new renderingContext_1.HorizontalRange(ranges[0].left, ranges[0].width)]; } ranges.sort(FloatHorizontalRange.compare); var result = [], resultLen = 0; var prevLeft = ranges[0].left; var prevWidth = ranges[0].width; for (var i = 1, len = ranges.length; i < len; i++) { var range = ranges[i]; var myLeft = range.left; var myWidth = range.width; if (prevLeft + prevWidth + 0.9 /* account for browser's rounding errors*/ >= myLeft) { prevWidth = Math.max(prevWidth, myLeft + myWidth - prevLeft); } else { result[resultLen++] = new renderingContext_1.HorizontalRange(prevLeft, prevWidth); prevLeft = myLeft; prevWidth = myWidth; } } result[resultLen++] = new renderingContext_1.HorizontalRange(prevLeft, prevWidth); return result; }; RangeUtil._createHorizontalRangesFromClientRects = function (clientRects, clientRectDeltaLeft) { if (!clientRects || clientRects.length === 0) { return null; } // We go through FloatHorizontalRange because it has been observed in bi-di text // that the clientRects are not coming in sorted from the browser var result = []; for (var i = 0, len = clientRects.length; i < len; i++) { var clientRect = clientRects[i]; result[i] = new FloatHorizontalRange(Math.max(0, clientRect.left - clientRectDeltaLeft), clientRect.width); } return this._mergeAdjacentRanges(result); }; RangeUtil.readHorizontalRanges = function (domNode, startChildIndex, startOffset, endChildIndex, endOffset, clientRectDeltaLeft, endNode) { // Panic check var min = 0; var 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 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 */; } } var startElement = domNode.children[startChildIndex].firstChild; var 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)); var clientRects = this._readClientRects(startElement, startOffset, endElement, endOffset, endNode); return this._createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft); }; return RangeUtil; }()); 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[360/*vs/editor/common/view/viewContext*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ViewContext = /** @class */ (function () { function ViewContext(configuration, theme, model, privateViewEventBus) { this.configuration = configuration; this.theme = theme; this.model = model; this.viewLayout = model.viewLayout; this.privateViewEventBus = privateViewEventBus; } ViewContext.prototype.addEventHandler = function (eventHandler) { this.privateViewEventBus.addEventHandler(eventHandler); }; ViewContext.prototype.removeEventHandler = function (eventHandler) { this.privateViewEventBus.removeEventHandler(eventHandler); }; return ViewContext; }()); 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[361/*vs/editor/common/view/viewEventDispatcher*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ViewEventDispatcher = /** @class */ (function () { function ViewEventDispatcher(eventHandlerGateKeeper) { this._eventHandlerGateKeeper = eventHandlerGateKeeper; this._eventHandlers = []; this._eventQueue = null; this._isConsumingQueue = false; } ViewEventDispatcher.prototype.addEventHandler = function (eventHandler) { for (var 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); }; ViewEventDispatcher.prototype.removeEventHandler = function (eventHandler) { for (var i = 0; i < this._eventHandlers.length; i++) { if (this._eventHandlers[i] === eventHandler) { this._eventHandlers.splice(i, 1); break; } } }; ViewEventDispatcher.prototype.emit = function (event) { if (this._eventQueue) { this._eventQueue.push(event); } else { this._eventQueue = [event]; } if (!this._isConsumingQueue) { this.consumeQueue(); } }; ViewEventDispatcher.prototype.emitMany = function (events) { if (this._eventQueue) { this._eventQueue = this._eventQueue.concat(events); } else { this._eventQueue = events; } if (!this._isConsumingQueue) { this.consumeQueue(); } }; ViewEventDispatcher.prototype.consumeQueue = function () { var _this = this; this._eventHandlerGateKeeper(function () { try { _this._isConsumingQueue = true; _this._doConsumeQueue(); } finally { _this._isConsumingQueue = false; } }); }; ViewEventDispatcher.prototype._doConsumeQueue = function () { while (this._eventQueue) { // Empty event queue, as events might come in while sending these off var events = this._eventQueue; this._eventQueue = null; // Use a clone of the event handlers list, as they might remove themselves var eventHandlers = this._eventHandlers.slice(0); for (var i = 0, len = eventHandlers.length; i < len; i++) { eventHandlers[i].handleEvents(events); } } }; return ViewEventDispatcher; }()); exports.ViewEventDispatcher = ViewEventDispatcher; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[81/*vs/editor/common/view/viewEvents*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/]), function (require, exports, errors, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ViewConfigurationChangedEvent = /** @class */ (function () { function ViewConfigurationChangedEvent(source) { this.type = 1 /* ViewConfigurationChanged */; this._source = source; } ViewConfigurationChangedEvent.prototype.hasChanged = function (id) { return this._source.hasChanged(id); }; return ViewConfigurationChangedEvent; }()); exports.ViewConfigurationChangedEvent = ViewConfigurationChangedEvent; var ViewContentSizeChangedEvent = /** @class */ (function () { function ViewContentSizeChangedEvent(source) { this.type = 2 /* ViewContentSizeChanged */; this.contentWidth = source.contentWidth; this.contentHeight = source.contentHeight; this.contentWidthChanged = source.contentWidthChanged; this.contentHeightChanged = source.contentHeightChanged; } return ViewContentSizeChangedEvent; }()); exports.ViewContentSizeChangedEvent = ViewContentSizeChangedEvent; var ViewCursorStateChangedEvent = /** @class */ (function () { function ViewCursorStateChangedEvent(selections, modelSelections) { this.type = 3 /* ViewCursorStateChanged */; this.selections = selections; this.modelSelections = modelSelections; } return ViewCursorStateChangedEvent; }()); exports.ViewCursorStateChangedEvent = ViewCursorStateChangedEvent; var ViewDecorationsChangedEvent = /** @class */ (function () { function ViewDecorationsChangedEvent() { this.type = 4 /* ViewDecorationsChanged */; // Nothing to do } return ViewDecorationsChangedEvent; }()); exports.ViewDecorationsChangedEvent = ViewDecorationsChangedEvent; var ViewFlushedEvent = /** @class */ (function () { function ViewFlushedEvent() { this.type = 5 /* ViewFlushed */; // Nothing to do } return ViewFlushedEvent; }()); exports.ViewFlushedEvent = ViewFlushedEvent; var ViewFocusChangedEvent = /** @class */ (function () { function ViewFocusChangedEvent(isFocused) { this.type = 6 /* ViewFocusChanged */; this.isFocused = isFocused; } return ViewFocusChangedEvent; }()); exports.ViewFocusChangedEvent = ViewFocusChangedEvent; var ViewLanguageConfigurationEvent = /** @class */ (function () { function ViewLanguageConfigurationEvent() { this.type = 7 /* ViewLanguageConfigurationChanged */; } return ViewLanguageConfigurationEvent; }()); exports.ViewLanguageConfigurationEvent = ViewLanguageConfigurationEvent; var ViewLineMappingChangedEvent = /** @class */ (function () { function ViewLineMappingChangedEvent() { this.type = 8 /* ViewLineMappingChanged */; // Nothing to do } return ViewLineMappingChangedEvent; }()); exports.ViewLineMappingChangedEvent = ViewLineMappingChangedEvent; var ViewLinesChangedEvent = /** @class */ (function () { function ViewLinesChangedEvent(fromLineNumber, toLineNumber) { this.type = 9 /* ViewLinesChanged */; this.fromLineNumber = fromLineNumber; this.toLineNumber = toLineNumber; } return ViewLinesChangedEvent; }()); exports.ViewLinesChangedEvent = ViewLinesChangedEvent; var ViewLinesDeletedEvent = /** @class */ (function () { function ViewLinesDeletedEvent(fromLineNumber, toLineNumber) { this.type = 10 /* ViewLinesDeleted */; this.fromLineNumber = fromLineNumber; this.toLineNumber = toLineNumber; } return ViewLinesDeletedEvent; }()); exports.ViewLinesDeletedEvent = ViewLinesDeletedEvent; var ViewLinesInsertedEvent = /** @class */ (function () { function ViewLinesInsertedEvent(fromLineNumber, toLineNumber) { this.type = 11 /* ViewLinesInserted */; this.fromLineNumber = fromLineNumber; this.toLineNumber = toLineNumber; } return ViewLinesInsertedEvent; }()); exports.ViewLinesInsertedEvent = ViewLinesInsertedEvent; var ViewRevealRangeRequestEvent = /** @class */ (function () { function ViewRevealRangeRequestEvent(source, range, verticalType, revealHorizontal, scrollType) { this.type = 12 /* ViewRevealRangeRequest */; this.source = source; this.range = range; this.verticalType = verticalType; this.revealHorizontal = revealHorizontal; this.scrollType = scrollType; } return ViewRevealRangeRequestEvent; }()); exports.ViewRevealRangeRequestEvent = ViewRevealRangeRequestEvent; var ViewScrollChangedEvent = /** @class */ (function () { function ViewScrollChangedEvent(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; } return ViewScrollChangedEvent; }()); exports.ViewScrollChangedEvent = ViewScrollChangedEvent; var ViewThemeChangedEvent = /** @class */ (function () { function ViewThemeChangedEvent() { this.type = 14 /* ViewThemeChanged */; } return ViewThemeChangedEvent; }()); exports.ViewThemeChangedEvent = ViewThemeChangedEvent; var ViewTokensChangedEvent = /** @class */ (function () { function ViewTokensChangedEvent(ranges) { this.type = 15 /* ViewTokensChanged */; this.ranges = ranges; } return ViewTokensChangedEvent; }()); exports.ViewTokensChangedEvent = ViewTokensChangedEvent; var ViewTokensColorsChangedEvent = /** @class */ (function () { function ViewTokensColorsChangedEvent() { this.type = 16 /* ViewTokensColorsChanged */; // Nothing to do } return ViewTokensColorsChangedEvent; }()); exports.ViewTokensColorsChangedEvent = ViewTokensColorsChangedEvent; var ViewZonesChangedEvent = /** @class */ (function () { function ViewZonesChangedEvent() { this.type = 17 /* ViewZonesChanged */; // Nothing to do } return ViewZonesChangedEvent; }()); exports.ViewZonesChangedEvent = ViewZonesChangedEvent; var ViewEventEmitter = /** @class */ (function (_super) { __extends(ViewEventEmitter, _super); function ViewEventEmitter() { var _this = _super.call(this) || this; _this._listeners = []; _this._collector = null; _this._collectorCnt = 0; return _this; } ViewEventEmitter.prototype.dispose = function () { this._listeners = []; _super.prototype.dispose.call(this); }; ViewEventEmitter.prototype._beginEmit = function () { this._collectorCnt++; if (this._collectorCnt === 1) { this._collector = new ViewEventsCollector(); } return this._collector; }; ViewEventEmitter.prototype._endEmit = function () { this._collectorCnt--; if (this._collectorCnt === 0) { var events = this._collector.finalize(); this._collector = null; if (events.length > 0) { this._emit(events); } } }; ViewEventEmitter.prototype._emit = function (events) { var listeners = this._listeners.slice(0); for (var i = 0, len = listeners.length; i < len; i++) { safeInvokeListener(listeners[i], events); } }; ViewEventEmitter.prototype.addEventListener = function (listener) { var _this = this; this._listeners.push(listener); return lifecycle_1.toDisposable(function () { var listeners = _this._listeners; for (var i = 0, len = listeners.length; i < len; i++) { if (listeners[i] === listener) { listeners.splice(i, 1); break; } } }); }; return ViewEventEmitter; }(lifecycle_1.Disposable)); exports.ViewEventEmitter = ViewEventEmitter; var ViewEventsCollector = /** @class */ (function () { function ViewEventsCollector() { this._eventsLen = 0; this._events = []; this._eventsLen = 0; } ViewEventsCollector.prototype.emit = function (event) { this._events[this._eventsLen++] = event; }; ViewEventsCollector.prototype.finalize = function () { var result = this._events; this._events = []; return result; }; return ViewEventsCollector; }()); exports.ViewEventsCollector = ViewEventsCollector; function safeInvokeListener(listener, events) { try { listener(events); } catch (e) { errors.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[148/*vs/editor/common/viewLayout/lineDecorations*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/]), function (require, exports, strings) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LineDecoration = /** @class */ (function () { function LineDecoration(startColumn, endColumn, className, type) { this.startColumn = startColumn; this.endColumn = endColumn; this.className = className; this.type = type; } LineDecoration._equals = function (a, b) { return (a.startColumn === b.startColumn && a.endColumn === b.endColumn && a.className === b.className && a.type === b.type); }; LineDecoration.equalsArr = function (a, b) { var aLen = a.length; var bLen = b.length; if (aLen !== bLen) { return false; } for (var i = 0; i < aLen; i++) { if (!LineDecoration._equals(a[i], b[i])) { return false; } } return true; }; LineDecoration.filter = function (lineDecorations, lineNumber, minLineColumn, maxLineColumn) { if (lineDecorations.length === 0) { return []; } var result = [], resultLen = 0; for (var i = 0, len = lineDecorations.length; i < len; i++) { var d = lineDecorations[i]; var 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; } var startColumn = (range.startLineNumber === lineNumber ? range.startColumn : minLineColumn); var endColumn = (range.endLineNumber === lineNumber ? range.endColumn : maxLineColumn); result[resultLen++] = new LineDecoration(startColumn, endColumn, d.inlineClassName, d.type); } return result; }; LineDecoration.compare = function (a, b) { if (a.startColumn === b.startColumn) { if (a.endColumn === b.endColumn) { if (a.className < b.className) { return -1; } if (a.className > b.className) { return 1; } return 0; } return a.endColumn - b.endColumn; } return a.startColumn - b.startColumn; }; return LineDecoration; }()); exports.LineDecoration = LineDecoration; var DecorationSegment = /** @class */ (function () { function DecorationSegment(startOffset, endOffset, className) { this.startOffset = startOffset; this.endOffset = endOffset; this.className = className; } return DecorationSegment; }()); exports.DecorationSegment = DecorationSegment; var Stack = /** @class */ (function () { function Stack() { this.stopOffsets = []; this.classNames = []; this.count = 0; } Stack.prototype.consumeLowerThan = function (maxStopOffset, nextStartOffset, result) { while (this.count > 0 && this.stopOffsets[0] < maxStopOffset) { var 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(' '))); nextStartOffset = this.stopOffsets[i] + 1; // Consume them this.stopOffsets.splice(0, i + 1); this.classNames.splice(0, i + 1); this.count -= (i + 1); } if (this.count > 0 && nextStartOffset < maxStopOffset) { result.push(new DecorationSegment(nextStartOffset, maxStopOffset - 1, this.classNames.join(' '))); nextStartOffset = maxStopOffset; } return nextStartOffset; }; Stack.prototype.insert = function (stopOffset, className) { if (this.count === 0 || this.stopOffsets[this.count - 1] <= stopOffset) { // Insert at the end this.stopOffsets.push(stopOffset); this.classNames.push(className); } else { // Find the insertion position for `stopOffset` for (var i = 0; i < this.count; i++) { if (this.stopOffsets[i] >= stopOffset) { this.stopOffsets.splice(i, 0, stopOffset); this.classNames.splice(i, 0, className); break; } } } this.count++; return; }; return Stack; }()); var LineDecorationsNormalizer = /** @class */ (function () { function LineDecorationsNormalizer() { } /** * Normalize line decorations. Overlapping decorations will generate multiple segments */ LineDecorationsNormalizer.normalize = function (lineContent, lineDecorations) { if (lineDecorations.length === 0) { return []; } var result = []; var stack = new Stack(); var nextStartOffset = 0; for (var i = 0, len = lineDecorations.length; i < len; i++) { var d = lineDecorations[i]; var startColumn = d.startColumn; var endColumn = d.endColumn; var className = d.className; // 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) { var charCodeBefore = lineContent.charCodeAt(startColumn - 2); if (strings.isHighSurrogate(charCodeBefore)) { startColumn--; } } if (endColumn > 1) { var charCodeBefore = lineContent.charCodeAt(endColumn - 2); if (strings.isHighSurrogate(charCodeBefore)) { endColumn--; } } var currentStartOffset = startColumn - 1; var currentEndOffset = endColumn - 2; nextStartOffset = stack.consumeLowerThan(currentStartOffset, nextStartOffset, result); if (stack.count === 0) { nextStartOffset = currentStartOffset; } stack.insert(currentEndOffset, className); } stack.consumeLowerThan(1073741824 /* MAX_SAFE_SMALL_INTEGER */, nextStartOffset, result); return result; }; return LineDecorationsNormalizer; }()); 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[362/*vs/editor/common/viewLayout/linesLayout*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/]), function (require, exports, strings) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var PendingChanges = /** @class */ (function () { function PendingChanges() { this._hasPending = false; this._inserts = []; this._changes = []; this._removes = []; } PendingChanges.prototype.insert = function (x) { this._hasPending = true; this._inserts.push(x); }; PendingChanges.prototype.change = function (x) { this._hasPending = true; this._changes.push(x); }; PendingChanges.prototype.remove = function (x) { this._hasPending = true; this._removes.push(x); }; PendingChanges.prototype.mustCommit = function () { return this._hasPending; }; PendingChanges.prototype.commit = function (linesLayout) { if (!this._hasPending) { return; } var inserts = this._inserts; var changes = this._changes; var removes = this._removes; this._hasPending = false; this._inserts = []; this._changes = []; this._removes = []; linesLayout._commitPendingChanges(inserts, changes, removes); }; return PendingChanges; }()); var EditorWhitespace = /** @class */ (function () { function EditorWhitespace(id, afterLineNumber, ordinal, height, minWidth) { this.id = id; this.afterLineNumber = afterLineNumber; this.ordinal = ordinal; this.height = height; this.minWidth = minWidth; this.prefixSum = 0; } return EditorWhitespace; }()); 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). */ var LinesLayout = /** @class */ (function () { function LinesLayout(lineCount, lineHeight) { 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; } /** * 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. */ LinesLayout.findInsertionIndex = function (arr, afterLineNumber, ordinal) { var low = 0; var high = arr.length; while (low < high) { var 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. */ LinesLayout.prototype.setLineHeight = function (lineHeight) { this._checkPendingChanges(); this._lineHeight = lineHeight; }; /** * Set the number of lines. * * @param lineCount New number of lines. */ LinesLayout.prototype.onFlushed = function (lineCount) { this._checkPendingChanges(); this._lineCount = lineCount; }; LinesLayout.prototype.changeWhitespace = function (callback) { var _this = this; try { var accessor = { insertWhitespace: function (afterLineNumber, ordinal, heightInPx, minWidth) { afterLineNumber = afterLineNumber | 0; ordinal = ordinal | 0; heightInPx = heightInPx | 0; minWidth = minWidth | 0; var id = _this._instanceId + (++_this._lastWhitespaceId); _this._pendingChanges.insert(new EditorWhitespace(id, afterLineNumber, ordinal, heightInPx, minWidth)); return id; }, changeOneWhitespace: function (id, newAfterLineNumber, newHeight) { newAfterLineNumber = newAfterLineNumber | 0; newHeight = newHeight | 0; _this._pendingChanges.change({ id: id, newAfterLineNumber: newAfterLineNumber, newHeight: newHeight }); }, removeWhitespace: function (id) { _this._pendingChanges.remove({ id: id }); } }; return callback(accessor); } finally { this._pendingChanges.commit(this); } }; LinesLayout.prototype._commitPendingChanges = function (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 (var _i = 0, inserts_1 = inserts; _i < inserts_1.length; _i++) { var insert = inserts_1[_i]; this._insertWhitespace(insert); } for (var _a = 0, changes_1 = changes; _a < changes_1.length; _a++) { var change = changes_1[_a]; this._changeOneWhitespace(change.id, change.newAfterLineNumber, change.newHeight); } for (var _b = 0, removes_1 = removes; _b < removes_1.length; _b++) { var remove = removes_1[_b]; var index = this._findWhitespaceIndex(remove.id); if (index === -1) { continue; } this._removeWhitespace(index); } return; } // simply rebuild the entire datastructure var toRemove = new Set(); for (var _c = 0, removes_2 = removes; _c < removes_2.length; _c++) { var remove = removes_2[_c]; toRemove.add(remove.id); } var toChange = new Map(); for (var _d = 0, changes_2 = changes; _d < changes_2.length; _d++) { var change = changes_2[_d]; toChange.set(change.id, change); } var applyRemoveAndChange = function (whitespaces) { var result = []; for (var _i = 0, whitespaces_1 = whitespaces; _i < whitespaces_1.length; _i++) { var whitespace = whitespaces_1[_i]; if (toRemove.has(whitespace.id)) { continue; } if (toChange.has(whitespace.id)) { var change = toChange.get(whitespace.id); whitespace.afterLineNumber = change.newAfterLineNumber; whitespace.height = change.newHeight; } result.push(whitespace); } return result; }; var result = applyRemoveAndChange(this._arr).concat(applyRemoveAndChange(inserts)); result.sort(function (a, b) { if (a.afterLineNumber === b.afterLineNumber) { return a.ordinal - b.ordinal; } return a.afterLineNumber - b.afterLineNumber; }); this._arr = result; this._prefixSumValidIndex = -1; }; LinesLayout.prototype._checkPendingChanges = function () { if (this._pendingChanges.mustCommit()) { this._pendingChanges.commit(this); } }; LinesLayout.prototype._insertWhitespace = function (whitespace) { var insertIndex = LinesLayout.findInsertionIndex(this._arr, whitespace.afterLineNumber, whitespace.ordinal); this._arr.splice(insertIndex, 0, whitespace); this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, insertIndex - 1); }; LinesLayout.prototype._findWhitespaceIndex = function (id) { var arr = this._arr; for (var i = 0, len = arr.length; i < len; i++) { if (arr[i].id === id) { return i; } } return -1; }; LinesLayout.prototype._changeOneWhitespace = function (id, newAfterLineNumber, newHeight) { var 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 var 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); } }; LinesLayout.prototype._removeWhitespace = function (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 */ LinesLayout.prototype.onLinesDeleted = function (fromLineNumber, toLineNumber) { this._checkPendingChanges(); fromLineNumber = fromLineNumber | 0; toLineNumber = toLineNumber | 0; this._lineCount -= (toLineNumber - fromLineNumber + 1); for (var i = 0, len = this._arr.length; i < len; i++) { var 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. */ LinesLayout.prototype.onLinesInserted = function (fromLineNumber, toLineNumber) { this._checkPendingChanges(); fromLineNumber = fromLineNumber | 0; toLineNumber = toLineNumber | 0; this._lineCount += (toLineNumber - fromLineNumber + 1); for (var i = 0, len = this._arr.length; i < len; i++) { var afterLineNumber = this._arr[i].afterLineNumber; if (fromLineNumber <= afterLineNumber) { this._arr[i].afterLineNumber += (toLineNumber - fromLineNumber + 1); } } }; /** * Get the sum of all the whitespaces. */ LinesLayout.prototype.getWhitespacesTotalHeight = function () { 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`. */ LinesLayout.prototype.getWhitespacesAccumulatedHeight = function (index) { this._checkPendingChanges(); index = index | 0; var startIndex = Math.max(0, this._prefixSumValidIndex + 1); if (startIndex === 0) { this._arr[0].prefixSum = this._arr[0].height; startIndex++; } for (var 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. */ LinesLayout.prototype.getLinesTotalHeight = function () { this._checkPendingChanges(); var linesHeight = this._lineHeight * this._lineCount; var whitespacesHeight = this.getWhitespacesTotalHeight(); return linesHeight + whitespacesHeight; }; /** * Returns the accumulated height of whitespaces before the given line number. * * @param lineNumber The line number */ LinesLayout.prototype.getWhitespaceAccumulatedHeightBeforeLineNumber = function (lineNumber) { this._checkPendingChanges(); lineNumber = lineNumber | 0; var lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber); if (lastWhitespaceBeforeLineNumber === -1) { return 0; } return this.getWhitespacesAccumulatedHeight(lastWhitespaceBeforeLineNumber); }; LinesLayout.prototype._findLastWhitespaceBeforeLineNumber = function (lineNumber) { lineNumber = lineNumber | 0; // Find the whitespace before line number var arr = this._arr; var low = 0; var high = arr.length - 1; while (low <= high) { var delta = (high - low) | 0; var halfDelta = (delta / 2) | 0; var 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; }; LinesLayout.prototype._findFirstWhitespaceAfterLineNumber = function (lineNumber) { lineNumber = lineNumber | 0; var lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber); var 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. */ LinesLayout.prototype.getFirstWhitespaceIndexAfterLineNumber = function (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`. */ LinesLayout.prototype.getVerticalOffsetForLineNumber = function (lineNumber) { this._checkPendingChanges(); lineNumber = lineNumber | 0; var previousLinesHeight; if (lineNumber > 1) { previousLinesHeight = this._lineHeight * (lineNumber - 1); } else { previousLinesHeight = 0; } var previousWhitespacesHeight = this.getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber); return previousLinesHeight + previousWhitespacesHeight; }; /** * The maximum min width for all whitespaces. */ LinesLayout.prototype.getWhitespaceMinWidth = function () { this._checkPendingChanges(); if (this._minWidth === -1) { var minWidth = 0; for (var 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. */ LinesLayout.prototype.isAfterLines = function (verticalOffset) { this._checkPendingChanges(); var totalHeight = this.getLinesTotalHeight(); return verticalOffset > totalHeight; }; /** * 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`. */ LinesLayout.prototype.getLineNumberAtOrAfterVerticalOffset = function (verticalOffset) { this._checkPendingChanges(); verticalOffset = verticalOffset | 0; if (verticalOffset < 0) { return 1; } var linesCount = this._lineCount | 0; var lineHeight = this._lineHeight; var minLineNumber = 1; var maxLineNumber = linesCount; while (minLineNumber < maxLineNumber) { var midLineNumber = ((minLineNumber + maxLineNumber) / 2) | 0; var 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`. */ LinesLayout.prototype.getLinesViewportData = function (verticalOffset1, verticalOffset2) { this._checkPendingChanges(); verticalOffset1 = verticalOffset1 | 0; verticalOffset2 = verticalOffset2 | 0; var 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 var startLineNumber = this.getLineNumberAtOrAfterVerticalOffset(verticalOffset1) | 0; var startLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(startLineNumber) | 0; var endLineNumber = this._lineCount | 0; // Also keep track of what whitespace we've got var whitespaceIndex = this.getFirstWhitespaceIndexAfterLineNumber(startLineNumber) | 0; var whitespaceCount = this.getWhitespacesCount() | 0; var currentWhitespaceHeight; var currentWhitespaceAfterLineNumber; if (whitespaceIndex === -1) { whitespaceIndex = whitespaceCount; currentWhitespaceAfterLineNumber = endLineNumber + 1; currentWhitespaceHeight = 0; } else { currentWhitespaceAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0; currentWhitespaceHeight = this.getHeightForWhitespaceIndex(whitespaceIndex) | 0; } var currentVerticalOffset = startLineNumberVerticalOffset; var currentLineRelativeOffset = currentVerticalOffset; // IE (all versions) cannot handle units above about 1,533,908 px, so every 500k pixels bring numbers down var STEP_SIZE = 500000; var 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; } var linesOffsets = []; var verticalCenter = verticalOffset1 + (verticalOffset2 - verticalOffset1) / 2; var centeredLineNumber = -1; // Figure out how far the lines go for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { if (centeredLineNumber === -1) { var currentLineTop = currentVerticalOffset; var 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; } var endLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(endLineNumber) | 0; var completelyVisibleStartLineNumber = startLineNumber; var 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 }; }; LinesLayout.prototype.getVerticalOffsetForWhitespaceIndex = function (whitespaceIndex) { this._checkPendingChanges(); whitespaceIndex = whitespaceIndex | 0; var afterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex); var previousLinesHeight; if (afterLineNumber >= 1) { previousLinesHeight = this._lineHeight * afterLineNumber; } else { previousLinesHeight = 0; } var previousWhitespacesHeight; if (whitespaceIndex > 0) { previousWhitespacesHeight = this.getWhitespacesAccumulatedHeight(whitespaceIndex - 1); } else { previousWhitespacesHeight = 0; } return previousLinesHeight + previousWhitespacesHeight; }; LinesLayout.prototype.getWhitespaceIndexAtOrAfterVerticallOffset = function (verticalOffset) { this._checkPendingChanges(); verticalOffset = verticalOffset | 0; var minWhitespaceIndex = 0; var maxWhitespaceIndex = this.getWhitespacesCount() - 1; if (maxWhitespaceIndex < 0) { return -1; } // Special case: nothing to be found var maxWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(maxWhitespaceIndex); var maxWhitespaceHeight = this.getHeightForWhitespaceIndex(maxWhitespaceIndex); if (verticalOffset >= maxWhitespaceVerticalOffset + maxWhitespaceHeight) { return -1; } while (minWhitespaceIndex < maxWhitespaceIndex) { var midWhitespaceIndex = Math.floor((minWhitespaceIndex + maxWhitespaceIndex) / 2); var midWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(midWhitespaceIndex); var 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. */ LinesLayout.prototype.getWhitespaceAtVerticalOffset = function (verticalOffset) { this._checkPendingChanges(); verticalOffset = verticalOffset | 0; var candidateIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset); if (candidateIndex < 0) { return null; } if (candidateIndex >= this.getWhitespacesCount()) { return null; } var candidateTop = this.getVerticalOffsetForWhitespaceIndex(candidateIndex); if (candidateTop > verticalOffset) { return null; } var candidateHeight = this.getHeightForWhitespaceIndex(candidateIndex); var candidateId = this.getIdForWhitespaceIndex(candidateIndex); var 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. */ LinesLayout.prototype.getWhitespaceViewportData = function (verticalOffset1, verticalOffset2) { this._checkPendingChanges(); verticalOffset1 = verticalOffset1 | 0; verticalOffset2 = verticalOffset2 | 0; var startIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset1); var endIndex = this.getWhitespacesCount() - 1; if (startIndex < 0) { return []; } var result = []; for (var i = startIndex; i <= endIndex; i++) { var top_1 = this.getVerticalOffsetForWhitespaceIndex(i); var height = this.getHeightForWhitespaceIndex(i); if (top_1 >= verticalOffset2) { break; } result.push({ id: this.getIdForWhitespaceIndex(i), afterLineNumber: this.getAfterLineNumberForWhitespaceIndex(i), verticalOffset: top_1, height: height }); } return result; }; /** * Get all whitespaces. */ LinesLayout.prototype.getWhitespaces = function () { this._checkPendingChanges(); return this._arr.slice(0); }; /** * The number of whitespaces. */ LinesLayout.prototype.getWhitespacesCount = function () { 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`. */ LinesLayout.prototype.getIdForWhitespaceIndex = function (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`. */ LinesLayout.prototype.getAfterLineNumberForWhitespaceIndex = function (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`. */ LinesLayout.prototype.getHeightForWhitespaceIndex = function (index) { this._checkPendingChanges(); index = index | 0; return this._arr[index].height; }; LinesLayout.INSTANCE_COUNT = 0; return LinesLayout; }()); exports.LinesLayout = LinesLayout; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[110/*vs/editor/common/viewLayout/viewLineRenderer*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,106/*vs/editor/common/core/stringBuilder*/,148/*vs/editor/common/viewLayout/lineDecorations*/]), function (require, exports, strings, stringBuilder_1, lineDecorations_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LinePart = /** @class */ (function () { function LinePart(endIndex, type) { this.endIndex = endIndex; this.type = type; } return LinePart; }()); var LineRange = /** @class */ (function () { function LineRange(startIndex, endIndex) { this.startOffset = startIndex; this.endOffset = endIndex; } LineRange.prototype.equals = function (otherLineRange) { return this.startOffset === otherLineRange.startOffset && this.endOffset === otherLineRange.endOffset; }; return LineRange; }()); exports.LineRange = LineRange; var RenderLineInput = /** @class */ (function () { function RenderLineInput(useMonospaceOptimizations, canUseHalfwidthRightwardsArrow, lineContent, continuesWithWrappedLine, isBasicASCII, containsRTL, fauxIndentLength, lineTokens, lineDecorations, tabSize, startVisibleColumn, spaceWidth, middotWidth, 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; this.tabSize = tabSize; this.startVisibleColumn = startVisibleColumn; this.spaceWidth = spaceWidth; this.middotWidth = middotWidth; this.stopRenderingLineAfter = stopRenderingLineAfter; this.renderWhitespace = (renderWhitespace === 'all' ? 3 /* All */ : renderWhitespace === 'boundary' ? 1 /* Boundary */ : renderWhitespace === 'selection' ? 2 /* Selection */ : 0 /* None */); this.renderControlCharacters = renderControlCharacters; this.fontLigatures = fontLigatures; this.selectionsOnLine = selectionsOnLine && selectionsOnLine.sort(function (a, b) { return a.startOffset < b.startOffset ? -1 : 1; }); } RenderLineInput.prototype.sameSelection = function (otherSelections) { if (this.selectionsOnLine === null) { return otherSelections === null; } if (otherSelections === null) { return false; } if (otherSelections.length !== this.selectionsOnLine.length) { return false; } for (var i = 0; i < this.selectionsOnLine.length; i++) { if (!this.selectionsOnLine[i].equals(otherSelections[i])) { return false; } } return true; }; RenderLineInput.prototype.equals = function (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.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)); }; return RenderLineInput; }()); exports.RenderLineInput = RenderLineInput; /** * Provides a both direction mapping between a line's character and its rendered position. */ var CharacterMapping = /** @class */ (function () { function CharacterMapping(length, partCount) { this.length = length; this._data = new Uint32Array(this.length); this._absoluteOffsets = new Uint32Array(this.length); } CharacterMapping.getPartIndex = function (partData) { return (partData & 4294901760 /* PART_INDEX_MASK */) >>> 16 /* PART_INDEX_OFFSET */; }; CharacterMapping.getCharIndex = function (partData) { return (partData & 65535 /* CHAR_INDEX_MASK */) >>> 0 /* CHAR_INDEX_OFFSET */; }; CharacterMapping.prototype.setPartData = function (charOffset, partIndex, charIndex, partAbsoluteOffset) { var partData = ((partIndex << 16 /* PART_INDEX_OFFSET */) | (charIndex << 0 /* CHAR_INDEX_OFFSET */)) >>> 0; this._data[charOffset] = partData; this._absoluteOffsets[charOffset] = partAbsoluteOffset + charIndex; }; CharacterMapping.prototype.getAbsoluteOffsets = function () { return this._absoluteOffsets; }; CharacterMapping.prototype.charOffsetToPartData = function (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]; }; CharacterMapping.prototype.partDataToCharOffset = function (partIndex, partLength, charIndex) { if (this.length === 0) { return 0; } var searchEntry = ((partIndex << 16 /* PART_INDEX_OFFSET */) | (charIndex << 0 /* CHAR_INDEX_OFFSET */)) >>> 0; var min = 0; var max = this.length - 1; while (min + 1 < max) { var mid = ((min + max) >>> 1); var midEntry = this._data[mid]; if (midEntry === searchEntry) { return mid; } else if (midEntry > searchEntry) { max = mid; } else { min = mid; } } if (min === max) { return min; } var minEntry = this._data[min]; var maxEntry = this._data[max]; if (minEntry === searchEntry) { return min; } if (maxEntry === searchEntry) { return max; } var minPartIndex = CharacterMapping.getPartIndex(minEntry); var minCharIndex = CharacterMapping.getCharIndex(minEntry); var maxPartIndex = CharacterMapping.getPartIndex(maxEntry); var maxCharIndex; if (minPartIndex !== maxPartIndex) { // sitting between parts maxCharIndex = partLength; } else { maxCharIndex = CharacterMapping.getCharIndex(maxEntry); } var minEntryDistance = charIndex - minCharIndex; var maxEntryDistance = maxCharIndex - charIndex; if (minEntryDistance <= maxEntryDistance) { return min; } return max; }; return CharacterMapping; }()); exports.CharacterMapping = CharacterMapping; var RenderLineOutput = /** @class */ (function () { function RenderLineOutput(characterMapping, containsRTL, containsForeignElements) { this.characterMapping = characterMapping; this.containsRTL = containsRTL; this.containsForeignElements = containsForeignElements; } return RenderLineOutput; }()); exports.RenderLineOutput = RenderLineOutput; function renderViewLine(input, sb) { if (input.lineContent.length === 0) { var containsForeignElements = 0 /* None */; // This is basically for IE's hit test to work var content = '\u00a0'; if (input.lineDecorations.length > 0) { // This line is empty, but it contains inline decorations var beforeClassNames = []; var afterClassNames = []; for (var i = 0, len = input.lineDecorations.length; i < len; i++) { var lineDecoration = input.lineDecorations[i]; if (lineDecoration.type === 1 /* Before */) { beforeClassNames.push(input.lineDecorations[i].className); containsForeignElements |= 1 /* Before */; } if (lineDecoration.type === 2 /* After */) { afterClassNames.push(input.lineDecorations[i].className); containsForeignElements |= 2 /* After */; } } if (containsForeignElements !== 0 /* None */) { var beforeSpan = (beforeClassNames.length > 0 ? "" : ""); var afterSpan = (afterClassNames.length > 0 ? "" : ""); content = "" + beforeSpan + afterSpan + ""; } } sb.appendASCIIString(content); return new RenderLineOutput(new CharacterMapping(0, 0), false, containsForeignElements); } return _renderLine(resolveRenderLineInput(input), sb); } exports.renderViewLine = renderViewLine; var RenderLineOutput2 = /** @class */ (function () { function RenderLineOutput2(characterMapping, html, containsRTL, containsForeignElements) { this.characterMapping = characterMapping; this.html = html; this.containsRTL = containsRTL; this.containsForeignElements = containsForeignElements; } return RenderLineOutput2; }()); exports.RenderLineOutput2 = RenderLineOutput2; function renderViewLine2(input) { var sb = stringBuilder_1.createStringBuilder(10000); var out = renderViewLine(input, sb); return new RenderLineOutput2(out.characterMapping, sb.build(), out.containsRTL, out.containsForeignElements); } exports.renderViewLine2 = renderViewLine2; var ResolvedRenderLineInput = /** @class */ (function () { function ResolvedRenderLineInput(fontIsMonospace, canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, parts, containsForeignElements, fauxIndentLength, tabSize, startVisibleColumn, containsRTL, spaceWidth, middotWidth, 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.middotWidth = middotWidth; this.renderWhitespace = renderWhitespace; this.renderControlCharacters = renderControlCharacters; // } return ResolvedRenderLineInput; }()); function resolveRenderLineInput(input) { var useMonospaceOptimizations = input.useMonospaceOptimizations; var lineContent = input.lineContent; var isOverflowing; var len; if (input.stopRenderingLineAfter !== -1 && input.stopRenderingLineAfter < lineContent.length) { isOverflowing = true; len = input.stopRenderingLineAfter; } else { isOverflowing = false; len = lineContent.length; } var tokens = transformAndRemoveOverflowing(input.lineTokens, input.fauxIndentLength, len); if (input.renderWhitespace === 3 /* All */ || input.renderWhitespace === 1 /* Boundary */ || (input.renderWhitespace === 2 /* Selection */ && !!input.selectionsOnLine)) { tokens = _applyRenderWhitespace(lineContent, len, input.continuesWithWrappedLine, tokens, input.fauxIndentLength, input.tabSize, input.startVisibleColumn, useMonospaceOptimizations, input.selectionsOnLine, input.renderWhitespace === 1 /* Boundary */); } var containsForeignElements = 0 /* None */; if (input.lineDecorations.length > 0) { for (var i = 0, len_1 = input.lineDecorations.length; i < len_1; i++) { var 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(useMonospaceOptimizations, input.canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, tokens, containsForeignElements, input.fauxIndentLength, input.tabSize, input.startVisibleColumn, input.containsRTL, input.spaceWidth, input.middotWidth, 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) { var result = [], resultLen = 0; // The faux indent part of the line should have no token type if (fauxIndentLength > 0) { result[resultLen++] = new LinePart(fauxIndentLength, ''); } for (var tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) { var endIndex = tokens.getEndOffset(tokenIndex); if (endIndex <= fauxIndentLength) { // The faux indent part of the line should have no token type continue; } var type = tokens.getClassName(tokenIndex); if (endIndex >= len) { result[resultLen++] = new LinePart(len, type); break; } result[resultLen++] = new LinePart(endIndex, type); } 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) { var lastTokenEndIndex = 0; var result = [], resultLen = 0; if (onlyAtSpaces) { // Split only at spaces => we need to walk each character for (var i = 0, len = tokens.length; i < len; i++) { var token = tokens[i]; var tokenEndIndex = token.endIndex; if (lastTokenEndIndex + 50 /* LongToken */ < tokenEndIndex) { var tokenType = token.type; var lastSpaceOffset = -1; var currTokenStart = lastTokenEndIndex; for (var 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); currTokenStart = lastSpaceOffset + 1; lastSpaceOffset = -1; } } if (currTokenStart !== tokenEndIndex) { result[resultLen++] = new LinePart(tokenEndIndex, tokenType); } } else { result[resultLen++] = token; } lastTokenEndIndex = tokenEndIndex; } } else { // Split anywhere => we don't need to walk each character for (var i = 0, len = tokens.length; i < len; i++) { var token = tokens[i]; var tokenEndIndex = token.endIndex; var diff = (tokenEndIndex - lastTokenEndIndex); if (diff > 50 /* LongToken */) { var tokenType = token.type; var piecesCount = Math.ceil(diff / 50 /* LongToken */); for (var j = 1; j < piecesCount; j++) { var pieceEndIndex = lastTokenEndIndex + (j * 50 /* LongToken */); result[resultLen++] = new LinePart(pieceEndIndex, tokenType); } result[resultLen++] = new LinePart(tokenEndIndex, tokenType); } else { result[resultLen++] = token; } lastTokenEndIndex = tokenEndIndex; } } return result; } /** * Whitespace is rendered by "replacing" tokens with a special-purpose `vs-whitespace` 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(lineContent, len, continuesWithWrappedLine, tokens, fauxIndentLength, tabSize, startVisibleColumn, useMonospaceOptimizations, selections, onlyBoundary) { var result = [], resultLen = 0; var tokenIndex = 0; var tokenType = tokens[tokenIndex].type; var tokenEndIndex = tokens[tokenIndex].endIndex; var tokensLength = tokens.length; var firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent); var lastNonWhitespaceIndex; if (firstNonWhitespaceIndex === -1) { // The entire line is whitespace firstNonWhitespaceIndex = len; lastNonWhitespaceIndex = len; } else { lastNonWhitespaceIndex = strings.lastNonWhitespaceIndex(lineContent); } var wasInWhitespace = false; var currentSelectionIndex = 0; var currentSelection = selections && selections[currentSelectionIndex]; var tmpIndent = startVisibleColumn % tabSize; for (var charIndex = fauxIndentLength; charIndex < len; charIndex++) { var chCode = lineContent.charCodeAt(charIndex); if (currentSelection && charIndex >= currentSelection.endOffset) { currentSelectionIndex++; currentSelection = selections && selections[currentSelectionIndex]; } var isInWhitespace = void 0; 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 { var 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 (wasInWhitespace) { // was in whitespace token if (!isInWhitespace || (!useMonospaceOptimizations && tmpIndent >= tabSize)) { // leaving whitespace token or entering a new indent result[resultLen++] = new LinePart(charIndex, 'vs-whitespace'); tmpIndent = tmpIndent % tabSize; } } else { // was in regular token if (charIndex === tokenEndIndex || (isInWhitespace && charIndex > fauxIndentLength)) { result[resultLen++] = new LinePart(charIndex, tokenType); tmpIndent = tmpIndent % tabSize; } } if (chCode === 9 /* Tab */) { tmpIndent = tabSize; } else if (strings.isFullWidthCharacter(chCode)) { tmpIndent += 2; } else { tmpIndent++; } wasInWhitespace = isInWhitespace; if (charIndex === tokenEndIndex) { tokenIndex++; if (tokenIndex < tokensLength) { tokenType = tokens[tokenIndex].type; tokenEndIndex = tokens[tokenIndex].endIndex; } } } var generateWhitespace = false; if (wasInWhitespace) { // was in whitespace token if (continuesWithWrappedLine && onlyBoundary) { var lastCharCode = (len > 0 ? lineContent.charCodeAt(len - 1) : 0 /* Null */); var prevCharCode = (len > 1 ? lineContent.charCodeAt(len - 2) : 0 /* Null */); var isSingleTrailingSpace = (lastCharCode === 32 /* Space */ && (prevCharCode !== 32 /* Space */ && prevCharCode !== 9 /* Tab */)); if (!isSingleTrailingSpace) { generateWhitespace = true; } } else { generateWhitespace = true; } } result[resultLen++] = new LinePart(len, generateWhitespace ? 'vs-whitespace' : tokenType); 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); var lineDecorations = lineDecorations_1.LineDecorationsNormalizer.normalize(lineContent, _lineDecorations); var lineDecorationsLen = lineDecorations.length; var lineDecorationIndex = 0; var result = [], resultLen = 0, lastResultEndIndex = 0; for (var tokenIndex = 0, len_2 = tokens.length; tokenIndex < len_2; tokenIndex++) { var token = tokens[tokenIndex]; var tokenEndIndex = token.endIndex; var tokenType = token.type; while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset < tokenEndIndex) { var lineDecoration = lineDecorations[lineDecorationIndex]; if (lineDecoration.startOffset > lastResultEndIndex) { lastResultEndIndex = lineDecoration.startOffset; result[resultLen++] = new LinePart(lastResultEndIndex, tokenType); } 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); lineDecorationIndex++; } else { // This line decoration continues on to the next token lastResultEndIndex = tokenEndIndex; result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + ' ' + lineDecoration.className); break; } } if (tokenEndIndex > lastResultEndIndex) { lastResultEndIndex = tokenEndIndex; result[resultLen++] = new LinePart(lastResultEndIndex, tokenType); } } var lastTokenEndIndex = tokens[tokens.length - 1].endIndex; if (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) { var classNames = []; while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) { classNames.push(lineDecorations[lineDecorationIndex].className); lineDecorationIndex++; } result[resultLen++] = new LinePart(lastResultEndIndex, classNames.join(' ')); } 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) { var fontIsMonospace = input.fontIsMonospace; var canUseHalfwidthRightwardsArrow = input.canUseHalfwidthRightwardsArrow; var containsForeignElements = input.containsForeignElements; var lineContent = input.lineContent; var len = input.len; var isOverflowing = input.isOverflowing; var parts = input.parts; var fauxIndentLength = input.fauxIndentLength; var tabSize = input.tabSize; var startVisibleColumn = input.startVisibleColumn; var containsRTL = input.containsRTL; var spaceWidth = input.spaceWidth; var middotWidth = input.middotWidth; var renderWhitespace = input.renderWhitespace; var renderControlCharacters = input.renderControlCharacters; // use U+2E31 - WORD SEPARATOR MIDDLE DOT or U+00B7 - MIDDLE DOT var spaceRenderWhitespaceCharacter = (middotWidth > spaceWidth ? 0x2E31 : 0xB7); var characterMapping = new CharacterMapping(len + 1, parts.length); var charIndex = 0; var visibleColumn = startVisibleColumn; var charOffsetInPart = 0; var prevPartContentCnt = 0; var partAbsoluteOffset = 0; sb.appendASCIIString(''); for (var partIndex = 0, tokensLen = parts.length; partIndex < tokensLen; partIndex++) { partAbsoluteOffset += prevPartContentCnt; var part = parts[partIndex]; var partEndIndex = part.endIndex; var partType = part.type; var partRendersWhitespace = (renderWhitespace !== 0 /* None */ && (partType.indexOf('vs-whitespace') >= 0)); charOffsetInPart = 0; sb.appendASCIIString(' 1) { sb.write1(0x2192); // RIGHTWARDS ARROW } else { sb.write1(0xFFEB); // HALFWIDTH RIGHTWARDS ARROW } for (var space = 2; space <= charWidth; space++) { sb.write1(0xA0); //   } } else { // must be CharCode.Space charWidth = 1; sb.write1(spaceRenderWhitespaceCharacter); // · or word separator middle dot } charOffsetInPart += charWidth; if (charIndex >= fauxIndentLength) { visibleColumn += charWidth; } } prevPartContentCnt = partContentCnt; } else { var partContentCnt = 0; if (containsRTL) { sb.appendASCIIString(' dir="ltr"'); } sb.appendASCII(62 /* GreaterThan */); for (; charIndex < partEndIndex; charIndex++) { characterMapping.setPartData(charIndex, partIndex, charOffsetInPart, partAbsoluteOffset); var charCode = lineContent.charCodeAt(charIndex); var producedCharacters = 1; var charWidth = 1; switch (charCode) { case 9 /* Tab */: producedCharacters = (tabSize - (visibleColumn % tabSize)); charWidth = producedCharacters; for (var 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 */: sb.appendASCIIString('�'); break; case 65279 /* UTF8_BOM */: case 8232 /* LINE_SEPARATOR_2028 */: sb.write1(0xFFFD); break; default: if (strings.isFullWidthCharacter(charCode)) { charWidth++; } if (renderControlCharacters && charCode < 32) { sb.write1(9216 + charCode); } else { sb.write1(charCode); } } charOffsetInPart += producedCharacters; partContentCnt += producedCharacters; if (charIndex >= fauxIndentLength) { visibleColumn += charWidth; } } prevPartContentCnt = partContentCnt; } sb.appendASCIIString(''); } // 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.setPartData(len, parts.length - 1, charOffsetInPart, partAbsoluteOffset); if (isOverflowing) { sb.appendASCIIString(''); } sb.appendASCIIString(''); return new RenderLineOutput(characterMapping, containsRTL, containsForeignElements); } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[363/*vs/editor/common/viewLayout/viewLinesViewportData*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/]), function (require, exports, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Contains all data needed to render at a specific viewport. */ var ViewportData = /** @class */ (function () { function ViewportData(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)); } ViewportData.prototype.getViewLineRenderingData = function (lineNumber) { return this._model.getViewLineRenderingData(this.visibleRange, lineNumber); }; ViewportData.prototype.getDecorationsInViewport = function () { return this._model.getDecorationsInViewport(this.visibleRange); }; return ViewportData; }()); 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[194/*vs/editor/common/viewModel/prefixSumComputer*/], __M([0/*require*/,1/*exports*/,179/*vs/base/common/uint*/]), function (require, exports, uint_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var PrefixSumIndexOfResult = /** @class */ (function () { function PrefixSumIndexOfResult(index, remainder) { this.index = index; this.remainder = remainder; } return PrefixSumIndexOfResult; }()); exports.PrefixSumIndexOfResult = PrefixSumIndexOfResult; var PrefixSumComputer = /** @class */ (function () { function PrefixSumComputer(values) { this.values = values; this.prefixSum = new Uint32Array(values.length); this.prefixSumValidIndex = new Int32Array(1); this.prefixSumValidIndex[0] = -1; } PrefixSumComputer.prototype.insertValues = function (insertIndex, insertValues) { insertIndex = uint_1.toUint32(insertIndex); var oldValues = this.values; var oldPrefixSum = this.prefixSum; var 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; }; PrefixSumComputer.prototype.changeValue = function (index, value) { index = uint_1.toUint32(index); value = 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; }; PrefixSumComputer.prototype.removeValues = function (startIndex, cnt) { startIndex = uint_1.toUint32(startIndex); cnt = uint_1.toUint32(cnt); var oldValues = this.values; var oldPrefixSum = this.prefixSum; if (startIndex >= oldValues.length) { return false; } var maxCnt = oldValues.length - startIndex; if (cnt >= maxCnt) { cnt = maxCnt; } if (cnt === 0) { return false; } this.values = new Uint32Array(oldValues.length - cnt); this.values.set(oldValues.subarray(0, startIndex), 0); this.values.set(oldValues.subarray(startIndex + cnt), 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; }; PrefixSumComputer.prototype.getTotalValue = function () { if (this.values.length === 0) { return 0; } return this._getAccumulatedValue(this.values.length - 1); }; PrefixSumComputer.prototype.getAccumulatedValue = function (index) { if (index < 0) { return 0; } index = uint_1.toUint32(index); return this._getAccumulatedValue(index); }; PrefixSumComputer.prototype._getAccumulatedValue = function (index) { if (index <= this.prefixSumValidIndex[0]) { return this.prefixSum[index]; } var 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 (var 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]; }; PrefixSumComputer.prototype.getIndexOf = function (accumulatedValue) { accumulatedValue = Math.floor(accumulatedValue); //@perf // Compute all sums (to get a fully valid prefixSum) this.getTotalValue(); var low = 0; var high = this.values.length - 1; var mid = 0; var midStop = 0; var midStart = 0; while (low <= high) { mid = low + ((high - low) / 2) | 0; midStop = this.prefixSum[mid]; midStart = midStop - this.values[mid]; if (accumulatedValue < midStart) { high = mid - 1; } else if (accumulatedValue >= midStop) { low = mid + 1; } else { break; } } return new PrefixSumIndexOfResult(mid, accumulatedValue - midStart); }; return PrefixSumComputer; }()); exports.PrefixSumComputer = PrefixSumComputer; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[364/*vs/editor/common/model/mirrorTextModel*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,194/*vs/editor/common/viewModel/prefixSumComputer*/]), function (require, exports, position_1, prefixSumComputer_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MirrorTextModel = /** @class */ (function () { function MirrorTextModel(uri, lines, eol, versionId) { this._uri = uri; this._lines = lines; this._eol = eol; this._versionId = versionId; this._lineStarts = null; } MirrorTextModel.prototype.dispose = function () { this._lines.length = 0; }; MirrorTextModel.prototype.getText = function () { return this._lines.join(this._eol); }; MirrorTextModel.prototype.onEvents = function (e) { if (e.eol && e.eol !== this._eol) { this._eol = e.eol; this._lineStarts = null; } // Update my lines var changes = e.changes; for (var _i = 0, changes_1 = changes; _i < changes_1.length; _i++) { var change = changes_1[_i]; this._acceptDeleteRange(change.range); this._acceptInsertText(new position_1.Position(change.range.startLineNumber, change.range.startColumn), change.text); } this._versionId = e.versionId; }; MirrorTextModel.prototype._ensureLineStarts = function () { if (!this._lineStarts) { var eolLength = this._eol.length; var linesLength = this._lines.length; var lineStartValues = new Uint32Array(linesLength); for (var 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 */ MirrorTextModel.prototype._setLineText = function (lineIndex, newValue) { this._lines[lineIndex] = newValue; if (this._lineStarts) { // update prefix sum this._lineStarts.changeValue(lineIndex, this._lines[lineIndex].length + this._eol.length); } }; MirrorTextModel.prototype._acceptDeleteRange = function (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); } }; MirrorTextModel.prototype._acceptInsertText = function (position, insertText) { if (insertText.length === 0) { // Nothing to insert return; } var insertLines = insertText.split(/\r\n|\r|\n/); 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 var newLengths = new Uint32Array(insertLines.length - 1); for (var 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); } }; return MirrorTextModel; }()); 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[365/*vs/editor/common/services/editorSimpleWorker*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,126/*vs/base/common/diff/diff*/,54/*vs/base/common/iterator*/,16/*vs/base/common/platform*/,25/*vs/base/common/uri*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,341/*vs/editor/common/diff/diffComputer*/,364/*vs/editor/common/model/mirrorTextModel*/,109/*vs/editor/common/model/wordHelper*/,351/*vs/editor/common/modes/linkComputer*/,354/*vs/editor/common/modes/supports/inplaceReplaceSupport*/,192/*vs/editor/common/standalone/standaloneBase*/,21/*vs/base/common/types*/]), function (require, exports, arrays_1, diff_1, iterator_1, platform_1, uri_1, position_1, range_1, diffComputer_1, mirrorTextModel_1, wordHelper_1, linkComputer_1, inplaceReplaceSupport_1, standaloneBase_1, types) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * @internal */ var MirrorModel = /** @class */ (function (_super) { __extends(MirrorModel, _super); function MirrorModel() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(MirrorModel.prototype, "uri", { get: function () { return this._uri; }, enumerable: true, configurable: true }); Object.defineProperty(MirrorModel.prototype, "version", { get: function () { return this._versionId; }, enumerable: true, configurable: true }); Object.defineProperty(MirrorModel.prototype, "eol", { get: function () { return this._eol; }, enumerable: true, configurable: true }); MirrorModel.prototype.getValue = function () { return this.getText(); }; MirrorModel.prototype.getLinesContent = function () { return this._lines.slice(0); }; MirrorModel.prototype.getLineCount = function () { return this._lines.length; }; MirrorModel.prototype.getLineContent = function (lineNumber) { return this._lines[lineNumber - 1]; }; MirrorModel.prototype.getWordAtPosition = function (position, wordDefinition) { var wordAtText = wordHelper_1.getWordAtText(position.column, 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; }; MirrorModel.prototype.createWordIterator = function (wordDefinition) { var _this = this; var obj; var lineNumber = 0; var lineText; var wordRangesIdx = 0; var wordRanges = []; var next = function () { if (wordRangesIdx < wordRanges.length) { var value = lineText.substring(wordRanges[wordRangesIdx].start, wordRanges[wordRangesIdx].end); wordRangesIdx += 1; if (!obj) { obj = { done: false, value: value }; } else { obj.value = value; } return obj; } else if (lineNumber >= _this._lines.length) { return iterator_1.FIN; } else { lineText = _this._lines[lineNumber]; wordRanges = _this._wordenize(lineText, wordDefinition); wordRangesIdx = 0; lineNumber += 1; return next(); } }; return { next: next }; }; MirrorModel.prototype.getLineWords = function (lineNumber, wordDefinition) { var content = this._lines[lineNumber - 1]; var ranges = this._wordenize(content, wordDefinition); var words = []; for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { var range = ranges_1[_i]; words.push({ word: content.substring(range.start, range.end), startColumn: range.start + 1, endColumn: range.end + 1 }); } return words; }; MirrorModel.prototype._wordenize = function (content, wordDefinition) { var result = []; var 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; }; MirrorModel.prototype.getValueInRange = function (range) { range = this._validateRange(range); if (range.startLineNumber === range.endLineNumber) { return this._lines[range.startLineNumber - 1].substring(range.startColumn - 1, range.endColumn - 1); } var lineEnding = this._eol; var startLineIndex = range.startLineNumber - 1; var endLineIndex = range.endLineNumber - 1; var resultLines = []; resultLines.push(this._lines[startLineIndex].substring(range.startColumn - 1)); for (var 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); }; MirrorModel.prototype.offsetAt = function (position) { position = this._validatePosition(position); this._ensureLineStarts(); return this._lineStarts.getAccumulatedValue(position.lineNumber - 2) + (position.column - 1); }; MirrorModel.prototype.positionAt = function (offset) { offset = Math.floor(offset); offset = Math.max(0, offset); this._ensureLineStarts(); var out = this._lineStarts.getIndexOf(offset); var lineLength = this._lines[out.index].length; // Ensure we return a valid position return { lineNumber: 1 + out.index, column: 1 + Math.min(out.remainder, lineLength) }; }; MirrorModel.prototype._validateRange = function (range) { var start = this._validatePosition({ lineNumber: range.startLineNumber, column: range.startColumn }); var 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; }; MirrorModel.prototype._validatePosition = function (position) { if (!position_1.Position.isIPosition(position)) { throw new Error('bad position'); } var lineNumber = position.lineNumber, column = position.column; var 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 { var 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: lineNumber, column: column }; } }; return MirrorModel; }(mirrorTextModel_1.MirrorTextModel)); /** * @internal */ var EditorSimpleWorker = /** @class */ (function () { function EditorSimpleWorker(host, foreignModuleFactory) { this._host = host; this._models = Object.create(null); this._foreignModuleFactory = foreignModuleFactory; this._foreignModule = null; } EditorSimpleWorker.prototype.dispose = function () { this._models = Object.create(null); }; EditorSimpleWorker.prototype._getModel = function (uri) { return this._models[uri]; }; EditorSimpleWorker.prototype._getModels = function () { var _this = this; var all = []; Object.keys(this._models).forEach(function (key) { return all.push(_this._models[key]); }); return all; }; EditorSimpleWorker.prototype.acceptNewModel = function (data) { this._models[data.url] = new MirrorModel(uri_1.URI.parse(data.url), data.lines, data.EOL, data.versionId); }; EditorSimpleWorker.prototype.acceptModelChanged = function (strURL, e) { if (!this._models[strURL]) { return; } var model = this._models[strURL]; model.onEvents(e); }; EditorSimpleWorker.prototype.acceptRemovedModel = function (strURL) { if (!this._models[strURL]) { return; } delete this._models[strURL]; }; // ---- BEGIN diff -------------------------------------------------------------------------- EditorSimpleWorker.prototype.computeDiff = function (originalUrl, modifiedUrl, ignoreTrimWhitespace, maxComputationTime) { return __awaiter(this, void 0, void 0, function () { var original, modified, originalLines, modifiedLines, diffComputer, diffResult, identical; return __generator(this, function (_a) { original = this._getModel(originalUrl); modified = this._getModel(modifiedUrl); if (!original || !modified) { return [2 /*return*/, null]; } originalLines = original.getLinesContent(); modifiedLines = modified.getLinesContent(); diffComputer = new diffComputer_1.DiffComputer(originalLines, modifiedLines, { shouldComputeCharChanges: true, shouldPostProcessCharChanges: true, shouldIgnoreTrimWhitespace: ignoreTrimWhitespace, shouldMakePrettyDiff: true, maxComputationTime: maxComputationTime }); diffResult = diffComputer.computeDiff(); identical = (diffResult.changes.length > 0 ? false : this._modelsAreIdentical(original, modified)); return [2 /*return*/, { quitEarly: diffResult.quitEarly, identical: identical, changes: diffResult.changes }]; }); }); }; EditorSimpleWorker.prototype._modelsAreIdentical = function (original, modified) { var originalLineCount = original.getLineCount(); var modifiedLineCount = modified.getLineCount(); if (originalLineCount !== modifiedLineCount) { return false; } for (var line = 1; line <= originalLineCount; line++) { var originalLine = original.getLineContent(line); var modifiedLine = modified.getLineContent(line); if (originalLine !== modifiedLine) { return false; } } return true; }; EditorSimpleWorker.prototype.computeMoreMinimalEdits = function (modelUrl, edits) { return __awaiter(this, void 0, void 0, function () { var model, result, lastEol, _i, edits_1, _a, range, text, eol, original, changes, editOffset, _b, changes_1, change, start, end, newEdit; return __generator(this, function (_c) { model = this._getModel(modelUrl); if (!model) { return [2 /*return*/, edits]; } result = []; lastEol = undefined; edits = arrays_1.mergeSort(edits, function (a, b) { if (a.range && b.range) { return range_1.Range.compareRangesUsingStarts(a.range, b.range); } // eol only changes should go to the end var aRng = a.range ? 0 : 1; var bRng = b.range ? 0 : 1; return aRng - bRng; }); for (_i = 0, edits_1 = edits; _i < edits_1.length; _i++) { _a = edits_1[_i], range = _a.range, text = _a.text, eol = _a.eol; if (typeof eol === 'number') { lastEol = eol; } if (range_1.Range.isEmpty(range) && !text) { // empty change continue; } 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: range, text: text }); continue; } changes = diff_1.stringDiff(original, text, false); editOffset = model.offsetAt(range_1.Range.lift(range).getStartPosition()); for (_b = 0, changes_1 = changes; _b < changes_1.length; _b++) { change = changes_1[_b]; start = model.positionAt(editOffset + change.originalStart); end = model.positionAt(editOffset + change.originalStart + change.originalLength); 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 [2 /*return*/, result]; }); }); }; // ---- END minimal edits --------------------------------------------------------------- EditorSimpleWorker.prototype.computeLinks = function (modelUrl) { return __awaiter(this, void 0, void 0, function () { var model; return __generator(this, function (_a) { model = this._getModel(modelUrl); if (!model) { return [2 /*return*/, null]; } return [2 /*return*/, linkComputer_1.computeLinks(model)]; }); }); }; EditorSimpleWorker.prototype.textualSuggest = function (modelUrl, position, wordDef, wordDefFlags) { return __awaiter(this, void 0, void 0, function () { var model, words, seen, wordDefRegExp, wordAt, iter, e, word; return __generator(this, function (_a) { model = this._getModel(modelUrl); if (!model) { return [2 /*return*/, null]; } words = []; seen = new Set(); wordDefRegExp = new RegExp(wordDef, wordDefFlags); wordAt = model.getWordAtPosition(position, wordDefRegExp); if (wordAt) { seen.add(model.getValueInRange(wordAt)); } for (iter = model.createWordIterator(wordDefRegExp), e = iter.next(); !e.done && seen.size <= EditorSimpleWorker._suggestionsLimit; e = iter.next()) { word = e.value; if (seen.has(word)) { continue; } seen.add(word); if (!isNaN(Number(word))) { continue; } words.push(word); } return [2 /*return*/, words]; }); }); }; // ---- END suggest -------------------------------------------------------------------------- //#region -- word ranges -- EditorSimpleWorker.prototype.computeWordRanges = function (modelUrl, range, wordDef, wordDefFlags) { return __awaiter(this, void 0, void 0, function () { var model, wordDefRegExp, result, line, words, _i, words_1, word, array; return __generator(this, function (_a) { model = this._getModel(modelUrl); if (!model) { return [2 /*return*/, Object.create(null)]; } wordDefRegExp = new RegExp(wordDef, wordDefFlags); result = Object.create(null); for (line = range.startLineNumber; line < range.endLineNumber; line++) { words = model.getLineWords(line, wordDefRegExp); for (_i = 0, words_1 = words; _i < words_1.length; _i++) { word = words_1[_i]; if (!isNaN(Number(word.word))) { continue; } array = result[word.word]; if (!array) { array = []; result[word.word] = array; } array.push({ startLineNumber: line, startColumn: word.startColumn, endLineNumber: line, endColumn: word.endColumn }); } } return [2 /*return*/, result]; }); }); }; //#endregion EditorSimpleWorker.prototype.navigateValueSet = function (modelUrl, range, up, wordDef, wordDefFlags) { return __awaiter(this, void 0, void 0, function () { var model, wordDefRegExp, selectionText, wordRange, word, result; return __generator(this, function (_a) { model = this._getModel(modelUrl); if (!model) { return [2 /*return*/, null]; } wordDefRegExp = new RegExp(wordDef, wordDefFlags); if (range.startColumn === range.endColumn) { range = { startLineNumber: range.startLineNumber, startColumn: range.startColumn, endLineNumber: range.endLineNumber, endColumn: range.endColumn + 1 }; } selectionText = model.getValueInRange(range); wordRange = model.getWordAtPosition({ lineNumber: range.startLineNumber, column: range.startColumn }, wordDefRegExp); if (!wordRange) { return [2 /*return*/, null]; } word = model.getValueInRange(wordRange); result = inplaceReplaceSupport_1.BasicInplaceReplace.INSTANCE.navigateValueSet(range, selectionText, wordRange, word, up); return [2 /*return*/, result]; }); }); }; // ---- BEGIN foreign module support -------------------------------------------------------------------------- EditorSimpleWorker.prototype.loadForeignModule = function (moduleId, createData, foreignHostMethods) { var _this = this; var proxyMethodRequest = function (method, args) { return _this._host.fhr(method, args); }; var foreignHost = types.createProxyObject(foreignHostMethods, proxyMethodRequest); var ctx = { host: foreignHost, getMirrorModels: function () { 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(function (resolve, reject) { require([moduleId], function (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 EditorSimpleWorker.prototype.fmr = function (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); } }; // ---- END diff -------------------------------------------------------------------------- // ---- BEGIN minimal edits --------------------------------------------------------------- EditorSimpleWorker._diffLimit = 100000; // ---- BEGIN suggest -------------------------------------------------------------------------- EditorSimpleWorker._suggestionsLimit = 10000; return EditorSimpleWorker; }()); exports.EditorSimpleWorker = EditorSimpleWorker; /** * 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 = standaloneBase_1.createMonacoBaseAPI(); } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[92/*vs/editor/common/viewModel/viewEventHandler*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/]), function (require, exports, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ViewEventHandler = /** @class */ (function (_super) { __extends(ViewEventHandler, _super); function ViewEventHandler() { var _this = _super.call(this) || this; _this._shouldRender = true; return _this; } ViewEventHandler.prototype.shouldRender = function () { return this._shouldRender; }; ViewEventHandler.prototype.forceShouldRender = function () { this._shouldRender = true; }; ViewEventHandler.prototype.setShouldRender = function () { this._shouldRender = true; }; ViewEventHandler.prototype.onDidRender = function () { this._shouldRender = false; }; // --- begin event handlers ViewEventHandler.prototype.onConfigurationChanged = function (e) { return false; }; ViewEventHandler.prototype.onContentSizeChanged = function (e) { return false; }; ViewEventHandler.prototype.onCursorStateChanged = function (e) { return false; }; ViewEventHandler.prototype.onDecorationsChanged = function (e) { return false; }; ViewEventHandler.prototype.onFlushed = function (e) { return false; }; ViewEventHandler.prototype.onFocusChanged = function (e) { return false; }; ViewEventHandler.prototype.onLanguageConfigurationChanged = function (e) { return false; }; ViewEventHandler.prototype.onLineMappingChanged = function (e) { return false; }; ViewEventHandler.prototype.onLinesChanged = function (e) { return false; }; ViewEventHandler.prototype.onLinesDeleted = function (e) { return false; }; ViewEventHandler.prototype.onLinesInserted = function (e) { return false; }; ViewEventHandler.prototype.onRevealRangeRequest = function (e) { return false; }; ViewEventHandler.prototype.onScrollChanged = function (e) { return false; }; ViewEventHandler.prototype.onThemeChanged = function (e) { return false; }; ViewEventHandler.prototype.onTokensChanged = function (e) { return false; }; ViewEventHandler.prototype.onTokensColorsChanged = function (e) { return false; }; ViewEventHandler.prototype.onZonesChanged = function (e) { return false; }; // --- end event handlers ViewEventHandler.prototype.handleEvents = function (events) { var shouldRender = false; for (var i = 0, len = events.length; i < len; i++) { var e = events[i]; switch (e.type) { case 1 /* ViewConfigurationChanged */: if (this.onConfigurationChanged(e)) { shouldRender = true; } break; case 2 /* ViewContentSizeChanged */: if (this.onContentSizeChanged(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; } }; return ViewEventHandler; }(lifecycle_1.Disposable)); 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[82/*vs/editor/browser/view/dynamicViewOverlay*/], __M([0/*require*/,1/*exports*/,92/*vs/editor/common/viewModel/viewEventHandler*/]), function (require, exports, viewEventHandler_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DynamicViewOverlay = /** @class */ (function (_super) { __extends(DynamicViewOverlay, _super); function DynamicViewOverlay() { return _super !== null && _super.apply(this, arguments) || this; } return DynamicViewOverlay; }(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[37/*vs/editor/browser/view/viewPart*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,92/*vs/editor/common/viewModel/viewEventHandler*/]), function (require, exports, fastDomNode_1, viewEventHandler_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ViewPart = /** @class */ (function (_super) { __extends(ViewPart, _super); function ViewPart(context) { var _this = _super.call(this) || this; _this._context = context; _this._context.addEventHandler(_this); return _this; } ViewPart.prototype.dispose = function () { this._context.removeEventHandler(this); _super.prototype.dispose.call(this); }; return ViewPart; }(viewEventHandler_1.ViewEventHandler)); exports.ViewPart = ViewPart; var PartFingerprints = /** @class */ (function () { function PartFingerprints() { } PartFingerprints.write = function (target, partId) { if (target instanceof fastDomNode_1.FastDomNode) { target.setAttribute('data-mprt', String(partId)); } else { target.setAttribute('data-mprt', String(partId)); } }; PartFingerprints.read = function (target) { var r = target.getAttribute('data-mprt'); if (r === null) { return 0 /* None */; } return parseInt(r, 10); }; PartFingerprints.collect = function (child, stopAt) { var result = [], resultLen = 0; while (child && child !== document.body) { if (child === stopAt) { break; } if (child.nodeType === child.ELEMENT_NODE) { result[resultLen++] = this.read(child); } child = child.parentElement; } var r = new Uint8Array(resultLen); for (var i = 0; i < resultLen; i++) { r[i] = result[resultLen - i - 1]; } return r; }; return PartFingerprints; }()); 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[366/*vs/editor/browser/viewParts/contentWidgets/contentWidgets*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,28/*vs/base/browser/fastDomNode*/,37/*vs/editor/browser/view/viewPart*/]), function (require, exports, dom, fastDomNode_1, viewPart_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Coordinate = /** @class */ (function () { function Coordinate(top, left) { this.top = top; this.left = left; } return Coordinate; }()); var ViewContentWidgets = /** @class */ (function (_super) { __extends(ViewContentWidgets, _super); function ViewContentWidgets(context, viewDomNode) { var _this = _super.call(this, context) || this; _this._viewDomNode = viewDomNode; _this._widgets = {}; _this.domNode = 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 = fastDomNode_1.createFastDomNode(document.createElement('div')); viewPart_1.PartFingerprints.write(_this.overflowingContentWidgetsDomNode, 2 /* OverflowingContentWidgets */); _this.overflowingContentWidgetsDomNode.setClassName('overflowingContentWidgets'); return _this; } ViewContentWidgets.prototype.dispose = function () { _super.prototype.dispose.call(this); this._widgets = {}; }; // --- begin event handlers ViewContentWidgets.prototype.onConfigurationChanged = function (e) { var keys = Object.keys(this._widgets); for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { var widgetId = keys_1[_i]; this._widgets[widgetId].onConfigurationChanged(e); } return true; }; ViewContentWidgets.prototype.onDecorationsChanged = function (e) { // true for inline decorations that can end up relayouting text return true; }; ViewContentWidgets.prototype.onFlushed = function (e) { return true; }; ViewContentWidgets.prototype.onLineMappingChanged = function (e) { var keys = Object.keys(this._widgets); for (var _i = 0, keys_2 = keys; _i < keys_2.length; _i++) { var widgetId = keys_2[_i]; this._widgets[widgetId].onLineMappingChanged(e); } return true; }; ViewContentWidgets.prototype.onLinesChanged = function (e) { return true; }; ViewContentWidgets.prototype.onLinesDeleted = function (e) { return true; }; ViewContentWidgets.prototype.onLinesInserted = function (e) { return true; }; ViewContentWidgets.prototype.onScrollChanged = function (e) { return true; }; ViewContentWidgets.prototype.onZonesChanged = function (e) { return true; }; // ---- end view event handlers ViewContentWidgets.prototype.addWidget = function (_widget) { var 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(); }; ViewContentWidgets.prototype.setWidgetPosition = function (widget, range, preference) { var myWidget = this._widgets[widget.getId()]; myWidget.setPosition(range, preference); this.setShouldRender(); }; ViewContentWidgets.prototype.removeWidget = function (widget) { var widgetId = widget.getId(); if (this._widgets.hasOwnProperty(widgetId)) { var myWidget = this._widgets[widgetId]; delete this._widgets[widgetId]; var domNode = myWidget.domNode.domNode; domNode.parentNode.removeChild(domNode); domNode.removeAttribute('monaco-visible-content-widget'); this.setShouldRender(); } }; ViewContentWidgets.prototype.shouldSuppressMouseDownOnWidget = function (widgetId) { if (this._widgets.hasOwnProperty(widgetId)) { return this._widgets[widgetId].suppressMouseDown; } return false; }; ViewContentWidgets.prototype.onBeforeRender = function (viewportData) { var keys = Object.keys(this._widgets); for (var _i = 0, keys_3 = keys; _i < keys_3.length; _i++) { var widgetId = keys_3[_i]; this._widgets[widgetId].onBeforeRender(viewportData); } }; ViewContentWidgets.prototype.prepareRender = function (ctx) { var keys = Object.keys(this._widgets); for (var _i = 0, keys_4 = keys; _i < keys_4.length; _i++) { var widgetId = keys_4[_i]; this._widgets[widgetId].prepareRender(ctx); } }; ViewContentWidgets.prototype.render = function (ctx) { var keys = Object.keys(this._widgets); for (var _i = 0, keys_5 = keys; _i < keys_5.length; _i++) { var widgetId = keys_5[_i]; this._widgets[widgetId].render(ctx); } }; return ViewContentWidgets; }(viewPart_1.ViewPart)); exports.ViewContentWidgets = ViewContentWidgets; var Widget = /** @class */ (function () { function Widget(context, viewDomNode, actual) { this._context = context; this._viewDomNode = viewDomNode; this._actual = actual; this.domNode = fastDomNode_1.createFastDomNode(this._actual.getDomNode()); this.id = this._actual.getId(); this.allowEditorOverflow = this._actual.allowEditorOverflow || false; this.suppressMouseDown = this._actual.suppressMouseDown || false; var options = this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); this._fixedOverflowWidgets = options.get(29 /* fixedOverflowWidgets */); this._contentWidth = layoutInfo.contentWidth; this._contentLeft = layoutInfo.contentLeft; this._lineHeight = options.get(49 /* lineHeight */); this._range = null; this._viewRange = null; this._preference = []; this._cachedDomNodeClientWidth = -1; this._cachedDomNodeClientHeight = -1; this._maxWidth = this._getMaxWidth(); this._isVisible = false; this._renderData = null; this.domNode.setPosition((this._fixedOverflowWidgets && this.allowEditorOverflow) ? 'fixed' : 'absolute'); this.domNode.setVisibility('hidden'); this.domNode.setAttribute('widgetId', this.id); this.domNode.setMaxWidth(this._maxWidth); } Widget.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; this._lineHeight = options.get(49 /* lineHeight */); if (e.hasChanged(107 /* layoutInfo */)) { var layoutInfo = options.get(107 /* layoutInfo */); this._contentLeft = layoutInfo.contentLeft; this._contentWidth = layoutInfo.contentWidth; this._maxWidth = this._getMaxWidth(); } }; Widget.prototype.onLineMappingChanged = function (e) { this._setPosition(this._range); }; Widget.prototype._setPosition = function (range) { this._range = range; this._viewRange = null; if (this._range) { // Do not trust that widgets give a valid position var 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); } } }; Widget.prototype._getMaxWidth = function () { return (this.allowEditorOverflow ? window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth : this._contentWidth); }; Widget.prototype.setPosition = function (range, preference) { this._setPosition(range); this._preference = preference; this._cachedDomNodeClientWidth = -1; this._cachedDomNodeClientHeight = -1; }; Widget.prototype._layoutBoxInViewport = function (topLeft, bottomLeft, width, height, ctx) { // Our visible box is split horizontally by the current line => 2 boxes // a) the box above the line var aboveLineTop = topLeft.top; var heightAboveLine = aboveLineTop; // b) the box under the line var underLineTop = bottomLeft.top + this._lineHeight; var heightUnderLine = ctx.viewportHeight - underLineTop; var aboveTop = aboveLineTop - height; var fitsAbove = (heightAboveLine >= height); var belowTop = underLineTop; var fitsBelow = (heightUnderLine >= height); // And its left var actualAboveLeft = topLeft.left; var 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, }; }; Widget.prototype._layoutHorizontalSegmentInPage = function (windowSize, domNodePosition, left, width) { // Initially, the limits are defined as the dom node limits var MIN_LIMIT = Math.max(0, domNodePosition.left - width); var MAX_LIMIT = Math.min(domNodePosition.left + domNodePosition.width + width, windowSize.width); var absoluteLeft = domNodePosition.left + left - dom.StandardWindow.scrollX; if (absoluteLeft + width > MAX_LIMIT) { var delta = absoluteLeft - (MAX_LIMIT - width); absoluteLeft -= delta; left -= delta; } if (absoluteLeft < MIN_LIMIT) { var delta = absoluteLeft - MIN_LIMIT; absoluteLeft -= delta; left -= delta; } return [left, absoluteLeft]; }; Widget.prototype._layoutBoxInPage = function (topLeft, bottomLeft, width, height, ctx) { var aboveTop = topLeft.top - height; var belowTop = bottomLeft.top + this._lineHeight; var domNodePosition = dom.getDomNodePagePosition(this._viewDomNode.domNode); var absoluteAboveTop = domNodePosition.top + aboveTop - dom.StandardWindow.scrollY; var absoluteBelowTop = domNodePosition.top + belowTop - dom.StandardWindow.scrollY; var windowSize = dom.getClientArea(document.body); var _a = this._layoutHorizontalSegmentInPage(windowSize, domNodePosition, topLeft.left - ctx.scrollLeft + this._contentLeft, width), aboveLeft = _a[0], absoluteAboveLeft = _a[1]; var _b = this._layoutHorizontalSegmentInPage(windowSize, domNodePosition, bottomLeft.left - ctx.scrollLeft + this._contentLeft, width), belowLeft = _b[0], absoluteBelowLeft = _b[1]; // Leave some clearance to the top/bottom var TOP_PADDING = 22; var BOTTOM_PADDING = 22; var fitsAbove = (absoluteAboveTop >= TOP_PADDING); var fitsBelow = (absoluteBelowTop + height <= windowSize.height - BOTTOM_PADDING); if (this._fixedOverflowWidgets) { return { fitsAbove: fitsAbove, aboveTop: Math.max(absoluteAboveTop, TOP_PADDING), aboveLeft: absoluteAboveLeft, fitsBelow: fitsBelow, belowTop: absoluteBelowTop, belowLeft: absoluteBelowLeft }; } return { fitsAbove: fitsAbove, aboveTop: Math.max(aboveTop, TOP_PADDING), aboveLeft: aboveLeft, fitsBelow: fitsBelow, belowTop: belowTop, belowLeft: belowLeft }; }; Widget.prototype._prepareRenderWidgetAtExactPositionOverflowing = function (topLeft) { return new Coordinate(topLeft.top, topLeft.left + this._contentLeft); }; /** * Compute `this._topLeft` */ Widget.prototype._getTopAndBottomLeft = function (ctx) { if (!this._viewRange) { return [null, null]; } var visibleRangesForRange = ctx.linesVisibleRangesForRange(this._viewRange, false); if (!visibleRangesForRange || visibleRangesForRange.length === 0) { return [null, null]; } var firstLine = visibleRangesForRange[0]; var lastLine = visibleRangesForRange[0]; for (var _i = 0, visibleRangesForRange_1 = visibleRangesForRange; _i < visibleRangesForRange_1.length; _i++) { var visibleRangesForLine = visibleRangesForRange_1[_i]; if (visibleRangesForLine.lineNumber < firstLine.lineNumber) { firstLine = visibleRangesForLine; } if (visibleRangesForLine.lineNumber > lastLine.lineNumber) { lastLine = visibleRangesForLine; } } var firstLineMinLeft = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; //firstLine.Constants.MAX_SAFE_SMALL_INTEGER; for (var _a = 0, _b = firstLine.ranges; _a < _b.length; _a++) { var visibleRange = _b[_a]; if (visibleRange.left < firstLineMinLeft) { firstLineMinLeft = visibleRange.left; } } var lastLineMinLeft = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; //lastLine.Constants.MAX_SAFE_SMALL_INTEGER; for (var _c = 0, _d = lastLine.ranges; _c < _d.length; _c++) { var visibleRange = _d[_c]; if (visibleRange.left < lastLineMinLeft) { lastLineMinLeft = visibleRange.left; } } var topForPosition = ctx.getVerticalOffsetForLineNumber(firstLine.lineNumber) - ctx.scrollTop; var topLeft = new Coordinate(topForPosition, firstLineMinLeft); var topForBottomLine = ctx.getVerticalOffsetForLineNumber(lastLine.lineNumber) - ctx.scrollTop; var bottomLeft = new Coordinate(topForBottomLine, lastLineMinLeft); return [topLeft, bottomLeft]; }; Widget.prototype._prepareRenderWidget = function (ctx) { var _a = this._getTopAndBottomLeft(ctx), topLeft = _a[0], bottomLeft = _a[1]; if (!topLeft || !bottomLeft) { return null; } if (this._cachedDomNodeClientWidth === -1 || this._cachedDomNodeClientHeight === -1) { var domNode = this.domNode.domNode; this._cachedDomNodeClientWidth = domNode.clientWidth; this._cachedDomNodeClientHeight = domNode.clientHeight; } var placement; if (this.allowEditorOverflow) { placement = this._layoutBoxInPage(topLeft, bottomLeft, this._cachedDomNodeClientWidth, this._cachedDomNodeClientHeight, ctx); } else { placement = this._layoutBoxInViewport(topLeft, bottomLeft, this._cachedDomNodeClientWidth, this._cachedDomNodeClientHeight, ctx); } // Do two passes, first for perfect fit, second picks first option if (this._preference) { for (var pass = 1; pass <= 2; pass++) { for (var _i = 0, _b = this._preference; _i < _b.length; _i++) { var pref = _b[_i]; // placement if (pref === 1 /* ABOVE */) { if (!placement) { // Widget outside of viewport return null; } if (pass === 2 || placement.fitsAbove) { return new Coordinate(placement.aboveTop, placement.aboveLeft); } } else if (pref === 2 /* BELOW */) { if (!placement) { // Widget outside of viewport return null; } if (pass === 2 || placement.fitsBelow) { return new Coordinate(placement.belowTop, placement.belowLeft); } } else { if (this.allowEditorOverflow) { return this._prepareRenderWidgetAtExactPositionOverflowing(topLeft); } else { return topLeft; } } } } } return null; }; /** * On this first pass, we ensure that the content widget (if it is in the viewport) has the max width set correctly. */ Widget.prototype.onBeforeRender = function (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); }; Widget.prototype.prepareRender = function (ctx) { this._renderData = this._prepareRenderWidget(ctx); }; Widget.prototype.render = function (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'); } return; } // This widget should be visible if (this.allowEditorOverflow) { this.domNode.setTop(this._renderData.top); this.domNode.setLeft(this._renderData.left); } else { this.domNode.setTop(this._renderData.top + ctx.scrollTop - ctx.bigNumbersDelta); this.domNode.setLeft(this._renderData.left); } if (!this._isVisible) { this.domNode.setVisibility('inherit'); this.domNode.setAttribute('monaco-visible-content-widget', 'true'); this._isVisible = true; } }; return 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[367/*vs/editor/browser/viewParts/decorations/decorations*/], __M([0/*require*/,1/*exports*/,82/*vs/editor/browser/view/dynamicViewOverlay*/,3/*vs/editor/common/core/range*/,91/*vs/editor/common/view/renderingContext*/,286/*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 }); var DecorationsOverlay = /** @class */ (function (_super) { __extends(DecorationsOverlay, _super); function DecorationsOverlay(context) { var _this = _super.call(this) || this; _this._context = context; var options = _this._context.configuration.options; _this._lineHeight = options.get(49 /* lineHeight */); _this._typicalHalfwidthCharacterWidth = options.get(34 /* fontInfo */).typicalHalfwidthCharacterWidth; _this._renderResult = null; _this._context.addEventHandler(_this); return _this; } DecorationsOverlay.prototype.dispose = function () { this._context.removeEventHandler(this); this._renderResult = null; _super.prototype.dispose.call(this); }; // --- begin event handlers DecorationsOverlay.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; this._lineHeight = options.get(49 /* lineHeight */); this._typicalHalfwidthCharacterWidth = options.get(34 /* fontInfo */).typicalHalfwidthCharacterWidth; return true; }; DecorationsOverlay.prototype.onDecorationsChanged = function (e) { return true; }; DecorationsOverlay.prototype.onFlushed = function (e) { return true; }; DecorationsOverlay.prototype.onLinesChanged = function (e) { return true; }; DecorationsOverlay.prototype.onLinesDeleted = function (e) { return true; }; DecorationsOverlay.prototype.onLinesInserted = function (e) { return true; }; DecorationsOverlay.prototype.onScrollChanged = function (e) { return e.scrollTopChanged || e.scrollWidthChanged; }; DecorationsOverlay.prototype.onZonesChanged = function (e) { return true; }; // --- end event handlers DecorationsOverlay.prototype.prepareRender = function (ctx) { var _decorations = ctx.getDecorationsInViewport(); // Keep only decorations with `className` var decorations = [], decorationsLen = 0; for (var i = 0, len = _decorations.length; i < len; i++) { var d = _decorations[i]; if (d.options.className) { decorations[decorationsLen++] = d; } } // Sort decorations for consistent render output decorations = decorations.sort(function (a, b) { if (a.options.zIndex < b.options.zIndex) { return -1; } if (a.options.zIndex > b.options.zIndex) { return 1; } var aClassName = a.options.className; var bClassName = b.options.className; if (aClassName < bClassName) { return -1; } if (aClassName > bClassName) { return 1; } return range_1.Range.compareRangesUsingStarts(a.range, b.range); }); var visibleStartLineNumber = ctx.visibleRange.startLineNumber; var visibleEndLineNumber = ctx.visibleRange.endLineNumber; var output = []; for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) { var 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; }; DecorationsOverlay.prototype._renderWholeLineDecorations = function (ctx, decorations, output) { var lineHeight = String(this._lineHeight); var visibleStartLineNumber = ctx.visibleRange.startLineNumber; var visibleEndLineNumber = ctx.visibleRange.endLineNumber; for (var i = 0, lenI = decorations.length; i < lenI; i++) { var d = decorations[i]; if (!d.options.isWholeLine) { continue; } var decorationOutput = ('
    '); var startLineNumber = Math.max(d.range.startLineNumber, visibleStartLineNumber); var endLineNumber = Math.min(d.range.endLineNumber, visibleEndLineNumber); for (var j = startLineNumber; j <= endLineNumber; j++) { var lineIndex = j - visibleStartLineNumber; output[lineIndex] += decorationOutput; } } }; DecorationsOverlay.prototype._renderNormalDecorations = function (ctx, decorations, output) { var lineHeight = String(this._lineHeight); var visibleStartLineNumber = ctx.visibleRange.startLineNumber; var prevClassName = null; var prevShowIfCollapsed = false; var prevRange = null; for (var i = 0, lenI = decorations.length; i < lenI; i++) { var d = decorations[i]; if (d.options.isWholeLine) { continue; } var className = d.options.className; var showIfCollapsed = Boolean(d.options.showIfCollapsed); var 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); } }; DecorationsOverlay.prototype._renderNormalDecoration = function (ctx, range, className, showIfCollapsed, lineHeight, visibleStartLineNumber, output) { var linesVisibleRanges = ctx.linesVisibleRangesForRange(range, /*TODO@Alex*/ className === 'findMatch'); if (!linesVisibleRanges) { return; } for (var j = 0, lenJ = linesVisibleRanges.length; j < lenJ; j++) { var lineVisibleRanges = linesVisibleRanges[j]; if (lineVisibleRanges.outsideRenderedLine) { continue; } var lineIndex = lineVisibleRanges.lineNumber - visibleStartLineNumber; if (showIfCollapsed && lineVisibleRanges.ranges.length === 1) { var singleVisibleRange = lineVisibleRanges.ranges[0]; if (singleVisibleRange.width === 0) { // collapsed range case => make the decoration visible by faking its width lineVisibleRanges.ranges[0] = new renderingContext_1.HorizontalRange(singleVisibleRange.left, this._typicalHalfwidthCharacterWidth); } } for (var k = 0, lenK = lineVisibleRanges.ranges.length; k < lenK; k++) { var visibleRange = lineVisibleRanges.ranges[k]; var decorationOutput = ('
    '); output[lineIndex] += decorationOutput; } } }; DecorationsOverlay.prototype.render = function (startLineNumber, lineNumber) { if (!this._renderResult) { return ''; } var lineIndex = lineNumber - startLineNumber; if (lineIndex < 0 || lineIndex >= this._renderResult.length) { return ''; } return this._renderResult[lineIndex]; }; return DecorationsOverlay; }(dynamicViewOverlay_1.DynamicViewOverlay)); 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[149/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([0/*require*/,1/*exports*/,82/*vs/editor/browser/view/dynamicViewOverlay*/,287/*vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin*/]), function (require, exports, dynamicViewOverlay_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DecorationToRender = /** @class */ (function () { function DecorationToRender(startLineNumber, endLineNumber, className) { this.startLineNumber = +startLineNumber; this.endLineNumber = +endLineNumber; this.className = String(className); } return DecorationToRender; }()); exports.DecorationToRender = DecorationToRender; var DedupOverlay = /** @class */ (function (_super) { __extends(DedupOverlay, _super); function DedupOverlay() { return _super !== null && _super.apply(this, arguments) || this; } DedupOverlay.prototype._render = function (visibleStartLineNumber, visibleEndLineNumber, decorations) { var output = []; for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) { var lineIndex = lineNumber - visibleStartLineNumber; output[lineIndex] = []; } if (decorations.length === 0) { return output; } decorations.sort(function (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); }); var prevClassName = null; var prevEndLineIndex = 0; for (var i = 0, len = decorations.length; i < len; i++) { var d = decorations[i]; var className = d.className; var startLineIndex = Math.max(d.startLineNumber, visibleStartLineNumber) - visibleStartLineNumber; var 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 (var i_1 = startLineIndex; i_1 <= prevEndLineIndex; i_1++) { output[i_1].push(prevClassName); } } return output; }; return DedupOverlay; }(dynamicViewOverlay_1.DynamicViewOverlay)); exports.DedupOverlay = DedupOverlay; var GlyphMarginOverlay = /** @class */ (function (_super) { __extends(GlyphMarginOverlay, _super); function GlyphMarginOverlay(context) { var _this = _super.call(this) || this; _this._context = context; var options = _this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); _this._lineHeight = options.get(49 /* lineHeight */); _this._glyphMargin = options.get(40 /* glyphMargin */); _this._glyphMarginLeft = layoutInfo.glyphMarginLeft; _this._glyphMarginWidth = layoutInfo.glyphMarginWidth; _this._renderResult = null; _this._context.addEventHandler(_this); return _this; } GlyphMarginOverlay.prototype.dispose = function () { this._context.removeEventHandler(this); this._renderResult = null; _super.prototype.dispose.call(this); }; // --- begin event handlers GlyphMarginOverlay.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); this._lineHeight = options.get(49 /* lineHeight */); this._glyphMargin = options.get(40 /* glyphMargin */); this._glyphMarginLeft = layoutInfo.glyphMarginLeft; this._glyphMarginWidth = layoutInfo.glyphMarginWidth; return true; }; GlyphMarginOverlay.prototype.onDecorationsChanged = function (e) { return true; }; GlyphMarginOverlay.prototype.onFlushed = function (e) { return true; }; GlyphMarginOverlay.prototype.onLinesChanged = function (e) { return true; }; GlyphMarginOverlay.prototype.onLinesDeleted = function (e) { return true; }; GlyphMarginOverlay.prototype.onLinesInserted = function (e) { return true; }; GlyphMarginOverlay.prototype.onScrollChanged = function (e) { return e.scrollTopChanged; }; GlyphMarginOverlay.prototype.onZonesChanged = function (e) { return true; }; // --- end event handlers GlyphMarginOverlay.prototype._getDecorations = function (ctx) { var decorations = ctx.getDecorationsInViewport(); var r = [], rLen = 0; for (var i = 0, len = decorations.length; i < len; i++) { var d = decorations[i]; var glyphMarginClassName = d.options.glyphMarginClassName; if (glyphMarginClassName) { r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, glyphMarginClassName); } } return r; }; GlyphMarginOverlay.prototype.prepareRender = function (ctx) { if (!this._glyphMargin) { this._renderResult = null; return; } var visibleStartLineNumber = ctx.visibleRange.startLineNumber; var visibleEndLineNumber = ctx.visibleRange.endLineNumber; var toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx)); var lineHeight = this._lineHeight.toString(); var left = this._glyphMarginLeft.toString(); var width = this._glyphMarginWidth.toString(); var common = '" style="left:' + left + 'px;width:' + width + 'px' + ';height:' + lineHeight + 'px;">'; var output = []; for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) { var lineIndex = lineNumber - visibleStartLineNumber; var classNames = toRender[lineIndex]; if (classNames.length === 0) { output[lineIndex] = ''; } else { output[lineIndex] = (''; var output = []; for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) { var lineIndex = lineNumber - visibleStartLineNumber; var classNames = toRender[lineIndex]; var lineOutput = ''; for (var i = 0, len = classNames.length; i < len; i++) { lineOutput += ''; } output[lineIndex] = lineOutput; } this._renderResult = output; }; MarginViewLineDecorationsOverlay.prototype.render = function (startLineNumber, lineNumber) { if (!this._renderResult) { return ''; } return this._renderResult[lineNumber - startLineNumber]; }; return MarginViewLineDecorationsOverlay; }(glyphMargin_1.DedupOverlay)); 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[370/*vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,37/*vs/editor/browser/view/viewPart*/,294/*vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/]), function (require, exports, fastDomNode_1, viewPart_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ViewOverlayWidgets = /** @class */ (function (_super) { __extends(ViewOverlayWidgets, _super); function ViewOverlayWidgets(context) { var _this = _super.call(this, context) || this; var options = _this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); _this._widgets = {}; _this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth; _this._minimapWidth = layoutInfo.minimapWidth; _this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight; _this._editorHeight = layoutInfo.height; _this._editorWidth = layoutInfo.width; _this._domNode = fastDomNode_1.createFastDomNode(document.createElement('div')); viewPart_1.PartFingerprints.write(_this._domNode, 4 /* OverlayWidgets */); _this._domNode.setClassName('overlayWidgets'); return _this; } ViewOverlayWidgets.prototype.dispose = function () { _super.prototype.dispose.call(this); this._widgets = {}; }; ViewOverlayWidgets.prototype.getDomNode = function () { return this._domNode; }; // ---- begin view event handlers ViewOverlayWidgets.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth; this._minimapWidth = layoutInfo.minimapWidth; this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight; this._editorHeight = layoutInfo.height; this._editorWidth = layoutInfo.width; return true; }; // ---- end view event handlers ViewOverlayWidgets.prototype.addWidget = function (widget) { var domNode = 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(); }; ViewOverlayWidgets.prototype.setWidgetPosition = function (widget, preference) { var widgetData = this._widgets[widget.getId()]; if (widgetData.preference === preference) { return false; } widgetData.preference = preference; this.setShouldRender(); return true; }; ViewOverlayWidgets.prototype.removeWidget = function (widget) { var widgetId = widget.getId(); if (this._widgets.hasOwnProperty(widgetId)) { var widgetData = this._widgets[widgetId]; var domNode = widgetData.domNode.domNode; delete this._widgets[widgetId]; domNode.parentNode.removeChild(domNode); this.setShouldRender(); } }; ViewOverlayWidgets.prototype._renderWidget = function (widgetData) { var 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 */) { var 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%'; } }; ViewOverlayWidgets.prototype.prepareRender = function (ctx) { // Nothing to read }; ViewOverlayWidgets.prototype.render = function (ctx) { this._domNode.setWidth(this._editorWidth); var keys = Object.keys(this._widgets); for (var i = 0, len = keys.length; i < len; i++) { var widgetId = keys[i]; this._renderWidget(this._widgets[widgetId]); } }; return ViewOverlayWidgets; }(viewPart_1.ViewPart)); 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[371/*vs/editor/browser/viewParts/overviewRuler/overviewRuler*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,193/*vs/editor/common/view/overviewZoneManager*/,92/*vs/editor/common/viewModel/viewEventHandler*/]), function (require, exports, fastDomNode_1, overviewZoneManager_1, viewEventHandler_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var OverviewRuler = /** @class */ (function (_super) { __extends(OverviewRuler, _super); function OverviewRuler(context, cssClassName) { var _this = _super.call(this) || this; _this._context = context; var options = _this._context.configuration.options; _this._domNode = 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(function (lineNumber) { return _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(49 /* lineHeight */)); _this._zoneManager.setPixelRatio(options.get(105 /* pixelRatio */)); _this._context.addEventHandler(_this); return _this; } OverviewRuler.prototype.dispose = function () { this._context.removeEventHandler(this); _super.prototype.dispose.call(this); }; // ---- begin view event handlers OverviewRuler.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; if (e.hasChanged(49 /* lineHeight */)) { this._zoneManager.setLineHeight(options.get(49 /* lineHeight */)); this._render(); } if (e.hasChanged(105 /* pixelRatio */)) { this._zoneManager.setPixelRatio(options.get(105 /* 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; }; OverviewRuler.prototype.onFlushed = function (e) { this._render(); return true; }; OverviewRuler.prototype.onScrollChanged = function (e) { if (e.scrollHeightChanged) { this._zoneManager.setOuterHeight(e.scrollHeight); this._render(); } return true; }; OverviewRuler.prototype.onZonesChanged = function (e) { this._render(); return true; }; // ---- end view event handlers OverviewRuler.prototype.getDomNode = function () { return this._domNode.domNode; }; OverviewRuler.prototype.setLayout = function (position) { this._domNode.setTop(position.top); this._domNode.setRight(position.right); var 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(); } }; OverviewRuler.prototype.setZones = function (zones) { this._zoneManager.setZones(zones); this._render(); }; OverviewRuler.prototype._render = function () { if (this._zoneManager.getOuterHeight() === 0) { return false; } var width = this._zoneManager.getCanvasWidth(); var height = this._zoneManager.getCanvasHeight(); var colorZones = this._zoneManager.resolveColorZones(); var id2Color = this._zoneManager.getId2Color(); var ctx = this._domNode.domNode.getContext('2d'); ctx.clearRect(0, 0, width, height); if (colorZones.length > 0) { this._renderOneLane(ctx, colorZones, id2Color, width); } return true; }; OverviewRuler.prototype._renderOneLane = function (ctx, colorZones, id2Color, width) { var currentColorId = 0; var currentFrom = 0; var currentTo = 0; for (var _i = 0, colorZones_1 = colorZones; _i < colorZones_1.length; _i++) { var zone = colorZones_1[_i]; var zoneColorId = zone.colorId; var zoneFrom = zone.from; var 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); }; return OverviewRuler; }(viewEventHandler_1.ViewEventHandler)); 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[372/*vs/editor/browser/viewParts/viewZones/viewZones*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,10/*vs/base/common/errors*/,37/*vs/editor/browser/view/viewPart*/,13/*vs/editor/common/core/position*/]), function (require, exports, fastDomNode_1, errors_1, viewPart_1, position_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var invalidFunc = function () { throw new Error("Invalid change accessor"); }; var ViewZones = /** @class */ (function (_super) { __extends(ViewZones, _super); function ViewZones(context) { var _this = _super.call(this, context) || this; var options = _this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); _this._lineHeight = options.get(49 /* lineHeight */); _this._contentWidth = layoutInfo.contentWidth; _this._contentLeft = layoutInfo.contentLeft; _this.domNode = 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 = 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 = {}; return _this; } ViewZones.prototype.dispose = function () { _super.prototype.dispose.call(this); this._zones = {}; }; // ---- begin view event handlers ViewZones.prototype._recomputeWhitespacesProps = function () { var _this = this; var whitespaces = this._context.viewLayout.getWhitespaces(); var oldWhitespaces = new Map(); for (var _i = 0, whitespaces_1 = whitespaces; _i < whitespaces_1.length; _i++) { var whitespace = whitespaces_1[_i]; oldWhitespaces.set(whitespace.id, whitespace); } return this._context.viewLayout.changeWhitespace(function (whitespaceAccessor) { var hadAChange = false; var keys = Object.keys(_this._zones); for (var i = 0, len = keys.length; i < len; i++) { var id = keys[i]; var zone = _this._zones[id]; var props = _this._computeWhitespaceProps(zone.delegate); var 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; }); }; ViewZones.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); this._lineHeight = options.get(49 /* lineHeight */); this._contentWidth = layoutInfo.contentWidth; this._contentLeft = layoutInfo.contentLeft; if (e.hasChanged(49 /* lineHeight */)) { this._recomputeWhitespacesProps(); } return true; }; ViewZones.prototype.onLineMappingChanged = function (e) { var hadAChange = this._recomputeWhitespacesProps(); if (hadAChange) { this._context.viewLayout.onHeightMaybeChanged(); } return hadAChange; }; ViewZones.prototype.onLinesDeleted = function (e) { return true; }; ViewZones.prototype.onScrollChanged = function (e) { return e.scrollTopChanged || e.scrollWidthChanged; }; ViewZones.prototype.onZonesChanged = function (e) { return true; }; ViewZones.prototype.onLinesInserted = function (e) { return true; }; // ---- end view event handlers ViewZones.prototype._getZoneOrdinal = function (zone) { if (typeof zone.afterColumn !== 'undefined') { return zone.afterColumn; } return 10000; }; ViewZones.prototype._computeWhitespaceProps = function (zone) { if (zone.afterLineNumber === 0) { return { afterViewLineNumber: 0, heightInPx: this._heightInPixels(zone), minWidthInPx: this._minWidthInPixels(zone) }; } var zoneAfterModelPosition; if (typeof zone.afterColumn !== 'undefined') { zoneAfterModelPosition = this._context.model.validateModelPosition({ lineNumber: zone.afterLineNumber, column: zone.afterColumn }); } else { var validAfterLineNumber = this._context.model.validateModelPosition({ lineNumber: zone.afterLineNumber, column: 1 }).lineNumber; zoneAfterModelPosition = new position_1.Position(validAfterLineNumber, this._context.model.getModelLineMaxColumn(validAfterLineNumber)); } var 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 }); } var viewPosition = this._context.model.coordinatesConverter.convertModelPositionToViewPosition(zoneAfterModelPosition); var isVisible = this._context.model.coordinatesConverter.modelPositionIsVisible(zoneBeforeModelPosition); return { afterViewLineNumber: viewPosition.lineNumber, heightInPx: (isVisible ? this._heightInPixels(zone) : 0), minWidthInPx: this._minWidthInPixels(zone) }; }; ViewZones.prototype.changeViewZones = function (callback) { var _this = this; return this._context.viewLayout.changeWhitespace(function (whitespaceAccessor) { var zonesHaveChanged = false; var changeAccessor = { addZone: function (zone) { zonesHaveChanged = true; return _this._addZone(whitespaceAccessor, zone); }, removeZone: function (id) { if (!id) { return; } zonesHaveChanged = _this._removeZone(whitespaceAccessor, id) || zonesHaveChanged; }, layoutZone: function (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; }); }; ViewZones.prototype._addZone = function (whitespaceAccessor, zone) { var props = this._computeWhitespaceProps(zone); var whitespaceId = whitespaceAccessor.insertWhitespace(props.afterViewLineNumber, this._getZoneOrdinal(zone), props.heightInPx, props.minWidthInPx); var myZone = { whitespaceId: whitespaceId, delegate: zone, isVisible: false, domNode: fastDomNode_1.createFastDomNode(zone.domNode), marginDomNode: zone.marginDomNode ? 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; }; ViewZones.prototype._removeZone = function (whitespaceAccessor, id) { if (this._zones.hasOwnProperty(id)) { var 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; }; ViewZones.prototype._layoutZone = function (whitespaceAccessor, id) { if (this._zones.hasOwnProperty(id)) { var zone = this._zones[id]; var props = this._computeWhitespaceProps(zone.delegate); // const newOrdinal = this._getZoneOrdinal(zone.delegate); whitespaceAccessor.changeOneWhitespace(zone.whitespaceId, props.afterViewLineNumber, props.heightInPx); // TODO@Alex: change `newOrdinal` too this._safeCallOnComputedHeight(zone.delegate, props.heightInPx); this.setShouldRender(); return true; } return false; }; ViewZones.prototype.shouldSuppressMouseDownOnViewZone = function (id) { if (this._zones.hasOwnProperty(id)) { var zone = this._zones[id]; return Boolean(zone.delegate.suppressMouseDown); } return false; }; ViewZones.prototype._heightInPixels = function (zone) { if (typeof zone.heightInPx === 'number') { return zone.heightInPx; } if (typeof zone.heightInLines === 'number') { return this._lineHeight * zone.heightInLines; } return this._lineHeight; }; ViewZones.prototype._minWidthInPixels = function (zone) { if (typeof zone.minWidthInPx === 'number') { return zone.minWidthInPx; } return 0; }; ViewZones.prototype._safeCallOnComputedHeight = function (zone, height) { if (typeof zone.onComputedHeight === 'function') { try { zone.onComputedHeight(height); } catch (e) { errors_1.onUnexpectedError(e); } } }; ViewZones.prototype._safeCallOnDomNodeTop = function (zone, top) { if (typeof zone.onDomNodeTop === 'function') { try { zone.onDomNodeTop(top); } catch (e) { errors_1.onUnexpectedError(e); } } }; ViewZones.prototype.prepareRender = function (ctx) { // Nothing to read }; ViewZones.prototype.render = function (ctx) { var visibleWhitespaces = ctx.viewportData.whitespaceViewportData; var visibleZones = {}; var hasVisibleZone = false; for (var i = 0, len = visibleWhitespaces.length; i < len; i++) { visibleZones[visibleWhitespaces[i].id] = visibleWhitespaces[i]; hasVisibleZone = true; } var keys = Object.keys(this._zones); for (var i = 0, len = keys.length; i < len; i++) { var id = keys[i]; var zone = this._zones[id]; var newTop = 0; var newHeight = 0; var 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); } }; return ViewZones; }(viewPart_1.ViewPart)); exports.ViewZones = ViewZones; function safeInvoke1Arg(func, arg1) { try { return func(arg1); } catch (e) { 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[69/*vs/editor/common/viewModel/viewModel*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/]), function (require, exports, strings) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Viewport = /** @class */ (function () { function Viewport(top, left, width, height) { this.top = top | 0; this.left = left | 0; this.width = width | 0; this.height = height | 0; } return Viewport; }()); exports.Viewport = Viewport; var MinimapLinesRenderingData = /** @class */ (function () { function MinimapLinesRenderingData(tabSize, data) { this.tabSize = tabSize; this.data = data; } return MinimapLinesRenderingData; }()); exports.MinimapLinesRenderingData = MinimapLinesRenderingData; var ViewLineData = /** @class */ (function () { function ViewLineData(content, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens) { this.content = content; this.continuesWithWrappedLine = continuesWithWrappedLine; this.minColumn = minColumn; this.maxColumn = maxColumn; this.startVisibleColumn = startVisibleColumn; this.tokens = tokens; } return ViewLineData; }()); exports.ViewLineData = ViewLineData; var ViewLineRenderingData = /** @class */ (function () { function ViewLineRenderingData(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; } ViewLineRenderingData.isBasicASCII = function (lineContent, mightContainNonBasicASCII) { if (mightContainNonBasicASCII) { return strings.isBasicASCII(lineContent); } return true; }; ViewLineRenderingData.containsRTL = function (lineContent, isBasicASCII, mightContainRTL) { if (!isBasicASCII && mightContainRTL) { return strings.containsRTL(lineContent); } return false; }; return ViewLineRenderingData; }()); exports.ViewLineRenderingData = ViewLineRenderingData; var InlineDecoration = /** @class */ (function () { function InlineDecoration(range, inlineClassName, type) { this.range = range; this.inlineClassName = inlineClassName; this.type = type; } return InlineDecoration; }()); exports.InlineDecoration = InlineDecoration; var ViewModelDecoration = /** @class */ (function () { function ViewModelDecoration(range, options) { this.range = range; this.options = options; } return ViewModelDecoration; }()); exports.ViewModelDecoration = ViewModelDecoration; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[373/*vs/editor/common/viewLayout/viewLayout*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,176/*vs/base/common/scrollable*/,362/*vs/editor/common/viewLayout/linesLayout*/,69/*vs/editor/common/viewModel/viewModel*/]), function (require, exports, event_1, lifecycle_1, scrollable_1, linesLayout_1, viewModel_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var SMOOTH_SCROLLING_TIME = 125; var EditorScrollDimensions = /** @class */ (function () { function EditorScrollDimensions(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); } EditorScrollDimensions.prototype.equals = function (other) { return (this.width === other.width && this.contentWidth === other.contentWidth && this.height === other.height && this.contentHeight === other.contentHeight); }; return EditorScrollDimensions; }()); var EditorScrollable = /** @class */ (function (_super) { __extends(EditorScrollable, _super); function EditorScrollable(smoothScrollDuration, scheduleAtNextAnimationFrame) { var _this = _super.call(this) || this; _this._onDidContentSizeChange = _this._register(new event_1.Emitter()); _this.onDidContentSizeChange = _this._onDidContentSizeChange.event; _this._dimensions = new EditorScrollDimensions(0, 0, 0, 0); _this._scrollable = _this._register(new scrollable_1.Scrollable(smoothScrollDuration, scheduleAtNextAnimationFrame)); _this.onDidScroll = _this._scrollable.onScroll; return _this; } EditorScrollable.prototype.getScrollable = function () { return this._scrollable; }; EditorScrollable.prototype.setSmoothScrollDuration = function (smoothScrollDuration) { this._scrollable.setSmoothScrollDuration(smoothScrollDuration); }; EditorScrollable.prototype.validateScrollPosition = function (scrollPosition) { return this._scrollable.validateScrollPosition(scrollPosition); }; EditorScrollable.prototype.getScrollDimensions = function () { return this._dimensions; }; EditorScrollable.prototype.setScrollDimensions = function (dimensions) { if (this._dimensions.equals(dimensions)) { return; } var oldDimensions = this._dimensions; this._dimensions = dimensions; this._scrollable.setScrollDimensions({ width: dimensions.width, scrollWidth: dimensions.scrollWidth, height: dimensions.height, scrollHeight: dimensions.scrollHeight }); var contentWidthChanged = (oldDimensions.contentWidth !== dimensions.contentWidth); var contentHeightChanged = (oldDimensions.contentHeight !== dimensions.contentHeight); if (contentWidthChanged || contentHeightChanged) { this._onDidContentSizeChange.fire({ contentWidth: dimensions.contentWidth, contentHeight: dimensions.contentHeight, contentWidthChanged: contentWidthChanged, contentHeightChanged: contentHeightChanged }); } }; EditorScrollable.prototype.getFutureScrollPosition = function () { return this._scrollable.getFutureScrollPosition(); }; EditorScrollable.prototype.getCurrentScrollPosition = function () { return this._scrollable.getCurrentScrollPosition(); }; EditorScrollable.prototype.setScrollPositionNow = function (update) { this._scrollable.setScrollPositionNow(update); }; EditorScrollable.prototype.setScrollPositionSmooth = function (update) { this._scrollable.setScrollPositionSmooth(update); }; return EditorScrollable; }(lifecycle_1.Disposable)); var ViewLayout = /** @class */ (function (_super) { __extends(ViewLayout, _super); function ViewLayout(configuration, lineCount, scheduleAtNextAnimationFrame) { var _this = _super.call(this) || this; _this._configuration = configuration; var options = _this._configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); _this._linesLayout = new linesLayout_1.LinesLayout(lineCount, options.get(49 /* lineHeight */)); _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(); return _this; } ViewLayout.prototype.dispose = function () { _super.prototype.dispose.call(this); }; ViewLayout.prototype.getScrollable = function () { return this._scrollable.getScrollable(); }; ViewLayout.prototype.onHeightMaybeChanged = function () { this._updateHeight(); }; ViewLayout.prototype._configureSmoothScrollDuration = function () { this._scrollable.setSmoothScrollDuration(this._configuration.options.get(87 /* smoothScrolling */) ? SMOOTH_SCROLLING_TIME : 0); }; // ---- begin view event handlers ViewLayout.prototype.onConfigurationChanged = function (e) { var options = this._configuration.options; if (e.hasChanged(49 /* lineHeight */)) { this._linesLayout.setLineHeight(options.get(49 /* lineHeight */)); } if (e.hasChanged(107 /* layoutInfo */)) { var layoutInfo = options.get(107 /* layoutInfo */); var width = layoutInfo.contentWidth; var height = layoutInfo.height; var scrollDimensions = this._scrollable.getScrollDimensions(); var scrollWidth = scrollDimensions.scrollWidth; this._scrollable.setScrollDimensions(new EditorScrollDimensions(width, scrollDimensions.contentWidth, height, this._getContentHeight(width, height, scrollWidth))); } else { this._updateHeight(); } if (e.hasChanged(87 /* smoothScrolling */)) { this._configureSmoothScrollDuration(); } }; ViewLayout.prototype.onFlushed = function (lineCount) { this._linesLayout.onFlushed(lineCount); }; ViewLayout.prototype.onLinesDeleted = function (fromLineNumber, toLineNumber) { this._linesLayout.onLinesDeleted(fromLineNumber, toLineNumber); }; ViewLayout.prototype.onLinesInserted = function (fromLineNumber, toLineNumber) { this._linesLayout.onLinesInserted(fromLineNumber, toLineNumber); }; // ---- end view event handlers ViewLayout.prototype._getHorizontalScrollbarHeight = function (width, scrollWidth) { var options = this._configuration.options; var scrollbar = options.get(78 /* scrollbar */); if (scrollbar.horizontal === 2 /* Hidden */) { // horizontal scrollbar not visible return 0; } if (width >= scrollWidth) { // horizontal scrollbar not visible return 0; } return scrollbar.horizontalScrollbarSize; }; ViewLayout.prototype._getContentHeight = function (width, height, scrollWidth) { var options = this._configuration.options; var result = this._linesLayout.getLinesTotalHeight(); if (options.get(80 /* scrollBeyondLastLine */)) { result += height - options.get(49 /* lineHeight */); } else { result += this._getHorizontalScrollbarHeight(width, scrollWidth); } return result; }; ViewLayout.prototype._updateHeight = function () { var scrollDimensions = this._scrollable.getScrollDimensions(); var width = scrollDimensions.width; var height = scrollDimensions.height; var scrollWidth = scrollDimensions.scrollWidth; this._scrollable.setScrollDimensions(new EditorScrollDimensions(width, scrollDimensions.contentWidth, height, this._getContentHeight(width, height, scrollWidth))); }; // ---- Layouting logic ViewLayout.prototype.getCurrentViewport = function () { var scrollDimensions = this._scrollable.getScrollDimensions(); var currentScrollPosition = this._scrollable.getCurrentScrollPosition(); return new viewModel_1.Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height); }; ViewLayout.prototype.getFutureViewport = function () { var scrollDimensions = this._scrollable.getScrollDimensions(); var currentScrollPosition = this._scrollable.getFutureScrollPosition(); return new viewModel_1.Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height); }; ViewLayout.prototype._computeContentWidth = function (maxLineWidth) { var options = this._configuration.options; var wrappingInfo = options.get(108 /* wrappingInfo */); var fontInfo = options.get(34 /* fontInfo */); if (wrappingInfo.isViewportWrapping) { var layoutInfo = options.get(107 /* layoutInfo */); var minimap = options.get(54 /* 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 { var extraHorizontalSpace = options.get(79 /* scrollBeyondLastColumn */) * fontInfo.typicalHalfwidthCharacterWidth; var whitespaceMinWidth = this._linesLayout.getWhitespaceMinWidth(); return Math.max(maxLineWidth + extraHorizontalSpace, whitespaceMinWidth); } }; ViewLayout.prototype.onMaxLineWidthChanged = function (maxLineWidth) { var 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 ViewLayout.prototype.saveState = function () { var currentScrollPosition = this._scrollable.getFutureScrollPosition(); var scrollTop = currentScrollPosition.scrollTop; var firstLineNumberInViewport = this._linesLayout.getLineNumberAtOrAfterVerticalOffset(scrollTop); var whitespaceAboveFirstLine = this._linesLayout.getWhitespaceAccumulatedHeightBeforeLineNumber(firstLineNumberInViewport); return { scrollTop: scrollTop, scrollTopWithoutViewZones: scrollTop - whitespaceAboveFirstLine, scrollLeft: currentScrollPosition.scrollLeft }; }; // ---- IVerticalLayoutProvider ViewLayout.prototype.changeWhitespace = function (callback) { return this._linesLayout.changeWhitespace(callback); }; ViewLayout.prototype.getVerticalOffsetForLineNumber = function (lineNumber) { return this._linesLayout.getVerticalOffsetForLineNumber(lineNumber); }; ViewLayout.prototype.isAfterLines = function (verticalOffset) { return this._linesLayout.isAfterLines(verticalOffset); }; ViewLayout.prototype.getLineNumberAtVerticalOffset = function (verticalOffset) { return this._linesLayout.getLineNumberAtOrAfterVerticalOffset(verticalOffset); }; ViewLayout.prototype.getWhitespaceAtVerticalOffset = function (verticalOffset) { return this._linesLayout.getWhitespaceAtVerticalOffset(verticalOffset); }; ViewLayout.prototype.getLinesViewportData = function () { var visibleBox = this.getCurrentViewport(); return this._linesLayout.getLinesViewportData(visibleBox.top, visibleBox.top + visibleBox.height); }; ViewLayout.prototype.getLinesViewportDataAtScrollTop = function (scrollTop) { // do some minimal validations on scrollTop var 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); }; ViewLayout.prototype.getWhitespaceViewportData = function () { var visibleBox = this.getCurrentViewport(); return this._linesLayout.getWhitespaceViewportData(visibleBox.top, visibleBox.top + visibleBox.height); }; ViewLayout.prototype.getWhitespaces = function () { return this._linesLayout.getWhitespaces(); }; // ---- IScrollingProvider ViewLayout.prototype.getContentWidth = function () { var scrollDimensions = this._scrollable.getScrollDimensions(); return scrollDimensions.contentWidth; }; ViewLayout.prototype.getScrollWidth = function () { var scrollDimensions = this._scrollable.getScrollDimensions(); return scrollDimensions.scrollWidth; }; ViewLayout.prototype.getContentHeight = function () { var scrollDimensions = this._scrollable.getScrollDimensions(); return scrollDimensions.contentHeight; }; ViewLayout.prototype.getScrollHeight = function () { var scrollDimensions = this._scrollable.getScrollDimensions(); return scrollDimensions.scrollHeight; }; ViewLayout.prototype.getCurrentScrollLeft = function () { var currentScrollPosition = this._scrollable.getCurrentScrollPosition(); return currentScrollPosition.scrollLeft; }; ViewLayout.prototype.getCurrentScrollTop = function () { var currentScrollPosition = this._scrollable.getCurrentScrollPosition(); return currentScrollPosition.scrollTop; }; ViewLayout.prototype.validateScrollPosition = function (scrollPosition) { return this._scrollable.validateScrollPosition(scrollPosition); }; ViewLayout.prototype.setScrollPositionNow = function (position) { this._scrollable.setScrollPositionNow(position); }; ViewLayout.prototype.setScrollPositionSmooth = function (position) { this._scrollable.setScrollPositionSmooth(position); }; ViewLayout.prototype.deltaScrollNow = function (deltaScrollLeft, deltaScrollTop) { var currentScrollPosition = this._scrollable.getCurrentScrollPosition(); this._scrollable.setScrollPositionNow({ scrollLeft: currentScrollPosition.scrollLeft + deltaScrollLeft, scrollTop: currentScrollPosition.scrollTop + deltaScrollTop }); }; return ViewLayout; }(lifecycle_1.Disposable)); 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[374/*vs/editor/contrib/caretOperations/moveCaretCommand*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/]), function (require, exports, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MoveCaretCommand = /** @class */ (function () { function MoveCaretCommand(selection, isMovingLeft) { this._selection = selection; this._isMovingLeft = isMovingLeft; this._cutStartIndex = -1; this._cutEndIndex = -1; this._moved = false; this._selectionId = null; } MoveCaretCommand.prototype.getEditOperations = function (model, builder) { var s = this._selection; this._selectionId = builder.trackSelection(s); if (s.startLineNumber !== s.endLineNumber) { return; } if (this._isMovingLeft && s.startColumn === 0) { return; } else if (!this._isMovingLeft && s.endColumn === model.getLineMaxColumn(s.startLineNumber)) { return; } var lineNumber = s.selectionStartLineNumber; var lineContent = model.getLineContent(lineNumber); var left; var middle; var right; if (this._isMovingLeft) { left = lineContent.substring(0, s.startColumn - 2); middle = lineContent.substring(s.startColumn - 1, s.endColumn - 1); right = lineContent.substring(s.startColumn - 2, s.startColumn - 1) + lineContent.substring(s.endColumn - 1); } else { left = lineContent.substring(0, s.startColumn - 1) + lineContent.substring(s.endColumn - 1, s.endColumn); middle = lineContent.substring(s.startColumn - 1, s.endColumn - 1); right = lineContent.substring(s.endColumn); } var newLineContent = left + middle + right; builder.addEditOperation(new range_1.Range(lineNumber, 1, lineNumber, model.getLineMaxColumn(lineNumber)), null); builder.addEditOperation(new range_1.Range(lineNumber, 1, lineNumber, 1), newLineContent); this._cutStartIndex = s.startColumn + (this._isMovingLeft ? -1 : 1); this._cutEndIndex = this._cutStartIndex + s.endColumn - s.startColumn; this._moved = true; }; MoveCaretCommand.prototype.computeCursorState = function (model, helper) { var result = helper.getTrackedSelection(this._selectionId); if (this._moved) { result = result.setStartPosition(result.startLineNumber, this._cutStartIndex); result = result.setEndPosition(result.startLineNumber, this._cutEndIndex); } return result; }; return MoveCaretCommand; }()); 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[111/*vs/editor/contrib/codeAction/types*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/]), function (require, exports, strings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CodeActionKind = /** @class */ (function () { function CodeActionKind(value) { this.value = value; } CodeActionKind.prototype.equals = function (other) { return this.value === other.value; }; CodeActionKind.prototype.contains = function (other) { return this.equals(other) || this.value === '' || strings_1.startsWith(other.value, this.value + CodeActionKind.sep); }; CodeActionKind.prototype.intersects = function (other) { return this.contains(other) || other.contains(this); }; CodeActionKind.prototype.append = function (part) { return new CodeActionKind(this.value + CodeActionKind.sep + part); }; 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'); return CodeActionKind; }()); exports.CodeActionKind = CodeActionKind; 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(function (exclude) { return 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) { var 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(function (exclude) { return 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; } var CodeActionCommandArgs = /** @class */ (function () { function CodeActionCommandArgs(kind, apply, preferred) { this.kind = kind; this.apply = apply; this.preferred = preferred; } CodeActionCommandArgs.fromUser = function (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)); }; CodeActionCommandArgs.getApplyFromUser = function (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; } }; CodeActionCommandArgs.getKindFromUser = function (arg, defaultKind) { return typeof arg.kind === 'string' ? new CodeActionKind(arg.kind) : defaultKind; }; CodeActionCommandArgs.getPreferredUser = function (arg) { return typeof arg.preferred === 'boolean' ? arg.preferred : false; }; return CodeActionCommandArgs; }()); 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[375/*vs/editor/contrib/colorPicker/colorPickerModel*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/]), function (require, exports, event_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ColorPickerModel = /** @class */ (function () { function ColorPickerModel(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; } Object.defineProperty(ColorPickerModel.prototype, "color", { get: function () { return this._color; }, set: function (color) { if (this._color.equals(color)) { return; } this._color = color; this._onDidChangeColor.fire(color); }, enumerable: true, configurable: true }); Object.defineProperty(ColorPickerModel.prototype, "presentation", { get: function () { return this.colorPresentations[this.presentationIndex]; }, enumerable: true, configurable: true }); Object.defineProperty(ColorPickerModel.prototype, "colorPresentations", { get: function () { return this._colorPresentations; }, set: function (colorPresentations) { this._colorPresentations = colorPresentations; if (this.presentationIndex > colorPresentations.length - 1) { this.presentationIndex = 0; } this._onDidChangePresentation.fire(this.presentation); }, enumerable: true, configurable: true }); ColorPickerModel.prototype.selectNextColorPresentation = function () { this.presentationIndex = (this.presentationIndex + 1) % this.colorPresentations.length; this.flushColor(); this._onDidChangePresentation.fire(this.presentation); }; ColorPickerModel.prototype.guessColorPresentation = function (color, originalText) { for (var i = 0; i < this.colorPresentations.length; i++) { if (originalText === this.colorPresentations[i].label) { this.presentationIndex = i; this._onDidChangePresentation.fire(this.presentation); break; } } }; ColorPickerModel.prototype.flushColor = function () { this._onColorFlushed.fire(this._color); }; return ColorPickerModel; }()); 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[196/*vs/editor/contrib/comment/blockCommentCommand*/], __M([0/*require*/,1/*exports*/,58/*vs/editor/common/core/editOperation*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, editOperation_1, position_1, range_1, selection_1, languageConfigurationRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var BlockCommentCommand = /** @class */ (function () { function BlockCommentCommand(selection, insertSpace) { this._selection = selection; this._insertSpace = insertSpace; this._usedEndToken = null; } BlockCommentCommand._haystackHasNeedleAtOffset = function (haystack, needle, offset) { if (offset < 0) { return false; } var needleLength = needle.length; var haystackLength = haystack.length; if (offset + needleLength > haystackLength) { return false; } for (var i = 0; i < needleLength; i++) { var codeA = haystack.charCodeAt(offset + i); var 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; }; BlockCommentCommand.prototype._createOperationsForBlockComment = function (selection, startToken, endToken, insertSpace, model, builder) { var startLineNumber = selection.startLineNumber; var startColumn = selection.startColumn; var endLineNumber = selection.endLineNumber; var endColumn = selection.endColumn; var startLineText = model.getLineContent(startLineNumber); var endLineText = model.getLineContent(endLineNumber); var startTokenIndex = startLineText.lastIndexOf(startToken, startColumn - 1 + startToken.length); var endTokenIndex = endLineText.indexOf(endToken, endColumn - 1 - endToken.length); if (startTokenIndex !== -1 && endTokenIndex !== -1) { if (startLineNumber === endLineNumber) { var lineBetweenTokens = startLineText.substring(startTokenIndex + startToken.length, endTokenIndex); if (lineBetweenTokens.indexOf(endToken) >= 0) { // force to add a block comment startTokenIndex = -1; endTokenIndex = -1; } } else { var startLineAfterStartToken = startLineText.substring(startTokenIndex + startToken.length); var endLineBeforeEndToken = endLineText.substring(0, endTokenIndex); if (startLineAfterStartToken.indexOf(endToken) >= 0 || endLineBeforeEndToken.indexOf(endToken) >= 0) { // force to add a block comment startTokenIndex = -1; endTokenIndex = -1; } } } var 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 (var _i = 0, ops_1 = ops; _i < ops_1.length; _i++) { var op = ops_1[_i]; builder.addTrackedEditOperation(op.range, op.text); } }; BlockCommentCommand._createRemoveBlockCommentOperations = function (r, startToken, endToken) { var 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; }; BlockCommentCommand._createAddBlockCommentOperations = function (r, startToken, endToken, insertSpace) { var 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; }; BlockCommentCommand.prototype.getEditOperations = function (model, builder) { var startLineNumber = this._selection.startLineNumber; var startColumn = this._selection.startColumn; model.tokenizeIfCheap(startLineNumber); var languageId = model.getLanguageIdAtPosition(startLineNumber, startColumn); var config = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getComments(languageId); if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) { // Mode does not support block comments return; } this._createOperationsForBlockComment(this._selection, config.blockCommentStartToken, config.blockCommentEndToken, this._insertSpace, model, builder); }; BlockCommentCommand.prototype.computeCursorState = function (model, helper) { var inverseEditOperations = helper.getInverseEditOperations(); if (inverseEditOperations.length === 2) { var startTokenEditOperation = inverseEditOperations[0]; var endTokenEditOperation = inverseEditOperations[1]; return new selection_1.Selection(startTokenEditOperation.range.endLineNumber, startTokenEditOperation.range.endColumn, endTokenEditOperation.range.startLineNumber, endTokenEditOperation.range.startColumn); } else { var srcRange = inverseEditOperations[0].range; var 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); } }; return BlockCommentCommand; }()); 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[376/*vs/editor/contrib/comment/lineCommentCommand*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,58/*vs/editor/common/core/editOperation*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/,196/*vs/editor/contrib/comment/blockCommentCommand*/]), function (require, exports, strings, editOperation_1, position_1, range_1, selection_1, languageConfigurationRegistry_1, blockCommentCommand_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LineCommentCommand = /** @class */ (function () { function LineCommentCommand(selection, tabSize, type, insertSpace) { this._selection = selection; this._tabSize = tabSize; this._type = type; this._insertSpace = insertSpace; this._selectionId = null; this._deltaColumn = 0; this._moveEndPositionDown = 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. */ LineCommentCommand._gatherPreflightCommentStrings = function (model, startLineNumber, endLineNumber) { model.tokenizeIfCheap(startLineNumber); var languageId = model.getLanguageIdAtPosition(startLineNumber, 1); var config = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getComments(languageId); var commentStr = (config ? config.lineCommentToken : null); if (!commentStr) { // Mode does not support line comments return null; } var lines = []; for (var 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. */ LineCommentCommand._analyzeLines = function (type, insertSpace, model, lines, startLineNumber) { var onlyWhitespaceLines = true; var shouldRemoveComments; if (type === 0 /* Toggle */) { shouldRemoveComments = true; } else if (type === 1 /* ForceAdd */) { shouldRemoveComments = false; } else { shouldRemoveComments = true; } for (var i = 0, lineCount = lines.length; i < lineCount; i++) { var lineData = lines[i]; var lineNumber = startLineNumber + i; var lineContent = model.getLineContent(lineNumber); var lineContentStartOffset = strings.firstNonWhitespaceIndex(lineContent); if (lineContentStartOffset === -1) { // Empty or whitespace only line if (type === 0 /* Toggle */) { lineData.ignore = true; } else if (type === 1 /* ForceAdd */) { lineData.ignore = true; } else { lineData.ignore = true; } 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 var 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 (var 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 */ LineCommentCommand._gatherPreflightData = function (type, insertSpace, model, startLineNumber, endLineNumber) { var lines = LineCommentCommand._gatherPreflightCommentStrings(model, startLineNumber, endLineNumber); if (lines === null) { return { supported: false }; } return LineCommentCommand._analyzeLines(type, insertSpace, model, lines, startLineNumber); }; /** * Given a successful analysis, execute either insert line comments, either remove line comments */ LineCommentCommand.prototype._executeLineComments = function (model, builder, data, s) { var 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); } var cursorPosition = new position_1.Position(s.positionLineNumber, s.positionColumn); for (var i = 0, len = ops.length; i < len; i++) { builder.addEditOperation(ops[i].range, ops[i].text); if (ops[i].range.isEmpty() && ops[i].range.getStartPosition().equals(cursorPosition)) { var lineContent = model.getLineContent(cursorPosition.lineNumber); if (lineContent.length + 1 === cursorPosition.column) { this._deltaColumn = (ops[i].text || '').length; } } } this._selectionId = builder.trackSelection(s); }; LineCommentCommand.prototype._attemptRemoveBlockComment = function (model, s, startToken, endToken) { var startLineNumber = s.startLineNumber; var endLineNumber = s.endLineNumber; var startTokenAllowedBeforeColumn = endToken.length + Math.max(model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.startColumn); var startTokenIndex = model.getLineContent(startLineNumber).lastIndexOf(startToken, startTokenAllowedBeforeColumn - 1); var 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 */ LineCommentCommand.prototype._executeBlockComment = function (model, builder, s) { model.tokenizeIfCheap(s.startLineNumber); var languageId = model.getLanguageIdAtPosition(s.startLineNumber, 1); var config = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getComments(languageId); if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) { // Mode does not support block comments return; } var startToken = config.blockCommentStartToken; var endToken = config.blockCommentEndToken; var ops = this._attemptRemoveBlockComment(model, s, startToken, endToken); if (!ops) { if (s.isEmpty()) { var lineContent = model.getLineContent(s.startLineNumber); var 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 (var _i = 0, ops_1 = ops; _i < ops_1.length; _i++) { var op = ops_1[_i]; builder.addEditOperation(op.range, op.text); } }; LineCommentCommand.prototype.getEditOperations = function (model, builder) { var s = this._selection; this._moveEndPositionDown = false; if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) { this._moveEndPositionDown = true; s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1)); } var data = LineCommentCommand._gatherPreflightData(this._type, this._insertSpace, model, s.startLineNumber, s.endLineNumber); if (data.supported) { return this._executeLineComments(model, builder, data, s); } return this._executeBlockComment(model, builder, s); }; LineCommentCommand.prototype.computeCursorState = function (model, helper) { var 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 */ LineCommentCommand._createRemoveLineCommentsOperations = function (lines, startLineNumber) { var res = []; for (var i = 0, len = lines.length; i < len; i++) { var 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 */ LineCommentCommand.prototype._createAddLineCommentsOperations = function (lines, startLineNumber) { var res = []; var afterCommentStr = this._insertSpace ? ' ' : ''; for (var i = 0, len = lines.length; i < len; i++) { var 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; }; LineCommentCommand.nextVisibleColumn = function (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 */ LineCommentCommand._normalizeInsertionPoint = function (model, lines, startLineNumber, tabSize) { var minVisibleColumn = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; var j; var lenJ; for (var i = 0, len = lines.length; i < len; i++) { if (lines[i].ignore) { continue; } var lineContent = model.getLineContent(startLineNumber + i); var currentVisibleColumn = 0; for (var j_1 = 0, lenJ_1 = lines[i].commentStrOffset; currentVisibleColumn < minVisibleColumn && j_1 < lenJ_1; j_1++) { currentVisibleColumn = LineCommentCommand.nextVisibleColumn(currentVisibleColumn, tabSize, lineContent.charCodeAt(j_1) === 9 /* Tab */, 1); } if (currentVisibleColumn < minVisibleColumn) { minVisibleColumn = currentVisibleColumn; } } minVisibleColumn = Math.floor(minVisibleColumn / tabSize) * tabSize; for (var i = 0, len = lines.length; i < len; i++) { if (lines[i].ignore) { continue; } var lineContent = model.getLineContent(startLineNumber + i); var 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; } } }; return LineCommentCommand; }()); 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[377/*vs/editor/contrib/dnd/dragAndDropCommand*/], __M([0/*require*/,1/*exports*/,22/*vs/editor/common/core/selection*/,3/*vs/editor/common/core/range*/]), function (require, exports, selection_1, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DragAndDropCommand = /** @class */ (function () { function DragAndDropCommand(selection, targetPosition, copy) { this.selection = selection; this.targetPosition = targetPosition; this.copy = copy; this.targetSelection = null; } DragAndDropCommand.prototype.getEditOperations = function (model, builder) { var 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); } }; DragAndDropCommand.prototype.computeCursorState = function (model, helper) { return this.targetSelection; }; return DragAndDropCommand; }()); 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[378/*vs/editor/contrib/find/findState*/], __M([0/*require*/,1/*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 }); function effectiveOptionValue(override, value) { if (override === 1 /* True */) { return true; } if (override === 2 /* False */) { return false; } return value; } var FindReplaceState = /** @class */ (function (_super) { __extends(FindReplaceState, _super); function FindReplaceState() { var _this = _super.call(this) || this; _this._onFindReplaceStateChange = _this._register(new event_1.Emitter()); _this.onFindReplaceStateChange = _this._onFindReplaceStateChange.event; _this._searchString = ''; _this._replaceString = ''; _this._isRevealed = false; _this._isReplaceRevealed = false; _this._isRegex = false; _this._isRegexOverride = 0 /* NotSet */; _this._wholeWord = false; _this._wholeWordOverride = 0 /* NotSet */; _this._matchCase = false; _this._matchCaseOverride = 0 /* NotSet */; _this._preserveCase = false; _this._preserveCaseOverride = 0 /* NotSet */; _this._searchScope = null; _this._matchesPosition = 0; _this._matchesCount = 0; _this._currentMatch = null; return _this; } Object.defineProperty(FindReplaceState.prototype, "searchString", { get: function () { return this._searchString; }, enumerable: true, configurable: true }); Object.defineProperty(FindReplaceState.prototype, "replaceString", { get: function () { return this._replaceString; }, enumerable: true, configurable: true }); Object.defineProperty(FindReplaceState.prototype, "isRevealed", { get: function () { return this._isRevealed; }, enumerable: true, configurable: true }); Object.defineProperty(FindReplaceState.prototype, "isReplaceRevealed", { get: function () { return this._isReplaceRevealed; }, enumerable: true, configurable: true }); Object.defineProperty(FindReplaceState.prototype, "isRegex", { get: function () { return effectiveOptionValue(this._isRegexOverride, this._isRegex); }, enumerable: true, configurable: true }); Object.defineProperty(FindReplaceState.prototype, "wholeWord", { get: function () { return effectiveOptionValue(this._wholeWordOverride, this._wholeWord); }, enumerable: true, configurable: true }); Object.defineProperty(FindReplaceState.prototype, "matchCase", { get: function () { return effectiveOptionValue(this._matchCaseOverride, this._matchCase); }, enumerable: true, configurable: true }); Object.defineProperty(FindReplaceState.prototype, "preserveCase", { get: function () { return effectiveOptionValue(this._preserveCaseOverride, this._preserveCase); }, enumerable: true, configurable: true }); Object.defineProperty(FindReplaceState.prototype, "actualIsRegex", { get: function () { return this._isRegex; }, enumerable: true, configurable: true }); Object.defineProperty(FindReplaceState.prototype, "actualWholeWord", { get: function () { return this._wholeWord; }, enumerable: true, configurable: true }); Object.defineProperty(FindReplaceState.prototype, "actualMatchCase", { get: function () { return this._matchCase; }, enumerable: true, configurable: true }); Object.defineProperty(FindReplaceState.prototype, "actualPreserveCase", { get: function () { return this._preserveCase; }, enumerable: true, configurable: true }); Object.defineProperty(FindReplaceState.prototype, "searchScope", { get: function () { return this._searchScope; }, enumerable: true, configurable: true }); Object.defineProperty(FindReplaceState.prototype, "matchesPosition", { get: function () { return this._matchesPosition; }, enumerable: true, configurable: true }); Object.defineProperty(FindReplaceState.prototype, "matchesCount", { get: function () { return this._matchesCount; }, enumerable: true, configurable: true }); Object.defineProperty(FindReplaceState.prototype, "currentMatch", { get: function () { return this._currentMatch; }, enumerable: true, configurable: true }); FindReplaceState.prototype.changeMatchInfo = function (matchesPosition, matchesCount, currentMatch) { var changeEvent = { moveCursor: false, updateHistory: false, searchString: false, replaceString: false, isRevealed: false, isReplaceRevealed: false, isRegex: false, wholeWord: false, matchCase: false, preserveCase: false, searchScope: false, matchesPosition: false, matchesCount: false, currentMatch: false }; var somethingChanged = false; if (matchesCount === 0) { matchesPosition = 0; } if (matchesPosition > matchesCount) { matchesPosition = matchesCount; } if (this._matchesPosition !== matchesPosition) { this._matchesPosition = matchesPosition; changeEvent.matchesPosition = true; somethingChanged = true; } if (this._matchesCount !== matchesCount) { this._matchesCount = matchesCount; changeEvent.matchesCount = true; somethingChanged = true; } if (typeof currentMatch !== 'undefined') { if (!range_1.Range.equalsRange(this._currentMatch, currentMatch)) { this._currentMatch = currentMatch; changeEvent.currentMatch = true; somethingChanged = true; } } if (somethingChanged) { this._onFindReplaceStateChange.fire(changeEvent); } }; FindReplaceState.prototype.change = function (newState, moveCursor, updateHistory) { if (updateHistory === void 0) { updateHistory = true; } var changeEvent = { moveCursor: moveCursor, updateHistory: updateHistory, searchString: false, replaceString: false, isRevealed: false, isReplaceRevealed: false, isRegex: false, wholeWord: false, matchCase: false, preserveCase: false, searchScope: false, matchesPosition: false, matchesCount: false, currentMatch: false }; var somethingChanged = false; var oldEffectiveIsRegex = this.isRegex; var oldEffectiveWholeWords = this.wholeWord; var oldEffectiveMatchCase = this.matchCase; var oldEffectivePreserveCase = this.preserveCase; if (typeof newState.searchString !== 'undefined') { if (this._searchString !== newState.searchString) { this._searchString = newState.searchString; changeEvent.searchString = true; somethingChanged = true; } } if (typeof newState.replaceString !== 'undefined') { if (this._replaceString !== newState.replaceString) { this._replaceString = newState.replaceString; changeEvent.replaceString = true; somethingChanged = true; } } if (typeof newState.isRevealed !== 'undefined') { if (this._isRevealed !== newState.isRevealed) { this._isRevealed = newState.isRevealed; changeEvent.isRevealed = true; somethingChanged = true; } } if (typeof newState.isReplaceRevealed !== 'undefined') { if (this._isReplaceRevealed !== newState.isReplaceRevealed) { this._isReplaceRevealed = newState.isReplaceRevealed; changeEvent.isReplaceRevealed = true; somethingChanged = true; } } if (typeof newState.isRegex !== 'undefined') { this._isRegex = newState.isRegex; } if (typeof newState.wholeWord !== 'undefined') { this._wholeWord = newState.wholeWord; } if (typeof newState.matchCase !== 'undefined') { this._matchCase = newState.matchCase; } if (typeof newState.preserveCase !== 'undefined') { this._preserveCase = newState.preserveCase; } if (typeof newState.searchScope !== 'undefined') { if (!range_1.Range.equalsRange(this._searchScope, newState.searchScope)) { this._searchScope = newState.searchScope; changeEvent.searchScope = true; somethingChanged = true; } } // Overrides get set when they explicitly come in and get reset anytime something else changes this._isRegexOverride = (typeof newState.isRegexOverride !== 'undefined' ? newState.isRegexOverride : 0 /* NotSet */); this._wholeWordOverride = (typeof newState.wholeWordOverride !== 'undefined' ? newState.wholeWordOverride : 0 /* NotSet */); this._matchCaseOverride = (typeof newState.matchCaseOverride !== 'undefined' ? newState.matchCaseOverride : 0 /* NotSet */); this._preserveCaseOverride = (typeof newState.preserveCaseOverride !== 'undefined' ? newState.preserveCaseOverride : 0 /* NotSet */); if (oldEffectiveIsRegex !== this.isRegex) { somethingChanged = true; changeEvent.isRegex = true; } if (oldEffectiveWholeWords !== this.wholeWord) { somethingChanged = true; changeEvent.wholeWord = true; } if (oldEffectiveMatchCase !== this.matchCase) { somethingChanged = true; changeEvent.matchCase = true; } if (oldEffectivePreserveCase !== this.preserveCase) { somethingChanged = true; changeEvent.preserveCase = true; } if (somethingChanged) { this._onFindReplaceStateChange.fire(changeEvent); } }; return FindReplaceState; }(lifecycle_1.Disposable)); exports.FindReplaceState = FindReplaceState; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[379/*vs/editor/contrib/find/replaceAllCommand*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/]), function (require, exports, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ReplaceAllCommand = /** @class */ (function () { function ReplaceAllCommand(editorSelection, ranges, replaceStrings) { this._editorSelection = editorSelection; this._ranges = ranges; this._replaceStrings = replaceStrings; this._trackedEditorSelectionId = null; } ReplaceAllCommand.prototype.getEditOperations = function (model, builder) { if (this._ranges.length > 0) { // Collect all edit operations var ops = []; for (var 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(function (o1, o2) { return range_1.Range.compareRangesUsingStarts(o1.range, o2.range); }); // Merge operations that touch each other var resultOps = []; var previousOp = ops[0]; for (var 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 (var _i = 0, resultOps_1 = resultOps; _i < resultOps_1.length; _i++) { var op = resultOps_1[_i]; builder.addEditOperation(op.range, op.text); } } this._trackedEditorSelectionId = builder.trackSelection(this._editorSelection); }; ReplaceAllCommand.prototype.computeCursorState = function (model, helper) { return helper.getTrackedSelection(this._trackedEditorSelectionId); }; return ReplaceAllCommand; }()); 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[380/*vs/editor/contrib/find/replacePattern*/], __M([0/*require*/,1/*exports*/,247/*vs/base/common/search*/]), function (require, exports, search_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Assigned when the replace pattern is entirely static. */ var StaticValueReplacePattern = /** @class */ (function () { function StaticValueReplacePattern(staticValue) { this.staticValue = staticValue; this.kind = 0 /* StaticValue */; } return StaticValueReplacePattern; }()); /** * Assigned when the replace pattern has replacemend patterns. */ var DynamicPiecesReplacePattern = /** @class */ (function () { function DynamicPiecesReplacePattern(pieces) { this.pieces = pieces; this.kind = 1 /* DynamicPieces */; } return DynamicPiecesReplacePattern; }()); var ReplacePattern = /** @class */ (function () { function ReplacePattern(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); } } ReplacePattern.fromStaticValue = function (value) { return new ReplacePattern([ReplacePiece.staticValue(value)]); }; Object.defineProperty(ReplacePattern.prototype, "hasReplacementPatterns", { get: function () { return (this._state.kind === 1 /* DynamicPieces */); }, enumerable: true, configurable: true }); ReplacePattern.prototype.buildReplaceString = function (matches, preserveCase) { if (this._state.kind === 0 /* StaticValue */) { if (preserveCase) { return search_1.buildReplaceStringWithCasePreserved(matches, this._state.staticValue); } else { return this._state.staticValue; } } var result = ''; for (var i = 0, len = this._state.pieces.length; i < len; i++) { var piece = this._state.pieces[i]; if (piece.staticValue !== null) { // static value ReplacePiece result += piece.staticValue; continue; } // match index ReplacePiece result += ReplacePattern._substitute(piece.matchIndex, matches); } return result; }; ReplacePattern._substitute = function (matchIndex, matches) { if (matches === null) { return ''; } if (matchIndex === 0) { return matches[0]; } var remainder = ''; while (matchIndex > 0) { if (matchIndex < matches.length) { // A match can be undefined var match = (matches[matchIndex] || ''); return match + remainder; } remainder = String(matchIndex % 10) + remainder; matchIndex = Math.floor(matchIndex / 10); } return '$' + remainder; }; return ReplacePattern; }()); exports.ReplacePattern = ReplacePattern; /** * A replace piece can either be a static string or an index to a specific match. */ var ReplacePiece = /** @class */ (function () { function ReplacePiece(staticValue, matchIndex) { this.staticValue = staticValue; this.matchIndex = matchIndex; } ReplacePiece.staticValue = function (value) { return new ReplacePiece(value, -1); }; ReplacePiece.matchIndex = function (index) { return new ReplacePiece(null, index); }; return ReplacePiece; }()); exports.ReplacePiece = ReplacePiece; var ReplacePieceBuilder = /** @class */ (function () { function ReplacePieceBuilder(source) { this._source = source; this._lastCharIndex = 0; this._result = []; this._resultLen = 0; this._currentStaticPiece = ''; } ReplacePieceBuilder.prototype.emitUnchanged = function (toCharIndex) { this._emitStatic(this._source.substring(this._lastCharIndex, toCharIndex)); this._lastCharIndex = toCharIndex; }; ReplacePieceBuilder.prototype.emitStatic = function (value, toCharIndex) { this._emitStatic(value); this._lastCharIndex = toCharIndex; }; ReplacePieceBuilder.prototype._emitStatic = function (value) { if (value.length === 0) { return; } this._currentStaticPiece += value; }; ReplacePieceBuilder.prototype.emitMatchIndex = function (index, toCharIndex) { if (this._currentStaticPiece.length !== 0) { this._result[this._resultLen++] = ReplacePiece.staticValue(this._currentStaticPiece); this._currentStaticPiece = ''; } this._result[this._resultLen++] = ReplacePiece.matchIndex(index); this._lastCharIndex = toCharIndex; }; ReplacePieceBuilder.prototype.finalize = function () { 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); }; return ReplacePieceBuilder; }()); /** * \n => inserts a LF * \t => inserts a TAB * \\ => inserts a "\". * $$ => 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); } var result = new ReplacePieceBuilder(replaceString); for (var i = 0, len = replaceString.length; i < len; i++) { var chCode = replaceString.charCodeAt(i); if (chCode === 92 /* Backslash */) { // move to next char i++; if (i >= len) { // string ends with a \ break; } var 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; } continue; } if (chCode === 36 /* DollarSign */) { // move to next char i++; if (i >= len) { // string ends with a $ break; } var 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); continue; } if (49 /* Digit1 */ <= nextChCode && nextChCode <= 57 /* Digit9 */) { // $n var matchIndex = nextChCode - 48 /* Digit0 */; // peek next char to probe for $nn if (i + 1 < len) { var 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); continue; } } result.emitUnchanged(i - 1); result.emitMatchIndex(matchIndex, i + 1); 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[150/*vs/editor/contrib/folding/foldingRanges*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MAX_FOLDING_REGIONS = 0xFFFF; exports.MAX_LINE_NUMBER = 0xFFFFFF; var MASK_INDENT = 0xFF000000; var FoldingRegions = /** @class */ (function () { function FoldingRegions(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; } FoldingRegions.prototype.ensureParentIndices = function () { var _this = this; if (!this._parentsComputed) { this._parentsComputed = true; var parentIndexes_1 = []; var isInsideLast = function (startLineNumber, endLineNumber) { var index = parentIndexes_1[parentIndexes_1.length - 1]; return _this.getStartLineNumber(index) <= startLineNumber && _this.getEndLineNumber(index) >= endLineNumber; }; for (var i = 0, len = this._startIndexes.length; i < len; i++) { var startLineNumber = this._startIndexes[i]; var 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_1.length > 0 && !isInsideLast(startLineNumber, endLineNumber)) { parentIndexes_1.pop(); } var parentIndex = parentIndexes_1.length > 0 ? parentIndexes_1[parentIndexes_1.length - 1] : -1; parentIndexes_1.push(i); this._startIndexes[i] = startLineNumber + ((parentIndex & 0xFF) << 24); this._endIndexes[i] = endLineNumber + ((parentIndex & 0xFF00) << 16); } } }; Object.defineProperty(FoldingRegions.prototype, "length", { get: function () { return this._startIndexes.length; }, enumerable: true, configurable: true }); FoldingRegions.prototype.getStartLineNumber = function (index) { return this._startIndexes[index] & exports.MAX_LINE_NUMBER; }; FoldingRegions.prototype.getEndLineNumber = function (index) { return this._endIndexes[index] & exports.MAX_LINE_NUMBER; }; FoldingRegions.prototype.getType = function (index) { return this._types ? this._types[index] : undefined; }; FoldingRegions.prototype.hasTypes = function () { return !!this._types; }; FoldingRegions.prototype.isCollapsed = function (index) { var arrayIndex = (index / 32) | 0; var bit = index % 32; return (this._collapseStates[arrayIndex] & (1 << bit)) !== 0; }; FoldingRegions.prototype.setCollapsed = function (index, newState) { var arrayIndex = (index / 32) | 0; var bit = index % 32; var value = this._collapseStates[arrayIndex]; if (newState) { this._collapseStates[arrayIndex] = value | (1 << bit); } else { this._collapseStates[arrayIndex] = value & ~(1 << bit); } }; FoldingRegions.prototype.toRegion = function (index) { return new FoldingRegion(this, index); }; FoldingRegions.prototype.getParentIndex = function (index) { this.ensureParentIndices(); var parent = ((this._startIndexes[index] & MASK_INDENT) >>> 24) + ((this._endIndexes[index] & MASK_INDENT) >>> 16); if (parent === exports.MAX_FOLDING_REGIONS) { return -1; } return parent; }; FoldingRegions.prototype.contains = function (index, line) { return this.getStartLineNumber(index) <= line && this.getEndLineNumber(index) >= line; }; FoldingRegions.prototype.findIndex = function (line) { var low = 0, high = this._startIndexes.length; if (high === 0) { return -1; // no children } while (low < high) { var mid = Math.floor((low + high) / 2); if (line < this.getStartLineNumber(mid)) { high = mid; } else { low = mid + 1; } } return low - 1; }; FoldingRegions.prototype.findRange = function (line) { var index = this.findIndex(line); if (index >= 0) { var 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; }; FoldingRegions.prototype.toString = function () { var res = []; for (var i = 0; i < this.length; i++) { res[i] = "[" + (this.isCollapsed(i) ? '+' : '-') + "] " + this.getStartLineNumber(i) + "/" + this.getEndLineNumber(i); } return res.join(', '); }; return FoldingRegions; }()); exports.FoldingRegions = FoldingRegions; var FoldingRegion = /** @class */ (function () { function FoldingRegion(ranges, index) { this.ranges = ranges; this.index = index; } Object.defineProperty(FoldingRegion.prototype, "startLineNumber", { get: function () { return this.ranges.getStartLineNumber(this.index); }, enumerable: true, configurable: true }); Object.defineProperty(FoldingRegion.prototype, "endLineNumber", { get: function () { return this.ranges.getEndLineNumber(this.index); }, enumerable: true, configurable: true }); Object.defineProperty(FoldingRegion.prototype, "regionIndex", { get: function () { return this.index; }, enumerable: true, configurable: true }); Object.defineProperty(FoldingRegion.prototype, "parentIndex", { get: function () { return this.ranges.getParentIndex(this.index); }, enumerable: true, configurable: true }); Object.defineProperty(FoldingRegion.prototype, "isCollapsed", { get: function () { return this.ranges.isCollapsed(this.index); }, enumerable: true, configurable: true }); FoldingRegion.prototype.containedBy = function (range) { return range.startLineNumber <= this.startLineNumber && range.endLineNumber >= this.endLineNumber; }; FoldingRegion.prototype.containsLine = function (lineNumber) { return this.startLineNumber <= lineNumber && lineNumber <= this.endLineNumber; }; return FoldingRegion; }()); 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[381/*vs/editor/contrib/folding/foldingModel*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,150/*vs/editor/contrib/folding/foldingRanges*/]), function (require, exports, event_1, foldingRanges_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var FoldingModel = /** @class */ (function () { function FoldingModel(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; } Object.defineProperty(FoldingModel.prototype, "regions", { get: function () { return this._regions; }, enumerable: true, configurable: true }); Object.defineProperty(FoldingModel.prototype, "textModel", { get: function () { return this._textModel; }, enumerable: true, configurable: true }); Object.defineProperty(FoldingModel.prototype, "isInitialized", { get: function () { return this._isInitialized; }, enumerable: true, configurable: true }); FoldingModel.prototype.toggleCollapseState = function (regions) { var _this = this; if (!regions.length) { return; } var processed = {}; this._decorationProvider.changeDecorations(function (accessor) { for (var _i = 0, regions_1 = regions; _i < regions_1.length; _i++) { var region = regions_1[_i]; var index = region.regionIndex; var editorDecorationId = _this._editorDecorationIds[index]; if (editorDecorationId && !processed[editorDecorationId]) { processed[editorDecorationId] = true; var newCollapseState = !_this._regions.isCollapsed(index); _this._regions.setCollapsed(index, newCollapseState); accessor.changeDecorationOptions(editorDecorationId, _this._decorationProvider.getDecorationOption(newCollapseState)); } } }); this._updateEventEmitter.fire({ model: this, collapseStateChanged: regions }); }; FoldingModel.prototype.update = function (newRegions, blockedLineNumers) { var _this = this; if (blockedLineNumers === void 0) { blockedLineNumers = []; } var newEditorDecorations = []; var isBlocked = function (startLineNumber, endLineNumber) { for (var _i = 0, blockedLineNumers_1 = blockedLineNumers; _i < blockedLineNumers_1.length; _i++) { var blockedLineNumber = blockedLineNumers_1[_i]; if (startLineNumber < blockedLineNumber && blockedLineNumber <= endLineNumber) { // first line is visible return true; } } return false; }; var initRange = function (index, isCollapsed) { var startLineNumber = newRegions.getStartLineNumber(index); if (isCollapsed && isBlocked(startLineNumber, newRegions.getEndLineNumber(index))) { isCollapsed = false; } newRegions.setCollapsed(index, isCollapsed); var maxColumn = _this._textModel.getLineMaxColumn(startLineNumber); var decorationRange = { startLineNumber: startLineNumber, startColumn: maxColumn, endLineNumber: startLineNumber, endColumn: maxColumn }; newEditorDecorations.push({ range: decorationRange, options: _this._decorationProvider.getDecorationOption(isCollapsed) }); }; var i = 0; var nextCollapsed = function () { while (i < _this._regions.length) { var isCollapsed = _this._regions.isCollapsed(i); i++; if (isCollapsed) { return i - 1; } } return -1; }; var k = 0; var collapsedIndex = nextCollapsed(); while (collapsedIndex !== -1 && k < newRegions.length) { // get the latest range var decRange = this._textModel.getDecorationRange(this._editorDecorationIds[collapsedIndex]); if (decRange) { var collapsedStartLineNumber = decRange.startLineNumber; if (this._textModel.getLineMaxColumn(collapsedStartLineNumber) === decRange.startColumn) { // test that the decoration is still at the end otherwise it got deleted while (k < newRegions.length) { var 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 */ FoldingModel.prototype.getMemento = function () { var collapsedRanges = []; for (var i = 0; i < this._regions.length; i++) { if (this._regions.isCollapsed(i)) { var range = this._textModel.getDecorationRange(this._editorDecorationIds[i]); if (range) { var startLineNumber = range.startLineNumber; var endLineNumber = range.endLineNumber + this._regions.getEndLineNumber(i) - this._regions.getStartLineNumber(i); collapsedRanges.push({ startLineNumber: startLineNumber, endLineNumber: endLineNumber }); } } } if (collapsedRanges.length > 0) { return collapsedRanges; } return undefined; }; /** * Apply persisted state, for persistence only */ FoldingModel.prototype.applyMemento = function (state) { if (!Array.isArray(state)) { return; } var toToogle = []; for (var _i = 0, state_1 = state; _i < state_1.length; _i++) { var range = state_1[_i]; var region = this.getRegionAtLine(range.startLineNumber); if (region && !region.isCollapsed) { toToogle.push(region); } } this.toggleCollapseState(toToogle); }; FoldingModel.prototype.dispose = function () { this._decorationProvider.deltaDecorations(this._editorDecorationIds, []); }; FoldingModel.prototype.getAllRegionsAtLine = function (lineNumber, filter) { var result = []; if (this._regions) { var index = this._regions.findRange(lineNumber); var level = 1; while (index >= 0) { var current = this._regions.toRegion(index); if (!filter || filter(current, level)) { result.push(current); } level++; index = current.parentIndex; } } return result; }; FoldingModel.prototype.getRegionAtLine = function (lineNumber) { if (this._regions) { var index = this._regions.findRange(lineNumber); if (index >= 0) { return this._regions.toRegion(index); } } return null; }; FoldingModel.prototype.getRegionsInside = function (region, filter) { var result = []; var index = region ? region.regionIndex + 1 : 0; var endLineNumber = region ? region.endLineNumber : Number.MAX_VALUE; if (filter && filter.length === 2) { var levelStack = []; for (var i = index, len = this._regions.length; i < len; i++) { var 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 (var i = index, len = this._regions.length; i < len; i++) { var current = this._regions.toRegion(i); if (this._regions.getStartLineNumber(i) < endLineNumber) { if (!filter || filter(current)) { result.push(current); } } else { break; } } } return result; }; return FoldingModel; }()); 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) { var toToggle = []; var _loop_1 = function (lineNumber) { var region = foldingModel.getRegionAtLine(lineNumber); if (region) { var doCollapse_1 = !region.isCollapsed; toToggle.push(region); if (levels > 1) { var regionsInside = foldingModel.getRegionsInside(region, function (r, level) { return r.isCollapsed !== doCollapse_1 && level < levels; }); toToggle.push.apply(toToggle, regionsInside); } } }; for (var _i = 0, lineNumbers_1 = lineNumbers; _i < lineNumbers_1.length; _i++) { var lineNumber = lineNumbers_1[_i]; _loop_1(lineNumber); } foldingModel.toggleCollapseState(toToggle); } exports.toggleCollapseState = toggleCollapseState; /** * Collapse or expand the regions at the given locations including all children. * @param doCollapse Wheter to collase 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, lineNumbers) { if (levels === void 0) { levels = Number.MAX_VALUE; } var toToggle = []; if (lineNumbers && lineNumbers.length > 0) { for (var _i = 0, lineNumbers_2 = lineNumbers; _i < lineNumbers_2.length; _i++) { var lineNumber = lineNumbers_2[_i]; var region = foldingModel.getRegionAtLine(lineNumber); if (region) { if (region.isCollapsed !== doCollapse) { toToggle.push(region); } if (levels > 1) { var regionsInside = foldingModel.getRegionsInside(region, function (r, level) { return r.isCollapsed !== doCollapse && level < levels; }); toToggle.push.apply(toToggle, regionsInside); } } } } else { var regionsInside = foldingModel.getRegionsInside(null, function (r, level) { return r.isCollapsed !== doCollapse && level < levels; }); toToggle.push.apply(toToggle, regionsInside); } foldingModel.toggleCollapseState(toToggle); } exports.setCollapseStateLevelsDown = setCollapseStateLevelsDown; /** * Collapse or expand the regions at the given locations including all parents. * @param doCollapse Wheter to collase 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) { var toToggle = []; for (var _i = 0, lineNumbers_3 = lineNumbers; _i < lineNumbers_3.length; _i++) { var lineNumber = lineNumbers_3[_i]; var regions = foldingModel.getAllRegionsAtLine(lineNumber, function (region, level) { return region.isCollapsed !== doCollapse && level <= levels; }); toToggle.push.apply(toToggle, 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 Wheter to collase or expand * @param lineNumbers the location of the regions to collapse or expand. */ function setCollapseStateUp(foldingModel, doCollapse, lineNumbers) { var toToggle = []; for (var _i = 0, lineNumbers_4 = lineNumbers; _i < lineNumbers_4.length; _i++) { var lineNumber = lineNumbers_4[_i]; var regions = foldingModel.getAllRegionsAtLine(lineNumber, function (region) { return 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 Wheter to collase or expand */ function setCollapseStateAtLevel(foldingModel, foldLevel, doCollapse, blockedLineNumbers) { var filter = function (region, level) { return level === foldLevel && region.isCollapsed !== doCollapse && !blockedLineNumbers.some(function (line) { return region.containsLine(line); }); }; var toToggle = foldingModel.getRegionsInside(null, filter); foldingModel.toggleCollapseState(toToggle); } exports.setCollapseStateAtLevel = setCollapseStateAtLevel; /** * Folds all regions for which the lines start with a given regex * @param foldingModel the folding model */ function setCollapseStateForMatchingLines(foldingModel, regExp, doCollapse) { var editorModel = foldingModel.textModel; var regions = foldingModel.regions; var toToggle = []; for (var i = regions.length - 1; i >= 0; i--) { if (doCollapse !== regions.isCollapsed(i)) { var 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) { var regions = foldingModel.regions; var toToggle = []; for (var 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; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[382/*vs/editor/contrib/folding/hiddenRangeModel*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,3/*vs/editor/common/core/range*/,19/*vs/base/common/arrays*/]), function (require, exports, event_1, range_1, arrays_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var HiddenRangeModel = /** @class */ (function () { function HiddenRangeModel(model) { var _this = this; this._updateEventEmitter = new event_1.Emitter(); this._foldingModel = model; this._foldingModelListener = model.onDidChange(function (_) { return _this.updateHiddenRanges(); }); this._hiddenRanges = []; if (model.regions.length) { this.updateHiddenRanges(); } } Object.defineProperty(HiddenRangeModel.prototype, "onDidChange", { get: function () { return this._updateEventEmitter.event; }, enumerable: true, configurable: true }); Object.defineProperty(HiddenRangeModel.prototype, "hiddenRanges", { get: function () { return this._hiddenRanges; }, enumerable: true, configurable: true }); HiddenRangeModel.prototype.updateHiddenRanges = function () { var updateHiddenAreas = false; var newHiddenAreas = []; var i = 0; // index into hidden var k = 0; var lastCollapsedStart = Number.MAX_VALUE; var lastCollapsedEnd = -1; var ranges = this._foldingModel.regions; for (; i < ranges.length; i++) { if (!ranges.isCollapsed(i)) { continue; } var startLineNumber = ranges.getStartLineNumber(i) + 1; // the first line is not hidden var endLineNumber = ranges.getEndLineNumber(i); if (lastCollapsedStart <= startLineNumber && endLineNumber <= lastCollapsedEnd) { // ignore ranges contained in collapsed regions continue; } if (!updateHiddenAreas && k < this._hiddenRanges.length && this._hiddenRanges[k].startLineNumber === startLineNumber && this._hiddenRanges[k].endLineNumber === endLineNumber) { // reuse the old ranges newHiddenAreas.push(this._hiddenRanges[k]); k++; } else { updateHiddenAreas = true; newHiddenAreas.push(new range_1.Range(startLineNumber, 1, endLineNumber, 1)); } lastCollapsedStart = startLineNumber; lastCollapsedEnd = endLineNumber; } if (updateHiddenAreas || k < this._hiddenRanges.length) { this.applyHiddenRanges(newHiddenAreas); } }; HiddenRangeModel.prototype.applyMemento = function (state) { if (!Array.isArray(state) || state.length === 0) { return false; } var hiddenRanges = []; for (var _i = 0, state_1 = state; _i < state_1.length; _i++) { var r = state_1[_i]; 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 */ HiddenRangeModel.prototype.getMemento = function () { return this._hiddenRanges.map(function (r) { return ({ startLineNumber: r.startLineNumber - 1, endLineNumber: r.endLineNumber }); }); }; HiddenRangeModel.prototype.applyHiddenRanges = function (newHiddenAreas) { this._hiddenRanges = newHiddenAreas; this._updateEventEmitter.fire(newHiddenAreas); }; HiddenRangeModel.prototype.hasRanges = function () { return this._hiddenRanges.length > 0; }; HiddenRangeModel.prototype.isHidden = function (line) { return findRange(this._hiddenRanges, line) !== null; }; HiddenRangeModel.prototype.adjustSelections = function (selections) { var _this = this; var hasChanges = false; var editorModel = this._foldingModel.textModel; var lastRange = null; var adjustLine = function (line) { if (!lastRange || !isInside(line, lastRange)) { lastRange = findRange(_this._hiddenRanges, line); } if (lastRange) { return lastRange.startLineNumber - 1; } return null; }; for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; var adjustedStartLine = adjustLine(selection.startLineNumber); if (adjustedStartLine) { selection = selection.setStartPosition(adjustedStartLine, editorModel.getLineMaxColumn(adjustedStartLine)); hasChanges = true; } var adjustedEndLine = adjustLine(selection.endLineNumber); if (adjustedEndLine) { selection = selection.setEndPosition(adjustedEndLine, editorModel.getLineMaxColumn(adjustedEndLine)); hasChanges = true; } selections[i] = selection; } return hasChanges; }; HiddenRangeModel.prototype.dispose = function () { if (this.hiddenRanges.length > 0) { this._hiddenRanges = []; this._updateEventEmitter.fire(this._hiddenRanges); } if (this._foldingModelListener) { this._foldingModelListener.dispose(); this._foldingModelListener = null; } }; return HiddenRangeModel; }()); exports.HiddenRangeModel = HiddenRangeModel; function isInside(line, range) { return line >= range.startLineNumber && line <= range.endLineNumber; } function findRange(ranges, line) { var i = arrays_1.findFirstInSorted(ranges, function (r) { return 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[197/*vs/editor/contrib/folding/syntaxRangeProvider*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,150/*vs/editor/contrib/folding/foldingRanges*/]), function (require, exports, errors_1, foldingRanges_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MAX_FOLDING_REGIONS = 5000; var foldingContext = {}; exports.ID_SYNTAX_PROVIDER = 'syntax'; var SyntaxRangeProvider = /** @class */ (function () { function SyntaxRangeProvider(editorModel, providers, limit) { if (limit === void 0) { limit = MAX_FOLDING_REGIONS; } this.editorModel = editorModel; this.providers = providers; this.limit = limit; this.id = exports.ID_SYNTAX_PROVIDER; } SyntaxRangeProvider.prototype.compute = function (cancellationToken) { var _this = this; return collectSyntaxRanges(this.providers, this.editorModel, cancellationToken).then(function (ranges) { if (ranges) { var res = sanitizeRanges(ranges, _this.limit); return res; } return null; }); }; SyntaxRangeProvider.prototype.dispose = function () { }; return SyntaxRangeProvider; }()); exports.SyntaxRangeProvider = SyntaxRangeProvider; function collectSyntaxRanges(providers, model, cancellationToken) { var rangeData = null; var promises = providers.map(function (provider, i) { return Promise.resolve(provider.provideFoldingRanges(model, foldingContext, cancellationToken)).then(function (ranges) { if (cancellationToken.isCancellationRequested) { return; } if (Array.isArray(ranges)) { if (!Array.isArray(rangeData)) { rangeData = []; } var nLines = model.getLineCount(); for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { var r = ranges_1[_i]; 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(function (_) { return rangeData; }); } var RangesCollector = /** @class */ (function () { function RangesCollector(foldingRangesLimit) { this._startIndexes = []; this._endIndexes = []; this._nestingLevels = []; this._nestingLevelCounts = []; this._types = []; this._length = 0; this._foldingRangesLimit = foldingRangesLimit; } RangesCollector.prototype.add = function (startLineNumber, endLineNumber, type, nestingLevel) { if (startLineNumber > foldingRanges_1.MAX_LINE_NUMBER || endLineNumber > foldingRanges_1.MAX_LINE_NUMBER) { return; } var 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; } }; RangesCollector.prototype.toIndentRanges = function () { if (this._length <= this._foldingRangesLimit) { var startIndexes = new Uint32Array(this._length); var endIndexes = new Uint32Array(this._length); for (var 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 { var entries = 0; var maxLevel = this._nestingLevelCounts.length; for (var i = 0; i < this._nestingLevelCounts.length; i++) { var n = this._nestingLevelCounts[i]; if (n) { if (n + entries > this._foldingRangesLimit) { maxLevel = i; break; } entries += n; } } var startIndexes = new Uint32Array(this._foldingRangesLimit); var endIndexes = new Uint32Array(this._foldingRangesLimit); var types = []; for (var i = 0, k = 0; i < this._length; i++) { var 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); } }; return RangesCollector; }()); exports.RangesCollector = RangesCollector; function sanitizeRanges(rangeData, limit) { var sorted = rangeData.sort(function (d1, d2) { var diff = d1.start - d2.start; if (diff === 0) { diff = d1.rank - d2.rank; } return diff; }); var collector = new RangesCollector(limit); var top = undefined; var previous = []; for (var _i = 0, sorted_1 = sorted; _i < sorted_1.length; _i++) { var entry = sorted_1[_i]; 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[383/*vs/editor/contrib/folding/intializingRangeProvider*/], __M([0/*require*/,1/*exports*/,197/*vs/editor/contrib/folding/syntaxRangeProvider*/]), function (require, exports, syntaxRangeProvider_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ID_INIT_PROVIDER = 'init'; var InitializingRangeProvider = /** @class */ (function () { function InitializingRangeProvider(editorModel, initialRanges, onTimeout, timeoutTime) { this.editorModel = editorModel; this.id = exports.ID_INIT_PROVIDER; if (initialRanges.length) { var toDecorationRange = function (range) { return { range: { startLineNumber: range.startLineNumber, startColumn: 0, endLineNumber: range.endLineNumber, endColumn: editorModel.getLineLength(range.endLineNumber) }, options: { stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ } }; }; this.decorationIds = editorModel.deltaDecorations([], initialRanges.map(toDecorationRange)); this.timeout = setTimeout(onTimeout, timeoutTime); } } InitializingRangeProvider.prototype.dispose = function () { if (this.decorationIds) { this.editorModel.deltaDecorations(this.decorationIds, []); this.decorationIds = undefined; } if (typeof this.timeout === 'number') { clearTimeout(this.timeout); this.timeout = undefined; } }; InitializingRangeProvider.prototype.compute = function (cancelationToken) { var foldingRangeData = []; if (this.decorationIds) { for (var _i = 0, _a = this.decorationIds; _i < _a.length; _i++) { var id = _a[_i]; var range = this.editorModel.getDecorationRange(id); if (range) { foldingRangeData.push({ start: range.startLineNumber, end: range.endLineNumber, rank: 1 }); } } } return Promise.resolve(syntaxRangeProvider_1.sanitizeRanges(foldingRangeData, Number.MAX_VALUE)); }; return InitializingRangeProvider; }()); 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[198/*vs/editor/contrib/format/formattingEdit*/], __M([0/*require*/,1/*exports*/,58/*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 }); var FormattingEdit = /** @class */ (function () { function FormattingEdit() { } FormattingEdit._handleEolEdits = function (editor, edits) { var newEol = undefined; var singleEdits = []; for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { var edit = edits_1[_i]; 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; }; FormattingEdit._isFullModelReplaceEdit = function (editor, edit) { if (!editor.hasModel()) { return false; } var model = editor.getModel(); var editRange = model.validateRange(edit.range); var fullModelRange = model.getFullModelRange(); return fullModelRange.equalsRange(editRange); }; FormattingEdit.execute = function (editor, _edits) { editor.pushUndoStop(); var 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(function (edit) { return editOperation_1.EditOperation.replace(range_1.Range.lift(edit.range), edit.text); })); } else { editor.executeEdits('formatEditsCommand', edits.map(function (edit) { return editOperation_1.EditOperation.replaceMove(range_1.Range.lift(edit.range), edit.text); })); } editor.pushUndoStop(); }; return FormattingEdit; }()); 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[199/*vs/editor/contrib/gotoSymbol/link/clickLinkGesture*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,2/*vs/base/common/lifecycle*/,4/*vs/base/common/event*/,16/*vs/base/common/platform*/]), function (require, exports, browser, lifecycle_1, event_1, platform) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function hasModifier(e, modifier) { return !!e[modifier]; } /** * An event that encapsulates the various trigger modifiers logic needed for go to definition. */ var ClickLinkMouseEvent = /** @class */ (function () { function ClickLinkMouseEvent(source, opts) { this.target = source.target; this.hasTriggerModifier = hasModifier(source.event, opts.triggerModifier); this.hasSideBySideModifier = hasModifier(source.event, opts.triggerSideBySideModifier); this.isNoneOrSingleMouseDown = (browser.isIE || source.event.detail <= 1); // IE does not support event.detail properly } return ClickLinkMouseEvent; }()); exports.ClickLinkMouseEvent = ClickLinkMouseEvent; /** * An event that encapsulates the various trigger modifiers logic needed for go to definition. */ var ClickLinkKeyboardEvent = /** @class */ (function () { function ClickLinkKeyboardEvent(source, opts) { this.keyCodeIsTriggerKey = (source.keyCode === opts.triggerKey); this.keyCodeIsSideBySideKey = (source.keyCode === opts.triggerSideBySideKey); this.hasTriggerModifier = hasModifier(source, opts.triggerModifier); } return ClickLinkKeyboardEvent; }()); exports.ClickLinkKeyboardEvent = ClickLinkKeyboardEvent; var ClickLinkOptions = /** @class */ (function () { function ClickLinkOptions(triggerKey, triggerModifier, triggerSideBySideKey, triggerSideBySideModifier) { this.triggerKey = triggerKey; this.triggerModifier = triggerModifier; this.triggerSideBySideKey = triggerSideBySideKey; this.triggerSideBySideModifier = triggerSideBySideModifier; } ClickLinkOptions.prototype.equals = function (other) { return (this.triggerKey === other.triggerKey && this.triggerModifier === other.triggerModifier && this.triggerSideBySideKey === other.triggerSideBySideKey && this.triggerSideBySideModifier === other.triggerSideBySideModifier); }; return ClickLinkOptions; }()); 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'); } var ClickLinkGesture = /** @class */ (function (_super) { __extends(ClickLinkGesture, _super); function ClickLinkGesture(editor) { var _this = _super.call(this) || this; _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(59 /* multiCursorModifier */)); _this.lastMouseMoveEvent = null; _this.hasTriggerKeyOnMouseDown = false; _this._register(_this._editor.onDidChangeConfiguration(function (e) { if (e.hasChanged(59 /* multiCursorModifier */)) { var newOpts = createOptions(_this._editor.getOption(59 /* multiCursorModifier */)); if (_this._opts.equals(newOpts)) { return; } _this._opts = newOpts; _this.lastMouseMoveEvent = null; _this.hasTriggerKeyOnMouseDown = false; _this._onCancel.fire(); } })); _this._register(_this._editor.onMouseMove(function (e) { return _this.onEditorMouseMove(new ClickLinkMouseEvent(e, _this._opts)); })); _this._register(_this._editor.onMouseDown(function (e) { return _this.onEditorMouseDown(new ClickLinkMouseEvent(e, _this._opts)); })); _this._register(_this._editor.onMouseUp(function (e) { return _this.onEditorMouseUp(new ClickLinkMouseEvent(e, _this._opts)); })); _this._register(_this._editor.onKeyDown(function (e) { return _this.onEditorKeyDown(new ClickLinkKeyboardEvent(e, _this._opts)); })); _this._register(_this._editor.onKeyUp(function (e) { return _this.onEditorKeyUp(new ClickLinkKeyboardEvent(e, _this._opts)); })); _this._register(_this._editor.onMouseDrag(function () { return _this.resetHandler(); })); _this._register(_this._editor.onDidChangeCursorSelection(function (e) { return _this.onDidChangeCursorSelection(e); })); _this._register(_this._editor.onDidChangeModel(function (e) { return _this.resetHandler(); })); _this._register(_this._editor.onDidChangeModelContent(function () { return _this.resetHandler(); })); _this._register(_this._editor.onDidScrollChange(function (e) { if (e.scrollTopChanged || e.scrollLeftChanged) { _this.resetHandler(); } })); return _this; } ClickLinkGesture.prototype.onDidChangeCursorSelection = function (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) } }; ClickLinkGesture.prototype.onEditorMouseMove = function (mouseEvent) { this.lastMouseMoveEvent = mouseEvent; this._onMouseMoveOrRelevantKeyDown.fire([mouseEvent, null]); }; ClickLinkGesture.prototype.onEditorMouseDown = function (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; }; ClickLinkGesture.prototype.onEditorMouseUp = function (mouseEvent) { if (this.hasTriggerKeyOnMouseDown) { this._onExecute.fire(mouseEvent); } }; ClickLinkGesture.prototype.onEditorKeyDown = function (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 } }; ClickLinkGesture.prototype.onEditorKeyUp = function (e) { if (e.keyCodeIsTriggerKey) { this._onCancel.fire(); } }; ClickLinkGesture.prototype.resetHandler = function () { this.lastMouseMoveEvent = null; this.hasTriggerKeyOnMouseDown = false; this._onCancel.fire(); }; return ClickLinkGesture; }(lifecycle_1.Disposable)); exports.ClickLinkGesture = ClickLinkGesture; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[200/*vs/editor/contrib/hover/hoverOperation*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,10/*vs/base/common/errors*/]), function (require, exports, async_1, errors_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var HoverOperation = /** @class */ (function () { function HoverOperation(computer, success, error, progress, hoverTime) { var _this = this; this._computer = computer; this._state = 0 /* IDLE */; this._hoverTime = hoverTime; this._firstWaitScheduler = new async_1.RunOnceScheduler(function () { return _this._triggerAsyncComputation(); }, 0); this._secondWaitScheduler = new async_1.RunOnceScheduler(function () { return _this._triggerSyncComputation(); }, 0); this._loadingMessageScheduler = new async_1.RunOnceScheduler(function () { return _this._showLoadingMessage(); }, 0); this._asyncComputationPromise = null; this._asyncComputationPromiseDone = false; this._completeCallback = success; this._errorCallback = error; this._progressCallback = progress; } HoverOperation.prototype.setHoverTime = function (hoverTime) { this._hoverTime = hoverTime; }; HoverOperation.prototype._firstWaitTime = function () { return this._hoverTime / 2; }; HoverOperation.prototype._secondWaitTime = function () { return this._hoverTime / 2; }; HoverOperation.prototype._loadingMessageTime = function () { return 3 * this._hoverTime; }; HoverOperation.prototype._triggerAsyncComputation = function () { var _this = this; this._state = 2 /* SECOND_WAIT */; this._secondWaitScheduler.schedule(this._secondWaitTime()); if (this._computer.computeAsync) { this._asyncComputationPromiseDone = false; this._asyncComputationPromise = async_1.createCancelablePromise(function (token) { return _this._computer.computeAsync(token); }); this._asyncComputationPromise.then(function (asyncResult) { _this._asyncComputationPromiseDone = true; _this._withAsyncResult(asyncResult); }, function (e) { return _this._onError(e); }); } else { this._asyncComputationPromiseDone = true; } }; HoverOperation.prototype._triggerSyncComputation = function () { if (this._computer.computeSync) { this._computer.onResult(this._computer.computeSync(), true); } if (this._asyncComputationPromiseDone) { this._state = 0 /* IDLE */; this._onComplete(this._computer.getResult()); } else { this._state = 3 /* WAITING_FOR_ASYNC_COMPUTATION */; this._onProgress(this._computer.getResult()); } }; HoverOperation.prototype._showLoadingMessage = function () { if (this._state === 3 /* WAITING_FOR_ASYNC_COMPUTATION */) { this._onProgress(this._computer.getResultWithLoadingMessage()); } }; HoverOperation.prototype._withAsyncResult = function (asyncResult) { if (asyncResult) { this._computer.onResult(asyncResult, false); } if (this._state === 3 /* WAITING_FOR_ASYNC_COMPUTATION */) { this._state = 0 /* IDLE */; this._onComplete(this._computer.getResult()); } }; HoverOperation.prototype._onComplete = function (value) { if (this._completeCallback) { this._completeCallback(value); } }; HoverOperation.prototype._onError = function (error) { if (this._errorCallback) { this._errorCallback(error); } else { errors_1.onUnexpectedError(error); } }; HoverOperation.prototype._onProgress = function (value) { if (this._progressCallback) { this._progressCallback(value); } }; HoverOperation.prototype.start = function (mode) { if (mode === 0 /* Delayed */) { if (this._state === 0 /* IDLE */) { this._state = 1 /* FIRST_WAIT */; this._firstWaitScheduler.schedule(this._firstWaitTime()); this._loadingMessageScheduler.schedule(this._loadingMessageTime()); } } else { switch (this._state) { case 0 /* IDLE */: this._triggerAsyncComputation(); this._secondWaitScheduler.cancel(); this._triggerSyncComputation(); break; case 2 /* SECOND_WAIT */: this._secondWaitScheduler.cancel(); this._triggerSyncComputation(); break; } } }; HoverOperation.prototype.cancel = function () { this._loadingMessageScheduler.cancel(); if (this._state === 1 /* FIRST_WAIT */) { this._firstWaitScheduler.cancel(); } if (this._state === 2 /* SECOND_WAIT */) { this._secondWaitScheduler.cancel(); if (this._asyncComputationPromise) { this._asyncComputationPromise.cancel(); this._asyncComputationPromise = null; } } if (this._state === 3 /* WAITING_FOR_ASYNC_COMPUTATION */) { if (this._asyncComputationPromise) { this._asyncComputationPromise.cancel(); this._asyncComputationPromise = null; } } this._state = 0 /* IDLE */; }; return HoverOperation; }()); 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. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[201/*vs/editor/contrib/hover/hoverWidgets*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,53/*vs/base/browser/ui/scrollbar/scrollableElement*/,47/*vs/base/browser/ui/widget*/]), function (require, exports, dom_1, scrollableElement_1, widget_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ContentHoverWidget = /** @class */ (function (_super) { __extends(ContentHoverWidget, _super); function ContentHoverWidget(id, editor) { var _this = _super.call(this) || this; // Editor.IContentWidget.allowEditorOverflow _this.allowEditorOverflow = true; _this._id = id; _this._editor = editor; _this._isVisible = false; _this._stoleFocus = false; _this._containerDomNode = document.createElement('div'); _this._containerDomNode.className = 'monaco-editor-hover hidden'; _this._containerDomNode.tabIndex = 0; _this._domNode = document.createElement('div'); _this._domNode.className = 'monaco-editor-hover-content'; _this.scrollbar = new scrollableElement_1.DomScrollableElement(_this._domNode, {}); _this._register(_this.scrollbar); _this._containerDomNode.appendChild(_this.scrollbar.getDomNode()); _this.onkeydown(_this._containerDomNode, function (e) { if (e.equals(9 /* Escape */)) { _this.hide(); } }); _this._register(_this._editor.onDidChangeConfiguration(function (e) { if (e.hasChanged(34 /* fontInfo */)) { _this.updateFont(); } })); _this._editor.onDidLayoutChange(function (e) { return _this.layout(); }); _this.layout(); _this._editor.addContentWidget(_this); _this._showAtPosition = null; _this._showAtRange = null; _this._stoleFocus = false; return _this; } Object.defineProperty(ContentHoverWidget.prototype, "isVisible", { get: function () { return this._isVisible; }, set: function (value) { this._isVisible = value; dom_1.toggleClass(this._containerDomNode, 'hidden', !this._isVisible); }, enumerable: true, configurable: true }); ContentHoverWidget.prototype.getId = function () { return this._id; }; ContentHoverWidget.prototype.getDomNode = function () { return this._containerDomNode; }; ContentHoverWidget.prototype.showAt = function (position, range, focus) { // Position has changed this._showAtPosition = position; this._showAtRange = range; this.isVisible = true; this._editor.layoutContentWidget(this); // Simply force a synchronous render on the editor // such that the widget does not really render with left = '0px' this._editor.render(); this._stoleFocus = focus; if (focus) { this._containerDomNode.focus(); } }; ContentHoverWidget.prototype.hide = function () { if (!this.isVisible) { return; } this.isVisible = false; this._editor.layoutContentWidget(this); if (this._stoleFocus) { this._editor.focus(); } }; ContentHoverWidget.prototype.getPosition = function () { if (this.isVisible) { return { position: this._showAtPosition, range: this._showAtRange, preference: [ 1 /* ABOVE */, 2 /* BELOW */ ] }; } return null; }; ContentHoverWidget.prototype.dispose = function () { this._editor.removeContentWidget(this); _super.prototype.dispose.call(this); }; ContentHoverWidget.prototype.updateFont = function () { var _this = this; var codeClasses = Array.prototype.slice.call(this._domNode.getElementsByClassName('code')); codeClasses.forEach(function (node) { return _this._editor.applyFontInfo(node); }); }; ContentHoverWidget.prototype.updateContents = function (node) { this._domNode.textContent = ''; this._domNode.appendChild(node); this.updateFont(); this._editor.layoutContentWidget(this); this.onContentsChange(); }; ContentHoverWidget.prototype.onContentsChange = function () { this.scrollbar.scanDomNode(); }; ContentHoverWidget.prototype.layout = function () { var height = Math.max(this._editor.getLayoutInfo().height / 4, 250); var _a = this._editor.getOption(34 /* fontInfo */), fontSize = _a.fontSize, lineHeight = _a.lineHeight; this._domNode.style.fontSize = fontSize + "px"; this._domNode.style.lineHeight = lineHeight + "px"; this._domNode.style.maxHeight = height + "px"; this._domNode.style.maxWidth = Math.max(this._editor.getLayoutInfo().width * 0.66, 500) + "px"; }; return ContentHoverWidget; }(widget_1.Widget)); exports.ContentHoverWidget = ContentHoverWidget; var GlyphHoverWidget = /** @class */ (function (_super) { __extends(GlyphHoverWidget, _super); function GlyphHoverWidget(id, editor) { var _this = _super.call(this) || this; _this._id = id; _this._editor = editor; _this._isVisible = false; _this._domNode = document.createElement('div'); _this._domNode.className = 'monaco-editor-hover hidden'; _this._domNode.setAttribute('aria-hidden', 'true'); _this._domNode.setAttribute('role', 'presentation'); _this._showAtLineNumber = -1; _this._register(_this._editor.onDidChangeConfiguration(function (e) { if (e.hasChanged(34 /* fontInfo */)) { _this.updateFont(); } })); _this._editor.addOverlayWidget(_this); return _this; } Object.defineProperty(GlyphHoverWidget.prototype, "isVisible", { get: function () { return this._isVisible; }, set: function (value) { this._isVisible = value; dom_1.toggleClass(this._domNode, 'hidden', !this._isVisible); }, enumerable: true, configurable: true }); GlyphHoverWidget.prototype.getId = function () { return this._id; }; GlyphHoverWidget.prototype.getDomNode = function () { return this._domNode; }; GlyphHoverWidget.prototype.showAt = function (lineNumber) { this._showAtLineNumber = lineNumber; if (!this.isVisible) { this.isVisible = true; } var editorLayout = this._editor.getLayoutInfo(); var topForLineNumber = this._editor.getTopForLineNumber(this._showAtLineNumber); var editorScrollTop = this._editor.getScrollTop(); var lineHeight = this._editor.getOption(49 /* lineHeight */); var nodeHeight = this._domNode.clientHeight; var top = topForLineNumber - editorScrollTop - ((nodeHeight - lineHeight) / 2); this._domNode.style.left = editorLayout.glyphMarginLeft + editorLayout.glyphMarginWidth + "px"; this._domNode.style.top = Math.max(Math.round(top), 0) + "px"; }; GlyphHoverWidget.prototype.hide = function () { if (!this.isVisible) { return; } this.isVisible = false; }; GlyphHoverWidget.prototype.getPosition = function () { return null; }; GlyphHoverWidget.prototype.dispose = function () { this._editor.removeOverlayWidget(this); _super.prototype.dispose.call(this); }; GlyphHoverWidget.prototype.updateFont = function () { var _this = this; var codeTags = Array.prototype.slice.call(this._domNode.getElementsByTagName('code')); var codeClasses = Array.prototype.slice.call(this._domNode.getElementsByClassName('code')); __spreadArrays(codeTags, codeClasses).forEach(function (node) { return _this._editor.applyFontInfo(node); }); }; GlyphHoverWidget.prototype.updateContents = function (node) { this._domNode.textContent = ''; this._domNode.appendChild(node); this.updateFont(); }; return GlyphHoverWidget; }(widget_1.Widget)); exports.GlyphHoverWidget = GlyphHoverWidget; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[384/*vs/editor/contrib/inPlaceReplace/inPlaceReplaceCommand*/], __M([0/*require*/,1/*exports*/,22/*vs/editor/common/core/selection*/]), function (require, exports, selection_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var InPlaceReplaceCommand = /** @class */ (function () { function InPlaceReplaceCommand(editRange, originalSelection, text) { this._editRange = editRange; this._originalSelection = originalSelection; this._text = text; } InPlaceReplaceCommand.prototype.getEditOperations = function (model, builder) { builder.addTrackedEditOperation(this._editRange, this._text); }; InPlaceReplaceCommand.prototype.computeCursorState = function (model, helper) { var inverseEditOperations = helper.getInverseEditOperations(); var 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)); }; return InPlaceReplaceCommand; }()); 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[385/*vs/editor/contrib/indentation/indentUtils*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function getSpaceCnt(str, tabSize) { var spacesCnt = 0; for (var 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; var result = ''; if (!insertSpaces) { var tabsCnt = Math.floor(spacesCnt / tabSize); spacesCnt = spacesCnt % tabSize; for (var i = 0; i < tabsCnt; i++) { result += '\t'; } } for (var 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[386/*vs/editor/contrib/linesOperations/copyLinesCommand*/], __M([0/*require*/,1/*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 }); var CopyLinesCommand = /** @class */ (function () { function CopyLinesCommand(selection, isCopyingDown) { this._selection = selection; this._isCopyingDown = isCopyingDown; this._selectionDirection = 0 /* LTR */; this._selectionId = null; this._startLineNumberDelta = 0; this._endLineNumberDelta = 0; } CopyLinesCommand.prototype.getEditOperations = function (model, builder) { var 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)); } var sourceLines = []; for (var i = s.startLineNumber; i <= s.endLineNumber; i++) { sourceLines.push(model.getLineContent(i)); } var sourceText = sourceLines.join('\n'); if (sourceText === '') { // Duplicating empty line if (this._isCopyingDown) { this._startLineNumberDelta++; this._endLineNumberDelta++; } } 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(); }; CopyLinesCommand.prototype.computeCursorState = function (model, helper) { var result = helper.getTrackedSelection(this._selectionId); if (this._startLineNumberDelta !== 0 || this._endLineNumberDelta !== 0) { var startLineNumber = result.startLineNumber; var startColumn = result.startColumn; var endLineNumber = result.endLineNumber; var 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; }; return CopyLinesCommand; }()); 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[387/*vs/editor/contrib/linesOperations/sortLinesCommand*/], __M([0/*require*/,1/*exports*/,58/*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 }); var SortLinesCommand = /** @class */ (function () { function SortLinesCommand(selection, descending) { this.selection = selection; this.descending = descending; this.selectionId = null; } SortLinesCommand.getCollator = function () { if (!SortLinesCommand._COLLATOR) { SortLinesCommand._COLLATOR = new Intl.Collator(); } return SortLinesCommand._COLLATOR; }; SortLinesCommand.prototype.getEditOperations = function (model, builder) { var op = sortLines(model, this.selection, this.descending); if (op) { builder.addEditOperation(op.range, op.text); } this.selectionId = builder.trackSelection(this.selection); }; SortLinesCommand.prototype.computeCursorState = function (model, helper) { return helper.getTrackedSelection(this.selectionId); }; SortLinesCommand.canRun = function (model, selection, descending) { if (model === null) { return false; } var data = getSortData(model, selection, descending); if (!data) { return false; } for (var i = 0, len = data.before.length; i < len; i++) { if (data.before[i] !== data.after[i]) { return true; } } return false; }; SortLinesCommand._COLLATOR = null; return SortLinesCommand; }()); exports.SortLinesCommand = SortLinesCommand; function getSortData(model, selection, descending) { var startLineNumber = selection.startLineNumber; var endLineNumber = selection.endLineNumber; if (selection.endColumn === 1) { endLineNumber--; } // Nothing to sort if user didn't select anything. if (startLineNumber >= endLineNumber) { return null; } var linesToSort = []; // Get the contents of the selection to be sorted. for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { linesToSort.push(model.getLineContent(lineNumber)); } var 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) { var 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[202/*vs/editor/contrib/smartSelect/bracketSelections*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,76/*vs/base/common/linkedList*/]), function (require, exports, position_1, range_1, linkedList_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var BracketSelectionRangeProvider = /** @class */ (function () { function BracketSelectionRangeProvider() { } BracketSelectionRangeProvider.prototype.provideSelectionRanges = function (model, positions) { return __awaiter(this, void 0, void 0, function () { var result, _loop_1, _i, positions_1, position; return __generator(this, function (_a) { switch (_a.label) { case 0: result = []; _loop_1 = function (position) { var bucket, ranges; return __generator(this, function (_a) { switch (_a.label) { case 0: bucket = []; result.push(bucket); ranges = new Map(); return [4 /*yield*/, new Promise(function (resolve) { return BracketSelectionRangeProvider._bracketsRightYield(resolve, 0, model, position, ranges); })]; case 1: _a.sent(); return [4 /*yield*/, new Promise(function (resolve) { return BracketSelectionRangeProvider._bracketsLeftYield(resolve, 0, model, position, ranges, bucket); })]; case 2: _a.sent(); return [2 /*return*/]; } }); }; _i = 0, positions_1 = positions; _a.label = 1; case 1: if (!(_i < positions_1.length)) return [3 /*break*/, 4]; position = positions_1[_i]; return [5 /*yield**/, _loop_1(position)]; case 2: _a.sent(); _a.label = 3; case 3: _i++; return [3 /*break*/, 1]; case 4: return [2 /*return*/, result]; } }); }); }; BracketSelectionRangeProvider._bracketsRightYield = function (resolve, round, model, pos, ranges) { var counts = new Map(); var t1 = Date.now(); while (true) { if (round >= BracketSelectionRangeProvider._maxRounds) { resolve(); break; } if (!pos) { resolve(); break; } var bracket = model.findNextBracket(pos); if (!bracket) { resolve(); break; } var d = Date.now() - t1; if (d > BracketSelectionRangeProvider._maxDuration) { setTimeout(function () { return BracketSelectionRangeProvider._bracketsRightYield(resolve, round + 1, model, pos, ranges); }); break; } var key = bracket.close[0]; if (bracket.isOpen) { // wait for closing var val = counts.has(key) ? counts.get(key) : 0; counts.set(key, val + 1); } else { // process closing var val = counts.has(key) ? counts.get(key) : 0; val -= 1; counts.set(key, Math.max(0, val)); if (val < 0) { var list = ranges.get(key); if (!list) { list = new linkedList_1.LinkedList(); ranges.set(key, list); } list.push(bracket.range); } } pos = bracket.range.getEndPosition(); } }; BracketSelectionRangeProvider._bracketsLeftYield = function (resolve, round, model, pos, ranges, bucket) { var counts = new Map(); var t1 = Date.now(); while (true) { if (round >= BracketSelectionRangeProvider._maxRounds && ranges.size === 0) { resolve(); break; } if (!pos) { resolve(); break; } var bracket = model.findPrevBracket(pos); if (!bracket) { resolve(); break; } var d = Date.now() - t1; if (d > BracketSelectionRangeProvider._maxDuration) { setTimeout(function () { return BracketSelectionRangeProvider._bracketsLeftYield(resolve, round + 1, model, pos, ranges, bucket); }); break; } var key = bracket.close[0]; if (!bracket.isOpen) { // wait for opening var val = counts.has(key) ? counts.get(key) : 0; counts.set(key, val + 1); } else { // opening var val = counts.has(key) ? counts.get(key) : 0; val -= 1; counts.set(key, Math.max(0, val)); if (val < 0) { var list = ranges.get(key); if (list) { var closing = list.shift(); if (list.size === 0) { ranges.delete(key); } var innerBracket = range_1.Range.fromPositions(bracket.range.getEndPosition(), closing.getStartPosition()); var 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(); } }; BracketSelectionRangeProvider._addBracketLeading = function (model, bracket, bucket) { if (bracket.startLineNumber === bracket.endLineNumber) { return; } // xxxxxxxx { // // } var startLine = bracket.startLineNumber; var 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 // { // // } var aboveLine = startLine - 1; if (aboveLine > 0) { var column_1 = model.getLineFirstNonWhitespaceColumn(aboveLine); if (column_1 === bracket.startColumn && column_1 !== model.getLineLastNonWhitespaceColumn(aboveLine)) { bucket.push({ range: range_1.Range.fromPositions(new position_1.Position(aboveLine, column_1), bracket.getEndPosition()) }); bucket.push({ range: range_1.Range.fromPositions(new position_1.Position(aboveLine, 1), bracket.getEndPosition()) }); } } }; BracketSelectionRangeProvider._maxDuration = 30; BracketSelectionRangeProvider._maxRounds = 2; return BracketSelectionRangeProvider; }()); exports.BracketSelectionRangeProvider = BracketSelectionRangeProvider; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[388/*vs/editor/contrib/smartSelect/wordSelections*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,5/*vs/base/common/strings*/]), function (require, exports, range_1, strings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var WordSelectionRangeProvider = /** @class */ (function () { function WordSelectionRangeProvider() { } WordSelectionRangeProvider.prototype.provideSelectionRanges = function (model, positions) { var result = []; for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) { var position = positions_1[_i]; var 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; }; WordSelectionRangeProvider.prototype._addInWordRanges = function (bucket, model, pos) { var obj = model.getWordAtPosition(pos); if (!obj) { return; } var word = obj.word, startColumn = obj.startColumn; var offset = pos.column - startColumn; var start = offset; var end = offset; var lastCh = 0; // LEFT anchor (start) for (; start >= 0; start--) { var ch = word.charCodeAt(start); if (ch === 95 /* Underline */ || ch === 45 /* Dash */) { // foo-bar OR foo_bar break; } else if (strings_1.isLowerAsciiLetter(ch) && strings_1.isUpperAsciiLetter(lastCh)) { // fooBar break; } lastCh = ch; } start += 1; // RIGHT anchor (end) for (; end < word.length; end++) { var ch = word.charCodeAt(end); if (strings_1.isUpperAsciiLetter(ch) && 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) }); } }; WordSelectionRangeProvider.prototype._addWordRanges = function (bucket, model, pos) { var word = model.getWordAtPosition(pos); if (word) { bucket.push({ range: new range_1.Range(pos.lineNumber, word.startColumn, pos.lineNumber, word.endColumn) }); } }; WordSelectionRangeProvider.prototype._addWhitespaceLine = function (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)) }); } }; return WordSelectionRangeProvider; }()); 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. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[151/*vs/editor/contrib/snippet/snippetParser*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; var _a; Object.defineProperty(exports, "__esModule", { value: true }); var Scanner = /** @class */ (function () { function Scanner() { this.value = ''; this.pos = 0; } Scanner.isDigitCharacter = function (ch) { return ch >= 48 /* Digit0 */ && ch <= 57 /* Digit9 */; }; Scanner.isVariableCharacter = function (ch) { return ch === 95 /* Underline */ || (ch >= 97 /* a */ && ch <= 122 /* z */) || (ch >= 65 /* A */ && ch <= 90 /* Z */); }; Scanner.prototype.text = function (value) { this.value = value; this.pos = 0; }; Scanner.prototype.tokenText = function (token) { return this.value.substr(token.pos, token.len); }; Scanner.prototype.next = function () { if (this.pos >= this.value.length) { return { type: 14 /* EOF */, pos: this.pos, len: 0 }; } var pos = this.pos; var len = 0; var ch = this.value.charCodeAt(pos); var type; // static types type = Scanner._table[ch]; if (typeof type === 'number') { this.pos += 1; return { type: type, pos: 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: type, pos: pos, len: 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: type, pos: pos, len: 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: type, pos: pos, len: len }; }; Scanner._table = (_a = {}, _a[36 /* DollarSign */] = 0 /* Dollar */, _a[58 /* Colon */] = 1 /* Colon */, _a[44 /* Comma */] = 2 /* Comma */, _a[123 /* OpenCurlyBrace */] = 3 /* CurlyOpen */, _a[125 /* CloseCurlyBrace */] = 4 /* CurlyClose */, _a[92 /* Backslash */] = 5 /* Backslash */, _a[47 /* Slash */] = 6 /* Forwardslash */, _a[124 /* Pipe */] = 7 /* Pipe */, _a[43 /* Plus */] = 11 /* Plus */, _a[45 /* Dash */] = 12 /* Dash */, _a[63 /* QuestionMark */] = 13 /* QuestionMark */, _a); return Scanner; }()); exports.Scanner = Scanner; var Marker = /** @class */ (function () { function Marker() { this._children = []; } Marker.prototype.appendChild = function (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; }; Marker.prototype.replace = function (child, others) { var parent = child.parent; var idx = parent.children.indexOf(child); var newChildren = parent.children.slice(0); newChildren.splice.apply(newChildren, __spreadArrays([idx, 1], others)); parent._children = newChildren; (function _fixParent(children, parent) { for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { var child_1 = children_1[_i]; child_1.parent = parent; _fixParent(child_1.children, child_1); } })(others, parent); }; Object.defineProperty(Marker.prototype, "children", { get: function () { return this._children; }, enumerable: true, configurable: true }); Object.defineProperty(Marker.prototype, "snippet", { get: function () { var candidate = this; while (true) { if (!candidate) { return undefined; } if (candidate instanceof TextmateSnippet) { return candidate; } candidate = candidate.parent; } }, enumerable: true, configurable: true }); Marker.prototype.toString = function () { return this.children.reduce(function (prev, cur) { return prev + cur.toString(); }, ''); }; Marker.prototype.len = function () { return 0; }; return Marker; }()); exports.Marker = Marker; var Text = /** @class */ (function (_super) { __extends(Text, _super); function Text(value) { var _this_1 = _super.call(this) || this; _this_1.value = value; return _this_1; } Text.prototype.toString = function () { return this.value; }; Text.prototype.len = function () { return this.value.length; }; Text.prototype.clone = function () { return new Text(this.value); }; return Text; }(Marker)); exports.Text = Text; var TransformableMarker = /** @class */ (function (_super) { __extends(TransformableMarker, _super); function TransformableMarker() { return _super !== null && _super.apply(this, arguments) || this; } return TransformableMarker; }(Marker)); exports.TransformableMarker = TransformableMarker; var Placeholder = /** @class */ (function (_super) { __extends(Placeholder, _super); function Placeholder(index) { var _this_1 = _super.call(this) || this; _this_1.index = index; return _this_1; } Placeholder.compareByIndex = function (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; } }; Object.defineProperty(Placeholder.prototype, "isFinalTabstop", { get: function () { return this.index === 0; }, enumerable: true, configurable: true }); Object.defineProperty(Placeholder.prototype, "choice", { get: function () { return this._children.length === 1 && this._children[0] instanceof Choice ? this._children[0] : undefined; }, enumerable: true, configurable: true }); Placeholder.prototype.clone = function () { var ret = new Placeholder(this.index); if (this.transform) { ret.transform = this.transform.clone(); } ret._children = this.children.map(function (child) { return child.clone(); }); return ret; }; return Placeholder; }(TransformableMarker)); exports.Placeholder = Placeholder; var Choice = /** @class */ (function (_super) { __extends(Choice, _super); function Choice() { var _this_1 = _super !== null && _super.apply(this, arguments) || this; _this_1.options = []; return _this_1; } Choice.prototype.appendChild = function (marker) { if (marker instanceof Text) { marker.parent = this; this.options.push(marker); } return this; }; Choice.prototype.toString = function () { return this.options[0].value; }; Choice.prototype.len = function () { return this.options[0].len(); }; Choice.prototype.clone = function () { var ret = new Choice(); this.options.forEach(ret.appendChild, ret); return ret; }; return Choice; }(Marker)); exports.Choice = Choice; var Transform = /** @class */ (function (_super) { __extends(Transform, _super); function Transform() { var _this_1 = _super !== null && _super.apply(this, arguments) || this; _this_1.regexp = new RegExp(''); return _this_1; } Transform.prototype.resolve = function (value) { var _this = this; var didMatch = false; var 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(function (child) { return child instanceof FormatString && Boolean(child.elseValue); })) { ret = this._replace([]); } return ret; }; Transform.prototype._replace = function (groups) { var ret = ''; for (var _i = 0, _a = this._children; _i < _a.length; _i++) { var marker = _a[_i]; if (marker instanceof FormatString) { var value = groups[marker.index] || ''; value = marker.resolve(value); ret += value; } else { ret += marker.toString(); } } return ret; }; Transform.prototype.toString = function () { return ''; }; Transform.prototype.clone = function () { var ret = new Transform(); ret.regexp = new RegExp(this.regexp.source, '' + (this.regexp.ignoreCase ? 'i' : '') + (this.regexp.global ? 'g' : '')); ret._children = this.children.map(function (child) { return child.clone(); }); return ret; }; return Transform; }(Marker)); exports.Transform = Transform; var FormatString = /** @class */ (function (_super) { __extends(FormatString, _super); function FormatString(index, shorthandName, ifValue, elseValue) { var _this_1 = _super.call(this) || this; _this_1.index = index; _this_1.shorthandName = shorthandName; _this_1.ifValue = ifValue; _this_1.elseValue = elseValue; return _this_1; } FormatString.prototype.resolve = function (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 (Boolean(value) && typeof this.ifValue === 'string') { return this.ifValue; } else if (!Boolean(value) && typeof this.elseValue === 'string') { return this.elseValue; } else { return value || ''; } }; FormatString.prototype._toPascalCase = function (value) { var match = value.match(/[a-z]+/gi); if (!match) { return value; } return match.map(function (word) { return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase(); }) .join(''); }; FormatString.prototype.clone = function () { var ret = new FormatString(this.index, this.shorthandName, this.ifValue, this.elseValue); return ret; }; return FormatString; }(Marker)); exports.FormatString = FormatString; var Variable = /** @class */ (function (_super) { __extends(Variable, _super); function Variable(name) { var _this_1 = _super.call(this) || this; _this_1.name = name; return _this_1; } Variable.prototype.resolve = function (resolver) { var value = resolver.resolve(this); if (this.transform) { value = this.transform.resolve(value || ''); } if (value !== undefined) { this._children = [new Text(value)]; return true; } return false; }; Variable.prototype.clone = function () { var ret = new Variable(this.name); if (this.transform) { ret.transform = this.transform.clone(); } ret._children = this.children.map(function (child) { return child.clone(); }); return ret; }; return Variable; }(TransformableMarker)); exports.Variable = Variable; function walk(marker, visitor) { var stack = __spreadArrays(marker); while (stack.length > 0) { var marker_1 = stack.shift(); var recurse = visitor(marker_1); if (!recurse) { break; } stack.unshift.apply(stack, marker_1.children); } } var TextmateSnippet = /** @class */ (function (_super) { __extends(TextmateSnippet, _super); function TextmateSnippet() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(TextmateSnippet.prototype, "placeholderInfo", { get: function () { if (!this._placeholders) { // fill in placeholders var all_1 = []; var last_1; this.walk(function (candidate) { if (candidate instanceof Placeholder) { all_1.push(candidate); last_1 = !last_1 || last_1.index < candidate.index ? candidate : last_1; } return true; }); this._placeholders = { all: all_1, last: last_1 }; } return this._placeholders; }, enumerable: true, configurable: true }); Object.defineProperty(TextmateSnippet.prototype, "placeholders", { get: function () { var all = this.placeholderInfo.all; return all; }, enumerable: true, configurable: true }); TextmateSnippet.prototype.offset = function (marker) { var pos = 0; var found = false; this.walk(function (candidate) { if (candidate === marker) { found = true; return false; } pos += candidate.len(); return true; }); if (!found) { return -1; } return pos; }; TextmateSnippet.prototype.fullLen = function (marker) { var ret = 0; walk([marker], function (marker) { ret += marker.len(); return true; }); return ret; }; TextmateSnippet.prototype.enclosingPlaceholders = function (placeholder) { var ret = []; var parent = placeholder.parent; while (parent) { if (parent instanceof Placeholder) { ret.push(parent); } parent = parent.parent; } return ret; }; TextmateSnippet.prototype.resolveVariables = function (resolver) { var _this_1 = this; this.walk(function (candidate) { if (candidate instanceof Variable) { if (candidate.resolve(resolver)) { _this_1._placeholders = undefined; } } return true; }); return this; }; TextmateSnippet.prototype.appendChild = function (child) { this._placeholders = undefined; return _super.prototype.appendChild.call(this, child); }; TextmateSnippet.prototype.replace = function (child, others) { this._placeholders = undefined; return _super.prototype.replace.call(this, child, others); }; TextmateSnippet.prototype.clone = function () { var ret = new TextmateSnippet(); this._children = this.children.map(function (child) { return child.clone(); }); return ret; }; TextmateSnippet.prototype.walk = function (visitor) { walk(this.children, visitor); }; return TextmateSnippet; }(Marker)); exports.TextmateSnippet = TextmateSnippet; var SnippetParser = /** @class */ (function () { function SnippetParser() { this._scanner = new Scanner(); this._token = { type: 14 /* EOF */, pos: 0, len: 0 }; } SnippetParser.escape = function (value) { return value.replace(/\$|}|\\/g, '\\$&'); }; SnippetParser.prototype.parse = function (value, insertFinalTabstop, enforceFinalTabstop) { this._scanner.text(value); this._token = this._scanner.next(); var 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 var placeholderDefaultValues = new Map(); var incompletePlaceholders = []; var placeholderCount = 0; snippet.walk(function (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 (var _i = 0, incompletePlaceholders_1 = incompletePlaceholders; _i < incompletePlaceholders_1.length; _i++) { var placeholder = incompletePlaceholders_1[_i]; var defaultValues = placeholderDefaultValues.get(placeholder.index); if (defaultValues) { var clone = new Placeholder(placeholder.index); clone.transform = placeholder.transform; for (var _a = 0, defaultValues_1 = defaultValues; _a < defaultValues_1.length; _a++) { var child = defaultValues_1[_a]; 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; }; SnippetParser.prototype._accept = function (type, value) { if (type === undefined || this._token.type === type) { var ret = !value ? true : this._scanner.tokenText(this._token); this._token = this._scanner.next(); return ret; } return false; }; SnippetParser.prototype._backTo = function (token) { this._scanner.pos = token.pos + token.len; this._token = token; return false; }; SnippetParser.prototype._until = function (type) { var start = this._token; while (this._token.type !== type) { if (this._token.type === 14 /* EOF */) { return false; } else if (this._token.type === 5 /* Backslash */) { var nextToken = this._scanner.next(); if (nextToken.type !== 0 /* Dollar */ && nextToken.type !== 4 /* CurlyClose */ && nextToken.type !== 5 /* Backslash */) { return false; } } this._token = this._scanner.next(); } var value = this._scanner.value.substring(start.pos, this._token.pos).replace(/\\(\$|}|\\)/g, '$1'); this._token = this._scanner.next(); return value; }; SnippetParser.prototype._parse = function (marker) { return this._parseEscaped(marker) || this._parseTabstopOrVariableName(marker) || this._parseComplexPlaceholder(marker) || this._parseComplexVariable(marker) || this._parseAnything(marker); }; // \$, \\, \} -> just text SnippetParser.prototype._parseEscaped = function (marker) { var 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 SnippetParser.prototype._parseTabstopOrVariableName = function (parent) { var value; var token = this._token; var 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 SnippetParser.prototype._parseComplexPlaceholder = function (parent) { var index; var token = this._token; var match = this._accept(0 /* Dollar */) && this._accept(3 /* CurlyOpen */) && (index = this._accept(8 /* Int */, true)); if (!match) { return this._backTo(token); } var 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|} var 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); } }; SnippetParser.prototype._parseChoiceElement = function (parent) { var token = this._token; var values = []; while (true) { if (this._token.type === 2 /* Comma */ || this._token.type === 7 /* Pipe */) { break; } var value = void 0; 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 SnippetParser.prototype._parseComplexVariable = function (parent) { var name; var token = this._token; var match = this._accept(0 /* Dollar */) && this._accept(3 /* CurlyOpen */) && (name = this._accept(9 /* VariableName */, true)); if (!match) { return this._backTo(token); } var 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); } }; SnippetParser.prototype._parseTransform = function (parent) { // ...//} var transform = new Transform(); var regexValue = ''; var regexOptions = ''; // (1) /regex while (true) { if (this._accept(6 /* Forwardslash */)) { break; } var escaped = void 0; 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; } var escaped = void 0; 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; }; SnippetParser.prototype._parseFormatString = function (parent) { var token = this._token; if (!this._accept(0 /* Dollar */)) { return false; } var complex = false; if (this._accept(3 /* CurlyOpen */)) { complex = true; } var 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} var 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:+} var 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:-} var 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:?:} var ifValue = this._until(1 /* Colon */); if (ifValue) { var elseValue = this._until(4 /* CurlyClose */); if (elseValue) { parent.appendChild(new FormatString(Number(index), undefined, ifValue, elseValue)); return true; } } } else { // ${1:} var elseValue = this._until(4 /* CurlyClose */); if (elseValue) { parent.appendChild(new FormatString(Number(index), undefined, undefined, elseValue)); return true; } } this._backTo(token); return false; }; SnippetParser.prototype._parseAnything = function (marker) { if (this._token.type !== 14 /* EOF */) { marker.appendChild(new Text(this._scanner.tokenText(this._token))); this._accept(undefined); return true; } return false; }; return SnippetParser; }()); 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[389/*vs/editor/contrib/suggest/completionModel*/], __M([0/*require*/,1/*exports*/,61/*vs/base/common/filters*/,5/*vs/base/common/strings*/]), function (require, exports, filters_1, strings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LineContext = /** @class */ (function () { function LineContext(leadingLineContent, characterCountDelta) { this.leadingLineContent = leadingLineContent; this.characterCountDelta = characterCountDelta; } return LineContext; }()); exports.LineContext = LineContext; var CompletionModel = /** @class */ (function () { function CompletionModel(items, column, lineContext, wordDistance, options, snippetSuggestions) { 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; } } Object.defineProperty(CompletionModel.prototype, "lineContext", { get: function () { return this._lineContext; }, set: function (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; } }, enumerable: true, configurable: true }); Object.defineProperty(CompletionModel.prototype, "items", { get: function () { this._ensureCachedState(); return this._filteredItems; }, enumerable: true, configurable: true }); Object.defineProperty(CompletionModel.prototype, "incomplete", { get: function () { this._ensureCachedState(); return this._isIncomplete; }, enumerable: true, configurable: true }); CompletionModel.prototype.adopt = function (except) { var res = new Array(); for (var 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; }; Object.defineProperty(CompletionModel.prototype, "stats", { get: function () { this._ensureCachedState(); return this._stats; }, enumerable: true, configurable: true }); CompletionModel.prototype._ensureCachedState = function () { if (this._refilterKind !== 0 /* Nothing */) { this._createCachedState(); } }; CompletionModel.prototype._createCachedState = function () { this._isIncomplete = new Set(); this._stats = { suggestionCount: 0, snippetCount: 0, textCount: 0 }; var _a = this._lineContext, leadingLineContent = _a.leadingLineContent, characterCountDelta = _a.characterCountDelta; var word = ''; var wordLow = ''; // incrementally filter less var source = this._refilterKind === 1 /* All */ ? this._items : this._filteredItems; var target = []; // picks a score function based on the number of // items that we have to score/filter and based on the // user-configuration var scoreFn = (!this._options.filterGraceful || source.length > 2000) ? filters_1.fuzzyScore : filters_1.fuzzyScoreGracefulAggressive; for (var i = 0; i < source.length; i++) { var item = source[i]; // collect those supports that signaled having // an incomplete result if (item.container.incomplete) { this._isIncomplete.add(item.provider); } // '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 var overwriteBefore = item.position.column - item.editStart.column; var 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) var wordPos = 0; while (wordPos < overwriteBefore) { var ch = word.charCodeAt(wordPos); if (ch === 32 /* Space */ || ch === 9 /* Tab */) { wordPos += 1; } else { break; } } var textLabel = typeof item.completion.label === 'string' ? item.completion.label : item.completion.label.name; 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 var match = scoreFn(word, wordLow, wordPos, item.completion.filterText, item.filterTextLow, 0, false); if (!match) { continue; // NO match } if (strings_1.compareIgnoreCase(item.completion.filterText, 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 = filters_1.anyScore(word, wordLow, wordPos, textLabel, item.labelLow, 0); item.score[0] = match[0]; // use score from filterText } } else { // by default match `word` against the `label` var match = scoreFn(word, wordLow, wordPos, 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 this._stats.suggestionCount++; switch (item.completion.kind) { case 25 /* Snippet */: this._stats.snippetCount++; break; case 18 /* Text */: this._stats.textCount++; break; } } this._filteredItems = target.sort(this._snippetCompareFn); this._refilterKind = 0 /* Nothing */; }; CompletionModel._compareCompletionItems = function (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; } }; CompletionModel._compareCompletionItemsSnippetsDown = function (a, b) { if (a.completion.kind !== b.completion.kind) { if (a.completion.kind === 25 /* Snippet */) { return 1; } else if (b.completion.kind === 25 /* Snippet */) { return -1; } } return CompletionModel._compareCompletionItems(a, b); }; CompletionModel._compareCompletionItemsSnippetsUp = function (a, b) { if (a.completion.kind !== b.completion.kind) { if (a.completion.kind === 25 /* Snippet */) { return -1; } else if (b.completion.kind === 25 /* Snippet */) { return 1; } } return CompletionModel._compareCompletionItems(a, b); }; return CompletionModel; }()); 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[390/*vs/editor/contrib/suggest/suggestCommitCharacters*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,79/*vs/editor/common/core/characterClassifier*/]), function (require, exports, arrays_1, lifecycle_1, characterClassifier_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CommitCharacterController = /** @class */ (function () { function CommitCharacterController(editor, widget, accept) { var _this = this; this._disposables = new lifecycle_1.DisposableStore(); this._disposables.add(widget.onDidShow(function () { return _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(function (text) { if (_this._active && !widget.isFrozen()) { var ch = text.charCodeAt(text.length - 1); if (_this._active.acceptCharacters.has(ch) && editor.getOption(0 /* acceptSuggestionOnCommitCharacter */)) { accept(_this._active.item); } } })); } CommitCharacterController.prototype._onItem = function (selected) { if (!selected || !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 var acceptCharacters = new characterClassifier_1.CharacterSet(); for (var _i = 0, _a = selected.item.completion.commitCharacters; _i < _a.length; _i++) { var ch = _a[_i]; if (ch.length > 0) { acceptCharacters.add(ch.charCodeAt(0)); } } this._active = { acceptCharacters: acceptCharacters, item: selected }; }; CommitCharacterController.prototype.reset = function () { this._active = undefined; }; CommitCharacterController.prototype.dispose = function () { this._disposables.dispose(); }; return CommitCharacterController; }()); 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[391/*vs/editor/contrib/suggest/suggestRangeHighlighter*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/,4/*vs/base/common/event*/,52/*vs/base/browser/event*/]), function (require, exports, lifecycle_1, range_1, event_1, event_2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var SuggestRangeHighlighter = /** @class */ (function () { function SuggestRangeHighlighter(_controller) { var _this = this; this._controller = _controller; this._disposables = new lifecycle_1.DisposableStore(); this._decorations = []; this._disposables.add(_controller.model.onDidSuggest(function (e) { if (!e.shy) { var widget = _this._controller.widget.getValue(); var focused = widget.getFocusedItem(); if (focused) { _this._highlight(focused.item); } if (!_this._widgetListener) { _this._widgetListener = widget.onDidFocus(function (e) { return _this._highlight(e.item); }); } } })); this._disposables.add(_controller.model.onDidCancel(function () { _this._reset(); })); } SuggestRangeHighlighter.prototype.dispose = function () { this._reset(); this._disposables.dispose(); lifecycle_1.dispose(this._widgetListener); lifecycle_1.dispose(this._shiftKeyListener); }; SuggestRangeHighlighter.prototype._reset = function () { this._decorations = this._controller.editor.deltaDecorations(this._decorations, []); if (this._shiftKeyListener) { this._shiftKeyListener.dispose(); this._shiftKeyListener = undefined; } }; SuggestRangeHighlighter.prototype._highlight = function (item) { var _this = this; var _a; this._currentItem = item; var opts = this._controller.editor.getOption(89 /* suggest */); var newDeco = []; if (opts.insertHighlight) { if (!this._shiftKeyListener) { this._shiftKeyListener = shiftKey.event(function () { return _this._highlight(_this._currentItem); }); } var info = this._controller.getOverwriteInfo(item, shiftKey.isPressed); var position = this._controller.editor.getPosition(); if (opts.insertMode === 'insert' && info.overwriteAfter > 0) { // wants inserts but got replace-mode -> highlight AFTER range newDeco = [{ range: new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column + info.overwriteAfter), options: { inlineClassName: 'suggest-insert-unexpected' } }]; } else if (opts.insertMode === 'replace' && info.overwriteAfter === 0) { // want replace but likely got insert -> highlight AFTER range var wordInfo = (_a = this._controller.editor.getModel()) === null || _a === void 0 ? void 0 : _a.getWordAtPosition(position); if (wordInfo && wordInfo.endColumn > position.column) { newDeco = [{ range: new range_1.Range(position.lineNumber, position.column, position.lineNumber, wordInfo.endColumn), options: { inlineClassName: 'suggest-insert-unexpected' } }]; } } } // update editor decorations this._decorations = this._controller.editor.deltaDecorations(this._decorations, newDeco); }; return SuggestRangeHighlighter; }()); exports.SuggestRangeHighlighter = SuggestRangeHighlighter; var shiftKey = new /** @class */ (function (_super) { __extends(ShiftKey, _super); function ShiftKey() { var _this = _super.call(this) || this; _this._subscriptions = new lifecycle_1.DisposableStore(); _this._isPressed = false; _this._subscriptions.add(event_2.domEvent(document.body, 'keydown')(function (e) { return _this.isPressed = e.shiftKey; })); _this._subscriptions.add(event_2.domEvent(document.body, 'keyup')(function () { return _this.isPressed = false; })); _this._subscriptions.add(event_2.domEvent(document.body, 'mouseleave')(function () { return _this.isPressed = false; })); _this._subscriptions.add(event_2.domEvent(document.body, 'blur')(function () { return _this.isPressed = false; })); return _this; } Object.defineProperty(ShiftKey.prototype, "isPressed", { get: function () { return this._isPressed; }, set: function (value) { if (this._isPressed !== value) { this._isPressed = value; this.fire(value); } }, enumerable: true, configurable: true }); ShiftKey.prototype.dispose = function () { this._subscriptions.dispose(); _super.prototype.dispose.call(this); }; return ShiftKey; }(event_1.Emitter)); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[392/*vs/editor/contrib/suggest/wordDistance*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,3/*vs/editor/common/core/range*/,202/*vs/editor/contrib/smartSelect/bracketSelections*/]), function (require, exports, arrays_1, range_1, bracketSelections_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var WordDistance = /** @class */ (function () { function WordDistance() { } WordDistance.create = function (service, editor) { return __awaiter(this, void 0, void 0, function () { var model, position, ranges, wordRanges; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!editor.getOption(89 /* suggest */).localityBonus) { return [2 /*return*/, WordDistance.None]; } if (!editor.hasModel()) { return [2 /*return*/, WordDistance.None]; } model = editor.getModel(); position = editor.getPosition(); if (!service.canComputeWordRanges(model.uri)) { return [2 /*return*/, WordDistance.None]; } return [4 /*yield*/, new bracketSelections_1.BracketSelectionRangeProvider().provideSelectionRanges(model, [position])]; case 1: ranges = _a.sent(); if (!ranges || ranges.length === 0 || ranges[0].length === 0) { return [2 /*return*/, WordDistance.None]; } return [4 /*yield*/, service.computeWordRanges(model.uri, ranges[0][0].range)]; case 2: wordRanges = _a.sent(); return [2 /*return*/, new /** @class */ (function (_super) { __extends(class_1, _super); function class_1() { return _super !== null && _super.apply(this, arguments) || this; } class_1.prototype.distance = function (anchor, suggestion) { if (!wordRanges || !position.equals(editor.getPosition())) { return 0; } if (suggestion.kind === 17 /* Keyword */) { return 2 << 20; } var word = typeof suggestion.label === 'string' ? suggestion.label : suggestion.label.name; var wordLines = wordRanges[word]; if (arrays_1.isFalsyOrEmpty(wordLines)) { return 2 << 20; } var idx = arrays_1.binarySearch(wordLines, range_1.Range.fromPositions(anchor), range_1.Range.compareRangesUsingStarts); var bestWordRange = idx >= 0 ? wordLines[idx] : wordLines[Math.max(0, ~idx - 1)]; var blockDistance = ranges.length; for (var _i = 0, _a = ranges[0]; _i < _a.length; _i++) { var range = _a[_i]; if (!range_1.Range.containsRange(range.range, bestWordRange)) { break; } blockDistance -= 1; } return blockDistance; }; return class_1; }(WordDistance))]; } }); }); }; WordDistance.None = new /** @class */ (function (_super) { __extends(class_2, _super); function class_2() { return _super !== null && _super.apply(this, arguments) || this; } class_2.prototype.distance = function () { return 0; }; return class_2; }(WordDistance)); return WordDistance; }()); exports.WordDistance = WordDistance; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[203/*vs/editor/standalone/common/monarch/monarchCommon*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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) { var re = /\$((\$)|(#)|(\d\d?)|[sS](\d\d?)|@(\w+))/g; var 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) { var state = inState; while (state && state.length > 0) { var rules = lexer.tokenizer[state]; if (rules) { return rules; } var 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) { var state = inState; while (state && state.length > 0) { var exist = lexer.stateNames[state]; if (exist) { return true; } var 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[393/*vs/editor/standalone/common/monarch/monarchCompile*/], __M([0/*require*/,1/*exports*/,203/*vs/editor/standalone/common/monarch/monarchCommon*/]), function (require, exports, monarchCommon) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /* * 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 (var _i = 0, obj_1 = obj; _i < obj_1.length; _i++) { var el = obj_1[_i]; 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) { var result = {}; for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var e = array_1[_i]; result[e] = true; } return result; } function createKeywordMatcher(arr, caseInsensitive) { if (caseInsensitive === void 0) { caseInsensitive = false; } if (caseInsensitive) { arr = arr.map(function (x) { return x.toLowerCase(); }); } var 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. * Also replaces @\w+ or sequences with the content of the specified attribute */ function compileRegExp(lexer, str) { var n = 0; while (str.indexOf('@') >= 0 && n < 5) { // at most 5 expansions n++; str = str.replace(/@(\w+)/g, function (s, attr) { var 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 + ')'); }); } return new RegExp(str, (lexer.ignoreCase ? 'i' : '')); } /** * 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; var 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 var scrut = -1; // -1: $!, 0-99: $n, 100+n: $Sn var oppat = tkey; var 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 var op = '~'; var 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 var tester; // special case a regexp that matches just words if ((op === '~' || op === '!~') && /^(\w|\|)*$/.test(pat)) { var inWords_1 = createKeywordMatcher(pat.split('|'), lexer.ignoreCase); tester = function (s) { return (op === '~' ? inWords_1(s) : !inWords_1(s)); }; } else if (op === '@' || op === '!@') { var 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); } var inWords_2 = createKeywordMatcher(words, lexer.ignoreCase); tester = function (s) { return (op === '@' ? inWords_2(s) : !inWords_2(s)); }; } else if (op === '~' || op === '!~') { if (pat.indexOf('$') < 0) { // precompile regular expression var re_1 = compileRegExp(lexer, '^' + pat + '$'); tester = function (s) { return (op === '~' ? re_1.test(s) : !re_1.test(s)); }; } else { tester = function (s, id, matches, state) { var re = compileRegExp(lexer, '^' + monarchCommon.substituteMatches(lexer, pat, id, matches, state) + '$'); return re.test(s); }; } } else { // if (op==='==' || op==='!=') { if (pat.indexOf('$') < 0) { var patx_1 = monarchCommon.fixCase(lexer, pat); tester = function (s) { return (op === '==' ? s === patx_1 : s !== patx_1); }; } else { var patx_2 = monarchCommon.fixCase(lexer, pat); tester = function (s, id, matches, state, eos) { var patexp = monarchCommon.substituteMatches(lexer, patx_2, 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) { var 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) var 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 { var 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)) { var results = []; for (var 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 var cases_1 = []; // for each case, push a test function and result value for (var tkey in action.cases) { if (action.cases.hasOwnProperty(tkey)) { var val = compileAction(lexer, ruleName, action.cases[tkey]); // what kind of case if (tkey === '@default' || tkey === '@' || tkey === '') { cases_1.push({ test: undefined, value: val, name: tkey }); } else if (tkey === '@eos') { cases_1.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey }); } else { cases_1.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture } } } // create a matching function var def_1 = lexer.defaultToken; return { test: function (id, matches, state, eos) { for (var _i = 0, cases_2 = cases_1; _i < cases_2.length; _i++) { var _case = cases_2[_i]; var didmatch = (!_case.test || _case.test(id, matches, state, eos)); if (didmatch) { return _case.value; } } return def_1; } }; } 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 */ var Rule = /** @class */ (function () { function Rule(name) { this.regex = new RegExp(''); this.action = { token: '' }; this.matchOnlyAtLineStart = false; this.name = ''; this.name = name; } Rule.prototype.setRegex = function (lexer, re) { var 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) + ')'); }; Rule.prototype.setAction = function (lexer, act) { this.action = compileAction(lexer, this.name, act); }; return Rule; }()); /** * 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 var lexer = {}; lexer.languageId = languageId; 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.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 var lexerMin = json; lexerMin.languageId = languageId; lexerMin.ignoreCase = lexer.ignoreCase; 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 (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) { var rule = rules_1[_i]; var 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 { var 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') { var 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 (var key in json.tokenizer) { if (json.tokenizer.hasOwnProperty(key)) { if (!lexer.start) { lexer.start = key; } var 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' } ]; } var brackets = []; for (var _i = 0, _a = json.brackets; _i < _a.length; _i++) { var el = _a[_i]; var desc = el; if (desc && Array.isArray(desc) && desc.length === 3) { desc = { token: desc[2], open: desc[0], close: desc[1] }; } if (desc.open === desc.close) { throw monarchCommon.createError(lexer, 'open and close brackets in a \'brackets\' attribute must be different: ' + desc.open + '\n hint: use the \'bracket\' attribute if matching on equal brackets is required.'); } if (typeof desc.open === 'string' && typeof desc.token === 'string' && typeof desc.close === 'string') { brackets.push({ token: desc.token + lexer.tokenPostfix, open: monarchCommon.fixCase(lexer, desc.open), close: monarchCommon.fixCase(lexer, desc.close) }); } else { throw monarchCommon.createError(lexer, 'every element in the \'brackets\' array must be a \'{open,close,token}\' object or array'); } } lexer.brackets = brackets; // Disable throw so the syntax highlighter goes, no matter what lexer.noThrow = true; return lexer; } exports.compile = compile; }); define(__m[394/*vs/nls!vs/base/browser/ui/actionbar/actionbar*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/actionbar/actionbar", 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/base/browser/ui/actionbar/actionbar*/], __M([0/*require*/,1/*exports*/,16/*vs/base/common/platform*/,394/*vs/nls!vs/base/browser/ui/actionbar/actionbar*/,2/*vs/base/common/lifecycle*/,55/*vs/base/common/actions*/,6/*vs/base/browser/dom*/,21/*vs/base/common/types*/,57/*vs/base/browser/touch*/,56/*vs/base/browser/keyboardEvent*/,4/*vs/base/common/event*/,98/*vs/base/browser/dnd*/,24/*vs/base/browser/browser*/,259/*vs/css!vs/base/browser/ui/actionbar/actionbar*/]), function (require, exports, platform, nls, lifecycle_1, actions_1, DOM, types, touch_1, keyboardEvent_1, event_1, dnd_1, browser_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var BaseActionViewItem = /** @class */ (function (_super) { __extends(BaseActionViewItem, _super); function BaseActionViewItem(context, action, options) { var _this = _super.call(this) || this; _this.options = options; _this._context = context || _this; _this._action = action; if (action instanceof actions_1.Action) { _this._register(action.onDidChange(function (event) { if (!_this.element) { // we have not been rendered yet, so there // is no point in updating the UI return; } _this.handleActionChangeEvent(event); })); } return _this; } BaseActionViewItem.prototype.handleActionChangeEvent = function (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(); } }; Object.defineProperty(BaseActionViewItem.prototype, "actionRunner", { get: function () { if (!this._actionRunner) { this._actionRunner = this._register(new actions_1.ActionRunner()); } return this._actionRunner; }, set: function (actionRunner) { this._actionRunner = actionRunner; }, enumerable: true, configurable: true }); BaseActionViewItem.prototype.getAction = function () { return this._action; }; BaseActionViewItem.prototype.isEnabled = function () { return this._action.enabled; }; BaseActionViewItem.prototype.setActionContext = function (newContext) { this._context = newContext; }; BaseActionViewItem.prototype.render = function (container) { var _this = this; var element = this.element = container; this._register(touch_1.Gesture.addTarget(container)); var 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(DOM.addDisposableListener(container, DOM.EventType.DRAG_START, function (e) { var _a; return (_a = e.dataTransfer) === null || _a === void 0 ? void 0 : _a.setData(dnd_1.DataTransfers.TEXT, _this._action.label); })); } } this._register(DOM.addDisposableListener(element, touch_1.EventType.Tap, function (e) { return _this.onClick(e); })); this._register(DOM.addDisposableListener(element, DOM.EventType.MOUSE_DOWN, function (e) { if (!enableDragging) { DOM.EventHelper.stop(e, true); // do not run when dragging is on because that would disable it } if (_this._action.enabled && e.button === 0) { DOM.addClass(element, 'active'); } })); this._register(DOM.addDisposableListener(element, DOM.EventType.CLICK, function (e) { DOM.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 (_this.options && _this.options.isMenu) { _this.onClick(e); } else { platform.setImmediate(function () { return _this.onClick(e); }); } })); this._register(DOM.addDisposableListener(element, DOM.EventType.DBLCLICK, function (e) { DOM.EventHelper.stop(e, true); })); [DOM.EventType.MOUSE_UP, DOM.EventType.MOUSE_OUT].forEach(function (event) { _this._register(DOM.addDisposableListener(element, event, function (e) { DOM.EventHelper.stop(e); DOM.removeClass(element, 'active'); })); }); }; BaseActionViewItem.prototype.onClick = function (event) { DOM.EventHelper.stop(event, true); var context; if (types.isUndefinedOrNull(this._context)) { context = event; } else { context = this._context; if (types.isObject(context)) { context.event = event; } } this.actionRunner.run(this._action, context); }; BaseActionViewItem.prototype.focus = function () { if (this.element) { this.element.focus(); DOM.addClass(this.element, 'focused'); } }; BaseActionViewItem.prototype.blur = function () { if (this.element) { this.element.blur(); DOM.removeClass(this.element, 'focused'); } }; BaseActionViewItem.prototype.updateEnabled = function () { // implement in subclass }; BaseActionViewItem.prototype.updateLabel = function () { // implement in subclass }; BaseActionViewItem.prototype.updateTooltip = function () { // implement in subclass }; BaseActionViewItem.prototype.updateClass = function () { // implement in subclass }; BaseActionViewItem.prototype.updateChecked = function () { // implement in subclass }; BaseActionViewItem.prototype.dispose = function () { if (this.element) { DOM.removeNode(this.element); this.element = undefined; } _super.prototype.dispose.call(this); }; return BaseActionViewItem; }(lifecycle_1.Disposable)); exports.BaseActionViewItem = BaseActionViewItem; var Separator = /** @class */ (function (_super) { __extends(Separator, _super); function Separator(label) { var _this = _super.call(this, Separator.ID, label, label ? 'separator text' : 'separator') || this; _this.checked = false; _this.enabled = false; return _this; } Separator.ID = 'vs.actions.separator'; return Separator; }(actions_1.Action)); exports.Separator = Separator; var ActionViewItem = /** @class */ (function (_super) { __extends(ActionViewItem, _super); function ActionViewItem(context, action, options) { if (options === void 0) { options = {}; } var _this = _super.call(this, context, action, options) || this; _this.options = options; _this.options.icon = options.icon !== undefined ? options.icon : false; _this.options.label = options.label !== undefined ? options.label : true; _this.cssClass = ''; return _this; } ActionViewItem.prototype.render = function (container) { _super.prototype.render.call(this, container); if (this.element) { this.label = DOM.append(this.element, DOM.$('a.action-label')); } if (this.label) { if (this._action.id === 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) { DOM.append(this.element, DOM.$('span.keybinding')).textContent = this.options.keybinding; } this.updateClass(); this.updateLabel(); this.updateTooltip(); this.updateEnabled(); this.updateChecked(); }; ActionViewItem.prototype.focus = function () { _super.prototype.focus.call(this); if (this.label) { this.label.focus(); } }; ActionViewItem.prototype.updateLabel = function () { if (this.options.label && this.label) { this.label.textContent = this.getAction().label; } }; ActionViewItem.prototype.updateTooltip = function () { var 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; } }; ActionViewItem.prototype.updateClass = function () { if (this.cssClass && this.label) { DOM.removeClasses(this.label, this.cssClass); } if (this.options.icon) { this.cssClass = this.getAction().class; if (this.label) { DOM.addClass(this.label, 'codicon'); if (this.cssClass) { DOM.addClasses(this.label, this.cssClass); } } this.updateEnabled(); } else { if (this.label) { DOM.removeClass(this.label, 'codicon'); } } }; ActionViewItem.prototype.updateEnabled = function () { if (this.getAction().enabled) { if (this.label) { this.label.removeAttribute('aria-disabled'); DOM.removeClass(this.label, 'disabled'); this.label.tabIndex = 0; } if (this.element) { DOM.removeClass(this.element, 'disabled'); } } else { if (this.label) { this.label.setAttribute('aria-disabled', 'true'); DOM.addClass(this.label, 'disabled'); DOM.removeTabIndexAndUpdateFocus(this.label); } if (this.element) { DOM.addClass(this.element, 'disabled'); } } }; ActionViewItem.prototype.updateChecked = function () { if (this.label) { if (this.getAction().checked) { DOM.addClass(this.label, 'checked'); } else { DOM.removeClass(this.label, 'checked'); } } }; return ActionViewItem; }(BaseActionViewItem)); exports.ActionViewItem = ActionViewItem; var defaultOptions = { orientation: 0 /* HORIZONTAL */, context: null, triggerKeys: { keys: [3 /* Enter */, 10 /* Space */], keyDown: false } }; var ActionBar = /** @class */ (function (_super) { __extends(ActionBar, _super); function ActionBar(container, options) { if (options === void 0) { options = defaultOptions; } var _this = _super.call(this) || this; _this._onDidBlur = _this._register(new event_1.Emitter()); _this.onDidBlur = _this._onDidBlur.event; _this._onDidCancel = _this._register(new event_1.Emitter()); _this.onDidCancel = _this._onDidCancel.event; _this._onDidRun = _this._register(new event_1.Emitter()); _this.onDidRun = _this._onDidRun.event; _this._onDidBeforeRun = _this._register(new event_1.Emitter()); _this.onDidBeforeRun = _this._onDidBeforeRun.event; _this.options = options; _this._context = options.context; if (!_this.options.triggerKeys) { _this.options.triggerKeys = defaultOptions.triggerKeys; } 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(function (e) { return _this._onDidRun.fire(e); })); _this._register(_this._actionRunner.onDidBeforeRun(function (e) { return _this._onDidBeforeRun.fire(e); })); _this.viewItems = []; _this.focusedItem = undefined; _this.domNode = document.createElement('div'); _this.domNode.className = 'monaco-action-bar'; if (options.animated !== false) { DOM.addClass(_this.domNode, 'animated'); } var previousKey; var nextKey; switch (_this.options.orientation) { case 0 /* HORIZONTAL */: previousKey = 15 /* LeftArrow */; nextKey = 17 /* RightArrow */; break; case 1 /* HORIZONTAL_REVERSE */: previousKey = 17 /* RightArrow */; nextKey = 15 /* LeftArrow */; _this.domNode.className += ' reverse'; break; case 2 /* VERTICAL */: previousKey = 16 /* UpArrow */; nextKey = 18 /* DownArrow */; _this.domNode.className += ' vertical'; break; case 3 /* VERTICAL_REVERSE */: previousKey = 18 /* DownArrow */; nextKey = 16 /* UpArrow */; _this.domNode.className += ' vertical reverse'; break; } _this._register(DOM.addDisposableListener(_this.domNode, DOM.EventType.KEY_DOWN, function (e) { var event = new keyboardEvent_1.StandardKeyboardEvent(e); var eventHandled = true; if (event.equals(previousKey)) { _this.focusPrevious(); } else if (event.equals(nextKey)) { _this.focusNext(); } else if (event.equals(9 /* Escape */)) { _this.cancel(); } else if (_this.isTriggerKeyEvent(event)) { // Staying out of the else branch even if not triggered if (_this.options.triggerKeys && _this.options.triggerKeys.keyDown) { _this.doTrigger(event); } } else { eventHandled = false; } if (eventHandled) { event.preventDefault(); event.stopPropagation(); } })); _this._register(DOM.addDisposableListener(_this.domNode, DOM.EventType.KEY_UP, function (e) { var event = new keyboardEvent_1.StandardKeyboardEvent(e); // Run action on Enter/Space if (_this.isTriggerKeyEvent(event)) { if (_this.options.triggerKeys && !_this.options.triggerKeys.keyDown) { _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(function () { if (document.activeElement === _this.domNode || !DOM.isAncestor(document.activeElement, _this.domNode)) { _this._onDidBlur.fire(); _this.focusedItem = undefined; } })); _this._register(_this.focusTracker.onDidFocus(function () { return _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); return _this; } ActionBar.prototype.isTriggerKeyEvent = function (event) { var ret = false; if (this.options.triggerKeys) { this.options.triggerKeys.keys.forEach(function (keyCode) { ret = ret || event.equals(keyCode); }); } return ret; }; ActionBar.prototype.updateFocusedItem = function () { for (var i = 0; i < this.actionsList.children.length; i++) { var elem = this.actionsList.children[i]; if (DOM.isAncestor(document.activeElement, elem)) { this.focusedItem = i; break; } } }; Object.defineProperty(ActionBar.prototype, "context", { get: function () { return this._context; }, set: function (context) { this._context = context; this.viewItems.forEach(function (i) { return i.setActionContext(context); }); }, enumerable: true, configurable: true }); ActionBar.prototype.getContainer = function () { return this.domNode; }; ActionBar.prototype.push = function (arg, options) { var _this = this; if (options === void 0) { options = {}; } var actions = Array.isArray(arg) ? arg : [arg]; var index = types.isNumber(options.index) ? options.index : null; actions.forEach(function (action) { var actionViewItemElement = document.createElement('li'); actionViewItemElement.className = 'action-item'; actionViewItemElement.setAttribute('role', 'presentation'); // Prevent native context menu on actions _this._register(DOM.addDisposableListener(actionViewItemElement, DOM.EventType.CONTEXT_MENU, function (e) { e.preventDefault(); e.stopPropagation(); })); var item; if (_this.options.actionViewItemProvider) { item = _this.options.actionViewItemProvider(action); } if (!item) { item = new ActionViewItem(_this.context, action, options); } item.actionRunner = _this._actionRunner; item.setActionContext(_this.context); item.render(actionViewItemElement); if (index === null || index < 0 || index >= _this.actionsList.children.length) { _this.actionsList.appendChild(actionViewItemElement); _this.viewItems.push(item); } else { _this.actionsList.insertBefore(actionViewItemElement, _this.actionsList.children[index]); _this.viewItems.splice(index, 0, item); index++; } }); }; ActionBar.prototype.clear = function () { this.viewItems = lifecycle_1.dispose(this.viewItems); DOM.clearNode(this.actionsList); }; ActionBar.prototype.isEmpty = function () { return this.viewItems.length === 0; }; ActionBar.prototype.focus = function (arg) { var selectFirst = false; var 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') { // Focus the first enabled item this.focusedItem = this.viewItems.length - 1; this.focusNext(); } else { if (index !== undefined) { this.focusedItem = index; } this.updateFocus(); } }; ActionBar.prototype.focusNext = function () { if (typeof this.focusedItem === 'undefined') { this.focusedItem = this.viewItems.length - 1; } var startIndex = this.focusedItem; var item; do { this.focusedItem = (this.focusedItem + 1) % this.viewItems.length; item = this.viewItems[this.focusedItem]; } while (this.focusedItem !== startIndex && !item.isEnabled()); if (this.focusedItem === startIndex && !item.isEnabled()) { this.focusedItem = undefined; } this.updateFocus(); }; ActionBar.prototype.focusPrevious = function () { if (typeof this.focusedItem === 'undefined') { this.focusedItem = 0; } var startIndex = this.focusedItem; var item; do { this.focusedItem = this.focusedItem - 1; if (this.focusedItem < 0) { this.focusedItem = this.viewItems.length - 1; } item = this.viewItems[this.focusedItem]; } while (this.focusedItem !== startIndex && !item.isEnabled()); if (this.focusedItem === startIndex && !item.isEnabled()) { this.focusedItem = undefined; } this.updateFocus(true); }; ActionBar.prototype.updateFocus = function (fromRight, preventScroll) { if (typeof this.focusedItem === 'undefined') { this.actionsList.focus({ preventScroll: preventScroll }); } for (var i = 0; i < this.viewItems.length; i++) { var item = this.viewItems[i]; var actionViewItem = item; if (i === this.focusedItem) { if (types.isFunction(actionViewItem.isEnabled)) { if (actionViewItem.isEnabled() && types.isFunction(actionViewItem.focus)) { actionViewItem.focus(fromRight); } else { this.actionsList.focus({ preventScroll: preventScroll }); } } } else { if (types.isFunction(actionViewItem.blur)) { actionViewItem.blur(); } } } }; ActionBar.prototype.doTrigger = function (event) { if (typeof this.focusedItem === 'undefined') { return; //nothing to focus } // trigger action var actionViewItem = this.viewItems[this.focusedItem]; if (actionViewItem instanceof BaseActionViewItem) { var context = (actionViewItem._context === null || actionViewItem._context === undefined) ? event : actionViewItem._context; this.run(actionViewItem._action, context); } }; ActionBar.prototype.cancel = function () { if (document.activeElement instanceof HTMLElement) { document.activeElement.blur(); // remove focus from focused action } this._onDidCancel.fire(); }; ActionBar.prototype.run = function (action, context) { return this._actionRunner.run(action, context); }; ActionBar.prototype.dispose = function () { lifecycle_1.dispose(this.viewItems); this.viewItems = []; DOM.removeNode(this.getContainer()); _super.prototype.dispose.call(this); }; return ActionBar; }(lifecycle_1.Disposable)); exports.ActionBar = ActionBar; }); define(__m[395/*vs/nls!vs/base/browser/ui/aria/aria*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/aria/aria", data); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[50/*vs/base/browser/ui/aria/aria*/], __M([0/*require*/,1/*exports*/,395/*vs/nls!vs/base/browser/ui/aria/aria*/,16/*vs/base/common/platform*/,6/*vs/base/browser/dom*/,260/*vs/css!vs/base/browser/ui/aria/aria*/]), function (require, exports, nls, platform_1, dom) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ariaContainer; var alertContainer; var statusContainer; function setARIAContainer(parent) { ariaContainer = document.createElement('div'); ariaContainer.className = 'monaco-aria-container'; alertContainer = document.createElement('div'); alertContainer.className = 'monaco-alert'; alertContainer.setAttribute('role', 'alert'); alertContainer.setAttribute('aria-atomic', 'true'); ariaContainer.appendChild(alertContainer); statusContainer = document.createElement('div'); statusContainer.className = 'monaco-status'; statusContainer.setAttribute('role', 'status'); statusContainer.setAttribute('aria-atomic', 'true'); ariaContainer.appendChild(statusContainer); 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, disableRepeat) { insertMessage(alertContainer, msg, disableRepeat); } exports.alert = alert; /** * Given the provided message, will make sure that it is read as status to screen readers. */ function status(msg, disableRepeat) { if (platform_1.isMacintosh) { alert(msg, disableRepeat); // VoiceOver does not seem to support status role } else { insertMessage(statusContainer, msg, disableRepeat); } } exports.status = status; var repeatedTimes = 0; var prevText = undefined; function insertMessage(target, msg, disableRepeat) { if (!ariaContainer) { return; } // If the same message should be inserted that is already present, a screen reader would // not announce this message because it matches the previous one. As a workaround, we // alter the message with the number of occurences unless this is explicitly disabled // via the disableRepeat flag. if (!disableRepeat) { if (prevText === msg) { repeatedTimes++; } else { prevText = msg; repeatedTimes = 0; } switch (repeatedTimes) { case 0: break; case 1: msg = nls.localize(0, null, msg); break; default: msg = nls.localize(1, null, msg, repeatedTimes); break; } } dom.clearNode(target); 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[396/*vs/nls!vs/base/browser/ui/findinput/findInput*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/findinput/findInput", data); }); define(__m[397/*vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes*/], __M([7/*vs/nls*/,8/*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[204/*vs/base/browser/ui/findinput/findInputCheckboxes*/], __M([0/*require*/,1/*exports*/,138/*vs/base/browser/ui/checkbox/checkbox*/,397/*vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes*/]), function (require, exports, checkbox_1, nls) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var NLS_CASE_SENSITIVE_CHECKBOX_LABEL = nls.localize(0, null); var NLS_WHOLE_WORD_CHECKBOX_LABEL = nls.localize(1, null); var NLS_REGEX_CHECKBOX_LABEL = nls.localize(2, null); var CaseSensitiveCheckbox = /** @class */ (function (_super) { __extends(CaseSensitiveCheckbox, _super); function CaseSensitiveCheckbox(opts) { return _super.call(this, { actionClassName: 'codicon-case-sensitive', title: NLS_CASE_SENSITIVE_CHECKBOX_LABEL + opts.appendTitle, isChecked: opts.isChecked, inputActiveOptionBorder: opts.inputActiveOptionBorder, inputActiveOptionBackground: opts.inputActiveOptionBackground }) || this; } return CaseSensitiveCheckbox; }(checkbox_1.Checkbox)); exports.CaseSensitiveCheckbox = CaseSensitiveCheckbox; var WholeWordsCheckbox = /** @class */ (function (_super) { __extends(WholeWordsCheckbox, _super); function WholeWordsCheckbox(opts) { return _super.call(this, { actionClassName: 'codicon-whole-word', title: NLS_WHOLE_WORD_CHECKBOX_LABEL + opts.appendTitle, isChecked: opts.isChecked, inputActiveOptionBorder: opts.inputActiveOptionBorder, inputActiveOptionBackground: opts.inputActiveOptionBackground }) || this; } return WholeWordsCheckbox; }(checkbox_1.Checkbox)); exports.WholeWordsCheckbox = WholeWordsCheckbox; var RegexCheckbox = /** @class */ (function (_super) { __extends(RegexCheckbox, _super); function RegexCheckbox(opts) { return _super.call(this, { actionClassName: 'codicon-regex', title: NLS_REGEX_CHECKBOX_LABEL + opts.appendTitle, isChecked: opts.isChecked, inputActiveOptionBorder: opts.inputActiveOptionBorder, inputActiveOptionBackground: opts.inputActiveOptionBackground }) || this; } return RegexCheckbox; }(checkbox_1.Checkbox)); exports.RegexCheckbox = RegexCheckbox; }); define(__m[398/*vs/nls!vs/base/browser/ui/findinput/replaceInput*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/findinput/replaceInput", data); }); define(__m[399/*vs/nls!vs/base/browser/ui/inputbox/inputBox*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/inputbox/inputBox", 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[152/*vs/base/browser/ui/inputbox/inputBox*/], __M([0/*require*/,1/*exports*/,399/*vs/nls!vs/base/browser/ui/inputbox/inputBox*/,24/*vs/base/browser/browser*/,6/*vs/base/browser/dom*/,134/*vs/base/browser/formattedTextRenderer*/,50/*vs/base/browser/ui/aria/aria*/,70/*vs/base/browser/ui/actionbar/actionbar*/,4/*vs/base/common/event*/,47/*vs/base/browser/ui/widget*/,27/*vs/base/common/color*/,31/*vs/base/common/objects*/,242/*vs/base/common/history*/,53/*vs/base/browser/ui/scrollbar/scrollableElement*/,52/*vs/base/browser/event*/,269/*vs/css!vs/base/browser/ui/inputbox/inputBox*/]), function (require, exports, nls, Bal, dom, formattedTextRenderer_1, aria, actionbar_1, event_1, widget_1, color_1, objects_1, history_1, scrollableElement_1, event_2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var $ = dom.$; var 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') }; var InputBox = /** @class */ (function (_super) { __extends(InputBox, _super); function InputBox(container, contextViewProvider, options) { var _this = _super.call(this) || this; _this.state = 'idle'; _this.maxHeight = Number.POSITIVE_INFINITY; _this._onDidChange = _this._register(new event_1.Emitter()); _this.onDidChange = _this._onDidChange.event; _this._onDidHeightChange = _this._register(new event_1.Emitter()); _this.onDidHeightChange = _this._onDidHeightChange.event; _this.contextViewProvider = contextViewProvider; _this.options = options || Object.create(null); objects_1.mixin(_this.options, defaultOpts, false); _this.message = null; _this.placeholder = _this.options.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')); var tagName = _this.options.flexibleHeight ? 'textarea' : 'input'; var wrapper = dom.append(_this.element, $('.wrapper')); _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, function () { return dom.addClass(_this.element, 'synthetic-focus'); }); _this.onblur(_this.input, function () { return dom.removeClass(_this.element, '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.innerHTML = ' '; _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(function (e) { return _this.input.scrollTop = e.scrollTop; })); var onSelectionChange = event_1.Event.filter(event_2.domEvent(document, 'selectionchange'), function () { var selection = document.getSelection(); return (selection === null || selection === void 0 ? void 0 : selection.anchorNode) === wrapper; }); // from DOM to ScrollableElement _this._register(onSelectionChange(_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.setPlaceHolder(_this.placeholder); } _this.oninput(_this.input, function () { return _this.onValueChange(); }); _this.onblur(_this.input, function () { return _this.onBlur(); }); _this.onfocus(_this.input, function () { return _this.onFocus(); }); // Add placeholder shim for IE because IE decides to hide the placeholder on focus (we dont want that!) if (_this.placeholder && Bal.isIE) { _this.onclick(_this.input, function (e) { dom.EventHelper.stop(e, true); _this.input.focus(); }); } _this.ignoreGesture(_this.input); setTimeout(function () { return _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(); return _this; } InputBox.prototype.onBlur = function () { this._hideMessage(); }; InputBox.prototype.onFocus = function () { this._showMessage(); }; InputBox.prototype.setPlaceHolder = function (placeHolder) { this.placeholder = placeHolder; this.input.setAttribute('placeholder', placeHolder); this.input.title = placeHolder; }; InputBox.prototype.setAriaLabel = function (label) { this.ariaLabel = label; if (label) { this.input.setAttribute('aria-label', this.ariaLabel); } else { this.input.removeAttribute('aria-label'); } }; Object.defineProperty(InputBox.prototype, "inputElement", { get: function () { return this.input; }, enumerable: true, configurable: true }); Object.defineProperty(InputBox.prototype, "value", { get: function () { return this.input.value; }, set: function (newValue) { if (this.input.value !== newValue) { this.input.value = newValue; this.onValueChange(); } }, enumerable: true, configurable: true }); Object.defineProperty(InputBox.prototype, "height", { get: function () { return typeof this.cachedHeight === 'number' ? this.cachedHeight : dom.getTotalHeight(this.element); }, enumerable: true, configurable: true }); InputBox.prototype.focus = function () { this.input.focus(); }; InputBox.prototype.blur = function () { this.input.blur(); }; InputBox.prototype.hasFocus = function () { return document.activeElement === this.input; }; InputBox.prototype.select = function (range) { if (range === void 0) { range = null; } this.input.select(); if (range) { this.input.setSelectionRange(range.start, range.end); } }; InputBox.prototype.enable = function () { this.input.removeAttribute('disabled'); }; InputBox.prototype.disable = function () { this.blur(); this.input.disabled = true; this._hideMessage(); }; Object.defineProperty(InputBox.prototype, "width", { get: function () { return dom.getTotalWidth(this.input); }, set: function (width) { if (this.options.flexibleHeight && this.options.flexibleWidth) { // textarea with horizontal scrolling var horizontalPadding = 0; if (this.mirror) { var paddingLeft = parseFloat(this.mirror.style.paddingLeft || '') || 0; var 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'; } }, enumerable: true, configurable: true }); Object.defineProperty(InputBox.prototype, "paddingRight", { set: function (paddingRight) { if (this.options.flexibleHeight && this.options.flexibleWidth) { this.input.style.width = "calc(100% - " + paddingRight + "px)"; } else { this.input.style.paddingRight = paddingRight + 'px'; } if (this.mirror) { this.mirror.style.paddingRight = paddingRight + 'px'; } }, enumerable: true, configurable: true }); InputBox.prototype.updateScrollDimensions = function () { if (typeof this.cachedContentHeight !== 'number' || typeof this.cachedHeight !== 'number' || !this.scrollableElement) { return; } var scrollHeight = this.cachedContentHeight; var height = this.cachedHeight; var scrollTop = this.input.scrollTop; this.scrollableElement.setScrollDimensions({ scrollHeight: scrollHeight, height: height }); this.scrollableElement.setScrollPosition({ scrollTop: scrollTop }); }; InputBox.prototype.showMessage = function (message, force) { this.message = message; dom.removeClass(this.element, 'idle'); dom.removeClass(this.element, 'info'); dom.removeClass(this.element, 'warning'); dom.removeClass(this.element, 'error'); dom.addClass(this.element, this.classForType(message.type)); var styles = this.stylesForType(this.message.type); this.element.style.border = styles.border ? "1px solid " + styles.border : ''; // ARIA Support var alertText; if (message.type === 3 /* ERROR */) { alertText = nls.localize(0, null, message.content); } else if (message.type === 2 /* WARNING */) { alertText = nls.localize(1, null, message.content); } else { alertText = nls.localize(2, null, message.content); } aria.alert(alertText); if (this.hasFocus() || force) { this._showMessage(); } }; InputBox.prototype.hideMessage = function () { this.message = null; dom.removeClass(this.element, 'info'); dom.removeClass(this.element, 'warning'); dom.removeClass(this.element, 'error'); dom.addClass(this.element, 'idle'); this._hideMessage(); this.applyStyles(); }; InputBox.prototype.validate = function () { var 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; }; InputBox.prototype.stylesForType = function (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 }; } }; InputBox.prototype.classForType = function (type) { switch (type) { case 1 /* INFO */: return 'info'; case 2 /* WARNING */: return 'warning'; default: return 'error'; } }; InputBox.prototype._showMessage = function () { var _this = this; if (!this.contextViewProvider || !this.message) { return; } var div; var layout = function () { return div.style.width = dom.getTotalWidth(_this.element) + 'px'; }; this.contextViewProvider.showContextView({ getAnchor: function () { return _this.element; }, anchorAlignment: 1 /* RIGHT */, render: function (container) { if (!_this.message) { return null; } div = dom.append(container, $('.monaco-inputbox-container')); layout(); var renderOptions = { inline: true, className: 'monaco-inputbox-message' }; var spanElement = (_this.message.formatContent ? formattedTextRenderer_1.renderFormattedText(_this.message.content, renderOptions) : formattedTextRenderer_1.renderText(_this.message.content, renderOptions)); dom.addClass(spanElement, _this.classForType(_this.message.type)); var 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: function () { _this.state = 'closed'; }, layout: layout }); this.state = 'open'; }; InputBox.prototype._hideMessage = function () { if (!this.contextViewProvider) { return; } if (this.state === 'open') { this.contextViewProvider.hideContextView(); } this.state = 'idle'; }; InputBox.prototype.onValueChange = function () { this._onDidChange.fire(this.value); this.validate(); this.updateMirror(); dom.toggleClass(this.input, 'empty', !this.value); if (this.state === 'open' && this.contextViewProvider) { this.contextViewProvider.layout(); } }; InputBox.prototype.updateMirror = function () { if (!this.mirror) { return; } var value = this.value; var lastCharCode = value.charCodeAt(value.length - 1); var suffix = lastCharCode === 10 ? ' ' : ''; var mirrorTextContent = value + suffix; if (mirrorTextContent) { this.mirror.textContent = value + suffix; } else { this.mirror.innerHTML = ' '; } this.layout(); }; InputBox.prototype.style = function (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(); }; InputBox.prototype.applyStyles = function () { var background = this.inputBackground ? this.inputBackground.toString() : ''; var foreground = this.inputForeground ? this.inputForeground.toString() : ''; var border = this.inputBorder ? this.inputBorder.toString() : ''; this.element.style.backgroundColor = background; this.element.style.color = foreground; this.input.style.backgroundColor = background; this.input.style.color = foreground; this.element.style.borderWidth = border ? '1px' : ''; this.element.style.borderStyle = border ? 'solid' : ''; this.element.style.borderColor = border; }; InputBox.prototype.layout = function () { if (!this.mirror) { return; } var 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); } }; InputBox.prototype.insertAtCursor = function (text) { var inputElement = this.inputElement; var start = inputElement.selectionStart; var end = inputElement.selectionEnd; var 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(); } }; InputBox.prototype.dispose = function () { this._hideMessage(); this.message = null; if (this.actionbar) { this.actionbar.dispose(); } _super.prototype.dispose.call(this); }; return InputBox; }(widget_1.Widget)); exports.InputBox = InputBox; var HistoryInputBox = /** @class */ (function (_super) { __extends(HistoryInputBox, _super); function HistoryInputBox(container, contextViewProvider, options) { var _this = _super.call(this, container, contextViewProvider, options) || this; _this.history = new history_1.HistoryNavigator(options.history, 100); return _this; } HistoryInputBox.prototype.addToHistory = function () { if (this.value && this.value !== this.getCurrentValue()) { this.history.add(this.value); } }; HistoryInputBox.prototype.showNextValue = function () { if (!this.history.has(this.value)) { this.addToHistory(); } var next = this.getNextValue(); if (next) { next = next === this.value ? this.getNextValue() : next; } if (next) { this.value = next; aria.status(this.value); } }; HistoryInputBox.prototype.showPreviousValue = function () { if (!this.history.has(this.value)) { this.addToHistory(); } var previous = this.getPreviousValue(); if (previous) { previous = previous === this.value ? this.getPreviousValue() : previous; } if (previous) { this.value = previous; aria.status(this.value); } }; HistoryInputBox.prototype.getCurrentValue = function () { var currentValue = this.history.current(); if (!currentValue) { currentValue = this.history.last(); this.history.next(); } return currentValue; }; HistoryInputBox.prototype.getPreviousValue = function () { return this.history.previous() || this.history.first(); }; HistoryInputBox.prototype.getNextValue = function () { return this.history.next() || this.history.last(); }; return HistoryInputBox; }(InputBox)); 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[400/*vs/base/browser/ui/findinput/findInput*/], __M([0/*require*/,1/*exports*/,396/*vs/nls!vs/base/browser/ui/findinput/findInput*/,6/*vs/base/browser/dom*/,152/*vs/base/browser/ui/inputbox/inputBox*/,47/*vs/base/browser/ui/widget*/,4/*vs/base/common/event*/,204/*vs/base/browser/ui/findinput/findInputCheckboxes*/,184/*vs/css!vs/base/browser/ui/findinput/findInput*/]), function (require, exports, nls, dom, inputBox_1, widget_1, event_1, findInputCheckboxes_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var NLS_DEFAULT_LABEL = nls.localize(0, null); var FindInput = /** @class */ (function (_super) { __extends(FindInput, _super); function FindInput(parent, contextViewProvider, _showOptionButtons, options) { var _this = _super.call(this) || this; _this._showOptionButtons = _showOptionButtons; _this.fixFocusOnOptionClickEnabled = true; _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.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; var appendCaseSensitiveLabel = options.appendCaseSensitiveLabel || ''; var appendWholeWordsLabel = options.appendWholeWordsLabel || ''; var appendRegexLabel = options.appendRegexLabel || ''; var history = options.history || []; var flexibleHeight = !!options.flexibleHeight; var flexibleWidth = !!options.flexibleWidth; var flexibleMaxHeight = options.flexibleMaxHeight; _this.domNode = document.createElement('div'); dom.addClass(_this.domNode, '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: history, flexibleHeight: flexibleHeight, flexibleWidth: flexibleWidth, flexibleMaxHeight: flexibleMaxHeight })); _this.regex = _this._register(new findInputCheckboxes_1.RegexCheckbox({ appendTitle: appendRegexLabel, isChecked: false, inputActiveOptionBorder: _this.inputActiveOptionBorder, inputActiveOptionBackground: _this.inputActiveOptionBackground })); _this._register(_this.regex.onChange(function (viaKeyboard) { _this._onDidOptionChange.fire(viaKeyboard); if (!viaKeyboard && _this.fixFocusOnOptionClickEnabled) { _this.inputBox.focus(); } _this.validate(); })); _this._register(_this.regex.onKeyDown(function (e) { _this._onRegexKeyDown.fire(e); })); _this.wholeWords = _this._register(new findInputCheckboxes_1.WholeWordsCheckbox({ appendTitle: appendWholeWordsLabel, isChecked: false, inputActiveOptionBorder: _this.inputActiveOptionBorder, inputActiveOptionBackground: _this.inputActiveOptionBackground })); _this._register(_this.wholeWords.onChange(function (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, inputActiveOptionBackground: _this.inputActiveOptionBackground })); _this._register(_this.caseSensitive.onChange(function (viaKeyboard) { _this._onDidOptionChange.fire(viaKeyboard); if (!viaKeyboard && _this.fixFocusOnOptionClickEnabled) { _this.inputBox.focus(); } _this.validate(); })); _this._register(_this.caseSensitive.onKeyDown(function (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 var indexes = [_this.caseSensitive.domNode, _this.wholeWords.domNode, _this.regex.domNode]; _this.onkeydown(_this.domNode, function (event) { if (event.equals(15 /* LeftArrow */) || event.equals(17 /* RightArrow */) || event.equals(9 /* Escape */)) { var index = indexes.indexOf(document.activeElement); if (index >= 0) { var 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(); } else if (newIndex >= 0) { indexes[newIndex].focus(); } dom.EventHelper.stop(event, true); } } }); var controls = document.createElement('div'); controls.className = 'controls'; controls.style.display = _this._showOptionButtons ? 'block' : 'none'; controls.appendChild(_this.caseSensitive.domNode); controls.appendChild(_this.wholeWords.domNode); controls.appendChild(_this.regex.domNode); _this.domNode.appendChild(controls); if (parent) { parent.appendChild(_this.domNode); } _this.onkeydown(_this.inputBox.inputElement, function (e) { return _this._onKeyDown.fire(e); }); _this.onkeyup(_this.inputBox.inputElement, function (e) { return _this._onKeyUp.fire(e); }); _this.oninput(_this.inputBox.inputElement, function (e) { return _this._onInput.fire(); }); _this.onmousedown(_this.inputBox.inputElement, function (e) { return _this._onMouseDown.fire(e); }); return _this; } FindInput.prototype.enable = function () { dom.removeClass(this.domNode, 'disabled'); this.inputBox.enable(); this.regex.enable(); this.wholeWords.enable(); this.caseSensitive.enable(); }; FindInput.prototype.disable = function () { dom.addClass(this.domNode, 'disabled'); this.inputBox.disable(); this.regex.disable(); this.wholeWords.disable(); this.caseSensitive.disable(); }; FindInput.prototype.setFocusInputOnOptionClick = function (value) { this.fixFocusOnOptionClickEnabled = value; }; FindInput.prototype.setEnabled = function (enabled) { if (enabled) { this.enable(); } else { this.disable(); } }; FindInput.prototype.getValue = function () { return this.inputBox.value; }; FindInput.prototype.setValue = function (value) { if (this.inputBox.value !== value) { this.inputBox.value = value; } }; FindInput.prototype.style = function (styles) { this.inputActiveOptionBorder = styles.inputActiveOptionBorder; 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(); }; FindInput.prototype.applyStyles = function () { if (this.domNode) { var checkBoxStyles = { inputActiveOptionBorder: this.inputActiveOptionBorder, inputActiveOptionBackground: this.inputActiveOptionBackground, }; this.regex.style(checkBoxStyles); this.wholeWords.style(checkBoxStyles); this.caseSensitive.style(checkBoxStyles); var 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); } }; FindInput.prototype.select = function () { this.inputBox.select(); }; FindInput.prototype.focus = function () { this.inputBox.focus(); }; FindInput.prototype.getCaseSensitive = function () { return this.caseSensitive.checked; }; FindInput.prototype.setCaseSensitive = function (value) { this.caseSensitive.checked = value; }; FindInput.prototype.getWholeWords = function () { return this.wholeWords.checked; }; FindInput.prototype.setWholeWords = function (value) { this.wholeWords.checked = value; }; FindInput.prototype.getRegex = function () { return this.regex.checked; }; FindInput.prototype.setRegex = function (value) { this.regex.checked = value; this.validate(); }; FindInput.prototype.focusOnCaseSensitive = function () { this.caseSensitive.focus(); }; FindInput.prototype.highlightFindOptions = function () { dom.removeClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions)); this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions; dom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions)); }; FindInput.prototype.validate = function () { this.inputBox.validate(); }; FindInput.prototype.clearMessage = function () { this.inputBox.hideMessage(); }; return FindInput; }(widget_1.Widget)); 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[401/*vs/base/browser/ui/findinput/replaceInput*/], __M([0/*require*/,1/*exports*/,398/*vs/nls!vs/base/browser/ui/findinput/replaceInput*/,6/*vs/base/browser/dom*/,152/*vs/base/browser/ui/inputbox/inputBox*/,47/*vs/base/browser/ui/widget*/,4/*vs/base/common/event*/,138/*vs/base/browser/ui/checkbox/checkbox*/,184/*vs/css!vs/base/browser/ui/findinput/findInput*/]), function (require, exports, nls, dom, inputBox_1, widget_1, event_1, checkbox_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var NLS_DEFAULT_LABEL = nls.localize(0, null); var NLS_PRESERVE_CASE_LABEL = nls.localize(1, null); var PreserveCaseCheckbox = /** @class */ (function (_super) { __extends(PreserveCaseCheckbox, _super); function PreserveCaseCheckbox(opts) { return _super.call(this, { // TODO: does this need its own icon? actionClassName: 'codicon-preserve-case', title: NLS_PRESERVE_CASE_LABEL + opts.appendTitle, isChecked: opts.isChecked, inputActiveOptionBorder: opts.inputActiveOptionBorder, inputActiveOptionBackground: opts.inputActiveOptionBackground }) || this; } return PreserveCaseCheckbox; }(checkbox_1.Checkbox)); exports.PreserveCaseCheckbox = PreserveCaseCheckbox; var ReplaceInput = /** @class */ (function (_super) { __extends(ReplaceInput, _super); function ReplaceInput(parent, contextViewProvider, _showOptionButtons, options) { var _this = _super.call(this) || this; _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.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; var history = options.history || []; var flexibleHeight = !!options.flexibleHeight; var flexibleWidth = !!options.flexibleWidth; var flexibleMaxHeight = options.flexibleMaxHeight; _this.domNode = document.createElement('div'); dom.addClass(_this.domNode, '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: history, flexibleHeight: flexibleHeight, flexibleWidth: flexibleWidth, flexibleMaxHeight: flexibleMaxHeight })); _this.preserveCase = _this._register(new PreserveCaseCheckbox({ appendTitle: '', isChecked: false, inputActiveOptionBorder: _this.inputActiveOptionBorder, inputActiveOptionBackground: _this.inputActiveOptionBackground, })); _this._register(_this.preserveCase.onChange(function (viaKeyboard) { _this._onDidOptionChange.fire(viaKeyboard); if (!viaKeyboard && _this.fixFocusOnOptionClickEnabled) { _this.inputBox.focus(); } _this.validate(); })); _this._register(_this.preserveCase.onKeyDown(function (e) { _this._onPreserveCaseKeyDown.fire(e); })); if (_this._showOptionButtons) { _this.cachedOptionsWidth = _this.preserveCase.width(); } else { _this.cachedOptionsWidth = 0; } // Arrow-Key support to navigate between options var indexes = [_this.preserveCase.domNode]; _this.onkeydown(_this.domNode, function (event) { if (event.equals(15 /* LeftArrow */) || event.equals(17 /* RightArrow */) || event.equals(9 /* Escape */)) { var index = indexes.indexOf(document.activeElement); if (index >= 0) { var 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(); } else if (newIndex >= 0) { indexes[newIndex].focus(); } dom.EventHelper.stop(event, true); } } }); var 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, function (e) { return _this._onKeyDown.fire(e); }); _this.onkeyup(_this.inputBox.inputElement, function (e) { return _this._onKeyUp.fire(e); }); _this.oninput(_this.inputBox.inputElement, function (e) { return _this._onInput.fire(); }); _this.onmousedown(_this.inputBox.inputElement, function (e) { return _this._onMouseDown.fire(e); }); return _this; } ReplaceInput.prototype.enable = function () { dom.removeClass(this.domNode, 'disabled'); this.inputBox.enable(); this.preserveCase.enable(); }; ReplaceInput.prototype.disable = function () { dom.addClass(this.domNode, 'disabled'); this.inputBox.disable(); this.preserveCase.disable(); }; ReplaceInput.prototype.setEnabled = function (enabled) { if (enabled) { this.enable(); } else { this.disable(); } }; ReplaceInput.prototype.style = function (styles) { this.inputActiveOptionBorder = styles.inputActiveOptionBorder; 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(); }; ReplaceInput.prototype.applyStyles = function () { if (this.domNode) { var checkBoxStyles = { inputActiveOptionBorder: this.inputActiveOptionBorder, inputActiveOptionBackground: this.inputActiveOptionBackground, }; this.preserveCase.style(checkBoxStyles); var 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); } }; ReplaceInput.prototype.select = function () { this.inputBox.select(); }; ReplaceInput.prototype.focus = function () { this.inputBox.focus(); }; ReplaceInput.prototype.getPreserveCase = function () { return this.preserveCase.checked; }; ReplaceInput.prototype.setPreserveCase = function (value) { this.preserveCase.checked = value; }; ReplaceInput.prototype.focusOnPreserve = function () { this.preserveCase.focus(); }; ReplaceInput.prototype.validate = function () { if (this.inputBox) { this.inputBox.validate(); } }; Object.defineProperty(ReplaceInput.prototype, "width", { set: function (newWidth) { this.inputBox.paddingRight = this.cachedOptionsWidth; this.inputBox.width = newWidth; this.domNode.style.width = newWidth + 'px'; }, enumerable: true, configurable: true }); ReplaceInput.prototype.dispose = function () { _super.prototype.dispose.call(this); }; return ReplaceInput; }(widget_1.Widget)); exports.ReplaceInput = ReplaceInput; }); define(__m[402/*vs/nls!vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/keybindingLabel/keybindingLabel", data); }); define(__m[403/*vs/nls!vs/base/browser/ui/list/listWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/list/listWidget", data); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[153/*vs/base/browser/ui/list/listWidget*/], __M([0/*require*/,1/*exports*/,403/*vs/nls!vs/base/browser/ui/list/listWidget*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/types*/,19/*vs/base/common/arrays*/,101/*vs/base/common/decorators*/,6/*vs/base/browser/dom*/,16/*vs/base/common/platform*/,57/*vs/base/browser/touch*/,56/*vs/base/browser/keyboardEvent*/,4/*vs/base/common/event*/,52/*vs/base/browser/event*/,239/*vs/base/browser/ui/list/list*/,140/*vs/base/browser/ui/list/listView*/,27/*vs/base/common/color*/,31/*vs/base/common/objects*/,240/*vs/base/browser/ui/list/splice*/,131/*vs/base/common/numbers*/,61/*vs/base/common/filters*/,271/*vs/css!vs/base/browser/ui/list/list*/]), function (require, exports, nls_1, lifecycle_1, types_1, arrays_1, decorators_1, DOM, platform, touch_1, keyboardEvent_1, event_1, event_2, list_1, listView_1, color_1, objects_1, splice_1, numbers_1, filters_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var TraitRenderer = /** @class */ (function () { function TraitRenderer(trait) { this.trait = trait; this.renderedElements = []; } Object.defineProperty(TraitRenderer.prototype, "templateId", { get: function () { return "template:" + this.trait.trait; }, enumerable: true, configurable: true }); TraitRenderer.prototype.renderTemplate = function (container) { return container; }; TraitRenderer.prototype.renderElement = function (element, index, templateData) { var renderedElementIndex = arrays_1.firstIndex(this.renderedElements, function (el) { return el.templateData === templateData; }); if (renderedElementIndex >= 0) { var rendered = this.renderedElements[renderedElementIndex]; this.trait.unrender(templateData); rendered.index = index; } else { var rendered = { index: index, templateData: templateData }; this.renderedElements.push(rendered); } this.trait.renderIndex(index, templateData); }; TraitRenderer.prototype.splice = function (start, deleteCount, insertCount) { var rendered = []; for (var _i = 0, _a = this.renderedElements; _i < _a.length; _i++) { var renderedElement = _a[_i]; 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; }; TraitRenderer.prototype.renderIndexes = function (indexes) { for (var _i = 0, _a = this.renderedElements; _i < _a.length; _i++) { var _b = _a[_i], index = _b.index, templateData = _b.templateData; if (indexes.indexOf(index) > -1) { this.trait.renderIndex(index, templateData); } } }; TraitRenderer.prototype.disposeTemplate = function (templateData) { var index = arrays_1.firstIndex(this.renderedElements, function (el) { return el.templateData === templateData; }); if (index < 0) { return; } this.renderedElements.splice(index, 1); }; return TraitRenderer; }()); var Trait = /** @class */ (function () { function Trait(_trait) { this._trait = _trait; this.indexes = []; this.sortedIndexes = []; this._onChange = new event_1.Emitter(); this.onChange = this._onChange.event; } Object.defineProperty(Trait.prototype, "trait", { get: function () { return this._trait; }, enumerable: true, configurable: true }); Object.defineProperty(Trait.prototype, "renderer", { get: function () { return new TraitRenderer(this); }, enumerable: true, configurable: true }); Trait.prototype.splice = function (start, deleteCount, elements) { var diff = elements.length - deleteCount; var end = start + deleteCount; var indexes = __spreadArrays(this.sortedIndexes.filter(function (i) { return i < start; }), elements.map(function (hasTrait, i) { return hasTrait ? i + start : -1; }).filter(function (i) { return i !== -1; }), this.sortedIndexes.filter(function (i) { return i >= end; }).map(function (i) { return i + diff; })); this.renderer.splice(start, deleteCount, elements.length); this._set(indexes, indexes); }; Trait.prototype.renderIndex = function (index, container) { DOM.toggleClass(container, this._trait, this.contains(index)); }; Trait.prototype.unrender = function (container) { DOM.removeClass(container, 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. */ Trait.prototype.set = function (indexes, browserEvent) { return this._set(indexes, __spreadArrays(indexes).sort(numericSort), browserEvent); }; Trait.prototype._set = function (indexes, sortedIndexes, browserEvent) { var result = this.indexes; var sortedResult = this.sortedIndexes; this.indexes = indexes; this.sortedIndexes = sortedIndexes; var toRender = disjunction(sortedResult, indexes); this.renderer.renderIndexes(toRender); this._onChange.fire({ indexes: indexes, browserEvent: browserEvent }); return result; }; Trait.prototype.get = function () { return this.indexes; }; Trait.prototype.contains = function (index) { return arrays_1.binarySearch(this.sortedIndexes, index, numericSort) >= 0; }; Trait.prototype.dispose = function () { lifecycle_1.dispose(this._onChange); }; __decorate([ decorators_1.memoize ], Trait.prototype, "renderer", null); return Trait; }()); var FocusTrait = /** @class */ (function (_super) { __extends(FocusTrait, _super); function FocusTrait() { return _super.call(this, 'focused') || this; } FocusTrait.prototype.renderIndex = function (index, container) { _super.prototype.renderIndex.call(this, index, container); if (this.contains(index)) { container.setAttribute('aria-selected', 'true'); } else { container.removeAttribute('aria-selected'); } }; return FocusTrait; }(Trait)); /** * The TraitSpliceable is used as a util class to be able * to preserve traits across splice calls, given an identity * provider. */ var TraitSpliceable = /** @class */ (function () { function TraitSpliceable(trait, view, identityProvider) { this.trait = trait; this.view = view; this.identityProvider = identityProvider; } TraitSpliceable.prototype.splice = function (start, deleteCount, elements) { var _this = this; if (!this.identityProvider) { return this.trait.splice(start, deleteCount, elements.map(function () { return false; })); } var pastElementsWithTrait = this.trait.get().map(function (i) { return _this.identityProvider.getId(_this.view.element(i)).toString(); }); var elementsWithTrait = elements.map(function (e) { return pastElementsWithTrait.indexOf(_this.identityProvider.getId(e).toString()) > -1; }); this.trait.splice(start, deleteCount, elementsWithTrait); }; return TraitSpliceable; }()); function isInputElement(e) { return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA'; } var KeyboardController = /** @class */ (function () { function KeyboardController(list, view, options) { this.list = list; this.view = view; this.disposables = new lifecycle_1.DisposableStore(); var multipleSelectionSupport = options.multipleSelectionSupport !== false; this.openController = options.openController || DefaultOpenController; var onKeyDown = event_1.Event.chain(event_2.domEvent(view.domNode, 'keydown')) .filter(function (e) { return !isInputElement(e.target); }) .map(function (e) { return new keyboardEvent_1.StandardKeyboardEvent(e); }); onKeyDown.filter(function (e) { return e.keyCode === 3 /* Enter */; }).on(this.onEnter, this, this.disposables); onKeyDown.filter(function (e) { return e.keyCode === 16 /* UpArrow */; }).on(this.onUpArrow, this, this.disposables); onKeyDown.filter(function (e) { return e.keyCode === 18 /* DownArrow */; }).on(this.onDownArrow, this, this.disposables); onKeyDown.filter(function (e) { return e.keyCode === 11 /* PageUp */; }).on(this.onPageUpArrow, this, this.disposables); onKeyDown.filter(function (e) { return e.keyCode === 12 /* PageDown */; }).on(this.onPageDownArrow, this, this.disposables); onKeyDown.filter(function (e) { return e.keyCode === 9 /* Escape */; }).on(this.onEscape, this, this.disposables); if (multipleSelectionSupport) { onKeyDown.filter(function (e) { return (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === 31 /* KEY_A */; }).on(this.onCtrlA, this, this.disposables); } } KeyboardController.prototype.onEnter = function (e) { e.preventDefault(); e.stopPropagation(); this.list.setSelection(this.list.getFocus(), e.browserEvent); if (this.openController.shouldOpen(e.browserEvent)) { this.list.open(this.list.getFocus(), e.browserEvent); } }; KeyboardController.prototype.onUpArrow = function (e) { e.preventDefault(); e.stopPropagation(); this.list.focusPrevious(1, false, e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); }; KeyboardController.prototype.onDownArrow = function (e) { e.preventDefault(); e.stopPropagation(); this.list.focusNext(1, false, e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); }; KeyboardController.prototype.onPageUpArrow = function (e) { e.preventDefault(); e.stopPropagation(); this.list.focusPreviousPage(e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); }; KeyboardController.prototype.onPageDownArrow = function (e) { e.preventDefault(); e.stopPropagation(); this.list.focusNextPage(e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); }; KeyboardController.prototype.onCtrlA = function (e) { e.preventDefault(); e.stopPropagation(); this.list.setSelection(arrays_1.range(this.list.length), e.browserEvent); this.view.domNode.focus(); }; KeyboardController.prototype.onEscape = function (e) { e.preventDefault(); e.stopPropagation(); this.list.setSelection([], e.browserEvent); this.view.domNode.focus(); }; KeyboardController.prototype.dispose = function () { this.disposables.dispose(); }; return KeyboardController; }()); var TypeLabelControllerState; (function (TypeLabelControllerState) { TypeLabelControllerState[TypeLabelControllerState["Idle"] = 0] = "Idle"; TypeLabelControllerState[TypeLabelControllerState["Typing"] = 1] = "Typing"; })(TypeLabelControllerState || (TypeLabelControllerState = {})); exports.DefaultKeyboardNavigationDelegate = new /** @class */ (function () { function class_1() { } class_1.prototype.mightProducePrintableCharacter = function (event) { if (event.ctrlKey || event.metaKey || event.altKey) { return false; } return (event.keyCode >= 31 /* KEY_A */ && event.keyCode <= 56 /* KEY_Z */) || (event.keyCode >= 21 /* KEY_0 */ && event.keyCode <= 30 /* KEY_9 */) || (event.keyCode >= 93 /* NUMPAD_0 */ && event.keyCode <= 102 /* NUMPAD_9 */) || (event.keyCode >= 80 /* US_SEMICOLON */ && event.keyCode <= 90 /* US_QUOTE */); }; return class_1; }()); var TypeLabelController = /** @class */ (function () { function TypeLabelController(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.enabledDisposables = new lifecycle_1.DisposableStore(); this.disposables = new lifecycle_1.DisposableStore(); this.updateOptions(list.options); } TypeLabelController.prototype.updateOptions = function (options) { var enableKeyboardNavigation = typeof options.enableKeyboardNavigation === 'undefined' ? true : !!options.enableKeyboardNavigation; if (enableKeyboardNavigation) { this.enable(); } else { this.disable(); } if (typeof options.automaticKeyboardNavigation !== 'undefined') { this.automaticKeyboardNavigation = options.automaticKeyboardNavigation; } }; TypeLabelController.prototype.enable = function () { var _this = this; if (this.enabled) { return; } var onChar = event_1.Event.chain(event_2.domEvent(this.view.domNode, 'keydown')) .filter(function (e) { return !isInputElement(e.target); }) .filter(function () { return _this.automaticKeyboardNavigation || _this.triggered; }) .map(function (event) { return new keyboardEvent_1.StandardKeyboardEvent(event); }) .filter(function (e) { return _this.delegate.mightProducePrintableCharacter(e); }) .forEach(function (e) { e.stopPropagation(); e.preventDefault(); }) .map(function (event) { return event.browserEvent.key; }) .event; var onClear = event_1.Event.debounce(onChar, function () { return null; }, 800); var onInput = event_1.Event.reduce(event_1.Event.any(onChar, onClear), function (r, i) { return i === null ? null : ((r || '') + i); }); onInput(this.onInput, this, this.enabledDisposables); this.enabled = true; this.triggered = false; }; TypeLabelController.prototype.disable = function () { if (!this.enabled) { return; } this.enabledDisposables.clear(); this.enabled = false; this.triggered = false; }; TypeLabelController.prototype.onInput = function (word) { if (!word) { this.state = TypeLabelControllerState.Idle; this.triggered = false; return; } var focus = this.list.getFocus(); var start = focus.length > 0 ? focus[0] : 0; var delta = this.state === TypeLabelControllerState.Idle ? 1 : 0; this.state = TypeLabelControllerState.Typing; for (var i = 0; i < this.list.length; i++) { var index = (start + i + delta) % this.list.length; var label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index)); var labelStr = label && label.toString(); if (typeof labelStr === 'undefined' || filters_1.matchesPrefix(word, labelStr)) { this.list.setFocus([index]); this.list.reveal(index); return; } } }; TypeLabelController.prototype.dispose = function () { this.disable(); this.enabledDisposables.dispose(); this.disposables.dispose(); }; return TypeLabelController; }()); var DOMFocusController = /** @class */ (function () { function DOMFocusController(list, view) { this.list = list; this.view = view; this.disposables = new lifecycle_1.DisposableStore(); var onKeyDown = event_1.Event.chain(event_2.domEvent(view.domNode, 'keydown')) .filter(function (e) { return !isInputElement(e.target); }) .map(function (e) { return new keyboardEvent_1.StandardKeyboardEvent(e); }); onKeyDown.filter(function (e) { return e.keyCode === 2 /* Tab */ && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey; }) .on(this.onTab, this, this.disposables); } DOMFocusController.prototype.onTab = function (e) { if (e.target !== this.view.domNode) { return; } var focus = this.list.getFocus(); if (focus.length === 0) { return; } var focusedDomElement = this.view.domElement(focus[0]); if (!focusedDomElement) { return; } var tabIndexElement = focusedDomElement.querySelector('[tabIndex]'); if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) { return; } var style = window.getComputedStyle(tabIndexElement); if (style.visibility === 'hidden' || style.display === 'none') { return; } e.preventDefault(); e.stopPropagation(); tabIndexElement.focus(); }; DOMFocusController.prototype.dispose = function () { this.disposables.dispose(); }; return DOMFocusController; }()); 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; } var DefaultMultipleSelectionController = { isSelectionSingleChangeEvent: isSelectionSingleChangeEvent, isSelectionRangeChangeEvent: isSelectionRangeChangeEvent }; var DefaultOpenController = { shouldOpen: function (event) { if (event instanceof MouseEvent) { return !isMouseRightClick(event); } return true; } }; var MouseController = /** @class */ (function () { function MouseController(list) { this.list = list; this.disposables = new lifecycle_1.DisposableStore(); this.multipleSelectionSupport = !(list.options.multipleSelectionSupport === false); if (this.multipleSelectionSupport) { this.multipleSelectionController = list.options.multipleSelectionController || DefaultMultipleSelectionController; } this.openController = list.options.openController || DefaultOpenController; 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())); } list.onMouseClick(this.onPointer, this, this.disposables); list.onMouseMiddleClick(this.onPointer, this, this.disposables); list.onTap(this.onPointer, this, this.disposables); } MouseController.prototype.isSelectionSingleChangeEvent = function (event) { if (this.multipleSelectionController) { return this.multipleSelectionController.isSelectionSingleChangeEvent(event); } return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey; }; MouseController.prototype.isSelectionRangeChangeEvent = function (event) { if (this.multipleSelectionController) { return this.multipleSelectionController.isSelectionRangeChangeEvent(event); } return event.browserEvent.shiftKey; }; MouseController.prototype.isSelectionChangeEvent = function (event) { return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event); }; MouseController.prototype.onMouseDown = function (e) { if (document.activeElement !== e.browserEvent.target) { this.list.domFocus(); } }; MouseController.prototype.onContextMenu = function (e) { var focus = typeof e.index === 'undefined' ? [] : [e.index]; this.list.setFocus(focus, e.browserEvent); }; MouseController.prototype.onPointer = function (e) { if (!this.mouseSupport) { return; } if (isInputElement(e.browserEvent.target)) { return; } var reference = this.list.getFocus()[0]; var selection = this.list.getSelection(); reference = reference === undefined ? selection[0] : reference; var focus = e.index; if (typeof focus === 'undefined') { this.list.setFocus([], e.browserEvent); this.list.setSelection([], e.browserEvent); return; } if (this.multipleSelectionSupport && this.isSelectionRangeChangeEvent(e)) { return this.changeSelection(e, reference); } if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) { return this.changeSelection(e, reference); } this.list.setFocus([focus], e.browserEvent); if (!isMouseRightClick(e.browserEvent)) { this.list.setSelection([focus], e.browserEvent); if (this.openController.shouldOpen(e.browserEvent)) { this.list.open([focus], e.browserEvent); } } }; MouseController.prototype.onDoubleClick = function (e) { if (isInputElement(e.browserEvent.target)) { return; } if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) { return; } var focus = this.list.getFocus(); this.list.setSelection(focus, e.browserEvent); this.list.pin(focus); }; MouseController.prototype.changeSelection = function (e, reference) { var focus = e.index; if (this.isSelectionRangeChangeEvent(e) && reference !== undefined) { var min = Math.min(reference, focus); var max = Math.max(reference, focus); var rangeSelection = arrays_1.range(min, max + 1); var selection = this.list.getSelection(); var contiguousRange = getContiguousRangeContaining(disjunction(selection, [reference]), reference); if (contiguousRange.length === 0) { return; } var newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange)); this.list.setSelection(newSelection, e.browserEvent); } else if (this.isSelectionSingleChangeEvent(e)) { var selection = this.list.getSelection(); var newSelection = selection.filter(function (i) { return i !== focus; }); this.list.setFocus([focus]); if (selection.length === newSelection.length) { this.list.setSelection(__spreadArrays(newSelection, [focus]), e.browserEvent); } else { this.list.setSelection(newSelection, e.browserEvent); } } }; MouseController.prototype.dispose = function () { this.disposables.dispose(); }; return MouseController; }()); exports.MouseController = MouseController; var DefaultStyleController = /** @class */ (function () { function DefaultStyleController(styleElement, selectorSuffix) { this.styleElement = styleElement; this.selectorSuffix = selectorSuffix; } DefaultStyleController.prototype.style = function (styles) { var suffix = this.selectorSuffix && "." + this.selectorSuffix; var 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.listFocusAndSelectionBackground) { content.push("\n\t\t\t\t.monaco-drag-image,\n\t\t\t\t.monaco-list" + suffix + ":focus .monaco-list-row.selected.focused { background-color: " + styles.listFocusAndSelectionBackground + "; }\n\t\t\t"); } if (styles.listFocusAndSelectionForeground) { content.push("\n\t\t\t\t.monaco-drag-image,\n\t\t\t\t.monaco-list" + suffix + ":focus .monaco-list-row.selected.focused { color: " + styles.listFocusAndSelectionForeground + "; }\n\t\t\t"); } 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("\n\t\t\t\t.monaco-drag-image,\n\t\t\t\t.monaco-list" + suffix + ":focus .monaco-list-row.focused { outline: 1px solid " + styles.listFocusOutline + "; outline-offset: -1px; }\n\t\t\t"); } 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("\n\t\t\t\t.monaco-list" + suffix + ".drop-target,\n\t\t\t\t.monaco-list" + suffix + " .monaco-list-rows.drop-target,\n\t\t\t\t.monaco-list" + suffix + " .monaco-list-row.drop-target { background-color: " + styles.listDropBackground + " !important; color: inherit !important; }\n\t\t\t"); } 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 + "; }"); } var newStyles = content.join('\n'); if (newStyles !== this.styleElement.innerHTML) { this.styleElement.innerHTML = newStyles; } }; return DefaultStyleController; }()); exports.DefaultStyleController = DefaultStyleController; var defaultStyles = { listFocusBackground: color_1.Color.fromHex('#7FB0D0'), listActiveSelectionBackground: color_1.Color.fromHex('#0E639C'), listActiveSelectionForeground: color_1.Color.fromHex('#FFFFFF'), listFocusAndSelectionBackground: color_1.Color.fromHex('#094771'), listFocusAndSelectionForeground: color_1.Color.fromHex('#FFFFFF'), listInactiveSelectionBackground: color_1.Color.fromHex('#3F3F46'), listHoverBackground: color_1.Color.fromHex('#2A2D2E'), listDropBackground: color_1.Color.fromHex('#383B3D'), treeIndentGuidesStroke: color_1.Color.fromHex('#a9a9a9') }; var DefaultOptions = { keyboardSupport: true, mouseSupport: true, multipleSelectionSupport: true, dnd: { getDragURI: function () { return null; }, onDragStart: function () { }, onDragOver: function () { return false; }, drop: function () { } }, ariaRootRole: list_1.ListAriaRootRole.TREE }; // TODO@Joao: move these utils into a SortedArray class function getContiguousRangeContaining(range, value) { var index = range.indexOf(value); if (index === -1) { return []; } var result = []; var 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) { var result = []; var 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) { var result = []; var 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; } var numericSort = function (a, b) { return a - b; }; var PipelineRenderer = /** @class */ (function () { function PipelineRenderer(_templateId, renderers) { this._templateId = _templateId; this.renderers = renderers; } Object.defineProperty(PipelineRenderer.prototype, "templateId", { get: function () { return this._templateId; }, enumerable: true, configurable: true }); PipelineRenderer.prototype.renderTemplate = function (container) { return this.renderers.map(function (r) { return r.renderTemplate(container); }); }; PipelineRenderer.prototype.renderElement = function (element, index, templateData, height) { var i = 0; for (var _i = 0, _a = this.renderers; _i < _a.length; _i++) { var renderer = _a[_i]; renderer.renderElement(element, index, templateData[i++], height); } }; PipelineRenderer.prototype.disposeElement = function (element, index, templateData, height) { var i = 0; for (var _i = 0, _a = this.renderers; _i < _a.length; _i++) { var renderer = _a[_i]; if (renderer.disposeElement) { renderer.disposeElement(element, index, templateData[i], height); } i += 1; } }; PipelineRenderer.prototype.disposeTemplate = function (templateData) { var i = 0; for (var _i = 0, _a = this.renderers; _i < _a.length; _i++) { var renderer = _a[_i]; renderer.disposeTemplate(templateData[i++]); } }; return PipelineRenderer; }()); var AccessibiltyRenderer = /** @class */ (function () { function AccessibiltyRenderer(accessibilityProvider) { this.accessibilityProvider = accessibilityProvider; this.templateId = 'a18n'; } AccessibiltyRenderer.prototype.renderTemplate = function (container) { return container; }; AccessibiltyRenderer.prototype.renderElement = function (element, index, container) { var ariaLabel = this.accessibilityProvider.getAriaLabel(element); if (ariaLabel) { container.setAttribute('aria-label', ariaLabel); } else { container.removeAttribute('aria-label'); } var ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element); if (typeof ariaLevel === 'number') { container.setAttribute('aria-level', "" + ariaLevel); } else { container.removeAttribute('aria-level'); } }; AccessibiltyRenderer.prototype.disposeTemplate = function (templateData) { // noop }; return AccessibiltyRenderer; }()); var ListViewDragAndDrop = /** @class */ (function () { function ListViewDragAndDrop(list, dnd) { this.list = list; this.dnd = dnd; } ListViewDragAndDrop.prototype.getDragElements = function (element) { var selection = this.list.getSelectedElements(); var elements = selection.indexOf(element) > -1 ? selection : [element]; return elements; }; ListViewDragAndDrop.prototype.getDragURI = function (element) { return this.dnd.getDragURI(element); }; ListViewDragAndDrop.prototype.getDragLabel = function (elements, originalEvent) { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(elements, originalEvent); } return undefined; }; ListViewDragAndDrop.prototype.onDragStart = function (data, originalEvent) { if (this.dnd.onDragStart) { this.dnd.onDragStart(data, originalEvent); } }; ListViewDragAndDrop.prototype.onDragOver = function (data, targetElement, targetIndex, originalEvent) { return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent); }; ListViewDragAndDrop.prototype.onDragEnd = function (originalEvent) { if (this.dnd.onDragEnd) { this.dnd.onDragEnd(originalEvent); } }; ListViewDragAndDrop.prototype.drop = function (data, targetElement, targetIndex, originalEvent) { this.dnd.drop(data, targetElement, targetIndex, originalEvent); }; return ListViewDragAndDrop; }()); var List = /** @class */ (function () { function List(user, container, virtualDelegate, renderers, _options) { if (_options === void 0) { _options = DefaultOptions; } this.user = user; this._options = _options; this.eventBufferer = new event_1.EventBufferer(); this.disposables = new lifecycle_1.DisposableStore(); this._onDidOpen = new event_1.Emitter(); this.onDidOpen = this._onDidOpen.event; this._onDidPin = new event_1.Emitter(); this.didJustPressContextMenuKey = false; this._onDidDispose = new event_1.Emitter(); this.onDidDispose = this._onDidDispose.event; this.focus = new FocusTrait(); this.selection = new Trait('selected'); objects_1.mixin(_options, defaultStyles, false); var 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(function (r) { return new PipelineRenderer(r.templateId, __spreadArrays(baseRenderers, [r])); }); var viewOptions = __assign(__assign({}, _options), { dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd) }); this.view = new listView_1.ListView(container, virtualDelegate, renderers, viewOptions); if (typeof _options.ariaRole !== 'string') { this.view.domNode.setAttribute('role', list_1.ListAriaRootRole.TREE); } else { this.view.domNode.setAttribute('role', _options.ariaRole); } if (_options.styleController) { this.styleController = _options.styleController(this.view.domId); } else { var styleElement = DOM.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), this.view ]); this.disposables.add(this.focus); this.disposables.add(this.selection); this.disposables.add(this.view); this.disposables.add(this._onDidDispose); this.onDidFocus = event_1.Event.map(event_2.domEvent(this.view.domNode, 'focus', true), function () { return null; }); this.onDidBlur = event_1.Event.map(event_2.domEvent(this.view.domNode, 'blur', true), function () { return null; }); this.disposables.add(new DOMFocusController(this, this.view)); if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) { var controller = new KeyboardController(this, this.view, _options); this.disposables.add(controller); } if (_options.keyboardNavigationLabelProvider) { var delegate = _options.keyboardNavigationDelegate || exports.DefaultKeyboardNavigationDelegate; this.typeLabelController = new TypeLabelController(this, this.view, _options.keyboardNavigationLabelProvider, delegate); this.disposables.add(this.typeLabelController); } this.disposables.add(this.createMouseController(_options)); this.onFocusChange(this._onFocusChange, this, this.disposables); this.onSelectionChange(this._onSelectionChange, this, this.disposables); if (_options.ariaLabel) { this.view.domNode.setAttribute('aria-label', nls_1.localize(0, null, _options.ariaLabel)); } } Object.defineProperty(List.prototype, "onFocusChange", { get: function () { var _this = this; return event_1.Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), function (e) { return _this.toListEvent(e); }); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "onSelectionChange", { get: function () { var _this = this; return event_1.Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), function (e) { return _this.toListEvent(e); }); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "domId", { get: function () { return this.view.domId; }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "onMouseClick", { get: function () { return this.view.onMouseClick; }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "onMouseDblClick", { get: function () { return this.view.onMouseDblClick; }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "onMouseMiddleClick", { get: function () { return this.view.onMouseMiddleClick; }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "onMouseDown", { get: function () { return this.view.onMouseDown; }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "onTouchStart", { get: function () { return this.view.onTouchStart; }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "onTap", { get: function () { return this.view.onTap; }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "onContextMenu", { get: function () { var _this = this; var fromKeydown = event_1.Event.chain(event_2.domEvent(this.view.domNode, 'keydown')) .map(function (e) { return new keyboardEvent_1.StandardKeyboardEvent(e); }) .filter(function (e) { return _this.didJustPressContextMenuKey = e.keyCode === 58 /* ContextMenu */ || (e.shiftKey && e.keyCode === 68 /* F10 */); }) .filter(function (e) { e.preventDefault(); e.stopPropagation(); return false; }) .event; var fromKeyup = event_1.Event.chain(event_2.domEvent(this.view.domNode, 'keyup')) .filter(function () { var didJustPressContextMenuKey = _this.didJustPressContextMenuKey; _this.didJustPressContextMenuKey = false; return didJustPressContextMenuKey; }) .filter(function () { return _this.getFocus().length > 0 && !!_this.view.domElement(_this.getFocus()[0]); }) .map(function (browserEvent) { var index = _this.getFocus()[0]; var element = _this.view.element(index); var anchor = _this.view.domElement(index); return { index: index, element: element, anchor: anchor, browserEvent: browserEvent }; }) .event; var fromMouse = event_1.Event.chain(this.view.onContextMenu) .filter(function () { return !_this.didJustPressContextMenuKey; }) .map(function (_a) { var element = _a.element, index = _a.index, browserEvent = _a.browserEvent; return ({ element: element, index: index, anchor: { x: browserEvent.clientX + 1, y: browserEvent.clientY }, browserEvent: browserEvent }); }) .event; return event_1.Event.any(fromKeydown, fromKeyup, fromMouse); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "onKeyDown", { get: function () { return event_2.domEvent(this.view.domNode, 'keydown'); }, enumerable: true, configurable: true }); List.prototype.createMouseController = function (options) { return new MouseController(this); }; List.prototype.updateOptions = function (optionsUpdate) { if (optionsUpdate === void 0) { optionsUpdate = {}; } this._options = __assign(__assign({}, this._options), optionsUpdate); if (this.typeLabelController) { this.typeLabelController.updateOptions(this._options); } }; Object.defineProperty(List.prototype, "options", { get: function () { return this._options; }, enumerable: true, configurable: true }); List.prototype.splice = function (start, deleteCount, elements) { var _this = this; if (elements === void 0) { 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(function () { return _this.spliceable.splice(start, deleteCount, elements); }); }; List.prototype.rerender = function () { this.view.rerender(); }; List.prototype.element = function (index) { return this.view.element(index); }; Object.defineProperty(List.prototype, "length", { get: function () { return this.view.length; }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "contentHeight", { get: function () { return this.view.contentHeight; }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "scrollTop", { get: function () { return this.view.getScrollTop(); }, set: function (scrollTop) { this.view.setScrollTop(scrollTop); }, enumerable: true, configurable: true }); List.prototype.domFocus = function () { this.view.domNode.focus(); }; List.prototype.layout = function (height, width) { this.view.layout(height, width); }; List.prototype.setSelection = function (indexes, browserEvent) { for (var _i = 0, indexes_1 = indexes; _i < indexes_1.length; _i++) { var index = indexes_1[_i]; if (index < 0 || index >= this.length) { throw new list_1.ListError(this.user, "Invalid index " + index); } } this.selection.set(indexes, browserEvent); }; List.prototype.getSelection = function () { return this.selection.get(); }; List.prototype.getSelectedElements = function () { var _this = this; return this.getSelection().map(function (i) { return _this.view.element(i); }); }; List.prototype.setFocus = function (indexes, browserEvent) { for (var _i = 0, indexes_2 = indexes; _i < indexes_2.length; _i++) { var index = indexes_2[_i]; if (index < 0 || index >= this.length) { throw new list_1.ListError(this.user, "Invalid index " + index); } } this.focus.set(indexes, browserEvent); }; List.prototype.focusNext = function (n, loop, browserEvent, filter) { if (n === void 0) { n = 1; } if (loop === void 0) { loop = false; } if (this.length === 0) { return; } var focus = this.focus.get(); var index = this.findNextIndex(focus.length > 0 ? focus[0] + n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } }; List.prototype.focusPrevious = function (n, loop, browserEvent, filter) { if (n === void 0) { n = 1; } if (loop === void 0) { loop = false; } if (this.length === 0) { return; } var focus = this.focus.get(); var index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } }; List.prototype.focusNextPage = function (browserEvent, filter) { var _this = this; var lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight); lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1; var lastPageElement = this.view.element(lastPageIndex); var currentlyFocusedElement = this.getFocusedElements()[0]; if (currentlyFocusedElement !== lastPageElement) { var lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter); if (lastGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(lastGoodPageIndex)) { this.setFocus([lastGoodPageIndex], browserEvent); } else { this.setFocus([lastPageIndex], browserEvent); } } else { var previousScrollTop = this.view.getScrollTop(); this.view.setScrollTop(previousScrollTop + this.view.renderHeight - this.view.elementHeight(lastPageIndex)); if (this.view.getScrollTop() !== previousScrollTop) { // Let the scroll event listener run setTimeout(function () { return _this.focusNextPage(browserEvent, filter); }, 0); } } }; List.prototype.focusPreviousPage = function (browserEvent, filter) { var _this = this; var firstPageIndex; var scrollTop = this.view.getScrollTop(); if (scrollTop === 0) { firstPageIndex = this.view.indexAt(scrollTop); } else { firstPageIndex = this.view.indexAfter(scrollTop - 1); } var firstPageElement = this.view.element(firstPageIndex); var currentlyFocusedElement = this.getFocusedElements()[0]; if (currentlyFocusedElement !== firstPageElement) { var firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter); if (firstGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(firstGoodPageIndex)) { this.setFocus([firstGoodPageIndex], browserEvent); } else { this.setFocus([firstPageIndex], browserEvent); } } else { var previousScrollTop = scrollTop; this.view.setScrollTop(scrollTop - this.view.renderHeight); if (this.view.getScrollTop() !== previousScrollTop) { // Let the scroll event listener run setTimeout(function () { return _this.focusPreviousPage(browserEvent, filter); }, 0); } } }; List.prototype.focusLast = function (browserEvent, filter) { if (this.length === 0) { return; } var index = this.findPreviousIndex(this.length - 1, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } }; List.prototype.focusFirst = function (browserEvent, filter) { if (this.length === 0) { return; } var index = this.findNextIndex(0, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } }; List.prototype.findNextIndex = function (index, loop, filter) { if (loop === void 0) { loop = false; } for (var 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; }; List.prototype.findPreviousIndex = function (index, loop, filter) { if (loop === void 0) { loop = false; } for (var 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; }; List.prototype.getFocus = function () { return this.focus.get(); }; List.prototype.getFocusedElements = function () { var _this = this; return this.getFocus().map(function (i) { return _this.view.element(i); }); }; List.prototype.reveal = function (index, relativeTop) { if (index < 0 || index >= this.length) { throw new list_1.ListError(this.user, "Invalid index " + index); } var scrollTop = this.view.getScrollTop(); var elementTop = this.view.elementTop(index); var elementHeight = this.view.elementHeight(index); if (types_1.isNumber(relativeTop)) { // y = mx + b var m = elementHeight - this.view.renderHeight; this.view.setScrollTop(m * numbers_1.clamp(relativeTop, 0, 1) + elementTop); } else { var viewItemBottom = elementTop + elementHeight; var wrapperBottom = scrollTop + this.view.renderHeight; if (elementTop < scrollTop && viewItemBottom >= wrapperBottom) { // The element is already overflowing the viewport, no-op } else if (elementTop < scrollTop) { this.view.setScrollTop(elementTop); } else if (viewItemBottom >= wrapperBottom) { 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. */ List.prototype.getRelativeTop = function (index) { if (index < 0 || index >= this.length) { throw new list_1.ListError(this.user, "Invalid index " + index); } var scrollTop = this.view.getScrollTop(); var elementTop = this.view.elementTop(index); var elementHeight = this.view.elementHeight(index); if (elementTop < scrollTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) { return null; } // y = mx + b var m = elementHeight - this.view.renderHeight; return Math.abs((scrollTop - elementTop) / m); }; List.prototype.getHTMLElement = function () { return this.view.domNode; }; List.prototype.open = function (indexes, browserEvent) { var _this = this; for (var _i = 0, indexes_3 = indexes; _i < indexes_3.length; _i++) { var index = indexes_3[_i]; if (index < 0 || index >= this.length) { throw new list_1.ListError(this.user, "Invalid index " + index); } } this._onDidOpen.fire({ indexes: indexes, elements: indexes.map(function (i) { return _this.view.element(i); }), browserEvent: browserEvent }); }; List.prototype.pin = function (indexes, browserEvent) { var _this = this; for (var _i = 0, indexes_4 = indexes; _i < indexes_4.length; _i++) { var index = indexes_4[_i]; if (index < 0 || index >= this.length) { throw new list_1.ListError(this.user, "Invalid index " + index); } } this._onDidPin.fire({ indexes: indexes, elements: indexes.map(function (i) { return _this.view.element(i); }), browserEvent: browserEvent }); }; List.prototype.style = function (styles) { this.styleController.style(styles); }; List.prototype.toListEvent = function (_a) { var _this = this; var indexes = _a.indexes, browserEvent = _a.browserEvent; return { indexes: indexes, elements: indexes.map(function (i) { return _this.view.element(i); }), browserEvent: browserEvent }; }; List.prototype._onFocusChange = function () { var focus = this.focus.get(); DOM.toggleClass(this.view.domNode, 'element-focused', focus.length > 0); this.onDidChangeActiveDescendant(); }; List.prototype.onDidChangeActiveDescendant = function () { var _a; var focus = this.focus.get(); if (focus.length > 0) { var id = void 0; 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'); } }; List.prototype._onSelectionChange = function () { var selection = this.selection.get(); DOM.toggleClass(this.view.domNode, 'selection-none', selection.length === 0); DOM.toggleClass(this.view.domNode, 'selection-single', selection.length === 1); DOM.toggleClass(this.view.domNode, 'selection-multiple', selection.length > 1); }; List.prototype.dispose = function () { this._onDidDispose.fire(); this.disposables.dispose(); this._onDidOpen.dispose(); this._onDidPin.dispose(); this._onDidDispose.dispose(); }; __decorate([ decorators_1.memoize ], List.prototype, "onFocusChange", null); __decorate([ decorators_1.memoize ], List.prototype, "onSelectionChange", null); __decorate([ decorators_1.memoize ], List.prototype, "onContextMenu", null); return List; }()); exports.List = List; }); define(__m[404/*vs/nls!vs/base/browser/ui/menu/menu*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/menu/menu", data); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[205/*vs/base/browser/ui/menu/menu*/], __M([0/*require*/,1/*exports*/,404/*vs/nls!vs/base/browser/ui/menu/menu*/,5/*vs/base/common/strings*/,55/*vs/base/common/actions*/,70/*vs/base/browser/ui/actionbar/actionbar*/,6/*vs/base/browser/dom*/,56/*vs/base/browser/keyboardEvent*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,53/*vs/base/browser/ui/scrollbar/scrollableElement*/,16/*vs/base/common/platform*/,272/*vs/css!vs/base/browser/ui/menu/menu*/]), function (require, exports, nls, strings, actions_1, actionbar_1, dom_1, keyboardEvent_1, async_1, lifecycle_1, scrollableElement_1, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 = {})); var SubmenuAction = /** @class */ (function (_super) { __extends(SubmenuAction, _super); function SubmenuAction(label, entries, cssClass) { var _this = _super.call(this, !!cssClass ? cssClass : 'submenu', label, '', true) || this; _this.entries = entries; return _this; } return SubmenuAction; }(actions_1.Action)); exports.SubmenuAction = SubmenuAction; var Menu = /** @class */ (function (_super) { __extends(Menu, _super); function Menu(container, actions, options) { if (options === void 0) { options = {}; } var _this = this; dom_1.addClass(container, 'monaco-menu-container'); container.setAttribute('role', 'presentation'); var menuElement = document.createElement('div'); dom_1.addClass(menuElement, 'monaco-menu'); menuElement.setAttribute('role', 'presentation'); _this = _super.call(this, menuElement, { orientation: 2 /* VERTICAL */, actionViewItemProvider: function (action) { return _this.doGetActionViewItem(action, options, parentData); }, context: options.context, actionRunner: options.actionRunner, ariaLabel: options.ariaLabel, triggerKeys: { keys: __spreadArrays([3 /* Enter */], (platform_1.isMacintosh ? [10 /* Space */] : [])), keyDown: true } }) || this; _this.menuElement = menuElement; _this.actionsList.setAttribute('role', 'menu'); _this.actionsList.tabIndex = 0; _this.menuDisposables = _this._register(new lifecycle_1.DisposableStore()); dom_1.addDisposableListener(menuElement, dom_1.EventType.KEY_DOWN, function (e) { var event = new keyboardEvent_1.StandardKeyboardEvent(e); // Stop tab navigation of menus if (event.equals(2 /* Tab */)) { e.preventDefault(); } }); if (options.enableMnemonics) { _this.menuDisposables.add(dom_1.addDisposableListener(menuElement, dom_1.EventType.KEY_DOWN, function (e) { var key = e.key.toLocaleLowerCase(); if (_this.mnemonics.has(key)) { dom_1.EventHelper.stop(e, true); var actions_2 = _this.mnemonics.get(key); if (actions_2.length === 1) { if (actions_2[0] instanceof SubmenuMenuActionViewItem && actions_2[0].container) { _this.focusItemByElement(actions_2[0].container); } actions_2[0].onClick(e); } if (actions_2.length > 1) { var action = actions_2.shift(); if (action && action.container) { _this.focusItemByElement(action.container); actions_2.push(action); } _this.mnemonics.set(key, actions_2); } } })); } if (platform_1.isLinux) { _this._register(dom_1.addDisposableListener(menuElement, dom_1.EventType.KEY_DOWN, function (e) { var 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(dom_1.addDisposableListener(_this.domNode, dom_1.EventType.MOUSE_OUT, function (e) { var relatedTarget = e.relatedTarget; if (!dom_1.isAncestor(relatedTarget, _this.domNode)) { _this.focusedItem = undefined; _this.updateFocus(); e.stopPropagation(); } })); _this._register(dom_1.addDisposableListener(_this.actionsList, dom_1.EventType.MOUSE_OVER, function (e) { var target = e.target; if (!target || !dom_1.isAncestor(target, _this.actionsList) || target === _this.actionsList) { return; } while (target.parentElement !== _this.actionsList && target.parentElement !== null) { target = target.parentElement; } if (dom_1.hasClass(target, 'action-item')) { var lastFocusedItem = _this.focusedItem; _this.setFocusedItem(target); if (lastFocusedItem !== _this.focusedItem) { _this.updateFocus(); } } })); var 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 })); var scrollElement = _this.scrollableElement.getDomNode(); scrollElement.style.position = ''; _this._register(dom_1.addDisposableListener(scrollElement, dom_1.EventType.MOUSE_UP, function (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 - 30) + "px"; _this.push(actions, { icon: true, label: true, isMenu: true }); container.appendChild(_this.scrollableElement.getDomNode()); _this.scrollableElement.scanDomNode(); _this.viewItems.filter(function (item) { return !(item instanceof MenuSeparatorActionViewItem); }).forEach(function (item, index, array) { item.updatePositionInSet(index + 1, array.length); }); return _this; } Menu.prototype.style = function (style) { var container = this.getContainer(); var fgColor = style.foregroundColor ? "" + style.foregroundColor : ''; var bgColor = style.backgroundColor ? "" + style.backgroundColor : ''; var border = style.borderColor ? "1px solid " + style.borderColor : ''; var 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(function (item) { if (item instanceof BaseMenuActionViewItem || item instanceof MenuSeparatorActionViewItem) { item.style(style); } }); } }; Menu.prototype.getContainer = function () { return this.scrollableElement.getDomNode(); }; Object.defineProperty(Menu.prototype, "onScroll", { get: function () { return this.scrollableElement.onScroll; }, enumerable: true, configurable: true }); Object.defineProperty(Menu.prototype, "scrollOffset", { get: function () { return this.menuElement.scrollTop; }, enumerable: true, configurable: true }); Menu.prototype.focusItemByElement = function (element) { var lastFocusedItem = this.focusedItem; this.setFocusedItem(element); if (lastFocusedItem !== this.focusedItem) { this.updateFocus(); } }; Menu.prototype.setFocusedItem = function (element) { for (var i = 0; i < this.actionsList.children.length; i++) { var elem = this.actionsList.children[i]; if (element === elem) { this.focusedItem = i; break; } } }; Menu.prototype.updateFocus = function (fromRight) { _super.prototype.updateFocus.call(this, fromRight, true); if (typeof this.focusedItem !== 'undefined') { // Workaround for #80047 caused by an issue in chromium // https://bugs.chromium.org/p/chromium/issues/detail?id=414283 // When that's fixed, just call this.scrollableElement.scanDomNode() this.scrollableElement.setScrollPosition({ scrollTop: Math.round(this.menuElement.scrollTop) }); } }; Menu.prototype.doGetActionViewItem = function (action, options, parentData) { if (action instanceof actionbar_1.Separator) { return new MenuSeparatorActionViewItem(options.context, action, { icon: true }); } else if (action instanceof SubmenuAction) { var menuActionViewItem = new SubmenuMenuActionViewItem(action, action.entries, parentData, options); if (options.enableMnemonics) { var mnemonic = menuActionViewItem.getMnemonic(); if (mnemonic && menuActionViewItem.isEnabled()) { var actionViewItems = []; if (this.mnemonics.has(mnemonic)) { actionViewItems = this.mnemonics.get(mnemonic); } actionViewItems.push(menuActionViewItem); this.mnemonics.set(mnemonic, actionViewItems); } } return menuActionViewItem; } else { var menuItemOptions = { enableMnemonics: options.enableMnemonics }; if (options.getKeyBinding) { var keybinding = options.getKeyBinding(action); if (keybinding) { var keybindingLabel = keybinding.getLabel(); if (keybindingLabel) { menuItemOptions.keybinding = keybindingLabel; } } } var menuActionViewItem = new BaseMenuActionViewItem(options.context, action, menuItemOptions); if (options.enableMnemonics) { var mnemonic = menuActionViewItem.getMnemonic(); if (mnemonic && menuActionViewItem.isEnabled()) { var actionViewItems = []; if (this.mnemonics.has(mnemonic)) { actionViewItems = this.mnemonics.get(mnemonic); } actionViewItems.push(menuActionViewItem); this.mnemonics.set(mnemonic, actionViewItems); } } return menuActionViewItem; } }; return Menu; }(actionbar_1.ActionBar)); exports.Menu = Menu; var BaseMenuActionViewItem = /** @class */ (function (_super) { __extends(BaseMenuActionViewItem, _super); function BaseMenuActionViewItem(ctx, action, options) { if (options === void 0) { options = {}; } var _this = this; options.isMenu = true; _this = _super.call(this, action, action, options) || this; _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) { var label = _this.getAction().label; if (label) { var 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(function () { if (!_this.element) { return; } _this._register(dom_1.addDisposableListener(_this.element, dom_1.EventType.MOUSE_UP, function (e) { if (e.defaultPrevented) { return; } dom_1.EventHelper.stop(e, true); _this.onClick(e); })); }, 100); _this._register(_this.runOnceToEnableMouseUp); return _this; } BaseMenuActionViewItem.prototype.render = function (container) { _super.prototype.render.call(this, container); if (!this.element) { return; } this.container = container; this.item = dom_1.append(this.element, dom_1.$('a.action-menu-item')); if (this._action.id === actionbar_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 = dom_1.append(this.item, dom_1.$('span.menu-item-check.codicon.codicon-check')); this.check.setAttribute('role', 'none'); this.label = dom_1.append(this.item, dom_1.$('span.action-label')); if (this.options.label && this.options.keybinding) { dom_1.append(this.item, 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(); }; BaseMenuActionViewItem.prototype.blur = function () { _super.prototype.blur.call(this); this.applyStyle(); }; BaseMenuActionViewItem.prototype.focus = function () { _super.prototype.focus.call(this); if (this.item) { this.item.focus(); } this.applyStyle(); }; BaseMenuActionViewItem.prototype.updatePositionInSet = function (pos, setSize) { if (this.item) { this.item.setAttribute('aria-posinset', "" + pos); this.item.setAttribute('aria-setsize', "" + setSize); } }; BaseMenuActionViewItem.prototype.updateLabel = function () { if (this.options.label) { var label = this.getAction().label; if (label) { var cleanLabel = cleanMnemonic(label); if (!this.options.enableMnemonics) { label = cleanLabel; } if (this.label) { this.label.setAttribute('aria-label', cleanLabel.replace(/&&/g, '&')); } var 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; var 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); } if (escMatch) { label = label.substr(0, escMatch.index) + "" + escMatch[3] + "" + label.substr(escMatch.index + escMatch[0].length); } label = label.replace(/&&/g, '&'); if (this.item) { this.item.setAttribute('aria-keyshortcuts', (!!matches[1] ? matches[1] : matches[3]).toLocaleLowerCase()); } } else { label = label.replace(/&&/g, '&'); } } if (this.label) { this.label.innerHTML = label.trim(); } } }; BaseMenuActionViewItem.prototype.updateTooltip = function () { var title = null; if (this.getAction().tooltip) { title = this.getAction().tooltip; } else if (!this.options.label && this.getAction().label && this.options.icon) { title = this.getAction().label; if (this.options.keybinding) { title = nls.localize(0, null, title, this.options.keybinding); } } if (title && this.item) { this.item.title = title; } }; BaseMenuActionViewItem.prototype.updateClass = function () { if (this.cssClass && this.item) { dom_1.removeClasses(this.item, this.cssClass); } if (this.options.icon && this.label) { this.cssClass = this.getAction().class || ''; dom_1.addClass(this.label, 'icon'); if (this.cssClass) { dom_1.addClasses(this.label, this.cssClass); } this.updateEnabled(); } else if (this.label) { dom_1.removeClass(this.label, 'icon'); } }; BaseMenuActionViewItem.prototype.updateEnabled = function () { if (this.getAction().enabled) { if (this.element) { dom_1.removeClass(this.element, 'disabled'); } if (this.item) { dom_1.removeClass(this.item, 'disabled'); this.item.tabIndex = 0; } } else { if (this.element) { dom_1.addClass(this.element, 'disabled'); } if (this.item) { dom_1.addClass(this.item, 'disabled'); dom_1.removeTabIndexAndUpdateFocus(this.item); } } }; BaseMenuActionViewItem.prototype.updateChecked = function () { if (!this.item) { return; } if (this.getAction().checked) { dom_1.addClass(this.item, 'checked'); this.item.setAttribute('role', 'menuitemcheckbox'); this.item.setAttribute('aria-checked', 'true'); } else { dom_1.removeClass(this.item, 'checked'); this.item.setAttribute('role', 'menuitem'); this.item.setAttribute('aria-checked', 'false'); } }; BaseMenuActionViewItem.prototype.getMnemonic = function () { return this.mnemonic; }; BaseMenuActionViewItem.prototype.applyStyle = function () { if (!this.menuStyle) { return; } var isSelected = this.element && dom_1.hasClass(this.element, 'focused'); var fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor; var bgColor = isSelected && this.menuStyle.selectionBackgroundColor ? this.menuStyle.selectionBackgroundColor : undefined; var 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; } }; BaseMenuActionViewItem.prototype.style = function (style) { this.menuStyle = style; this.applyStyle(); }; return BaseMenuActionViewItem; }(actionbar_1.BaseActionViewItem)); var SubmenuMenuActionViewItem = /** @class */ (function (_super) { __extends(SubmenuMenuActionViewItem, _super); function SubmenuMenuActionViewItem(action, submenuActions, parentData, submenuOptions) { var _this = _super.call(this, action, action, submenuOptions) || this; _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(function () { if (_this.mouseOver) { _this.cleanupExistingSubmenu(false); _this.createSubmenu(false); } }, 250); _this.hideScheduler = new async_1.RunOnceScheduler(function () { if (_this.element && (!dom_1.isAncestor(document.activeElement, _this.element) && _this.parentData.submenu === _this.mysubmenu)) { _this.parentData.parent.focus(false); _this.cleanupExistingSubmenu(true); } }, 750); return _this; } SubmenuMenuActionViewItem.prototype.render = function (container) { var _this = this; _super.prototype.render.call(this, container); if (!this.element) { return; } if (this.item) { dom_1.addClass(this.item, 'monaco-submenu-item'); this.item.setAttribute('aria-haspopup', 'true'); this.updateAriaExpanded('false'); this.submenuIndicator = dom_1.append(this.item, dom_1.$('span.submenu-indicator.codicon.codicon-chevron-right')); this.submenuIndicator.setAttribute('aria-hidden', 'true'); } this._register(dom_1.addDisposableListener(this.element, dom_1.EventType.KEY_UP, function (e) { var 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(dom_1.addDisposableListener(this.element, dom_1.EventType.KEY_DOWN, function (e) { var event = new keyboardEvent_1.StandardKeyboardEvent(e); if (document.activeElement === _this.item) { if (event.equals(17 /* RightArrow */) || event.equals(3 /* Enter */)) { dom_1.EventHelper.stop(e, true); } } })); this._register(dom_1.addDisposableListener(this.element, dom_1.EventType.MOUSE_OVER, function (e) { if (!_this.mouseOver) { _this.mouseOver = true; _this.showScheduler.schedule(); } })); this._register(dom_1.addDisposableListener(this.element, dom_1.EventType.MOUSE_LEAVE, function (e) { _this.mouseOver = false; })); this._register(dom_1.addDisposableListener(this.element, dom_1.EventType.FOCUS_OUT, function (e) { if (_this.element && !dom_1.isAncestor(document.activeElement, _this.element)) { _this.hideScheduler.schedule(); } })); this._register(this.parentData.parent.onScroll(function () { _this.parentData.parent.focus(false); _this.cleanupExistingSubmenu(false); })); }; SubmenuMenuActionViewItem.prototype.onClick = function (e) { // stop clicking from trying to run an action dom_1.EventHelper.stop(e, true); this.cleanupExistingSubmenu(false); this.createSubmenu(true); }; SubmenuMenuActionViewItem.prototype.cleanupExistingSubmenu = function (force) { if (this.parentData.submenu && (force || (this.parentData.submenu !== this.mysubmenu))) { this.parentData.submenu.dispose(); this.parentData.submenu = undefined; this.updateAriaExpanded('false'); if (this.submenuContainer) { this.submenuDisposables.clear(); this.submenuContainer = undefined; } } }; SubmenuMenuActionViewItem.prototype.createSubmenu = function (selectFirstItem) { var _this = this; if (selectFirstItem === void 0) { selectFirstItem = true; } if (!this.element) { return; } if (!this.parentData.submenu) { this.updateAriaExpanded('true'); this.submenuContainer = dom_1.append(this.element, dom_1.$('div.monaco-submenu')); dom_1.addClasses(this.submenuContainer, '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 var computedStyles = getComputedStyle(this.parentData.parent.domNode); var paddingTop = parseFloat(computedStyles.paddingTop || '0') || 0; this.submenuContainer.style.top = this.element.offsetTop - this.parentData.parent.scrollOffset - paddingTop + "px"; this.parentData.submenu = new Menu(this.submenuContainer, this.submenuActions, this.submenuOptions); if (this.menuStyle) { this.parentData.submenu.style(this.menuStyle); } var boundingRect = this.element.getBoundingClientRect(); var childBoundingRect = this.submenuContainer.getBoundingClientRect(); if (this.expandDirection === Direction.Right) { if (window.innerWidth <= boundingRect.right + childBoundingRect.width) { this.submenuContainer.style.left = '10px'; this.submenuContainer.style.top = this.element.offsetTop - this.parentData.parent.scrollOffset + boundingRect.height + "px"; } else { this.submenuContainer.style.left = this.element.offsetWidth + "px"; this.submenuContainer.style.top = this.element.offsetTop - this.parentData.parent.scrollOffset - paddingTop + "px"; } } else if (this.expandDirection === Direction.Left) { this.submenuContainer.style.right = this.element.offsetWidth + "px"; this.submenuContainer.style.left = 'auto'; this.submenuContainer.style.top = this.element.offsetTop - this.parentData.parent.scrollOffset - paddingTop + "px"; } this.submenuDisposables.add(dom_1.addDisposableListener(this.submenuContainer, dom_1.EventType.KEY_UP, function (e) { var 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(dom_1.addDisposableListener(this.submenuContainer, dom_1.EventType.KEY_DOWN, function (e) { var event = new keyboardEvent_1.StandardKeyboardEvent(e); if (event.equals(15 /* LeftArrow */)) { dom_1.EventHelper.stop(e, true); } })); this.submenuDisposables.add(this.parentData.submenu.onDidCancel(function () { _this.parentData.parent.focus(); _this.cleanupExistingSubmenu(true); })); this.parentData.submenu.focus(selectFirstItem); this.mysubmenu = this.parentData.submenu; } else { this.parentData.submenu.focus(false); } }; SubmenuMenuActionViewItem.prototype.updateAriaExpanded = function (value) { var _a; if (this.item) { (_a = this.item) === null || _a === void 0 ? void 0 : _a.setAttribute('aria-expanded', value); } }; SubmenuMenuActionViewItem.prototype.applyStyle = function () { _super.prototype.applyStyle.call(this); if (!this.menuStyle) { return; } var isSelected = this.element && dom_1.hasClass(this.element, 'focused'); var 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); } }; SubmenuMenuActionViewItem.prototype.dispose = function () { _super.prototype.dispose.call(this); this.hideScheduler.dispose(); if (this.mysubmenu) { this.mysubmenu.dispose(); this.mysubmenu = null; } if (this.submenuContainer) { this.submenuContainer = undefined; } }; return SubmenuMenuActionViewItem; }(BaseMenuActionViewItem)); var MenuSeparatorActionViewItem = /** @class */ (function (_super) { __extends(MenuSeparatorActionViewItem, _super); function MenuSeparatorActionViewItem() { return _super !== null && _super.apply(this, arguments) || this; } MenuSeparatorActionViewItem.prototype.style = function (style) { if (this.label) { this.label.style.borderBottomColor = style.separatorColor ? "" + style.separatorColor : ''; } }; return MenuSeparatorActionViewItem; }(actionbar_1.ActionViewItem)); function cleanMnemonic(label) { var regex = exports.MENU_MNEMONIC_REGEX; var matches = regex.exec(label); if (!matches) { return label; } var mnemonicInText = !matches[1]; return label.replace(regex, mnemonicInText ? '$2$3' : '').trim(); } exports.cleanMnemonic = cleanMnemonic; }); /*--------------------------------------------------------------------------------------------- * 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/base/browser/contextmenu*/], __M([0/*require*/,1/*exports*/,205/*vs/base/browser/ui/menu/menu*/]), function (require, exports, menu_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ContextSubMenu = /** @class */ (function (_super) { __extends(ContextSubMenu, _super); function ContextSubMenu(label, entries) { var _this = _super.call(this, label, entries, 'contextsubmenu') || this; _this.entries = entries; return _this; } return ContextSubMenu; }(menu_1.SubmenuAction)); exports.ContextSubMenu = ContextSubMenu; }); define(__m[406/*vs/nls!vs/base/browser/ui/tree/abstractTree*/], __M([7/*vs/nls*/,8/*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. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[154/*vs/base/browser/ui/tree/abstractTree*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,153/*vs/base/browser/ui/list/listWidget*/,6/*vs/base/browser/dom*/,4/*vs/base/common/event*/,56/*vs/base/browser/keyboardEvent*/,98/*vs/base/browser/dnd*/,19/*vs/base/common/arrays*/,140/*vs/base/browser/ui/list/listView*/,52/*vs/base/browser/event*/,61/*vs/base/common/filters*/,129/*vs/base/browser/ui/tree/indexTreeModel*/,406/*vs/nls!vs/base/browser/ui/tree/abstractTree*/,15/*vs/base/common/async*/,16/*vs/base/common/platform*/,38/*vs/base/common/map*/,131/*vs/base/common/numbers*/,87/*vs/base/common/collections*/,280/*vs/css!vs/base/browser/ui/tree/media/tree*/]), function (require, exports, lifecycle_1, listWidget_1, dom_1, event_1, keyboardEvent_1, dnd_1, arrays_1, listView_1, event_2, filters_1, indexTreeModel_1, nls_1, async_1, platform_1, map_1, numbers_1, collections_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var TreeElementsDragAndDropData = /** @class */ (function (_super) { __extends(TreeElementsDragAndDropData, _super); function TreeElementsDragAndDropData(data) { var _this = _super.call(this, data.elements.map(function (node) { return node.element; })) || this; _this.data = data; return _this; } return TreeElementsDragAndDropData; }(listView_1.ElementsDragAndDropData)); function asTreeDragAndDropData(data) { if (data instanceof listView_1.ElementsDragAndDropData) { return new TreeElementsDragAndDropData(data); } return data; } var TreeNodeListDragAndDrop = /** @class */ (function () { function TreeNodeListDragAndDrop(modelProvider, dnd) { this.modelProvider = modelProvider; this.dnd = dnd; this.autoExpandDisposable = lifecycle_1.Disposable.None; } TreeNodeListDragAndDrop.prototype.getDragURI = function (node) { return this.dnd.getDragURI(node.element); }; TreeNodeListDragAndDrop.prototype.getDragLabel = function (nodes, originalEvent) { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(nodes.map(function (node) { return node.element; }), originalEvent); } return undefined; }; TreeNodeListDragAndDrop.prototype.onDragStart = function (data, originalEvent) { if (this.dnd.onDragStart) { this.dnd.onDragStart(asTreeDragAndDropData(data), originalEvent); } }; TreeNodeListDragAndDrop.prototype.onDragOver = function (data, targetNode, targetIndex, originalEvent, raw) { var _this = this; if (raw === void 0) { raw = true; } var result = this.dnd.onDragOver(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent); var 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 = async_1.disposableTimeout(function () { var model = _this.modelProvider(); var 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) { var accept = typeof result === 'boolean' ? result : result.accept; var effect = typeof result === 'boolean' ? undefined : result.effect; return { accept: accept, effect: effect, feedback: [targetIndex] }; } return result; } if (result.bubble === 1 /* Up */) { var model_1 = this.modelProvider(); var ref_1 = model_1.getNodeLocation(targetNode); var parentRef = model_1.getParentNodeLocation(ref_1); var parentNode = model_1.getNode(parentRef); var parentIndex = parentRef && model_1.getListIndex(parentRef); return this.onDragOver(data, parentNode, parentIndex, originalEvent, false); } var model = this.modelProvider(); var ref = model.getNodeLocation(targetNode); var start = model.getListIndex(ref); var length = model.getListRenderCount(ref); return __assign(__assign({}, result), { feedback: arrays_1.range(start, start + length) }); }; TreeNodeListDragAndDrop.prototype.drop = function (data, targetNode, targetIndex, originalEvent) { this.autoExpandDisposable.dispose(); this.autoExpandNode = undefined; this.dnd.drop(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent); }; TreeNodeListDragAndDrop.prototype.onDragEnd = function (originalEvent) { if (this.dnd.onDragEnd) { this.dnd.onDragEnd(originalEvent); } }; return TreeNodeListDragAndDrop; }()); function asListOptions(modelProvider, options) { return options && __assign(__assign({}, options), { identityProvider: options.identityProvider && { getId: function (el) { return options.identityProvider.getId(el.element); } }, dnd: options.dnd && new TreeNodeListDragAndDrop(modelProvider, options.dnd), multipleSelectionController: options.multipleSelectionController && { isSelectionSingleChangeEvent: function (e) { return options.multipleSelectionController.isSelectionSingleChangeEvent(__assign(__assign({}, e), { element: e.element })); }, isSelectionRangeChangeEvent: function (e) { return options.multipleSelectionController.isSelectionRangeChangeEvent(__assign(__assign({}, e), { element: e.element })); } }, accessibilityProvider: options.accessibilityProvider && __assign(__assign({}, options.accessibilityProvider), { getAriaLabel: function (e) { return options.accessibilityProvider.getAriaLabel(e.element); }, getAriaLevel: function (node) { return node.depth; }, getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && (function (node) { return options.accessibilityProvider.getActiveDescendantId(node.element); }) }), keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && __assign(__assign({}, options.keyboardNavigationLabelProvider), { getKeyboardNavigationLabel: function (node) { return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(node.element); } }), enableKeyboardNavigation: options.simpleKeyboardNavigation, ariaProvider: { getSetSize: function (node) { var model = modelProvider(); var ref = model.getNodeLocation(node); var parentRef = model.getParentNodeLocation(ref); var parentNode = model.getNode(parentRef); return parentNode.visibleChildrenCount; }, getPosInSet: function (node) { return node.visibleChildIndex + 1; }, isChecked: options.ariaProvider && options.ariaProvider.isChecked ? function (node) { return options.ariaProvider.isChecked(node.element); } : undefined, getRole: options.ariaProvider && options.ariaProvider.getRole ? function (node) { return options.ariaProvider.getRole(node.element); } : undefined } }); } var ComposedTreeDelegate = /** @class */ (function () { function ComposedTreeDelegate(delegate) { this.delegate = delegate; } ComposedTreeDelegate.prototype.getHeight = function (element) { return this.delegate.getHeight(element.element); }; ComposedTreeDelegate.prototype.getTemplateId = function (element) { return this.delegate.getTemplateId(element.element); }; ComposedTreeDelegate.prototype.hasDynamicHeight = function (element) { return !!this.delegate.hasDynamicHeight && this.delegate.hasDynamicHeight(element.element); }; ComposedTreeDelegate.prototype.setDynamicHeight = function (element, height) { if (this.delegate.setDynamicHeight) { this.delegate.setDynamicHeight(element.element, height); } }; return ComposedTreeDelegate; }()); exports.ComposedTreeDelegate = ComposedTreeDelegate; var RenderIndentGuides; (function (RenderIndentGuides) { RenderIndentGuides["None"] = "none"; RenderIndentGuides["OnHover"] = "onHover"; RenderIndentGuides["Always"] = "always"; })(RenderIndentGuides = exports.RenderIndentGuides || (exports.RenderIndentGuides = {})); var EventCollection = /** @class */ (function () { function EventCollection(onDidChange, _elements) { var _this = this; if (_elements === void 0) { _elements = []; } this._elements = _elements; this.onDidChange = event_1.Event.forEach(onDidChange, function (elements) { return _this._elements = elements; }); } Object.defineProperty(EventCollection.prototype, "elements", { get: function () { return this._elements; }, enumerable: true, configurable: true }); return EventCollection; }()); var TreeRenderer = /** @class */ (function () { function TreeRenderer(renderer, modelProvider, onDidChangeCollapseState, activeNodes, options) { if (options === void 0) { options = {}; } this.renderer = renderer; this.modelProvider = modelProvider; this.activeNodes = activeNodes; this.renderedElements = new Map(); this.renderedNodes = new Map(); this.indent = TreeRenderer.DefaultIndent; this.hideTwistiesOfChildlessElements = false; this.shouldRenderIndentGuides = false; this.renderedIndentGuides = new collections_1.SetMap(); this.activeIndentNodes = new Set(); this.indentGuidesDisposable = lifecycle_1.Disposable.None; this.disposables = new lifecycle_1.DisposableStore(); this.templateId = renderer.templateId; this.updateOptions(options); event_1.Event.map(onDidChangeCollapseState, function (e) { return e.node; })(this.onDidChangeNodeTwistieState, this, this.disposables); if (renderer.onDidChangeTwistieState) { renderer.onDidChangeTwistieState(this.onDidChangeTwistieState, this, this.disposables); } } TreeRenderer.prototype.updateOptions = function (options) { if (options === void 0) { options = {}; } if (typeof options.indent !== 'undefined') { this.indent = numbers_1.clamp(options.indent, 0, 40); } if (typeof options.renderIndentGuides !== 'undefined') { var shouldRenderIndentGuides = options.renderIndentGuides !== RenderIndentGuides.None; if (shouldRenderIndentGuides !== this.shouldRenderIndentGuides) { this.shouldRenderIndentGuides = shouldRenderIndentGuides; this.indentGuidesDisposable.dispose(); if (shouldRenderIndentGuides) { var 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; } }; TreeRenderer.prototype.renderTemplate = function (container) { var el = dom_1.append(container, dom_1.$('.monaco-tl-row')); var indent = dom_1.append(el, dom_1.$('.monaco-tl-indent')); var twistie = dom_1.append(el, dom_1.$('.monaco-tl-twistie')); var contents = dom_1.append(el, dom_1.$('.monaco-tl-contents')); var templateData = this.renderer.renderTemplate(contents); return { container: container, indent: indent, twistie: twistie, indentGuidesDisposable: lifecycle_1.Disposable.None, templateData: templateData }; }; TreeRenderer.prototype.renderElement = function (node, index, templateData, height) { if (typeof height === 'number') { this.renderedNodes.set(node, { templateData: templateData, height: height }); this.renderedElements.set(node.element, node); } var 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); }; TreeRenderer.prototype.disposeElement = function (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); } }; TreeRenderer.prototype.disposeTemplate = function (templateData) { this.renderer.disposeTemplate(templateData.templateData); }; TreeRenderer.prototype.onDidChangeTwistieState = function (element) { var node = this.renderedElements.get(element); if (!node) { return; } this.onDidChangeNodeTwistieState(node); }; TreeRenderer.prototype.onDidChangeNodeTwistieState = function (node) { var data = this.renderedNodes.get(node); if (!data) { return; } this.renderTwistie(node, data.templateData); this._onDidChangeActiveNodes(this.activeNodes.elements); this.renderIndentGuides(node, data.templateData); }; TreeRenderer.prototype.renderTwistie = function (node, templateData) { if (this.renderer.renderTwistie) { this.renderer.renderTwistie(node.element, templateData.twistie); } if (node.collapsible && (!this.hideTwistiesOfChildlessElements || node.visibleChildrenCount > 0)) { dom_1.addClasses(templateData.twistie, 'codicon', 'codicon-chevron-down', 'collapsible'); dom_1.toggleClass(templateData.twistie, 'collapsed', node.collapsed); } else { dom_1.removeClasses(templateData.twistie, 'codicon', 'codicon-chevron-down', 'collapsible', 'collapsed'); } if (node.collapsible) { templateData.container.setAttribute('aria-expanded', String(!node.collapsed)); } else { templateData.container.removeAttribute('aria-expanded'); } }; TreeRenderer.prototype.renderIndentGuides = function (target, templateData) { var _this = this; dom_1.clearNode(templateData.indent); templateData.indentGuidesDisposable.dispose(); if (!this.shouldRenderIndentGuides) { return; } var disposableStore = new lifecycle_1.DisposableStore(); var model = this.modelProvider(); var node = target; var _loop_1 = function () { var ref = model.getNodeLocation(node); var parentRef = model.getParentNodeLocation(ref); if (!parentRef) { return "break"; } var parent_1 = model.getNode(parentRef); var guide = dom_1.$('.indent-guide', { style: "width: " + this_1.indent + "px" }); if (this_1.activeIndentNodes.has(parent_1)) { dom_1.addClass(guide, 'active'); } if (templateData.indent.childElementCount === 0) { templateData.indent.appendChild(guide); } else { templateData.indent.insertBefore(guide, templateData.indent.firstElementChild); } this_1.renderedIndentGuides.add(parent_1, guide); disposableStore.add(lifecycle_1.toDisposable(function () { return _this.renderedIndentGuides.delete(parent_1, guide); })); node = parent_1; }; var this_1 = this; while (true) { var state_1 = _loop_1(); if (state_1 === "break") break; } templateData.indentGuidesDisposable = disposableStore; }; TreeRenderer.prototype._onDidChangeActiveNodes = function (nodes) { var _this = this; if (!this.shouldRenderIndentGuides) { return; } var set = new Set(); var model = this.modelProvider(); nodes.forEach(function (node) { var ref = model.getNodeLocation(node); try { var 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(function (node) { if (!set.has(node)) { _this.renderedIndentGuides.forEach(node, function (line) { return dom_1.removeClass(line, 'active'); }); } }); set.forEach(function (node) { if (!_this.activeIndentNodes.has(node)) { _this.renderedIndentGuides.forEach(node, function (line) { return dom_1.addClass(line, 'active'); }); } }); this.activeIndentNodes = set; }; TreeRenderer.prototype.dispose = function () { this.renderedNodes.clear(); this.renderedElements.clear(); this.indentGuidesDisposable.dispose(); lifecycle_1.dispose(this.disposables); }; TreeRenderer.DefaultIndent = 8; return TreeRenderer; }()); var TypeFilter = /** @class */ (function () { function TypeFilter(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); } Object.defineProperty(TypeFilter.prototype, "totalCount", { get: function () { return this._totalCount; }, enumerable: true, configurable: true }); Object.defineProperty(TypeFilter.prototype, "matchCount", { get: function () { return this._matchCount; }, enumerable: true, configurable: true }); Object.defineProperty(TypeFilter.prototype, "pattern", { set: function (pattern) { this._pattern = pattern; this._lowercasePattern = pattern.toLowerCase(); }, enumerable: true, configurable: true }); TypeFilter.prototype.filter = function (element, parentVisibility) { if (this._filter) { var result = this._filter.filter(element, parentVisibility); if (this.tree.options.simpleKeyboardNavigation) { return result; } var visibility = void 0; if (typeof result === 'boolean') { visibility = result ? 1 /* Visible */ : 0 /* Hidden */; } else if (indexTreeModel_1.isFilterResult(result)) { visibility = 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 }; } var label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(element); var labelStr = label && label.toString(); if (typeof labelStr === 'undefined') { return { data: filters_1.FuzzyScore.Default, visibility: true }; } var score = filters_1.fuzzyScore(this._pattern, this._lowercasePattern, 0, labelStr, labelStr.toLowerCase(), 0, true); if (!score) { if (this.tree.options.filterOnType) { return 2 /* Recurse */; } else { return { data: filters_1.FuzzyScore.Default, visibility: true }; } // DEMO: smarter filter ? // return parentVisibility === TreeVisibility.Visible ? true : TreeVisibility.Recurse; } this._matchCount++; return { data: score, visibility: true }; }; TypeFilter.prototype.reset = function () { this._totalCount = 0; this._matchCount = 0; }; TypeFilter.prototype.dispose = function () { lifecycle_1.dispose(this.disposables); }; return TypeFilter; }()); var TypeFilterController = /** @class */ (function () { function TypeFilterController(tree, model, view, filter, keyboardNavigationDelegate) { this.tree = tree; this.view = view; this.filter = filter; this.keyboardNavigationDelegate = keyboardNavigationDelegate; this._enabled = false; this._pattern = ''; this._empty = false; this._onDidChangeEmptyState = new event_1.Emitter(); this.positionClassName = 'ne'; this.automaticKeyboardNavigation = true; this.triggered = false; this._onDidChangePattern = new event_1.Emitter(); this.enabledDisposables = new lifecycle_1.DisposableStore(); this.disposables = new lifecycle_1.DisposableStore(); this.domNode = dom_1.$(".monaco-list-type-filter." + this.positionClassName); this.domNode.draggable = true; event_2.domEvent(this.domNode, 'dragstart')(this.onDragStart, this, this.disposables); this.messageDomNode = dom_1.append(view.getHTMLElement(), dom_1.$(".monaco-list-type-filter-message")); this.labelDomNode = dom_1.append(this.domNode, dom_1.$('span.label')); var controls = dom_1.append(this.domNode, dom_1.$('.controls')); this._filterOnType = !!tree.options.filterOnType; this.filterOnTypeDomNode = dom_1.append(controls, dom_1.$('input.filter.codicon.codicon-list-selection')); this.filterOnTypeDomNode.type = 'checkbox'; this.filterOnTypeDomNode.checked = this._filterOnType; this.filterOnTypeDomNode.tabIndex = -1; this.updateFilterOnTypeTitle(); event_2.domEvent(this.filterOnTypeDomNode, 'input')(this.onDidChangeFilterOnType, this, this.disposables); this.clearDomNode = dom_1.append(controls, dom_1.$('button.clear.codicon.codicon-close')); this.clearDomNode.tabIndex = -1; this.clearDomNode.title = nls_1.localize(0, null); this.keyboardNavigationEventFilter = tree.options.keyboardNavigationEventFilter; model.onDidSplice(this.onDidSpliceModel, this, this.disposables); this.updateOptions(tree.options); } Object.defineProperty(TypeFilterController.prototype, "enabled", { get: function () { return this._enabled; }, enumerable: true, configurable: true }); Object.defineProperty(TypeFilterController.prototype, "pattern", { get: function () { return this._pattern; }, enumerable: true, configurable: true }); Object.defineProperty(TypeFilterController.prototype, "filterOnType", { get: function () { return this._filterOnType; }, enumerable: true, configurable: true }); TypeFilterController.prototype.updateOptions = function (options) { if (options.simpleKeyboardNavigation) { this.disable(); } else { this.enable(); } if (typeof options.filterOnType !== 'undefined') { this._filterOnType = !!options.filterOnType; this.filterOnTypeDomNode.checked = this._filterOnType; } if (typeof options.automaticKeyboardNavigation !== 'undefined') { this.automaticKeyboardNavigation = options.automaticKeyboardNavigation; } this.tree.refilter(); this.render(); if (!this.automaticKeyboardNavigation) { this.onEventOrInput(''); } }; TypeFilterController.prototype.enable = function () { var _this = this; if (this._enabled) { return; } var onKeyDown = event_1.Event.chain(event_2.domEvent(this.view.getHTMLElement(), 'keydown')) .filter(function (e) { return !isInputElement(e.target) || e.target === _this.filterOnTypeDomNode; }) .filter(function (e) { return e.key !== 'Dead' && !/^Media/.test(e.key); }) .map(function (e) { return new keyboardEvent_1.StandardKeyboardEvent(e); }) .filter(this.keyboardNavigationEventFilter || (function () { return true; })) .filter(function () { return _this.automaticKeyboardNavigation || _this.triggered; }) .filter(function (e) { return _this.keyboardNavigationDelegate.mightProducePrintableCharacter(e) || ((_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(function (e) { e.stopPropagation(); e.preventDefault(); }) .event; var onClear = event_2.domEvent(this.clearDomNode, 'click'); event_1.Event.chain(event_1.Event.any(onKeyDown, onClear)) .event(this.onEventOrInput, this, this.enabledDisposables); this.filter.pattern = ''; this.tree.refilter(); this.render(); this._enabled = true; this.triggered = false; }; TypeFilterController.prototype.disable = function () { if (!this._enabled) { return; } this.domNode.remove(); this.enabledDisposables.clear(); this.tree.refilter(); this.render(); this._enabled = false; this.triggered = false; }; TypeFilterController.prototype.onEventOrInput = function (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); } }; TypeFilterController.prototype.onInput = function (pattern) { var 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, function (node) { return !filters_1.FuzzyScore.isDefault(node.filterData); }); } var focus = this.tree.getFocus(); if (focus.length > 0) { var element = focus[0]; if (this.tree.getRelativeTop(element) === null) { this.tree.reveal(element, 0.5); } } this.render(); if (!pattern) { this.triggered = false; } }; TypeFilterController.prototype.onDragStart = function () { var _this = this; var container = this.view.getHTMLElement(); var left = dom_1.getDomNodePagePosition(container).left; var containerWidth = container.clientWidth; var midContainerWidth = containerWidth / 2; var width = this.domNode.clientWidth; var disposables = new lifecycle_1.DisposableStore(); var positionClassName = this.positionClassName; var updatePosition = function () { 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; } }; var onDragOver = function (event) { event.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome) var x = event.screenX - left; if (event.dataTransfer) { event.dataTransfer.dropEffect = 'none'; } if (x < midContainerWidth) { positionClassName = 'nw'; } else { positionClassName = 'ne'; } updatePosition(); }; var onDragEnd = function () { _this.positionClassName = positionClassName; _this.domNode.className = "monaco-list-type-filter " + _this.positionClassName; _this.domNode.style.top = ''; _this.domNode.style.left = ''; lifecycle_1.dispose(disposables); }; updatePosition(); dom_1.removeClass(this.domNode, positionClassName); dom_1.addClass(this.domNode, 'dragging'); disposables.add(lifecycle_1.toDisposable(function () { return dom_1.removeClass(_this.domNode, 'dragging'); })); event_2.domEvent(document, 'dragover')(onDragOver, null, disposables); event_2.domEvent(this.domNode, 'dragend')(onDragEnd, null, disposables); dnd_1.StaticDND.CurrentDragAndDropData = new dnd_1.DragAndDropData('vscode-ui'); disposables.add(lifecycle_1.toDisposable(function () { return dnd_1.StaticDND.CurrentDragAndDropData = undefined; })); }; TypeFilterController.prototype.onDidSpliceModel = function () { if (!this._enabled || this.pattern.length === 0) { return; } this.tree.refilter(); this.render(); }; TypeFilterController.prototype.onDidChangeFilterOnType = function () { this.tree.updateOptions({ filterOnType: this.filterOnTypeDomNode.checked }); this.tree.refilter(); this.tree.domFocus(); this.render(); this.updateFilterOnTypeTitle(); }; TypeFilterController.prototype.updateFilterOnTypeTitle = function () { if (this.filterOnType) { this.filterOnTypeDomNode.title = nls_1.localize(1, null); } else { this.filterOnTypeDomNode.title = nls_1.localize(2, null); } }; TypeFilterController.prototype.render = function () { var noMatches = this.filter.totalCount > 0 && this.filter.matchCount === 0; if (this.pattern && this.tree.options.filterOnType && noMatches) { this.messageDomNode.textContent = nls_1.localize(3, null); this._empty = true; } else { this.messageDomNode.innerHTML = ''; this._empty = false; } dom_1.toggleClass(this.domNode, 'no-matches', noMatches); this.domNode.title = 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); }; TypeFilterController.prototype.shouldAllowFocus = function (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); }; TypeFilterController.prototype.dispose = function () { if (this._enabled) { this.domNode.remove(); this.enabledDisposables.dispose(); this._enabled = false; this.triggered = false; } this._onDidChangePattern.dispose(); lifecycle_1.dispose(this.disposables); }; return TypeFilterController; }()); function isInputElement(e) { return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA'; } function asTreeEvent(event) { return { elements: event.elements.map(function (node) { return node.element; }), browserEvent: event.browserEvent }; } function dfs(node, fn) { fn(node); node.children.forEach(function (child) { return dfs(child, fn); }); } /** * The trait concept needs to exist at the tree level, because collapsed * tree nodes will not be known by the list. */ var Trait = /** @class */ (function () { function Trait(identityProvider) { this.identityProvider = identityProvider; this.nodes = []; this._onDidChange = new event_1.Emitter(); this.onDidChange = this._onDidChange.event; } Object.defineProperty(Trait.prototype, "nodeSet", { get: function () { if (!this._nodeSet) { this._nodeSet = this.createNodeSet(); } return this._nodeSet; }, enumerable: true, configurable: true }); Trait.prototype.set = function (nodes, browserEvent) { if (arrays_1.equals(this.nodes, nodes)) { return; } this._set(nodes, false, browserEvent); }; Trait.prototype._set = function (nodes, silent, browserEvent) { this.nodes = __spreadArrays(nodes); this.elements = undefined; this._nodeSet = undefined; if (!silent) { var that_1 = this; this._onDidChange.fire({ get elements() { return that_1.get(); }, browserEvent: browserEvent }); } }; Trait.prototype.get = function () { if (!this.elements) { this.elements = this.nodes.map(function (node) { return node.element; }); } return __spreadArrays(this.elements); }; Trait.prototype.getNodes = function () { return this.nodes; }; Trait.prototype.has = function (node) { return this.nodeSet.has(node); }; Trait.prototype.onDidModelSplice = function (_a) { var _this = this; var insertedNodes = _a.insertedNodes, deletedNodes = _a.deletedNodes; if (!this.identityProvider) { var set_1 = this.createNodeSet(); var visit_1 = function (node) { return set_1.delete(node); }; deletedNodes.forEach(function (node) { return dfs(node, visit_1); }); this.set(map_1.values(set_1)); return; } var deletedNodesIdSet = new Set(); var deletedNodesVisitor = function (node) { return deletedNodesIdSet.add(_this.identityProvider.getId(node.element).toString()); }; deletedNodes.forEach(function (node) { return dfs(node, deletedNodesVisitor); }); var insertedNodesMap = new Map(); var insertedNodesVisitor = function (node) { return insertedNodesMap.set(_this.identityProvider.getId(node.element).toString(), node); }; insertedNodes.forEach(function (node) { return dfs(node, insertedNodesVisitor); }); var nodes = []; for (var _i = 0, _b = this.nodes; _i < _b.length; _i++) { var node = _b[_i]; var id = this.identityProvider.getId(node.element).toString(); var wasDeleted = deletedNodesIdSet.has(id); if (!wasDeleted) { nodes.push(node); } else { var insertedNode = insertedNodesMap.get(id); if (insertedNode) { nodes.push(insertedNode); } } } this._set(nodes, true); }; Trait.prototype.createNodeSet = function () { var set = new Set(); for (var _i = 0, _a = this.nodes; _i < _a.length; _i++) { var node = _a[_i]; set.add(node); } return set; }; return Trait; }()); var TreeNodeListMouseController = /** @class */ (function (_super) { __extends(TreeNodeListMouseController, _super); function TreeNodeListMouseController(list, tree) { var _this = _super.call(this, list) || this; _this.tree = tree; return _this; } TreeNodeListMouseController.prototype.onPointer = function (e) { if (isInputElement(e.browserEvent.target)) { return; } var node = e.element; if (!node) { return _super.prototype.onPointer.call(this, e); } if (this.isSelectionRangeChangeEvent(e) || this.isSelectionSingleChangeEvent(e)) { return _super.prototype.onPointer.call(this, e); } var onTwistie = dom_1.hasClass(e.browserEvent.target, 'monaco-tl-twistie'); if (!this.tree.openOnSingleClick && e.browserEvent.detail !== 2 && !onTwistie) { return _super.prototype.onPointer.call(this, e); } var expandOnlyOnTwistieClick = false; if (typeof this.tree.expandOnlyOnTwistieClick === 'function') { expandOnlyOnTwistieClick = this.tree.expandOnlyOnTwistieClick(node.element); } else { expandOnlyOnTwistieClick = !!this.tree.expandOnlyOnTwistieClick; } if (expandOnlyOnTwistieClick && !onTwistie) { return _super.prototype.onPointer.call(this, e); } if (node.collapsible) { var model = this.tree.model; // internal var location_1 = model.getNodeLocation(node); var recursive = e.browserEvent.altKey; model.setCollapsed(location_1, undefined, recursive); if (expandOnlyOnTwistieClick && onTwistie) { return; } } _super.prototype.onPointer.call(this, e); }; TreeNodeListMouseController.prototype.onDoubleClick = function (e) { var onTwistie = dom_1.hasClass(e.browserEvent.target, 'monaco-tl-twistie'); if (onTwistie) { return; } _super.prototype.onDoubleClick.call(this, e); }; return TreeNodeListMouseController; }(listWidget_1.MouseController)); /** * We use this List subclass to restore selection and focus as nodes * get rendered in the list, possibly due to a node expand() call. */ var TreeNodeList = /** @class */ (function (_super) { __extends(TreeNodeList, _super); function TreeNodeList(user, container, virtualDelegate, renderers, focusTrait, selectionTrait, options) { var _this = _super.call(this, user, container, virtualDelegate, renderers, options) || this; _this.focusTrait = focusTrait; _this.selectionTrait = selectionTrait; return _this; } TreeNodeList.prototype.createMouseController = function (options) { return new TreeNodeListMouseController(this, options.tree); }; TreeNodeList.prototype.splice = function (start, deleteCount, elements) { var _this = this; if (elements === void 0) { elements = []; } _super.prototype.splice.call(this, start, deleteCount, elements); if (elements.length === 0) { return; } var additionalFocus = []; var additionalSelection = []; elements.forEach(function (node, index) { if (_this.focusTrait.has(node)) { additionalFocus.push(start + index); } if (_this.selectionTrait.has(node)) { additionalSelection.push(start + index); } }); if (additionalFocus.length > 0) { _super.prototype.setFocus.call(this, arrays_1.distinctES6(__spreadArrays(_super.prototype.getFocus.call(this), additionalFocus))); } if (additionalSelection.length > 0) { _super.prototype.setSelection.call(this, arrays_1.distinctES6(__spreadArrays(_super.prototype.getSelection.call(this), additionalSelection))); } }; TreeNodeList.prototype.setFocus = function (indexes, browserEvent, fromAPI) { var _this = this; if (fromAPI === void 0) { fromAPI = false; } _super.prototype.setFocus.call(this, indexes, browserEvent); if (!fromAPI) { this.focusTrait.set(indexes.map(function (i) { return _this.element(i); }), browserEvent); } }; TreeNodeList.prototype.setSelection = function (indexes, browserEvent, fromAPI) { var _this = this; if (fromAPI === void 0) { fromAPI = false; } _super.prototype.setSelection.call(this, indexes, browserEvent); if (!fromAPI) { this.selectionTrait.set(indexes.map(function (i) { return _this.element(i); }), browserEvent); } }; return TreeNodeList; }(listWidget_1.List)); var AbstractTree = /** @class */ (function () { function AbstractTree(user, container, delegate, renderers, _options) { var _this = this; if (_options === void 0) { _options = {}; } this._options = _options; this.eventBufferer = new event_1.EventBufferer(); this.disposables = new lifecycle_1.DisposableStore(); this._onWillRefilter = new event_1.Emitter(); this.onWillRefilter = this._onWillRefilter.event; this._onDidUpdateOptions = new event_1.Emitter(); var treeDelegate = new ComposedTreeDelegate(delegate); var onDidChangeCollapseStateRelay = new event_1.Relay(); var onDidChangeActiveNodes = new event_1.Relay(); var activeNodes = new EventCollection(onDidChangeActiveNodes.event); this.renderers = renderers.map(function (r) { return new TreeRenderer(r, function () { return _this.model; }, onDidChangeCollapseStateRelay.event, activeNodes, _options); }); for (var _i = 0, _a = this.renderers; _i < _a.length; _i++) { var r = _a[_i]; this.disposables.add(r); } var filter; if (_options.keyboardNavigationLabelProvider) { filter = new TypeFilter(this, _options.keyboardNavigationLabelProvider, _options.filter); _options = __assign(__assign({}, _options), { filter: filter }); // TODO need typescript help here this.disposables.add(filter); } this.focus = new Trait(_options.identityProvider); this.selection = new Trait(_options.identityProvider); this.view = new TreeNodeList(user, container, treeDelegate, this.renderers, this.focus, this.selection, __assign(__assign({}, asListOptions(function () { return _this.model; }, _options)), { tree: this })); this.model = this.createModel(user, this.view, _options); onDidChangeCollapseStateRelay.input = this.model.onDidChangeCollapseState; var onDidModelSplice = event_1.Event.forEach(this.model.onDidSplice, function (e) { _this.eventBufferer.bufferEvents(function () { _this.focus.onDidModelSplice(e); _this.selection.onDidModelSplice(e); }); }); // Make sure the `forEach` always runs onDidModelSplice(function () { return null; }, null, this.disposables); // Active nodes can change when the model changes or when focus or selection change. // We debounce it with 0 delay since these events may fire in the same stack and we only // want to run this once. It also doesn't matter if it runs on the next tick since it's only // a nice to have UI feature. onDidChangeActiveNodes.input = event_1.Event.chain(event_1.Event.any(onDidModelSplice, this.focus.onDidChange, this.selection.onDidChange)) .debounce(function () { return null; }, 0) .map(function () { var set = new Set(); for (var _i = 0, _a = _this.focus.getNodes(); _i < _a.length; _i++) { var node = _a[_i]; set.add(node); } for (var _b = 0, _c = _this.selection.getNodes(); _b < _c.length; _b++) { var node = _c[_b]; set.add(node); } return arrays_1.fromSet(set); }).event; if (_options.keyboardSupport !== false) { var onKeyDown = event_1.Event.chain(this.view.onKeyDown) .filter(function (e) { return !isInputElement(e.target); }) .map(function (e) { return new keyboardEvent_1.StandardKeyboardEvent(e); }); onKeyDown.filter(function (e) { return e.keyCode === 15 /* LeftArrow */; }).on(this.onLeftArrow, this, this.disposables); onKeyDown.filter(function (e) { return e.keyCode === 17 /* RightArrow */; }).on(this.onRightArrow, this, this.disposables); onKeyDown.filter(function (e) { return e.keyCode === 10 /* Space */; }).on(this.onSpace, this, this.disposables); } if (_options.keyboardNavigationLabelProvider) { var delegate_1 = _options.keyboardNavigationDelegate || listWidget_1.DefaultKeyboardNavigationDelegate; this.typeFilterController = new TypeFilterController(this, this.model, this.view, filter, delegate_1); this.focusNavigationFilter = function (node) { return _this.typeFilterController.shouldAllowFocus(node); }; this.disposables.add(this.typeFilterController); } this.styleElement = dom_1.createStyleSheet(this.view.getHTMLElement()); dom_1.toggleClass(this.getHTMLElement(), 'always', this._options.renderIndentGuides === RenderIndentGuides.Always); } Object.defineProperty(AbstractTree.prototype, "onDidChangeFocus", { get: function () { return this.eventBufferer.wrapEvent(this.focus.onDidChange); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractTree.prototype, "onDidChangeSelection", { get: function () { return this.eventBufferer.wrapEvent(this.selection.onDidChange); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractTree.prototype, "onDidOpen", { get: function () { return event_1.Event.map(this.view.onDidOpen, asTreeEvent); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractTree.prototype, "onDidFocus", { get: function () { return this.view.onDidFocus; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractTree.prototype, "onDidChangeCollapseState", { get: function () { return this.model.onDidChangeCollapseState; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractTree.prototype, "openOnSingleClick", { get: function () { return typeof this._options.openOnSingleClick === 'undefined' ? true : this._options.openOnSingleClick; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractTree.prototype, "expandOnlyOnTwistieClick", { get: function () { return typeof this._options.expandOnlyOnTwistieClick === 'undefined' ? false : this._options.expandOnlyOnTwistieClick; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractTree.prototype, "onDidDispose", { get: function () { return this.view.onDidDispose; }, enumerable: true, configurable: true }); AbstractTree.prototype.updateOptions = function (optionsUpdate) { if (optionsUpdate === void 0) { optionsUpdate = {}; } this._options = __assign(__assign({}, this._options), optionsUpdate); for (var _i = 0, _a = this.renderers; _i < _a.length; _i++) { var renderer = _a[_i]; renderer.updateOptions(optionsUpdate); } this.view.updateOptions({ enableKeyboardNavigation: this._options.simpleKeyboardNavigation, automaticKeyboardNavigation: this._options.automaticKeyboardNavigation }); if (this.typeFilterController) { this.typeFilterController.updateOptions(this._options); } this._onDidUpdateOptions.fire(this._options); dom_1.toggleClass(this.getHTMLElement(), 'always', this._options.renderIndentGuides === RenderIndentGuides.Always); }; Object.defineProperty(AbstractTree.prototype, "options", { get: function () { return this._options; }, enumerable: true, configurable: true }); // Widget AbstractTree.prototype.getHTMLElement = function () { return this.view.getHTMLElement(); }; Object.defineProperty(AbstractTree.prototype, "scrollTop", { get: function () { return this.view.scrollTop; }, set: function (scrollTop) { this.view.scrollTop = scrollTop; }, enumerable: true, configurable: true }); AbstractTree.prototype.domFocus = function () { this.view.domFocus(); }; AbstractTree.prototype.layout = function (height, width) { this.view.layout(height, width); }; AbstractTree.prototype.style = function (styles) { var suffix = "." + this.view.domId; var 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 + "; }"); } var newStyles = content.join('\n'); if (newStyles !== this.styleElement.innerHTML) { this.styleElement.innerHTML = newStyles; } this.view.style(styles); }; AbstractTree.prototype.collapse = function (location, recursive) { if (recursive === void 0) { recursive = false; } return this.model.setCollapsed(location, true, recursive); }; AbstractTree.prototype.expand = function (location, recursive) { if (recursive === void 0) { recursive = false; } return this.model.setCollapsed(location, false, recursive); }; AbstractTree.prototype.isCollapsible = function (location) { return this.model.isCollapsible(location); }; AbstractTree.prototype.setCollapsible = function (location, collapsible) { return this.model.setCollapsible(location, collapsible); }; AbstractTree.prototype.isCollapsed = function (location) { return this.model.isCollapsed(location); }; AbstractTree.prototype.refilter = function () { this._onWillRefilter.fire(undefined); this.model.refilter(); }; AbstractTree.prototype.setSelection = function (elements, browserEvent) { var _this = this; var nodes = elements.map(function (e) { return _this.model.getNode(e); }); this.selection.set(nodes, browserEvent); var indexes = elements.map(function (e) { return _this.model.getListIndex(e); }).filter(function (i) { return i > -1; }); this.view.setSelection(indexes, browserEvent, true); }; AbstractTree.prototype.getSelection = function () { return this.selection.get(); }; AbstractTree.prototype.setFocus = function (elements, browserEvent) { var _this = this; var nodes = elements.map(function (e) { return _this.model.getNode(e); }); this.focus.set(nodes, browserEvent); var indexes = elements.map(function (e) { return _this.model.getListIndex(e); }).filter(function (i) { return i > -1; }); this.view.setFocus(indexes, browserEvent, true); }; AbstractTree.prototype.focusNext = function (n, loop, browserEvent, filter) { if (n === void 0) { n = 1; } if (loop === void 0) { loop = false; } if (filter === void 0) { filter = this.focusNavigationFilter; } this.view.focusNext(n, loop, browserEvent, filter); }; AbstractTree.prototype.getFocus = function () { return this.focus.get(); }; AbstractTree.prototype.reveal = function (location, relativeTop) { this.model.expandTo(location); var 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. */ AbstractTree.prototype.getRelativeTop = function (location) { var index = this.model.getListIndex(location); if (index === -1) { return null; } return this.view.getRelativeTop(index); }; // List AbstractTree.prototype.onLeftArrow = function (e) { e.preventDefault(); e.stopPropagation(); var nodes = this.view.getFocusedElements(); if (nodes.length === 0) { return; } var node = nodes[0]; var location = this.model.getNodeLocation(node); var didChange = this.model.setCollapsed(location, true); if (!didChange) { var parentLocation = this.model.getParentNodeLocation(location); if (!parentLocation) { return; } var parentListIndex = this.model.getListIndex(parentLocation); this.view.reveal(parentListIndex); this.view.setFocus([parentListIndex]); } }; AbstractTree.prototype.onRightArrow = function (e) { e.preventDefault(); e.stopPropagation(); var nodes = this.view.getFocusedElements(); if (nodes.length === 0) { return; } var node = nodes[0]; var location = this.model.getNodeLocation(node); var didChange = this.model.setCollapsed(location, false); if (!didChange) { if (!node.children.some(function (child) { return child.visible; })) { return; } var focusedIndex = this.view.getFocus()[0]; var firstChildIndex = focusedIndex + 1; this.view.reveal(firstChildIndex); this.view.setFocus([firstChildIndex]); } }; AbstractTree.prototype.onSpace = function (e) { e.preventDefault(); e.stopPropagation(); var nodes = this.view.getFocusedElements(); if (nodes.length === 0) { return; } var node = nodes[0]; var location = this.model.getNodeLocation(node); var recursive = e.browserEvent.altKey; this.model.setCollapsed(location, undefined, recursive); }; AbstractTree.prototype.dispose = function () { lifecycle_1.dispose(this.disposables); this.view.dispose(); }; return AbstractTree; }()); 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[407/*vs/base/browser/ui/tree/dataTree*/], __M([0/*require*/,1/*exports*/,154/*vs/base/browser/ui/tree/abstractTree*/,130/*vs/base/browser/ui/tree/objectTreeModel*/]), function (require, exports, abstractTree_1, objectTreeModel_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DataTree = /** @class */ (function (_super) { __extends(DataTree, _super); function DataTree(user, container, delegate, renderers, dataSource, options) { if (options === void 0) { options = {}; } var _this = _super.call(this, user, container, delegate, renderers, options) || this; _this.user = user; _this.dataSource = dataSource; _this.identityProvider = options.identityProvider; return _this; } DataTree.prototype.createModel = function (user, view, options) { return new objectTreeModel_1.ObjectTreeModel(user, view, options); }; return DataTree; }(abstractTree_1.AbstractTree)); 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[206/*vs/base/browser/ui/tree/objectTree*/], __M([0/*require*/,1/*exports*/,154/*vs/base/browser/ui/tree/abstractTree*/,130/*vs/base/browser/ui/tree/objectTreeModel*/,243/*vs/base/browser/ui/tree/compressedObjectTreeModel*/,101/*vs/base/common/decorators*/]), function (require, exports, abstractTree_1, objectTreeModel_1, compressedObjectTreeModel_1, decorators_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ObjectTree = /** @class */ (function (_super) { __extends(ObjectTree, _super); function ObjectTree(user, container, delegate, renderers, options) { if (options === void 0) { options = {}; } return _super.call(this, user, container, delegate, renderers, options) || this; } Object.defineProperty(ObjectTree.prototype, "onDidChangeCollapseState", { get: function () { return this.model.onDidChangeCollapseState; }, enumerable: true, configurable: true }); ObjectTree.prototype.setChildren = function (element, children) { this.model.setChildren(element, children); }; ObjectTree.prototype.rerender = function (element) { if (element === undefined) { this.view.rerender(); return; } this.model.rerender(element); }; ObjectTree.prototype.hasElement = function (element) { return this.model.has(element); }; ObjectTree.prototype.createModel = function (user, view, options) { return new objectTreeModel_1.ObjectTreeModel(user, view, options); }; return ObjectTree; }(abstractTree_1.AbstractTree)); exports.ObjectTree = ObjectTree; var CompressibleRenderer = /** @class */ (function () { function CompressibleRenderer(_compressedTreeNodeProvider, renderer) { this._compressedTreeNodeProvider = _compressedTreeNodeProvider; this.renderer = renderer; this.templateId = renderer.templateId; if (renderer.onDidChangeTwistieState) { this.onDidChangeTwistieState = renderer.onDidChangeTwistieState; } } Object.defineProperty(CompressibleRenderer.prototype, "compressedTreeNodeProvider", { get: function () { return this._compressedTreeNodeProvider(); }, enumerable: true, configurable: true }); CompressibleRenderer.prototype.renderTemplate = function (container) { var data = this.renderer.renderTemplate(container); return { compressedTreeNode: undefined, data: data }; }; CompressibleRenderer.prototype.renderElement = function (node, index, templateData, height) { var 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); } }; CompressibleRenderer.prototype.disposeElement = function (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); } } }; CompressibleRenderer.prototype.disposeTemplate = function (templateData) { this.renderer.disposeTemplate(templateData.data); }; CompressibleRenderer.prototype.renderTwistie = function (element, twistieElement) { if (this.renderer.renderTwistie) { this.renderer.renderTwistie(element, twistieElement); } }; __decorate([ decorators_1.memoize ], CompressibleRenderer.prototype, "compressedTreeNodeProvider", null); return CompressibleRenderer; }()); function asObjectTreeOptions(compressedTreeNodeProvider, options) { return options && __assign(__assign({}, options), { keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && { getKeyboardNavigationLabel: function (e) { var 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); } } } }); } var CompressibleObjectTree = /** @class */ (function (_super) { __extends(CompressibleObjectTree, _super); function CompressibleObjectTree(user, container, delegate, renderers, options) { if (options === void 0) { options = {}; } var _this = this; var compressedTreeNodeProvider = function () { return _this; }; var compressibleRenderers = renderers.map(function (r) { return new CompressibleRenderer(compressedTreeNodeProvider, r); }); _this = _super.call(this, user, container, delegate, compressibleRenderers, asObjectTreeOptions(compressedTreeNodeProvider, options)) || this; return _this; } CompressibleObjectTree.prototype.setChildren = function (element, children) { this.model.setChildren(element, children); }; CompressibleObjectTree.prototype.createModel = function (user, view, options) { return new compressedObjectTreeModel_1.CompressibleObjectTreeModel(user, view, options); }; CompressibleObjectTree.prototype.updateOptions = function (optionsUpdate) { if (optionsUpdate === void 0) { optionsUpdate = {}; } _super.prototype.updateOptions.call(this, optionsUpdate); if (typeof optionsUpdate.compressionEnabled !== 'undefined') { this.model.setCompressionEnabled(optionsUpdate.compressionEnabled); } }; CompressibleObjectTree.prototype.getCompressedTreeNode = function (element) { if (element === void 0) { element = null; } return this.model.getCompressedTreeNode(element); }; return CompressibleObjectTree; }(ObjectTree)); 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. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[408/*vs/base/browser/ui/tree/asyncDataTree*/], __M([0/*require*/,1/*exports*/,154/*vs/base/browser/ui/tree/abstractTree*/,206/*vs/base/browser/ui/tree/objectTree*/,99/*vs/base/browser/ui/tree/tree*/,2/*vs/base/common/lifecycle*/,4/*vs/base/common/event*/,15/*vs/base/common/async*/,54/*vs/base/common/iterator*/,140/*vs/base/browser/ui/list/listView*/,10/*vs/base/common/errors*/,6/*vs/base/browser/dom*/,38/*vs/base/common/map*/,129/*vs/base/browser/ui/tree/indexTreeModel*/]), function (require, exports, abstractTree_1, objectTree_1, tree_1, lifecycle_1, event_1, async_1, iterator_1, listView_1, errors_1, dom_1, map_1, indexTreeModel_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function createAsyncDataTreeNode(props) { return __assign(__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); } var AsyncDataTreeNodeWrapper = /** @class */ (function () { function AsyncDataTreeNodeWrapper(node) { this.node = node; } Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "element", { get: function () { return this.node.element.element; }, enumerable: true, configurable: true }); Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "children", { get: function () { return this.node.children.map(function (node) { return new AsyncDataTreeNodeWrapper(node); }); }, enumerable: true, configurable: true }); Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "depth", { get: function () { return this.node.depth; }, enumerable: true, configurable: true }); Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "visibleChildrenCount", { get: function () { return this.node.visibleChildrenCount; }, enumerable: true, configurable: true }); Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "visibleChildIndex", { get: function () { return this.node.visibleChildIndex; }, enumerable: true, configurable: true }); Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "collapsible", { get: function () { return this.node.collapsible; }, enumerable: true, configurable: true }); Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "collapsed", { get: function () { return this.node.collapsed; }, enumerable: true, configurable: true }); Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "visible", { get: function () { return this.node.visible; }, enumerable: true, configurable: true }); Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "filterData", { get: function () { return this.node.filterData; }, enumerable: true, configurable: true }); return AsyncDataTreeNodeWrapper; }()); var AsyncDataTreeRenderer = /** @class */ (function () { function AsyncDataTreeRenderer(renderer, nodeMapper, onDidChangeTwistieState) { this.renderer = renderer; this.nodeMapper = nodeMapper; this.onDidChangeTwistieState = onDidChangeTwistieState; this.renderedNodes = new Map(); this.templateId = renderer.templateId; } AsyncDataTreeRenderer.prototype.renderTemplate = function (container) { var templateData = this.renderer.renderTemplate(container); return { templateData: templateData }; }; AsyncDataTreeRenderer.prototype.renderElement = function (node, index, templateData, height) { this.renderer.renderElement(this.nodeMapper.map(node), index, templateData.templateData, height); }; AsyncDataTreeRenderer.prototype.renderTwistie = function (element, twistieElement) { dom_1.toggleClass(twistieElement, 'codicon-loading', element.slow); return false; }; AsyncDataTreeRenderer.prototype.disposeElement = function (node, index, templateData, height) { if (this.renderer.disposeElement) { this.renderer.disposeElement(this.nodeMapper.map(node), index, templateData.templateData, height); } }; AsyncDataTreeRenderer.prototype.disposeTemplate = function (templateData) { this.renderer.disposeTemplate(templateData.templateData); }; AsyncDataTreeRenderer.prototype.dispose = function () { this.renderedNodes.clear(); }; return AsyncDataTreeRenderer; }()); function asTreeEvent(e) { return { browserEvent: e.browserEvent, elements: e.elements.map(function (e) { return e.element; }) }; } var AsyncDataTreeElementsDragAndDropData = /** @class */ (function (_super) { __extends(AsyncDataTreeElementsDragAndDropData, _super); function AsyncDataTreeElementsDragAndDropData(data) { var _this = _super.call(this, data.elements.map(function (node) { return node.element; })) || this; _this.data = data; return _this; } return AsyncDataTreeElementsDragAndDropData; }(listView_1.ElementsDragAndDropData)); function asAsyncDataTreeDragAndDropData(data) { if (data instanceof listView_1.ElementsDragAndDropData) { return new AsyncDataTreeElementsDragAndDropData(data); } return data; } var AsyncDataTreeNodeListDragAndDrop = /** @class */ (function () { function AsyncDataTreeNodeListDragAndDrop(dnd) { this.dnd = dnd; } AsyncDataTreeNodeListDragAndDrop.prototype.getDragURI = function (node) { return this.dnd.getDragURI(node.element); }; AsyncDataTreeNodeListDragAndDrop.prototype.getDragLabel = function (nodes, originalEvent) { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(nodes.map(function (node) { return node.element; }), originalEvent); } return undefined; }; AsyncDataTreeNodeListDragAndDrop.prototype.onDragStart = function (data, originalEvent) { if (this.dnd.onDragStart) { this.dnd.onDragStart(asAsyncDataTreeDragAndDropData(data), originalEvent); } }; AsyncDataTreeNodeListDragAndDrop.prototype.onDragOver = function (data, targetNode, targetIndex, originalEvent, raw) { if (raw === void 0) { raw = true; } return this.dnd.onDragOver(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent); }; AsyncDataTreeNodeListDragAndDrop.prototype.drop = function (data, targetNode, targetIndex, originalEvent) { this.dnd.drop(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent); }; AsyncDataTreeNodeListDragAndDrop.prototype.onDragEnd = function (originalEvent) { if (this.dnd.onDragEnd) { this.dnd.onDragEnd(originalEvent); } }; return AsyncDataTreeNodeListDragAndDrop; }()); function asObjectTreeOptions(options) { return options && __assign(__assign({}, options), { collapseByDefault: true, identityProvider: options.identityProvider && { getId: function (el) { return options.identityProvider.getId(el.element); } }, dnd: options.dnd && new AsyncDataTreeNodeListDragAndDrop(options.dnd), multipleSelectionController: options.multipleSelectionController && { isSelectionSingleChangeEvent: function (e) { return options.multipleSelectionController.isSelectionSingleChangeEvent(__assign(__assign({}, e), { element: e.element })); }, isSelectionRangeChangeEvent: function (e) { return options.multipleSelectionController.isSelectionRangeChangeEvent(__assign(__assign({}, e), { element: e.element })); } }, accessibilityProvider: options.accessibilityProvider && __assign(__assign({}, options.accessibilityProvider), { getAriaLabel: function (e) { return options.accessibilityProvider.getAriaLabel(e.element); }, getAriaLevel: options.accessibilityProvider.getAriaLevel && (function (node) { return options.accessibilityProvider.getAriaLevel(node.element); }), getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && (function (node) { return options.accessibilityProvider.getActiveDescendantId(node.element); }) }), filter: options.filter && { filter: function (e, parentVisibility) { return options.filter.filter(e.element, parentVisibility); } }, keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && __assign(__assign({}, options.keyboardNavigationLabelProvider), { getKeyboardNavigationLabel: function (e) { return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e.element); } }), sorter: undefined, expandOnlyOnTwistieClick: typeof options.expandOnlyOnTwistieClick === 'undefined' ? undefined : (typeof options.expandOnlyOnTwistieClick !== 'function' ? options.expandOnlyOnTwistieClick : (function (e) { return options.expandOnlyOnTwistieClick(e.element); })), ariaProvider: options.ariaProvider && { getPosInSet: function (el, index) { return options.ariaProvider.getPosInSet(el.element, index); }, getSetSize: function (el, index, listLength) { return options.ariaProvider.getSetSize(el.element, index, listLength); }, getRole: options.ariaProvider.getRole ? function (el) { return options.ariaProvider.getRole(el.element); } : undefined, isChecked: options.ariaProvider.isChecked ? function (e) { var _a; return ((_a = options.ariaProvider) === null || _a === void 0 ? void 0 : _a.isChecked)(e.element); } : undefined }, additionalScrollHeight: options.additionalScrollHeight }); } function dfs(node, fn) { fn(node); node.children.forEach(function (child) { return dfs(child, fn); }); } var AsyncDataTree = /** @class */ (function () { function AsyncDataTree(user, container, delegate, renderers, dataSource, options) { if (options === void 0) { 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(function (node) { return 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 = __assign(__assign({}, this.root), { id: null }); } this.nodes.set(null, this.root); this.tree.onDidChangeCollapseState(this._onDidChangeCollapseState, this, this.disposables); } Object.defineProperty(AsyncDataTree.prototype, "onDidChangeFocus", { get: function () { return event_1.Event.map(this.tree.onDidChangeFocus, asTreeEvent); }, enumerable: true, configurable: true }); Object.defineProperty(AsyncDataTree.prototype, "onDidChangeSelection", { get: function () { return event_1.Event.map(this.tree.onDidChangeSelection, asTreeEvent); }, enumerable: true, configurable: true }); Object.defineProperty(AsyncDataTree.prototype, "onDidOpen", { get: function () { return event_1.Event.map(this.tree.onDidOpen, asTreeEvent); }, enumerable: true, configurable: true }); Object.defineProperty(AsyncDataTree.prototype, "onDidFocus", { get: function () { return this.tree.onDidFocus; }, enumerable: true, configurable: true }); Object.defineProperty(AsyncDataTree.prototype, "onDidDispose", { get: function () { return this.tree.onDidDispose; }, enumerable: true, configurable: true }); AsyncDataTree.prototype.createTree = function (user, container, delegate, renderers, options) { var _this = this; var objectTreeDelegate = new abstractTree_1.ComposedTreeDelegate(delegate); var objectTreeRenderers = renderers.map(function (r) { return new AsyncDataTreeRenderer(r, _this.nodeMapper, _this._onDidChangeNodeSlowState.event); }); var objectTreeOptions = asObjectTreeOptions(options) || {}; return new objectTree_1.ObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions); }; AsyncDataTree.prototype.updateOptions = function (options) { if (options === void 0) { options = {}; } this.tree.updateOptions(options); }; // Widget AsyncDataTree.prototype.getHTMLElement = function () { return this.tree.getHTMLElement(); }; Object.defineProperty(AsyncDataTree.prototype, "scrollTop", { get: function () { return this.tree.scrollTop; }, set: function (scrollTop) { this.tree.scrollTop = scrollTop; }, enumerable: true, configurable: true }); AsyncDataTree.prototype.domFocus = function () { this.tree.domFocus(); }; AsyncDataTree.prototype.layout = function (height, width) { this.tree.layout(height, width); }; AsyncDataTree.prototype.style = function (styles) { this.tree.style(styles); }; // Model AsyncDataTree.prototype.getInput = function () { return this.root.element; }; AsyncDataTree.prototype.setInput = function (input, viewState) { return __awaiter(this, void 0, void 0, function () { var viewStateContext; return __generator(this, function (_a) { switch (_a.label) { case 0: this.refreshPromises.forEach(function (promise) { return promise.cancel(); }); this.refreshPromises.clear(); this.root.element = input; viewStateContext = viewState && { viewState: viewState, focus: [], selection: [] }; return [4 /*yield*/, this._updateChildren(input, true, false, viewStateContext)]; case 1: _a.sent(); if (viewStateContext) { this.tree.setFocus(viewStateContext.focus); this.tree.setSelection(viewStateContext.selection); } if (viewState && typeof viewState.scrollTop === 'number') { this.scrollTop = viewState.scrollTop; } return [2 /*return*/]; } }); }); }; AsyncDataTree.prototype._updateChildren = function (element, recursive, rerender, viewStateContext) { if (element === void 0) { element = this.root.element; } if (recursive === void 0) { recursive = true; } if (rerender === void 0) { rerender = false; } return __awaiter(this, void 0, void 0, function () { var node; return __generator(this, function (_a) { switch (_a.label) { case 0: if (typeof this.root.element === 'undefined') { throw new tree_1.TreeError(this.user, 'Tree input not set'); } if (!this.root.refreshPromise) return [3 /*break*/, 3]; return [4 /*yield*/, this.root.refreshPromise]; case 1: _a.sent(); return [4 /*yield*/, event_1.Event.toPromise(this._onDidRender.event)]; case 2: _a.sent(); _a.label = 3; case 3: node = this.getDataNode(element); return [4 /*yield*/, this.refreshAndRenderNode(node, recursive, viewStateContext)]; case 4: _a.sent(); if (rerender) { try { this.tree.rerender(node); } catch (_b) { // missing nodes are fine, this could've resulted from // parallel refresh calls, removing `node` altogether } } return [2 /*return*/]; } }); }); }; // View AsyncDataTree.prototype.rerender = function (element) { if (element === undefined || element === this.root.element) { this.tree.rerender(); return; } var node = this.getDataNode(element); this.tree.rerender(node); }; AsyncDataTree.prototype.collapse = function (element, recursive) { if (recursive === void 0) { recursive = false; } var node = this.getDataNode(element); return this.tree.collapse(node === this.root ? null : node, recursive); }; AsyncDataTree.prototype.expand = function (element, recursive) { if (recursive === void 0) { recursive = false; } return __awaiter(this, void 0, void 0, function () { var node, result; return __generator(this, function (_a) { switch (_a.label) { case 0: if (typeof this.root.element === 'undefined') { throw new tree_1.TreeError(this.user, 'Tree input not set'); } if (!this.root.refreshPromise) return [3 /*break*/, 3]; return [4 /*yield*/, this.root.refreshPromise]; case 1: _a.sent(); return [4 /*yield*/, event_1.Event.toPromise(this._onDidRender.event)]; case 2: _a.sent(); _a.label = 3; case 3: node = this.getDataNode(element); if (this.tree.hasElement(node) && !this.tree.isCollapsible(node)) { return [2 /*return*/, false]; } if (!node.refreshPromise) return [3 /*break*/, 6]; return [4 /*yield*/, this.root.refreshPromise]; case 4: _a.sent(); return [4 /*yield*/, event_1.Event.toPromise(this._onDidRender.event)]; case 5: _a.sent(); _a.label = 6; case 6: if (node !== this.root && !node.refreshPromise && !this.tree.isCollapsed(node)) { return [2 /*return*/, false]; } result = this.tree.expand(node === this.root ? null : node, recursive); if (!node.refreshPromise) return [3 /*break*/, 9]; return [4 /*yield*/, this.root.refreshPromise]; case 7: _a.sent(); return [4 /*yield*/, event_1.Event.toPromise(this._onDidRender.event)]; case 8: _a.sent(); _a.label = 9; case 9: return [2 /*return*/, result]; } }); }); }; AsyncDataTree.prototype.setSelection = function (elements, browserEvent) { var _this = this; var nodes = elements.map(function (e) { return _this.getDataNode(e); }); this.tree.setSelection(nodes, browserEvent); }; AsyncDataTree.prototype.getSelection = function () { var nodes = this.tree.getSelection(); return nodes.map(function (n) { return n.element; }); }; AsyncDataTree.prototype.setFocus = function (elements, browserEvent) { var _this = this; var nodes = elements.map(function (e) { return _this.getDataNode(e); }); this.tree.setFocus(nodes, browserEvent); }; AsyncDataTree.prototype.getFocus = function () { var nodes = this.tree.getFocus(); return nodes.map(function (n) { return n.element; }); }; AsyncDataTree.prototype.reveal = function (element, relativeTop) { this.tree.reveal(this.getDataNode(element), relativeTop); }; // Implementation AsyncDataTree.prototype.getDataNode = function (element) { var 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; }; AsyncDataTree.prototype.refreshAndRenderNode = function (node, recursive, viewStateContext) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.refreshNode(node, recursive, viewStateContext)]; case 1: _a.sent(); this.render(node, viewStateContext); return [2 /*return*/]; } }); }); }; AsyncDataTree.prototype.refreshNode = function (node, recursive, viewStateContext) { return __awaiter(this, void 0, void 0, function () { var result; var _this = this; return __generator(this, function (_a) { this.subTreeRefreshPromises.forEach(function (refreshPromise, refreshNode) { if (!result && intersects(refreshNode, node)) { result = refreshPromise.then(function () { return _this.refreshNode(node, recursive, viewStateContext); }); } }); if (result) { return [2 /*return*/, result]; } return [2 /*return*/, this.doRefreshSubTree(node, recursive, viewStateContext)]; }); }); }; AsyncDataTree.prototype.doRefreshSubTree = function (node, recursive, viewStateContext) { return __awaiter(this, void 0, void 0, function () { var done, childrenToRefresh; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: node.refreshPromise = new Promise(function (c) { return done = c; }); this.subTreeRefreshPromises.set(node, node.refreshPromise); node.refreshPromise.finally(function () { node.refreshPromise = undefined; _this.subTreeRefreshPromises.delete(node); }); _a.label = 1; case 1: _a.trys.push([1, , 4, 5]); return [4 /*yield*/, this.doRefreshNode(node, recursive, viewStateContext)]; case 2: childrenToRefresh = _a.sent(); node.stale = false; return [4 /*yield*/, Promise.all(childrenToRefresh.map(function (child) { return _this.doRefreshSubTree(child, recursive, viewStateContext); }))]; case 3: _a.sent(); return [3 /*break*/, 5]; case 4: done(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; AsyncDataTree.prototype.doRefreshNode = function (node, recursive, viewStateContext) { return __awaiter(this, void 0, void 0, function () { var childrenPromise, slowTimeout_1, children, err_1; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: node.hasChildren = !!this.dataSource.hasChildren(node.element); if (!node.hasChildren) { childrenPromise = Promise.resolve([]); } else { slowTimeout_1 = async_1.timeout(800); slowTimeout_1.then(function () { node.slow = true; _this._onDidChangeNodeSlowState.fire(node); }, function (_) { return null; }); childrenPromise = this.doGetChildren(node) .finally(function () { return slowTimeout_1.cancel(); }); } _a.label = 1; case 1: _a.trys.push([1, 3, 4, 5]); return [4 /*yield*/, childrenPromise]; case 2: children = _a.sent(); return [2 /*return*/, this.setChildren(node, children, recursive, viewStateContext)]; case 3: err_1 = _a.sent(); if (node !== this.root) { this.tree.collapse(node === this.root ? null : node); } if (errors_1.isPromiseCanceledError(err_1)) { return [2 /*return*/, []]; } throw err_1; case 4: if (node.slow) { node.slow = false; this._onDidChangeNodeSlowState.fire(node); } return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; AsyncDataTree.prototype.doGetChildren = function (node) { var _this = this; var result = this.refreshPromises.get(node); if (result) { return result; } result = async_1.createCancelablePromise(function () { return __awaiter(_this, void 0, void 0, function () { var children; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.dataSource.getChildren(node.element)]; case 1: children = _a.sent(); return [2 /*return*/, this.processChildren(children)]; } }); }); }); this.refreshPromises.set(node, result); return result.finally(function () { return _this.refreshPromises.delete(node); }); }; AsyncDataTree.prototype._onDidChangeCollapseState = function (_a) { var node = _a.node, deep = _a.deep; if (!node.collapsed && node.element.stale) { if (deep) { this.collapse(node.element.element); } else { this.refreshAndRenderNode(node.element, false) .catch(errors_1.onUnexpectedError); } } }; AsyncDataTree.prototype.setChildren = function (node, childrenElements, recursive, viewStateContext) { var _a; var _this = this; // perf: if the node was and still is a leaf, avoid all this hassle if (node.children.length === 0 && childrenElements.length === 0) { return []; } var nodesToForget = new Map(); var childrenTreeNodesById = new Map(); for (var _i = 0, _b = node.children; _i < _b.length; _i++) { var child = _b[_i]; nodesToForget.set(child.element, child); if (this.identityProvider) { var collapsed = this.tree.isCollapsed(child); childrenTreeNodesById.set(child.id, { node: child, collapsed: collapsed }); } } var childrenToRefresh = []; var children = childrenElements.map(function (element) { var hasChildren = !!_this.dataSource.hasChildren(element); if (!_this.identityProvider) { var asyncDataTreeNode = createAsyncDataTreeNode({ element: element, parent: node, hasChildren: hasChildren }); if (hasChildren && _this.collapseByDefault && !_this.collapseByDefault(element)) { asyncDataTreeNode.collapsedByDefault = false; childrenToRefresh.push(asyncDataTreeNode); } return asyncDataTreeNode; } var id = _this.identityProvider.getId(element).toString(); var result = childrenTreeNodesById.get(id); if (result) { var 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(function (node) { return dfs(node, function (node) { return _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; } var childAsyncDataTreeNode = createAsyncDataTreeNode({ element: element, parent: node, id: id, hasChildren: 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 (var _c = 0, _d = map_1.values(nodesToForget); _c < _d.length; _c++) { var node_1 = _d[_c]; dfs(node_1, function (node) { return _this.nodes.delete(node.element); }); } for (var _e = 0, children_1 = children; _e < children_1.length; _e++) { var child = children_1[_e]; this.nodes.set(child.element, child); } (_a = node.children).splice.apply(_a, __spreadArrays([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; }; AsyncDataTree.prototype.render = function (node, viewStateContext) { var _this = this; var children = node.children.map(function (node) { return _this.asTreeElement(node, viewStateContext); }); this.tree.setChildren(node === this.root ? null : node, children); if (node !== this.root) { this.tree.setCollapsible(node, node.hasChildren); } this._onDidRender.fire(); }; AsyncDataTree.prototype.asTreeElement = function (node, viewStateContext) { var _this = this; if (node.stale) { return { element: node, collapsible: node.hasChildren, collapsed: true }; } var 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.Iterator.map(iterator_1.Iterator.fromArray(node.children), function (child) { return _this.asTreeElement(child, viewStateContext); }) : [], collapsible: node.hasChildren, collapsed: collapsed }; }; AsyncDataTree.prototype.processChildren = function (children) { if (this.sorter) { children.sort(this.sorter.compare.bind(this.sorter)); } return children; }; AsyncDataTree.prototype.dispose = function () { this.disposables.dispose(); }; return AsyncDataTree; }()); exports.AsyncDataTree = AsyncDataTree; var CompressibleAsyncDataTreeNodeWrapper = /** @class */ (function () { function CompressibleAsyncDataTreeNodeWrapper(node) { this.node = node; } Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "element", { get: function () { return { elements: this.node.element.elements.map(function (e) { return e.element; }), incompressible: this.node.element.incompressible }; }, enumerable: true, configurable: true }); Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "children", { get: function () { return this.node.children.map(function (node) { return new CompressibleAsyncDataTreeNodeWrapper(node); }); }, enumerable: true, configurable: true }); Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "depth", { get: function () { return this.node.depth; }, enumerable: true, configurable: true }); Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "visibleChildrenCount", { get: function () { return this.node.visibleChildrenCount; }, enumerable: true, configurable: true }); Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "visibleChildIndex", { get: function () { return this.node.visibleChildIndex; }, enumerable: true, configurable: true }); Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "collapsible", { get: function () { return this.node.collapsible; }, enumerable: true, configurable: true }); Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "collapsed", { get: function () { return this.node.collapsed; }, enumerable: true, configurable: true }); Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "visible", { get: function () { return this.node.visible; }, enumerable: true, configurable: true }); Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "filterData", { get: function () { return this.node.filterData; }, enumerable: true, configurable: true }); return CompressibleAsyncDataTreeNodeWrapper; }()); var CompressibleAsyncDataTreeRenderer = /** @class */ (function () { function CompressibleAsyncDataTreeRenderer(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; } CompressibleAsyncDataTreeRenderer.prototype.renderTemplate = function (container) { var templateData = this.renderer.renderTemplate(container); return { templateData: templateData }; }; CompressibleAsyncDataTreeRenderer.prototype.renderElement = function (node, index, templateData, height) { this.renderer.renderElement(this.nodeMapper.map(node), index, templateData.templateData, height); }; CompressibleAsyncDataTreeRenderer.prototype.renderCompressedElements = function (node, index, templateData, height) { this.renderer.renderCompressedElements(this.compressibleNodeMapperProvider().map(node), index, templateData.templateData, height); }; CompressibleAsyncDataTreeRenderer.prototype.renderTwistie = function (element, twistieElement) { dom_1.toggleClass(twistieElement, 'codicon-loading', element.slow); return false; }; CompressibleAsyncDataTreeRenderer.prototype.disposeElement = function (node, index, templateData, height) { if (this.renderer.disposeElement) { this.renderer.disposeElement(this.nodeMapper.map(node), index, templateData.templateData, height); } }; CompressibleAsyncDataTreeRenderer.prototype.disposeCompressedElements = function (node, index, templateData, height) { if (this.renderer.disposeCompressedElements) { this.renderer.disposeCompressedElements(this.compressibleNodeMapperProvider().map(node), index, templateData.templateData, height); } }; CompressibleAsyncDataTreeRenderer.prototype.disposeTemplate = function (templateData) { this.renderer.disposeTemplate(templateData.templateData); }; CompressibleAsyncDataTreeRenderer.prototype.dispose = function () { this.renderedNodes.clear(); this.disposables = lifecycle_1.dispose(this.disposables); }; return CompressibleAsyncDataTreeRenderer; }()); function asCompressibleObjectTreeOptions(options) { var objectTreeOptions = options && asObjectTreeOptions(options); return objectTreeOptions && __assign(__assign({}, objectTreeOptions), { keyboardNavigationLabelProvider: objectTreeOptions.keyboardNavigationLabelProvider && __assign(__assign({}, objectTreeOptions.keyboardNavigationLabelProvider), { getCompressedNodeKeyboardNavigationLabel: function (els) { return options.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(els.map(function (e) { return e.element; })); } }) }); } var CompressibleAsyncDataTree = /** @class */ (function (_super) { __extends(CompressibleAsyncDataTree, _super); function CompressibleAsyncDataTree(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, options) { if (options === void 0) { options = {}; } var _this = _super.call(this, user, container, virtualDelegate, renderers, dataSource, options) || this; _this.compressionDelegate = compressionDelegate; _this.compressibleNodeMapper = new tree_1.WeakMapper(function (node) { return new CompressibleAsyncDataTreeNodeWrapper(node); }); _this.filter = options.filter; return _this; } CompressibleAsyncDataTree.prototype.createTree = function (user, container, delegate, renderers, options) { var _this = this; var objectTreeDelegate = new abstractTree_1.ComposedTreeDelegate(delegate); var objectTreeRenderers = renderers.map(function (r) { return new CompressibleAsyncDataTreeRenderer(r, _this.nodeMapper, function () { return _this.compressibleNodeMapper; }, _this._onDidChangeNodeSlowState.event); }); var objectTreeOptions = asCompressibleObjectTreeOptions(options) || {}; return new objectTree_1.CompressibleObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions); }; CompressibleAsyncDataTree.prototype.asTreeElement = function (node, viewStateContext) { return __assign({ incompressible: this.compressionDelegate.isIncompressible(node.element) }, _super.prototype.asTreeElement.call(this, node, viewStateContext)); }; CompressibleAsyncDataTree.prototype.updateOptions = function (options) { if (options === void 0) { options = {}; } this.tree.updateOptions(options); }; CompressibleAsyncDataTree.prototype.render = function (node, viewStateContext) { var _this = this; if (!this.identityProvider) { return _super.prototype.render.call(this, 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. var getId = function (element) { return _this.identityProvider.getId(element).toString(); }; var getUncompressedIds = function (nodes) { var result = new Set(); for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { var node_2 = nodes_1[_i]; var compressedNode = _this.tree.getCompressedTreeNode(node_2 === _this.root ? null : node_2); if (!compressedNode.element) { continue; } for (var _a = 0, _b = compressedNode.element.elements; _a < _b.length; _a++) { var node_3 = _b[_a]; result.add(getId(node_3.element)); } } return result; }; var oldSelection = getUncompressedIds(this.tree.getSelection()); var oldFocus = getUncompressedIds(this.tree.getFocus()); _super.prototype.render.call(this, node, viewStateContext); var selection = this.getSelection(); var didChangeSelection = false; var focus = this.getFocus(); var didChangeFocus = false; var visit = function (node) { var compressedNode = node.element; if (compressedNode) { for (var i = 0; i < compressedNode.elements.length; i++) { var id = getId(compressedNode.elements[i].element); var 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 CompressibleAsyncDataTree.prototype.processChildren = function (children) { var _this = this; if (this.filter) { children = children.filter(function (e) { var result = _this.filter.filter(e, 1 /* Visible */); var 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.prototype.processChildren.call(this, children); }; return CompressibleAsyncDataTree; }(AsyncDataTree)); exports.CompressibleAsyncDataTree = CompressibleAsyncDataTree; function getVisibility(filterResult) { if (typeof filterResult === 'boolean') { return filterResult ? 1 /* Visible */ : 0 /* Hidden */; } else if (indexTreeModel_1.isFilterResult(filterResult)) { return indexTreeModel_1.getVisibleState(filterResult.visibility); } else { return indexTreeModel_1.getVisibleState(filterResult); } } }); define(__m[409/*vs/nls!vs/base/common/keybindingLabels*/], __M([7/*vs/nls*/,8/*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[207/*vs/base/common/keybindingLabels*/], __M([0/*require*/,1/*exports*/,409/*vs/nls!vs/base/common/keybindingLabels*/]), function (require, exports, nls) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ModifierLabelProvider = /** @class */ (function () { function ModifierLabelProvider(mac, windows, linux) { if (linux === void 0) { 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; } ModifierLabelProvider.prototype.toLabel = function (OS, parts, keyLabelProvider) { if (parts.length === 0) { return null; } var result = []; for (var i = 0, len = parts.length; i < len; i++) { var part = parts[i]; var keyLabel = keyLabelProvider(part); if (keyLabel === null) { // this keybinding cannot be expressed... return null; } result[i] = _simpleAsString(part, keyLabel, this.modifierLabels[OS]); } return result.join(' '); }; return ModifierLabelProvider; }()); exports.ModifierLabelProvider = ModifierLabelProvider; /** * A label provider that prints modifiers in a suitable format for displaying in the UI. */ exports.UILabelProvider = new ModifierLabelProvider({ ctrlKey: '⌃', shiftKey: '⇧', altKey: '⌥', metaKey: '⌘', separator: '', }, { ctrlKey: nls.localize(0, null), shiftKey: nls.localize(1, null), altKey: nls.localize(2, null), metaKey: nls.localize(3, null), separator: '+', }, { ctrlKey: nls.localize(4, null), shiftKey: nls.localize(5, null), altKey: nls.localize(6, null), metaKey: nls.localize(7, null), separator: '+', }); /** * A label provider that prints modifiers in a suitable format for ARIA. */ exports.AriaLabelProvider = new ModifierLabelProvider({ ctrlKey: nls.localize(8, null), shiftKey: nls.localize(9, null), altKey: nls.localize(10, null), metaKey: nls.localize(11, null), separator: '+', }, { ctrlKey: nls.localize(12, null), shiftKey: nls.localize(13, null), altKey: nls.localize(14, null), metaKey: nls.localize(15, null), separator: '+', }, { ctrlKey: nls.localize(16, null), shiftKey: nls.localize(17, null), altKey: nls.localize(18, null), metaKey: nls.localize(19, null), separator: '+', }); function _simpleAsString(modifiers, key, labels) { if (key === null) { return ''; } var 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 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[410/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([0/*require*/,1/*exports*/,31/*vs/base/common/objects*/,207/*vs/base/common/keybindingLabels*/,6/*vs/base/browser/dom*/,402/*vs/nls!vs/base/browser/ui/keybindingLabel/keybindingLabel*/,270/*vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel*/]), function (require, exports, objects_1, keybindingLabels_1, dom, nls_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var $ = dom.$; var KeybindingLabel = /** @class */ (function () { function KeybindingLabel(container, os, options) { this.os = os; this.options = options; this.domNode = dom.append(container, $('.monaco-keybinding')); this.didEverRender = false; container.appendChild(this.domNode); } KeybindingLabel.prototype.set = function (keybinding, matches) { if (this.didEverRender && this.keybinding === keybinding && KeybindingLabel.areSame(this.matches, matches)) { return; } this.keybinding = keybinding; this.matches = matches; this.render(); }; KeybindingLabel.prototype.render = function () { dom.clearNode(this.domNode); if (this.keybinding) { var _a = this.keybinding.getParts(), firstPart = _a[0], chordPart = _a[1]; 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.didEverRender = true; }; KeybindingLabel.prototype.renderPart = function (parent, part, match) { var 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); } var keyLabel = part.keyLabel; if (keyLabel) { this.renderKey(parent, keyLabel, Boolean(match === null || match === void 0 ? void 0 : match.keyCode), ''); } }; KeybindingLabel.prototype.renderKey = function (parent, label, highlight, separator) { dom.append(parent, $('span.monaco-keybinding-key' + (highlight ? '.highlight' : ''), undefined, label)); if (separator) { dom.append(parent, $('span.monaco-keybinding-key-separator', undefined, separator)); } }; KeybindingLabel.prototype.renderUnbound = function (parent) { dom.append(parent, $('span.monaco-keybinding-key', undefined, nls_1.localize(0, null))); }; KeybindingLabel.areSame = function (a, b) { if (a === b || (!a && !b)) { return true; } return !!a && !!b && objects_1.equals(a.firstPart, b.firstPart) && objects_1.equals(a.chordPart, b.chordPart); }; return KeybindingLabel; }()); exports.KeybindingLabel = KeybindingLabel; }); define(__m[411/*vs/nls!vs/base/common/severity*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/common/severity", 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[112/*vs/base/common/severity*/], __M([0/*require*/,1/*exports*/,411/*vs/nls!vs/base/common/severity*/,5/*vs/base/common/strings*/]), function (require, exports, nls, 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) { var _error = 'error'; var _warning = 'warning'; var _warn = 'warn'; var _info = 'info'; var _displayStrings = Object.create(null); _displayStrings[Severity.Error] = nls.localize(0, null); _displayStrings[Severity.Warning] = nls.localize(1, null); _displayStrings[Severity.Info] = nls.localize(2, null); /** * 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; })(Severity || (Severity = {})); exports.default = Severity; }); define(__m[412/*vs/nls!vs/base/parts/quickopen/browser/quickOpenModel*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/parts/quickopen/browser/quickOpenModel", 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[155/*vs/base/parts/quickopen/browser/quickOpenModel*/], __M([0/*require*/,1/*exports*/,412/*vs/nls!vs/base/parts/quickopen/browser/quickOpenModel*/,21/*vs/base/common/types*/,139/*vs/base/browser/ui/iconLabel/iconLabel*/,70/*vs/base/browser/ui/actionbar/actionbar*/,133/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,6/*vs/base/browser/dom*/,410/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/,16/*vs/base/common/platform*/,19/*vs/base/common/arrays*/]), function (require, exports, nls, types, iconLabel_1, actionbar_1, highlightedLabel_1, DOM, keybindingLabel_1, platform_1, arrays_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var IDS = 0; var QuickOpenEntry = /** @class */ (function () { function QuickOpenEntry(highlights) { if (highlights === void 0) { highlights = []; } this.id = (IDS++).toString(); this.labelHighlights = highlights; this.descriptionHighlights = []; } /** * A unique identifier for the entry */ QuickOpenEntry.prototype.getId = function () { return this.id; }; /** * The label of the entry to identify it from others in the list */ QuickOpenEntry.prototype.getLabel = function () { return undefined; }; /** * The options for the label to use for this entry */ QuickOpenEntry.prototype.getLabelOptions = function () { return undefined; }; /** * The label of the entry to use when a screen reader wants to read about the entry */ QuickOpenEntry.prototype.getAriaLabel = function () { return arrays_1.coalesce([this.getLabel(), this.getDescription(), this.getDetail()]) .join(', '); }; /** * Detail information about the entry that is optional and can be shown below the label */ QuickOpenEntry.prototype.getDetail = function () { return undefined; }; /** * The icon of the entry to identify it from others in the list */ QuickOpenEntry.prototype.getIcon = function () { return undefined; }; /** * A secondary description that is optional and can be shown right to the label */ QuickOpenEntry.prototype.getDescription = function () { return undefined; }; /** * A tooltip to show when hovering over the entry. */ QuickOpenEntry.prototype.getTooltip = function () { return undefined; }; /** * A tooltip to show when hovering over the description portion of the entry. */ QuickOpenEntry.prototype.getDescriptionTooltip = function () { return undefined; }; /** * An optional keybinding to show for an entry. */ QuickOpenEntry.prototype.getKeybinding = function () { return undefined; }; /** * Allows to reuse the same model while filtering. Hidden entries will not show up in the viewer. */ QuickOpenEntry.prototype.isHidden = function () { return !!this.hidden; }; /** * Allows to set highlight ranges that should show up for the entry label and optionally description if set. */ QuickOpenEntry.prototype.setHighlights = function (labelHighlights, descriptionHighlights, detailHighlights) { this.labelHighlights = labelHighlights; this.descriptionHighlights = descriptionHighlights; this.detailHighlights = detailHighlights; }; /** * Allows to return highlight ranges that should show up for the entry label and description. */ QuickOpenEntry.prototype.getHighlights = function () { return [this.labelHighlights, this.descriptionHighlights, this.detailHighlights]; }; /** * Called when the entry is selected for opening. Returns a boolean value indicating if an action was performed or not. * The mode parameter gives an indication if the element is previewed (using arrow keys) or opened. * * The context parameter provides additional context information how the run was triggered. */ QuickOpenEntry.prototype.run = function (mode, context) { return false; }; return QuickOpenEntry; }()); exports.QuickOpenEntry = QuickOpenEntry; var QuickOpenEntryGroup = /** @class */ (function (_super) { __extends(QuickOpenEntryGroup, _super); function QuickOpenEntryGroup(entry, groupLabel, withBorder) { var _this = _super.call(this) || this; _this.entry = entry; _this.groupLabel = groupLabel; _this.withBorder = withBorder; return _this; } /** * The label of the group or null if none. */ QuickOpenEntryGroup.prototype.getGroupLabel = function () { return this.groupLabel; }; QuickOpenEntryGroup.prototype.setGroupLabel = function (groupLabel) { this.groupLabel = groupLabel; }; /** * Whether to show a border on top of the group entry or not. */ QuickOpenEntryGroup.prototype.showBorder = function () { return !!this.withBorder; }; QuickOpenEntryGroup.prototype.setShowBorder = function (showBorder) { this.withBorder = showBorder; }; QuickOpenEntryGroup.prototype.getLabel = function () { return this.entry ? this.entry.getLabel() : _super.prototype.getLabel.call(this); }; QuickOpenEntryGroup.prototype.getLabelOptions = function () { return this.entry ? this.entry.getLabelOptions() : _super.prototype.getLabelOptions.call(this); }; QuickOpenEntryGroup.prototype.getAriaLabel = function () { return this.entry ? this.entry.getAriaLabel() : _super.prototype.getAriaLabel.call(this); }; QuickOpenEntryGroup.prototype.getDetail = function () { return this.entry ? this.entry.getDetail() : _super.prototype.getDetail.call(this); }; QuickOpenEntryGroup.prototype.getIcon = function () { return this.entry ? this.entry.getIcon() : _super.prototype.getIcon.call(this); }; QuickOpenEntryGroup.prototype.getDescription = function () { return this.entry ? this.entry.getDescription() : _super.prototype.getDescription.call(this); }; QuickOpenEntryGroup.prototype.getHighlights = function () { return this.entry ? this.entry.getHighlights() : _super.prototype.getHighlights.call(this); }; QuickOpenEntryGroup.prototype.isHidden = function () { return this.entry ? this.entry.isHidden() : _super.prototype.isHidden.call(this); }; QuickOpenEntryGroup.prototype.setHighlights = function (labelHighlights, descriptionHighlights, detailHighlights) { this.entry ? this.entry.setHighlights(labelHighlights, descriptionHighlights, detailHighlights) : _super.prototype.setHighlights.call(this, labelHighlights, descriptionHighlights, detailHighlights); }; QuickOpenEntryGroup.prototype.run = function (mode, context) { return this.entry ? this.entry.run(mode, context) : _super.prototype.run.call(this, mode, context); }; return QuickOpenEntryGroup; }(QuickOpenEntry)); exports.QuickOpenEntryGroup = QuickOpenEntryGroup; var NoActionProvider = /** @class */ (function () { function NoActionProvider() { } NoActionProvider.prototype.hasActions = function (tree, element) { return false; }; NoActionProvider.prototype.getActions = function (tree, element) { return null; }; return NoActionProvider; }()); var templateEntry = 'quickOpenEntry'; var templateEntryGroup = 'quickOpenEntryGroup'; var Renderer = /** @class */ (function () { function Renderer(actionProvider, actionRunner) { if (actionProvider === void 0) { actionProvider = new NoActionProvider(); } this.actionProvider = actionProvider; this.actionRunner = actionRunner; } Renderer.prototype.getHeight = function (entry) { if (entry.getDetail()) { return 44; } return 22; }; Renderer.prototype.getTemplateId = function (entry) { if (entry instanceof QuickOpenEntryGroup) { return templateEntryGroup; } return templateEntry; }; Renderer.prototype.renderTemplate = function (templateId, container, styles) { var entryContainer = document.createElement('div'); DOM.addClass(entryContainer, 'sub-content'); container.appendChild(entryContainer); // Entry var row1 = DOM.$('.quick-open-row'); var row2 = DOM.$('.quick-open-row'); var entry = DOM.$('.quick-open-entry', undefined, row1, row2); entryContainer.appendChild(entry); // Icon var icon = document.createElement('span'); row1.appendChild(icon); // Label var label = new iconLabel_1.IconLabel(row1, { supportHighlights: true, supportDescriptionHighlights: true, supportCodicons: true }); // Keybinding var keybindingContainer = document.createElement('span'); row1.appendChild(keybindingContainer); DOM.addClass(keybindingContainer, 'quick-open-entry-keybinding'); var keybinding = new keybindingLabel_1.KeybindingLabel(keybindingContainer, platform_1.OS); // Detail var detailContainer = document.createElement('div'); row2.appendChild(detailContainer); DOM.addClass(detailContainer, 'quick-open-entry-meta'); var detail = new highlightedLabel_1.HighlightedLabel(detailContainer, true); // Entry Group var group; if (templateId === templateEntryGroup) { group = document.createElement('div'); DOM.addClass(group, 'results-group'); container.appendChild(group); } // Actions DOM.addClass(container, 'actions'); var actionBarContainer = document.createElement('div'); DOM.addClass(actionBarContainer, 'primary-action-bar'); container.appendChild(actionBarContainer); var actionBar = new actionbar_1.ActionBar(actionBarContainer, { actionRunner: this.actionRunner }); return { container: container, entry: entry, icon: icon, label: label, detail: detail, keybinding: keybinding, group: group, actionBar: actionBar }; }; Renderer.prototype.renderElement = function (entry, templateId, data, styles) { // Action Bar if (this.actionProvider.hasActions(null, entry)) { DOM.addClass(data.container, 'has-actions'); } else { DOM.removeClass(data.container, 'has-actions'); } data.actionBar.context = entry; // make sure the context is the current element var actions = this.actionProvider.getActions(null, entry); if (data.actionBar.isEmpty() && actions && actions.length > 0) { data.actionBar.push(actions, { icon: true, label: false }); } else if (!data.actionBar.isEmpty() && (!actions || actions.length === 0)) { data.actionBar.clear(); } // Entry group class if (entry instanceof QuickOpenEntryGroup && entry.getGroupLabel()) { DOM.addClass(data.container, 'has-group-label'); } else { DOM.removeClass(data.container, 'has-group-label'); } // Entry group if (entry instanceof QuickOpenEntryGroup) { var group = entry; var groupData = data; // Border if (group.showBorder()) { DOM.addClass(groupData.container, 'results-group-separator'); if (styles.pickerGroupBorder) { groupData.container.style.borderTopColor = styles.pickerGroupBorder.toString(); } } else { DOM.removeClass(groupData.container, 'results-group-separator'); groupData.container.style.borderTopColor = ''; } // Group Label var groupLabel = group.getGroupLabel() || ''; if (groupData.group) { groupData.group.textContent = groupLabel; if (styles.pickerGroupForeground) { groupData.group.style.color = styles.pickerGroupForeground.toString(); } } } // Normal Entry if (entry instanceof QuickOpenEntry) { var _a = entry.getHighlights(), labelHighlights = _a[0], descriptionHighlights = _a[1], detailHighlights = _a[2]; // Icon var iconClass = entry.getIcon() ? ('quick-open-entry-icon ' + entry.getIcon()) : ''; data.icon.className = iconClass; // Label var options = entry.getLabelOptions() || Object.create(null); options.matches = labelHighlights || []; options.title = entry.getTooltip(); options.descriptionTitle = entry.getDescriptionTooltip() || entry.getDescription(); // tooltip over description because it could overflow options.descriptionMatches = descriptionHighlights || []; data.label.setLabel(entry.getLabel() || '', entry.getDescription(), options); // Meta data.detail.set(entry.getDetail(), detailHighlights); // Keybinding data.keybinding.set(entry.getKeybinding()); } }; Renderer.prototype.disposeTemplate = function (templateId, templateData) { templateData.actionBar.dispose(); templateData.actionBar = null; templateData.container = null; templateData.entry = null; templateData.keybinding = null; templateData.detail = null; templateData.group = null; templateData.icon = null; templateData.label.dispose(); templateData.label = null; }; return Renderer; }()); var QuickOpenModel = /** @class */ (function () { function QuickOpenModel(entries, actionProvider) { if (entries === void 0) { entries = []; } if (actionProvider === void 0) { actionProvider = new NoActionProvider(); } this._entries = entries; this._dataSource = this; this._renderer = new Renderer(actionProvider); this._filter = this; this._runner = this; this._accessibilityProvider = this; } Object.defineProperty(QuickOpenModel.prototype, "entries", { get: function () { return this._entries; }, set: function (entries) { this._entries = entries; }, enumerable: true, configurable: true }); Object.defineProperty(QuickOpenModel.prototype, "dataSource", { get: function () { return this._dataSource; }, enumerable: true, configurable: true }); Object.defineProperty(QuickOpenModel.prototype, "renderer", { get: function () { return this._renderer; }, enumerable: true, configurable: true }); Object.defineProperty(QuickOpenModel.prototype, "filter", { get: function () { return this._filter; }, enumerable: true, configurable: true }); Object.defineProperty(QuickOpenModel.prototype, "runner", { get: function () { return this._runner; }, enumerable: true, configurable: true }); Object.defineProperty(QuickOpenModel.prototype, "accessibilityProvider", { get: function () { return this._accessibilityProvider; }, enumerable: true, configurable: true }); QuickOpenModel.prototype.getId = function (entry) { return entry.getId(); }; QuickOpenModel.prototype.getLabel = function (entry) { return types.withUndefinedAsNull(entry.getLabel()); }; QuickOpenModel.prototype.getAriaLabel = function (entry) { var ariaLabel = entry.getAriaLabel(); if (ariaLabel) { return nls.localize(0, null, entry.getAriaLabel()); } return nls.localize(1, null); }; QuickOpenModel.prototype.isVisible = function (entry) { return !entry.isHidden(); }; QuickOpenModel.prototype.run = function (entry, mode, context) { return entry.run(mode, context); }; return QuickOpenModel; }()); exports.QuickOpenModel = QuickOpenModel; }); define(__m[413/*vs/nls!vs/base/parts/quickopen/browser/quickOpenWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/parts/quickopen/browser/quickOpenWidget", 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[414/*vs/base/parts/quickopen/browser/quickOpenWidget*/], __M([0/*require*/,1/*exports*/,413/*vs/nls!vs/base/parts/quickopen/browser/quickOpenWidget*/,16/*vs/base/common/platform*/,21/*vs/base/common/types*/,253/*vs/base/parts/quickopen/browser/quickOpenViewer*/,152/*vs/base/browser/ui/inputbox/inputBox*/,283/*vs/base/parts/tree/browser/treeImpl*/,274/*vs/base/browser/ui/progressbar/progressbar*/,56/*vs/base/browser/keyboardEvent*/,137/*vs/base/parts/tree/browser/treeDefaults*/,6/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,27/*vs/base/common/color*/,31/*vs/base/common/objects*/,45/*vs/base/browser/mouseEvent*/,281/*vs/css!vs/base/parts/quickopen/browser/quickopen*/]), function (require, exports, nls, platform, types, quickOpenViewer_1, inputBox_1, treeImpl_1, progressbar_1, keyboardEvent_1, treeDefaults_1, DOM, lifecycle_1, color_1, objects_1, mouseEvent_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var QuickOpenController = /** @class */ (function (_super) { __extends(QuickOpenController, _super); function QuickOpenController() { return _super !== null && _super.apply(this, arguments) || this; } QuickOpenController.prototype.onContextMenu = function (tree, element, event) { if (platform.isMacintosh) { return this.onLeftClick(tree, element, event); // https://github.com/Microsoft/vscode/issues/1011 } return _super.prototype.onContextMenu.call(this, tree, element, event); }; return QuickOpenController; }(treeDefaults_1.DefaultController)); exports.QuickOpenController = QuickOpenController; var defaultStyles = { background: color_1.Color.fromHex('#1E1E1E'), foreground: color_1.Color.fromHex('#CCCCCC'), pickerGroupForeground: color_1.Color.fromHex('#0097FB'), pickerGroupBorder: color_1.Color.fromHex('#3F3F46'), widgetShadow: color_1.Color.fromHex('#000000'), progressBarBackground: color_1.Color.fromHex('#0E70C0') }; var DEFAULT_INPUT_ARIA_LABEL = nls.localize(0, null); var QuickOpenWidget = /** @class */ (function (_super) { __extends(QuickOpenWidget, _super); function QuickOpenWidget(container, callbacks, options) { var _this = _super.call(this) || this; _this.isDisposed = false; _this.container = container; _this.callbacks = callbacks; _this.options = options; _this.styles = options || Object.create(null); objects_1.mixin(_this.styles, defaultStyles, false); _this.model = null; return _this; } QuickOpenWidget.prototype.getModel = function () { return this.model; }; QuickOpenWidget.prototype.create = function () { var _this = this; // Container this.element = document.createElement('div'); DOM.addClass(this.element, 'monaco-quick-open-widget'); this.container.appendChild(this.element); this._register(DOM.addDisposableListener(this.element, DOM.EventType.CONTEXT_MENU, function (e) { return DOM.EventHelper.stop(e, true); })); // Do this to fix an issue on Mac where the menu goes into the way this._register(DOM.addDisposableListener(this.element, DOM.EventType.FOCUS, function (e) { return _this.gainingFocus(); }, true)); this._register(DOM.addDisposableListener(this.element, DOM.EventType.BLUR, function (e) { return _this.loosingFocus(e); }, true)); this._register(DOM.addDisposableListener(this.element, DOM.EventType.KEY_DOWN, function (e) { var keyboardEvent = new keyboardEvent_1.StandardKeyboardEvent(e); if (keyboardEvent.keyCode === 9 /* Escape */) { DOM.EventHelper.stop(e, true); _this.hide(2 /* CANCELED */); } else if (keyboardEvent.keyCode === 2 /* Tab */ && !keyboardEvent.altKey && !keyboardEvent.ctrlKey && !keyboardEvent.metaKey) { var stops = e.currentTarget.querySelectorAll('input, .monaco-tree, .monaco-tree-row.focused .action-label.icon'); if (keyboardEvent.shiftKey && keyboardEvent.target === stops[0]) { DOM.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!keyboardEvent.shiftKey && keyboardEvent.target === stops[stops.length - 1]) { DOM.EventHelper.stop(e, true); stops[0].focus(); } } })); // Progress Bar this.progressBar = this._register(new progressbar_1.ProgressBar(this.element, { progressBarBackground: this.styles.progressBarBackground })); this.progressBar.hide(); // Input Field this.inputContainer = document.createElement('div'); DOM.addClass(this.inputContainer, 'quick-open-input'); this.element.appendChild(this.inputContainer); this.inputBox = this._register(new inputBox_1.InputBox(this.inputContainer, undefined, { placeholder: this.options.inputPlaceHolder || '', ariaLabel: DEFAULT_INPUT_ARIA_LABEL, inputBackground: this.styles.inputBackground, inputForeground: this.styles.inputForeground, inputBorder: this.styles.inputBorder, inputValidationInfoBackground: this.styles.inputValidationInfoBackground, inputValidationInfoForeground: this.styles.inputValidationInfoForeground, inputValidationInfoBorder: this.styles.inputValidationInfoBorder, inputValidationWarningBackground: this.styles.inputValidationWarningBackground, inputValidationWarningForeground: this.styles.inputValidationWarningForeground, inputValidationWarningBorder: this.styles.inputValidationWarningBorder, inputValidationErrorBackground: this.styles.inputValidationErrorBackground, inputValidationErrorForeground: this.styles.inputValidationErrorForeground, inputValidationErrorBorder: this.styles.inputValidationErrorBorder })); this.inputElement = this.inputBox.inputElement; this.inputElement.setAttribute('role', 'combobox'); this.inputElement.setAttribute('aria-haspopup', 'false'); this.inputElement.setAttribute('aria-autocomplete', 'list'); this._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.INPUT, function (e) { return _this.onType(); })); this._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.KEY_DOWN, function (e) { var keyboardEvent = new keyboardEvent_1.StandardKeyboardEvent(e); var shouldOpenInBackground = _this.shouldOpenInBackground(keyboardEvent); // Do not handle Tab: It is used to navigate between elements without mouse if (keyboardEvent.keyCode === 2 /* Tab */) { return; } // Pass tree navigation keys to the tree but leave focus in input field else if (keyboardEvent.keyCode === 18 /* DownArrow */ || keyboardEvent.keyCode === 16 /* UpArrow */ || keyboardEvent.keyCode === 12 /* PageDown */ || keyboardEvent.keyCode === 11 /* PageUp */) { DOM.EventHelper.stop(e, true); _this.navigateInTree(keyboardEvent.keyCode, keyboardEvent.shiftKey); // Position cursor at the end of input to allow right arrow (open in background) // to function immediately unless the user has made a selection if (_this.inputBox.inputElement.selectionStart === _this.inputBox.inputElement.selectionEnd) { _this.inputBox.inputElement.selectionStart = _this.inputBox.value.length; } } // Select element on Enter or on Arrow-Right if we are at the end of the input else if (keyboardEvent.keyCode === 3 /* Enter */ || shouldOpenInBackground) { DOM.EventHelper.stop(e, true); var focus_1 = _this.tree.getFocus(); if (focus_1) { _this.elementSelected(focus_1, e, shouldOpenInBackground ? 2 /* OPEN_IN_BACKGROUND */ : 1 /* OPEN */); } } })); // Result count for screen readers this.resultCount = document.createElement('div'); DOM.addClass(this.resultCount, 'quick-open-result-count'); this.resultCount.setAttribute('aria-live', 'polite'); this.resultCount.setAttribute('aria-atomic', 'true'); this.element.appendChild(this.resultCount); // Tree this.treeContainer = document.createElement('div'); DOM.addClass(this.treeContainer, 'quick-open-tree'); this.element.appendChild(this.treeContainer); var createTree = this.options.treeCreator || (function (container, config, opts) { return new treeImpl_1.Tree(container, config, opts); }); this.tree = this._register(createTree(this.treeContainer, { dataSource: new quickOpenViewer_1.DataSource(this), controller: new QuickOpenController({ clickBehavior: 1 /* ON_MOUSE_UP */, keyboardSupport: this.options.keyboardSupport }), renderer: (this.renderer = new quickOpenViewer_1.Renderer(this, this.styles)), filter: new quickOpenViewer_1.Filter(this), accessibilityProvider: new quickOpenViewer_1.AccessibilityProvider(this) }, { twistiePixels: 11, indentPixels: 0, alwaysFocused: true, verticalScrollMode: 3 /* Visible */, horizontalScrollMode: 2 /* Hidden */, ariaLabel: nls.localize(1, null), keyboardSupport: this.options.keyboardSupport, preventRootFocus: false })); this.treeElement = this.tree.getHTMLElement(); // Handle Focus and Selection event this._register(this.tree.onDidChangeFocus(function (event) { _this.elementFocused(event.focus, event); })); this._register(this.tree.onDidChangeSelection(function (event) { if (event.selection && event.selection.length > 0) { var mouseEvent = event.payload && event.payload.originalEvent instanceof mouseEvent_1.StandardMouseEvent ? event.payload.originalEvent : undefined; var shouldOpenInBackground = mouseEvent ? _this.shouldOpenInBackground(mouseEvent) : false; _this.elementSelected(event.selection[0], event, shouldOpenInBackground ? 2 /* OPEN_IN_BACKGROUND */ : 1 /* OPEN */); } })); this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, function (e) { var keyboardEvent = new keyboardEvent_1.StandardKeyboardEvent(e); // Only handle when in quick navigation mode if (!_this.quickNavigateConfiguration) { return; } // Support keyboard navigation in quick navigation mode if (keyboardEvent.keyCode === 18 /* DownArrow */ || keyboardEvent.keyCode === 16 /* UpArrow */ || keyboardEvent.keyCode === 12 /* PageDown */ || keyboardEvent.keyCode === 11 /* PageUp */) { DOM.EventHelper.stop(e, true); _this.navigateInTree(keyboardEvent.keyCode); } // Support to open item with Enter still even in quick nav mode else if (keyboardEvent.keyCode === 3 /* Enter */) { DOM.EventHelper.stop(e, true); var focus_2 = _this.tree.getFocus(); if (focus_2) { _this.elementSelected(focus_2, e); } } })); this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_UP, function (e) { var keyboardEvent = new keyboardEvent_1.StandardKeyboardEvent(e); var keyCode = keyboardEvent.keyCode; // Only handle when in quick navigation mode if (!_this.quickNavigateConfiguration) { return; } // Select element when keys are pressed that signal it var quickNavKeys = _this.quickNavigateConfiguration.keybindings; var wasTriggerKeyPressed = quickNavKeys.some(function (k) { var _a = k.getParts(), firstPart = _a[0], chordPart = _a[1]; 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 open } 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) { var focus_3 = _this.tree.getFocus(); if (focus_3) { _this.elementSelected(focus_3, e); } } })); // Support layout if (this.layoutDimensions) { this.layout(this.layoutDimensions); } this.applyStyles(); // Allows focus to switch to next/previous entry after tab into an actionbar item this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, function (e) { var keyboardEvent = new keyboardEvent_1.StandardKeyboardEvent(e); // Only handle when not in quick navigation mode if (_this.quickNavigateConfiguration) { return; } if (keyboardEvent.keyCode === 18 /* DownArrow */ || keyboardEvent.keyCode === 16 /* UpArrow */ || keyboardEvent.keyCode === 12 /* PageDown */ || keyboardEvent.keyCode === 11 /* PageUp */) { DOM.EventHelper.stop(e, true); _this.navigateInTree(keyboardEvent.keyCode, keyboardEvent.shiftKey); _this.treeElement.focus(); } })); return this.element; }; QuickOpenWidget.prototype.style = function (styles) { this.styles = styles; this.applyStyles(); }; QuickOpenWidget.prototype.applyStyles = function () { if (this.element) { var foreground = this.styles.foreground ? this.styles.foreground.toString() : ''; var background = this.styles.background ? this.styles.background.toString() : ''; var borderColor = this.styles.borderColor ? this.styles.borderColor.toString() : ''; var widgetShadow = this.styles.widgetShadow ? this.styles.widgetShadow.toString() : ''; this.element.style.color = foreground; this.element.style.backgroundColor = background; this.element.style.borderColor = borderColor; this.element.style.borderWidth = borderColor ? '1px' : ''; this.element.style.borderStyle = borderColor ? 'solid' : ''; this.element.style.boxShadow = widgetShadow ? "0 5px 8px " + widgetShadow : ''; } if (this.progressBar) { this.progressBar.style({ progressBarBackground: this.styles.progressBarBackground }); } if (this.inputBox) { this.inputBox.style({ inputBackground: this.styles.inputBackground, inputForeground: this.styles.inputForeground, inputBorder: this.styles.inputBorder, inputValidationInfoBackground: this.styles.inputValidationInfoBackground, inputValidationInfoForeground: this.styles.inputValidationInfoForeground, inputValidationInfoBorder: this.styles.inputValidationInfoBorder, inputValidationWarningBackground: this.styles.inputValidationWarningBackground, inputValidationWarningForeground: this.styles.inputValidationWarningForeground, inputValidationWarningBorder: this.styles.inputValidationWarningBorder, inputValidationErrorBackground: this.styles.inputValidationErrorBackground, inputValidationErrorForeground: this.styles.inputValidationErrorForeground, inputValidationErrorBorder: this.styles.inputValidationErrorBorder }); } if (this.tree && !this.options.treeCreator) { this.tree.style(this.styles); } if (this.renderer) { this.renderer.updateStyles(this.styles); } }; QuickOpenWidget.prototype.shouldOpenInBackground = function (e) { // Keyboard if (e instanceof keyboardEvent_1.StandardKeyboardEvent) { if (e.keyCode !== 17 /* RightArrow */) { return false; // only for right arrow } if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return false; // no modifiers allowed } // validate the cursor is at the end of the input and there is no selection, // and if not prevent opening in the background such as the selection can be changed var element = this.inputBox.inputElement; return element.selectionEnd === this.inputBox.value.length && element.selectionStart === element.selectionEnd; } // Mouse return e.middleButton; }; QuickOpenWidget.prototype.onType = function () { var value = this.inputBox.value; // Adjust help text as needed if present if (this.helpText) { if (value) { DOM.hide(this.helpText); } else { DOM.show(this.helpText); } } // Send to callbacks this.callbacks.onType(value); }; QuickOpenWidget.prototype.navigateInTree = function (keyCode, isShift) { var model = this.tree.getInput(); var entries = model ? model.entries : []; var oldFocus = this.tree.getFocus(); // Normal Navigation switch (keyCode) { case 18 /* DownArrow */: this.tree.focusNext(); break; case 16 /* UpArrow */: this.tree.focusPrevious(); break; case 12 /* PageDown */: this.tree.focusNextPage(); break; case 11 /* PageUp */: this.tree.focusPreviousPage(); break; case 2 /* Tab */: if (isShift) { this.tree.focusPrevious(); } else { this.tree.focusNext(); } break; } var newFocus = this.tree.getFocus(); // Support cycle-through navigation if focus did not change if (entries.length > 1 && oldFocus === newFocus) { // Up from no entry or first entry goes down to last if (keyCode === 16 /* UpArrow */ || (keyCode === 2 /* Tab */ && isShift)) { this.tree.focusLast(); } // Down from last entry goes to up to first else if (keyCode === 18 /* DownArrow */ || keyCode === 2 /* Tab */ && !isShift) { this.tree.focusFirst(); } } // Reveal newFocus = this.tree.getFocus(); if (newFocus) { this.tree.reveal(newFocus); } }; QuickOpenWidget.prototype.elementFocused = function (value, event) { if (!value || !this.isVisible()) { return; } // ARIA var arivaActiveDescendant = this.treeElement.getAttribute('aria-activedescendant'); if (arivaActiveDescendant) { this.inputElement.setAttribute('aria-activedescendant', arivaActiveDescendant); } else { this.inputElement.removeAttribute('aria-activedescendant'); } var context = { event: event, keymods: this.extractKeyMods(event), quickNavigateConfiguration: this.quickNavigateConfiguration }; this.model.runner.run(value, 0 /* PREVIEW */, context); }; QuickOpenWidget.prototype.elementSelected = function (value, event, preferredMode) { var hide = true; // Trigger open of element on selection if (this.isVisible()) { var mode = preferredMode || 1 /* OPEN */; var context = { event: event, keymods: this.extractKeyMods(event), quickNavigateConfiguration: this.quickNavigateConfiguration }; hide = this.model.runner.run(value, mode, context); } // Hide if command was run successfully if (hide) { this.hide(0 /* ELEMENT_SELECTED */); } }; QuickOpenWidget.prototype.extractKeyMods = function (event) { return { ctrlCmd: event && (event.ctrlKey || event.metaKey || (event.payload && event.payload.originalEvent && (event.payload.originalEvent.ctrlKey || event.payload.originalEvent.metaKey))), alt: event && (event.altKey || (event.payload && event.payload.originalEvent && event.payload.originalEvent.altKey)) }; }; QuickOpenWidget.prototype.show = function (param, options) { this.visible = true; this.isLoosingFocus = false; this.quickNavigateConfiguration = options ? options.quickNavigateConfiguration : undefined; // Adjust UI for quick navigate mode if (this.quickNavigateConfiguration) { DOM.hide(this.inputContainer); DOM.show(this.element); this.tree.domFocus(); } // Otherwise use normal UI else { DOM.show(this.inputContainer); DOM.show(this.element); this.inputBox.focus(); } // Adjust Help text for IE if (this.helpText) { if (this.quickNavigateConfiguration || types.isString(param)) { DOM.hide(this.helpText); } else { DOM.show(this.helpText); } } // Show based on param if (types.isString(param)) { this.doShowWithPrefix(param); } else { if (options && options.value) { this.restoreLastInput(options.value); } this.doShowWithInput(param, options && options.autoFocus ? options.autoFocus : {}); } // Respect selectAll option if (options && options.inputSelection && !this.quickNavigateConfiguration) { this.inputBox.select(options.inputSelection); } if (this.callbacks.onShow) { this.callbacks.onShow(); } }; QuickOpenWidget.prototype.restoreLastInput = function (lastInput) { this.inputBox.value = lastInput; this.inputBox.select(); this.callbacks.onType(lastInput); }; QuickOpenWidget.prototype.doShowWithPrefix = function (prefix) { this.inputBox.value = prefix; this.callbacks.onType(prefix); }; QuickOpenWidget.prototype.doShowWithInput = function (input, autoFocus) { this.setInput(input, autoFocus); }; QuickOpenWidget.prototype.setInputAndLayout = function (input, autoFocus) { var _this = this; this.treeContainer.style.height = this.getHeight(input) + "px"; this.tree.setInput(null).then(function () { _this.model = input; // ARIA _this.inputElement.setAttribute('aria-haspopup', String(input && input.entries && input.entries.length > 0)); return _this.tree.setInput(input); }).then(function () { // Indicate entries to tree _this.tree.layout(); var entries = input ? input.entries.filter(function (e) { return _this.isElementVisible(input, e); }) : []; _this.updateResultCount(entries.length); // Handle auto focus if (entries.length) { _this.autoFocus(input, entries, autoFocus); } }); }; QuickOpenWidget.prototype.isElementVisible = function (input, e) { if (!input.filter) { return true; } return input.filter.isVisible(e); }; QuickOpenWidget.prototype.autoFocus = function (input, entries, autoFocus) { if (autoFocus === void 0) { autoFocus = {}; } // First check for auto focus of prefix matches if (autoFocus.autoFocusPrefixMatch) { var caseSensitiveMatch = void 0; var caseInsensitiveMatch = void 0; var prefix = autoFocus.autoFocusPrefixMatch; var lowerCasePrefix = prefix.toLowerCase(); for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { var entry = entries_1[_i]; var label = input.dataSource.getLabel(entry) || ''; if (!caseSensitiveMatch && label.indexOf(prefix) === 0) { caseSensitiveMatch = entry; } else if (!caseInsensitiveMatch && label.toLowerCase().indexOf(lowerCasePrefix) === 0) { caseInsensitiveMatch = entry; } if (caseSensitiveMatch && caseInsensitiveMatch) { break; } } var entryToFocus = caseSensitiveMatch || caseInsensitiveMatch; if (entryToFocus) { this.tree.setFocus(entryToFocus); this.tree.reveal(entryToFocus, 0.5); return; } } // Second check for auto focus of first entry if (autoFocus.autoFocusFirstEntry) { this.tree.focusFirst(); this.tree.reveal(this.tree.getFocus()); } // Third check for specific index option else if (typeof autoFocus.autoFocusIndex === 'number') { if (entries.length > autoFocus.autoFocusIndex) { this.tree.focusNth(autoFocus.autoFocusIndex); this.tree.reveal(this.tree.getFocus()); } } // Check for auto focus of second entry else if (autoFocus.autoFocusSecondEntry) { if (entries.length > 1) { this.tree.focusNth(1); } } // Finally check for auto focus of last entry else if (autoFocus.autoFocusLastEntry) { if (entries.length > 1) { this.tree.focusLast(); this.tree.reveal(this.tree.getFocus()); } } }; QuickOpenWidget.prototype.getHeight = function (input) { var _this = this; var renderer = input.renderer; if (!input) { var itemHeight = renderer.getHeight(null); return this.options.minItemsToShow ? this.options.minItemsToShow * itemHeight : 0; } var height = 0; var preferredItemsHeight; if (this.layoutDimensions && this.layoutDimensions.height) { preferredItemsHeight = (this.layoutDimensions.height - 50 /* subtract height of input field (30px) and some spacing (drop shadow) to fit */) * 0.4 /* max 40% of screen */; } if (!preferredItemsHeight || preferredItemsHeight > QuickOpenWidget.MAX_ITEMS_HEIGHT) { preferredItemsHeight = QuickOpenWidget.MAX_ITEMS_HEIGHT; } var entries = input.entries.filter(function (e) { return _this.isElementVisible(input, e); }); var maxEntries = this.options.maxItemsToShow || entries.length; for (var i = 0; i < maxEntries && i < entries.length; i++) { var entryHeight = renderer.getHeight(entries[i]); if (height + entryHeight <= preferredItemsHeight) { height += entryHeight; } else { break; } } return height; }; QuickOpenWidget.prototype.updateResultCount = function (count) { this.resultCount.textContent = nls.localize(2, null, count); }; QuickOpenWidget.prototype.hide = function (reason) { if (!this.isVisible()) { return; } this.visible = false; DOM.hide(this.element); this.element.blur(); // Clear input field and clear tree this.inputBox.value = ''; this.tree.setInput(null); // ARIA this.inputElement.setAttribute('aria-haspopup', 'false'); // Reset Tree Height this.treeContainer.style.height = (this.options.minItemsToShow ? this.options.minItemsToShow * 22 : 0) + "px"; // Clear any running Progress this.progressBar.stop().hide(); // Clear Focus if (this.tree.isDOMFocused()) { this.tree.domBlur(); } else if (this.inputBox.hasFocus()) { this.inputBox.blur(); } // Callbacks if (reason === 0 /* ELEMENT_SELECTED */) { this.callbacks.onOk(); } else { this.callbacks.onCancel(); } if (this.callbacks.onHide) { this.callbacks.onHide(reason); } }; QuickOpenWidget.prototype.setInput = function (input, autoFocus, ariaLabel) { if (!this.isVisible()) { return; } // If the input changes, indicate this to the tree if (!!this.getInput()) { this.onInputChanging(); } // Adapt tree height to entries and apply input this.setInputAndLayout(input, autoFocus); // Apply ARIA if (this.inputBox) { this.inputBox.setAriaLabel(ariaLabel || DEFAULT_INPUT_ARIA_LABEL); } }; QuickOpenWidget.prototype.onInputChanging = function () { var _this = this; if (this.inputChangingTimeoutHandle) { clearTimeout(this.inputChangingTimeoutHandle); this.inputChangingTimeoutHandle = null; } // when the input is changing in quick open, we indicate this as CSS class to the widget // for a certain timeout. this helps reducing some hectic UI updates when input changes quickly DOM.addClass(this.element, 'content-changing'); this.inputChangingTimeoutHandle = setTimeout(function () { DOM.removeClass(_this.element, 'content-changing'); }, 500); }; QuickOpenWidget.prototype.getInput = function () { return this.tree.getInput(); }; QuickOpenWidget.prototype.isVisible = function () { return this.visible; }; QuickOpenWidget.prototype.layout = function (dimension) { this.layoutDimensions = dimension; // Apply to quick open width (height is dynamic by number of items to show) var quickOpenWidth = Math.min(this.layoutDimensions.width * 0.62 /* golden cut */, QuickOpenWidget.MAX_WIDTH); if (this.element) { // quick open this.element.style.width = quickOpenWidth + "px"; this.element.style.marginLeft = "-" + quickOpenWidth / 2 + "px"; // input field this.inputContainer.style.width = quickOpenWidth - 12 + "px"; } }; QuickOpenWidget.prototype.gainingFocus = function () { this.isLoosingFocus = false; }; QuickOpenWidget.prototype.loosingFocus = function (e) { var _this = this; if (!this.isVisible()) { return; } var relatedTarget = e.relatedTarget; if (!this.quickNavigateConfiguration && DOM.isAncestor(relatedTarget, this.element)) { return; // user clicked somewhere into quick open widget, do not close thereby } this.isLoosingFocus = true; setTimeout(function () { if (!_this.isLoosingFocus || _this.isDisposed) { return; } var veto = _this.callbacks.onFocusLost && _this.callbacks.onFocusLost(); if (!veto) { _this.hide(1 /* FOCUS_LOST */); } }, 0); }; QuickOpenWidget.prototype.dispose = function () { _super.prototype.dispose.call(this); this.isDisposed = true; }; QuickOpenWidget.MAX_WIDTH = 600; // Max total width of quick open widget QuickOpenWidget.MAX_ITEMS_HEIGHT = 20 * 22; // Max height of item list below input field return QuickOpenWidget; }(lifecycle_1.Disposable)); exports.QuickOpenWidget = QuickOpenWidget; }); define(__m[415/*vs/nls!vs/editor/browser/controller/coreCommands*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/controller/coreCommands", data); }); define(__m[416/*vs/nls!vs/editor/browser/controller/textAreaHandler*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/controller/textAreaHandler", data); }); define(__m[417/*vs/nls!vs/editor/browser/widget/codeEditorWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/codeEditorWidget", data); }); define(__m[418/*vs/nls!vs/editor/browser/widget/diffEditorWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/diffEditorWidget", data); }); define(__m[419/*vs/nls!vs/editor/browser/widget/diffReview*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/diffReview", data); }); define(__m[420/*vs/nls!vs/editor/browser/widget/inlineDiffMargin*/], __M([7/*vs/nls*/,8/*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[421/*vs/editor/browser/widget/inlineDiffMargin*/], __M([0/*require*/,1/*exports*/,420/*vs/nls!vs/editor/browser/widget/inlineDiffMargin*/,6/*vs/base/browser/dom*/,55/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/]), function (require, exports, nls, dom, actions_1, lifecycle_1, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var InlineDiffMargin = /** @class */ (function (_super) { __extends(InlineDiffMargin, _super); function InlineDiffMargin(_viewZoneId, _marginDomNode, editor, diff, _contextMenuService, _clipboardService) { var _this = _super.call(this) || this; _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 = 'codicon codicon-lightbulb lightbulb-glyph'; _this._diffActions.style.position = 'absolute'; var lineHeight = editor.getOption(49 /* lineHeight */); var 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); var actions = []; // default action actions.push(new actions_1.Action('diff.clipboard.copyDeletedContent', diff.originalEndLineNumber > diff.modifiedStartLineNumber ? nls.localize(0, null) : nls.localize(1, null), undefined, true, function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this._clipboardService.writeText(diff.originalContent.join(lineFeed) + lineFeed)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); })); var currentLineNumberOffset = 0; var copyLineAction = undefined; if (diff.originalEndLineNumber > diff.modifiedStartLineNumber) { copyLineAction = new actions_1.Action('diff.clipboard.copyDeletedLineContent', nls.localize(2, null, diff.originalStartLineNumber), undefined, true, function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this._clipboardService.writeText(diff.originalContent[currentLineNumberOffset])]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }); actions.push(copyLineAction); } var readOnly = editor.getOption(68 /* readOnly */); if (!readOnly) { actions.push(new actions_1.Action('diff.inline.revertChange', nls.localize(3, null), undefined, true, function () { return __awaiter(_this, void 0, void 0, function () { var column, column; return __generator(this, function (_a) { if (diff.modifiedEndLineNumber === 0) { column = editor.getModel().getLineMaxColumn(diff.modifiedStartLineNumber); editor.executeEdits('diffEditor', [ { range: new range_1.Range(diff.modifiedStartLineNumber, column, diff.modifiedStartLineNumber, column), text: lineFeed + diff.originalContent.join(lineFeed) } ]); } else { column = editor.getModel().getLineMaxColumn(diff.modifiedEndLineNumber); editor.executeEdits('diffEditor', [ { range: new range_1.Range(diff.modifiedStartLineNumber, 1, diff.modifiedEndLineNumber, column), text: diff.originalContent.join(lineFeed) } ]); } return [2 /*return*/]; }); }); })); } var showContextMenu = function (x, y) { _this._contextMenuService.showContextMenu({ getAnchor: function () { return { x: x, y: y }; }, getActions: function () { if (copyLineAction) { copyLineAction.label = nls.localize(4, null, diff.originalStartLineNumber + currentLineNumberOffset); } return actions; }, autoSelectFirstItem: true }); }; _this._register(dom.addStandardDisposableListener(_this._diffActions, 'mousedown', function (e) { var _a = dom.getDomNodePagePosition(_this._diffActions), top = _a.top, height = _a.height; var pad = Math.floor(lineHeight / 3); e.preventDefault(); showContextMenu(e.posx, top + height + pad); })); _this._register(editor.onMouseMove(function (e) { if (e.target.type === 8 /* CONTENT_VIEW_ZONE */ || e.target.type === 5 /* GUTTER_VIEW_ZONE */) { var 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(function (e) { if (!e.event.rightButton) { return; } if (e.target.type === 8 /* CONTENT_VIEW_ZONE */ || e.target.type === 5 /* GUTTER_VIEW_ZONE */) { var 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); } } })); return _this; } Object.defineProperty(InlineDiffMargin.prototype, "visibility", { get: function () { return this._visibility; }, set: function (_visibility) { if (this._visibility !== _visibility) { this._visibility = _visibility; if (_visibility) { this._diffActions.style.visibility = 'visible'; } else { this._diffActions.style.visibility = 'hidden'; } } }, enumerable: true, configurable: true }); InlineDiffMargin.prototype._updateLightBulbPosition = function (marginDomNode, y, lineHeight) { var top = dom.getDomNodePagePosition(marginDomNode).top; var offset = y - top; var lineNumberOffset = Math.floor(offset / lineHeight); var newTop = lineNumberOffset * lineHeight; this._diffActions.style.top = newTop + "px"; return lineNumberOffset; }; return InlineDiffMargin; }(lifecycle_1.Disposable)); exports.InlineDiffMargin = InlineDiffMargin; }); define(__m[422/*vs/nls!vs/editor/common/config/commonEditorConfig*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/config/commonEditorConfig", data); }); define(__m[423/*vs/nls!vs/editor/common/config/editorOptions*/], __M([7/*vs/nls*/,8/*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[33/*vs/editor/common/config/editorOptions*/], __M([0/*require*/,1/*exports*/,423/*vs/nls!vs/editor/common/config/editorOptions*/,16/*vs/base/common/platform*/,109/*vs/editor/common/model/wordHelper*/]), function (require, exports, nls, platform, wordHelper_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * @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. */ var ConfigurationChangedEvent = /** @class */ (function () { /** * @internal */ function ConfigurationChangedEvent(values) { this._values = values; } ConfigurationChangedEvent.prototype.hasChanged = function (id) { return this._values[id]; }; return ConfigurationChangedEvent; }()); exports.ConfigurationChangedEvent = ConfigurationChangedEvent; /** * @internal */ var ValidatedEditorOptions = /** @class */ (function () { function ValidatedEditorOptions() { this._values = []; } ValidatedEditorOptions.prototype._read = function (option) { return this._values[option]; }; ValidatedEditorOptions.prototype.get = function (id) { return this._values[id]; }; ValidatedEditorOptions.prototype._write = function (option, value) { this._values[option] = value; }; return ValidatedEditorOptions; }()); exports.ValidatedEditorOptions = ValidatedEditorOptions; /** * @internal */ var BaseEditorOption = /** @class */ (function () { function BaseEditorOption(id, name, defaultValue, schema) { this.id = id; this.name = name; this.defaultValue = defaultValue; this.schema = schema; } BaseEditorOption.prototype.compute = function (env, options, value) { return value; }; return BaseEditorOption; }()); /** * @internal */ var ComputedEditorOption = /** @class */ (function () { function ComputedEditorOption(id, deps) { if (deps === void 0) { deps = null; } this.schema = undefined; this.id = id; this.name = '_never_'; this.defaultValue = undefined; this.deps = deps; } ComputedEditorOption.prototype.validate = function (input) { return this.defaultValue; }; return ComputedEditorOption; }()); var SimpleEditorOption = /** @class */ (function () { function SimpleEditorOption(id, name, defaultValue, schema) { this.id = id; this.name = name; this.defaultValue = defaultValue; this.schema = schema; } SimpleEditorOption.prototype.validate = function (input) { if (typeof input === 'undefined') { return this.defaultValue; } return input; }; SimpleEditorOption.prototype.compute = function (env, options, value) { return value; }; return SimpleEditorOption; }()); var EditorBooleanOption = /** @class */ (function (_super) { __extends(EditorBooleanOption, _super); function EditorBooleanOption(id, name, defaultValue, schema) { if (schema === void 0) { schema = undefined; } var _this = this; if (typeof schema !== 'undefined') { schema.type = 'boolean'; schema.default = defaultValue; } _this = _super.call(this, id, name, defaultValue, schema) || this; return _this; } EditorBooleanOption.boolean = function (value, defaultValue) { if (typeof value === 'undefined') { return defaultValue; } if (value === 'false') { // treat the string 'false' as false return false; } return Boolean(value); }; EditorBooleanOption.prototype.validate = function (input) { return EditorBooleanOption.boolean(input, this.defaultValue); }; return EditorBooleanOption; }(SimpleEditorOption)); var EditorIntOption = /** @class */ (function (_super) { __extends(EditorIntOption, _super); function EditorIntOption(id, name, defaultValue, minimum, maximum, schema) { if (schema === void 0) { schema = undefined; } var _this = this; if (typeof schema !== 'undefined') { schema.type = 'integer'; schema.default = defaultValue; schema.minimum = minimum; schema.maximum = maximum; } _this = _super.call(this, id, name, defaultValue, schema) || this; _this.minimum = minimum; _this.maximum = maximum; return _this; } EditorIntOption.clampedInt = function (value, defaultValue, minimum, maximum) { var r; if (typeof value === 'undefined') { r = defaultValue; } else { r = parseInt(value, 10); if (isNaN(r)) { r = defaultValue; } } r = Math.max(minimum, r); r = Math.min(maximum, r); return r | 0; }; EditorIntOption.prototype.validate = function (input) { return EditorIntOption.clampedInt(input, this.defaultValue, this.minimum, this.maximum); }; return EditorIntOption; }(SimpleEditorOption)); var EditorFloatOption = /** @class */ (function (_super) { __extends(EditorFloatOption, _super); function EditorFloatOption(id, name, defaultValue, validationFn, schema) { var _this = this; if (typeof schema !== 'undefined') { schema.type = 'number'; schema.default = defaultValue; } _this = _super.call(this, id, name, defaultValue, schema) || this; _this.validationFn = validationFn; return _this; } EditorFloatOption.clamp = function (n, min, max) { if (n < min) { return min; } if (n > max) { return max; } return n; }; EditorFloatOption.float = function (value, defaultValue) { if (typeof value === 'number') { return value; } if (typeof value === 'undefined') { return defaultValue; } var r = parseFloat(value); return (isNaN(r) ? defaultValue : r); }; EditorFloatOption.prototype.validate = function (input) { return this.validationFn(EditorFloatOption.float(input, this.defaultValue)); }; return EditorFloatOption; }(SimpleEditorOption)); var EditorStringOption = /** @class */ (function (_super) { __extends(EditorStringOption, _super); function EditorStringOption(id, name, defaultValue, schema) { if (schema === void 0) { schema = undefined; } var _this = this; if (typeof schema !== 'undefined') { schema.type = 'string'; schema.default = defaultValue; } _this = _super.call(this, id, name, defaultValue, schema) || this; return _this; } EditorStringOption.string = function (value, defaultValue) { if (typeof value !== 'string') { return defaultValue; } return value; }; EditorStringOption.prototype.validate = function (input) { return EditorStringOption.string(input, this.defaultValue); }; return EditorStringOption; }(SimpleEditorOption)); var EditorStringEnumOption = /** @class */ (function (_super) { __extends(EditorStringEnumOption, _super); function EditorStringEnumOption(id, name, defaultValue, allowedValues, schema) { if (schema === void 0) { schema = undefined; } var _this = this; if (typeof schema !== 'undefined') { schema.type = 'string'; schema.enum = allowedValues; schema.default = defaultValue; } _this = _super.call(this, id, name, defaultValue, schema) || this; _this._allowedValues = allowedValues; return _this; } EditorStringEnumOption.stringSet = function (value, defaultValue, allowedValues) { if (typeof value !== 'string') { return defaultValue; } if (allowedValues.indexOf(value) === -1) { return defaultValue; } return value; }; EditorStringEnumOption.prototype.validate = function (input) { return EditorStringEnumOption.stringSet(input, this.defaultValue, this._allowedValues); }; return EditorStringEnumOption; }(SimpleEditorOption)); var EditorEnumOption = /** @class */ (function (_super) { __extends(EditorEnumOption, _super); function EditorEnumOption(id, name, defaultValue, defaultStringValue, allowedValues, convert, schema) { if (schema === void 0) { schema = undefined; } var _this = this; if (typeof schema !== 'undefined') { schema.type = 'string'; schema.enum = allowedValues; schema.default = defaultStringValue; } _this = _super.call(this, id, name, defaultValue, schema) || this; _this._allowedValues = allowedValues; _this._convert = convert; return _this; } EditorEnumOption.prototype.validate = function (input) { if (typeof input !== 'string') { return this.defaultValue; } if (this._allowedValues.indexOf(input) === -1) { return this.defaultValue; } return this._convert(input); }; return EditorEnumOption; }(BaseEditorOption)); //#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 var EditorAccessibilitySupport = /** @class */ (function (_super) { __extends(EditorAccessibilitySupport, _super); function EditorAccessibilitySupport() { return _super.call(this, 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) }) || this; } EditorAccessibilitySupport.prototype.validate = function (input) { switch (input) { case 'auto': return 0 /* Unknown */; case 'off': return 1 /* Disabled */; case 'on': return 2 /* Enabled */; } return this.defaultValue; }; EditorAccessibilitySupport.prototype.compute = function (env, options, value) { if (value === 0 /* Unknown */) { // The editor reads the `accessibilitySupport` from the environment return env.accessibilitySupport; } return value; }; return EditorAccessibilitySupport; }(BaseEditorOption)); var EditorComments = /** @class */ (function (_super) { __extends(EditorComments, _super); function EditorComments() { var _this = this; var defaults = { insertSpace: true, }; _this = _super.call(this, 13 /* comments */, 'comments', defaults, { 'editor.comments.insertSpace': { type: 'boolean', default: defaults.insertSpace, description: nls.localize(4, null) }, }) || this; return _this; } EditorComments.prototype.validate = function (_input) { if (typeof _input !== 'object') { return this.defaultValue; } var input = _input; return { insertSpace: EditorBooleanOption.boolean(input.insertSpace, this.defaultValue.insertSpace), }; }; return EditorComments; }(BaseEditorOption)); 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 var EditorClassName = /** @class */ (function (_super) { __extends(EditorClassName, _super); function EditorClassName() { return _super.call(this, 104 /* editorClassName */, [55 /* mouseStyle */, 26 /* extraEditorClassName */]) || this; } EditorClassName.prototype.compute = function (env, options, _) { var className = 'monaco-editor'; if (options.get(26 /* extraEditorClassName */)) { className += ' ' + options.get(26 /* extraEditorClassName */); } if (env.extraEditorClassName) { className += ' ' + env.extraEditorClassName; } if (options.get(55 /* mouseStyle */) === 'default') { className += ' mouse-default'; } else if (options.get(55 /* mouseStyle */) === 'copy') { className += ' mouse-copy'; } if (options.get(85 /* showUnused */)) { className += ' showUnused'; } return className; }; return EditorClassName; }(ComputedEditorOption)); //#endregion //#region emptySelectionClipboard var EditorEmptySelectionClipboard = /** @class */ (function (_super) { __extends(EditorEmptySelectionClipboard, _super); function EditorEmptySelectionClipboard() { return _super.call(this, 25 /* emptySelectionClipboard */, 'emptySelectionClipboard', true, { description: nls.localize(5, null) }) || this; } EditorEmptySelectionClipboard.prototype.compute = function (env, options, value) { return value && env.emptySelectionClipboard; }; return EditorEmptySelectionClipboard; }(EditorBooleanOption)); var EditorFind = /** @class */ (function (_super) { __extends(EditorFind, _super); function EditorFind() { var _this = this; var defaults = { seedSearchStringFromSelection: true, autoFindInSelection: 'never', globalFindClipboard: false, addExtraSpaceOnTop: true }; _this = _super.call(this, 28 /* find */, 'find', defaults, { 'editor.find.seedSearchStringFromSelection': { type: 'boolean', default: defaults.seedSearchStringFromSelection, description: nls.localize(6, null) }, 'editor.find.autoFindInSelection': { type: 'string', enum: ['never', 'always', 'multiline'], default: defaults.autoFindInSelection, enumDescriptions: [ nls.localize(7, null), nls.localize(8, null), nls.localize(9, null) ], description: nls.localize(10, null) }, 'editor.find.globalFindClipboard': { type: 'boolean', default: defaults.globalFindClipboard, description: nls.localize(11, null), included: platform.isMacintosh }, 'editor.find.addExtraSpaceOnTop': { type: 'boolean', default: defaults.addExtraSpaceOnTop, description: nls.localize(12, null) } }) || this; return _this; } EditorFind.prototype.validate = function (_input) { if (typeof _input !== 'object') { return this.defaultValue; } var input = _input; return { seedSearchStringFromSelection: EditorBooleanOption.boolean(input.seedSearchStringFromSelection, this.defaultValue.seedSearchStringFromSelection), autoFindInSelection: typeof _input.autoFindInSelection === 'boolean' ? (_input.autoFindInSelection ? 'always' : 'never') : EditorStringEnumOption.stringSet(input.autoFindInSelection, this.defaultValue.autoFindInSelection, ['never', 'always', 'multiline']), globalFindClipboard: EditorBooleanOption.boolean(input.globalFindClipboard, this.defaultValue.globalFindClipboard), addExtraSpaceOnTop: EditorBooleanOption.boolean(input.addExtraSpaceOnTop, this.defaultValue.addExtraSpaceOnTop) }; }; return EditorFind; }(BaseEditorOption)); //#endregion //#region fontLigatures /** * @internal */ var EditorFontLigatures = /** @class */ (function (_super) { __extends(EditorFontLigatures, _super); function EditorFontLigatures() { return _super.call(this, 35 /* fontLigatures */, 'fontLigatures', EditorFontLigatures.OFF, { anyOf: [ { type: 'boolean', description: nls.localize(13, null), }, { type: 'string', description: nls.localize(14, null) } ], description: nls.localize(15, null), default: false }) || this; } EditorFontLigatures.prototype.validate = function (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; }; EditorFontLigatures.OFF = '"liga" off, "calt" off'; EditorFontLigatures.ON = '"liga" on, "calt" on'; return EditorFontLigatures; }(BaseEditorOption)); exports.EditorFontLigatures = EditorFontLigatures; //#endregion //#region fontInfo var EditorFontInfo = /** @class */ (function (_super) { __extends(EditorFontInfo, _super); function EditorFontInfo() { return _super.call(this, 34 /* fontInfo */) || this; } EditorFontInfo.prototype.compute = function (env, options, _) { return env.fontInfo; }; return EditorFontInfo; }(ComputedEditorOption)); //#endregion //#region fontSize var EditorFontSize = /** @class */ (function (_super) { __extends(EditorFontSize, _super); function EditorFontSize() { return _super.call(this, 36 /* fontSize */, 'fontSize', exports.EDITOR_FONT_DEFAULTS.fontSize, { type: 'number', minimum: 6, maximum: 100, default: exports.EDITOR_FONT_DEFAULTS.fontSize, description: nls.localize(16, null) }) || this; } EditorFontSize.prototype.validate = function (input) { var r = EditorFloatOption.float(input, this.defaultValue); if (r === 0) { return exports.EDITOR_FONT_DEFAULTS.fontSize; } return EditorFloatOption.clamp(r, 6, 100); }; EditorFontSize.prototype.compute = function (env, options, value) { // The final fontSize respects the editor zoom level. // So take the result from env.fontInfo return env.fontInfo.fontSize; }; return EditorFontSize; }(SimpleEditorOption)); var EditorGoToLocation = /** @class */ (function (_super) { __extends(EditorGoToLocation, _super); function EditorGoToLocation() { var _this = this; var 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: '', }; var jsonSubset = { type: 'string', enum: ['peek', 'gotoAndPeek', 'goto'], default: defaults.multiple, enumDescriptions: [ nls.localize(17, null), nls.localize(18, null), nls.localize(19, null) ] }; _this = _super.call(this, 41 /* gotoLocation */, 'gotoLocation', defaults, { 'editor.gotoLocation.multiple': { deprecationMessage: nls.localize(20, null), }, 'editor.gotoLocation.multipleDefinitions': __assign({ description: nls.localize(21, null) }, jsonSubset), 'editor.gotoLocation.multipleTypeDefinitions': __assign({ description: nls.localize(22, null) }, jsonSubset), 'editor.gotoLocation.multipleDeclarations': __assign({ description: nls.localize(23, null) }, jsonSubset), 'editor.gotoLocation.multipleImplementations': __assign({ description: nls.localize(24, null) }, jsonSubset), 'editor.gotoLocation.multipleReferences': __assign({ description: nls.localize(25, null) }, jsonSubset), 'editor.gotoLocation.alternativeDefinitionCommand': { type: 'string', default: defaults.alternativeDefinitionCommand, description: nls.localize(26, null) }, 'editor.gotoLocation.alternativeTypeDefinitionCommand': { type: 'string', default: defaults.alternativeTypeDefinitionCommand, description: nls.localize(27, null) }, 'editor.gotoLocation.alternativeDeclarationCommand': { type: 'string', default: defaults.alternativeDeclarationCommand, description: nls.localize(28, null) }, 'editor.gotoLocation.alternativeImplementationCommand': { type: 'string', default: defaults.alternativeImplementationCommand, description: nls.localize(29, null) }, 'editor.gotoLocation.alternativeReferenceCommand': { type: 'string', default: defaults.alternativeReferenceCommand, description: nls.localize(30, null) }, }) || this; return _this; } EditorGoToLocation.prototype.validate = function (_input) { var _a, _b, _c, _d, _e; if (typeof _input !== 'object') { return this.defaultValue; } var input = _input; return { multiple: EditorStringEnumOption.stringSet(input.multiple, this.defaultValue.multiple, ['peek', 'gotoAndPeek', 'goto']), multipleDefinitions: (_a = input.multipleDefinitions) !== null && _a !== void 0 ? _a : EditorStringEnumOption.stringSet(input.multipleDefinitions, 'peek', ['peek', 'gotoAndPeek', 'goto']), multipleTypeDefinitions: (_b = input.multipleTypeDefinitions) !== null && _b !== void 0 ? _b : EditorStringEnumOption.stringSet(input.multipleTypeDefinitions, 'peek', ['peek', 'gotoAndPeek', 'goto']), multipleDeclarations: (_c = input.multipleDeclarations) !== null && _c !== void 0 ? _c : EditorStringEnumOption.stringSet(input.multipleDeclarations, 'peek', ['peek', 'gotoAndPeek', 'goto']), multipleImplementations: (_d = input.multipleImplementations) !== null && _d !== void 0 ? _d : EditorStringEnumOption.stringSet(input.multipleImplementations, 'peek', ['peek', 'gotoAndPeek', 'goto']), multipleReferences: (_e = input.multipleReferences) !== null && _e !== void 0 ? _e : EditorStringEnumOption.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), }; }; return EditorGoToLocation; }(BaseEditorOption)); var EditorHover = /** @class */ (function (_super) { __extends(EditorHover, _super); function EditorHover() { var _this = this; var defaults = { enabled: true, delay: 300, sticky: true }; _this = _super.call(this, 44 /* hover */, 'hover', defaults, { 'editor.hover.enabled': { type: 'boolean', default: defaults.enabled, description: nls.localize(31, null) }, 'editor.hover.delay': { type: 'number', default: defaults.delay, description: nls.localize(32, null) }, 'editor.hover.sticky': { type: 'boolean', default: defaults.sticky, description: nls.localize(33, null) }, }) || this; return _this; } EditorHover.prototype.validate = function (_input) { if (typeof _input !== 'object') { return this.defaultValue; } var input = _input; return { enabled: EditorBooleanOption.boolean(input.enabled, this.defaultValue.enabled), delay: EditorIntOption.clampedInt(input.delay, this.defaultValue.delay, 0, 10000), sticky: EditorBooleanOption.boolean(input.sticky, this.defaultValue.sticky) }; }; return EditorHover; }(BaseEditorOption)); /** * @internal */ var EditorLayoutInfoComputer = /** @class */ (function (_super) { __extends(EditorLayoutInfoComputer, _super); function EditorLayoutInfoComputer() { return _super.call(this, 107 /* layoutInfo */, [40 /* glyphMargin */, 48 /* lineDecorationsWidth */, 30 /* folding */, 54 /* minimap */, 78 /* scrollbar */, 50 /* lineNumbers */]) || this; } EditorLayoutInfoComputer.prototype.compute = function (env, options, _) { return EditorLayoutInfoComputer.computeLayout(options, { outerWidth: env.outerWidth, outerHeight: env.outerHeight, lineHeight: env.fontInfo.lineHeight, lineNumbersDigitCount: env.lineNumbersDigitCount, typicalHalfwidthCharacterWidth: env.fontInfo.typicalHalfwidthCharacterWidth, maxDigitWidth: env.fontInfo.maxDigitWidth, pixelRatio: env.pixelRatio }); }; EditorLayoutInfoComputer.computeLayout = function (options, env) { var outerWidth = env.outerWidth | 0; var outerHeight = env.outerHeight | 0; var lineHeight = env.lineHeight | 0; var lineNumbersDigitCount = env.lineNumbersDigitCount | 0; var typicalHalfwidthCharacterWidth = env.typicalHalfwidthCharacterWidth; var maxDigitWidth = env.maxDigitWidth; var pixelRatio = env.pixelRatio; var showGlyphMargin = options.get(40 /* glyphMargin */); var showLineNumbers = (options.get(50 /* lineNumbers */).renderType !== 0 /* Off */); var lineNumbersMinChars = options.get(51 /* lineNumbersMinChars */) | 0; var minimap = options.get(54 /* minimap */); var minimapEnabled = minimap.enabled; var minimapSide = minimap.side; var minimapRenderCharacters = minimap.renderCharacters; var minimapScale = (pixelRatio >= 2 ? Math.round(minimap.scale * 2) : minimap.scale); var minimapMaxColumn = minimap.maxColumn | 0; var scrollbar = options.get(78 /* scrollbar */); var verticalScrollbarWidth = scrollbar.verticalScrollbarSize | 0; var verticalScrollbarHasArrows = scrollbar.verticalHasArrows; var scrollbarArrowSize = scrollbar.arrowSize | 0; var horizontalScrollbarHeight = scrollbar.horizontalScrollbarSize | 0; var rawLineDecorationsWidth = options.get(48 /* lineDecorationsWidth */); var folding = options.get(30 /* folding */); var lineDecorationsWidth; if (typeof rawLineDecorationsWidth === 'string' && /^\d+(\.\d+)?ch$/.test(rawLineDecorationsWidth)) { var 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; } var lineNumbersWidth = 0; if (showLineNumbers) { var digitCount = Math.max(lineNumbersDigitCount, lineNumbersMinChars); lineNumbersWidth = Math.round(digitCount * maxDigitWidth); } var glyphMarginWidth = 0; if (showGlyphMargin) { glyphMarginWidth = lineHeight; } var glyphMarginLeft = 0; var lineNumbersLeft = glyphMarginLeft + glyphMarginWidth; var decorationsLeft = lineNumbersLeft + lineNumbersWidth; var contentLeft = decorationsLeft + lineDecorationsWidth; var remainingWidth = outerWidth - glyphMarginWidth - lineNumbersWidth - lineDecorationsWidth; var renderMinimap; var minimapLeft; var minimapWidth; var contentWidth; if (!minimapEnabled) { minimapLeft = 0; minimapWidth = 0; renderMinimap = 0 /* None */; contentWidth = remainingWidth; } else { // The minimapScale is also the pixel width of each character. Adjust // for the pixel ratio of the screen. var minimapCharWidth = minimapScale / pixelRatio; renderMinimap = minimapRenderCharacters ? 1 /* Text */ : 2 /* Blocks */; // 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) minimapWidth = Math.max(0, Math.floor(((remainingWidth - verticalScrollbarWidth - 2) * minimapCharWidth) / (typicalHalfwidthCharacterWidth + minimapCharWidth))) + exports.MINIMAP_GUTTER_WIDTH; var minimapColumns = minimapWidth / minimapCharWidth; if (minimapColumns > minimapMaxColumn) { minimapWidth = Math.floor(minimapMaxColumn * minimapCharWidth); } contentWidth = remainingWidth - minimapWidth; if (minimapSide === 'left') { minimapLeft = 0; glyphMarginLeft += minimapWidth; lineNumbersLeft += minimapWidth; decorationsLeft += minimapWidth; contentLeft += minimapWidth; } else { minimapLeft = outerWidth - minimapWidth - verticalScrollbarWidth; } } // (leaving 2px for the cursor to have space after the last character) var viewportColumn = Math.max(1, Math.floor((contentWidth - verticalScrollbarWidth - 2) / typicalHalfwidthCharacterWidth)); var verticalArrowSize = (verticalScrollbarHasArrows ? scrollbarArrowSize : 0); return { width: outerWidth, height: outerHeight, glyphMarginLeft: glyphMarginLeft, glyphMarginWidth: glyphMarginWidth, lineNumbersLeft: lineNumbersLeft, lineNumbersWidth: lineNumbersWidth, decorationsLeft: decorationsLeft, decorationsWidth: lineDecorationsWidth, contentLeft: contentLeft, contentWidth: contentWidth, renderMinimap: renderMinimap, minimapLeft: minimapLeft, minimapWidth: minimapWidth, viewportColumn: viewportColumn, verticalScrollbarWidth: verticalScrollbarWidth, horizontalScrollbarHeight: horizontalScrollbarHeight, overviewRuler: { top: verticalArrowSize, width: verticalScrollbarWidth, height: (outerHeight - 2 * verticalArrowSize), right: 0 } }; }; return EditorLayoutInfoComputer; }(ComputedEditorOption)); exports.EditorLayoutInfoComputer = EditorLayoutInfoComputer; var EditorLightbulb = /** @class */ (function (_super) { __extends(EditorLightbulb, _super); function EditorLightbulb() { var _this = this; var defaults = { enabled: true }; _this = _super.call(this, 47 /* lightbulb */, 'lightbulb', defaults, { 'editor.lightbulb.enabled': { type: 'boolean', default: defaults.enabled, description: nls.localize(34, null) }, }) || this; return _this; } EditorLightbulb.prototype.validate = function (_input) { if (typeof _input !== 'object') { return this.defaultValue; } var input = _input; return { enabled: EditorBooleanOption.boolean(input.enabled, this.defaultValue.enabled) }; }; return EditorLightbulb; }(BaseEditorOption)); //#endregion //#region lineHeight var EditorLineHeight = /** @class */ (function (_super) { __extends(EditorLineHeight, _super); function EditorLineHeight() { return _super.call(this, 49 /* lineHeight */, 'lineHeight', exports.EDITOR_FONT_DEFAULTS.lineHeight, 0, 150, { description: nls.localize(35, null) }) || this; } EditorLineHeight.prototype.compute = function (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; }; return EditorLineHeight; }(EditorIntOption)); var EditorMinimap = /** @class */ (function (_super) { __extends(EditorMinimap, _super); function EditorMinimap() { var _this = this; var defaults = { enabled: true, side: 'right', showSlider: 'mouseover', renderCharacters: true, maxColumn: 120, scale: 1, }; _this = _super.call(this, 54 /* minimap */, 'minimap', defaults, { 'editor.minimap.enabled': { type: 'boolean', default: defaults.enabled, description: nls.localize(36, null) }, 'editor.minimap.side': { type: 'string', enum: ['left', 'right'], default: defaults.side, description: nls.localize(37, null) }, 'editor.minimap.showSlider': { type: 'string', enum: ['always', 'mouseover'], default: defaults.showSlider, description: nls.localize(38, null) }, 'editor.minimap.scale': { type: 'number', default: defaults.scale, minimum: 1, maximum: 3, description: nls.localize(39, null) }, 'editor.minimap.renderCharacters': { type: 'boolean', default: defaults.renderCharacters, description: nls.localize(40, null) }, 'editor.minimap.maxColumn': { type: 'number', default: defaults.maxColumn, description: nls.localize(41, null) }, }) || this; return _this; } EditorMinimap.prototype.validate = function (_input) { if (typeof _input !== 'object') { return this.defaultValue; } var input = _input; return { enabled: EditorBooleanOption.boolean(input.enabled, this.defaultValue.enabled), side: EditorStringEnumOption.stringSet(input.side, this.defaultValue.side, ['right', 'left']), showSlider: EditorStringEnumOption.stringSet(input.showSlider, this.defaultValue.showSlider, ['always', 'mouseover']), renderCharacters: EditorBooleanOption.boolean(input.renderCharacters, this.defaultValue.renderCharacters), scale: EditorIntOption.clampedInt(input.scale, 1, 1, 3), maxColumn: EditorIntOption.clampedInt(input.maxColumn, this.defaultValue.maxColumn, 1, 10000), }; }; return EditorMinimap; }(BaseEditorOption)); //#endregion //#region multiCursorModifier function _multiCursorModifierFromString(multiCursorModifier) { if (multiCursorModifier === 'ctrlCmd') { return (platform.isMacintosh ? 'metaKey' : 'ctrlKey'); } return 'altKey'; } var EditorParameterHints = /** @class */ (function (_super) { __extends(EditorParameterHints, _super); function EditorParameterHints() { var _this = this; var defaults = { enabled: true, cycle: false }; _this = _super.call(this, 64 /* parameterHints */, 'parameterHints', defaults, { 'editor.parameterHints.enabled': { type: 'boolean', default: defaults.enabled, description: nls.localize(42, null) }, 'editor.parameterHints.cycle': { type: 'boolean', default: defaults.cycle, description: nls.localize(43, null) }, }) || this; return _this; } EditorParameterHints.prototype.validate = function (_input) { if (typeof _input !== 'object') { return this.defaultValue; } var input = _input; return { enabled: EditorBooleanOption.boolean(input.enabled, this.defaultValue.enabled), cycle: EditorBooleanOption.boolean(input.cycle, this.defaultValue.cycle) }; }; return EditorParameterHints; }(BaseEditorOption)); //#endregion //#region pixelRatio var EditorPixelRatio = /** @class */ (function (_super) { __extends(EditorPixelRatio, _super); function EditorPixelRatio() { return _super.call(this, 105 /* pixelRatio */) || this; } EditorPixelRatio.prototype.compute = function (env, options, _) { return env.pixelRatio; }; return EditorPixelRatio; }(ComputedEditorOption)); var EditorQuickSuggestions = /** @class */ (function (_super) { __extends(EditorQuickSuggestions, _super); function EditorQuickSuggestions() { var _this = this; var defaults = { other: true, comments: false, strings: false }; _this = _super.call(this, 66 /* quickSuggestions */, 'quickSuggestions', defaults, { anyOf: [ { type: 'boolean', }, { type: 'object', properties: { strings: { type: 'boolean', default: defaults.strings, description: nls.localize(44, null) }, comments: { type: 'boolean', default: defaults.comments, description: nls.localize(45, null) }, other: { type: 'boolean', default: defaults.other, description: nls.localize(46, null) }, } } ], default: defaults, description: nls.localize(47, null) }) || this; _this.defaultValue = defaults; return _this; } EditorQuickSuggestions.prototype.validate = function (_input) { if (typeof _input === 'boolean') { return _input; } if (typeof _input === 'object') { var input = _input; var opts = { other: EditorBooleanOption.boolean(input.other, this.defaultValue.other), comments: EditorBooleanOption.boolean(input.comments, this.defaultValue.comments), strings: EditorBooleanOption.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; }; return EditorQuickSuggestions; }(BaseEditorOption)); var EditorRenderLineNumbersOption = /** @class */ (function (_super) { __extends(EditorRenderLineNumbersOption, _super); function EditorRenderLineNumbersOption() { return _super.call(this, 50 /* lineNumbers */, 'lineNumbers', { renderType: 1 /* On */, renderFn: null }, { type: 'string', enum: ['off', 'on', 'relative', 'interval'], enumDescriptions: [ nls.localize(48, null), nls.localize(49, null), nls.localize(50, null), nls.localize(51, null) ], default: 'on', description: nls.localize(52, null) }) || this; } EditorRenderLineNumbersOption.prototype.validate = function (lineNumbers) { var renderType = this.defaultValue.renderType; var 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: renderType, renderFn: renderFn }; }; return EditorRenderLineNumbersOption; }(BaseEditorOption)); //#endregion //#region renderValidationDecorations /** * @internal */ function filterValidationDecorations(options) { var renderValidationDecorations = options.get(73 /* renderValidationDecorations */); if (renderValidationDecorations === 'editable') { return options.get(68 /* readOnly */); } return renderValidationDecorations === 'on' ? false : true; } exports.filterValidationDecorations = filterValidationDecorations; //#endregion //#region rulers var EditorRulers = /** @class */ (function (_super) { __extends(EditorRulers, _super); function EditorRulers() { var _this = this; var defaults = []; _this = _super.call(this, 77 /* rulers */, 'rulers', defaults, { type: 'array', items: { type: 'number' }, default: defaults, description: nls.localize(53, null) }) || this; return _this; } EditorRulers.prototype.validate = function (input) { if (Array.isArray(input)) { var rulers = []; for (var _i = 0, input_1 = input; _i < input_1.length; _i++) { var value = input_1[_i]; rulers.push(EditorIntOption.clampedInt(value, 0, 0, 10000)); } rulers.sort(function (a, b) { return a - b; }); return rulers; } return this.defaultValue; }; return EditorRulers; }(SimpleEditorOption)); 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 */; } } var EditorScrollbar = /** @class */ (function (_super) { __extends(EditorScrollbar, _super); function EditorScrollbar() { return _super.call(this, 78 /* scrollbar */, 'scrollbar', { vertical: 1 /* Auto */, horizontal: 1 /* Auto */, arrowSize: 11, useShadows: true, verticalHasArrows: false, horizontalHasArrows: false, horizontalScrollbarSize: 10, horizontalSliderSize: 10, verticalScrollbarSize: 14, verticalSliderSize: 14, handleMouseWheel: true, alwaysConsumeMouseWheel: true }) || this; } EditorScrollbar.prototype.validate = function (_input) { if (typeof _input !== 'object') { return this.defaultValue; } var input = _input; var horizontalScrollbarSize = EditorIntOption.clampedInt(input.horizontalScrollbarSize, this.defaultValue.horizontalScrollbarSize, 0, 1000); var 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: EditorBooleanOption.boolean(input.useShadows, this.defaultValue.useShadows), verticalHasArrows: EditorBooleanOption.boolean(input.verticalHasArrows, this.defaultValue.verticalHasArrows), horizontalHasArrows: EditorBooleanOption.boolean(input.horizontalHasArrows, this.defaultValue.horizontalHasArrows), handleMouseWheel: EditorBooleanOption.boolean(input.handleMouseWheel, this.defaultValue.handleMouseWheel), alwaysConsumeMouseWheel: EditorBooleanOption.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), }; }; return EditorScrollbar; }(BaseEditorOption)); var EditorSuggest = /** @class */ (function (_super) { __extends(EditorSuggest, _super); function EditorSuggest() { var _this = this; var defaults = { insertMode: 'insert', insertHighlight: false, filterGraceful: true, snippetsPreventQuickSuggestions: true, localityBonus: false, shareSuggestSelections: false, showIcons: true, maxVisibleSuggestions: 12, showMethods: true, showFunctions: true, showConstructors: 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, hideStatusBar: true }; _this = _super.call(this, 89 /* suggest */, 'suggest', defaults, { 'editor.suggest.insertMode': { type: 'string', enum: ['insert', 'replace'], enumDescriptions: [ nls.localize(54, null), nls.localize(55, null), ], default: defaults.insertMode, description: nls.localize(56, null) }, 'editor.suggest.insertHighlight': { type: 'boolean', default: defaults.insertHighlight, description: nls.localize(57, null) }, 'editor.suggest.filterGraceful': { type: 'boolean', default: defaults.filterGraceful, description: nls.localize(58, null) }, 'editor.suggest.localityBonus': { type: 'boolean', default: defaults.localityBonus, description: nls.localize(59, null) }, 'editor.suggest.shareSuggestSelections': { type: 'boolean', default: defaults.shareSuggestSelections, markdownDescription: nls.localize(60, null) }, 'editor.suggest.snippetsPreventQuickSuggestions': { type: 'boolean', default: defaults.snippetsPreventQuickSuggestions, description: nls.localize(61, null) }, 'editor.suggest.showIcons': { type: 'boolean', default: defaults.showIcons, description: nls.localize(62, null) }, 'editor.suggest.maxVisibleSuggestions': { type: 'number', default: defaults.maxVisibleSuggestions, minimum: 1, maximum: 15, description: nls.localize(63, null) }, 'editor.suggest.filteredTypes': { type: 'object', deprecationMessage: nls.localize(64, null) }, 'editor.suggest.showMethods': { type: 'boolean', default: true, markdownDescription: nls.localize(65, null) }, 'editor.suggest.showFunctions': { type: 'boolean', default: true, markdownDescription: nls.localize(66, null) }, 'editor.suggest.showConstructors': { type: 'boolean', default: true, markdownDescription: nls.localize(67, null) }, 'editor.suggest.showFields': { type: 'boolean', default: true, markdownDescription: nls.localize(68, null) }, 'editor.suggest.showVariables': { type: 'boolean', default: true, markdownDescription: nls.localize(69, null) }, 'editor.suggest.showClasses': { type: 'boolean', default: true, markdownDescription: nls.localize(70, null) }, 'editor.suggest.showStructs': { type: 'boolean', default: true, markdownDescription: nls.localize(71, null) }, 'editor.suggest.showInterfaces': { type: 'boolean', default: true, markdownDescription: nls.localize(72, null) }, 'editor.suggest.showModules': { type: 'boolean', default: true, markdownDescription: nls.localize(73, null) }, 'editor.suggest.showProperties': { type: 'boolean', default: true, markdownDescription: nls.localize(74, null) }, 'editor.suggest.showEvents': { type: 'boolean', default: true, markdownDescription: nls.localize(75, null) }, 'editor.suggest.showOperators': { type: 'boolean', default: true, markdownDescription: nls.localize(76, null) }, 'editor.suggest.showUnits': { type: 'boolean', default: true, markdownDescription: nls.localize(77, null) }, 'editor.suggest.showValues': { type: 'boolean', default: true, markdownDescription: nls.localize(78, null) }, 'editor.suggest.showConstants': { type: 'boolean', default: true, markdownDescription: nls.localize(79, null) }, 'editor.suggest.showEnums': { type: 'boolean', default: true, markdownDescription: nls.localize(80, null) }, 'editor.suggest.showEnumMembers': { type: 'boolean', default: true, markdownDescription: nls.localize(81, null) }, 'editor.suggest.showKeywords': { type: 'boolean', default: true, markdownDescription: nls.localize(82, null) }, 'editor.suggest.showWords': { type: 'boolean', default: true, markdownDescription: nls.localize(83, null) }, 'editor.suggest.showColors': { type: 'boolean', default: true, markdownDescription: nls.localize(84, null) }, 'editor.suggest.showFiles': { type: 'boolean', default: true, markdownDescription: nls.localize(85, null) }, 'editor.suggest.showReferences': { type: 'boolean', default: true, markdownDescription: nls.localize(86, null) }, 'editor.suggest.showCustomcolors': { type: 'boolean', default: true, markdownDescription: nls.localize(87, null) }, 'editor.suggest.showFolders': { type: 'boolean', default: true, markdownDescription: nls.localize(88, null) }, 'editor.suggest.showTypeParameters': { type: 'boolean', default: true, markdownDescription: nls.localize(89, null) }, 'editor.suggest.showSnippets': { type: 'boolean', default: true, markdownDescription: nls.localize(90, null) }, 'editor.suggest.hideStatusBar': { type: 'boolean', default: true, markdownDescription: nls.localize(91, null) } }) || this; return _this; } EditorSuggest.prototype.validate = function (_input) { if (typeof _input !== 'object') { return this.defaultValue; } var input = _input; return { insertMode: EditorStringEnumOption.stringSet(input.insertMode, this.defaultValue.insertMode, ['insert', 'replace']), insertHighlight: EditorBooleanOption.boolean(input.insertHighlight, this.defaultValue.insertHighlight), filterGraceful: EditorBooleanOption.boolean(input.filterGraceful, this.defaultValue.filterGraceful), snippetsPreventQuickSuggestions: EditorBooleanOption.boolean(input.snippetsPreventQuickSuggestions, this.defaultValue.filterGraceful), localityBonus: EditorBooleanOption.boolean(input.localityBonus, this.defaultValue.localityBonus), shareSuggestSelections: EditorBooleanOption.boolean(input.shareSuggestSelections, this.defaultValue.shareSuggestSelections), showIcons: EditorBooleanOption.boolean(input.showIcons, this.defaultValue.showIcons), maxVisibleSuggestions: EditorIntOption.clampedInt(input.maxVisibleSuggestions, this.defaultValue.maxVisibleSuggestions, 1, 15), showMethods: EditorBooleanOption.boolean(input.showMethods, this.defaultValue.showMethods), showFunctions: EditorBooleanOption.boolean(input.showFunctions, this.defaultValue.showFunctions), showConstructors: EditorBooleanOption.boolean(input.showConstructors, this.defaultValue.showConstructors), showFields: EditorBooleanOption.boolean(input.showFields, this.defaultValue.showFields), showVariables: EditorBooleanOption.boolean(input.showVariables, this.defaultValue.showVariables), showClasses: EditorBooleanOption.boolean(input.showClasses, this.defaultValue.showClasses), showStructs: EditorBooleanOption.boolean(input.showStructs, this.defaultValue.showStructs), showInterfaces: EditorBooleanOption.boolean(input.showInterfaces, this.defaultValue.showInterfaces), showModules: EditorBooleanOption.boolean(input.showModules, this.defaultValue.showModules), showProperties: EditorBooleanOption.boolean(input.showProperties, this.defaultValue.showProperties), showEvents: EditorBooleanOption.boolean(input.showEvents, this.defaultValue.showEvents), showOperators: EditorBooleanOption.boolean(input.showOperators, this.defaultValue.showOperators), showUnits: EditorBooleanOption.boolean(input.showUnits, this.defaultValue.showUnits), showValues: EditorBooleanOption.boolean(input.showValues, this.defaultValue.showValues), showConstants: EditorBooleanOption.boolean(input.showConstants, this.defaultValue.showConstants), showEnums: EditorBooleanOption.boolean(input.showEnums, this.defaultValue.showEnums), showEnumMembers: EditorBooleanOption.boolean(input.showEnumMembers, this.defaultValue.showEnumMembers), showKeywords: EditorBooleanOption.boolean(input.showKeywords, this.defaultValue.showKeywords), showWords: EditorBooleanOption.boolean(input.showWords, this.defaultValue.showWords), showColors: EditorBooleanOption.boolean(input.showColors, this.defaultValue.showColors), showFiles: EditorBooleanOption.boolean(input.showFiles, this.defaultValue.showFiles), showReferences: EditorBooleanOption.boolean(input.showReferences, this.defaultValue.showReferences), showFolders: EditorBooleanOption.boolean(input.showFolders, this.defaultValue.showFolders), showTypeParameters: EditorBooleanOption.boolean(input.showTypeParameters, this.defaultValue.showTypeParameters), showSnippets: EditorBooleanOption.boolean(input.showSnippets, this.defaultValue.showSnippets), hideStatusBar: EditorBooleanOption.boolean(input.hideStatusBar, this.defaultValue.hideStatusBar), }; }; return EditorSuggest; }(BaseEditorOption)); //#endregion //#region tabFocusMode var EditorTabFocusMode = /** @class */ (function (_super) { __extends(EditorTabFocusMode, _super); function EditorTabFocusMode() { return _super.call(this, 106 /* tabFocusMode */, [68 /* readOnly */]) || this; } EditorTabFocusMode.prototype.compute = function (env, options, _) { var readOnly = options.get(68 /* readOnly */); return (readOnly ? true : env.tabFocusMode); }; return EditorTabFocusMode; }(ComputedEditorOption)); 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 */; } } var EditorWrappingInfoComputer = /** @class */ (function (_super) { __extends(EditorWrappingInfoComputer, _super); function EditorWrappingInfoComputer() { return _super.call(this, 108 /* wrappingInfo */, [97 /* wordWrap */, 100 /* wordWrapColumn */, 101 /* wordWrapMinified */, 107 /* layoutInfo */, 2 /* accessibilitySupport */]) || this; } EditorWrappingInfoComputer.prototype.compute = function (env, options, _) { var wordWrap = options.get(97 /* wordWrap */); var wordWrapColumn = options.get(100 /* wordWrapColumn */); var wordWrapMinified = options.get(101 /* wordWrapMinified */); var layoutInfo = options.get(107 /* layoutInfo */); var accessibilitySupport = options.get(2 /* accessibilitySupport */); var bareWrappingInfo = null; { 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. bareWrappingInfo = { isWordWrapMinified: false, isViewportWrapping: false, wrappingColumn: -1 }; } else if (wordWrapMinified && env.isDominatedByLongLines) { // Force viewport width wrapping if model is dominated by long lines bareWrappingInfo = { isWordWrapMinified: true, isViewportWrapping: true, wrappingColumn: Math.max(1, layoutInfo.viewportColumn) }; } else if (wordWrap === 'on') { bareWrappingInfo = { isWordWrapMinified: false, isViewportWrapping: true, wrappingColumn: Math.max(1, layoutInfo.viewportColumn) }; } else if (wordWrap === 'bounded') { bareWrappingInfo = { isWordWrapMinified: false, isViewportWrapping: true, wrappingColumn: Math.min(Math.max(1, layoutInfo.viewportColumn), wordWrapColumn) }; } else if (wordWrap === 'wordWrapColumn') { bareWrappingInfo = { isWordWrapMinified: false, isViewportWrapping: false, wrappingColumn: wordWrapColumn }; } else { bareWrappingInfo = { isWordWrapMinified: false, isViewportWrapping: false, wrappingColumn: -1 }; } } return { isDominatedByLongLines: env.isDominatedByLongLines, isWordWrapMinified: bareWrappingInfo.isWordWrapMinified, isViewportWrapping: bareWrappingInfo.isViewportWrapping, wrappingColumn: bareWrappingInfo.wrappingColumn, }; }; return EditorWrappingInfoComputer; }(ComputedEditorOption)); //#endregion var DEFAULT_WINDOWS_FONT_FAMILY = 'Consolas, \'Courier New\', monospace'; var DEFAULT_MAC_FONT_FAMILY = 'Menlo, Monaco, \'Courier New\', monospace'; var DEFAULT_LINUX_FONT_FAMILY = '\'Droid Sans Mono\', \'monospace\', monospace, \'Droid Sans Fallback\''; /** * @internal */ exports.EDITOR_FONT_DEFAULTS = { fontFamily: (platform.isMacintosh ? DEFAULT_MAC_FONT_FAMILY : (platform.isLinux ? DEFAULT_LINUX_FONT_FAMILY : DEFAULT_WINDOWS_FONT_FAMILY)), fontWeight: 'normal', fontSize: (platform.isMacintosh ? 12 : 14), lineHeight: 0, letterSpacing: 0, }; /** * @internal */ exports.EDITOR_MODEL_DEFAULTS = { tabSize: 4, indentSize: 4, insertSpaces: true, detectIndentation: true, trimAutoWhitespace: true, largeFileOptimizations: true }; /** * @internal */ exports.editorOptionsRegistry = []; function register(option) { exports.editorOptionsRegistry[option.id] = option; return option; } /** * WORKAROUND: TS emits "any" for complex editor options values (anything except string, bool, enum, etc. ends up being "any") * @monacodtsreplace * /accessibilitySupport, any/accessibilitySupport, AccessibilitySupport/ * /comments, any/comments, EditorCommentsOptions/ * /find, any/find, EditorFindOptions/ * /fontInfo, any/fontInfo, FontInfo/ * /gotoLocation, any/gotoLocation, GoToLocationOptions/ * /hover, any/hover, EditorHoverOptions/ * /lightbulb, any/lightbulb, EditorLightbulbOptions/ * /minimap, any/minimap, EditorMinimapOptions/ * /parameterHints, any/parameterHints, InternalParameterHintOptions/ * /quickSuggestions, any/quickSuggestions, ValidQuickSuggestionsOptions/ * /suggest, any/suggest, InternalSuggestOptions/ */ exports.EditorOptions = { acceptSuggestionOnCommitCharacter: register(new EditorBooleanOption(0 /* acceptSuggestionOnCommitCharacter */, 'acceptSuggestionOnCommitCharacter', true, { markdownDescription: nls.localize(92, null) })), acceptSuggestionOnEnter: register(new EditorStringEnumOption(1 /* acceptSuggestionOnEnter */, 'acceptSuggestionOnEnter', 'on', ['on', 'smart', 'off'], { markdownEnumDescriptions: [ '', nls.localize(93, null), '' ], markdownDescription: nls.localize(94, null) })), accessibilitySupport: register(new EditorAccessibilitySupport()), accessibilityPageSize: register(new EditorIntOption(3 /* accessibilityPageSize */, 'accessibilityPageSize', 10, 1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(95, null) })), ariaLabel: register(new EditorStringOption(4 /* ariaLabel */, 'ariaLabel', nls.localize(96, null))), autoClosingBrackets: register(new EditorStringEnumOption(5 /* autoClosingBrackets */, 'autoClosingBrackets', 'languageDefined', ['always', 'languageDefined', 'beforeWhitespace', 'never'], { enumDescriptions: [ '', nls.localize(97, null), nls.localize(98, null), '', ], description: nls.localize(99, null) })), autoClosingOvertype: register(new EditorStringEnumOption(6 /* autoClosingOvertype */, 'autoClosingOvertype', 'auto', ['always', 'auto', 'never'], { enumDescriptions: [ '', nls.localize(100, null), '', ], description: nls.localize(101, null) })), autoClosingQuotes: register(new EditorStringEnumOption(7 /* autoClosingQuotes */, 'autoClosingQuotes', 'languageDefined', ['always', 'languageDefined', 'beforeWhitespace', 'never'], { enumDescriptions: [ '', nls.localize(102, null), nls.localize(103, null), '', ], description: nls.localize(104, null) })), autoIndent: register(new EditorEnumOption(8 /* autoIndent */, 'autoIndent', 4 /* Full */, 'full', ['none', 'keep', 'brackets', 'advanced', 'full'], _autoIndentFromString, { enumDescriptions: [ nls.localize(105, null), nls.localize(106, null), nls.localize(107, null), nls.localize(108, null), nls.localize(109, null), ], description: nls.localize(110, null) })), automaticLayout: register(new EditorBooleanOption(9 /* automaticLayout */, 'automaticLayout', false)), autoSurround: register(new EditorStringEnumOption(10 /* autoSurround */, 'autoSurround', 'languageDefined', ['languageDefined', 'quotes', 'brackets', 'never'], { enumDescriptions: [ nls.localize(111, null), nls.localize(112, null), nls.localize(113, null), '' ], description: nls.localize(114, null) })), codeLens: register(new EditorBooleanOption(11 /* codeLens */, 'codeLens', true, { description: nls.localize(115, null) })), colorDecorators: register(new EditorBooleanOption(12 /* colorDecorators */, 'colorDecorators', true, { description: nls.localize(116, null) })), comments: register(new EditorComments()), contextmenu: register(new EditorBooleanOption(14 /* contextmenu */, 'contextmenu', true)), copyWithSyntaxHighlighting: register(new EditorBooleanOption(15 /* copyWithSyntaxHighlighting */, 'copyWithSyntaxHighlighting', true, { description: nls.localize(117, null) })), cursorBlinking: register(new EditorEnumOption(16 /* cursorBlinking */, 'cursorBlinking', 1 /* Blink */, 'blink', ['blink', 'smooth', 'phase', 'expand', 'solid'], _cursorBlinkingStyleFromString, { description: nls.localize(118, null) })), cursorSmoothCaretAnimation: register(new EditorBooleanOption(17 /* cursorSmoothCaretAnimation */, 'cursorSmoothCaretAnimation', false, { description: nls.localize(119, null) })), cursorStyle: register(new EditorEnumOption(18 /* cursorStyle */, 'cursorStyle', TextEditorCursorStyle.Line, 'line', ['line', 'block', 'underline', 'line-thin', 'block-outline', 'underline-thin'], _cursorStyleFromString, { description: nls.localize(120, null) })), cursorSurroundingLines: register(new EditorIntOption(19 /* cursorSurroundingLines */, 'cursorSurroundingLines', 0, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(121, null) })), cursorSurroundingLinesStyle: register(new EditorStringEnumOption(20 /* cursorSurroundingLinesStyle */, 'cursorSurroundingLinesStyle', 'default', ['default', 'all'], { enumDescriptions: [ nls.localize(122, null), nls.localize(123, null) ], description: nls.localize(124, null) })), cursorWidth: register(new EditorIntOption(21 /* cursorWidth */, 'cursorWidth', 0, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { markdownDescription: nls.localize(125, null) })), disableLayerHinting: register(new EditorBooleanOption(22 /* disableLayerHinting */, 'disableLayerHinting', false)), disableMonospaceOptimizations: register(new EditorBooleanOption(23 /* disableMonospaceOptimizations */, 'disableMonospaceOptimizations', false)), dragAndDrop: register(new EditorBooleanOption(24 /* dragAndDrop */, 'dragAndDrop', true, { description: nls.localize(126, null) })), emptySelectionClipboard: register(new EditorEmptySelectionClipboard()), extraEditorClassName: register(new EditorStringOption(26 /* extraEditorClassName */, 'extraEditorClassName', '')), fastScrollSensitivity: register(new EditorFloatOption(27 /* fastScrollSensitivity */, 'fastScrollSensitivity', 5, function (x) { return (x <= 0 ? 5 : x); }, { markdownDescription: nls.localize(127, null) })), find: register(new EditorFind()), fixedOverflowWidgets: register(new EditorBooleanOption(29 /* fixedOverflowWidgets */, 'fixedOverflowWidgets', false)), folding: register(new EditorBooleanOption(30 /* folding */, 'folding', true, { description: nls.localize(128, null) })), foldingStrategy: register(new EditorStringEnumOption(31 /* foldingStrategy */, 'foldingStrategy', 'auto', ['auto', 'indentation'], { markdownDescription: nls.localize(129, null) })), foldingHighlight: register(new EditorBooleanOption(32 /* foldingHighlight */, 'foldingHighlight', true, { description: nls.localize(130, null) })), fontFamily: register(new EditorStringOption(33 /* fontFamily */, 'fontFamily', exports.EDITOR_FONT_DEFAULTS.fontFamily, { description: nls.localize(131, null) })), fontInfo: register(new EditorFontInfo()), fontLigatures2: register(new EditorFontLigatures()), fontSize: register(new EditorFontSize()), fontWeight: register(new EditorStringOption(37 /* fontWeight */, 'fontWeight', exports.EDITOR_FONT_DEFAULTS.fontWeight, { enum: ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'], description: nls.localize(132, null) })), formatOnPaste: register(new EditorBooleanOption(38 /* formatOnPaste */, 'formatOnPaste', false, { description: nls.localize(133, null) })), formatOnType: register(new EditorBooleanOption(39 /* formatOnType */, 'formatOnType', false, { description: nls.localize(134, null) })), glyphMargin: register(new EditorBooleanOption(40 /* glyphMargin */, 'glyphMargin', true, { description: nls.localize(135, null) })), gotoLocation: register(new EditorGoToLocation()), hideCursorInOverviewRuler: register(new EditorBooleanOption(42 /* hideCursorInOverviewRuler */, 'hideCursorInOverviewRuler', false, { description: nls.localize(136, null) })), highlightActiveIndentGuide: register(new EditorBooleanOption(43 /* highlightActiveIndentGuide */, 'highlightActiveIndentGuide', true, { description: nls.localize(137, null) })), hover: register(new EditorHover()), inDiffEditor: register(new EditorBooleanOption(45 /* inDiffEditor */, 'inDiffEditor', false)), letterSpacing: register(new EditorFloatOption(46 /* letterSpacing */, 'letterSpacing', exports.EDITOR_FONT_DEFAULTS.letterSpacing, function (x) { return EditorFloatOption.clamp(x, -5, 20); }, { description: nls.localize(138, null) })), lightbulb: register(new EditorLightbulb()), lineDecorationsWidth: register(new SimpleEditorOption(48 /* lineDecorationsWidth */, 'lineDecorationsWidth', 10)), lineHeight: register(new EditorLineHeight()), lineNumbers: register(new EditorRenderLineNumbersOption()), lineNumbersMinChars: register(new EditorIntOption(51 /* lineNumbersMinChars */, 'lineNumbersMinChars', 5, 1, 300)), links: register(new EditorBooleanOption(52 /* links */, 'links', true, { description: nls.localize(139, null) })), matchBrackets: register(new EditorStringEnumOption(53 /* matchBrackets */, 'matchBrackets', 'always', ['always', 'near', 'never'], { description: nls.localize(140, null) })), minimap: register(new EditorMinimap()), mouseStyle: register(new EditorStringEnumOption(55 /* mouseStyle */, 'mouseStyle', 'text', ['text', 'default', 'copy'])), mouseWheelScrollSensitivity: register(new EditorFloatOption(56 /* mouseWheelScrollSensitivity */, 'mouseWheelScrollSensitivity', 1, function (x) { return (x === 0 ? 1 : x); }, { markdownDescription: nls.localize(141, null) })), mouseWheelZoom: register(new EditorBooleanOption(57 /* mouseWheelZoom */, 'mouseWheelZoom', false, { markdownDescription: nls.localize(142, null) })), multiCursorMergeOverlapping: register(new EditorBooleanOption(58 /* multiCursorMergeOverlapping */, 'multiCursorMergeOverlapping', true, { description: nls.localize(143, null) })), multiCursorModifier: register(new EditorEnumOption(59 /* multiCursorModifier */, 'multiCursorModifier', 'altKey', 'alt', ['ctrlCmd', 'alt'], _multiCursorModifierFromString, { markdownEnumDescriptions: [ nls.localize(144, null), nls.localize(145, null) ], markdownDescription: nls.localize(146, null) })), multiCursorPaste: register(new EditorStringEnumOption(60 /* multiCursorPaste */, 'multiCursorPaste', 'spread', ['spread', 'full'], { markdownEnumDescriptions: [ nls.localize(147, null), nls.localize(148, null) ], markdownDescription: nls.localize(149, null) })), occurrencesHighlight: register(new EditorBooleanOption(61 /* occurrencesHighlight */, 'occurrencesHighlight', true, { description: nls.localize(150, null) })), overviewRulerBorder: register(new EditorBooleanOption(62 /* overviewRulerBorder */, 'overviewRulerBorder', true, { description: nls.localize(151, null) })), overviewRulerLanes: register(new EditorIntOption(63 /* overviewRulerLanes */, 'overviewRulerLanes', 3, 0, 3)), parameterHints: register(new EditorParameterHints()), peekWidgetDefaultFocus: register(new EditorStringEnumOption(65 /* peekWidgetDefaultFocus */, 'peekWidgetDefaultFocus', 'tree', ['tree', 'editor'], { enumDescriptions: [ nls.localize(152, null), nls.localize(153, null) ], description: nls.localize(154, null) })), quickSuggestions: register(new EditorQuickSuggestions()), quickSuggestionsDelay: register(new EditorIntOption(67 /* quickSuggestionsDelay */, 'quickSuggestionsDelay', 10, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(155, null) })), readOnly: register(new EditorBooleanOption(68 /* readOnly */, 'readOnly', false)), renderControlCharacters: register(new EditorBooleanOption(69 /* renderControlCharacters */, 'renderControlCharacters', false, { description: nls.localize(156, null) })), renderIndentGuides: register(new EditorBooleanOption(70 /* renderIndentGuides */, 'renderIndentGuides', true, { description: nls.localize(157, null) })), renderFinalNewline: register(new EditorBooleanOption(71 /* renderFinalNewline */, 'renderFinalNewline', true, { description: nls.localize(158, null) })), renderLineHighlight: register(new EditorStringEnumOption(72 /* renderLineHighlight */, 'renderLineHighlight', 'line', ['none', 'gutter', 'line', 'all'], { enumDescriptions: [ '', '', '', nls.localize(159, null), ], description: nls.localize(160, null) })), renderValidationDecorations: register(new EditorStringEnumOption(73 /* renderValidationDecorations */, 'renderValidationDecorations', 'editable', ['editable', 'on', 'off'])), renderWhitespace: register(new EditorStringEnumOption(74 /* renderWhitespace */, 'renderWhitespace', 'none', ['none', 'boundary', 'selection', 'all'], { enumDescriptions: [ '', nls.localize(161, null), nls.localize(162, null), '' ], description: nls.localize(163, null) })), revealHorizontalRightPadding: register(new EditorIntOption(75 /* revealHorizontalRightPadding */, 'revealHorizontalRightPadding', 30, 0, 1000)), roundedSelection: register(new EditorBooleanOption(76 /* roundedSelection */, 'roundedSelection', true, { description: nls.localize(164, null) })), rulers: register(new EditorRulers()), scrollbar: register(new EditorScrollbar()), scrollBeyondLastColumn: register(new EditorIntOption(79 /* scrollBeyondLastColumn */, 'scrollBeyondLastColumn', 5, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(165, null) })), scrollBeyondLastLine: register(new EditorBooleanOption(80 /* scrollBeyondLastLine */, 'scrollBeyondLastLine', true, { description: nls.localize(166, null) })), selectionClipboard: register(new EditorBooleanOption(81 /* selectionClipboard */, 'selectionClipboard', true, { description: nls.localize(167, null), included: platform.isLinux })), selectionHighlight: register(new EditorBooleanOption(82 /* selectionHighlight */, 'selectionHighlight', true, { description: nls.localize(168, null) })), selectOnLineNumbers: register(new EditorBooleanOption(83 /* selectOnLineNumbers */, 'selectOnLineNumbers', true)), showFoldingControls: register(new EditorStringEnumOption(84 /* showFoldingControls */, 'showFoldingControls', 'mouseover', ['always', 'mouseover'], { description: nls.localize(169, null) })), showUnused: register(new EditorBooleanOption(85 /* showUnused */, 'showUnused', true, { description: nls.localize(170, null) })), snippetSuggestions: register(new EditorStringEnumOption(86 /* snippetSuggestions */, 'snippetSuggestions', 'inline', ['top', 'bottom', 'inline', 'none'], { enumDescriptions: [ nls.localize(171, null), nls.localize(172, null), nls.localize(173, null), nls.localize(174, null), ], description: nls.localize(175, null) })), smoothScrolling: register(new EditorBooleanOption(87 /* smoothScrolling */, 'smoothScrolling', false, { description: nls.localize(176, null) })), stopRenderingLineAfter: register(new EditorIntOption(88 /* stopRenderingLineAfter */, 'stopRenderingLineAfter', 10000, -1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */)), suggest: register(new EditorSuggest()), suggestFontSize: register(new EditorIntOption(90 /* suggestFontSize */, 'suggestFontSize', 0, 0, 1000, { markdownDescription: nls.localize(177, null) })), suggestLineHeight: register(new EditorIntOption(91 /* suggestLineHeight */, 'suggestLineHeight', 0, 0, 1000, { markdownDescription: nls.localize(178, null) })), suggestOnTriggerCharacters: register(new EditorBooleanOption(92 /* suggestOnTriggerCharacters */, 'suggestOnTriggerCharacters', true, { description: nls.localize(179, null) })), suggestSelection: register(new EditorStringEnumOption(93 /* suggestSelection */, 'suggestSelection', 'recentlyUsed', ['first', 'recentlyUsed', 'recentlyUsedByPrefix'], { markdownEnumDescriptions: [ nls.localize(180, null), nls.localize(181, null), nls.localize(182, null), ], description: nls.localize(183, null) })), tabCompletion: register(new EditorStringEnumOption(94 /* tabCompletion */, 'tabCompletion', 'off', ['on', 'off', 'onlySnippets'], { enumDescriptions: [ nls.localize(184, null), nls.localize(185, null), nls.localize(186, null), ], description: nls.localize(187, null) })), useTabStops: register(new EditorBooleanOption(95 /* useTabStops */, 'useTabStops', true, { description: nls.localize(188, null) })), wordSeparators: register(new EditorStringOption(96 /* wordSeparators */, 'wordSeparators', wordHelper_1.USUAL_WORD_SEPARATORS, { description: nls.localize(189, null) })), wordWrap: register(new EditorStringEnumOption(97 /* wordWrap */, 'wordWrap', 'off', ['off', 'on', 'wordWrapColumn', 'bounded'], { markdownEnumDescriptions: [ nls.localize(190, null), nls.localize(191, null), nls.localize(192, null), nls.localize(193, null), ], description: nls.localize(194, null) })), wordWrapBreakAfterCharacters: register(new EditorStringOption(98 /* wordWrapBreakAfterCharacters */, 'wordWrapBreakAfterCharacters', ' \t})]?|/&.,;¢°′″‰℃、。。、¢,.:;?!%・・ゝゞヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻ァィゥェォャュョッー”〉》」』】〕)]}」')), wordWrapBreakBeforeCharacters: register(new EditorStringOption(99 /* wordWrapBreakBeforeCharacters */, 'wordWrapBreakBeforeCharacters', '([{‘“〈《「『【〔([{「£¥$£¥++')), wordWrapColumn: register(new EditorIntOption(100 /* wordWrapColumn */, 'wordWrapColumn', 80, 1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { markdownDescription: nls.localize(195, null) })), wordWrapMinified: register(new EditorBooleanOption(101 /* wordWrapMinified */, 'wordWrapMinified', true)), wrappingIndent: register(new EditorEnumOption(102 /* wrappingIndent */, 'wrappingIndent', 1 /* Same */, 'same', ['none', 'same', 'indent', 'deepIndent'], _wrappingIndentFromString, { enumDescriptions: [ nls.localize(196, null), nls.localize(197, null), nls.localize(198, null), nls.localize(199, null), ], description: nls.localize(200, null), })), wrappingStrategy: register(new EditorStringEnumOption(103 /* wrappingStrategy */, 'wrappingStrategy', 'simple', ['simple', 'advanced'], { enumDescriptions: [ nls.localize(201, null), nls.localize(202, null) ], description: nls.localize(203, 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[424/*vs/editor/common/viewModel/viewModelDecorations*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,69/*vs/editor/common/viewModel/viewModel*/,33/*vs/editor/common/config/editorOptions*/]), function (require, exports, position_1, range_1, viewModel_1, editorOptions_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ViewModelDecorations = /** @class */ (function () { function ViewModelDecorations(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; } ViewModelDecorations.prototype._clearCachedModelDecorationsResolver = function () { this._cachedModelDecorationsResolver = null; this._cachedModelDecorationsResolverViewRange = null; }; ViewModelDecorations.prototype.dispose = function () { this._decorationsCache = Object.create(null); this._clearCachedModelDecorationsResolver(); }; ViewModelDecorations.prototype.reset = function () { this._decorationsCache = Object.create(null); this._clearCachedModelDecorationsResolver(); }; ViewModelDecorations.prototype.onModelDecorationsChanged = function () { this._decorationsCache = Object.create(null); this._clearCachedModelDecorationsResolver(); }; ViewModelDecorations.prototype.onLineMappingChanged = function () { this._decorationsCache = Object.create(null); this._clearCachedModelDecorationsResolver(); }; ViewModelDecorations.prototype._getOrCreateViewModelDecoration = function (modelDecoration) { var id = modelDecoration.id; var r = this._decorationsCache[id]; if (!r) { var modelRange = modelDecoration.range; var options = modelDecoration.options; var viewRange = void 0; if (options.isWholeLine) { var start = this._coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.startLineNumber, 1)); var end = this._coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.endLineNumber, this.model.getLineMaxColumn(modelRange.endLineNumber))); viewRange = new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column); } else { viewRange = this._coordinatesConverter.convertModelRangeToViewRange(modelRange); } r = new viewModel_1.ViewModelDecoration(viewRange, options); this._decorationsCache[id] = r; } return r; }; ViewModelDecorations.prototype.getDecorationsViewportData = function (viewRange) { var cacheIsValid = (this._cachedModelDecorationsResolver !== null); cacheIsValid = cacheIsValid && (viewRange.equalsRange(this._cachedModelDecorationsResolverViewRange)); if (!cacheIsValid) { this._cachedModelDecorationsResolver = this._getDecorationsViewportData(viewRange); this._cachedModelDecorationsResolverViewRange = viewRange; } return this._cachedModelDecorationsResolver; }; ViewModelDecorations.prototype._getDecorationsViewportData = function (viewportRange) { var modelDecorations = this._linesCollection.getDecorationsInRange(viewportRange, this.editorId, editorOptions_1.filterValidationDecorations(this.configuration.options)); var startLineNumber = viewportRange.startLineNumber; var endLineNumber = viewportRange.endLineNumber; var decorationsInViewport = [], decorationsInViewportLen = 0; var inlineDecorations = []; for (var j = startLineNumber; j <= endLineNumber; j++) { inlineDecorations[j - startLineNumber] = []; } for (var i = 0, len = modelDecorations.length; i < len; i++) { var modelDecoration = modelDecorations[i]; var decorationOptions = modelDecoration.options; var viewModelDecoration = this._getOrCreateViewModelDecoration(modelDecoration); var viewRange = viewModelDecoration.range; decorationsInViewport[decorationsInViewportLen++] = viewModelDecoration; if (decorationOptions.inlineClassName) { var inlineDecoration = new viewModel_1.InlineDecoration(viewRange, decorationOptions.inlineClassName, decorationOptions.inlineClassNameAffectsLetterSpacing ? 3 /* RegularAffectingLetterSpacing */ : 0 /* Regular */); var intersectedStartLineNumber = Math.max(startLineNumber, viewRange.startLineNumber); var intersectedEndLineNumber = Math.min(endLineNumber, viewRange.endLineNumber); for (var j = intersectedStartLineNumber; j <= intersectedEndLineNumber; j++) { inlineDecorations[j - startLineNumber].push(inlineDecoration); } } if (decorationOptions.beforeContentClassName) { if (startLineNumber <= viewRange.startLineNumber && viewRange.startLineNumber <= endLineNumber) { var 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) { var 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 }; }; return ViewModelDecorations; }()); exports.ViewModelDecorations = ViewModelDecorations; }); define(__m[425/*vs/nls!vs/editor/common/modes/modesRegistry*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/modes/modesRegistry", data); }); define(__m[426/*vs/nls!vs/editor/common/standaloneStrings*/], __M([7/*vs/nls*/,8/*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[59/*vs/editor/common/standaloneStrings*/], __M([0/*require*/,1/*exports*/,426/*vs/nls!vs/editor/common/standaloneStrings*/]), function (require, exports, nls) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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.gotoLineLabelValidLineAndColumn = nls.localize(24, null); GoToLineNLS.gotoLineLabelValidLine = nls.localize(25, null); GoToLineNLS.gotoLineLabelEmptyWithLineLimit = nls.localize(26, null); GoToLineNLS.gotoLineLabelEmptyWithLineAndColumnLimit = nls.localize(27, null); GoToLineNLS.gotoLineAriaLabel = nls.localize(28, null); GoToLineNLS.gotoLineActionInput = nls.localize(29, null); GoToLineNLS.gotoLineActionLabel = nls.localize(30, null); })(GoToLineNLS = exports.GoToLineNLS || (exports.GoToLineNLS = {})); var QuickCommandNLS; (function (QuickCommandNLS) { QuickCommandNLS.ariaLabelEntryWithKey = nls.localize(31, null); QuickCommandNLS.ariaLabelEntry = nls.localize(32, null); QuickCommandNLS.quickCommandActionInput = nls.localize(33, null); QuickCommandNLS.quickCommandActionLabel = nls.localize(34, null); })(QuickCommandNLS = exports.QuickCommandNLS || (exports.QuickCommandNLS = {})); var QuickOutlineNLS; (function (QuickOutlineNLS) { QuickOutlineNLS.entryAriaLabel = nls.localize(35, null); QuickOutlineNLS.quickOutlineActionInput = nls.localize(36, null); QuickOutlineNLS.quickOutlineActionLabel = nls.localize(37, null); QuickOutlineNLS._symbols_ = nls.localize(38, null); QuickOutlineNLS._modules_ = nls.localize(39, null); QuickOutlineNLS._class_ = nls.localize(40, null); QuickOutlineNLS._interface_ = nls.localize(41, null); QuickOutlineNLS._method_ = nls.localize(42, null); QuickOutlineNLS._function_ = nls.localize(43, null); QuickOutlineNLS._property_ = nls.localize(44, null); QuickOutlineNLS._variable_ = nls.localize(45, null); QuickOutlineNLS._variable2_ = nls.localize(46, null); QuickOutlineNLS._constructor_ = nls.localize(47, null); QuickOutlineNLS._call_ = nls.localize(48, null); })(QuickOutlineNLS = exports.QuickOutlineNLS || (exports.QuickOutlineNLS = {})); var StandaloneCodeEditorNLS; (function (StandaloneCodeEditorNLS) { StandaloneCodeEditorNLS.editorViewAccessibleLabel = nls.localize(49, null); StandaloneCodeEditorNLS.accessibilityHelpMessageIE = nls.localize(50, null); StandaloneCodeEditorNLS.accessibilityHelpMessage = nls.localize(51, null); })(StandaloneCodeEditorNLS = exports.StandaloneCodeEditorNLS || (exports.StandaloneCodeEditorNLS = {})); var ToggleHighContrastNLS; (function (ToggleHighContrastNLS) { ToggleHighContrastNLS.toggleHighContrast = nls.localize(52, null); })(ToggleHighContrastNLS = exports.ToggleHighContrastNLS || (exports.ToggleHighContrastNLS = {})); var SimpleServicesNLS; (function (SimpleServicesNLS) { SimpleServicesNLS.bulkEditServiceSummary = nls.localize(53, null); })(SimpleServicesNLS = exports.SimpleServicesNLS || (exports.SimpleServicesNLS = {})); }); define(__m[427/*vs/nls!vs/editor/common/view/editorColorRegistry*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/view/editorColorRegistry", data); }); define(__m[428/*vs/nls!vs/editor/contrib/bracketMatching/bracketMatching*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/bracketMatching/bracketMatching", data); }); define(__m[429/*vs/nls!vs/editor/contrib/caretOperations/caretOperations*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/caretOperations/caretOperations", data); }); define(__m[430/*vs/nls!vs/editor/contrib/caretOperations/transpose*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/caretOperations/transpose", data); }); define(__m[431/*vs/nls!vs/editor/contrib/clipboard/clipboard*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/clipboard/clipboard", data); }); define(__m[432/*vs/nls!vs/editor/contrib/codeAction/codeActionCommands*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/codeAction/codeActionCommands", data); }); define(__m[433/*vs/nls!vs/editor/contrib/codeAction/lightBulbWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/codeAction/lightBulbWidget", data); }); define(__m[434/*vs/nls!vs/editor/contrib/comment/comment*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/comment/comment", data); }); define(__m[435/*vs/nls!vs/editor/contrib/contextmenu/contextmenu*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/contextmenu/contextmenu", data); }); define(__m[436/*vs/nls!vs/editor/contrib/cursorUndo/cursorUndo*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/cursorUndo/cursorUndo", data); }); define(__m[437/*vs/nls!vs/editor/contrib/documentSymbols/outlineTree*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/documentSymbols/outlineTree", data); }); define(__m[438/*vs/nls!vs/editor/contrib/find/findController*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/find/findController", data); }); define(__m[439/*vs/nls!vs/editor/contrib/find/findWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/find/findWidget", data); }); define(__m[440/*vs/nls!vs/editor/contrib/folding/folding*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/folding/folding", data); }); define(__m[441/*vs/nls!vs/editor/contrib/fontZoom/fontZoom*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/fontZoom/fontZoom", data); }); define(__m[442/*vs/nls!vs/editor/contrib/format/format*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/format/format", data); }); define(__m[443/*vs/nls!vs/editor/contrib/format/formatActions*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/format/formatActions", data); }); define(__m[444/*vs/nls!vs/editor/contrib/gotoError/gotoError*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoError/gotoError", data); }); define(__m[445/*vs/nls!vs/editor/contrib/gotoError/gotoErrorWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoError/gotoErrorWidget", data); }); define(__m[446/*vs/nls!vs/editor/contrib/gotoSymbol/goToCommands*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/goToCommands", data); }); define(__m[447/*vs/nls!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition", data); }); define(__m[448/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesController*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/peek/referencesController", data); }); define(__m[449/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesTree*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/peek/referencesTree", data); }); define(__m[450/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/peek/referencesWidget", data); }); define(__m[451/*vs/nls!vs/editor/contrib/gotoSymbol/referencesModel*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/referencesModel", data); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[113/*vs/editor/contrib/gotoSymbol/referencesModel*/], __M([0/*require*/,1/*exports*/,451/*vs/nls!vs/editor/contrib/gotoSymbol/referencesModel*/,4/*vs/base/common/event*/,39/*vs/base/common/resources*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,127/*vs/base/common/idGenerator*/,3/*vs/editor/common/core/range*/]), function (require, exports, nls_1, event_1, resources_1, lifecycle_1, strings, idGenerator_1, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var OneReference = /** @class */ (function () { function OneReference(isProviderFirst, parent, _range, _rangeCallback) { this.isProviderFirst = isProviderFirst; this.parent = parent; this._range = _range; this._rangeCallback = _rangeCallback; this.id = idGenerator_1.defaultGenerator.nextId(); } Object.defineProperty(OneReference.prototype, "uri", { get: function () { return this.parent.uri; }, enumerable: true, configurable: true }); Object.defineProperty(OneReference.prototype, "range", { get: function () { return this._range; }, set: function (value) { this._range = value; this._rangeCallback(this); }, enumerable: true, configurable: true }); Object.defineProperty(OneReference.prototype, "ariaMessage", { get: function () { return nls_1.localize(0, null, resources_1.basename(this.uri), this.range.startLineNumber, this.range.startColumn); }, enumerable: true, configurable: true }); return OneReference; }()); exports.OneReference = OneReference; var FilePreview = /** @class */ (function () { function FilePreview(_modelReference) { this._modelReference = _modelReference; } FilePreview.prototype.dispose = function () { this._modelReference.dispose(); }; FilePreview.prototype.preview = function (range, n) { if (n === void 0) { n = 8; } var model = this._modelReference.object.textEditorModel; if (!model) { return undefined; } var startLineNumber = range.startLineNumber, startColumn = range.startColumn, endLineNumber = range.endLineNumber, endColumn = range.endColumn; var word = model.getWordUntilPosition({ lineNumber: startLineNumber, column: startColumn - n }); var beforeRange = new range_1.Range(startLineNumber, word.startColumn, startLineNumber, startColumn); var afterRange = new range_1.Range(endLineNumber, endColumn, endLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */); var before = model.getValueInRange(beforeRange).replace(/^\s+/, ''); var inside = model.getValueInRange(range); var after = model.getValueInRange(afterRange).replace(/\s+$/, ''); return { value: before + inside + after, highlight: { start: before.length, end: before.length + inside.length } }; }; return FilePreview; }()); exports.FilePreview = FilePreview; var FileReferences = /** @class */ (function () { function FileReferences(parent, uri) { this.parent = parent; this.uri = uri; this.children = []; } FileReferences.prototype.dispose = function () { lifecycle_1.dispose(this._preview); this._preview = undefined; }; Object.defineProperty(FileReferences.prototype, "preview", { get: function () { return this._preview; }, enumerable: true, configurable: true }); Object.defineProperty(FileReferences.prototype, "failure", { get: function () { return this._loadFailure; }, enumerable: true, configurable: true }); Object.defineProperty(FileReferences.prototype, "ariaMessage", { get: function () { var len = this.children.length; if (len === 1) { return nls_1.localize(1, null, resources_1.basename(this.uri), this.uri.fsPath); } else { return nls_1.localize(2, null, len, resources_1.basename(this.uri), this.uri.fsPath); } }, enumerable: true, configurable: true }); FileReferences.prototype.resolve = function (textModelResolverService) { var _this = this; if (this._resolved) { return Promise.resolve(this); } return Promise.resolve(textModelResolverService.createModelReference(this.uri).then(function (modelReference) { var model = modelReference.object; if (!model) { modelReference.dispose(); throw new Error(); } _this._preview = new FilePreview(modelReference); _this._resolved = true; return _this; }, function (err) { // something wrong here _this.children.length = 0; _this._resolved = true; _this._loadFailure = err; return _this; })); }; return FileReferences; }()); exports.FileReferences = FileReferences; var ReferencesModel = /** @class */ (function () { function ReferencesModel(links, title) { var _this = this; this._disposables = new lifecycle_1.DisposableStore(); this.groups = []; this.references = []; this._onDidChangeReferenceRange = new event_1.Emitter(); this.onDidChangeReferenceRange = this._onDidChangeReferenceRange.event; this._links = links; this._title = title; // grouping and sorting var providersFirst = links[0]; links.sort(ReferencesModel._compareReferences); var current; for (var _i = 0, links_1 = links; _i < links_1.length; _i++) { var link = links_1[_i]; if (!current || current.uri.toString() !== link.uri.toString()) { // new group current = new FileReferences(this, link.uri); this.groups.push(current); } // append, check for equality first! if (current.children.length === 0 || !range_1.Range.equalsRange(link.range, current.children[current.children.length - 1].range)) { var oneRef = new OneReference(providersFirst === link, current, link.targetSelectionRange || link.range, function (ref) { return _this._onDidChangeReferenceRange.fire(ref); }); this.references.push(oneRef); current.children.push(oneRef); } } } ReferencesModel.prototype.dispose = function () { lifecycle_1.dispose(this.groups); this._disposables.dispose(); this._onDidChangeReferenceRange.dispose(); this.groups.length = 0; }; ReferencesModel.prototype.clone = function () { return new ReferencesModel(this._links, this._title); }; Object.defineProperty(ReferencesModel.prototype, "title", { get: function () { return this._title; }, enumerable: true, configurable: true }); Object.defineProperty(ReferencesModel.prototype, "isEmpty", { get: function () { return this.groups.length === 0; }, enumerable: true, configurable: true }); Object.defineProperty(ReferencesModel.prototype, "ariaMessage", { get: function () { if (this.isEmpty) { return nls_1.localize(3, null); } else if (this.references.length === 1) { return nls_1.localize(4, null, this.references[0].uri.fsPath); } else if (this.groups.length === 1) { return nls_1.localize(5, null, this.references.length, this.groups[0].uri.fsPath); } else { return nls_1.localize(6, null, this.references.length, this.groups.length); } }, enumerable: true, configurable: true }); ReferencesModel.prototype.nextOrPreviousReference = function (reference, next) { var parent = reference.parent; var idx = parent.children.indexOf(reference); var childCount = parent.children.length; var 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]; } }; ReferencesModel.prototype.nearestReference = function (resource, position) { var nearest = this.references.map(function (ref, idx) { return { idx: 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(function (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; }; ReferencesModel.prototype.referenceAt = function (resource, position) { for (var _i = 0, _a = this.references; _i < _a.length; _i++) { var ref = _a[_i]; if (ref.uri.toString() === resource.toString()) { if (range_1.Range.containsPosition(ref.range, position)) { return ref; } } } return undefined; }; ReferencesModel.prototype.firstReference = function () { for (var _i = 0, _a = this.references; _i < _a.length; _i++) { var ref = _a[_i]; if (ref.isProviderFirst) { return ref; } } return this.references[0]; }; ReferencesModel._compareReferences = function (a, b) { return strings.compare(a.uri.toString(), b.uri.toString()) || range_1.Range.compareRangesUsingStarts(a.range, b.range); }; return ReferencesModel; }()); exports.ReferencesModel = ReferencesModel; }); define(__m[452/*vs/nls!vs/editor/contrib/gotoSymbol/symbolNavigation*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/symbolNavigation", data); }); define(__m[453/*vs/nls!vs/editor/contrib/hover/hover*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/hover", data); }); define(__m[454/*vs/nls!vs/editor/contrib/hover/modesContentHover*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/modesContentHover", data); }); define(__m[455/*vs/nls!vs/editor/contrib/inPlaceReplace/inPlaceReplace*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/inPlaceReplace/inPlaceReplace", data); }); define(__m[456/*vs/nls!vs/editor/contrib/linesOperations/linesOperations*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/linesOperations/linesOperations", data); }); define(__m[457/*vs/nls!vs/editor/contrib/links/links*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/links/links", data); }); define(__m[458/*vs/nls!vs/editor/contrib/message/messageController*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/message/messageController", data); }); define(__m[459/*vs/nls!vs/editor/contrib/multicursor/multicursor*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/multicursor/multicursor", data); }); define(__m[460/*vs/nls!vs/editor/contrib/parameterHints/parameterHints*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/parameterHints/parameterHints", data); }); define(__m[461/*vs/nls!vs/editor/contrib/parameterHints/parameterHintsWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/parameterHints/parameterHintsWidget", data); }); define(__m[462/*vs/nls!vs/editor/contrib/peekView/peekView*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/peekView/peekView", data); }); define(__m[463/*vs/nls!vs/editor/contrib/rename/rename*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/rename/rename", data); }); define(__m[464/*vs/nls!vs/editor/contrib/rename/renameInputField*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/rename/renameInputField", data); }); define(__m[465/*vs/nls!vs/editor/contrib/smartSelect/smartSelect*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/smartSelect/smartSelect", data); }); define(__m[466/*vs/nls!vs/editor/contrib/snippet/snippetVariables*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/snippet/snippetVariables", data); }); define(__m[467/*vs/nls!vs/editor/contrib/suggest/suggestController*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestController", data); }); define(__m[468/*vs/nls!vs/editor/contrib/suggest/suggestWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestWidget", data); }); define(__m[469/*vs/nls!vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode", data); }); define(__m[470/*vs/nls!vs/editor/contrib/tokenization/tokenization*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/tokenization/tokenization", data); }); define(__m[471/*vs/nls!vs/editor/contrib/wordHighlighter/wordHighlighter*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/wordHighlighter/wordHighlighter", data); }); define(__m[472/*vs/nls!vs/platform/configuration/common/configurationRegistry*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/configuration/common/configurationRegistry", data); }); define(__m[473/*vs/nls!vs/platform/keybinding/common/abstractKeybindingService*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/keybinding/common/abstractKeybindingService", data); }); define(__m[474/*vs/nls!vs/platform/list/browser/listService*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/list/browser/listService", data); }); define(__m[475/*vs/nls!vs/platform/markers/common/markers*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/markers/common/markers", data); }); define(__m[476/*vs/nls!vs/platform/theme/common/colorRegistry*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/theme/common/colorRegistry", data); }); define(__m[477/*vs/platform/contextkey/common/contextkeys*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.InputFocusedContextKey = 'inputFocus'; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[478/*vs/platform/editor/common/editor*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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[479/*vs/platform/extensions/common/extensions*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * **!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. */ var ExtensionIdentifier = /** @class */ (function () { function ExtensionIdentifier(value) { this.value = value; this._lower = value.toLowerCase(); } /** * Gives the value by which to index (for equality). */ ExtensionIdentifier.toKey = function (id) { if (typeof id === 'string') { return id.toLowerCase(); } return id._lower; }; return ExtensionIdentifier; }()); exports.ExtensionIdentifier = ExtensionIdentifier; }); define(__m[208/*vs/platform/files/common/files*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 = {})); }); define(__m[209/*vs/platform/instantiation/common/descriptors*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var SyncDescriptor = /** @class */ (function () { function SyncDescriptor(ctor, staticArguments, supportsDelayedInstantiation) { if (staticArguments === void 0) { staticArguments = []; } if (supportsDelayedInstantiation === void 0) { supportsDelayedInstantiation = false; } this.ctor = ctor; this.staticArguments = staticArguments; this.supportsDelayedInstantiation = supportsDelayedInstantiation; } return SyncDescriptor; }()); 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[83/*vs/platform/instantiation/common/extensions*/], __M([0/*require*/,1/*exports*/,209/*vs/platform/instantiation/common/descriptors*/]), function (require, exports, descriptors_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _registry = []; function registerSingleton(id, ctor, supportsDelayedInstantiation) { _registry.push([id, new descriptors_1.SyncDescriptor(ctor, [], supportsDelayedInstantiation)]); } 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[480/*vs/platform/instantiation/common/graph*/], __M([0/*require*/,1/*exports*/,21/*vs/base/common/types*/,87/*vs/base/common/collections*/]), function (require, exports, types_1, collections_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function newNode(data) { return { data: data, incoming: Object.create(null), outgoing: Object.create(null) }; } var Graph = /** @class */ (function () { function Graph(_hashFn) { this._hashFn = _hashFn; this._nodes = Object.create(null); // empty } Graph.prototype.roots = function () { var ret = []; collections_1.forEach(this._nodes, function (entry) { if (types_1.isEmptyObject(entry.value.outgoing)) { ret.push(entry.value); } }); return ret; }; Graph.prototype.insertEdge = function (from, to) { var fromNode = this.lookupOrInsertNode(from), toNode = this.lookupOrInsertNode(to); fromNode.outgoing[this._hashFn(to)] = toNode; toNode.incoming[this._hashFn(from)] = fromNode; }; Graph.prototype.removeNode = function (data) { var key = this._hashFn(data); delete this._nodes[key]; collections_1.forEach(this._nodes, function (entry) { delete entry.value.outgoing[key]; delete entry.value.incoming[key]; }); }; Graph.prototype.lookupOrInsertNode = function (data) { var key = this._hashFn(data); var node = this._nodes[key]; if (!node) { node = newNode(data); this._nodes[key] = node; } return node; }; Graph.prototype.isEmpty = function () { for (var _key in this._nodes) { return false; } return true; }; Graph.prototype.toString = function () { var data = []; collections_1.forEach(this._nodes, function (entry) { data.push(entry.key + ", (incoming)[" + Object.keys(entry.value.incoming).join(', ') + "], (outgoing)[" + Object.keys(entry.value.outgoing).join(',') + "]"); }); return data.join('\n'); }; return Graph; }()); 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[11/*vs/platform/instantiation/common/instantiation*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // ------ 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: id, index: index, optional: optional }); } else { target[_util.DI_DEPENDENCIES] = [{ id: id, index: index, optional: optional }]; target[_util.DI_TARGET] = target; } } /** * A *only* valid way to create a {{ServiceIdentifier}}. */ function createDecorator(serviceId) { if (_util.serviceIds.has(serviceId)) { return _util.serviceIds.get(serviceId); } var 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 = function () { return serviceId; }; _util.serviceIds.set(serviceId, id); return id; } exports.createDecorator = createDecorator; /** * Mark a service dependency as optional. */ function optional(serviceIdentifier) { return function (target, key, index) { if (arguments.length !== 3) { throw new Error('@optional-decorator can only be used to decorate a parameter'); } storeServiceDependency(serviceIdentifier, target, index, true); }; } exports.optional = optional; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[156/*vs/editor/browser/services/bulkEditService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IBulkEditService = instantiation_1.createDecorator('IWorkspaceEditService'); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[32/*vs/editor/browser/services/codeEditorService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ICodeEditorService = 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[62/*vs/editor/common/services/editorWorkerService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ID_EDITOR_WORKER_SERVICE = 'editorWorkerService'; exports.IEditorWorkerService = 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[210/*vs/editor/common/services/markersDecorationService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IMarkerDecorationsService = 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[71/*vs/editor/common/services/modeService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IModeService = instantiation_1.createDecorator('modeService'); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[49/*vs/editor/common/services/modelService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IModelService = instantiation_1.createDecorator('modelService'); function shouldSynchronizeModel(model) { return (!model.isTooLargeForSyncing() && !model.isForSimpleWidget); } exports.shouldSynchronizeModel = shouldSynchronizeModel; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[481/*vs/editor/common/modes/languageFeatureRegistry*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,350/*vs/editor/common/modes/languageSelector*/,49/*vs/editor/common/services/modelService*/]), function (require, exports, event_1, lifecycle_1, languageSelector_1, modelService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isExclusive(selector) { if (typeof selector === 'string') { return false; } else if (Array.isArray(selector)) { return selector.every(isExclusive); } else { return !!selector.exclusive; } } var LanguageFeatureRegistry = /** @class */ (function () { function LanguageFeatureRegistry() { this._clock = 0; this._entries = []; this._onDidChange = new event_1.Emitter(); } Object.defineProperty(LanguageFeatureRegistry.prototype, "onDidChange", { get: function () { return this._onDidChange.event; }, enumerable: true, configurable: true }); LanguageFeatureRegistry.prototype.register = function (selector, provider) { var _this = this; var entry = { selector: selector, provider: provider, _score: -1, _time: this._clock++ }; this._entries.push(entry); this._lastCandidate = undefined; this._onDidChange.fire(this._entries.length); return lifecycle_1.toDisposable(function () { if (entry) { var idx = _this._entries.indexOf(entry); if (idx >= 0) { _this._entries.splice(idx, 1); _this._lastCandidate = undefined; _this._onDidChange.fire(_this._entries.length); entry = undefined; } } }); }; LanguageFeatureRegistry.prototype.has = function (model) { return this.all(model).length > 0; }; LanguageFeatureRegistry.prototype.all = function (model) { if (!model) { return []; } this._updateScores(model); var result = []; // from registry for (var _i = 0, _a = this._entries; _i < _a.length; _i++) { var entry = _a[_i]; if (entry._score > 0) { result.push(entry.provider); } } return result; }; LanguageFeatureRegistry.prototype.ordered = function (model) { var result = []; this._orderedForEach(model, function (entry) { return result.push(entry.provider); }); return result; }; LanguageFeatureRegistry.prototype.orderedGroups = function (model) { var result = []; var lastBucket; var lastBucketScore; this._orderedForEach(model, function (entry) { if (lastBucket && lastBucketScore === entry._score) { lastBucket.push(entry.provider); } else { lastBucketScore = entry._score; lastBucket = [entry.provider]; result.push(lastBucket); } }); return result; }; LanguageFeatureRegistry.prototype._orderedForEach = function (model, callback) { if (!model) { return; } this._updateScores(model); for (var _i = 0, _a = this._entries; _i < _a.length; _i++) { var entry = _a[_i]; if (entry._score > 0) { callback(entry); } } }; LanguageFeatureRegistry.prototype._updateScores = function (model) { var candidate = { uri: model.uri.toString(), language: model.getLanguageIdentifier().language }; if (this._lastCandidate && this._lastCandidate.language === candidate.language && this._lastCandidate.uri === candidate.uri) { // nothing has changed return; } this._lastCandidate = candidate; for (var _i = 0, _a = this._entries; _i < _a.length; _i++) { var entry = _a[_i]; entry._score = languageSelector_1.score(entry.selector, model.uri, model.getLanguageIdentifier().language, modelService_1.shouldSynchronizeModel(model)); if (isExclusive(entry.selector) && entry._score > 0) { // support for one exclusive selector that overwrites // any other selector for (var _b = 0, _c = this._entries; _b < _c.length; _b++) { var entry_1 = _c[_b]; entry_1._score = 0; } entry._score = 1000; break; } } // needs sorting this._entries.sort(LanguageFeatureRegistry._compareByScoreAndTime); }; LanguageFeatureRegistry._compareByScoreAndTime = function (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; } }; return LanguageFeatureRegistry; }()); 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[17/*vs/editor/common/modes*/], __M([0/*require*/,1/*exports*/,21/*vs/base/common/types*/,25/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,481/*vs/editor/common/modes/languageFeatureRegistry*/,358/*vs/editor/common/modes/tokenizationRegistry*/]), function (require, exports, types_1, uri_1, range_1, languageFeatureRegistry_1, tokenizationRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * @internal */ var LanguageIdentifier = /** @class */ (function () { function LanguageIdentifier(language, id) { this.language = language; this.id = id; } return LanguageIdentifier; }()); exports.LanguageIdentifier = LanguageIdentifier; /** * @internal */ var TokenMetadata = /** @class */ (function () { function TokenMetadata() { } TokenMetadata.getLanguageId = function (metadata) { return (metadata & 255 /* LANGUAGEID_MASK */) >>> 0 /* LANGUAGEID_OFFSET */; }; TokenMetadata.getTokenType = function (metadata) { return (metadata & 1792 /* TOKEN_TYPE_MASK */) >>> 8 /* TOKEN_TYPE_OFFSET */; }; TokenMetadata.getFontStyle = function (metadata) { return (metadata & 14336 /* FONT_STYLE_MASK */) >>> 11 /* FONT_STYLE_OFFSET */; }; TokenMetadata.getForeground = function (metadata) { return (metadata & 8372224 /* FOREGROUND_MASK */) >>> 14 /* FOREGROUND_OFFSET */; }; TokenMetadata.getBackground = function (metadata) { return (metadata & 4286578688 /* BACKGROUND_MASK */) >>> 23 /* BACKGROUND_OFFSET */; }; TokenMetadata.getClassNameFromMetadata = function (metadata) { var foreground = this.getForeground(metadata); var className = 'mtk' + foreground; var fontStyle = this.getFontStyle(metadata); if (fontStyle & 1 /* Italic */) { className += ' mtki'; } if (fontStyle & 2 /* Bold */) { className += ' mtkb'; } if (fontStyle & 4 /* Underline */) { className += ' mtku'; } return className; }; TokenMetadata.getInlineStyleFromMetadata = function (metadata, colorMap) { var foreground = this.getForeground(metadata); var fontStyle = this.getFontStyle(metadata); var result = "color: " + colorMap[foreground] + ";"; if (fontStyle & 1 /* Italic */) { result += 'font-style: italic;'; } if (fontStyle & 2 /* Bold */) { result += 'font-weight: bold;'; } if (fontStyle & 4 /* Underline */) { result += 'text-decoration: underline;'; } return result; }; return TokenMetadata; }()); exports.TokenMetadata = TokenMetadata; /** * @internal */ exports.completionKindToCssClass = (function () { var data = Object.create(null); data[0 /* Method */] = 'method'; data[1 /* Function */] = 'function'; data[2 /* Constructor */] = 'constructor'; data[3 /* Field */] = 'field'; data[4 /* Variable */] = 'variable'; data[5 /* Class */] = 'class'; data[6 /* Struct */] = 'struct'; data[7 /* Interface */] = 'interface'; data[8 /* Module */] = 'module'; data[9 /* Property */] = 'property'; data[10 /* Event */] = 'event'; data[11 /* Operator */] = 'operator'; data[12 /* Unit */] = 'unit'; data[13 /* Value */] = 'value'; data[14 /* Constant */] = 'constant'; data[15 /* Enum */] = 'enum'; data[16 /* EnumMember */] = 'enum-member'; data[17 /* Keyword */] = 'keyword'; data[25 /* Snippet */] = 'snippet'; data[18 /* Text */] = 'text'; data[19 /* Color */] = 'color'; data[20 /* File */] = 'file'; data[21 /* Reference */] = 'reference'; data[22 /* Customcolor */] = 'customcolor'; data[23 /* Folder */] = 'folder'; data[24 /* TypeParameter */] = 'type-parameter'; return function (kind) { return data[kind] || 'property'; }; })(); /** * @internal */ exports.completionKindFromString = (function () { var data = Object.create(null); data['method'] = 0 /* Method */; data['function'] = 1 /* Function */; data['constructor'] = 2 /* Constructor */; data['field'] = 3 /* Field */; data['variable'] = 4 /* Variable */; data['class'] = 5 /* Class */; data['struct'] = 6 /* Struct */; data['interface'] = 7 /* Interface */; data['module'] = 8 /* Module */; data['property'] = 9 /* Property */; data['event'] = 10 /* Event */; data['operator'] = 11 /* Operator */; data['unit'] = 12 /* Unit */; data['value'] = 13 /* Value */; data['constant'] = 14 /* Constant */; data['enum'] = 15 /* Enum */; data['enum-member'] = 16 /* EnumMember */; data['enumMember'] = 16 /* EnumMember */; data['keyword'] = 17 /* Keyword */; data['snippet'] = 25 /* Snippet */; data['text'] = 18 /* Text */; data['color'] = 19 /* Color */; data['file'] = 20 /* File */; data['reference'] = 21 /* Reference */; data['customcolor'] = 22 /* Customcolor */; data['folder'] = 23 /* Folder */; data['type-parameter'] = 24 /* TypeParameter */; data['typeParameter'] = 24 /* TypeParameter */; return function (value, strict) { var res = data[value]; if (typeof res === 'undefined' && !strict) { res = 9 /* Property */; } return res; }; })(); 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) { var byName = new Map(); byName.set('file', 0 /* File */); byName.set('module', 1 /* Module */); byName.set('namespace', 2 /* Namespace */); byName.set('package', 3 /* Package */); byName.set('class', 4 /* Class */); byName.set('method', 5 /* Method */); byName.set('property', 6 /* Property */); byName.set('field', 7 /* Field */); byName.set('constructor', 8 /* Constructor */); byName.set('enum', 9 /* Enum */); byName.set('interface', 10 /* Interface */); byName.set('function', 11 /* Function */); byName.set('variable', 12 /* Variable */); byName.set('constant', 13 /* Constant */); byName.set('string', 14 /* String */); byName.set('number', 15 /* Number */); byName.set('boolean', 16 /* Boolean */); byName.set('array', 17 /* Array */); byName.set('object', 18 /* Object */); byName.set('key', 19 /* Key */); byName.set('null', 20 /* Null */); byName.set('enum-member', 21 /* EnumMember */); byName.set('struct', 22 /* Struct */); byName.set('event', 23 /* Event */); byName.set('operator', 24 /* Operator */); byName.set('type-parameter', 25 /* TypeParameter */); var byKind = new Map(); byKind.set(0 /* File */, 'file'); byKind.set(1 /* Module */, 'module'); byKind.set(2 /* Namespace */, 'namespace'); byKind.set(3 /* Package */, 'package'); byKind.set(4 /* Class */, 'class'); byKind.set(5 /* Method */, 'method'); byKind.set(6 /* Property */, 'property'); byKind.set(7 /* Field */, 'field'); byKind.set(8 /* Constructor */, 'constructor'); byKind.set(9 /* Enum */, 'enum'); byKind.set(10 /* Interface */, 'interface'); byKind.set(11 /* Function */, 'function'); byKind.set(12 /* Variable */, 'variable'); byKind.set(13 /* Constant */, 'constant'); byKind.set(14 /* String */, 'string'); byKind.set(15 /* Number */, 'number'); byKind.set(16 /* Boolean */, 'boolean'); byKind.set(17 /* Array */, 'array'); byKind.set(18 /* Object */, 'object'); byKind.set(19 /* Key */, 'key'); byKind.set(20 /* Null */, 'null'); byKind.set(21 /* EnumMember */, 'enum-member'); byKind.set(22 /* Struct */, 'struct'); byKind.set(23 /* Event */, 'event'); byKind.set(24 /* Operator */, 'operator'); byKind.set(25 /* TypeParameter */, 'type-parameter'); /** * @internal */ function fromString(value) { return byName.get(value); } SymbolKinds.fromString = fromString; /** * @internal */ function toString(kind) { return byKind.get(kind); } SymbolKinds.toString = toString; /** * @internal */ function toCssClassName(kind, inline) { return "codicon " + (inline ? 'inline' : 'block') + " codicon-symbol-" + (byKind.get(kind) || 'property'); } SymbolKinds.toCssClassName = toCssClassName; })(SymbolKinds = exports.SymbolKinds || (exports.SymbolKinds = {})); var FoldingRangeKind = /** @class */ (function () { /** * Creates a new [FoldingRangeKind](#FoldingRangeKind). * * @param value of the kind. */ function FoldingRangeKind(value) { this.value = value; } /** * 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'); return FoldingRangeKind; }()); exports.FoldingRangeKind = FoldingRangeKind; /** * @internal */ var WorkspaceFileEdit; (function (WorkspaceFileEdit) { /** * @internal */ function is(thing) { return types_1.isObject(thing) && (Boolean(thing.newUri) || Boolean(thing.oldUri)); } WorkspaceFileEdit.is = is; })(WorkspaceFileEdit = exports.WorkspaceFileEdit || (exports.WorkspaceFileEdit = {})); /** * @internal */ var WorkspaceTextEdit; (function (WorkspaceTextEdit) { /** * @internal */ function is(thing) { return types_1.isObject(thing) && uri_1.URI.isUri(thing.resource) && types_1.isObject(thing.edit); } WorkspaceTextEdit.is = is; })(WorkspaceTextEdit = exports.WorkspaceTextEdit || (exports.WorkspaceTextEdit = {})); // --- 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.SignatureHelpProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry(); /** * @internal */ exports.HoverProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry(); /** * @internal */ exports.DocumentSymbolProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry(); /** * @internal */ exports.DocumentHighlightProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry(); /** * @internal */ exports.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.CodeActionProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry(); /** * @internal */ exports.DocumentFormattingEditProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry(); /** * @internal */ exports.DocumentRangeFormattingEditProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry(); /** * @internal */ exports.OnTypeFormattingEditProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry(); /** * @internal */ exports.LinkProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry(); /** * @internal */ exports.ColorProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry(); /** * @internal */ exports.SelectionRangeRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry(); /** * @internal */ exports.FoldingRangeProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry(); /** * @internal */ exports.DocumentSemanticTokensProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry(); /** * @internal */ exports.DocumentRangeSemanticTokensProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry(); /** * @internal */ exports.TokenizationRegistry = new tokenizationRegistry_1.TokenizationRegistryImpl(); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[93/*vs/editor/common/core/lineTokens*/], __M([0/*require*/,1/*exports*/,17/*vs/editor/common/modes*/]), function (require, exports, modes_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LineTokens = /** @class */ (function () { function LineTokens(tokens, text) { this._tokens = tokens; this._tokensCount = (this._tokens.length >>> 1); this._text = text; } LineTokens.prototype.equals = function (other) { if (other instanceof LineTokens) { return this.slicedEquals(other, 0, this._tokensCount); } return false; }; LineTokens.prototype.slicedEquals = function (other, sliceFromTokenIndex, sliceTokenCount) { if (this._text !== other._text) { return false; } if (this._tokensCount !== other._tokensCount) { return false; } var from = (sliceFromTokenIndex << 1); var to = from + (sliceTokenCount << 1); for (var i = from; i < to; i++) { if (this._tokens[i] !== other._tokens[i]) { return false; } } return true; }; LineTokens.prototype.getLineContent = function () { return this._text; }; LineTokens.prototype.getCount = function () { return this._tokensCount; }; LineTokens.prototype.getStartOffset = function (tokenIndex) { if (tokenIndex > 0) { return this._tokens[(tokenIndex - 1) << 1]; } return 0; }; LineTokens.prototype.getMetadata = function (tokenIndex) { var metadata = this._tokens[(tokenIndex << 1) + 1]; return metadata; }; LineTokens.prototype.getLanguageId = function (tokenIndex) { var metadata = this._tokens[(tokenIndex << 1) + 1]; return modes_1.TokenMetadata.getLanguageId(metadata); }; LineTokens.prototype.getStandardTokenType = function (tokenIndex) { var metadata = this._tokens[(tokenIndex << 1) + 1]; return modes_1.TokenMetadata.getTokenType(metadata); }; LineTokens.prototype.getForeground = function (tokenIndex) { var metadata = this._tokens[(tokenIndex << 1) + 1]; return modes_1.TokenMetadata.getForeground(metadata); }; LineTokens.prototype.getClassName = function (tokenIndex) { var metadata = this._tokens[(tokenIndex << 1) + 1]; return modes_1.TokenMetadata.getClassNameFromMetadata(metadata); }; LineTokens.prototype.getInlineStyle = function (tokenIndex, colorMap) { var metadata = this._tokens[(tokenIndex << 1) + 1]; return modes_1.TokenMetadata.getInlineStyleFromMetadata(metadata, colorMap); }; LineTokens.prototype.getEndOffset = function (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. */ LineTokens.prototype.findTokenIndexAtOffset = function (offset) { return LineTokens.findIndexInTokensArray(this._tokens, offset); }; LineTokens.prototype.inflate = function () { return this; }; LineTokens.prototype.sliceAndInflate = function (startOffset, endOffset, deltaOffset) { return new SlicedLineTokens(this, startOffset, endOffset, deltaOffset); }; LineTokens.convertToEndOffset = function (tokens, lineTextLength) { var tokenCount = (tokens.length >>> 1); var lastTokenIndex = tokenCount - 1; for (var tokenIndex = 0; tokenIndex < lastTokenIndex; tokenIndex++) { tokens[tokenIndex << 1] = tokens[(tokenIndex + 1) << 1]; } tokens[lastTokenIndex << 1] = lineTextLength; }; LineTokens.findIndexInTokensArray = function (tokens, desiredIndex) { if (tokens.length <= 2) { return 0; } var low = 0; var high = (tokens.length >>> 1) - 1; while (low < high) { var mid = low + Math.floor((high - low) / 2); var 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; }; return LineTokens; }()); exports.LineTokens = LineTokens; var SlicedLineTokens = /** @class */ (function () { function SlicedLineTokens(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 (var i = this._firstTokenIndex, len = source.getCount(); i < len; i++) { var tokenStartOffset = source.getStartOffset(i); if (tokenStartOffset >= endOffset) { break; } this._tokensCount++; } } SlicedLineTokens.prototype.equals = function (other) { if (other instanceof SlicedLineTokens) { return (this._startOffset === other._startOffset && this._endOffset === other._endOffset && this._deltaOffset === other._deltaOffset && this._source.slicedEquals(other._source, this._firstTokenIndex, this._tokensCount)); } return false; }; SlicedLineTokens.prototype.getCount = function () { return this._tokensCount; }; SlicedLineTokens.prototype.getForeground = function (tokenIndex) { return this._source.getForeground(this._firstTokenIndex + tokenIndex); }; SlicedLineTokens.prototype.getEndOffset = function (tokenIndex) { var tokenEndOffset = this._source.getEndOffset(this._firstTokenIndex + tokenIndex); return Math.min(this._endOffset, tokenEndOffset) - this._startOffset + this._deltaOffset; }; SlicedLineTokens.prototype.getClassName = function (tokenIndex) { return this._source.getClassName(this._firstTokenIndex + tokenIndex); }; SlicedLineTokens.prototype.getInlineStyle = function (tokenIndex, colorMap) { return this._source.getInlineStyle(this._firstTokenIndex + tokenIndex, colorMap); }; SlicedLineTokens.prototype.findTokenIndexAtOffset = function (offset) { return this._source.findTokenIndexAtOffset(offset + this._startOffset - this._deltaOffset) - this._firstTokenIndex; }; return SlicedLineTokens; }()); exports.SlicedLineTokens = SlicedLineTokens; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[157/*vs/editor/common/model/tokensStore*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,93/*vs/editor/common/core/lineTokens*/,13/*vs/editor/common/core/position*/,17/*vs/editor/common/modes*/]), function (require, exports, arrays, lineTokens_1, position_1, modes_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function countEOL(text) { var eolCount = 0; var firstLineLength = 0; var lastLineStart = 0; for (var i = 0, len = text.length; i < len; i++) { var 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 i++; // skip \n } else { // \r... case } lastLineStart = i + 1; } else if (chr === 10 /* LineFeed */) { if (eolCount === 0) { firstLineLength = i; } eolCount++; lastLineStart = i + 1; } } if (eolCount === 0) { firstLineLength = text.length; } return [eolCount, firstLineLength, text.length - lastLineStart]; } exports.countEOL = countEOL; function getDefaultMetadata(topLevelLanguageId) { return ((topLevelLanguageId << 0 /* LANGUAGEID_OFFSET */) | (0 /* Other */ << 8 /* TOKEN_TYPE_OFFSET */) | (0 /* None */ << 11 /* FONT_STYLE_OFFSET */) | (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */) | (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0; } var EMPTY_LINE_TOKENS = (new Uint32Array(0)).buffer; var MultilineTokensBuilder = /** @class */ (function () { function MultilineTokensBuilder() { this.tokens = []; } MultilineTokensBuilder.prototype.add = function (lineNumber, lineTokens) { if (this.tokens.length > 0) { var last = this.tokens[this.tokens.length - 1]; var lastLineNumber = last.startLineNumber + last.tokens.length - 1; if (lastLineNumber + 1 === lineNumber) { // append last.tokens.push(lineTokens); return; } } this.tokens.push(new MultilineTokens(lineNumber, [lineTokens])); }; return MultilineTokensBuilder; }()); exports.MultilineTokensBuilder = MultilineTokensBuilder; var SparseEncodedTokens = /** @class */ (function () { function SparseEncodedTokens(tokens) { this._tokens = tokens; this._tokenCount = tokens.length / 4; } SparseEncodedTokens.prototype.getMaxDeltaLine = function () { var tokenCount = this.getTokenCount(); if (tokenCount === 0) { return -1; } return this.getDeltaLine(tokenCount - 1); }; SparseEncodedTokens.prototype.getTokenCount = function () { return this._tokenCount; }; SparseEncodedTokens.prototype.getDeltaLine = function (tokenIndex) { return this._tokens[4 * tokenIndex]; }; SparseEncodedTokens.prototype.getStartCharacter = function (tokenIndex) { return this._tokens[4 * tokenIndex + 1]; }; SparseEncodedTokens.prototype.getEndCharacter = function (tokenIndex) { return this._tokens[4 * tokenIndex + 2]; }; SparseEncodedTokens.prototype.getMetadata = function (tokenIndex) { return this._tokens[4 * tokenIndex + 3]; }; SparseEncodedTokens.prototype.clear = function () { this._tokenCount = 0; }; SparseEncodedTokens.prototype.acceptDeleteRange = function (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 // var tokens = this._tokens; var tokenCount = this._tokenCount; var deletedLineCount = (endDeltaLine - startDeltaLine); var newTokenCount = 0; var hasDeletedTokens = false; for (var i = 0; i < tokenCount; i++) { var srcOffset = 4 * i; var tokenDeltaLine = tokens[srcOffset]; var tokenStartCharacter = tokens[srcOffset + 1]; var tokenEndCharacter = tokens[srcOffset + 2]; var 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!"); } var destOffset = 4 * newTokenCount; tokens[destOffset] = tokenDeltaLine; tokens[destOffset + 1] = tokenStartCharacter; tokens[destOffset + 2] = tokenEndCharacter; tokens[destOffset + 3] = tokenMetadata; newTokenCount++; } this._tokenCount = newTokenCount; }; SparseEncodedTokens.prototype.acceptInsertText = function (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 // | ----------- // var isInsertingPreciselyOneWordCharacter = (eolCount === 0 && firstLineLength === 1 && ((firstCharCode >= 48 /* Digit0 */ && firstCharCode <= 57 /* Digit9 */) || (firstCharCode >= 65 /* A */ && firstCharCode <= 90 /* Z */) || (firstCharCode >= 97 /* a */ && firstCharCode <= 122 /* z */))); var tokens = this._tokens; var tokenCount = this._tokenCount; for (var i = 0; i < tokenCount; i++) { var offset = 4 * i; var tokenDeltaLine = tokens[offset]; var tokenStartCharacter = tokens[offset + 1]; var 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 { var tokenLength = tokenEndCharacter - tokenStartCharacter; tokenStartCharacter = lastLineLength + (tokenStartCharacter - character); tokenEndCharacter = tokenStartCharacter + tokenLength; } } else { tokenDeltaLine += eolCount; } } tokens[offset] = tokenDeltaLine; tokens[offset + 1] = tokenStartCharacter; tokens[offset + 2] = tokenEndCharacter; } }; return SparseEncodedTokens; }()); exports.SparseEncodedTokens = SparseEncodedTokens; var LineTokens2 = /** @class */ (function () { function LineTokens2(actual, startTokenIndex, endTokenIndex) { this._actual = actual; this._startTokenIndex = startTokenIndex; this._endTokenIndex = endTokenIndex; } LineTokens2.prototype.getCount = function () { return this._endTokenIndex - this._startTokenIndex + 1; }; LineTokens2.prototype.getStartCharacter = function (tokenIndex) { return this._actual.getStartCharacter(this._startTokenIndex + tokenIndex); }; LineTokens2.prototype.getEndCharacter = function (tokenIndex) { return this._actual.getEndCharacter(this._startTokenIndex + tokenIndex); }; LineTokens2.prototype.getMetadata = function (tokenIndex) { return this._actual.getMetadata(this._startTokenIndex + tokenIndex); }; return LineTokens2; }()); exports.LineTokens2 = LineTokens2; var MultilineTokens2 = /** @class */ (function () { function MultilineTokens2(startLineNumber, tokens) { this.startLineNumber = startLineNumber; this.tokens = tokens; this.endLineNumber = this.startLineNumber + this.tokens.getMaxDeltaLine(); } MultilineTokens2.prototype._updateEndLineNumber = function () { this.endLineNumber = this.startLineNumber + this.tokens.getMaxDeltaLine(); }; MultilineTokens2.prototype.getLineTokens = function (lineNumber) { if (this.startLineNumber <= lineNumber && lineNumber <= this.endLineNumber) { var findResult = MultilineTokens2._findTokensWithLine(this.tokens, lineNumber - this.startLineNumber); if (findResult) { var startTokenIndex = findResult[0], endTokenIndex = findResult[1]; return new LineTokens2(this.tokens, startTokenIndex, endTokenIndex); } } return null; }; MultilineTokens2._findTokensWithLine = function (tokens, deltaLine) { var low = 0; var high = tokens.getTokenCount() - 1; while (low < high) { var mid = low + Math.floor((high - low) / 2); var midDeltaLine = tokens.getDeltaLine(mid); if (midDeltaLine < deltaLine) { low = mid + 1; } else if (midDeltaLine > deltaLine) { high = mid - 1; } else { var min = mid; while (min > low && tokens.getDeltaLine(min - 1) === deltaLine) { min--; } var max = mid; while (max < high && tokens.getDeltaLine(max + 1) === deltaLine) { max++; } return [min, max]; } } if (tokens.getDeltaLine(low) === deltaLine) { return [low, low]; } return null; }; MultilineTokens2.prototype.applyEdit = function (range, text) { var _a = countEOL(text), eolCount = _a[0], firstLineLength = _a[1], lastLineLength = _a[2]; this.acceptEdit(range, eolCount, firstLineLength, lastLineLength, text.length > 0 ? text.charCodeAt(0) : 0 /* Null */); }; MultilineTokens2.prototype.acceptEdit = function (range, eolCount, firstLineLength, lastLineLength, firstCharCode) { this._acceptDeleteRange(range); this._acceptInsertText(new position_1.Position(range.startLineNumber, range.startColumn), eolCount, firstLineLength, lastLineLength, firstCharCode); this._updateEndLineNumber(); }; MultilineTokens2.prototype._acceptDeleteRange = function (range) { if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) { // Nothing to delete return; } var firstLineIndex = range.startLineNumber - this.startLineNumber; var lastLineIndex = range.endLineNumber - this.startLineNumber; if (lastLineIndex < 0) { // this deletion occurs entirely before this block, so we only need to adjust line numbers var deletedLinesCount = lastLineIndex - firstLineIndex; this.startLineNumber -= deletedLinesCount; return; } var 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) { var 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); } }; MultilineTokens2.prototype._acceptInsertText = function (position, eolCount, firstLineLength, lastLineLength, firstCharCode) { if (eolCount === 0 && firstLineLength === 0) { // Nothing to insert return; } var 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; } var 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); }; return MultilineTokens2; }()); exports.MultilineTokens2 = MultilineTokens2; var MultilineTokens = /** @class */ (function () { function MultilineTokens(startLineNumber, tokens) { this.startLineNumber = startLineNumber; this.tokens = tokens; } return MultilineTokens; }()); exports.MultilineTokens = MultilineTokens; function toUint32Array(arr) { if (arr instanceof Uint32Array) { return arr; } else { return new Uint32Array(arr); } } var TokensStore2 = /** @class */ (function () { function TokensStore2() { this._pieces = []; } TokensStore2.prototype.flush = function () { this._pieces = []; }; TokensStore2.prototype.set = function (pieces) { this._pieces = pieces || []; }; TokensStore2.prototype.addSemanticTokens = function (lineNumber, aTokens) { var pieces = this._pieces; if (pieces.length === 0) { return aTokens; } var pieceIndex = TokensStore2._findFirstPieceWithLine(pieces, lineNumber); var bTokens = this._pieces[pieceIndex].getLineTokens(lineNumber); if (!bTokens) { return aTokens; } var aLen = aTokens.getCount(); var bLen = bTokens.getCount(); var aIndex = 0; var result = [], resultLen = 0; for (var bIndex = 0; bIndex < bLen; bIndex++) { var bStartCharacter = bTokens.getStartCharacter(bIndex); var bEndCharacter = bTokens.getEndCharacter(bIndex); var bMetadata = bTokens.getMetadata(bIndex); var bMask = (((bMetadata & 1 /* SEMANTIC_USE_ITALIC */) ? 2048 /* ITALIC_MASK */ : 0) | ((bMetadata & 2 /* SEMANTIC_USE_BOLD */) ? 4096 /* BOLD_MASK */ : 0) | ((bMetadata & 4 /* SEMANTIC_USE_UNDERLINE */) ? 8192 /* UNDERLINE_MASK */ : 0) | ((bMetadata & 8 /* SEMANTIC_USE_FOREGROUND */) ? 8372224 /* FOREGROUND_MASK */ : 0) | ((bMetadata & 16 /* SEMANTIC_USE_BACKGROUND */) ? 4286578688 /* BACKGROUND_MASK */ : 0)) >>> 0; var aMask = (~bMask) >>> 0; // push any token from `a` that is before `b` while (aIndex < aLen && aTokens.getEndOffset(aIndex) <= bStartCharacter) { result[resultLen++] = aTokens.getEndOffset(aIndex); result[resultLen++] = aTokens.getMetadata(aIndex); aIndex++; } // push the token from `a` if it intersects the token from `b` if (aIndex < aLen && aTokens.getStartOffset(aIndex) < bStartCharacter) { result[resultLen++] = bStartCharacter; result[resultLen++] = aTokens.getMetadata(aIndex); } // skip any tokens from `a` that are contained inside `b` while (aIndex < aLen && aTokens.getEndOffset(aIndex) < bEndCharacter) { result[resultLen++] = aTokens.getEndOffset(aIndex); result[resultLen++] = (aTokens.getMetadata(aIndex) & aMask) | (bMetadata & bMask); aIndex++; } if (aIndex < aLen && aTokens.getEndOffset(aIndex) === bEndCharacter) { // `a` ends exactly at the same spot as `b`! result[resultLen++] = aTokens.getEndOffset(aIndex); result[resultLen++] = (aTokens.getMetadata(aIndex) & aMask) | (bMetadata & bMask); aIndex++; } else { var aMergeIndex = Math.min(Math.max(0, aIndex - 1), aLen - 1); // push the token from `b` result[resultLen++] = bEndCharacter; result[resultLen++] = (aTokens.getMetadata(aMergeIndex) & aMask) | (bMetadata & bMask); } } // push the remaining tokens from `a` while (aIndex < aLen) { result[resultLen++] = aTokens.getEndOffset(aIndex); result[resultLen++] = aTokens.getMetadata(aIndex); aIndex++; } return new lineTokens_1.LineTokens(new Uint32Array(result), aTokens.getLineContent()); }; TokensStore2._findFirstPieceWithLine = function (pieces, lineNumber) { var low = 0; var high = pieces.length - 1; while (low < high) { var mid = low + Math.floor((high - low) / 2); if (pieces[mid].endLineNumber < lineNumber) { low = mid + 1; } else if (pieces[mid].startLineNumber > lineNumber) { high = mid - 1; } else { while (mid > low && pieces[mid - 1].startLineNumber <= lineNumber && lineNumber <= pieces[mid - 1].endLineNumber) { mid--; } return mid; } } return low; }; //#region Editing TokensStore2.prototype.acceptEdit = function (range, eolCount, firstLineLength, lastLineLength, firstCharCode) { for (var _i = 0, _a = this._pieces; _i < _a.length; _i++) { var piece = _a[_i]; piece.acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode); } }; return TokensStore2; }()); exports.TokensStore2 = TokensStore2; var TokensStore = /** @class */ (function () { function TokensStore() { this._lineTokens = []; this._len = 0; } TokensStore.prototype.flush = function () { this._lineTokens = []; this._len = 0; }; TokensStore.prototype.getTokens = function (topLevelLanguageId, lineIndex, lineText) { var rawLineTokens = null; if (lineIndex < this._len) { rawLineTokens = this._lineTokens[lineIndex]; } if (rawLineTokens !== null && rawLineTokens !== EMPTY_LINE_TOKENS) { return new lineTokens_1.LineTokens(toUint32Array(rawLineTokens), lineText); } var lineTokens = new Uint32Array(2); lineTokens[0] = lineText.length; lineTokens[1] = getDefaultMetadata(topLevelLanguageId); return new lineTokens_1.LineTokens(lineTokens, lineText); }; TokensStore._massageTokens = function (topLevelLanguageId, lineTextLength, _tokens) { var tokens = _tokens ? toUint32Array(_tokens) : null; if (lineTextLength === 0) { var hasDifferentLanguageId = false; if (tokens && tokens.length > 1) { hasDifferentLanguageId = (modes_1.TokenMetadata.getLanguageId(tokens[1]) !== topLevelLanguageId); } if (!hasDifferentLanguageId) { return EMPTY_LINE_TOKENS; } } if (!tokens || tokens.length === 0) { var tokens_1 = new Uint32Array(2); tokens_1[0] = lineTextLength; tokens_1[1] = getDefaultMetadata(topLevelLanguageId); return tokens_1.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; }; TokensStore.prototype._ensureLine = function (lineIndex) { while (lineIndex >= this._len) { this._lineTokens[this._len] = null; this._len++; } }; TokensStore.prototype._deleteLines = function (start, deleteCount) { if (deleteCount === 0) { return; } if (start + deleteCount > this._len) { deleteCount = this._len - start; } this._lineTokens.splice(start, deleteCount); this._len -= deleteCount; }; TokensStore.prototype._insertLines = function (insertIndex, insertCount) { if (insertCount === 0) { return; } var lineTokens = []; for (var i = 0; i < insertCount; i++) { lineTokens[i] = null; } this._lineTokens = arrays.arrayInsert(this._lineTokens, insertIndex, lineTokens); this._len += insertCount; }; TokensStore.prototype.setTokens = function (topLevelLanguageId, lineIndex, lineTextLength, _tokens) { var tokens = TokensStore._massageTokens(topLevelLanguageId, lineTextLength, _tokens); this._ensureLine(lineIndex); this._lineTokens[lineIndex] = tokens; }; //#region Editing TokensStore.prototype.acceptEdit = function (range, eolCount, firstLineLength) { this._acceptDeleteRange(range); this._acceptInsertText(new position_1.Position(range.startLineNumber, range.startColumn), eolCount, firstLineLength); }; TokensStore.prototype._acceptDeleteRange = function (range) { var firstLineIndex = range.startLineNumber - 1; if (firstLineIndex >= this._len) { return; } if (range.startLineNumber === range.endLineNumber) { if (range.startColumn === range.endColumn) { // Nothing to delete return; } this._lineTokens[firstLineIndex] = TokensStore._delete(this._lineTokens[firstLineIndex], range.startColumn - 1, range.endColumn - 1); return; } this._lineTokens[firstLineIndex] = TokensStore._deleteEnding(this._lineTokens[firstLineIndex], range.startColumn - 1); var lastLineIndex = range.endLineNumber - 1; var lastLineTokens = null; if (lastLineIndex < this._len) { lastLineTokens = TokensStore._deleteBeginning(this._lineTokens[lastLineIndex], range.endColumn - 1); } // Take remaining text on last line and append it to remaining text on first line this._lineTokens[firstLineIndex] = TokensStore._append(this._lineTokens[firstLineIndex], lastLineTokens); // Delete middle lines this._deleteLines(range.startLineNumber, range.endLineNumber - range.startLineNumber); }; TokensStore.prototype._acceptInsertText = function (position, eolCount, firstLineLength) { if (eolCount === 0 && firstLineLength === 0) { // Nothing to insert return; } var lineIndex = position.lineNumber - 1; if (lineIndex >= this._len) { return; } if (eolCount === 0) { // Inserting text on one line this._lineTokens[lineIndex] = TokensStore._insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength); return; } this._lineTokens[lineIndex] = TokensStore._deleteEnding(this._lineTokens[lineIndex], position.column - 1); this._lineTokens[lineIndex] = TokensStore._insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength); this._insertLines(position.lineNumber, eolCount); }; TokensStore._deleteBeginning = function (lineTokens, toChIndex) { if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) { return lineTokens; } return TokensStore._delete(lineTokens, 0, toChIndex); }; TokensStore._deleteEnding = function (lineTokens, fromChIndex) { if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) { return lineTokens; } var tokens = toUint32Array(lineTokens); var lineTextLength = tokens[tokens.length - 2]; return TokensStore._delete(lineTokens, fromChIndex, lineTextLength); }; TokensStore._delete = function (lineTokens, fromChIndex, toChIndex) { if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS || fromChIndex === toChIndex) { return lineTokens; } var tokens = toUint32Array(lineTokens); var tokensCount = (tokens.length >>> 1); // special case: deleting everything if (fromChIndex === 0 && tokens[tokens.length - 2] === toChIndex) { return EMPTY_LINE_TOKENS; } var fromTokenIndex = lineTokens_1.LineTokens.findIndexInTokensArray(tokens, fromChIndex); var fromTokenStartOffset = (fromTokenIndex > 0 ? tokens[(fromTokenIndex - 1) << 1] : 0); var fromTokenEndOffset = tokens[fromTokenIndex << 1]; if (toChIndex < fromTokenEndOffset) { // the delete range is inside a single token var delta_1 = (toChIndex - fromChIndex); for (var i = fromTokenIndex; i < tokensCount; i++) { tokens[i << 1] -= delta_1; } return lineTokens; } var dest; var lastEnd; if (fromTokenStartOffset !== fromChIndex) { tokens[fromTokenIndex << 1] = fromChIndex; dest = ((fromTokenIndex + 1) << 1); lastEnd = fromChIndex; } else { dest = (fromTokenIndex << 1); lastEnd = fromTokenStartOffset; } var delta = (toChIndex - fromChIndex); for (var tokenIndex = fromTokenIndex + 1; tokenIndex < tokensCount; tokenIndex++) { var 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; } var tmp = new Uint32Array(dest); tmp.set(tokens.subarray(0, dest), 0); return tmp.buffer; }; TokensStore._append = function (lineTokens, _otherTokens) { if (_otherTokens === EMPTY_LINE_TOKENS) { return lineTokens; } if (lineTokens === EMPTY_LINE_TOKENS) { return _otherTokens; } if (lineTokens === null) { return lineTokens; } if (_otherTokens === null) { // cannot determine combined line length... return null; } var myTokens = toUint32Array(lineTokens); var otherTokens = toUint32Array(_otherTokens); var otherTokensCount = (otherTokens.length >>> 1); var result = new Uint32Array(myTokens.length + otherTokens.length); result.set(myTokens, 0); var dest = myTokens.length; var delta = myTokens[myTokens.length - 2]; for (var i = 0; i < otherTokensCount; i++) { result[dest++] = otherTokens[(i << 1)] + delta; result[dest++] = otherTokens[(i << 1) + 1]; } return result.buffer; }; TokensStore._insert = function (lineTokens, chIndex, textLength) { if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) { // nothing to do return lineTokens; } var tokens = toUint32Array(lineTokens); var tokensCount = (tokens.length >>> 1); var fromTokenIndex = lineTokens_1.LineTokens.findIndexInTokensArray(tokens, chIndex); if (fromTokenIndex > 0) { var fromTokenStartOffset = tokens[(fromTokenIndex - 1) << 1]; if (fromTokenStartOffset === chIndex) { fromTokenIndex--; } } for (var tokenIndex = fromTokenIndex; tokenIndex < tokensCount; tokenIndex++) { tokens[tokenIndex << 1] += textLength; } return lineTokens; }; return TokensStore; }()); exports.TokensStore = TokensStore; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[63/*vs/editor/common/modes/nullMode*/], __M([0/*require*/,1/*exports*/,107/*vs/editor/common/core/token*/,17/*vs/editor/common/modes*/]), function (require, exports, token_1, modes_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var NullStateImpl = /** @class */ (function () { function NullStateImpl() { } NullStateImpl.prototype.clone = function () { return this; }; NullStateImpl.prototype.equals = function (other) { return (this === other); }; return NullStateImpl; }()); exports.NULL_STATE = new NullStateImpl(); exports.NULL_MODE_ID = 'vs.editor.nullMode'; exports.NULL_LANGUAGE_IDENTIFIER = new modes_1.LanguageIdentifier(exports.NULL_MODE_ID, 0 /* Null */); function nullTokenize(modeId, buffer, state, deltaOffset) { return new token_1.TokenizationResult([new token_1.Token(deltaOffset, '', modeId)], state); } exports.nullTokenize = nullTokenize; function nullTokenize2(languageId, buffer, state, deltaOffset) { var tokens = new Uint32Array(2); tokens[0] = deltaOffset; tokens[1] = ((languageId << 0 /* LANGUAGEID_OFFSET */) | (0 /* Other */ << 8 /* TOKEN_TYPE_OFFSET */) | (0 /* None */ << 11 /* FONT_STYLE_OFFSET */) | (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */) | (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0; return new token_1.TokenizationResult2(tokens, state === null ? exports.NULL_STATE : state); } exports.nullTokenize2 = nullTokenize2; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[482/*vs/editor/common/model/textModelTokens*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,10/*vs/base/common/errors*/,93/*vs/editor/common/core/lineTokens*/,13/*vs/editor/common/core/position*/,17/*vs/editor/common/modes*/,63/*vs/editor/common/modes/nullMode*/,2/*vs/base/common/lifecycle*/,132/*vs/base/common/stopwatch*/,157/*vs/editor/common/model/tokensStore*/,16/*vs/base/common/platform*/]), function (require, exports, arrays, errors_1, lineTokens_1, position_1, modes_1, nullMode_1, lifecycle_1, stopwatch_1, tokensStore_1, platform) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var TokenizationStateStore = /** @class */ (function () { function TokenizationStateStore() { this._beginState = []; this._valid = []; this._len = 0; this._invalidLineStartIndex = 0; } TokenizationStateStore.prototype._reset = function (initialState) { this._beginState = []; this._valid = []; this._len = 0; this._invalidLineStartIndex = 0; if (initialState) { this._setBeginState(0, initialState); } }; TokenizationStateStore.prototype.flush = function (initialState) { this._reset(initialState); }; Object.defineProperty(TokenizationStateStore.prototype, "invalidLineStartIndex", { get: function () { return this._invalidLineStartIndex; }, enumerable: true, configurable: true }); TokenizationStateStore.prototype._invalidateLine = function (lineIndex) { if (lineIndex < this._len) { this._valid[lineIndex] = false; } if (lineIndex < this._invalidLineStartIndex) { this._invalidLineStartIndex = lineIndex; } }; TokenizationStateStore.prototype._isValid = function (lineIndex) { if (lineIndex < this._len) { return this._valid[lineIndex]; } return false; }; TokenizationStateStore.prototype.getBeginState = function (lineIndex) { if (lineIndex < this._len) { return this._beginState[lineIndex]; } return null; }; TokenizationStateStore.prototype._ensureLine = function (lineIndex) { while (lineIndex >= this._len) { this._beginState[this._len] = null; this._valid[this._len] = false; this._len++; } }; TokenizationStateStore.prototype._deleteLines = function (start, deleteCount) { if (deleteCount === 0) { return; } if (start + deleteCount > this._len) { deleteCount = this._len - start; } this._beginState.splice(start, deleteCount); this._valid.splice(start, deleteCount); this._len -= deleteCount; }; TokenizationStateStore.prototype._insertLines = function (insertIndex, insertCount) { if (insertCount === 0) { return; } var beginState = []; var valid = []; for (var i = 0; i < insertCount; i++) { beginState[i] = null; valid[i] = false; } this._beginState = arrays.arrayInsert(this._beginState, insertIndex, beginState); this._valid = arrays.arrayInsert(this._valid, insertIndex, valid); this._len += insertCount; }; TokenizationStateStore.prototype._setValid = function (lineIndex, valid) { this._ensureLine(lineIndex); this._valid[lineIndex] = valid; }; TokenizationStateStore.prototype._setBeginState = function (lineIndex, beginState) { this._ensureLine(lineIndex); this._beginState[lineIndex] = beginState; }; TokenizationStateStore.prototype.setEndState = function (linesLength, lineIndex, endState) { this._setValid(lineIndex, true); this._invalidLineStartIndex = lineIndex + 1; // Check if this was the last line if (lineIndex === linesLength - 1) { return; } // Check if the end state has changed var previousEndState = this.getBeginState(lineIndex + 1); if (previousEndState === null || !endState.equals(previousEndState)) { this._setBeginState(lineIndex + 1, endState); this._invalidateLine(lineIndex + 1); return; } // Perhaps we can skip tokenizing some lines... var i = lineIndex + 1; while (i < linesLength) { if (!this._isValid(i)) { break; } i++; } this._invalidLineStartIndex = i; }; TokenizationStateStore.prototype.setFakeTokens = function (lineIndex) { this._setValid(lineIndex, false); }; //#region Editing TokenizationStateStore.prototype.applyEdits = function (range, eolCount) { var deletingLinesCnt = range.endLineNumber - range.startLineNumber; var insertingLinesCnt = eolCount; var editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt); for (var j = editingLinesCnt; j >= 0; j--) { this._invalidateLine(range.startLineNumber + j - 1); } this._acceptDeleteRange(range); this._acceptInsertText(new position_1.Position(range.startLineNumber, range.startColumn), eolCount); }; TokenizationStateStore.prototype._acceptDeleteRange = function (range) { var firstLineIndex = range.startLineNumber - 1; if (firstLineIndex >= this._len) { return; } this._deleteLines(range.startLineNumber, range.endLineNumber - range.startLineNumber); }; TokenizationStateStore.prototype._acceptInsertText = function (position, eolCount) { var lineIndex = position.lineNumber - 1; if (lineIndex >= this._len) { return; } this._insertLines(position.lineNumber, eolCount); }; return TokenizationStateStore; }()); exports.TokenizationStateStore = TokenizationStateStore; var TextModelTokenization = /** @class */ (function (_super) { __extends(TextModelTokenization, _super); function TextModelTokenization(textModel) { var _this = _super.call(this) || this; _this._isDisposed = false; _this._textModel = textModel; _this._tokenizationStateStore = new TokenizationStateStore(); _this._tokenizationSupport = null; _this._register(modes_1.TokenizationRegistry.onDidChange(function (e) { var languageIdentifier = _this._textModel.getLanguageIdentifier(); if (e.changedLanguages.indexOf(languageIdentifier.language) === -1) { return; } _this._resetTokenizationState(); _this._textModel.clearTokens(); })); _this._register(_this._textModel.onDidChangeRawContentFast(function (e) { if (e.containsEvent(1 /* Flush */)) { _this._resetTokenizationState(); return; } })); _this._register(_this._textModel.onDidChangeContentFast(function (e) { for (var i = 0, len = e.changes.length; i < len; i++) { var change = e.changes[i]; var eolCount = tokensStore_1.countEOL(change.text)[0]; _this._tokenizationStateStore.applyEdits(change.range, eolCount); } _this._beginBackgroundTokenization(); })); _this._register(_this._textModel.onDidChangeAttached(function () { _this._beginBackgroundTokenization(); })); _this._register(_this._textModel.onDidChangeLanguage(function () { _this._resetTokenizationState(); _this._textModel.clearTokens(); })); _this._resetTokenizationState(); return _this; } TextModelTokenization.prototype.dispose = function () { this._isDisposed = true; _super.prototype.dispose.call(this); }; TextModelTokenization.prototype._resetTokenizationState = function () { var _a = initializeTokenization(this._textModel), tokenizationSupport = _a[0], initialState = _a[1]; this._tokenizationSupport = tokenizationSupport; this._tokenizationStateStore.flush(initialState); this._beginBackgroundTokenization(); }; TextModelTokenization.prototype._beginBackgroundTokenization = function () { var _this = this; if (this._textModel.isAttachedToEditor() && this._hasLinesToTokenize()) { platform.setImmediate(function () { if (_this._isDisposed) { // disposed in the meantime return; } _this._revalidateTokensNow(); }); } }; TextModelTokenization.prototype._revalidateTokensNow = function (toLineNumber) { if (toLineNumber === void 0) { toLineNumber = this._textModel.getLineCount(); } var MAX_ALLOWED_TIME = 1; var builder = new tokensStore_1.MultilineTokensBuilder(); var sw = stopwatch_1.StopWatch.create(false); while (this._hasLinesToTokenize()) { if (sw.elapsed() > MAX_ALLOWED_TIME) { // Stop if MAX_ALLOWED_TIME is reached break; } var tokenizedLineNumber = this._tokenizeOneInvalidLine(builder); if (tokenizedLineNumber >= toLineNumber) { break; } } this._beginBackgroundTokenization(); this._textModel.setTokens(builder.tokens); }; TextModelTokenization.prototype.tokenizeViewport = function (startLineNumber, endLineNumber) { var builder = new tokensStore_1.MultilineTokensBuilder(); this._tokenizeViewport(builder, startLineNumber, endLineNumber); this._textModel.setTokens(builder.tokens); }; TextModelTokenization.prototype.reset = function () { this._resetTokenizationState(); this._textModel.clearTokens(); }; TextModelTokenization.prototype.forceTokenization = function (lineNumber) { var builder = new tokensStore_1.MultilineTokensBuilder(); this._updateTokensUntilLine(builder, lineNumber); this._textModel.setTokens(builder.tokens); }; TextModelTokenization.prototype.isCheapToTokenize = function (lineNumber) { if (!this._tokenizationSupport) { return true; } var 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; }; TextModelTokenization.prototype._hasLinesToTokenize = function () { if (!this._tokenizationSupport) { return false; } return (this._tokenizationStateStore.invalidLineStartIndex < this._textModel.getLineCount()); }; TextModelTokenization.prototype._tokenizeOneInvalidLine = function (builder) { if (!this._hasLinesToTokenize()) { return this._textModel.getLineCount() + 1; } var lineNumber = this._tokenizationStateStore.invalidLineStartIndex + 1; this._updateTokensUntilLine(builder, lineNumber); return lineNumber; }; TextModelTokenization.prototype._updateTokensUntilLine = function (builder, lineNumber) { if (!this._tokenizationSupport) { return; } var languageIdentifier = this._textModel.getLanguageIdentifier(); var linesLength = this._textModel.getLineCount(); var endLineIndex = lineNumber - 1; // Validate all states up to and including endLineIndex for (var lineIndex = this._tokenizationStateStore.invalidLineStartIndex; lineIndex <= endLineIndex; lineIndex++) { var text = this._textModel.getLineContent(lineIndex + 1); var lineStartState = this._tokenizationStateStore.getBeginState(lineIndex); var r = safeTokenize(languageIdentifier, this._tokenizationSupport, text, 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 } }; TextModelTokenization.prototype._tokenizeViewport = function (builder, startLineNumber, endLineNumber) { if (!this._tokenizationSupport) { // nothing to do return; } if (endLineNumber <= this._tokenizationStateStore.invalidLineStartIndex) { // nothing to do return; } if (startLineNumber <= this._tokenizationStateStore.invalidLineStartIndex) { // tokenization has reached the viewport start... this._updateTokensUntilLine(builder, endLineNumber); return; } var nonWhitespaceColumn = this._textModel.getLineFirstNonWhitespaceColumn(startLineNumber); var fakeLines = []; var initialState = null; for (var i = startLineNumber - 1; nonWhitespaceColumn > 0 && i >= 1; i--) { var newNonWhitespaceIndex = this._textModel.getLineFirstNonWhitespaceColumn(i); if (newNonWhitespaceIndex === 0) { continue; } if (newNonWhitespaceIndex < nonWhitespaceColumn) { initialState = this._tokenizationStateStore.getBeginState(i - 1); if (initialState) { break; } fakeLines.push(this._textModel.getLineContent(i)); nonWhitespaceColumn = newNonWhitespaceIndex; } } if (!initialState) { initialState = this._tokenizationSupport.getInitialState(); } var languageIdentifier = this._textModel.getLanguageIdentifier(); var state = initialState; for (var i = fakeLines.length - 1; i >= 0; i--) { var r = safeTokenize(languageIdentifier, this._tokenizationSupport, fakeLines[i], state); state = r.endState; } for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { var text = this._textModel.getLineContent(lineNumber); var r = safeTokenize(languageIdentifier, this._tokenizationSupport, text, state); builder.add(lineNumber, r.tokens); this._tokenizationStateStore.setFakeTokens(lineNumber - 1); state = r.endState; } }; return TextModelTokenization; }(lifecycle_1.Disposable)); exports.TextModelTokenization = TextModelTokenization; function initializeTokenization(textModel) { var languageIdentifier = textModel.getLanguageIdentifier(); var tokenizationSupport = (textModel.isTooLargeForTokenization() ? null : modes_1.TokenizationRegistry.get(languageIdentifier.language)); var initialState = null; if (tokenizationSupport) { try { initialState = tokenizationSupport.getInitialState(); } catch (e) { errors_1.onUnexpectedError(e); tokenizationSupport = null; } } return [tokenizationSupport, initialState]; } function safeTokenize(languageIdentifier, tokenizationSupport, text, state) { var r = null; if (tokenizationSupport) { try { r = tokenizationSupport.tokenize2(text, state.clone(), 0); } catch (e) { errors_1.onUnexpectedError(e); } } if (!r) { r = nullMode_1.nullTokenize2(languageIdentifier.id, text, state, 0); } lineTokens_1.LineTokens.convertToEndOffset(r.tokens, text.length); return r; } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[30/*vs/editor/common/model/textModel*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,25/*vs/base/common/uri*/,33/*vs/editor/common/config/editorOptions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,48/*vs/editor/common/model*/,342/*vs/editor/common/model/editStack*/,343/*vs/editor/common/model/indentationGuesser*/,344/*vs/editor/common/model/intervalTree*/,348/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder*/,346/*vs/editor/common/model/textModelEvents*/,144/*vs/editor/common/model/textModelSearch*/,482/*vs/editor/common/model/textModelTokens*/,109/*vs/editor/common/model/wordHelper*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/,63/*vs/editor/common/modes/nullMode*/,145/*vs/editor/common/modes/supports*/,146/*vs/editor/common/modes/supports/richEditBrackets*/,21/*vs/base/common/types*/,157/*vs/editor/common/model/tokensStore*/,27/*vs/base/common/color*/]), function (require, exports, errors_1, event_1, lifecycle_1, strings, uri_1, editorOptions_1, position_1, range_1, selection_1, model, editStack_1, indentationGuesser_1, intervalTree_1, pieceTreeTextBufferBuilder_1, textModelEvents_1, textModelSearch_1, textModelTokens_1, wordHelper_1, languageConfigurationRegistry_1, nullMode_1, supports_1, richEditBrackets_1, types_1, tokensStore_1, color_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function createTextBufferBuilder() { return new pieceTreeTextBufferBuilder_1.PieceTreeTextBufferBuilder(); } function createTextBufferFactory(text) { var builder = createTextBufferBuilder(); builder.acceptChunk(text); return builder.finish(); } exports.createTextBufferFactory = createTextBufferFactory; function createTextBuffer(value, defaultEOL) { var factory = (typeof value === 'string' ? createTextBufferFactory(value) : value); return factory.create(defaultEOL); } exports.createTextBuffer = createTextBuffer; var MODEL_ID = 0; var LIMIT_FIND_COUNT = 999; exports.LONG_LINE_BOUNDARY = 10000; var invalidFunc = function () { throw new Error("Invalid change accessor"); }; var TextModel = /** @class */ (function (_super) { __extends(TextModel, _super); //#endregion function TextModel(source, creationOptions, languageIdentifier, associatedResource) { if (associatedResource === void 0) { associatedResource = null; } var _this = _super.call(this) || this; //#region Events _this._onWillDispose = _this._register(new event_1.Emitter()); _this.onWillDispose = _this._onWillDispose.event; _this._onDidChangeDecorations = _this._register(new DidChangeDecorationsEmitter()); _this.onDidChangeDecorations = _this._onDidChangeDecorations.event; _this._onDidChangeLanguage = _this._register(new event_1.Emitter()); _this.onDidChangeLanguage = _this._onDidChangeLanguage.event; _this._onDidChangeLanguageConfiguration = _this._register(new event_1.Emitter()); _this.onDidChangeLanguageConfiguration = _this._onDidChangeLanguageConfiguration.event; _this._onDidChangeTokens = _this._register(new event_1.Emitter()); _this.onDidChangeTokens = _this._onDidChangeTokens.event; _this._onDidChangeOptions = _this._register(new event_1.Emitter()); _this.onDidChangeOptions = _this._onDidChangeOptions.event; _this._onDidChangeAttached = _this._register(new event_1.Emitter()); _this.onDidChangeAttached = _this._onDidChangeAttached.event; _this._eventEmitter = _this._register(new DidChangeContentEmitter()); // Generate a new unique model id MODEL_ID++; _this.id = '$model' + MODEL_ID; _this.isForSimpleWidget = creationOptions.isForSimpleWidget; if (typeof associatedResource === 'undefined' || associatedResource === null) { _this._associatedResource = uri_1.URI.parse('inmemory://model/' + MODEL_ID); } else { _this._associatedResource = associatedResource; } _this._attachedEditorCount = 0; _this._buffer = createTextBuffer(source, creationOptions.defaultEOL); _this._options = TextModel.resolveOptions(_this._buffer, creationOptions); var bufferLineCount = _this._buffer.getLineCount(); var bufferTextLength = _this._buffer.getValueLengthInRange(new range_1.Range(1, 1, bufferLineCount, _this._buffer.getLineLength(bufferLineCount) + 1), 0 /* TextDefined */); // !!! Make a decision in the ctor and permanently respect this decision !!! // If a model is too large at construction time, it will never get tokenized, // under no circumstances. if (creationOptions.largeFileOptimizations) { _this._isTooLargeForTokenization = ((bufferTextLength > TextModel.LARGE_FILE_SIZE_THRESHOLD) || (bufferLineCount > TextModel.LARGE_FILE_LINE_COUNT_THRESHOLD)); } else { _this._isTooLargeForTokenization = false; } _this._isTooLargeForSyncing = (bufferTextLength > TextModel.MODEL_SYNC_LIMIT); _this._versionId = 1; _this._alternativeVersionId = 1; _this._isDisposed = false; _this._isDisposing = false; _this._languageIdentifier = languageIdentifier || nullMode_1.NULL_LANGUAGE_IDENTIFIER; _this._languageRegistryListener = languageConfigurationRegistry_1.LanguageConfigurationRegistry.onDidChange(function (e) { if (e.languageIdentifier.id === _this._languageIdentifier.id) { _this._onDidChangeLanguageConfiguration.fire({}); } }); _this._instanceId = strings.singleLetterHash(MODEL_ID); _this._lastDecorationId = 0; _this._decorations = Object.create(null); _this._decorationsTree = new DecorationsTrees(); _this._commandManager = new editStack_1.EditStack(_this); _this._isUndoing = false; _this._isRedoing = false; _this._trimAutoWhitespaceLines = null; _this._tokens = new tokensStore_1.TokensStore(); _this._tokens2 = new tokensStore_1.TokensStore2(); _this._tokenization = new textModelTokens_1.TextModelTokenization(_this); return _this; } TextModel.createFromString = function (text, options, languageIdentifier, uri) { if (options === void 0) { options = TextModel.DEFAULT_CREATION_OPTIONS; } if (languageIdentifier === void 0) { languageIdentifier = null; } if (uri === void 0) { uri = null; } return new TextModel(text, options, languageIdentifier, uri); }; TextModel.resolveOptions = function (textBuffer, options) { if (options.detectIndentation) { var guessedIndentation = indentationGuesser_1.guessIndentation(textBuffer, options.tabSize, options.insertSpaces); return new model.TextModelResolvedOptions({ tabSize: guessedIndentation.tabSize, indentSize: guessedIndentation.tabSize, insertSpaces: guessedIndentation.insertSpaces, trimAutoWhitespace: options.trimAutoWhitespace, defaultEOL: options.defaultEOL }); } return new model.TextModelResolvedOptions({ tabSize: options.tabSize, indentSize: options.indentSize, insertSpaces: options.insertSpaces, trimAutoWhitespace: options.trimAutoWhitespace, defaultEOL: options.defaultEOL }); }; TextModel.prototype.onDidChangeRawContentFast = function (listener) { return this._eventEmitter.fastEvent(function (e) { return listener(e.rawContentChangedEvent); }); }; TextModel.prototype.onDidChangeRawContent = function (listener) { return this._eventEmitter.slowEvent(function (e) { return listener(e.rawContentChangedEvent); }); }; TextModel.prototype.onDidChangeContentFast = function (listener) { return this._eventEmitter.fastEvent(function (e) { return listener(e.contentChangedEvent); }); }; TextModel.prototype.onDidChangeContent = function (listener) { return this._eventEmitter.slowEvent(function (e) { return listener(e.contentChangedEvent); }); }; TextModel.prototype.dispose = function () { this._isDisposing = true; this._onWillDispose.fire(); this._languageRegistryListener.dispose(); this._tokenization.dispose(); this._isDisposed = true; _super.prototype.dispose.call(this); this._isDisposing = false; }; TextModel.prototype._assertNotDisposed = function () { if (this._isDisposed) { throw new Error('Model is disposed!'); } }; TextModel.prototype._emitContentChangedEvent = function (rawChange, change) { if (this._isDisposing) { // Do not confuse listeners by emitting any event after disposing return; } this._eventEmitter.fire(new textModelEvents_1.InternalModelContentChangeEvent(rawChange, change)); }; TextModel.prototype.setValue = function (value) { this._assertNotDisposed(); if (value === null) { // There's nothing to do return; } var textBuffer = createTextBuffer(value, this._options.defaultEOL); this.setValueFromTextBuffer(textBuffer); }; TextModel.prototype._createContentChanged2 = function (range, rangeOffset, rangeLength, text, isUndoing, isRedoing, isFlush) { return { changes: [{ range: range, rangeOffset: rangeOffset, rangeLength: rangeLength, text: text, }], eol: this._buffer.getEOL(), versionId: this.getVersionId(), isUndoing: isUndoing, isRedoing: isRedoing, isFlush: isFlush }; }; TextModel.prototype.setValueFromTextBuffer = function (textBuffer) { this._assertNotDisposed(); if (textBuffer === null) { // There's nothing to do return; } var oldFullModelRange = this.getFullModelRange(); var oldModelValueLength = this.getValueLengthInRange(oldFullModelRange); var endLineNumber = this.getLineCount(); var endColumn = this.getLineMaxColumn(endLineNumber); this._buffer = textBuffer; this._increaseVersionId(); // Flush all tokens this._tokens.flush(); this._tokens2.flush(); // Destroy all my decorations this._decorations = Object.create(null); this._decorationsTree = new DecorationsTrees(); // Destroy my edit history and settings this._commandManager = new editStack_1.EditStack(this); this._trimAutoWhitespaceLines = null; this._emitContentChangedEvent(new textModelEvents_1.ModelRawContentChangedEvent([ new textModelEvents_1.ModelRawFlush() ], this._versionId, false, false), this._createContentChanged2(new range_1.Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, true)); }; TextModel.prototype.setEOL = function (eol) { this._assertNotDisposed(); var newEOL = (eol === 1 /* CRLF */ ? '\r\n' : '\n'); if (this._buffer.getEOL() === newEOL) { // Nothing to do return; } var oldFullModelRange = this.getFullModelRange(); var oldModelValueLength = this.getValueLengthInRange(oldFullModelRange); var endLineNumber = this.getLineCount(); var endColumn = this.getLineMaxColumn(endLineNumber); this._onBeforeEOLChange(); this._buffer.setEOL(newEOL); this._increaseVersionId(); this._onAfterEOLChange(); this._emitContentChangedEvent(new textModelEvents_1.ModelRawContentChangedEvent([ new textModelEvents_1.ModelRawEOLChanged() ], this._versionId, false, false), this._createContentChanged2(new range_1.Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, false)); }; TextModel.prototype._onBeforeEOLChange = function () { // Ensure all decorations get their `range` set. var versionId = this.getVersionId(); var allDecorations = this._decorationsTree.search(0, false, false, versionId); this._ensureNodesHaveRanges(allDecorations); }; TextModel.prototype._onAfterEOLChange = function () { // Transform back `range` to offsets var versionId = this.getVersionId(); var allDecorations = this._decorationsTree.collectNodesPostOrder(); for (var i = 0, len = allDecorations.length; i < len; i++) { var node = allDecorations[i]; var delta = node.cachedAbsoluteStart - node.start; var startOffset = this._buffer.getOffsetAt(node.range.startLineNumber, node.range.startColumn); var endOffset = this._buffer.getOffsetAt(node.range.endLineNumber, node.range.endColumn); node.cachedAbsoluteStart = startOffset; node.cachedAbsoluteEnd = endOffset; node.cachedVersionId = versionId; node.start = startOffset - delta; node.end = endOffset - delta; intervalTree_1.recomputeMaxEnd(node); } }; TextModel.prototype.onBeforeAttached = function () { this._attachedEditorCount++; if (this._attachedEditorCount === 1) { this._onDidChangeAttached.fire(undefined); } }; TextModel.prototype.onBeforeDetached = function () { this._attachedEditorCount--; if (this._attachedEditorCount === 0) { this._onDidChangeAttached.fire(undefined); } }; TextModel.prototype.isAttachedToEditor = function () { return this._attachedEditorCount > 0; }; TextModel.prototype.getAttachedEditorCount = function () { return this._attachedEditorCount; }; TextModel.prototype.isTooLargeForSyncing = function () { return this._isTooLargeForSyncing; }; TextModel.prototype.isTooLargeForTokenization = function () { return this._isTooLargeForTokenization; }; TextModel.prototype.isDisposed = function () { return this._isDisposed; }; TextModel.prototype.isDominatedByLongLines = function () { this._assertNotDisposed(); if (this.isTooLargeForTokenization()) { // Cannot word wrap huge files anyways, so it doesn't really matter return false; } var smallLineCharCount = 0; var longLineCharCount = 0; var lineCount = this._buffer.getLineCount(); for (var lineNumber = 1; lineNumber <= lineCount; lineNumber++) { var lineLength = this._buffer.getLineLength(lineNumber); if (lineLength >= exports.LONG_LINE_BOUNDARY) { longLineCharCount += lineLength; } else { smallLineCharCount += lineLength; } } return (longLineCharCount > smallLineCharCount); }; Object.defineProperty(TextModel.prototype, "uri", { get: function () { return this._associatedResource; }, enumerable: true, configurable: true }); //#region Options TextModel.prototype.getOptions = function () { this._assertNotDisposed(); return this._options; }; TextModel.prototype.getFormattingOptions = function () { return { tabSize: this._options.indentSize, insertSpaces: this._options.insertSpaces }; }; TextModel.prototype.updateOptions = function (_newOpts) { this._assertNotDisposed(); var tabSize = (typeof _newOpts.tabSize !== 'undefined') ? _newOpts.tabSize : this._options.tabSize; var indentSize = (typeof _newOpts.indentSize !== 'undefined') ? _newOpts.indentSize : this._options.indentSize; var insertSpaces = (typeof _newOpts.insertSpaces !== 'undefined') ? _newOpts.insertSpaces : this._options.insertSpaces; var trimAutoWhitespace = (typeof _newOpts.trimAutoWhitespace !== 'undefined') ? _newOpts.trimAutoWhitespace : this._options.trimAutoWhitespace; var newOpts = new model.TextModelResolvedOptions({ tabSize: tabSize, indentSize: indentSize, insertSpaces: insertSpaces, defaultEOL: this._options.defaultEOL, trimAutoWhitespace: trimAutoWhitespace }); if (this._options.equals(newOpts)) { return; } var e = this._options.createChangeEvent(newOpts); this._options = newOpts; this._onDidChangeOptions.fire(e); }; TextModel.prototype.detectIndentation = function (defaultInsertSpaces, defaultTabSize) { this._assertNotDisposed(); var guessedIndentation = indentationGuesser_1.guessIndentation(this._buffer, defaultTabSize, defaultInsertSpaces); this.updateOptions({ insertSpaces: guessedIndentation.insertSpaces, tabSize: guessedIndentation.tabSize, indentSize: guessedIndentation.tabSize, }); }; TextModel._normalizeIndentationFromWhitespace = function (str, indentSize, insertSpaces) { var spacesCnt = 0; for (var i = 0; i < str.length; i++) { if (str.charAt(i) === '\t') { spacesCnt += indentSize; } else { spacesCnt++; } } var result = ''; if (!insertSpaces) { var tabsCnt = Math.floor(spacesCnt / indentSize); spacesCnt = spacesCnt % indentSize; for (var i = 0; i < tabsCnt; i++) { result += '\t'; } } for (var i = 0; i < spacesCnt; i++) { result += ' '; } return result; }; TextModel.normalizeIndentation = function (str, indentSize, insertSpaces) { var firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(str); if (firstNonWhitespaceIndex === -1) { firstNonWhitespaceIndex = str.length; } return TextModel._normalizeIndentationFromWhitespace(str.substring(0, firstNonWhitespaceIndex), indentSize, insertSpaces) + str.substring(firstNonWhitespaceIndex); }; TextModel.prototype.normalizeIndentation = function (str) { this._assertNotDisposed(); return TextModel.normalizeIndentation(str, this._options.indentSize, this._options.insertSpaces); }; //#endregion //#region Reading TextModel.prototype.getVersionId = function () { this._assertNotDisposed(); return this._versionId; }; TextModel.prototype.mightContainRTL = function () { return this._buffer.mightContainRTL(); }; TextModel.prototype.mightContainNonBasicASCII = function () { return this._buffer.mightContainNonBasicASCII(); }; TextModel.prototype.getAlternativeVersionId = function () { this._assertNotDisposed(); return this._alternativeVersionId; }; TextModel.prototype.getOffsetAt = function (rawPosition) { this._assertNotDisposed(); var position = this._validatePosition(rawPosition.lineNumber, rawPosition.column, 0 /* Relaxed */); return this._buffer.getOffsetAt(position.lineNumber, position.column); }; TextModel.prototype.getPositionAt = function (rawOffset) { this._assertNotDisposed(); var offset = (Math.min(this._buffer.getLength(), Math.max(0, rawOffset))); return this._buffer.getPositionAt(offset); }; TextModel.prototype._increaseVersionId = function () { this._versionId = this._versionId + 1; this._alternativeVersionId = this._versionId; }; TextModel.prototype._overwriteAlternativeVersionId = function (newAlternativeVersionId) { this._alternativeVersionId = newAlternativeVersionId; }; TextModel.prototype.getValue = function (eol, preserveBOM) { if (preserveBOM === void 0) { preserveBOM = false; } this._assertNotDisposed(); var fullModelRange = this.getFullModelRange(); var fullModelValue = this.getValueInRange(fullModelRange, eol); if (preserveBOM) { return this._buffer.getBOM() + fullModelValue; } return fullModelValue; }; TextModel.prototype.getValueLength = function (eol, preserveBOM) { if (preserveBOM === void 0) { preserveBOM = false; } this._assertNotDisposed(); var fullModelRange = this.getFullModelRange(); var fullModelValue = this.getValueLengthInRange(fullModelRange, eol); if (preserveBOM) { return this._buffer.getBOM().length + fullModelValue; } return fullModelValue; }; TextModel.prototype.getValueInRange = function (rawRange, eol) { if (eol === void 0) { eol = 0 /* TextDefined */; } this._assertNotDisposed(); return this._buffer.getValueInRange(this.validateRange(rawRange), eol); }; TextModel.prototype.getValueLengthInRange = function (rawRange, eol) { if (eol === void 0) { eol = 0 /* TextDefined */; } this._assertNotDisposed(); return this._buffer.getValueLengthInRange(this.validateRange(rawRange), eol); }; TextModel.prototype.getCharacterCountInRange = function (rawRange, eol) { if (eol === void 0) { eol = 0 /* TextDefined */; } this._assertNotDisposed(); return this._buffer.getCharacterCountInRange(this.validateRange(rawRange), eol); }; TextModel.prototype.getLineCount = function () { this._assertNotDisposed(); return this._buffer.getLineCount(); }; TextModel.prototype.getLineContent = function (lineNumber) { this._assertNotDisposed(); if (lineNumber < 1 || lineNumber > this.getLineCount()) { throw new Error('Illegal value for lineNumber'); } return this._buffer.getLineContent(lineNumber); }; TextModel.prototype.getLineLength = function (lineNumber) { this._assertNotDisposed(); if (lineNumber < 1 || lineNumber > this.getLineCount()) { throw new Error('Illegal value for lineNumber'); } return this._buffer.getLineLength(lineNumber); }; TextModel.prototype.getLinesContent = function () { this._assertNotDisposed(); return this._buffer.getLinesContent(); }; TextModel.prototype.getEOL = function () { this._assertNotDisposed(); return this._buffer.getEOL(); }; TextModel.prototype.getLineMinColumn = function (lineNumber) { this._assertNotDisposed(); return 1; }; TextModel.prototype.getLineMaxColumn = function (lineNumber) { this._assertNotDisposed(); if (lineNumber < 1 || lineNumber > this.getLineCount()) { throw new Error('Illegal value for lineNumber'); } return this._buffer.getLineLength(lineNumber) + 1; }; TextModel.prototype.getLineFirstNonWhitespaceColumn = function (lineNumber) { this._assertNotDisposed(); if (lineNumber < 1 || lineNumber > this.getLineCount()) { throw new Error('Illegal value for lineNumber'); } return this._buffer.getLineFirstNonWhitespaceColumn(lineNumber); }; TextModel.prototype.getLineLastNonWhitespaceColumn = function (lineNumber) { this._assertNotDisposed(); if (lineNumber < 1 || lineNumber > this.getLineCount()) { throw new Error('Illegal value for lineNumber'); } return this._buffer.getLineLastNonWhitespaceColumn(lineNumber); }; /** * Validates `range` is within buffer bounds, but allows it to sit in between surrogate pairs, etc. * Will try to not allocate if possible. */ TextModel.prototype._validateRangeRelaxedNoAllocations = function (range) { var linesCount = this._buffer.getLineCount(); var initialStartLineNumber = range.startLineNumber; var initialStartColumn = range.startColumn; var startLineNumber; var startColumn; if (initialStartLineNumber < 1) { startLineNumber = 1; startColumn = 1; } else if (initialStartLineNumber > linesCount) { startLineNumber = linesCount; startColumn = this.getLineMaxColumn(startLineNumber); } else { startLineNumber = initialStartLineNumber | 0; if (initialStartColumn <= 1) { startColumn = 1; } else { var maxColumn = this.getLineMaxColumn(startLineNumber); if (initialStartColumn >= maxColumn) { startColumn = maxColumn; } else { startColumn = initialStartColumn | 0; } } } var initialEndLineNumber = range.endLineNumber; var initialEndColumn = range.endColumn; var endLineNumber; var endColumn; if (initialEndLineNumber < 1) { endLineNumber = 1; endColumn = 1; } else if (initialEndLineNumber > linesCount) { endLineNumber = linesCount; endColumn = this.getLineMaxColumn(endLineNumber); } else { endLineNumber = initialEndLineNumber | 0; if (initialEndColumn <= 1) { endColumn = 1; } else { var maxColumn = this.getLineMaxColumn(endLineNumber); if (initialEndColumn >= maxColumn) { endColumn = maxColumn; } else { endColumn = initialEndColumn | 0; } } } if (initialStartLineNumber === startLineNumber && initialStartColumn === startColumn && initialEndLineNumber === endLineNumber && initialEndColumn === endColumn && range instanceof range_1.Range && !(range instanceof selection_1.Selection)) { return range; } return new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn); }; TextModel.prototype._isValidPosition = function (lineNumber, column, validationType) { if (typeof lineNumber !== 'number' || typeof column !== 'number') { return false; } if (isNaN(lineNumber) || isNaN(column)) { return false; } if (lineNumber < 1 || column < 1) { return false; } if ((lineNumber | 0) !== lineNumber || (column | 0) !== column) { return false; } var lineCount = this._buffer.getLineCount(); if (lineNumber > lineCount) { return false; } if (column === 1) { return true; } var maxColumn = this.getLineMaxColumn(lineNumber); if (column > maxColumn) { return false; } if (validationType === 1 /* SurrogatePairs */) { // !!At this point, column > 1 var charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2); if (strings.isHighSurrogate(charCodeBefore)) { return false; } } return true; }; TextModel.prototype._validatePosition = function (_lineNumber, _column, validationType) { var lineNumber = Math.floor((typeof _lineNumber === 'number' && !isNaN(_lineNumber)) ? _lineNumber : 1); var column = Math.floor((typeof _column === 'number' && !isNaN(_column)) ? _column : 1); var lineCount = this._buffer.getLineCount(); if (lineNumber < 1) { return new position_1.Position(1, 1); } if (lineNumber > lineCount) { return new position_1.Position(lineCount, this.getLineMaxColumn(lineCount)); } if (column <= 1) { return new position_1.Position(lineNumber, 1); } var maxColumn = this.getLineMaxColumn(lineNumber); if (column >= maxColumn) { return new position_1.Position(lineNumber, maxColumn); } if (validationType === 1 /* SurrogatePairs */) { // If the position would end up in the middle of a high-low surrogate pair, // we move it to before the pair // !!At this point, column > 1 var charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2); if (strings.isHighSurrogate(charCodeBefore)) { return new position_1.Position(lineNumber, column - 1); } } return new position_1.Position(lineNumber, column); }; TextModel.prototype.validatePosition = function (position) { var validationType = 1 /* SurrogatePairs */; this._assertNotDisposed(); // Avoid object allocation and cover most likely case if (position instanceof position_1.Position) { if (this._isValidPosition(position.lineNumber, position.column, validationType)) { return position; } } return this._validatePosition(position.lineNumber, position.column, validationType); }; TextModel.prototype._isValidRange = function (range, validationType) { var startLineNumber = range.startLineNumber; var startColumn = range.startColumn; var endLineNumber = range.endLineNumber; var endColumn = range.endColumn; if (!this._isValidPosition(startLineNumber, startColumn, 0 /* Relaxed */)) { return false; } if (!this._isValidPosition(endLineNumber, endColumn, 0 /* Relaxed */)) { return false; } if (validationType === 1 /* SurrogatePairs */) { var charCodeBeforeStart = (startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0); var charCodeBeforeEnd = (endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0); var startInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeStart); var endInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeEnd); if (!startInsideSurrogatePair && !endInsideSurrogatePair) { return true; } return false; } return true; }; TextModel.prototype.validateRange = function (_range) { var validationType = 1 /* SurrogatePairs */; this._assertNotDisposed(); // Avoid object allocation and cover most likely case if ((_range instanceof range_1.Range) && !(_range instanceof selection_1.Selection)) { if (this._isValidRange(_range, validationType)) { return _range; } } var start = this._validatePosition(_range.startLineNumber, _range.startColumn, 0 /* Relaxed */); var end = this._validatePosition(_range.endLineNumber, _range.endColumn, 0 /* Relaxed */); var startLineNumber = start.lineNumber; var startColumn = start.column; var endLineNumber = end.lineNumber; var endColumn = end.column; if (validationType === 1 /* SurrogatePairs */) { var charCodeBeforeStart = (startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0); var charCodeBeforeEnd = (endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0); var startInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeStart); var endInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeEnd); if (!startInsideSurrogatePair && !endInsideSurrogatePair) { return new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn); } if (startLineNumber === endLineNumber && startColumn === endColumn) { // do not expand a collapsed range, simply move it to a valid location return new range_1.Range(startLineNumber, startColumn - 1, endLineNumber, endColumn - 1); } if (startInsideSurrogatePair && endInsideSurrogatePair) { // expand range at both ends return new range_1.Range(startLineNumber, startColumn - 1, endLineNumber, endColumn + 1); } if (startInsideSurrogatePair) { // only expand range at the start return new range_1.Range(startLineNumber, startColumn - 1, endLineNumber, endColumn); } // only expand range at the end return new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn + 1); } return new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn); }; TextModel.prototype.modifyPosition = function (rawPosition, offset) { this._assertNotDisposed(); var candidate = this.getOffsetAt(rawPosition) + offset; return this.getPositionAt(Math.min(this._buffer.getLength(), Math.max(0, candidate))); }; TextModel.prototype.getFullModelRange = function () { this._assertNotDisposed(); var lineCount = this.getLineCount(); return new range_1.Range(1, 1, lineCount, this.getLineMaxColumn(lineCount)); }; TextModel.prototype.findMatchesLineByLine = function (searchRange, searchData, captureMatches, limitResultCount) { return this._buffer.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount); }; TextModel.prototype.findMatches = function (searchString, rawSearchScope, isRegex, matchCase, wordSeparators, captureMatches, limitResultCount) { if (limitResultCount === void 0) { limitResultCount = LIMIT_FIND_COUNT; } this._assertNotDisposed(); var searchRange; if (range_1.Range.isIRange(rawSearchScope)) { searchRange = this.validateRange(rawSearchScope); } else { searchRange = this.getFullModelRange(); } if (!isRegex && searchString.indexOf('\n') < 0) { // not regex, not multi line var searchParams = new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators); var searchData = searchParams.parseSearchRequest(); if (!searchData) { return []; } return this.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount); } return textModelSearch_1.TextModelSearch.findMatches(this, new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators), searchRange, captureMatches, limitResultCount); }; TextModel.prototype.findNextMatch = function (searchString, rawSearchStart, isRegex, matchCase, wordSeparators, captureMatches) { this._assertNotDisposed(); var searchStart = this.validatePosition(rawSearchStart); if (!isRegex && searchString.indexOf('\n') < 0) { var searchParams = new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators); var searchData = searchParams.parseSearchRequest(); if (!searchData) { return null; } var lineCount = this.getLineCount(); var searchRange = new range_1.Range(searchStart.lineNumber, searchStart.column, lineCount, this.getLineMaxColumn(lineCount)); var ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1); textModelSearch_1.TextModelSearch.findNextMatch(this, new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches); if (ret.length > 0) { return ret[0]; } searchRange = new range_1.Range(1, 1, searchStart.lineNumber, this.getLineMaxColumn(searchStart.lineNumber)); ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1); if (ret.length > 0) { return ret[0]; } return null; } return textModelSearch_1.TextModelSearch.findNextMatch(this, new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches); }; TextModel.prototype.findPreviousMatch = function (searchString, rawSearchStart, isRegex, matchCase, wordSeparators, captureMatches) { this._assertNotDisposed(); var searchStart = this.validatePosition(rawSearchStart); return textModelSearch_1.TextModelSearch.findPreviousMatch(this, new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches); }; //#endregion //#region Editing TextModel.prototype.pushStackElement = function () { this._commandManager.pushStackElement(); }; TextModel.prototype.pushEOL = function (eol) { var currentEOL = (this.getEOL() === '\n' ? 0 /* LF */ : 1 /* CRLF */); if (currentEOL === eol) { return; } try { this._onDidChangeDecorations.beginDeferredEmit(); this._eventEmitter.beginDeferredEmit(); this._commandManager.pushEOL(eol); } finally { this._eventEmitter.endDeferredEmit(); this._onDidChangeDecorations.endDeferredEmit(); } }; TextModel.prototype.pushEditOperations = function (beforeCursorState, editOperations, cursorStateComputer) { try { this._onDidChangeDecorations.beginDeferredEmit(); this._eventEmitter.beginDeferredEmit(); return this._pushEditOperations(beforeCursorState, editOperations, cursorStateComputer); } finally { this._eventEmitter.endDeferredEmit(); this._onDidChangeDecorations.endDeferredEmit(); } }; TextModel.prototype._pushEditOperations = function (beforeCursorState, editOperations, cursorStateComputer) { var _this = this; if (this._options.trimAutoWhitespace && this._trimAutoWhitespaceLines) { // Go through each saved line number and insert a trim whitespace edit // if it is safe to do so (no conflicts with other edits). var incomingEdits = editOperations.map(function (op) { return { range: _this.validateRange(op.range), text: op.text }; }); // Sometimes, auto-formatters change ranges automatically which can cause undesired auto whitespace trimming near the cursor // We'll use the following heuristic: if the edits occur near the cursor, then it's ok to trim auto whitespace var editsAreNearCursors = true; for (var i = 0, len = beforeCursorState.length; i < len; i++) { var sel = beforeCursorState[i]; var foundEditNearSel = false; for (var j = 0, lenJ = incomingEdits.length; j < lenJ; j++) { var editRange = incomingEdits[j].range; var selIsAbove = editRange.startLineNumber > sel.endLineNumber; var selIsBelow = sel.startLineNumber > editRange.endLineNumber; if (!selIsAbove && !selIsBelow) { foundEditNearSel = true; break; } } if (!foundEditNearSel) { editsAreNearCursors = false; break; } } if (editsAreNearCursors) { for (var i = 0, len = this._trimAutoWhitespaceLines.length; i < len; i++) { var trimLineNumber = this._trimAutoWhitespaceLines[i]; var maxLineColumn = this.getLineMaxColumn(trimLineNumber); var allowTrimLine = true; for (var j = 0, lenJ = incomingEdits.length; j < lenJ; j++) { var editRange = incomingEdits[j].range; var editText = incomingEdits[j].text; if (trimLineNumber < editRange.startLineNumber || trimLineNumber > editRange.endLineNumber) { // `trimLine` is completely outside this edit continue; } // At this point: // editRange.startLineNumber <= trimLine <= editRange.endLineNumber if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === maxLineColumn && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(0) === '\n') { // This edit inserts a new line (and maybe other text) after `trimLine` continue; } if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === 1 && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(editText.length - 1) === '\n') { // This edit inserts a new line (and maybe other text) before `trimLine` continue; } // Looks like we can't trim this line as it would interfere with an incoming edit allowTrimLine = false; break; } if (allowTrimLine) { editOperations.push({ range: new range_1.Range(trimLineNumber, 1, trimLineNumber, maxLineColumn), text: null }); } } } this._trimAutoWhitespaceLines = null; } return this._commandManager.pushEditOperation(beforeCursorState, editOperations, cursorStateComputer); }; TextModel.prototype.applyEdits = function (rawOperations) { try { this._onDidChangeDecorations.beginDeferredEmit(); this._eventEmitter.beginDeferredEmit(); return this._applyEdits(rawOperations); } finally { this._eventEmitter.endDeferredEmit(); this._onDidChangeDecorations.endDeferredEmit(); } }; TextModel.prototype._applyEdits = function (rawOperations) { for (var i = 0, len = rawOperations.length; i < len; i++) { rawOperations[i].range = this.validateRange(rawOperations[i].range); } var oldLineCount = this._buffer.getLineCount(); var result = this._buffer.applyEdits(rawOperations, this._options.trimAutoWhitespace); var newLineCount = this._buffer.getLineCount(); var contentChanges = result.changes; this._trimAutoWhitespaceLines = result.trimAutoWhitespaceLineNumbers; if (contentChanges.length !== 0) { var rawContentChanges = []; var lineCount = oldLineCount; for (var i = 0, len = contentChanges.length; i < len; i++) { var change = contentChanges[i]; var _a = tokensStore_1.countEOL(change.text), eolCount = _a[0], firstLineLength = _a[1], lastLineLength = _a[2]; this._tokens.acceptEdit(change.range, eolCount, firstLineLength); this._tokens2.acceptEdit(change.range, eolCount, firstLineLength, lastLineLength, change.text.length > 0 ? change.text.charCodeAt(0) : 0 /* Null */); this._onDidChangeDecorations.fire(); this._decorationsTree.acceptReplace(change.rangeOffset, change.rangeLength, change.text.length, change.forceMoveMarkers); var startLineNumber = change.range.startLineNumber; var endLineNumber = change.range.endLineNumber; var deletingLinesCnt = endLineNumber - startLineNumber; var insertingLinesCnt = eolCount; var editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt); var changeLineCountDelta = (insertingLinesCnt - deletingLinesCnt); for (var j = editingLinesCnt; j >= 0; j--) { var editLineNumber = startLineNumber + j; var currentEditLineNumber = newLineCount - lineCount - changeLineCountDelta + editLineNumber; rawContentChanges.push(new textModelEvents_1.ModelRawLineChanged(editLineNumber, this.getLineContent(currentEditLineNumber))); } if (editingLinesCnt < deletingLinesCnt) { // Must delete some lines var spliceStartLineNumber = startLineNumber + editingLinesCnt; rawContentChanges.push(new textModelEvents_1.ModelRawLinesDeleted(spliceStartLineNumber + 1, endLineNumber)); } if (editingLinesCnt < insertingLinesCnt) { // Must insert some lines var spliceLineNumber = startLineNumber + editingLinesCnt; var cnt = insertingLinesCnt - editingLinesCnt; var fromLineNumber = newLineCount - lineCount - cnt + spliceLineNumber + 1; var newLines = []; for (var i_1 = 0; i_1 < cnt; i_1++) { var lineNumber = fromLineNumber + i_1; newLines[lineNumber - fromLineNumber] = this.getLineContent(lineNumber); } rawContentChanges.push(new textModelEvents_1.ModelRawLinesInserted(spliceLineNumber + 1, startLineNumber + insertingLinesCnt, newLines)); } lineCount += changeLineCountDelta; } this._increaseVersionId(); this._emitContentChangedEvent(new textModelEvents_1.ModelRawContentChangedEvent(rawContentChanges, this.getVersionId(), this._isUndoing, this._isRedoing), { changes: contentChanges, eol: this._buffer.getEOL(), versionId: this.getVersionId(), isUndoing: this._isUndoing, isRedoing: this._isRedoing, isFlush: false }); } return result.reverseEdits; }; TextModel.prototype._undo = function () { this._isUndoing = true; var r = this._commandManager.undo(); this._isUndoing = false; if (!r) { return null; } this._overwriteAlternativeVersionId(r.recordedVersionId); return r.selections; }; TextModel.prototype.undo = function () { try { this._onDidChangeDecorations.beginDeferredEmit(); this._eventEmitter.beginDeferredEmit(); return this._undo(); } finally { this._eventEmitter.endDeferredEmit(); this._onDidChangeDecorations.endDeferredEmit(); } }; TextModel.prototype.canUndo = function () { return this._commandManager.canUndo(); }; TextModel.prototype._redo = function () { this._isRedoing = true; var r = this._commandManager.redo(); this._isRedoing = false; if (!r) { return null; } this._overwriteAlternativeVersionId(r.recordedVersionId); return r.selections; }; TextModel.prototype.redo = function () { try { this._onDidChangeDecorations.beginDeferredEmit(); this._eventEmitter.beginDeferredEmit(); return this._redo(); } finally { this._eventEmitter.endDeferredEmit(); this._onDidChangeDecorations.endDeferredEmit(); } }; TextModel.prototype.canRedo = function () { return this._commandManager.canRedo(); }; //#endregion //#region Decorations TextModel.prototype.changeDecorations = function (callback, ownerId) { if (ownerId === void 0) { ownerId = 0; } this._assertNotDisposed(); try { this._onDidChangeDecorations.beginDeferredEmit(); return this._changeDecorations(ownerId, callback); } finally { this._onDidChangeDecorations.endDeferredEmit(); } }; TextModel.prototype._changeDecorations = function (ownerId, callback) { var _this = this; var changeAccessor = { addDecoration: function (range, options) { _this._onDidChangeDecorations.fire(); return _this._deltaDecorationsImpl(ownerId, [], [{ range: range, options: options }])[0]; }, changeDecoration: function (id, newRange) { _this._onDidChangeDecorations.fire(); _this._changeDecorationImpl(id, newRange); }, changeDecorationOptions: function (id, options) { _this._onDidChangeDecorations.fire(); _this._changeDecorationOptionsImpl(id, _normalizeOptions(options)); }, removeDecoration: function (id) { _this._onDidChangeDecorations.fire(); _this._deltaDecorationsImpl(ownerId, [id], []); }, deltaDecorations: function (oldDecorations, newDecorations) { if (oldDecorations.length === 0 && newDecorations.length === 0) { // nothing to do return []; } _this._onDidChangeDecorations.fire(); return _this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations); } }; var result = null; try { result = callback(changeAccessor); } catch (e) { errors_1.onUnexpectedError(e); } // Invalidate change accessor changeAccessor.addDecoration = invalidFunc; changeAccessor.changeDecoration = invalidFunc; changeAccessor.changeDecorationOptions = invalidFunc; changeAccessor.removeDecoration = invalidFunc; changeAccessor.deltaDecorations = invalidFunc; return result; }; TextModel.prototype.deltaDecorations = function (oldDecorations, newDecorations, ownerId) { if (ownerId === void 0) { ownerId = 0; } this._assertNotDisposed(); if (!oldDecorations) { oldDecorations = []; } if (oldDecorations.length === 0 && newDecorations.length === 0) { // nothing to do return []; } try { this._onDidChangeDecorations.beginDeferredEmit(); this._onDidChangeDecorations.fire(); return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations); } finally { this._onDidChangeDecorations.endDeferredEmit(); } }; TextModel.prototype._getTrackedRange = function (id) { return this.getDecorationRange(id); }; TextModel.prototype._setTrackedRange = function (id, newRange, newStickiness) { var node = (id ? this._decorations[id] : null); if (!node) { if (!newRange) { // node doesn't exist, the request is to delete => nothing to do return null; } // node doesn't exist, the request is to set => add the tracked range return this._deltaDecorationsImpl(0, [], [{ range: newRange, options: TRACKED_RANGE_OPTIONS[newStickiness] }])[0]; } if (!newRange) { // node exists, the request is to delete => delete node this._decorationsTree.delete(node); delete this._decorations[node.id]; return null; } // node exists, the request is to set => change the tracked range and its options var range = this._validateRangeRelaxedNoAllocations(newRange); var startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn); var endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn); this._decorationsTree.delete(node); node.reset(this.getVersionId(), startOffset, endOffset, range); node.setOptions(TRACKED_RANGE_OPTIONS[newStickiness]); this._decorationsTree.insert(node); return node.id; }; TextModel.prototype.removeAllDecorationsWithOwnerId = function (ownerId) { if (this._isDisposed) { return; } var nodes = this._decorationsTree.collectNodesFromOwner(ownerId); for (var i = 0, len = nodes.length; i < len; i++) { var node = nodes[i]; this._decorationsTree.delete(node); delete this._decorations[node.id]; } }; TextModel.prototype.getDecorationOptions = function (decorationId) { var node = this._decorations[decorationId]; if (!node) { return null; } return node.options; }; TextModel.prototype.getDecorationRange = function (decorationId) { var node = this._decorations[decorationId]; if (!node) { return null; } var versionId = this.getVersionId(); if (node.cachedVersionId !== versionId) { this._decorationsTree.resolveNode(node, versionId); } if (node.range === null) { node.range = this._getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd); } return node.range; }; TextModel.prototype.getLineDecorations = function (lineNumber, ownerId, filterOutValidation) { if (ownerId === void 0) { ownerId = 0; } if (filterOutValidation === void 0) { filterOutValidation = false; } if (lineNumber < 1 || lineNumber > this.getLineCount()) { return []; } return this.getLinesDecorations(lineNumber, lineNumber, ownerId, filterOutValidation); }; TextModel.prototype.getLinesDecorations = function (_startLineNumber, _endLineNumber, ownerId, filterOutValidation) { if (ownerId === void 0) { ownerId = 0; } if (filterOutValidation === void 0) { filterOutValidation = false; } var lineCount = this.getLineCount(); var startLineNumber = Math.min(lineCount, Math.max(1, _startLineNumber)); var endLineNumber = Math.min(lineCount, Math.max(1, _endLineNumber)); var endColumn = this.getLineMaxColumn(endLineNumber); return this._getDecorationsInRange(new range_1.Range(startLineNumber, 1, endLineNumber, endColumn), ownerId, filterOutValidation); }; TextModel.prototype.getDecorationsInRange = function (range, ownerId, filterOutValidation) { if (ownerId === void 0) { ownerId = 0; } if (filterOutValidation === void 0) { filterOutValidation = false; } var validatedRange = this.validateRange(range); return this._getDecorationsInRange(validatedRange, ownerId, filterOutValidation); }; TextModel.prototype.getOverviewRulerDecorations = function (ownerId, filterOutValidation) { if (ownerId === void 0) { ownerId = 0; } if (filterOutValidation === void 0) { filterOutValidation = false; } var versionId = this.getVersionId(); var result = this._decorationsTree.search(ownerId, filterOutValidation, true, versionId); return this._ensureNodesHaveRanges(result); }; TextModel.prototype.getAllDecorations = function (ownerId, filterOutValidation) { if (ownerId === void 0) { ownerId = 0; } if (filterOutValidation === void 0) { filterOutValidation = false; } var versionId = this.getVersionId(); var result = this._decorationsTree.search(ownerId, filterOutValidation, false, versionId); return this._ensureNodesHaveRanges(result); }; TextModel.prototype._getDecorationsInRange = function (filterRange, filterOwnerId, filterOutValidation) { var startOffset = this._buffer.getOffsetAt(filterRange.startLineNumber, filterRange.startColumn); var endOffset = this._buffer.getOffsetAt(filterRange.endLineNumber, filterRange.endColumn); var versionId = this.getVersionId(); var result = this._decorationsTree.intervalSearch(startOffset, endOffset, filterOwnerId, filterOutValidation, versionId); return this._ensureNodesHaveRanges(result); }; TextModel.prototype._ensureNodesHaveRanges = function (nodes) { for (var i = 0, len = nodes.length; i < len; i++) { var node = nodes[i]; if (node.range === null) { node.range = this._getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd); } } return nodes; }; TextModel.prototype._getRangeAt = function (start, end) { return this._buffer.getRangeAt(start, end - start); }; TextModel.prototype._changeDecorationImpl = function (decorationId, _range) { var node = this._decorations[decorationId]; if (!node) { return; } var range = this._validateRangeRelaxedNoAllocations(_range); var startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn); var endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn); this._decorationsTree.delete(node); node.reset(this.getVersionId(), startOffset, endOffset, range); this._decorationsTree.insert(node); }; TextModel.prototype._changeDecorationOptionsImpl = function (decorationId, options) { var node = this._decorations[decorationId]; if (!node) { return; } var nodeWasInOverviewRuler = (node.options.overviewRuler && node.options.overviewRuler.color ? true : false); var nodeIsInOverviewRuler = (options.overviewRuler && options.overviewRuler.color ? true : false); if (nodeWasInOverviewRuler !== nodeIsInOverviewRuler) { // Delete + Insert due to an overview ruler status change this._decorationsTree.delete(node); node.setOptions(options); this._decorationsTree.insert(node); } else { node.setOptions(options); } }; TextModel.prototype._deltaDecorationsImpl = function (ownerId, oldDecorationsIds, newDecorations) { var versionId = this.getVersionId(); var oldDecorationsLen = oldDecorationsIds.length; var oldDecorationIndex = 0; var newDecorationsLen = newDecorations.length; var newDecorationIndex = 0; var result = new Array(newDecorationsLen); while (oldDecorationIndex < oldDecorationsLen || newDecorationIndex < newDecorationsLen) { var node = null; if (oldDecorationIndex < oldDecorationsLen) { // (1) get ourselves an old node do { node = this._decorations[oldDecorationsIds[oldDecorationIndex++]]; } while (!node && oldDecorationIndex < oldDecorationsLen); // (2) remove the node from the tree (if it exists) if (node) { this._decorationsTree.delete(node); } } if (newDecorationIndex < newDecorationsLen) { // (3) create a new node if necessary if (!node) { var internalDecorationId = (++this._lastDecorationId); var decorationId = this._instanceId + ";" + internalDecorationId; node = new intervalTree_1.IntervalNode(decorationId, 0, 0); this._decorations[decorationId] = node; } // (4) initialize node var newDecoration = newDecorations[newDecorationIndex]; var range = this._validateRangeRelaxedNoAllocations(newDecoration.range); var options = _normalizeOptions(newDecoration.options); var startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn); var endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn); node.ownerId = ownerId; node.reset(versionId, startOffset, endOffset, range); node.setOptions(options); this._decorationsTree.insert(node); result[newDecorationIndex] = node.id; newDecorationIndex++; } else { if (node) { delete this._decorations[node.id]; } } } return result; }; //#endregion //#region Tokenization TextModel.prototype.setLineTokens = function (lineNumber, tokens) { if (lineNumber < 1 || lineNumber > this.getLineCount()) { throw new Error('Illegal value for lineNumber'); } this._tokens.setTokens(this._languageIdentifier.id, lineNumber - 1, this._buffer.getLineLength(lineNumber), tokens); }; TextModel.prototype.setTokens = function (tokens) { if (tokens.length === 0) { return; } var ranges = []; for (var i = 0, len = tokens.length; i < len; i++) { var element = tokens[i]; ranges.push({ fromLineNumber: element.startLineNumber, toLineNumber: element.startLineNumber + element.tokens.length - 1 }); for (var j = 0, lenJ = element.tokens.length; j < lenJ; j++) { this.setLineTokens(element.startLineNumber + j, element.tokens[j]); } } this._emitModelTokensChangedEvent({ tokenizationSupportChanged: false, ranges: ranges }); }; TextModel.prototype.setSemanticTokens = function (tokens) { this._tokens2.set(tokens); this._emitModelTokensChangedEvent({ tokenizationSupportChanged: false, ranges: [{ fromLineNumber: 1, toLineNumber: this.getLineCount() }] }); }; TextModel.prototype.tokenizeViewport = function (startLineNumber, endLineNumber) { startLineNumber = Math.max(1, startLineNumber); endLineNumber = Math.min(this._buffer.getLineCount(), endLineNumber); this._tokenization.tokenizeViewport(startLineNumber, endLineNumber); }; TextModel.prototype.clearTokens = function () { this._tokens.flush(); this._emitModelTokensChangedEvent({ tokenizationSupportChanged: true, ranges: [{ fromLineNumber: 1, toLineNumber: this._buffer.getLineCount() }] }); }; TextModel.prototype._emitModelTokensChangedEvent = function (e) { if (!this._isDisposing) { this._onDidChangeTokens.fire(e); } }; TextModel.prototype.resetTokenization = function () { this._tokenization.reset(); }; TextModel.prototype.forceTokenization = function (lineNumber) { if (lineNumber < 1 || lineNumber > this.getLineCount()) { throw new Error('Illegal value for lineNumber'); } this._tokenization.forceTokenization(lineNumber); }; TextModel.prototype.isCheapToTokenize = function (lineNumber) { return this._tokenization.isCheapToTokenize(lineNumber); }; TextModel.prototype.tokenizeIfCheap = function (lineNumber) { if (this.isCheapToTokenize(lineNumber)) { this.forceTokenization(lineNumber); } }; TextModel.prototype.getLineTokens = function (lineNumber) { if (lineNumber < 1 || lineNumber > this.getLineCount()) { throw new Error('Illegal value for lineNumber'); } return this._getLineTokens(lineNumber); }; TextModel.prototype._getLineTokens = function (lineNumber) { var lineText = this.getLineContent(lineNumber); var syntacticTokens = this._tokens.getTokens(this._languageIdentifier.id, lineNumber - 1, lineText); return this._tokens2.addSemanticTokens(lineNumber, syntacticTokens); }; TextModel.prototype.getLanguageIdentifier = function () { return this._languageIdentifier; }; TextModel.prototype.getModeId = function () { return this._languageIdentifier.language; }; TextModel.prototype.setMode = function (languageIdentifier) { if (this._languageIdentifier.id === languageIdentifier.id) { // There's nothing to do return; } var e = { oldLanguage: this._languageIdentifier.language, newLanguage: languageIdentifier.language }; this._languageIdentifier = languageIdentifier; this._onDidChangeLanguage.fire(e); this._onDidChangeLanguageConfiguration.fire({}); }; TextModel.prototype.getLanguageIdAtPosition = function (lineNumber, column) { var position = this.validatePosition(new position_1.Position(lineNumber, column)); var lineTokens = this.getLineTokens(position.lineNumber); return lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1)); }; // Having tokens allows implementing additional helper methods TextModel.prototype.getWordAtPosition = function (_position) { this._assertNotDisposed(); var position = this.validatePosition(_position); var lineContent = this.getLineContent(position.lineNumber); var lineTokens = this._getLineTokens(position.lineNumber); var tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); // (1). First try checking right biased word var _a = TextModel._findLanguageBoundaries(lineTokens, tokenIndex), rbStartOffset = _a[0], rbEndOffset = _a[1]; var rightBiasedWord = wordHelper_1.getWordAtText(position.column, languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(lineTokens.getLanguageId(tokenIndex)), lineContent.substring(rbStartOffset, rbEndOffset), rbStartOffset); // Make sure the result touches the original passed in position if (rightBiasedWord && rightBiasedWord.startColumn <= _position.column && _position.column <= rightBiasedWord.endColumn) { return rightBiasedWord; } // (2). Else, if we were at a language boundary, check the left biased word if (tokenIndex > 0 && rbStartOffset === position.column - 1) { // edge case, where `position` sits between two tokens belonging to two different languages var _b = TextModel._findLanguageBoundaries(lineTokens, tokenIndex - 1), lbStartOffset = _b[0], lbEndOffset = _b[1]; var leftBiasedWord = wordHelper_1.getWordAtText(position.column, languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(lineTokens.getLanguageId(tokenIndex - 1)), lineContent.substring(lbStartOffset, lbEndOffset), lbStartOffset); // Make sure the result touches the original passed in position if (leftBiasedWord && leftBiasedWord.startColumn <= _position.column && _position.column <= leftBiasedWord.endColumn) { return leftBiasedWord; } } return null; }; TextModel._findLanguageBoundaries = function (lineTokens, tokenIndex) { var languageId = lineTokens.getLanguageId(tokenIndex); // go left until a different language is hit var startOffset = 0; for (var i = tokenIndex; i >= 0 && lineTokens.getLanguageId(i) === languageId; i--) { startOffset = lineTokens.getStartOffset(i); } // go right until a different language is hit var endOffset = lineTokens.getLineContent().length; for (var i = tokenIndex, tokenCount = lineTokens.getCount(); i < tokenCount && lineTokens.getLanguageId(i) === languageId; i++) { endOffset = lineTokens.getEndOffset(i); } return [startOffset, endOffset]; }; TextModel.prototype.getWordUntilPosition = function (position) { var wordAtPosition = this.getWordAtPosition(position); if (!wordAtPosition) { return { word: '', startColumn: position.column, endColumn: position.column }; } return { word: wordAtPosition.word.substr(0, position.column - wordAtPosition.startColumn), startColumn: wordAtPosition.startColumn, endColumn: position.column }; }; TextModel.prototype.findMatchingBracketUp = function (_bracket, _position) { var bracket = _bracket.toLowerCase(); var position = this.validatePosition(_position); var lineTokens = this._getLineTokens(position.lineNumber); var languageId = lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1)); var bracketsSupport = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId); if (!bracketsSupport) { return null; } var data = bracketsSupport.textIsBracket[bracket]; if (!data) { return null; } return this._findMatchingBracketUp(data, position); }; TextModel.prototype.matchBracket = function (position) { return this._matchBracket(this.validatePosition(position)); }; TextModel.prototype._matchBracket = function (position) { var lineNumber = position.lineNumber; var lineTokens = this._getLineTokens(lineNumber); var tokenCount = lineTokens.getCount(); var lineText = this._buffer.getLineContent(lineNumber); var tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); if (tokenIndex < 0) { return null; } var currentModeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(tokenIndex)); // check that the token is not to be ignored if (currentModeBrackets && !supports_1.ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex))) { // limit search to not go before `maxBracketLength` var searchStartOffset = Math.max(0, position.column - 1 - currentModeBrackets.maxBracketLength); for (var i = tokenIndex - 1; i >= 0; i--) { var tokenEndOffset = lineTokens.getEndOffset(i); if (tokenEndOffset <= searchStartOffset) { break; } if (supports_1.ignoreBracketsInToken(lineTokens.getStandardTokenType(i))) { searchStartOffset = tokenEndOffset; } } // limit search to not go after `maxBracketLength` var searchEndOffset = Math.min(lineText.length, position.column - 1 + currentModeBrackets.maxBracketLength); // it might be the case that [currentTokenStart -> currentTokenEnd] contains multiple brackets // `bestResult` will contain the most right-side result var bestResult = null; while (true) { var 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) { var foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase(); var r = this._matchFoundBracket(foundBracket, currentModeBrackets.textIsBracket[foundBracketText], currentModeBrackets.textIsOpenBracket[foundBracketText]); if (r) { 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) { var prevTokenIndex = tokenIndex - 1; var prevModeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(prevTokenIndex)); // check that previous token is not to be ignored if (prevModeBrackets && !supports_1.ignoreBracketsInToken(lineTokens.getStandardTokenType(prevTokenIndex))) { // limit search in case previous token is very large, there's no need to go beyond `maxBracketLength` var searchStartOffset = Math.max(0, position.column - 1 - prevModeBrackets.maxBracketLength); var searchEndOffset = Math.min(lineText.length, position.column - 1 + prevModeBrackets.maxBracketLength); for (var i = prevTokenIndex + 1; i < tokenCount; i++) { var tokenStartOffset = lineTokens.getStartOffset(i); if (tokenStartOffset >= searchEndOffset) { break; } if (supports_1.ignoreBracketsInToken(lineTokens.getStandardTokenType(i))) { searchEndOffset = tokenStartOffset; } } var 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) { var foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase(); var r = this._matchFoundBracket(foundBracket, prevModeBrackets.textIsBracket[foundBracketText], prevModeBrackets.textIsOpenBracket[foundBracketText]); if (r) { return r; } } } } return null; }; TextModel.prototype._matchFoundBracket = function (foundBracket, data, isOpen) { if (!data) { return null; } if (isOpen) { var matched = this._findMatchingBracketDown(data, foundBracket.getEndPosition()); if (matched) { return [foundBracket, matched]; } } else { var matched = this._findMatchingBracketUp(data, foundBracket.getStartPosition()); if (matched) { return [foundBracket, matched]; } } return null; }; TextModel.prototype._findMatchingBracketUp = function (bracket, position) { // console.log('_findMatchingBracketUp: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position)); var languageId = bracket.languageIdentifier.id; var reversedBracketRegex = bracket.reversedRegex; var count = -1; var searchPrevMatchingBracketInRange = function (lineNumber, lineText, searchStartOffset, searchEndOffset) { while (true) { var r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); if (!r) { break; } var 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 (var lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) { var lineTokens = this._getLineTokens(lineNumber); var tokenCount = lineTokens.getCount(); var lineText = this._buffer.getLineContent(lineNumber); var tokenIndex = tokenCount - 1; var searchStartOffset = lineText.length; var searchEndOffset = lineText.length; if (lineNumber === position.lineNumber) { tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); searchStartOffset = position.column - 1; searchEndOffset = position.column - 1; } var prevSearchInToken = true; for (; tokenIndex >= 0; tokenIndex--) { var searchInToken = (lineTokens.getLanguageId(tokenIndex) === languageId && !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) { var r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return r; } } } prevSearchInToken = searchInToken; } if (prevSearchInToken && searchStartOffset !== searchEndOffset) { var r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return r; } } } return null; }; TextModel.prototype._findMatchingBracketDown = function (bracket, position) { // console.log('_findMatchingBracketDown: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position)); var languageId = bracket.languageIdentifier.id; var bracketRegex = bracket.forwardRegex; var count = 1; var searchNextMatchingBracketInRange = function (lineNumber, lineText, searchStartOffset, searchEndOffset) { while (true) { var r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(bracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); if (!r) { break; } var 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; }; var lineCount = this.getLineCount(); for (var lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) { var lineTokens = this._getLineTokens(lineNumber); var tokenCount = lineTokens.getCount(); var lineText = this._buffer.getLineContent(lineNumber); var tokenIndex = 0; var searchStartOffset = 0; var searchEndOffset = 0; if (lineNumber === position.lineNumber) { tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); searchStartOffset = position.column - 1; searchEndOffset = position.column - 1; } var prevSearchInToken = true; for (; tokenIndex < tokenCount; tokenIndex++) { var searchInToken = (lineTokens.getLanguageId(tokenIndex) === languageId && !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) { var r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return r; } } } prevSearchInToken = searchInToken; } if (prevSearchInToken && searchStartOffset !== searchEndOffset) { var r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return r; } } } return null; }; TextModel.prototype.findPrevBracket = function (_position) { var position = this.validatePosition(_position); var languageId = -1; var modeBrackets = null; for (var lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) { var lineTokens = this._getLineTokens(lineNumber); var tokenCount = lineTokens.getCount(); var lineText = this._buffer.getLineContent(lineNumber); var tokenIndex = tokenCount - 1; var searchStartOffset = lineText.length; var searchEndOffset = lineText.length; if (lineNumber === position.lineNumber) { tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); searchStartOffset = position.column - 1; searchEndOffset = position.column - 1; var tokenLanguageId = lineTokens.getLanguageId(tokenIndex); if (languageId !== tokenLanguageId) { languageId = tokenLanguageId; modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId); } } var prevSearchInToken = true; for (; tokenIndex >= 0; tokenIndex--) { var tokenLanguageId = lineTokens.getLanguageId(tokenIndex); if (languageId !== tokenLanguageId) { // language id change! if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) { var r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return this._toFoundBracket(modeBrackets, r); } prevSearchInToken = false; } languageId = tokenLanguageId; modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId); } var searchInToken = (!!modeBrackets && !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) { var 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) { var r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return this._toFoundBracket(modeBrackets, r); } } } return null; }; TextModel.prototype.findNextBracket = function (_position) { var position = this.validatePosition(_position); var lineCount = this.getLineCount(); var languageId = -1; var modeBrackets = null; for (var lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) { var lineTokens = this._getLineTokens(lineNumber); var tokenCount = lineTokens.getCount(); var lineText = this._buffer.getLineContent(lineNumber); var tokenIndex = 0; var searchStartOffset = 0; var searchEndOffset = 0; if (lineNumber === position.lineNumber) { tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); searchStartOffset = position.column - 1; searchEndOffset = position.column - 1; var tokenLanguageId = lineTokens.getLanguageId(tokenIndex); if (languageId !== tokenLanguageId) { languageId = tokenLanguageId; modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId); } } var prevSearchInToken = true; for (; tokenIndex < tokenCount; tokenIndex++) { var tokenLanguageId = lineTokens.getLanguageId(tokenIndex); if (languageId !== tokenLanguageId) { // language id change! if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) { var r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return this._toFoundBracket(modeBrackets, r); } prevSearchInToken = false; } languageId = tokenLanguageId; modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId); } var searchInToken = (!!modeBrackets && !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) { var 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) { var r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return this._toFoundBracket(modeBrackets, r); } } } return null; }; TextModel.prototype.findEnclosingBrackets = function (_position, maxDuration) { var _this = this; if (maxDuration === void 0) { maxDuration = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; } var position = this.validatePosition(_position); var lineCount = this.getLineCount(); var savedCounts = new Map(); var counts = []; var resetCounts = function (languageId, modeBrackets) { if (!savedCounts.has(languageId)) { var tmp = []; for (var i = 0, len = modeBrackets ? modeBrackets.brackets.length : 0; i < len; i++) { tmp[i] = 0; } savedCounts.set(languageId, tmp); } counts = savedCounts.get(languageId); }; var searchInRange = function (modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset) { while (true) { var r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); if (!r) { break; } var hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase(); var 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); } } searchStartOffset = r.endColumn - 1; } return null; }; var languageId = -1; var modeBrackets = null; var startTime = Date.now(); for (var lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) { var elapsedTime = Date.now() - startTime; if (elapsedTime > maxDuration) { return null; } var lineTokens = this._getLineTokens(lineNumber); var tokenCount = lineTokens.getCount(); var lineText = this._buffer.getLineContent(lineNumber); var tokenIndex = 0; var searchStartOffset = 0; var searchEndOffset = 0; if (lineNumber === position.lineNumber) { tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); searchStartOffset = position.column - 1; searchEndOffset = position.column - 1; var tokenLanguageId = lineTokens.getLanguageId(tokenIndex); if (languageId !== tokenLanguageId) { languageId = tokenLanguageId; modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId); resetCounts(languageId, modeBrackets); } } var prevSearchInToken = true; for (; tokenIndex < tokenCount; tokenIndex++) { var tokenLanguageId = lineTokens.getLanguageId(tokenIndex); if (languageId !== tokenLanguageId) { // language id change! if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) { var r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return r; } prevSearchInToken = false; } languageId = tokenLanguageId; modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId); resetCounts(languageId, modeBrackets); } var searchInToken = (!!modeBrackets && !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) { var r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return r; } } } prevSearchInToken = searchInToken; } if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) { var r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset); if (r) { return r; } } } return null; }; TextModel.prototype._toFoundBracket = function (modeBrackets, r) { if (!r) { return null; } var text = this.getValueInRange(r); text = text.toLowerCase(); var data = modeBrackets.textIsBracket[text]; if (!data) { return null; } return { range: r, open: data.open, close: data.close, isOpen: modeBrackets.textIsOpenBracket[text] }; }; /** * Returns: * - -1 => the line consists of whitespace * - otherwise => the indent level is returned value */ TextModel.computeIndentLevel = function (line, tabSize) { var indent = 0; var i = 0; var len = line.length; while (i < len) { var 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; }; TextModel.prototype._computeIndentLevel = function (lineIndex) { return TextModel.computeIndentLevel(this._buffer.getLineContent(lineIndex + 1), this._options.tabSize); }; TextModel.prototype.getActiveIndentGuide = function (lineNumber, minLineNumber, maxLineNumber) { var _this = this; this._assertNotDisposed(); var lineCount = this.getLineCount(); if (lineNumber < 1 || lineNumber > lineCount) { throw new Error('Illegal value for lineNumber'); } var foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(this._languageIdentifier.id); var offSide = Boolean(foldingRules && foldingRules.offSide); var up_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */ var up_aboveContentLineIndent = -1; var up_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */ var up_belowContentLineIndent = -1; var up_resolveIndents = function (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 (var lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) { var indent_1 = _this._computeIndentLevel(lineIndex); if (indent_1 >= 0) { up_aboveContentLineIndex = lineIndex; up_aboveContentLineIndent = indent_1; break; } } } if (up_belowContentLineIndex === -2) { up_belowContentLineIndex = -1; up_belowContentLineIndent = -1; // must find next line with content for (var lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) { var indent_2 = _this._computeIndentLevel(lineIndex); if (indent_2 >= 0) { up_belowContentLineIndex = lineIndex; up_belowContentLineIndent = indent_2; break; } } } }; var down_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */ var down_aboveContentLineIndent = -1; var down_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */ var down_belowContentLineIndent = -1; var down_resolveIndents = function (lineNumber) { if (down_aboveContentLineIndex === -2) { down_aboveContentLineIndex = -1; down_aboveContentLineIndent = -1; // must find previous line with content for (var lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) { var indent_3 = _this._computeIndentLevel(lineIndex); if (indent_3 >= 0) { down_aboveContentLineIndex = lineIndex; down_aboveContentLineIndent = indent_3; 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 (var lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) { var indent_4 = _this._computeIndentLevel(lineIndex); if (indent_4 >= 0) { down_belowContentLineIndex = lineIndex; down_belowContentLineIndent = indent_4; break; } } } }; var startLineNumber = 0; var goUp = true; var endLineNumber = 0; var goDown = true; var indent = 0; for (var distance = 0; goUp || goDown; distance++) { var upLineNumber = lineNumber - distance; var downLineNumber = lineNumber + distance; if (distance !== 0 && (upLineNumber < 1 || upLineNumber < minLineNumber)) { goUp = false; } if (distance !== 0 && (downLineNumber > lineCount || downLineNumber > maxLineNumber)) { goDown = false; } if (distance > 50000) { // stop processing goUp = false; goDown = false; } if (goUp) { // compute indent level going up var upLineIndentLevel = void 0; var currentIndent = this._computeIndentLevel(upLineNumber - 1); if (currentIndent >= 0) { // This line has content (besides whitespace) // Use the line's indent up_belowContentLineIndex = upLineNumber - 1; up_belowContentLineIndent = currentIndent; upLineIndentLevel = Math.ceil(currentIndent / this._options.indentSize); } else { up_resolveIndents(upLineNumber); upLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, up_aboveContentLineIndent, up_belowContentLineIndent); } if (distance === 0) { // This is the initial line number startLineNumber = upLineNumber; endLineNumber = downLineNumber; indent = upLineIndentLevel; if (indent === 0) { // No need to continue return { startLineNumber: startLineNumber, endLineNumber: endLineNumber, indent: indent }; } continue; } if (upLineIndentLevel >= indent) { startLineNumber = upLineNumber; } else { goUp = false; } } if (goDown) { // compute indent level going down var downLineIndentLevel = void 0; var currentIndent = this._computeIndentLevel(downLineNumber - 1); if (currentIndent >= 0) { // This line has content (besides whitespace) // Use the line's indent down_aboveContentLineIndex = downLineNumber - 1; down_aboveContentLineIndent = currentIndent; downLineIndentLevel = Math.ceil(currentIndent / this._options.indentSize); } else { down_resolveIndents(downLineNumber); downLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, down_aboveContentLineIndent, down_belowContentLineIndent); } if (downLineIndentLevel >= indent) { endLineNumber = downLineNumber; } else { goDown = false; } } } return { startLineNumber: startLineNumber, endLineNumber: endLineNumber, indent: indent }; }; TextModel.prototype.getLinesIndentGuides = function (startLineNumber, endLineNumber) { this._assertNotDisposed(); var lineCount = this.getLineCount(); if (startLineNumber < 1 || startLineNumber > lineCount) { throw new Error('Illegal value for startLineNumber'); } if (endLineNumber < 1 || endLineNumber > lineCount) { throw new Error('Illegal value for endLineNumber'); } var foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(this._languageIdentifier.id); var offSide = Boolean(foldingRules && foldingRules.offSide); var result = new Array(endLineNumber - startLineNumber + 1); var aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */ var aboveContentLineIndent = -1; var belowContentLineIndex = -2; /* -2 is a marker for not having computed it */ var belowContentLineIndent = -1; for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { var resultIndex = lineNumber - startLineNumber; var currentIndent = this._computeIndentLevel(lineNumber - 1); if (currentIndent >= 0) { // This line has content (besides whitespace) // Use the line's indent aboveContentLineIndex = lineNumber - 1; aboveContentLineIndent = currentIndent; result[resultIndex] = Math.ceil(currentIndent / this._options.indentSize); continue; } if (aboveContentLineIndex === -2) { aboveContentLineIndex = -1; aboveContentLineIndent = -1; // must find previous line with content for (var lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) { var 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 (var lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) { var indent = this._computeIndentLevel(lineIndex); if (indent >= 0) { belowContentLineIndex = lineIndex; belowContentLineIndent = indent; break; } } } result[resultIndex] = this._getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent); } return result; }; TextModel.prototype._getIndentLevelForWhitespaceLine = function (offSide, aboveContentLineIndent, belowContentLineIndent) { if (aboveContentLineIndent === -1 || belowContentLineIndent === -1) { // At the top or bottom of the file return 0; } else if (aboveContentLineIndent < belowContentLineIndent) { // we are inside the region above return (1 + Math.floor(aboveContentLineIndent / this._options.indentSize)); } else if (aboveContentLineIndent === belowContentLineIndent) { // we are in between two regions return Math.ceil(belowContentLineIndent / this._options.indentSize); } else { if (offSide) { // same level as region below return Math.ceil(belowContentLineIndent / this._options.indentSize); } else { // we are inside the region that ends below return (1 + Math.floor(belowContentLineIndent / this._options.indentSize)); } } }; TextModel.MODEL_SYNC_LIMIT = 50 * 1024 * 1024; // 50 MB TextModel.LARGE_FILE_SIZE_THRESHOLD = 20 * 1024 * 1024; // 20 MB; TextModel.LARGE_FILE_LINE_COUNT_THRESHOLD = 300 * 1000; // 300K lines TextModel.DEFAULT_CREATION_OPTIONS = { isForSimpleWidget: false, tabSize: editorOptions_1.EDITOR_MODEL_DEFAULTS.tabSize, indentSize: editorOptions_1.EDITOR_MODEL_DEFAULTS.indentSize, insertSpaces: editorOptions_1.EDITOR_MODEL_DEFAULTS.insertSpaces, detectIndentation: false, defaultEOL: 1 /* LF */, trimAutoWhitespace: editorOptions_1.EDITOR_MODEL_DEFAULTS.trimAutoWhitespace, largeFileOptimizations: editorOptions_1.EDITOR_MODEL_DEFAULTS.largeFileOptimizations, }; return TextModel; }(lifecycle_1.Disposable)); exports.TextModel = TextModel; //#region Decorations var DecorationsTrees = /** @class */ (function () { function DecorationsTrees() { this._decorationsTree0 = new intervalTree_1.IntervalTree(); this._decorationsTree1 = new intervalTree_1.IntervalTree(); } DecorationsTrees.prototype.intervalSearch = function (start, end, filterOwnerId, filterOutValidation, cachedVersionId) { var r0 = this._decorationsTree0.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId); var r1 = this._decorationsTree1.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId); return r0.concat(r1); }; DecorationsTrees.prototype.search = function (filterOwnerId, filterOutValidation, overviewRulerOnly, cachedVersionId) { if (overviewRulerOnly) { return this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId); } else { var r0 = this._decorationsTree0.search(filterOwnerId, filterOutValidation, cachedVersionId); var r1 = this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId); return r0.concat(r1); } }; DecorationsTrees.prototype.collectNodesFromOwner = function (ownerId) { var r0 = this._decorationsTree0.collectNodesFromOwner(ownerId); var r1 = this._decorationsTree1.collectNodesFromOwner(ownerId); return r0.concat(r1); }; DecorationsTrees.prototype.collectNodesPostOrder = function () { var r0 = this._decorationsTree0.collectNodesPostOrder(); var r1 = this._decorationsTree1.collectNodesPostOrder(); return r0.concat(r1); }; DecorationsTrees.prototype.insert = function (node) { if (intervalTree_1.getNodeIsInOverviewRuler(node)) { this._decorationsTree1.insert(node); } else { this._decorationsTree0.insert(node); } }; DecorationsTrees.prototype.delete = function (node) { if (intervalTree_1.getNodeIsInOverviewRuler(node)) { this._decorationsTree1.delete(node); } else { this._decorationsTree0.delete(node); } }; DecorationsTrees.prototype.resolveNode = function (node, cachedVersionId) { if (intervalTree_1.getNodeIsInOverviewRuler(node)) { this._decorationsTree1.resolveNode(node, cachedVersionId); } else { this._decorationsTree0.resolveNode(node, cachedVersionId); } }; DecorationsTrees.prototype.acceptReplace = function (offset, length, textLength, forceMoveMarkers) { this._decorationsTree0.acceptReplace(offset, length, textLength, forceMoveMarkers); this._decorationsTree1.acceptReplace(offset, length, textLength, forceMoveMarkers); }; return DecorationsTrees; }()); function cleanClassName(className) { return className.replace(/[^a-z0-9\-_]/gi, ' '); } var DecorationOptions = /** @class */ (function () { function DecorationOptions(options) { this.color = options.color || ''; this.darkColor = options.darkColor || ''; } return DecorationOptions; }()); var ModelDecorationOverviewRulerOptions = /** @class */ (function (_super) { __extends(ModelDecorationOverviewRulerOptions, _super); function ModelDecorationOverviewRulerOptions(options) { var _this = _super.call(this, options) || this; _this._resolvedColor = null; _this.position = (typeof options.position === 'number' ? options.position : model.OverviewRulerLane.Center); return _this; } ModelDecorationOverviewRulerOptions.prototype.getColor = function (theme) { if (!this._resolvedColor) { if (theme.type !== 'light' && this.darkColor) { this._resolvedColor = this._resolveColor(this.darkColor, theme); } else { this._resolvedColor = this._resolveColor(this.color, theme); } } return this._resolvedColor; }; ModelDecorationOverviewRulerOptions.prototype.invalidateCachedColor = function () { this._resolvedColor = null; }; ModelDecorationOverviewRulerOptions.prototype._resolveColor = function (color, theme) { if (typeof color === 'string') { return color; } var c = color ? theme.getColor(color.id) : null; if (!c) { return ''; } return c.toString(); }; return ModelDecorationOverviewRulerOptions; }(DecorationOptions)); exports.ModelDecorationOverviewRulerOptions = ModelDecorationOverviewRulerOptions; var ModelDecorationMinimapOptions = /** @class */ (function (_super) { __extends(ModelDecorationMinimapOptions, _super); function ModelDecorationMinimapOptions(options) { var _this = _super.call(this, options) || this; _this.position = options.position; return _this; } ModelDecorationMinimapOptions.prototype.getColor = function (theme) { if (!this._resolvedColor) { if (theme.type !== 'light' && this.darkColor) { this._resolvedColor = this._resolveColor(this.darkColor, theme); } else { this._resolvedColor = this._resolveColor(this.color, theme); } } return this._resolvedColor; }; ModelDecorationMinimapOptions.prototype.invalidateCachedColor = function () { this._resolvedColor = undefined; }; ModelDecorationMinimapOptions.prototype._resolveColor = function (color, theme) { if (typeof color === 'string') { return color_1.Color.fromHex(color); } return theme.getColor(color.id); }; return ModelDecorationMinimapOptions; }(DecorationOptions)); exports.ModelDecorationMinimapOptions = ModelDecorationMinimapOptions; var ModelDecorationOptions = /** @class */ (function () { function ModelDecorationOptions(options) { this.stickiness = options.stickiness || 0 /* AlwaysGrowsWhenTypingAtEdges */; this.zIndex = options.zIndex || 0; this.className = options.className ? cleanClassName(options.className) : null; this.hoverMessage = types_1.withUndefinedAsNull(options.hoverMessage); this.glyphMarginHoverMessage = types_1.withUndefinedAsNull(options.glyphMarginHoverMessage); this.isWholeLine = options.isWholeLine || false; this.showIfCollapsed = options.showIfCollapsed || false; this.collapseOnReplaceEdit = options.collapseOnReplaceEdit || false; this.overviewRuler = options.overviewRuler ? new ModelDecorationOverviewRulerOptions(options.overviewRuler) : null; this.minimap = options.minimap ? new ModelDecorationMinimapOptions(options.minimap) : null; this.glyphMarginClassName = options.glyphMarginClassName ? cleanClassName(options.glyphMarginClassName) : null; this.linesDecorationsClassName = options.linesDecorationsClassName ? cleanClassName(options.linesDecorationsClassName) : null; this.marginClassName = options.marginClassName ? cleanClassName(options.marginClassName) : null; this.inlineClassName = options.inlineClassName ? cleanClassName(options.inlineClassName) : null; this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false; this.beforeContentClassName = options.beforeContentClassName ? cleanClassName(options.beforeContentClassName) : null; this.afterContentClassName = options.afterContentClassName ? cleanClassName(options.afterContentClassName) : null; } ModelDecorationOptions.register = function (options) { return new ModelDecorationOptions(options); }; ModelDecorationOptions.createDynamic = function (options) { return new ModelDecorationOptions(options); }; return ModelDecorationOptions; }()); exports.ModelDecorationOptions = ModelDecorationOptions; ModelDecorationOptions.EMPTY = ModelDecorationOptions.register({}); /** * The order carefully matches the values of the enum. */ var TRACKED_RANGE_OPTIONS = [ ModelDecorationOptions.register({ stickiness: 0 /* AlwaysGrowsWhenTypingAtEdges */ }), ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ }), ModelDecorationOptions.register({ stickiness: 2 /* GrowsOnlyWhenTypingBefore */ }), ModelDecorationOptions.register({ stickiness: 3 /* GrowsOnlyWhenTypingAfter */ }), ]; function _normalizeOptions(options) { if (options instanceof ModelDecorationOptions) { return options; } return ModelDecorationOptions.createDynamic(options); } var DidChangeDecorationsEmitter = /** @class */ (function (_super) { __extends(DidChangeDecorationsEmitter, _super); function DidChangeDecorationsEmitter() { var _this = _super.call(this) || this; _this._actual = _this._register(new event_1.Emitter()); _this.event = _this._actual.event; _this._deferredCnt = 0; _this._shouldFire = false; return _this; } DidChangeDecorationsEmitter.prototype.beginDeferredEmit = function () { this._deferredCnt++; }; DidChangeDecorationsEmitter.prototype.endDeferredEmit = function () { this._deferredCnt--; if (this._deferredCnt === 0) { if (this._shouldFire) { this._shouldFire = false; this._actual.fire({}); } } }; DidChangeDecorationsEmitter.prototype.fire = function () { this._shouldFire = true; }; return DidChangeDecorationsEmitter; }(lifecycle_1.Disposable)); exports.DidChangeDecorationsEmitter = DidChangeDecorationsEmitter; //#endregion var DidChangeContentEmitter = /** @class */ (function (_super) { __extends(DidChangeContentEmitter, _super); function DidChangeContentEmitter() { var _this = _super.call(this) || this; /** * Both `fastEvent` and `slowEvent` work the same way and contain the same events, but first we invoke `fastEvent` and then `slowEvent`. */ _this._fastEmitter = _this._register(new event_1.Emitter()); _this.fastEvent = _this._fastEmitter.event; _this._slowEmitter = _this._register(new event_1.Emitter()); _this.slowEvent = _this._slowEmitter.event; _this._deferredCnt = 0; _this._deferredEvent = null; return _this; } DidChangeContentEmitter.prototype.beginDeferredEmit = function () { this._deferredCnt++; }; DidChangeContentEmitter.prototype.endDeferredEmit = function () { this._deferredCnt--; if (this._deferredCnt === 0) { if (this._deferredEvent !== null) { var e = this._deferredEvent; this._deferredEvent = null; this._fastEmitter.fire(e); this._slowEmitter.fire(e); } } }; DidChangeContentEmitter.prototype.fire = function (e) { if (this._deferredCnt > 0) { if (this._deferredEvent) { this._deferredEvent = this._deferredEvent.merge(e); } else { this._deferredEvent = e; } return; } this._fastEmitter.fire(e); this._slowEmitter.fire(e); }; return DidChangeContentEmitter; }(lifecycle_1.Disposable)); exports.DidChangeContentEmitter = DidChangeContentEmitter; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[40/*vs/editor/common/controller/cursorCommon*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,5/*vs/base/common/strings*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,30/*vs/editor/common/model/textModel*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, errors_1, strings, position_1, range_1, selection_1, textModel_1, languageConfigurationRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var autoCloseAlways = function () { return true; }; var autoCloseNever = function () { return false; }; var autoCloseBeforeWhitespace = function (chr) { return (chr === ' ' || chr === '\t'); }; function appendEntry(target, key, value) { if (target.has(key)) { target.get(key).push(value); } else { target.set(key, [value]); } } var CursorConfiguration = /** @class */ (function () { function CursorConfiguration(languageIdentifier, modelOptions, configuration) { this._languageIdentifier = languageIdentifier; var options = configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); this.readOnly = options.get(68 /* readOnly */); this.tabSize = modelOptions.tabSize; this.indentSize = modelOptions.indentSize; this.insertSpaces = modelOptions.insertSpaces; this.lineHeight = options.get(49 /* lineHeight */); this.pageSize = Math.max(1, Math.floor(layoutInfo.height / this.lineHeight) - 2); this.useTabStops = options.get(95 /* useTabStops */); this.wordSeparators = options.get(96 /* wordSeparators */); this.emptySelectionClipboard = options.get(25 /* emptySelectionClipboard */); this.copyWithSyntaxHighlighting = options.get(15 /* copyWithSyntaxHighlighting */); this.multiCursorMergeOverlapping = options.get(58 /* multiCursorMergeOverlapping */); this.multiCursorPaste = options.get(60 /* multiCursorPaste */); this.autoClosingBrackets = options.get(5 /* autoClosingBrackets */); this.autoClosingQuotes = options.get(7 /* autoClosingQuotes */); this.autoClosingOvertype = options.get(6 /* autoClosingOvertype */); this.autoSurround = options.get(10 /* autoSurround */); this.autoIndent = options.get(8 /* autoIndent */); this.autoClosingPairsOpen2 = new Map(); this.autoClosingPairsClose2 = new Map(); this.surroundingPairs = {}; this._electricChars = null; this.shouldAutoCloseBefore = { quote: CursorConfiguration._getShouldAutoClose(languageIdentifier, this.autoClosingQuotes), bracket: CursorConfiguration._getShouldAutoClose(languageIdentifier, this.autoClosingBrackets) }; var autoClosingPairs = CursorConfiguration._getAutoClosingPairs(languageIdentifier); if (autoClosingPairs) { for (var _i = 0, autoClosingPairs_1 = autoClosingPairs; _i < autoClosingPairs_1.length; _i++) { var pair = autoClosingPairs_1[_i]; appendEntry(this.autoClosingPairsOpen2, pair.open.charAt(pair.open.length - 1), pair); if (pair.close.length === 1) { appendEntry(this.autoClosingPairsClose2, pair.close, pair); } } } var surroundingPairs = CursorConfiguration._getSurroundingPairs(languageIdentifier); if (surroundingPairs) { for (var _a = 0, surroundingPairs_1 = surroundingPairs; _a < surroundingPairs_1.length; _a++) { var pair = surroundingPairs_1[_a]; this.surroundingPairs[pair.open] = pair.close; } } } CursorConfiguration.shouldRecreate = function (e) { return (e.hasChanged(107 /* layoutInfo */) || e.hasChanged(96 /* wordSeparators */) || e.hasChanged(25 /* emptySelectionClipboard */) || e.hasChanged(58 /* multiCursorMergeOverlapping */) || e.hasChanged(60 /* multiCursorPaste */) || e.hasChanged(5 /* autoClosingBrackets */) || e.hasChanged(7 /* autoClosingQuotes */) || e.hasChanged(6 /* autoClosingOvertype */) || e.hasChanged(10 /* autoSurround */) || e.hasChanged(95 /* useTabStops */) || e.hasChanged(49 /* lineHeight */) || e.hasChanged(68 /* readOnly */)); }; Object.defineProperty(CursorConfiguration.prototype, "electricChars", { get: function () { if (!this._electricChars) { this._electricChars = {}; var electricChars = CursorConfiguration._getElectricCharacters(this._languageIdentifier); if (electricChars) { for (var _i = 0, electricChars_1 = electricChars; _i < electricChars_1.length; _i++) { var char = electricChars_1[_i]; this._electricChars[char] = true; } } } return this._electricChars; }, enumerable: true, configurable: true }); CursorConfiguration.prototype.normalizeIndentation = function (str) { return textModel_1.TextModel.normalizeIndentation(str, this.indentSize, this.insertSpaces); }; CursorConfiguration._getElectricCharacters = function (languageIdentifier) { try { return languageConfigurationRegistry_1.LanguageConfigurationRegistry.getElectricCharacters(languageIdentifier.id); } catch (e) { errors_1.onUnexpectedError(e); return null; } }; CursorConfiguration._getAutoClosingPairs = function (languageIdentifier) { try { return languageConfigurationRegistry_1.LanguageConfigurationRegistry.getAutoClosingPairs(languageIdentifier.id); } catch (e) { errors_1.onUnexpectedError(e); return null; } }; CursorConfiguration._getShouldAutoClose = function (languageIdentifier, autoCloseConfig) { switch (autoCloseConfig) { case 'beforeWhitespace': return autoCloseBeforeWhitespace; case 'languageDefined': return CursorConfiguration._getLanguageDefinedShouldAutoClose(languageIdentifier); case 'always': return autoCloseAlways; case 'never': return autoCloseNever; } }; CursorConfiguration._getLanguageDefinedShouldAutoClose = function (languageIdentifier) { try { var autoCloseBeforeSet_1 = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getAutoCloseBeforeSet(languageIdentifier.id); return function (c) { return autoCloseBeforeSet_1.indexOf(c) !== -1; }; } catch (e) { errors_1.onUnexpectedError(e); return autoCloseNever; } }; CursorConfiguration._getSurroundingPairs = function (languageIdentifier) { try { return languageConfigurationRegistry_1.LanguageConfigurationRegistry.getSurroundingPairs(languageIdentifier.id); } catch (e) { errors_1.onUnexpectedError(e); return null; } }; return CursorConfiguration; }()); exports.CursorConfiguration = CursorConfiguration; /** * Represents the cursor state on either the model or on the view model. */ var SingleCursorState = /** @class */ (function () { function SingleCursorState(selectionStart, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns) { this.selectionStart = selectionStart; this.selectionStartLeftoverVisibleColumns = selectionStartLeftoverVisibleColumns; this.position = position; this.leftoverVisibleColumns = leftoverVisibleColumns; this.selection = SingleCursorState._computeSelection(this.selectionStart, this.position); } SingleCursorState.prototype.equals = function (other) { return (this.selectionStartLeftoverVisibleColumns === other.selectionStartLeftoverVisibleColumns && this.leftoverVisibleColumns === other.leftoverVisibleColumns && this.position.equals(other.position) && this.selectionStart.equalsRange(other.selectionStart)); }; SingleCursorState.prototype.hasSelection = function () { return (!this.selection.isEmpty() || !this.selectionStart.isEmpty()); }; SingleCursorState.prototype.move = function (inSelectionMode, lineNumber, column, leftoverVisibleColumns) { if (inSelectionMode) { // move just position return new SingleCursorState(this.selectionStart, this.selectionStartLeftoverVisibleColumns, new position_1.Position(lineNumber, column), leftoverVisibleColumns); } else { // move everything return new SingleCursorState(new range_1.Range(lineNumber, column, lineNumber, column), leftoverVisibleColumns, new position_1.Position(lineNumber, column), leftoverVisibleColumns); } }; SingleCursorState._computeSelection = function (selectionStart, position) { var startLineNumber, startColumn, endLineNumber, endColumn; if (selectionStart.isEmpty()) { startLineNumber = selectionStart.startLineNumber; startColumn = selectionStart.startColumn; endLineNumber = position.lineNumber; endColumn = position.column; } else { if (position.isBeforeOrEqual(selectionStart.getStartPosition())) { startLineNumber = selectionStart.endLineNumber; startColumn = selectionStart.endColumn; endLineNumber = position.lineNumber; endColumn = position.column; } else { startLineNumber = selectionStart.startLineNumber; startColumn = selectionStart.startColumn; endLineNumber = position.lineNumber; endColumn = position.column; } } return new selection_1.Selection(startLineNumber, startColumn, endLineNumber, endColumn); }; return SingleCursorState; }()); exports.SingleCursorState = SingleCursorState; var CursorContext = /** @class */ (function () { function CursorContext(configuration, model, viewModel) { this.model = model; this.viewModel = viewModel; this.config = new CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), configuration); } CursorContext.prototype.validateViewPosition = function (viewPosition, modelPosition) { return this.viewModel.coordinatesConverter.validateViewPosition(viewPosition, modelPosition); }; CursorContext.prototype.validateViewRange = function (viewRange, expectedModelRange) { return this.viewModel.coordinatesConverter.validateViewRange(viewRange, expectedModelRange); }; CursorContext.prototype.convertViewRangeToModelRange = function (viewRange) { return this.viewModel.coordinatesConverter.convertViewRangeToModelRange(viewRange); }; CursorContext.prototype.convertViewPositionToModelPosition = function (lineNumber, column) { return this.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(lineNumber, column)); }; CursorContext.prototype.convertModelPositionToViewPosition = function (modelPosition) { return this.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition); }; CursorContext.prototype.convertModelRangeToViewRange = function (modelRange) { return this.viewModel.coordinatesConverter.convertModelRangeToViewRange(modelRange); }; CursorContext.prototype.getCurrentScrollTop = function () { return this.viewModel.viewLayout.getCurrentScrollTop(); }; CursorContext.prototype.getCompletelyVisibleViewRange = function () { return this.viewModel.getCompletelyVisibleViewRange(); }; CursorContext.prototype.getCompletelyVisibleModelRange = function () { var viewRange = this.viewModel.getCompletelyVisibleViewRange(); return this.viewModel.coordinatesConverter.convertViewRangeToModelRange(viewRange); }; CursorContext.prototype.getCompletelyVisibleViewRangeAtScrollTop = function (scrollTop) { return this.viewModel.getCompletelyVisibleViewRangeAtScrollTop(scrollTop); }; CursorContext.prototype.getVerticalOffsetForViewLine = function (viewLineNumber) { return this.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewLineNumber); }; return CursorContext; }()); exports.CursorContext = CursorContext; var PartialModelCursorState = /** @class */ (function () { function PartialModelCursorState(modelState) { this.modelState = modelState; this.viewState = null; } return PartialModelCursorState; }()); exports.PartialModelCursorState = PartialModelCursorState; var PartialViewCursorState = /** @class */ (function () { function PartialViewCursorState(viewState) { this.modelState = null; this.viewState = viewState; } return PartialViewCursorState; }()); exports.PartialViewCursorState = PartialViewCursorState; var CursorState = /** @class */ (function () { function CursorState(modelState, viewState) { this.modelState = modelState; this.viewState = viewState; } CursorState.fromModelState = function (modelState) { return new PartialModelCursorState(modelState); }; CursorState.fromViewState = function (viewState) { return new PartialViewCursorState(viewState); }; CursorState.fromModelSelection = function (modelSelection) { var selectionStartLineNumber = modelSelection.selectionStartLineNumber; var selectionStartColumn = modelSelection.selectionStartColumn; var positionLineNumber = modelSelection.positionLineNumber; var positionColumn = modelSelection.positionColumn; var modelState = new SingleCursorState(new range_1.Range(selectionStartLineNumber, selectionStartColumn, selectionStartLineNumber, selectionStartColumn), 0, new position_1.Position(positionLineNumber, positionColumn), 0); return CursorState.fromModelState(modelState); }; CursorState.fromModelSelections = function (modelSelections) { var states = []; for (var i = 0, len = modelSelections.length; i < len; i++) { states[i] = this.fromModelSelection(modelSelections[i]); } return states; }; CursorState.prototype.equals = function (other) { return (this.viewState.equals(other.viewState) && this.modelState.equals(other.modelState)); }; return CursorState; }()); exports.CursorState = CursorState; var EditOperationResult = /** @class */ (function () { function EditOperationResult(type, commands, opts) { this.type = type; this.commands = commands; this.shouldPushStackElementBefore = opts.shouldPushStackElementBefore; this.shouldPushStackElementAfter = opts.shouldPushStackElementAfter; } return EditOperationResult; }()); exports.EditOperationResult = EditOperationResult; /** * Common operations that work and make sense both on the model and on the view model. */ var CursorColumns = /** @class */ (function () { function CursorColumns() { } CursorColumns.visibleColumnFromColumn = function (lineContent, column, tabSize) { var lineContentLength = lineContent.length; var endOffset = column - 1 < lineContentLength ? column - 1 : lineContentLength; var result = 0; var i = 0; while (i < endOffset) { var codePoint = strings.getNextCodePoint(lineContent, endOffset, i); i += (codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); if (codePoint === 9 /* Tab */) { result = CursorColumns.nextRenderTabStop(result, tabSize); } else { var graphemeBreakType = strings.getGraphemeBreakType(codePoint); while (i < endOffset) { var nextCodePoint = strings.getNextCodePoint(lineContent, endOffset, i); var nextGraphemeBreakType = strings.getGraphemeBreakType(nextCodePoint); if (strings.breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) { break; } i += (nextCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); graphemeBreakType = nextGraphemeBreakType; } if (strings.isFullWidthCharacter(codePoint) || strings.isEmojiImprecise(codePoint)) { result = result + 2; } else { result = result + 1; } } } return result; }; CursorColumns.visibleColumnFromColumn2 = function (config, model, position) { return this.visibleColumnFromColumn(model.getLineContent(position.lineNumber), position.column, config.tabSize); }; CursorColumns.columnFromVisibleColumn = function (lineContent, visibleColumn, tabSize) { if (visibleColumn <= 0) { return 1; } var lineLength = lineContent.length; var beforeVisibleColumn = 0; var beforeColumn = 1; var i = 0; while (i < lineLength) { var codePoint = strings.getNextCodePoint(lineContent, lineLength, i); i += (codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); var afterVisibleColumn = void 0; if (codePoint === 9 /* Tab */) { afterVisibleColumn = CursorColumns.nextRenderTabStop(beforeVisibleColumn, tabSize); } else { var graphemeBreakType = strings.getGraphemeBreakType(codePoint); while (i < lineLength) { var nextCodePoint = strings.getNextCodePoint(lineContent, lineLength, i); var nextGraphemeBreakType = strings.getGraphemeBreakType(nextCodePoint); if (strings.breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) { break; } i += (nextCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); graphemeBreakType = nextGraphemeBreakType; } if (strings.isFullWidthCharacter(codePoint) || strings.isEmojiImprecise(codePoint)) { afterVisibleColumn = beforeVisibleColumn + 2; } else { afterVisibleColumn = beforeVisibleColumn + 1; } } var afterColumn = i + 1; if (afterVisibleColumn >= visibleColumn) { var beforeDelta = visibleColumn - beforeVisibleColumn; var afterDelta = afterVisibleColumn - visibleColumn; if (afterDelta < beforeDelta) { return afterColumn; } else { return beforeColumn; } } beforeVisibleColumn = afterVisibleColumn; beforeColumn = afterColumn; } // walked the entire string return lineLength + 1; }; CursorColumns.columnFromVisibleColumn2 = function (config, model, lineNumber, visibleColumn) { var result = this.columnFromVisibleColumn(model.getLineContent(lineNumber), visibleColumn, config.tabSize); var minColumn = model.getLineMinColumn(lineNumber); if (result < minColumn) { return minColumn; } var maxColumn = model.getLineMaxColumn(lineNumber); if (result > maxColumn) { return maxColumn; } return result; }; /** * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns) */ CursorColumns.nextRenderTabStop = function (visibleColumn, tabSize) { return visibleColumn + tabSize - visibleColumn % tabSize; }; /** * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns) */ CursorColumns.nextIndentTabStop = function (visibleColumn, indentSize) { return visibleColumn + indentSize - visibleColumn % indentSize; }; /** * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns) */ CursorColumns.prevRenderTabStop = function (column, tabSize) { return column - 1 - (column - 1) % tabSize; }; /** * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns) */ CursorColumns.prevIndentTabStop = function (column, indentSize) { return column - 1 - (column - 1) % indentSize; }; return CursorColumns; }()); exports.CursorColumns = CursorColumns; function isQuote(ch) { return (ch === '\'' || ch === '"' || ch === '`'); } exports.isQuote = isQuote; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[211/*vs/editor/common/commands/shiftCommand*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,40/*vs/editor/common/controller/cursorCommon*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, strings, cursorCommon_1, range_1, selection_1, languageConfigurationRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var repeatCache = Object.create(null); function cachedStringRepeat(str, count) { if (!repeatCache[str]) { repeatCache[str] = ['', str]; } var cache = repeatCache[str]; for (var i = cache.length; i <= count; i++) { cache[i] = cache[i - 1] + str; } return cache[count]; } exports.cachedStringRepeat = cachedStringRepeat; var ShiftCommand = /** @class */ (function () { function ShiftCommand(range, opts) { this._opts = opts; this._selection = range; this._selectionId = null; this._useLastEditRangeForCursorEndPosition = false; this._selectionStartColumnStaysPut = false; } ShiftCommand.unshiftIndent = function (line, column, tabSize, indentSize, insertSpaces) { // Determine the visible column where the content starts var contentStartVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(line, column, tabSize); if (insertSpaces) { var indent = cachedStringRepeat(' ', indentSize); var desiredTabStop = cursorCommon_1.CursorColumns.prevIndentTabStop(contentStartVisibleColumn, indentSize); var indentCount = desiredTabStop / indentSize; // will be an integer return cachedStringRepeat(indent, indentCount); } else { var indent = '\t'; var desiredTabStop = cursorCommon_1.CursorColumns.prevRenderTabStop(contentStartVisibleColumn, tabSize); var indentCount = desiredTabStop / tabSize; // will be an integer return cachedStringRepeat(indent, indentCount); } }; ShiftCommand.shiftIndent = function (line, column, tabSize, indentSize, insertSpaces) { // Determine the visible column where the content starts var contentStartVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(line, column, tabSize); if (insertSpaces) { var indent = cachedStringRepeat(' ', indentSize); var desiredTabStop = cursorCommon_1.CursorColumns.nextIndentTabStop(contentStartVisibleColumn, indentSize); var indentCount = desiredTabStop / indentSize; // will be an integer return cachedStringRepeat(indent, indentCount); } else { var indent = '\t'; var desiredTabStop = cursorCommon_1.CursorColumns.nextRenderTabStop(contentStartVisibleColumn, tabSize); var indentCount = desiredTabStop / tabSize; // will be an integer return cachedStringRepeat(indent, indentCount); } }; ShiftCommand.prototype._addEditOperation = function (builder, range, text) { if (this._useLastEditRangeForCursorEndPosition) { builder.addTrackedEditOperation(range, text); } else { builder.addEditOperation(range, text); } }; ShiftCommand.prototype.getEditOperations = function (model, builder) { var startLine = this._selection.startLineNumber; var endLine = this._selection.endLineNumber; if (this._selection.endColumn === 1 && startLine !== endLine) { endLine = endLine - 1; } var _a = this._opts, tabSize = _a.tabSize, indentSize = _a.indentSize, insertSpaces = _a.insertSpaces; var shouldIndentEmptyLines = (startLine === endLine); // if indenting or outdenting on a whitespace only line if (this._selection.isEmpty()) { if (/^\s*$/.test(model.getLineContent(startLine))) { this._useLastEditRangeForCursorEndPosition = true; } } if (this._opts.useTabStops) { // keep track of previous line's "miss-alignment" var previousLineExtraSpaces = 0, extraSpaces = 0; for (var lineNumber = startLine; lineNumber <= endLine; lineNumber++, previousLineExtraSpaces = extraSpaces) { extraSpaces = 0; var lineText = model.getLineContent(lineNumber); var 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) { var contentStartVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(lineText, indentationEndIndex + 1, tabSize); if (contentStartVisibleColumn % indentSize !== 0) { // The current line is "miss-aligned", so let's see if this is expected... // This can only happen when it has trailing commas in the indent if (model.isCheapToTokenize(lineNumber - 1)) { var 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 (var 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 (var 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; } var desiredIndent = void 0; 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 { var oneIndent = (insertSpaces ? cachedStringRepeat(' ', indentSize) : '\t'); for (var lineNumber = startLine; lineNumber <= endLine; lineNumber++) { var lineText = model.getLineContent(lineNumber); var 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 (var i = 0; i < indentationEndIndex; i++) { var 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); }; ShiftCommand.prototype.computeCursorState = function (model, helper) { if (this._useLastEditRangeForCursorEndPosition) { var lastOp = helper.getInverseEditOperations()[0]; return new selection_1.Selection(lastOp.range.endLineNumber, lastOp.range.endColumn, lastOp.range.endLineNumber, lastOp.range.endColumn); } var result = helper.getTrackedSelection(this._selectionId); if (this._selectionStartColumnStaysPut) { // The selection start should not move var initialStartColumn = this._selection.startColumn; var 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; }; return ShiftCommand; }()); 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[483/*vs/editor/common/controller/cursorColumnSelection*/], __M([0/*require*/,1/*exports*/,40/*vs/editor/common/controller/cursorCommon*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, cursorCommon_1, position_1, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ColumnSelection = /** @class */ (function () { function ColumnSelection() { } ColumnSelection.columnSelect = function (config, model, fromLineNumber, fromVisibleColumn, toLineNumber, toVisibleColumn) { var lineCount = Math.abs(toLineNumber - fromLineNumber) + 1; var reversed = (fromLineNumber > toLineNumber); var isRTL = (fromVisibleColumn > toVisibleColumn); var isLTR = (fromVisibleColumn < toVisibleColumn); var result = []; // console.log(`fromVisibleColumn: ${fromVisibleColumn}, toVisibleColumn: ${toVisibleColumn}`); for (var i = 0; i < lineCount; i++) { var lineNumber = fromLineNumber + (reversed ? -i : i); var startColumn = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, fromVisibleColumn); var endColumn = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, toVisibleColumn); var visibleStartColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, new position_1.Position(lineNumber, startColumn)); var visibleEndColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, new position_1.Position(lineNumber, endColumn)); // console.log(`lineNumber: ${lineNumber}: visibleStartColumn: ${visibleStartColumn}, visibleEndColumn: ${visibleEndColumn}`); if (isLTR) { if (visibleStartColumn > toVisibleColumn) { continue; } if (visibleEndColumn < fromVisibleColumn) { continue; } } if (isRTL) { if (visibleEndColumn > fromVisibleColumn) { continue; } if (visibleStartColumn < toVisibleColumn) { continue; } } result.push(new cursorCommon_1.SingleCursorState(new range_1.Range(lineNumber, startColumn, lineNumber, startColumn), 0, new position_1.Position(lineNumber, endColumn), 0)); } if (result.length === 0) { // We are after all the lines, so add cursor at the end of each line for (var i = 0; i < lineCount; i++) { var lineNumber = fromLineNumber + (reversed ? -i : i); var maxColumn = model.getLineMaxColumn(lineNumber); result.push(new cursorCommon_1.SingleCursorState(new range_1.Range(lineNumber, maxColumn, lineNumber, maxColumn), 0, new position_1.Position(lineNumber, maxColumn), 0)); } } return { viewStates: result, reversed: reversed, fromLineNumber: fromLineNumber, fromVisualColumn: fromVisibleColumn, toLineNumber: toLineNumber, toVisualColumn: toVisibleColumn }; }; ColumnSelection.columnSelectLeft = function (config, model, prevColumnSelectData) { var toViewVisualColumn = prevColumnSelectData.toViewVisualColumn; if (toViewVisualColumn > 1) { toViewVisualColumn--; } return ColumnSelection.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn); }; ColumnSelection.columnSelectRight = function (config, model, prevColumnSelectData) { var maxVisualViewColumn = 0; var minViewLineNumber = Math.min(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber); var maxViewLineNumber = Math.max(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber); for (var lineNumber = minViewLineNumber; lineNumber <= maxViewLineNumber; lineNumber++) { var lineMaxViewColumn = model.getLineMaxColumn(lineNumber); var lineMaxVisualViewColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, new position_1.Position(lineNumber, lineMaxViewColumn)); maxVisualViewColumn = Math.max(maxVisualViewColumn, lineMaxVisualViewColumn); } var toViewVisualColumn = prevColumnSelectData.toViewVisualColumn; if (toViewVisualColumn < maxVisualViewColumn) { toViewVisualColumn++; } return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn); }; ColumnSelection.columnSelectUp = function (config, model, prevColumnSelectData, isPaged) { var linesCount = isPaged ? config.pageSize : 1; var toViewLineNumber = Math.max(1, prevColumnSelectData.toViewLineNumber - linesCount); return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn); }; ColumnSelection.columnSelectDown = function (config, model, prevColumnSelectData, isPaged) { var linesCount = isPaged ? config.pageSize : 1; var toViewLineNumber = Math.min(model.getLineCount(), prevColumnSelectData.toViewLineNumber + linesCount); return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn); }; return ColumnSelection; }()); exports.ColumnSelection = ColumnSelection; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[158/*vs/editor/common/controller/cursorMoveOperations*/], __M([0/*require*/,1/*exports*/,40/*vs/editor/common/controller/cursorCommon*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,5/*vs/base/common/strings*/]), function (require, exports, cursorCommon_1, position_1, range_1, strings) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CursorPosition = /** @class */ (function () { function CursorPosition(lineNumber, column, leftoverVisibleColumns) { this.lineNumber = lineNumber; this.column = column; this.leftoverVisibleColumns = leftoverVisibleColumns; } return CursorPosition; }()); exports.CursorPosition = CursorPosition; var MoveOperations = /** @class */ (function () { function MoveOperations() { } MoveOperations.leftPosition = function (model, lineNumber, column) { if (column > model.getLineMinColumn(lineNumber)) { column = column - strings.prevCharLength(model.getLineContent(lineNumber), column - 1); } else if (lineNumber > 1) { lineNumber = lineNumber - 1; column = model.getLineMaxColumn(lineNumber); } return new position_1.Position(lineNumber, column); }; MoveOperations.left = function (config, model, lineNumber, column) { var pos = MoveOperations.leftPosition(model, lineNumber, column); return new CursorPosition(pos.lineNumber, pos.column, 0); }; MoveOperations.moveLeft = function (config, model, cursor, inSelectionMode, noOfColumns) { var lineNumber, column; if (cursor.hasSelection() && !inSelectionMode) { // If we are in selection mode, move left without selection cancels selection and puts cursor at the beginning of the selection lineNumber = cursor.selection.startLineNumber; column = cursor.selection.startColumn; } else { var r = MoveOperations.left(config, model, cursor.position.lineNumber, cursor.position.column - (noOfColumns - 1)); lineNumber = r.lineNumber; column = r.column; } return cursor.move(inSelectionMode, lineNumber, column, 0); }; MoveOperations.rightPosition = function (model, lineNumber, column) { if (column < model.getLineMaxColumn(lineNumber)) { column = column + strings.nextCharLength(model.getLineContent(lineNumber), column - 1); } else if (lineNumber < model.getLineCount()) { lineNumber = lineNumber + 1; column = model.getLineMinColumn(lineNumber); } return new position_1.Position(lineNumber, column); }; MoveOperations.right = function (config, model, lineNumber, column) { var pos = MoveOperations.rightPosition(model, lineNumber, column); return new CursorPosition(pos.lineNumber, pos.column, 0); }; MoveOperations.moveRight = function (config, model, cursor, inSelectionMode, noOfColumns) { var lineNumber, column; if (cursor.hasSelection() && !inSelectionMode) { // If we are in selection mode, move right without selection cancels selection and puts cursor at the end of the selection lineNumber = cursor.selection.endLineNumber; column = cursor.selection.endColumn; } else { var r = MoveOperations.right(config, model, cursor.position.lineNumber, cursor.position.column + (noOfColumns - 1)); lineNumber = r.lineNumber; column = r.column; } return cursor.move(inSelectionMode, lineNumber, column, 0); }; MoveOperations.down = function (config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnLastLine) { var currentVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns; lineNumber = lineNumber + count; var lineCount = model.getLineCount(); if (lineNumber > lineCount) { lineNumber = lineCount; if (allowMoveOnLastLine) { column = model.getLineMaxColumn(lineNumber); } else { column = Math.min(model.getLineMaxColumn(lineNumber), column); } } else { column = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, currentVisibleColumn); } leftoverVisibleColumns = currentVisibleColumn - cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize); return new CursorPosition(lineNumber, column, leftoverVisibleColumns); }; MoveOperations.moveDown = function (config, model, cursor, inSelectionMode, linesCount) { var lineNumber, column; if (cursor.hasSelection() && !inSelectionMode) { // If we are in selection mode, move down acts relative to the end of selection lineNumber = cursor.selection.endLineNumber; column = cursor.selection.endColumn; } else { lineNumber = cursor.position.lineNumber; column = cursor.position.column; } var r = MoveOperations.down(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true); return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns); }; MoveOperations.translateDown = function (config, model, cursor) { var selection = cursor.selection; var selectionStart = MoveOperations.down(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false); var position = MoveOperations.down(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false); return new cursorCommon_1.SingleCursorState(new range_1.Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), selectionStart.leftoverVisibleColumns, new position_1.Position(position.lineNumber, position.column), position.leftoverVisibleColumns); }; MoveOperations.up = function (config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnFirstLine) { var currentVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns; lineNumber = lineNumber - count; if (lineNumber < 1) { lineNumber = 1; if (allowMoveOnFirstLine) { column = model.getLineMinColumn(lineNumber); } else { column = Math.min(model.getLineMaxColumn(lineNumber), column); } } else { column = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, currentVisibleColumn); } leftoverVisibleColumns = currentVisibleColumn - cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize); return new CursorPosition(lineNumber, column, leftoverVisibleColumns); }; MoveOperations.moveUp = function (config, model, cursor, inSelectionMode, linesCount) { var lineNumber, column; if (cursor.hasSelection() && !inSelectionMode) { // If we are in selection mode, move up acts relative to the beginning of selection lineNumber = cursor.selection.startLineNumber; column = cursor.selection.startColumn; } else { lineNumber = cursor.position.lineNumber; column = cursor.position.column; } var r = MoveOperations.up(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true); return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns); }; MoveOperations.translateUp = function (config, model, cursor) { var selection = cursor.selection; var selectionStart = MoveOperations.up(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false); var position = MoveOperations.up(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false); return new cursorCommon_1.SingleCursorState(new range_1.Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), selectionStart.leftoverVisibleColumns, new position_1.Position(position.lineNumber, position.column), position.leftoverVisibleColumns); }; MoveOperations.moveToBeginningOfLine = function (config, model, cursor, inSelectionMode) { var lineNumber = cursor.position.lineNumber; var minColumn = model.getLineMinColumn(lineNumber); var firstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(lineNumber) || minColumn; var column; var relevantColumnNumber = cursor.position.column; if (relevantColumnNumber === firstNonBlankColumn) { column = minColumn; } else { column = firstNonBlankColumn; } return cursor.move(inSelectionMode, lineNumber, column, 0); }; MoveOperations.moveToEndOfLine = function (config, model, cursor, inSelectionMode) { var lineNumber = cursor.position.lineNumber; var maxColumn = model.getLineMaxColumn(lineNumber); return cursor.move(inSelectionMode, lineNumber, maxColumn, 0); }; MoveOperations.moveToBeginningOfBuffer = function (config, model, cursor, inSelectionMode) { return cursor.move(inSelectionMode, 1, 1, 0); }; MoveOperations.moveToEndOfBuffer = function (config, model, cursor, inSelectionMode) { var lastLineNumber = model.getLineCount(); var lastColumn = model.getLineMaxColumn(lastLineNumber); return cursor.move(inSelectionMode, lastLineNumber, lastColumn, 0); }; return MoveOperations; }()); exports.MoveOperations = MoveOperations; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[212/*vs/editor/common/controller/cursorDeleteOperations*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,80/*vs/editor/common/commands/replaceCommand*/,40/*vs/editor/common/controller/cursorCommon*/,158/*vs/editor/common/controller/cursorMoveOperations*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings, replaceCommand_1, cursorCommon_1, cursorMoveOperations_1, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DeleteOperations = /** @class */ (function () { function DeleteOperations() { } DeleteOperations.deleteRight = function (prevEditOperationType, config, model, selections) { var commands = []; var shouldPushStackElementBefore = (prevEditOperationType !== 3 /* DeletingRight */); for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; var deleteSelection = selection; if (deleteSelection.isEmpty()) { var position = selection.getPosition(); var rightOfPosition = cursorMoveOperations_1.MoveOperations.right(config, model, position.lineNumber, position.column); deleteSelection = new range_1.Range(rightOfPosition.lineNumber, rightOfPosition.column, position.lineNumber, position.column); } if (deleteSelection.isEmpty()) { // Probably at end of file => ignore commands[i] = null; continue; } if (deleteSelection.startLineNumber !== deleteSelection.endLineNumber) { shouldPushStackElementBefore = true; } commands[i] = new replaceCommand_1.ReplaceCommand(deleteSelection, ''); } return [shouldPushStackElementBefore, commands]; }; DeleteOperations._isAutoClosingPairDelete = function (config, model, selections) { if (config.autoClosingBrackets === 'never' && config.autoClosingQuotes === 'never') { return false; } for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; var position = selection.getPosition(); if (!selection.isEmpty()) { return false; } var lineText = model.getLineContent(position.lineNumber); var character = lineText[position.column - 2]; var autoClosingPairCandidates = config.autoClosingPairsOpen2.get(character); if (!autoClosingPairCandidates) { return false; } if (cursorCommon_1.isQuote(character)) { if (config.autoClosingQuotes === 'never') { return false; } } else { if (config.autoClosingBrackets === 'never') { return false; } } var afterCharacter = lineText[position.column - 1]; var foundAutoClosingPair = false; for (var _i = 0, autoClosingPairCandidates_1 = autoClosingPairCandidates; _i < autoClosingPairCandidates_1.length; _i++) { var autoClosingPairCandidate = autoClosingPairCandidates_1[_i]; if (autoClosingPairCandidate.open === character && autoClosingPairCandidate.close === afterCharacter) { foundAutoClosingPair = true; } } if (!foundAutoClosingPair) { return false; } } return true; }; DeleteOperations._runAutoClosingPairDelete = function (config, model, selections) { var commands = []; for (var i = 0, len = selections.length; i < len; i++) { var position = selections[i].getPosition(); var deleteSelection = new range_1.Range(position.lineNumber, position.column - 1, position.lineNumber, position.column + 1); commands[i] = new replaceCommand_1.ReplaceCommand(deleteSelection, ''); } return [true, commands]; }; DeleteOperations.deleteLeft = function (prevEditOperationType, config, model, selections) { if (this._isAutoClosingPairDelete(config, model, selections)) { return this._runAutoClosingPairDelete(config, model, selections); } var commands = []; var shouldPushStackElementBefore = (prevEditOperationType !== 2 /* DeletingLeft */); for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; var deleteSelection = selection; if (deleteSelection.isEmpty()) { var position = selection.getPosition(); if (config.useTabStops && position.column > 1) { var lineContent = model.getLineContent(position.lineNumber); var firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent); var lastIndentationColumn = (firstNonWhitespaceIndex === -1 ? /* entire string is whitespace */ lineContent.length + 1 : firstNonWhitespaceIndex + 1); if (position.column <= lastIndentationColumn) { var fromVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, position); var toVisibleColumn = cursorCommon_1.CursorColumns.prevIndentTabStop(fromVisibleColumn, config.indentSize); var toColumn = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, position.lineNumber, toVisibleColumn); deleteSelection = new range_1.Range(position.lineNumber, toColumn, position.lineNumber, position.column); } else { deleteSelection = new range_1.Range(position.lineNumber, position.column - 1, position.lineNumber, position.column); } } else { var leftOfPosition = cursorMoveOperations_1.MoveOperations.left(config, model, position.lineNumber, position.column); deleteSelection = new range_1.Range(leftOfPosition.lineNumber, leftOfPosition.column, position.lineNumber, position.column); } } if (deleteSelection.isEmpty()) { // Probably at beginning of file => ignore commands[i] = null; continue; } if (deleteSelection.startLineNumber !== deleteSelection.endLineNumber) { shouldPushStackElementBefore = true; } commands[i] = new replaceCommand_1.ReplaceCommand(deleteSelection, ''); } return [shouldPushStackElementBefore, commands]; }; DeleteOperations.cut = function (config, model, selections) { var commands = []; for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; if (selection.isEmpty()) { if (config.emptySelectionClipboard) { // This is a full line cut var position = selection.getPosition(); var startLineNumber = void 0, startColumn = void 0, endLineNumber = void 0, endColumn = void 0; if (position.lineNumber < model.getLineCount()) { // Cutting a line in the middle of the model startLineNumber = position.lineNumber; startColumn = 1; endLineNumber = position.lineNumber + 1; endColumn = 1; } else if (position.lineNumber > 1) { // Cutting the last line & there are more than 1 lines in the model startLineNumber = position.lineNumber - 1; startColumn = model.getLineMaxColumn(position.lineNumber - 1); endLineNumber = position.lineNumber; endColumn = model.getLineMaxColumn(position.lineNumber); } else { // Cutting the single line that the model contains startLineNumber = position.lineNumber; startColumn = 1; endLineNumber = position.lineNumber; endColumn = model.getLineMaxColumn(position.lineNumber); } var deleteSelection = new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn); if (!deleteSelection.isEmpty()) { commands[i] = new replaceCommand_1.ReplaceCommand(deleteSelection, ''); } else { commands[i] = null; } } else { // Cannot cut empty selection commands[i] = null; } } else { commands[i] = new replaceCommand_1.ReplaceCommand(selection, ''); } } return new cursorCommon_1.EditOperationResult(0 /* Other */, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: true }); }; return DeleteOperations; }()); exports.DeleteOperations = DeleteOperations; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[159/*vs/editor/common/controller/cursorTypeOperations*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,5/*vs/base/common/strings*/,80/*vs/editor/common/commands/replaceCommand*/,211/*vs/editor/common/commands/shiftCommand*/,340/*vs/editor/common/commands/surroundSelectionCommand*/,40/*vs/editor/common/controller/cursorCommon*/,89/*vs/editor/common/controller/wordCharacterClassifier*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,90/*vs/editor/common/modes/languageConfiguration*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, errors_1, strings, replaceCommand_1, shiftCommand_1, surroundSelectionCommand_1, cursorCommon_1, wordCharacterClassifier_1, range_1, selection_1, languageConfiguration_1, languageConfigurationRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var TypeOperations = /** @class */ (function () { function TypeOperations() { } TypeOperations.indent = function (config, model, selections) { if (model === null || selections === null) { return []; } var commands = []; for (var i = 0, len = selections.length; i < len; i++) { commands[i] = new shiftCommand_1.ShiftCommand(selections[i], { isUnshift: false, tabSize: config.tabSize, indentSize: config.indentSize, insertSpaces: config.insertSpaces, useTabStops: config.useTabStops, autoIndent: config.autoIndent }); } return commands; }; TypeOperations.outdent = function (config, model, selections) { var commands = []; for (var i = 0, len = selections.length; i < len; i++) { commands[i] = new shiftCommand_1.ShiftCommand(selections[i], { isUnshift: true, tabSize: config.tabSize, indentSize: config.indentSize, insertSpaces: config.insertSpaces, useTabStops: config.useTabStops, autoIndent: config.autoIndent }); } return commands; }; TypeOperations.shiftIndent = function (config, indentation, count) { count = count || 1; return shiftCommand_1.ShiftCommand.shiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces); }; TypeOperations.unshiftIndent = function (config, indentation, count) { count = count || 1; return shiftCommand_1.ShiftCommand.unshiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces); }; TypeOperations._distributedPaste = function (config, model, selections, text) { var commands = []; for (var i = 0, len = selections.length; i < len; i++) { commands[i] = new replaceCommand_1.ReplaceCommand(selections[i], text[i]); } return new cursorCommon_1.EditOperationResult(0 /* Other */, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: true }); }; TypeOperations._simplePaste = function (config, model, selections, text, pasteOnNewLine) { var commands = []; for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; var position = selection.getPosition(); if (pasteOnNewLine && !selection.isEmpty()) { pasteOnNewLine = false; } if (pasteOnNewLine && text.indexOf('\n') !== text.length - 1) { pasteOnNewLine = false; } if (pasteOnNewLine) { // Paste entire line at the beginning of line var typeSelection = new range_1.Range(position.lineNumber, 1, position.lineNumber, 1); commands[i] = new replaceCommand_1.ReplaceCommandThatPreservesSelection(typeSelection, text, selection, true); } else { commands[i] = new replaceCommand_1.ReplaceCommand(selection, text); } } return new cursorCommon_1.EditOperationResult(0 /* Other */, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: true }); }; TypeOperations._distributePasteToCursors = function (config, selections, text, pasteOnNewLine, multicursorText) { if (pasteOnNewLine) { return null; } if (selections.length === 1) { return null; } if (multicursorText && multicursorText.length === selections.length) { return multicursorText; } if (config.multiCursorPaste === 'spread') { // Try to spread the pasted text in case the line count matches the cursor count // Remove trailing \n if present if (text.charCodeAt(text.length - 1) === 10 /* LineFeed */) { text = text.substr(0, text.length - 1); } // Remove trailing \r if present if (text.charCodeAt(text.length - 1) === 13 /* CarriageReturn */) { text = text.substr(0, text.length - 1); } var lines = text.split(/\r\n|\r|\n/); if (lines.length === selections.length) { return lines; } } return null; }; TypeOperations.paste = function (config, model, selections, text, pasteOnNewLine, multicursorText) { var distributedPaste = this._distributePasteToCursors(config, selections, text, pasteOnNewLine, multicursorText); if (distributedPaste) { selections = selections.sort(range_1.Range.compareRangesUsingStarts); return this._distributedPaste(config, model, selections, distributedPaste); } else { return this._simplePaste(config, model, selections, text, pasteOnNewLine); } }; TypeOperations._goodIndentForLine = function (config, model, lineNumber) { var action = null; var indentation = ''; var expectedIndentAction = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getInheritIndentForLine(config.autoIndent, model, lineNumber, false); if (expectedIndentAction) { action = expectedIndentAction.action; indentation = expectedIndentAction.indentation; } else if (lineNumber > 1) { var lastLineNumber = void 0; for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) { var lineText = model.getLineContent(lastLineNumber); var nonWhitespaceIdx = strings.lastNonWhitespaceIndex(lineText); if (nonWhitespaceIdx >= 0) { break; } } if (lastLineNumber < 1) { // No previous line with content found return null; } var maxColumn = model.getLineMaxColumn(lastLineNumber); var expectedEnterAction = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(config.autoIndent, model, new range_1.Range(lastLineNumber, maxColumn, lastLineNumber, maxColumn)); if (expectedEnterAction) { indentation = expectedEnterAction.indentation + expectedEnterAction.appendText; } } if (action) { if (action === languageConfiguration_1.IndentAction.Indent) { indentation = TypeOperations.shiftIndent(config, indentation); } if (action === languageConfiguration_1.IndentAction.Outdent) { indentation = TypeOperations.unshiftIndent(config, indentation); } indentation = config.normalizeIndentation(indentation); } if (!indentation) { return null; } return indentation; }; TypeOperations._replaceJumpToNextIndent = function (config, model, selection, insertsAutoWhitespace) { var typeText = ''; var position = selection.getStartPosition(); if (config.insertSpaces) { var visibleColumnFromColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, position); var indentSize = config.indentSize; var spacesCnt = indentSize - (visibleColumnFromColumn % indentSize); for (var i = 0; i < spacesCnt; i++) { typeText += ' '; } } else { typeText = '\t'; } return new replaceCommand_1.ReplaceCommand(selection, typeText, insertsAutoWhitespace); }; TypeOperations.tab = function (config, model, selections) { var commands = []; for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; if (selection.isEmpty()) { var lineText = model.getLineContent(selection.startLineNumber); if (/^\s*$/.test(lineText) && model.isCheapToTokenize(selection.startLineNumber)) { var goodIndent = this._goodIndentForLine(config, model, selection.startLineNumber); goodIndent = goodIndent || '\t'; var possibleTypeText = config.normalizeIndentation(goodIndent); if (!strings.startsWith(lineText, possibleTypeText)) { commands[i] = new replaceCommand_1.ReplaceCommand(new range_1.Range(selection.startLineNumber, 1, selection.startLineNumber, lineText.length + 1), possibleTypeText, true); continue; } } commands[i] = this._replaceJumpToNextIndent(config, model, selection, true); } else { if (selection.startLineNumber === selection.endLineNumber) { var lineMaxColumn = model.getLineMaxColumn(selection.startLineNumber); if (selection.startColumn !== 1 || selection.endColumn !== lineMaxColumn) { // This is a single line selection that is not the entire line commands[i] = this._replaceJumpToNextIndent(config, model, selection, false); continue; } } commands[i] = new shiftCommand_1.ShiftCommand(selection, { isUnshift: false, tabSize: config.tabSize, indentSize: config.indentSize, insertSpaces: config.insertSpaces, useTabStops: config.useTabStops, autoIndent: config.autoIndent }); } } return commands; }; TypeOperations.replacePreviousChar = function (prevEditOperationType, config, model, selections, txt, replaceCharCnt) { var commands = []; for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; if (!selection.isEmpty()) { // looks like https://github.com/Microsoft/vscode/issues/2773 // where a cursor operation occurred before a canceled composition // => ignore composition commands[i] = null; continue; } var pos = selection.getPosition(); var startColumn = Math.max(1, pos.column - replaceCharCnt); var range = new range_1.Range(pos.lineNumber, startColumn, pos.lineNumber, pos.column); commands[i] = new replaceCommand_1.ReplaceCommand(range, txt); } return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands, { shouldPushStackElementBefore: (prevEditOperationType !== 1 /* Typing */), shouldPushStackElementAfter: false }); }; TypeOperations._typeCommand = function (range, text, keepPosition) { if (keepPosition) { return new replaceCommand_1.ReplaceCommandWithoutChangingPosition(range, text, true); } else { return new replaceCommand_1.ReplaceCommand(range, text, true); } }; TypeOperations._enter = function (config, model, keepPosition, range) { if (config.autoIndent === 0 /* None */) { return TypeOperations._typeCommand(range, '\n', keepPosition); } if (!model.isCheapToTokenize(range.getStartPosition().lineNumber) || config.autoIndent === 1 /* Keep */) { var lineText_1 = model.getLineContent(range.startLineNumber); var indentation_1 = strings.getLeadingWhitespace(lineText_1).substring(0, range.startColumn - 1); return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation_1), keepPosition); } var r = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(config.autoIndent, model, range); if (r) { if (r.indentAction === languageConfiguration_1.IndentAction.None) { // Nothing special return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(r.indentation + r.appendText), keepPosition); } else if (r.indentAction === languageConfiguration_1.IndentAction.Indent) { // Indent once return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(r.indentation + r.appendText), keepPosition); } else if (r.indentAction === languageConfiguration_1.IndentAction.IndentOutdent) { // Ultra special var normalIndent = config.normalizeIndentation(r.indentation); var increasedIndent = config.normalizeIndentation(r.indentation + r.appendText); var typeText = '\n' + increasedIndent + '\n' + normalIndent; if (keepPosition) { return new replaceCommand_1.ReplaceCommandWithoutChangingPosition(range, typeText, true); } else { return new replaceCommand_1.ReplaceCommandWithOffsetCursorState(range, typeText, -1, increasedIndent.length - normalIndent.length, true); } } else if (r.indentAction === languageConfiguration_1.IndentAction.Outdent) { var actualIndentation = TypeOperations.unshiftIndent(config, r.indentation); return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(actualIndentation + r.appendText), keepPosition); } } var lineText = model.getLineContent(range.startLineNumber); var indentation = strings.getLeadingWhitespace(lineText).substring(0, range.startColumn - 1); if (config.autoIndent >= 4 /* Full */) { var ir = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentForEnter(config.autoIndent, model, range, { unshiftIndent: function (indent) { return TypeOperations.unshiftIndent(config, indent); }, shiftIndent: function (indent) { return TypeOperations.shiftIndent(config, indent); }, normalizeIndentation: function (indent) { return config.normalizeIndentation(indent); } }); if (ir) { var oldEndViewColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, range.getEndPosition()); var oldEndColumn = range.endColumn; var beforeText = '\n'; if (indentation !== config.normalizeIndentation(ir.beforeEnter)) { beforeText = config.normalizeIndentation(ir.beforeEnter) + lineText.substring(indentation.length, range.startColumn - 1) + '\n'; range = new range_1.Range(range.startLineNumber, 1, range.endLineNumber, range.endColumn); } var newLineContent = model.getLineContent(range.endLineNumber); var firstNonWhitespace = strings.firstNonWhitespaceIndex(newLineContent); if (firstNonWhitespace >= 0) { range = range.setEndPosition(range.endLineNumber, Math.max(range.endColumn, firstNonWhitespace + 1)); } else { range = range.setEndPosition(range.endLineNumber, model.getLineMaxColumn(range.endLineNumber)); } if (keepPosition) { return new replaceCommand_1.ReplaceCommandWithoutChangingPosition(range, beforeText + config.normalizeIndentation(ir.afterEnter), true); } else { var offset = 0; if (oldEndColumn <= firstNonWhitespace + 1) { if (!config.insertSpaces) { oldEndViewColumn = Math.ceil(oldEndViewColumn / config.indentSize); } offset = Math.min(oldEndViewColumn + 1 - config.normalizeIndentation(ir.afterEnter).length - 1, 0); } return new replaceCommand_1.ReplaceCommandWithOffsetCursorState(range, beforeText + config.normalizeIndentation(ir.afterEnter), 0, offset, true); } } } return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation), keepPosition); }; TypeOperations._isAutoIndentType = function (config, model, selections) { if (config.autoIndent < 4 /* Full */) { return false; } for (var i = 0, len = selections.length; i < len; i++) { if (!model.isCheapToTokenize(selections[i].getEndPosition().lineNumber)) { return false; } } return true; }; TypeOperations._runAutoIndentType = function (config, model, range, ch) { var currentIndentation = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentationAtPosition(model, range.startLineNumber, range.startColumn); var actualIndentation = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentActionForType(config.autoIndent, model, range, ch, { shiftIndent: function (indentation) { return TypeOperations.shiftIndent(config, indentation); }, unshiftIndent: function (indentation) { return TypeOperations.unshiftIndent(config, indentation); }, }); if (actualIndentation === null) { return null; } if (actualIndentation !== config.normalizeIndentation(currentIndentation)) { var firstNonWhitespace = model.getLineFirstNonWhitespaceColumn(range.startLineNumber); if (firstNonWhitespace === 0) { return TypeOperations._typeCommand(new range_1.Range(range.startLineNumber, 0, range.endLineNumber, range.endColumn), config.normalizeIndentation(actualIndentation) + ch, false); } else { return TypeOperations._typeCommand(new range_1.Range(range.startLineNumber, 0, range.endLineNumber, range.endColumn), config.normalizeIndentation(actualIndentation) + model.getLineContent(range.startLineNumber).substring(firstNonWhitespace - 1, range.startColumn - 1) + ch, false); } } return null; }; TypeOperations._isAutoClosingOvertype = function (config, model, selections, autoClosedCharacters, ch) { if (config.autoClosingOvertype === 'never') { return false; } if (!config.autoClosingPairsClose2.has(ch)) { return false; } for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; if (!selection.isEmpty()) { return false; } var position = selection.getPosition(); var lineText = model.getLineContent(position.lineNumber); var afterCharacter = lineText.charAt(position.column - 1); if (afterCharacter !== ch) { return false; } // Do not over-type quotes after a backslash var chIsQuote = cursorCommon_1.isQuote(ch); var beforeCharacter = position.column > 2 ? lineText.charCodeAt(position.column - 2) : 0 /* Null */; if (beforeCharacter === 92 /* Backslash */ && chIsQuote) { return false; } // Must over-type a closing character typed by the editor if (config.autoClosingOvertype === 'auto') { var found = false; for (var j = 0, lenJ = autoClosedCharacters.length; j < lenJ; j++) { var autoClosedCharacter = autoClosedCharacters[j]; if (position.lineNumber === autoClosedCharacter.startLineNumber && position.column === autoClosedCharacter.startColumn) { found = true; break; } } if (!found) { return false; } } } return true; }; TypeOperations._runAutoClosingOvertype = function (prevEditOperationType, config, model, selections, ch) { var commands = []; for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; var position = selection.getPosition(); var typeSelection = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column + 1); commands[i] = new replaceCommand_1.ReplaceCommand(typeSelection, ch); } return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands, { shouldPushStackElementBefore: (prevEditOperationType !== 1 /* Typing */), shouldPushStackElementAfter: false }); }; TypeOperations._autoClosingPairIsSymmetric = function (autoClosingPair) { var open = autoClosingPair.open, close = autoClosingPair.close; return (open.indexOf(close) >= 0 || close.indexOf(open) >= 0); }; TypeOperations._isBeforeClosingBrace = function (config, autoClosingPair, characterAfter) { var otherAutoClosingPairs = config.autoClosingPairsClose2.get(characterAfter); if (!otherAutoClosingPairs) { return false; } var thisBraceIsSymmetric = TypeOperations._autoClosingPairIsSymmetric(autoClosingPair); for (var _i = 0, otherAutoClosingPairs_1 = otherAutoClosingPairs; _i < otherAutoClosingPairs_1.length; _i++) { var otherAutoClosingPair = otherAutoClosingPairs_1[_i]; var otherBraceIsSymmetric = TypeOperations._autoClosingPairIsSymmetric(otherAutoClosingPair); if (!thisBraceIsSymmetric && otherBraceIsSymmetric) { continue; } return true; } return false; }; TypeOperations._findAutoClosingPairOpen = function (config, model, positions, ch) { var autoClosingPairCandidates = config.autoClosingPairsOpen2.get(ch); if (!autoClosingPairCandidates) { return null; } // Determine which auto-closing pair it is var autoClosingPair = null; for (var _i = 0, autoClosingPairCandidates_1 = autoClosingPairCandidates; _i < autoClosingPairCandidates_1.length; _i++) { var autoClosingPairCandidate = autoClosingPairCandidates_1[_i]; if (autoClosingPair === null || autoClosingPairCandidate.open.length > autoClosingPair.open.length) { var candidateIsMatch = true; for (var _a = 0, positions_1 = positions; _a < positions_1.length; _a++) { var position = positions_1[_a]; var relevantText = model.getValueInRange(new range_1.Range(position.lineNumber, position.column - autoClosingPairCandidate.open.length + 1, position.lineNumber, position.column)); if (relevantText + ch !== autoClosingPairCandidate.open) { candidateIsMatch = false; break; } } if (candidateIsMatch) { autoClosingPair = autoClosingPairCandidate; } } } return autoClosingPair; }; TypeOperations._isAutoClosingOpenCharType = function (config, model, selections, ch, insertOpenCharacter) { var chIsQuote = cursorCommon_1.isQuote(ch); var autoCloseConfig = chIsQuote ? config.autoClosingQuotes : config.autoClosingBrackets; if (autoCloseConfig === 'never') { return null; } var autoClosingPair = this._findAutoClosingPairOpen(config, model, selections.map(function (s) { return s.getPosition(); }), ch); if (!autoClosingPair) { return null; } var shouldAutoCloseBefore = chIsQuote ? config.shouldAutoCloseBefore.quote : config.shouldAutoCloseBefore.bracket; for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; if (!selection.isEmpty()) { return null; } var position = selection.getPosition(); var lineText = model.getLineContent(position.lineNumber); // Only consider auto closing the pair if a space follows or if another autoclosed pair follows if (lineText.length > position.column - 1) { var characterAfter = lineText.charAt(position.column - 1); var isBeforeCloseBrace = TypeOperations._isBeforeClosingBrace(config, autoClosingPair, characterAfter); if (!isBeforeCloseBrace && !shouldAutoCloseBefore(characterAfter)) { return null; } } if (!model.isCheapToTokenize(position.lineNumber)) { // Do not force tokenization return null; } // Do not auto-close ' or " after a word character if (autoClosingPair.open.length === 1 && chIsQuote && autoCloseConfig !== 'always') { var wordSeparators = wordCharacterClassifier_1.getMapForWordSeparators(config.wordSeparators); if (insertOpenCharacter && position.column > 1 && wordSeparators.get(lineText.charCodeAt(position.column - 2)) === 0 /* Regular */) { return null; } if (!insertOpenCharacter && position.column > 2 && wordSeparators.get(lineText.charCodeAt(position.column - 3)) === 0 /* Regular */) { return null; } } model.forceTokenization(position.lineNumber); var lineTokens = model.getLineTokens(position.lineNumber); var shouldAutoClosePair = false; try { shouldAutoClosePair = languageConfigurationRegistry_1.LanguageConfigurationRegistry.shouldAutoClosePair(autoClosingPair, lineTokens, insertOpenCharacter ? position.column : position.column - 1); } catch (e) { errors_1.onUnexpectedError(e); } if (!shouldAutoClosePair) { return null; } } return autoClosingPair; }; TypeOperations._runAutoClosingOpenCharType = function (prevEditOperationType, config, model, selections, ch, insertOpenCharacter, autoClosingPair) { var commands = []; for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; commands[i] = new TypeWithAutoClosingCommand(selection, ch, insertOpenCharacter, autoClosingPair.close); } return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: false }); }; TypeOperations._shouldSurroundChar = function (config, ch) { if (cursorCommon_1.isQuote(ch)) { return (config.autoSurround === 'quotes' || config.autoSurround === 'languageDefined'); } else { // Character is a bracket return (config.autoSurround === 'brackets' || config.autoSurround === 'languageDefined'); } }; TypeOperations._isSurroundSelectionType = function (config, model, selections, ch) { if (!TypeOperations._shouldSurroundChar(config, ch) || !config.surroundingPairs.hasOwnProperty(ch)) { return false; } var isTypingAQuoteCharacter = cursorCommon_1.isQuote(ch); for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; if (selection.isEmpty()) { return false; } var selectionContainsOnlyWhitespace = true; for (var lineNumber = selection.startLineNumber; lineNumber <= selection.endLineNumber; lineNumber++) { var lineText = model.getLineContent(lineNumber); var startIndex = (lineNumber === selection.startLineNumber ? selection.startColumn - 1 : 0); var endIndex = (lineNumber === selection.endLineNumber ? selection.endColumn - 1 : lineText.length); var selectedText = lineText.substring(startIndex, endIndex); if (/[^ \t]/.test(selectedText)) { // this selected text contains something other than whitespace selectionContainsOnlyWhitespace = false; break; } } if (selectionContainsOnlyWhitespace) { return false; } if (isTypingAQuoteCharacter && selection.startLineNumber === selection.endLineNumber && selection.startColumn + 1 === selection.endColumn) { var selectionText = model.getValueInRange(selection); if (cursorCommon_1.isQuote(selectionText)) { // Typing a quote character on top of another quote character // => disable surround selection type return false; } } } return true; }; TypeOperations._runSurroundSelectionType = function (prevEditOperationType, config, model, selections, ch) { var commands = []; for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; var closeCharacter = config.surroundingPairs[ch]; commands[i] = new surroundSelectionCommand_1.SurroundSelectionCommand(selection, ch, closeCharacter); } return new cursorCommon_1.EditOperationResult(0 /* Other */, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: true }); }; TypeOperations._isTypeInterceptorElectricChar = function (config, model, selections) { if (selections.length === 1 && model.isCheapToTokenize(selections[0].getEndPosition().lineNumber)) { return true; } return false; }; TypeOperations._typeInterceptorElectricChar = function (prevEditOperationType, config, model, selection, ch) { if (!config.electricChars.hasOwnProperty(ch) || !selection.isEmpty()) { return null; } var position = selection.getPosition(); model.forceTokenization(position.lineNumber); var lineTokens = model.getLineTokens(position.lineNumber); var electricAction; try { electricAction = languageConfigurationRegistry_1.LanguageConfigurationRegistry.onElectricCharacter(ch, lineTokens, position.column); } catch (e) { errors_1.onUnexpectedError(e); return null; } if (!electricAction) { return null; } if (electricAction.matchOpenBracket) { var endColumn = (lineTokens.getLineContent() + ch).lastIndexOf(electricAction.matchOpenBracket) + 1; var match = model.findMatchingBracketUp(electricAction.matchOpenBracket, { lineNumber: position.lineNumber, column: endColumn }); if (match) { if (match.startLineNumber === position.lineNumber) { // matched something on the same line => no change in indentation return null; } var matchLine = model.getLineContent(match.startLineNumber); var matchLineIndentation = strings.getLeadingWhitespace(matchLine); var newIndentation = config.normalizeIndentation(matchLineIndentation); var lineText = model.getLineContent(position.lineNumber); var lineFirstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(position.lineNumber) || position.column; var prefix = lineText.substring(lineFirstNonBlankColumn - 1, position.column - 1); var typeText = newIndentation + prefix + ch; var typeSelection = new range_1.Range(position.lineNumber, 1, position.lineNumber, position.column); var command = new replaceCommand_1.ReplaceCommand(typeSelection, typeText); return new cursorCommon_1.EditOperationResult(1 /* Typing */, [command], { shouldPushStackElementBefore: false, shouldPushStackElementAfter: true }); } } return null; }; /** * This is very similar with typing, but the character is already in the text buffer! */ TypeOperations.compositionEndWithInterceptors = function (prevEditOperationType, config, model, selectionsWhenCompositionStarted, selections, autoClosedCharacters) { if (!selectionsWhenCompositionStarted || selection_1.Selection.selectionsArrEqual(selectionsWhenCompositionStarted, selections)) { // no content was typed return null; } var ch = null; // extract last typed character for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) { var selection = selections_1[_i]; if (!selection.isEmpty()) { return null; } var position = selection.getPosition(); var currentChar = model.getValueInRange(new range_1.Range(position.lineNumber, position.column - 1, position.lineNumber, position.column)); if (ch === null) { ch = currentChar; } else if (ch !== currentChar) { return null; } } if (!ch) { return null; } if (this._isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch)) { // Unfortunately, the close character is at this point "doubled", so we need to delete it... var commands = selections.map(function (s) { return new replaceCommand_1.ReplaceCommand(new range_1.Range(s.positionLineNumber, s.positionColumn, s.positionLineNumber, s.positionColumn + 1), '', false); }); return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: false }); } var autoClosingPairOpenCharType = this._isAutoClosingOpenCharType(config, model, selections, ch, false); if (autoClosingPairOpenCharType) { return this._runAutoClosingOpenCharType(prevEditOperationType, config, model, selections, ch, false, autoClosingPairOpenCharType); } return null; }; TypeOperations.typeWithInterceptors = function (prevEditOperationType, config, model, selections, autoClosedCharacters, ch) { if (ch === '\n') { var commands_1 = []; for (var i = 0, len = selections.length; i < len; i++) { commands_1[i] = TypeOperations._enter(config, model, false, selections[i]); } return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands_1, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: false, }); } if (this._isAutoIndentType(config, model, selections)) { var commands_2 = []; var autoIndentFails = false; for (var i = 0, len = selections.length; i < len; i++) { commands_2[i] = this._runAutoIndentType(config, model, selections[i], ch); if (!commands_2[i]) { autoIndentFails = true; break; } } if (!autoIndentFails) { return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands_2, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: false, }); } } if (this._isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch)) { return this._runAutoClosingOvertype(prevEditOperationType, config, model, selections, ch); } var autoClosingPairOpenCharType = this._isAutoClosingOpenCharType(config, model, selections, ch, true); if (autoClosingPairOpenCharType) { return this._runAutoClosingOpenCharType(prevEditOperationType, config, model, selections, ch, true, autoClosingPairOpenCharType); } if (this._isSurroundSelectionType(config, model, selections, ch)) { return this._runSurroundSelectionType(prevEditOperationType, config, model, selections, ch); } // Electric characters make sense only when dealing with a single cursor, // as multiple cursors typing brackets for example would interfer with bracket matching if (this._isTypeInterceptorElectricChar(config, model, selections)) { var r = this._typeInterceptorElectricChar(prevEditOperationType, config, model, selections[0], ch); if (r) { return r; } } // A simple character type var commands = []; for (var i = 0, len = selections.length; i < len; i++) { commands[i] = new replaceCommand_1.ReplaceCommand(selections[i], ch); } var shouldPushStackElementBefore = (prevEditOperationType !== 1 /* Typing */); if (ch === ' ') { shouldPushStackElementBefore = true; } return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands, { shouldPushStackElementBefore: shouldPushStackElementBefore, shouldPushStackElementAfter: false }); }; TypeOperations.typeWithoutInterceptors = function (prevEditOperationType, config, model, selections, str) { var commands = []; for (var i = 0, len = selections.length; i < len; i++) { commands[i] = new replaceCommand_1.ReplaceCommand(selections[i], str); } return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands, { shouldPushStackElementBefore: (prevEditOperationType !== 1 /* Typing */), shouldPushStackElementAfter: false }); }; TypeOperations.lineInsertBefore = function (config, model, selections) { if (model === null || selections === null) { return []; } var commands = []; for (var i = 0, len = selections.length; i < len; i++) { var lineNumber = selections[i].positionLineNumber; if (lineNumber === 1) { commands[i] = new replaceCommand_1.ReplaceCommandWithoutChangingPosition(new range_1.Range(1, 1, 1, 1), '\n'); } else { lineNumber--; var column = model.getLineMaxColumn(lineNumber); commands[i] = this._enter(config, model, false, new range_1.Range(lineNumber, column, lineNumber, column)); } } return commands; }; TypeOperations.lineInsertAfter = function (config, model, selections) { if (model === null || selections === null) { return []; } var commands = []; for (var i = 0, len = selections.length; i < len; i++) { var lineNumber = selections[i].positionLineNumber; var column = model.getLineMaxColumn(lineNumber); commands[i] = this._enter(config, model, false, new range_1.Range(lineNumber, column, lineNumber, column)); } return commands; }; TypeOperations.lineBreakInsert = function (config, model, selections) { var commands = []; for (var i = 0, len = selections.length; i < len; i++) { commands[i] = this._enter(config, model, true, selections[i]); } return commands; }; return TypeOperations; }()); exports.TypeOperations = TypeOperations; var TypeWithAutoClosingCommand = /** @class */ (function (_super) { __extends(TypeWithAutoClosingCommand, _super); function TypeWithAutoClosingCommand(selection, openCharacter, insertOpenCharacter, closeCharacter) { var _this = _super.call(this, selection, (insertOpenCharacter ? openCharacter : '') + closeCharacter, 0, -closeCharacter.length) || this; _this._openCharacter = openCharacter; _this._closeCharacter = closeCharacter; _this.closeCharacterRange = null; _this.enclosingRange = null; return _this; } TypeWithAutoClosingCommand.prototype.computeCursorState = function (model, helper) { var inverseEditOperations = helper.getInverseEditOperations(); var range = inverseEditOperations[0].range; this.closeCharacterRange = new range_1.Range(range.startLineNumber, range.endColumn - this._closeCharacter.length, range.endLineNumber, range.endColumn); this.enclosingRange = new range_1.Range(range.startLineNumber, range.endColumn - this._openCharacter.length - this._closeCharacter.length, range.endLineNumber, range.endColumn); return _super.prototype.computeCursorState.call(this, model, helper); }; return TypeWithAutoClosingCommand; }(replaceCommand_1.ReplaceCommandWithOffsetCursorState)); exports.TypeWithAutoClosingCommand = TypeWithAutoClosingCommand; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[160/*vs/editor/common/controller/cursorWordOperations*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,40/*vs/editor/common/controller/cursorCommon*/,89/*vs/editor/common/controller/wordCharacterClassifier*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings, cursorCommon_1, wordCharacterClassifier_1, position_1, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var WordOperations = /** @class */ (function () { function WordOperations() { } WordOperations._createWord = function (lineContent, wordType, nextCharClass, start, end) { // console.log('WORD ==> ' + start + ' => ' + end + ':::: <<<' + lineContent.substring(start, end) + '>>>'); return { start: start, end: end, wordType: wordType, nextCharClass: nextCharClass }; }; WordOperations._findPreviousWordOnLine = function (wordSeparators, model, position) { var lineContent = model.getLineContent(position.lineNumber); return this._doFindPreviousWordOnLine(lineContent, wordSeparators, position); }; WordOperations._doFindPreviousWordOnLine = function (lineContent, wordSeparators, position) { var wordType = 0 /* None */; for (var chIndex = position.column - 2; chIndex >= 0; chIndex--) { var chCode = lineContent.charCodeAt(chIndex); var chClass = wordSeparators.get(chCode); if (chClass === 0 /* Regular */) { if (wordType === 2 /* Separator */) { return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1)); } wordType = 1 /* Regular */; } else if (chClass === 2 /* WordSeparator */) { if (wordType === 1 /* Regular */) { return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1)); } wordType = 2 /* Separator */; } else if (chClass === 1 /* Whitespace */) { if (wordType !== 0 /* None */) { return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1)); } } } if (wordType !== 0 /* None */) { return this._createWord(lineContent, wordType, 1 /* Whitespace */, 0, this._findEndOfWord(lineContent, wordSeparators, wordType, 0)); } return null; }; WordOperations._findEndOfWord = function (lineContent, wordSeparators, wordType, startIndex) { var len = lineContent.length; for (var chIndex = startIndex; chIndex < len; chIndex++) { var chCode = lineContent.charCodeAt(chIndex); var chClass = wordSeparators.get(chCode); if (chClass === 1 /* Whitespace */) { return chIndex; } if (wordType === 1 /* Regular */ && chClass === 2 /* WordSeparator */) { return chIndex; } if (wordType === 2 /* Separator */ && chClass === 0 /* Regular */) { return chIndex; } } return len; }; WordOperations._findNextWordOnLine = function (wordSeparators, model, position) { var lineContent = model.getLineContent(position.lineNumber); return this._doFindNextWordOnLine(lineContent, wordSeparators, position); }; WordOperations._doFindNextWordOnLine = function (lineContent, wordSeparators, position) { var wordType = 0 /* None */; var len = lineContent.length; for (var chIndex = position.column - 1; chIndex < len; chIndex++) { var chCode = lineContent.charCodeAt(chIndex); var chClass = wordSeparators.get(chCode); if (chClass === 0 /* Regular */) { if (wordType === 2 /* Separator */) { return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex); } wordType = 1 /* Regular */; } else if (chClass === 2 /* WordSeparator */) { if (wordType === 1 /* Regular */) { return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex); } wordType = 2 /* Separator */; } else if (chClass === 1 /* Whitespace */) { if (wordType !== 0 /* None */) { return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex); } } } if (wordType !== 0 /* None */) { return this._createWord(lineContent, wordType, 1 /* Whitespace */, this._findStartOfWord(lineContent, wordSeparators, wordType, len - 1), len); } return null; }; WordOperations._findStartOfWord = function (lineContent, wordSeparators, wordType, startIndex) { for (var chIndex = startIndex; chIndex >= 0; chIndex--) { var chCode = lineContent.charCodeAt(chIndex); var chClass = wordSeparators.get(chCode); if (chClass === 1 /* Whitespace */) { return chIndex + 1; } if (wordType === 1 /* Regular */ && chClass === 2 /* WordSeparator */) { return chIndex + 1; } if (wordType === 2 /* Separator */ && chClass === 0 /* Regular */) { return chIndex + 1; } } return 0; }; WordOperations.moveWordLeft = function (wordSeparators, model, position, wordNavigationType) { var lineNumber = position.lineNumber; var column = position.column; var movedToPreviousLine = false; if (column === 1) { if (lineNumber > 1) { movedToPreviousLine = true; lineNumber = lineNumber - 1; column = model.getLineMaxColumn(lineNumber); } } var prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, column)); if (wordNavigationType === 0 /* WordStart */) { if (prevWordOnLine && !movedToPreviousLine) { // Special case for Visual Studio compatibility: // when starting in the trim whitespace at the end of a line, // go to the end of the last word var lastWhitespaceColumn = model.getLineLastNonWhitespaceColumn(lineNumber); if (lastWhitespaceColumn < column) { return new position_1.Position(lineNumber, prevWordOnLine.end + 1); } } return new position_1.Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1); } if (wordNavigationType === 1 /* WordStartFast */) { if (prevWordOnLine && prevWordOnLine.wordType === 2 /* Separator */ && prevWordOnLine.end - prevWordOnLine.start === 1 && prevWordOnLine.nextCharClass === 0 /* Regular */) { // Skip over a word made up of one single separator and followed by a regular character prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, prevWordOnLine.start + 1)); } return new position_1.Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1); } if (wordNavigationType === 3 /* WordAccessibility */) { while (prevWordOnLine && prevWordOnLine.wordType === 2 /* Separator */) { // Skip over words made up of only separators prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, prevWordOnLine.start + 1)); } return new position_1.Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1); } // We are stopping at the ending of words if (prevWordOnLine && column <= prevWordOnLine.end + 1) { prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, prevWordOnLine.start + 1)); } return new position_1.Position(lineNumber, prevWordOnLine ? prevWordOnLine.end + 1 : 1); }; WordOperations._moveWordPartLeft = function (model, position) { var lineNumber = position.lineNumber; var maxColumn = model.getLineMaxColumn(lineNumber); if (position.column === 1) { return (lineNumber > 1 ? new position_1.Position(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)) : position); } var lineContent = model.getLineContent(lineNumber); for (var column = position.column - 1; column > 1; column--) { var left = lineContent.charCodeAt(column - 2); var right = lineContent.charCodeAt(column - 1); if (left !== 95 /* Underline */ && right === 95 /* Underline */) { // snake_case_variables return new position_1.Position(lineNumber, column); } if (strings.isLowerAsciiLetter(left) && strings.isUpperAsciiLetter(right)) { // camelCaseVariables return new position_1.Position(lineNumber, column); } if (strings.isUpperAsciiLetter(left) && strings.isUpperAsciiLetter(right)) { // thisIsACamelCaseWithOneLetterWords if (column + 1 < maxColumn) { var rightRight = lineContent.charCodeAt(column); if (strings.isLowerAsciiLetter(rightRight)) { return new position_1.Position(lineNumber, column); } } } } return new position_1.Position(lineNumber, 1); }; WordOperations.moveWordRight = function (wordSeparators, model, position, wordNavigationType) { var lineNumber = position.lineNumber; var column = position.column; var movedDown = false; if (column === model.getLineMaxColumn(lineNumber)) { if (lineNumber < model.getLineCount()) { movedDown = true; lineNumber = lineNumber + 1; column = 1; } } var nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, column)); if (wordNavigationType === 2 /* WordEnd */) { if (nextWordOnLine && nextWordOnLine.wordType === 2 /* Separator */) { if (nextWordOnLine.end - nextWordOnLine.start === 1 && nextWordOnLine.nextCharClass === 0 /* Regular */) { // Skip over a word made up of one single separator and followed by a regular character nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, nextWordOnLine.end + 1)); } } if (nextWordOnLine) { column = nextWordOnLine.end + 1; } else { column = model.getLineMaxColumn(lineNumber); } } else if (wordNavigationType === 3 /* WordAccessibility */) { if (movedDown) { // If we move to the next line, pretend that the cursor is right before the first character. // This is needed when the first word starts right at the first character - and in order not to miss it, // we need to start before. column = 0; } while (nextWordOnLine && (nextWordOnLine.wordType === 2 /* Separator */ || nextWordOnLine.start + 1 <= column)) { // Skip over a word made up of one single separator // Also skip over word if it begins before current cursor position to ascertain we're moving forward at least 1 character. nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, nextWordOnLine.end + 1)); } if (nextWordOnLine) { column = nextWordOnLine.start + 1; } else { column = model.getLineMaxColumn(lineNumber); } } else { if (nextWordOnLine && !movedDown && column >= nextWordOnLine.start + 1) { nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, nextWordOnLine.end + 1)); } if (nextWordOnLine) { column = nextWordOnLine.start + 1; } else { column = model.getLineMaxColumn(lineNumber); } } return new position_1.Position(lineNumber, column); }; WordOperations._moveWordPartRight = function (model, position) { var lineNumber = position.lineNumber; var maxColumn = model.getLineMaxColumn(lineNumber); if (position.column === maxColumn) { return (lineNumber < model.getLineCount() ? new position_1.Position(lineNumber + 1, 1) : position); } var lineContent = model.getLineContent(lineNumber); for (var column = position.column + 1; column < maxColumn; column++) { var left = lineContent.charCodeAt(column - 2); var right = lineContent.charCodeAt(column - 1); if (left === 95 /* Underline */ && right !== 95 /* Underline */) { // snake_case_variables return new position_1.Position(lineNumber, column); } if (strings.isLowerAsciiLetter(left) && strings.isUpperAsciiLetter(right)) { // camelCaseVariables return new position_1.Position(lineNumber, column); } if (strings.isUpperAsciiLetter(left) && strings.isUpperAsciiLetter(right)) { // thisIsACamelCaseWithOneLetterWords if (column + 1 < maxColumn) { var rightRight = lineContent.charCodeAt(column); if (strings.isLowerAsciiLetter(rightRight)) { return new position_1.Position(lineNumber, column); } } } } return new position_1.Position(lineNumber, maxColumn); }; WordOperations._deleteWordLeftWhitespace = function (model, position) { var lineContent = model.getLineContent(position.lineNumber); var startIndex = position.column - 2; var lastNonWhitespace = strings.lastNonWhitespaceIndex(lineContent, startIndex); if (lastNonWhitespace + 1 < startIndex) { return new range_1.Range(position.lineNumber, lastNonWhitespace + 2, position.lineNumber, position.column); } return null; }; WordOperations.deleteWordLeft = function (wordSeparators, model, selection, whitespaceHeuristics, wordNavigationType) { if (!selection.isEmpty()) { return selection; } var position = new position_1.Position(selection.positionLineNumber, selection.positionColumn); var lineNumber = position.lineNumber; var column = position.column; if (lineNumber === 1 && column === 1) { // Ignore deleting at beginning of file return null; } if (whitespaceHeuristics) { var r = this._deleteWordLeftWhitespace(model, position); if (r) { return r; } } var prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, position); if (wordNavigationType === 0 /* WordStart */) { if (prevWordOnLine) { column = prevWordOnLine.start + 1; } else { if (column > 1) { column = 1; } else { lineNumber--; column = model.getLineMaxColumn(lineNumber); } } } else { if (prevWordOnLine && column <= prevWordOnLine.end + 1) { prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, prevWordOnLine.start + 1)); } if (prevWordOnLine) { column = prevWordOnLine.end + 1; } else { if (column > 1) { column = 1; } else { lineNumber--; column = model.getLineMaxColumn(lineNumber); } } } return new range_1.Range(lineNumber, column, position.lineNumber, position.column); }; WordOperations._deleteWordPartLeft = function (model, selection) { if (!selection.isEmpty()) { return selection; } var pos = selection.getPosition(); var toPosition = WordOperations._moveWordPartLeft(model, pos); return new range_1.Range(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column); }; WordOperations._findFirstNonWhitespaceChar = function (str, startIndex) { var len = str.length; for (var chIndex = startIndex; chIndex < len; chIndex++) { var ch = str.charAt(chIndex); if (ch !== ' ' && ch !== '\t') { return chIndex; } } return len; }; WordOperations._deleteWordRightWhitespace = function (model, position) { var lineContent = model.getLineContent(position.lineNumber); var startIndex = position.column - 1; var firstNonWhitespace = this._findFirstNonWhitespaceChar(lineContent, startIndex); if (startIndex + 1 < firstNonWhitespace) { // bingo return new range_1.Range(position.lineNumber, position.column, position.lineNumber, firstNonWhitespace + 1); } return null; }; WordOperations.deleteWordRight = function (wordSeparators, model, selection, whitespaceHeuristics, wordNavigationType) { if (!selection.isEmpty()) { return selection; } var position = new position_1.Position(selection.positionLineNumber, selection.positionColumn); var lineNumber = position.lineNumber; var column = position.column; var lineCount = model.getLineCount(); var maxColumn = model.getLineMaxColumn(lineNumber); if (lineNumber === lineCount && column === maxColumn) { // Ignore deleting at end of file return null; } if (whitespaceHeuristics) { var r = this._deleteWordRightWhitespace(model, position); if (r) { return r; } } var nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, position); if (wordNavigationType === 2 /* WordEnd */) { if (nextWordOnLine) { column = nextWordOnLine.end + 1; } else { if (column < maxColumn || lineNumber === lineCount) { column = maxColumn; } else { lineNumber++; nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, 1)); if (nextWordOnLine) { column = nextWordOnLine.start + 1; } else { column = model.getLineMaxColumn(lineNumber); } } } } else { if (nextWordOnLine && column >= nextWordOnLine.start + 1) { nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, nextWordOnLine.end + 1)); } if (nextWordOnLine) { column = nextWordOnLine.start + 1; } else { if (column < maxColumn || lineNumber === lineCount) { column = maxColumn; } else { lineNumber++; nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, 1)); if (nextWordOnLine) { column = nextWordOnLine.start + 1; } else { column = model.getLineMaxColumn(lineNumber); } } } } return new range_1.Range(lineNumber, column, position.lineNumber, position.column); }; WordOperations._deleteWordPartRight = function (model, selection) { if (!selection.isEmpty()) { return selection; } var pos = selection.getPosition(); var toPosition = WordOperations._moveWordPartRight(model, pos); return new range_1.Range(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column); }; WordOperations.word = function (config, model, cursor, inSelectionMode, position) { var wordSeparators = wordCharacterClassifier_1.getMapForWordSeparators(config.wordSeparators); var prevWord = WordOperations._findPreviousWordOnLine(wordSeparators, model, position); var nextWord = WordOperations._findNextWordOnLine(wordSeparators, model, position); if (!inSelectionMode) { // Entering word selection for the first time var startColumn_1; var endColumn_1; if (prevWord && prevWord.wordType === 1 /* Regular */ && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) { // isTouchingPrevWord startColumn_1 = prevWord.start + 1; endColumn_1 = prevWord.end + 1; } else if (nextWord && nextWord.wordType === 1 /* Regular */ && nextWord.start <= position.column - 1 && position.column - 1 <= nextWord.end) { // isTouchingNextWord startColumn_1 = nextWord.start + 1; endColumn_1 = nextWord.end + 1; } else { if (prevWord) { startColumn_1 = prevWord.end + 1; } else { startColumn_1 = 1; } if (nextWord) { endColumn_1 = nextWord.start + 1; } else { endColumn_1 = model.getLineMaxColumn(position.lineNumber); } } return new cursorCommon_1.SingleCursorState(new range_1.Range(position.lineNumber, startColumn_1, position.lineNumber, endColumn_1), 0, new position_1.Position(position.lineNumber, endColumn_1), 0); } var startColumn; var endColumn; if (prevWord && prevWord.wordType === 1 /* Regular */ && prevWord.start < position.column - 1 && position.column - 1 < prevWord.end) { // isInsidePrevWord startColumn = prevWord.start + 1; endColumn = prevWord.end + 1; } else if (nextWord && nextWord.wordType === 1 /* Regular */ && nextWord.start < position.column - 1 && position.column - 1 < nextWord.end) { // isInsideNextWord startColumn = nextWord.start + 1; endColumn = nextWord.end + 1; } else { startColumn = position.column; endColumn = position.column; } var lineNumber = position.lineNumber; var column; if (cursor.selectionStart.containsPosition(position)) { column = cursor.selectionStart.endColumn; } else if (position.isBeforeOrEqual(cursor.selectionStart.getStartPosition())) { column = startColumn; var possiblePosition = new position_1.Position(lineNumber, column); if (cursor.selectionStart.containsPosition(possiblePosition)) { column = cursor.selectionStart.endColumn; } } else { column = endColumn; var possiblePosition = new position_1.Position(lineNumber, column); if (cursor.selectionStart.containsPosition(possiblePosition)) { column = cursor.selectionStart.startColumn; } } return cursor.move(true, lineNumber, column, 0); }; return WordOperations; }()); exports.WordOperations = WordOperations; var WordPartOperations = /** @class */ (function (_super) { __extends(WordPartOperations, _super); function WordPartOperations() { return _super !== null && _super.apply(this, arguments) || this; } WordPartOperations.deleteWordPartLeft = function (wordSeparators, model, selection, whitespaceHeuristics) { var candidates = enforceDefined([ WordOperations.deleteWordLeft(wordSeparators, model, selection, whitespaceHeuristics, 0 /* WordStart */), WordOperations.deleteWordLeft(wordSeparators, model, selection, whitespaceHeuristics, 2 /* WordEnd */), WordOperations._deleteWordPartLeft(model, selection) ]); candidates.sort(range_1.Range.compareRangesUsingEnds); return candidates[2]; }; WordPartOperations.deleteWordPartRight = function (wordSeparators, model, selection, whitespaceHeuristics) { var candidates = enforceDefined([ WordOperations.deleteWordRight(wordSeparators, model, selection, whitespaceHeuristics, 0 /* WordStart */), WordOperations.deleteWordRight(wordSeparators, model, selection, whitespaceHeuristics, 2 /* WordEnd */), WordOperations._deleteWordPartRight(model, selection) ]); candidates.sort(range_1.Range.compareRangesUsingStarts); return candidates[0]; }; WordPartOperations.moveWordPartLeft = function (wordSeparators, model, position) { var candidates = enforceDefined([ WordOperations.moveWordLeft(wordSeparators, model, position, 0 /* WordStart */), WordOperations.moveWordLeft(wordSeparators, model, position, 2 /* WordEnd */), WordOperations._moveWordPartLeft(model, position) ]); candidates.sort(position_1.Position.compare); return candidates[2]; }; WordPartOperations.moveWordPartRight = function (wordSeparators, model, position) { var candidates = enforceDefined([ WordOperations.moveWordRight(wordSeparators, model, position, 0 /* WordStart */), WordOperations.moveWordRight(wordSeparators, model, position, 2 /* WordEnd */), WordOperations._moveWordPartRight(model, position) ]); candidates.sort(position_1.Position.compare); return candidates[0]; }; return WordPartOperations; }(WordOperations)); exports.WordPartOperations = WordPartOperations; function enforceDefined(arr) { return arr.filter(function (el) { return Boolean(el); }); } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[213/*vs/editor/common/controller/cursorMoveCommands*/], __M([0/*require*/,1/*exports*/,21/*vs/base/common/types*/,40/*vs/editor/common/controller/cursorCommon*/,158/*vs/editor/common/controller/cursorMoveOperations*/,160/*vs/editor/common/controller/cursorWordOperations*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, types, cursorCommon_1, cursorMoveOperations_1, cursorWordOperations_1, position_1, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CursorMoveCommands = /** @class */ (function () { function CursorMoveCommands() { } CursorMoveCommands.addCursorDown = function (context, cursors, useLogicalLine) { var result = [], resultLen = 0; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; result[resultLen++] = new cursorCommon_1.CursorState(cursor.modelState, cursor.viewState); if (useLogicalLine) { result[resultLen++] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.translateDown(context.config, context.model, cursor.modelState)); } else { result[resultLen++] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.translateDown(context.config, context.viewModel, cursor.viewState)); } } return result; }; CursorMoveCommands.addCursorUp = function (context, cursors, useLogicalLine) { var result = [], resultLen = 0; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; result[resultLen++] = new cursorCommon_1.CursorState(cursor.modelState, cursor.viewState); if (useLogicalLine) { result[resultLen++] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.translateUp(context.config, context.model, cursor.modelState)); } else { result[resultLen++] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.translateUp(context.config, context.viewModel, cursor.viewState)); } } return result; }; CursorMoveCommands.moveToBeginningOfLine = function (context, cursors, inSelectionMode) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; result[i] = this._moveToLineStart(context, cursor, inSelectionMode); } return result; }; CursorMoveCommands._moveToLineStart = function (context, cursor, inSelectionMode) { var currentViewStateColumn = cursor.viewState.position.column; var currentModelStateColumn = cursor.modelState.position.column; var isFirstLineOfWrappedLine = currentViewStateColumn === currentModelStateColumn; var currentViewStatelineNumber = cursor.viewState.position.lineNumber; var firstNonBlankColumn = context.viewModel.getLineFirstNonWhitespaceColumn(currentViewStatelineNumber); var isBeginningOfViewLine = currentViewStateColumn === firstNonBlankColumn; if (!isFirstLineOfWrappedLine && !isBeginningOfViewLine) { return this._moveToLineStartByView(context, cursor, inSelectionMode); } else { return this._moveToLineStartByModel(context, cursor, inSelectionMode); } }; CursorMoveCommands._moveToLineStartByView = function (context, cursor, inSelectionMode) { return cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveToBeginningOfLine(context.config, context.viewModel, cursor.viewState, inSelectionMode)); }; CursorMoveCommands._moveToLineStartByModel = function (context, cursor, inSelectionMode) { return cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToBeginningOfLine(context.config, context.model, cursor.modelState, inSelectionMode)); }; CursorMoveCommands.moveToEndOfLine = function (context, cursors, inSelectionMode) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; result[i] = this._moveToLineEnd(context, cursor, inSelectionMode); } return result; }; CursorMoveCommands._moveToLineEnd = function (context, cursor, inSelectionMode) { var viewStatePosition = cursor.viewState.position; var viewModelMaxColumn = context.viewModel.getLineMaxColumn(viewStatePosition.lineNumber); var isEndOfViewLine = viewStatePosition.column === viewModelMaxColumn; var modelStatePosition = cursor.modelState.position; var modelMaxColumn = context.model.getLineMaxColumn(modelStatePosition.lineNumber); var isEndLineOfWrappedLine = viewModelMaxColumn - viewStatePosition.column === modelMaxColumn - modelStatePosition.column; if (isEndOfViewLine || isEndLineOfWrappedLine) { return this._moveToLineEndByModel(context, cursor, inSelectionMode); } else { return this._moveToLineEndByView(context, cursor, inSelectionMode); } }; CursorMoveCommands._moveToLineEndByView = function (context, cursor, inSelectionMode) { return cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveToEndOfLine(context.config, context.viewModel, cursor.viewState, inSelectionMode)); }; CursorMoveCommands._moveToLineEndByModel = function (context, cursor, inSelectionMode) { return cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToEndOfLine(context.config, context.model, cursor.modelState, inSelectionMode)); }; CursorMoveCommands.expandLineSelection = function (context, cursors) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; var startLineNumber = cursor.modelState.selection.startLineNumber; var lineCount = context.model.getLineCount(); var endLineNumber = cursor.modelState.selection.endLineNumber; var endColumn = void 0; if (endLineNumber === lineCount) { endColumn = context.model.getLineMaxColumn(lineCount); } else { endLineNumber++; endColumn = 1; } result[i] = cursorCommon_1.CursorState.fromModelState(new cursorCommon_1.SingleCursorState(new range_1.Range(startLineNumber, 1, startLineNumber, 1), 0, new position_1.Position(endLineNumber, endColumn), 0)); } return result; }; CursorMoveCommands.moveToBeginningOfBuffer = function (context, cursors, inSelectionMode) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToBeginningOfBuffer(context.config, context.model, cursor.modelState, inSelectionMode)); } return result; }; CursorMoveCommands.moveToEndOfBuffer = function (context, cursors, inSelectionMode) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToEndOfBuffer(context.config, context.model, cursor.modelState, inSelectionMode)); } return result; }; CursorMoveCommands.selectAll = function (context, cursor) { var lineCount = context.model.getLineCount(); var maxColumn = context.model.getLineMaxColumn(lineCount); return cursorCommon_1.CursorState.fromModelState(new cursorCommon_1.SingleCursorState(new range_1.Range(1, 1, 1, 1), 0, new position_1.Position(lineCount, maxColumn), 0)); }; CursorMoveCommands.line = function (context, cursor, inSelectionMode, _position, _viewPosition) { var position = context.model.validatePosition(_position); var viewPosition = (_viewPosition ? context.validateViewPosition(new position_1.Position(_viewPosition.lineNumber, _viewPosition.column), position) : context.convertModelPositionToViewPosition(position)); if (!inSelectionMode || !cursor.modelState.hasSelection()) { // Entering line selection for the first time var lineCount = context.model.getLineCount(); var selectToLineNumber = position.lineNumber + 1; var selectToColumn = 1; if (selectToLineNumber > lineCount) { selectToLineNumber = lineCount; selectToColumn = context.model.getLineMaxColumn(selectToLineNumber); } return cursorCommon_1.CursorState.fromModelState(new cursorCommon_1.SingleCursorState(new range_1.Range(position.lineNumber, 1, selectToLineNumber, selectToColumn), 0, new position_1.Position(selectToLineNumber, selectToColumn), 0)); } // Continuing line selection var enteringLineNumber = cursor.modelState.selectionStart.getStartPosition().lineNumber; if (position.lineNumber < enteringLineNumber) { return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(cursor.modelState.hasSelection(), viewPosition.lineNumber, 1, 0)); } else if (position.lineNumber > enteringLineNumber) { var lineCount = context.viewModel.getLineCount(); var selectToViewLineNumber = viewPosition.lineNumber + 1; var selectToViewColumn = 1; if (selectToViewLineNumber > lineCount) { selectToViewLineNumber = lineCount; selectToViewColumn = context.viewModel.getLineMaxColumn(selectToViewLineNumber); } return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(cursor.modelState.hasSelection(), selectToViewLineNumber, selectToViewColumn, 0)); } else { var endPositionOfSelectionStart = cursor.modelState.selectionStart.getEndPosition(); return cursorCommon_1.CursorState.fromModelState(cursor.modelState.move(cursor.modelState.hasSelection(), endPositionOfSelectionStart.lineNumber, endPositionOfSelectionStart.column, 0)); } }; CursorMoveCommands.word = function (context, cursor, inSelectionMode, _position) { var position = context.model.validatePosition(_position); return cursorCommon_1.CursorState.fromModelState(cursorWordOperations_1.WordOperations.word(context.config, context.model, cursor.modelState, inSelectionMode, position)); }; CursorMoveCommands.cancelSelection = function (context, cursor) { if (!cursor.modelState.hasSelection()) { return new cursorCommon_1.CursorState(cursor.modelState, cursor.viewState); } var lineNumber = cursor.viewState.position.lineNumber; var column = cursor.viewState.position.column; return cursorCommon_1.CursorState.fromViewState(new cursorCommon_1.SingleCursorState(new range_1.Range(lineNumber, column, lineNumber, column), 0, new position_1.Position(lineNumber, column), 0)); }; CursorMoveCommands.moveTo = function (context, cursor, inSelectionMode, _position, _viewPosition) { var position = context.model.validatePosition(_position); var viewPosition = (_viewPosition ? context.validateViewPosition(new position_1.Position(_viewPosition.lineNumber, _viewPosition.column), position) : context.convertModelPositionToViewPosition(position)); return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(inSelectionMode, viewPosition.lineNumber, viewPosition.column, 0)); }; CursorMoveCommands.move = function (context, cursors, args) { var inSelectionMode = args.select; var value = args.value; switch (args.direction) { case 0 /* Left */: { if (args.unit === 4 /* HalfLine */) { // Move left by half the current line length return this._moveHalfLineLeft(context, cursors, inSelectionMode); } else { // Move left by `moveParams.value` columns return this._moveLeft(context, cursors, inSelectionMode, value); } } case 1 /* Right */: { if (args.unit === 4 /* HalfLine */) { // Move right by half the current line length return this._moveHalfLineRight(context, cursors, inSelectionMode); } else { // Move right by `moveParams.value` columns return this._moveRight(context, cursors, inSelectionMode, value); } } case 2 /* Up */: { if (args.unit === 2 /* WrappedLine */) { // Move up by view lines return this._moveUpByViewLines(context, cursors, inSelectionMode, value); } else { // Move up by model lines return this._moveUpByModelLines(context, cursors, inSelectionMode, value); } } case 3 /* Down */: { if (args.unit === 2 /* WrappedLine */) { // Move down by view lines return this._moveDownByViewLines(context, cursors, inSelectionMode, value); } else { // Move down by model lines return this._moveDownByModelLines(context, cursors, inSelectionMode, value); } } case 4 /* WrappedLineStart */: { // Move to the beginning of the current view line return this._moveToViewMinColumn(context, cursors, inSelectionMode); } case 5 /* WrappedLineFirstNonWhitespaceCharacter */: { // Move to the first non-whitespace column of the current view line return this._moveToViewFirstNonWhitespaceColumn(context, cursors, inSelectionMode); } case 6 /* WrappedLineColumnCenter */: { // Move to the "center" of the current view line return this._moveToViewCenterColumn(context, cursors, inSelectionMode); } case 7 /* WrappedLineEnd */: { // Move to the end of the current view line return this._moveToViewMaxColumn(context, cursors, inSelectionMode); } case 8 /* WrappedLineLastNonWhitespaceCharacter */: { // Move to the last non-whitespace column of the current view line return this._moveToViewLastNonWhitespaceColumn(context, cursors, inSelectionMode); } case 9 /* ViewPortTop */: { // Move to the nth line start in the viewport (from the top) var cursor = cursors[0]; var visibleModelRange = context.getCompletelyVisibleModelRange(); var modelLineNumber = this._firstLineNumberInRange(context.model, visibleModelRange, value); var modelColumn = context.model.getLineFirstNonWhitespaceColumn(modelLineNumber); return [this._moveToModelPosition(context, cursor, inSelectionMode, modelLineNumber, modelColumn)]; } case 11 /* ViewPortBottom */: { // Move to the nth line start in the viewport (from the bottom) var cursor = cursors[0]; var visibleModelRange = context.getCompletelyVisibleModelRange(); var modelLineNumber = this._lastLineNumberInRange(context.model, visibleModelRange, value); var modelColumn = context.model.getLineFirstNonWhitespaceColumn(modelLineNumber); return [this._moveToModelPosition(context, cursor, inSelectionMode, modelLineNumber, modelColumn)]; } case 10 /* ViewPortCenter */: { // Move to the line start in the viewport center var cursor = cursors[0]; var visibleModelRange = context.getCompletelyVisibleModelRange(); var modelLineNumber = Math.round((visibleModelRange.startLineNumber + visibleModelRange.endLineNumber) / 2); var modelColumn = context.model.getLineFirstNonWhitespaceColumn(modelLineNumber); return [this._moveToModelPosition(context, cursor, inSelectionMode, modelLineNumber, modelColumn)]; } case 12 /* ViewPortIfOutside */: { // Move to a position inside the viewport var visibleViewRange = context.getCompletelyVisibleViewRange(); var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; result[i] = this.findPositionInViewportIfOutside(context, cursor, visibleViewRange, inSelectionMode); } return result; } } return null; }; CursorMoveCommands.findPositionInViewportIfOutside = function (context, cursor, visibleViewRange, inSelectionMode) { var viewLineNumber = cursor.viewState.position.lineNumber; if (visibleViewRange.startLineNumber <= viewLineNumber && viewLineNumber <= visibleViewRange.endLineNumber - 1) { // Nothing to do, cursor is in viewport return new cursorCommon_1.CursorState(cursor.modelState, cursor.viewState); } else { if (viewLineNumber > visibleViewRange.endLineNumber - 1) { viewLineNumber = visibleViewRange.endLineNumber - 1; } if (viewLineNumber < visibleViewRange.startLineNumber) { viewLineNumber = visibleViewRange.startLineNumber; } var viewColumn = context.viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber); return this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn); } }; /** * Find the nth line start included in the range (from the start). */ CursorMoveCommands._firstLineNumberInRange = function (model, range, count) { var startLineNumber = range.startLineNumber; if (range.startColumn !== model.getLineMinColumn(startLineNumber)) { // Move on to the second line if the first line start is not included in the range startLineNumber++; } return Math.min(range.endLineNumber, startLineNumber + count - 1); }; /** * Find the nth line start included in the range (from the end). */ CursorMoveCommands._lastLineNumberInRange = function (model, range, count) { var startLineNumber = range.startLineNumber; if (range.startColumn !== model.getLineMinColumn(startLineNumber)) { // Move on to the second line if the first line start is not included in the range startLineNumber++; } return Math.max(startLineNumber, range.endLineNumber - count + 1); }; CursorMoveCommands._moveLeft = function (context, cursors, inSelectionMode, noOfColumns) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; var newViewState = cursorMoveOperations_1.MoveOperations.moveLeft(context.config, context.viewModel, cursor.viewState, inSelectionMode, noOfColumns); if (noOfColumns === 1 && newViewState.position.lineNumber !== cursor.viewState.position.lineNumber) { // moved over to the previous view line var newViewModelPosition = context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(newViewState.position); if (newViewModelPosition.lineNumber === cursor.modelState.position.lineNumber) { // stayed on the same model line => pass wrapping point where 2 view positions map to a single model position newViewState = cursorMoveOperations_1.MoveOperations.moveLeft(context.config, context.viewModel, newViewState, inSelectionMode, 1); } } result[i] = cursorCommon_1.CursorState.fromViewState(newViewState); } return result; }; CursorMoveCommands._moveHalfLineLeft = function (context, cursors, inSelectionMode) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; var viewLineNumber = cursor.viewState.position.lineNumber; var halfLine = Math.round(context.viewModel.getLineContent(viewLineNumber).length / 2); result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveLeft(context.config, context.viewModel, cursor.viewState, inSelectionMode, halfLine)); } return result; }; CursorMoveCommands._moveRight = function (context, cursors, inSelectionMode, noOfColumns) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; var newViewState = cursorMoveOperations_1.MoveOperations.moveRight(context.config, context.viewModel, cursor.viewState, inSelectionMode, noOfColumns); if (noOfColumns === 1 && newViewState.position.lineNumber !== cursor.viewState.position.lineNumber) { // moved over to the next view line var newViewModelPosition = context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(newViewState.position); if (newViewModelPosition.lineNumber === cursor.modelState.position.lineNumber) { // stayed on the same model line => pass wrapping point where 2 view positions map to a single model position newViewState = cursorMoveOperations_1.MoveOperations.moveRight(context.config, context.viewModel, newViewState, inSelectionMode, 1); } } result[i] = cursorCommon_1.CursorState.fromViewState(newViewState); } return result; }; CursorMoveCommands._moveHalfLineRight = function (context, cursors, inSelectionMode) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; var viewLineNumber = cursor.viewState.position.lineNumber; var halfLine = Math.round(context.viewModel.getLineContent(viewLineNumber).length / 2); result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveRight(context.config, context.viewModel, cursor.viewState, inSelectionMode, halfLine)); } return result; }; CursorMoveCommands._moveDownByViewLines = function (context, cursors, inSelectionMode, linesCount) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveDown(context.config, context.viewModel, cursor.viewState, inSelectionMode, linesCount)); } return result; }; CursorMoveCommands._moveDownByModelLines = function (context, cursors, inSelectionMode, linesCount) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveDown(context.config, context.model, cursor.modelState, inSelectionMode, linesCount)); } return result; }; CursorMoveCommands._moveUpByViewLines = function (context, cursors, inSelectionMode, linesCount) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveUp(context.config, context.viewModel, cursor.viewState, inSelectionMode, linesCount)); } return result; }; CursorMoveCommands._moveUpByModelLines = function (context, cursors, inSelectionMode, linesCount) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveUp(context.config, context.model, cursor.modelState, inSelectionMode, linesCount)); } return result; }; CursorMoveCommands._moveToViewPosition = function (context, cursor, inSelectionMode, toViewLineNumber, toViewColumn) { return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(inSelectionMode, toViewLineNumber, toViewColumn, 0)); }; CursorMoveCommands._moveToModelPosition = function (context, cursor, inSelectionMode, toModelLineNumber, toModelColumn) { return cursorCommon_1.CursorState.fromModelState(cursor.modelState.move(inSelectionMode, toModelLineNumber, toModelColumn, 0)); }; CursorMoveCommands._moveToViewMinColumn = function (context, cursors, inSelectionMode) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; var viewLineNumber = cursor.viewState.position.lineNumber; var viewColumn = context.viewModel.getLineMinColumn(viewLineNumber); result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn); } return result; }; CursorMoveCommands._moveToViewFirstNonWhitespaceColumn = function (context, cursors, inSelectionMode) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; var viewLineNumber = cursor.viewState.position.lineNumber; var viewColumn = context.viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber); result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn); } return result; }; CursorMoveCommands._moveToViewCenterColumn = function (context, cursors, inSelectionMode) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; var viewLineNumber = cursor.viewState.position.lineNumber; var viewColumn = Math.round((context.viewModel.getLineMaxColumn(viewLineNumber) + context.viewModel.getLineMinColumn(viewLineNumber)) / 2); result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn); } return result; }; CursorMoveCommands._moveToViewMaxColumn = function (context, cursors, inSelectionMode) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; var viewLineNumber = cursor.viewState.position.lineNumber; var viewColumn = context.viewModel.getLineMaxColumn(viewLineNumber); result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn); } return result; }; CursorMoveCommands._moveToViewLastNonWhitespaceColumn = function (context, cursors, inSelectionMode) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; var viewLineNumber = cursor.viewState.position.lineNumber; var viewColumn = context.viewModel.getLineLastNonWhitespaceColumn(viewLineNumber); result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn); } return result; }; return CursorMoveCommands; }()); exports.CursorMoveCommands = CursorMoveCommands; var CursorMove; (function (CursorMove) { var isCursorMoveArgs = function (arg) { if (!types.isObject(arg)) { return false; } var cursorMoveArg = arg; if (!types.isString(cursorMoveArg.to)) { return false; } if (!types.isUndefined(cursorMoveArg.select) && !types.isBoolean(cursorMoveArg.select)) { return false; } if (!types.isUndefined(cursorMoveArg.by) && !types.isString(cursorMoveArg.by)) { return false; } if (!types.isUndefined(cursorMoveArg.value) && !types.isNumber(cursorMoveArg.value)) { return false; } return true; }; CursorMove.description = { description: 'Move cursor to a logical position in the view', args: [ { name: 'Cursor move argument object', description: "Property-value pairs that can be passed through this argument:\n\t\t\t\t\t* 'to': A mandatory logical position value providing where to move the cursor.\n\t\t\t\t\t\t```\n\t\t\t\t\t\t'left', 'right', 'up', 'down'\n\t\t\t\t\t\t'wrappedLineStart', 'wrappedLineEnd', 'wrappedLineColumnCenter'\n\t\t\t\t\t\t'wrappedLineFirstNonWhitespaceCharacter', 'wrappedLineLastNonWhitespaceCharacter'\n\t\t\t\t\t\t'viewPortTop', 'viewPortCenter', 'viewPortBottom', 'viewPortIfOutside'\n\t\t\t\t\t\t```\n\t\t\t\t\t* 'by': Unit to move. Default is computed based on 'to' value.\n\t\t\t\t\t\t```\n\t\t\t\t\t\t'line', 'wrappedLine', 'character', 'halfLine'\n\t\t\t\t\t\t```\n\t\t\t\t\t* 'value': Number of units to move. Default is '1'.\n\t\t\t\t\t* 'select': If 'true' makes the selection. Default is 'false'.\n\t\t\t\t", constraint: isCursorMoveArgs, schema: { 'type': 'object', 'required': ['to'], 'properties': { 'to': { 'type': 'string', 'enum': ['left', 'right', 'up', 'down', 'wrappedLineStart', 'wrappedLineEnd', 'wrappedLineColumnCenter', 'wrappedLineFirstNonWhitespaceCharacter', 'wrappedLineLastNonWhitespaceCharacter', 'viewPortTop', 'viewPortCenter', 'viewPortBottom', 'viewPortIfOutside'] }, 'by': { 'type': 'string', 'enum': ['line', 'wrappedLine', 'character', 'halfLine'] }, 'value': { 'type': 'number', 'default': 1 }, 'select': { 'type': 'boolean', 'default': false } } } } ] }; /** * Positions in the view for cursor move command. */ CursorMove.RawDirection = { Left: 'left', Right: 'right', Up: 'up', Down: 'down', WrappedLineStart: 'wrappedLineStart', WrappedLineFirstNonWhitespaceCharacter: 'wrappedLineFirstNonWhitespaceCharacter', WrappedLineColumnCenter: 'wrappedLineColumnCenter', WrappedLineEnd: 'wrappedLineEnd', WrappedLineLastNonWhitespaceCharacter: 'wrappedLineLastNonWhitespaceCharacter', ViewPortTop: 'viewPortTop', ViewPortCenter: 'viewPortCenter', ViewPortBottom: 'viewPortBottom', ViewPortIfOutside: 'viewPortIfOutside' }; /** * Units for Cursor move 'by' argument */ CursorMove.RawUnit = { Line: 'line', WrappedLine: 'wrappedLine', Character: 'character', HalfLine: 'halfLine' }; function parse(args) { if (!args.to) { // illegal arguments return null; } var direction; switch (args.to) { case CursorMove.RawDirection.Left: direction = 0 /* Left */; break; case CursorMove.RawDirection.Right: direction = 1 /* Right */; break; case CursorMove.RawDirection.Up: direction = 2 /* Up */; break; case CursorMove.RawDirection.Down: direction = 3 /* Down */; break; case CursorMove.RawDirection.WrappedLineStart: direction = 4 /* WrappedLineStart */; break; case CursorMove.RawDirection.WrappedLineFirstNonWhitespaceCharacter: direction = 5 /* WrappedLineFirstNonWhitespaceCharacter */; break; case CursorMove.RawDirection.WrappedLineColumnCenter: direction = 6 /* WrappedLineColumnCenter */; break; case CursorMove.RawDirection.WrappedLineEnd: direction = 7 /* WrappedLineEnd */; break; case CursorMove.RawDirection.WrappedLineLastNonWhitespaceCharacter: direction = 8 /* WrappedLineLastNonWhitespaceCharacter */; break; case CursorMove.RawDirection.ViewPortTop: direction = 9 /* ViewPortTop */; break; case CursorMove.RawDirection.ViewPortBottom: direction = 11 /* ViewPortBottom */; break; case CursorMove.RawDirection.ViewPortCenter: direction = 10 /* ViewPortCenter */; break; case CursorMove.RawDirection.ViewPortIfOutside: direction = 12 /* ViewPortIfOutside */; break; default: // illegal arguments return null; } var unit = 0 /* None */; switch (args.by) { case CursorMove.RawUnit.Line: unit = 1 /* Line */; break; case CursorMove.RawUnit.WrappedLine: unit = 2 /* WrappedLine */; break; case CursorMove.RawUnit.Character: unit = 3 /* Character */; break; case CursorMove.RawUnit.HalfLine: unit = 4 /* HalfLine */; break; } return { direction: direction, unit: unit, select: (!!args.select), value: (args.value || 1) }; } CursorMove.parse = parse; })(CursorMove = exports.CursorMove || (exports.CursorMove = {})); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[484/*vs/editor/common/controller/oneCursor*/], __M([0/*require*/,1/*exports*/,40/*vs/editor/common/controller/cursorCommon*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/]), function (require, exports, cursorCommon_1, position_1, range_1, selection_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var OneCursor = /** @class */ (function () { function OneCursor(context) { this._selTrackedRange = null; this._trackSelection = true; this._setState(context, new cursorCommon_1.SingleCursorState(new range_1.Range(1, 1, 1, 1), 0, new position_1.Position(1, 1), 0), new cursorCommon_1.SingleCursorState(new range_1.Range(1, 1, 1, 1), 0, new position_1.Position(1, 1), 0)); } OneCursor.prototype.dispose = function (context) { this._removeTrackedRange(context); }; OneCursor.prototype.startTrackingSelection = function (context) { this._trackSelection = true; this._updateTrackedRange(context); }; OneCursor.prototype.stopTrackingSelection = function (context) { this._trackSelection = false; this._removeTrackedRange(context); }; OneCursor.prototype._updateTrackedRange = function (context) { if (!this._trackSelection) { // don't track the selection return; } this._selTrackedRange = context.model._setTrackedRange(this._selTrackedRange, this.modelState.selection, 0 /* AlwaysGrowsWhenTypingAtEdges */); }; OneCursor.prototype._removeTrackedRange = function (context) { this._selTrackedRange = context.model._setTrackedRange(this._selTrackedRange, null, 0 /* AlwaysGrowsWhenTypingAtEdges */); }; OneCursor.prototype.asCursorState = function () { return new cursorCommon_1.CursorState(this.modelState, this.viewState); }; OneCursor.prototype.readSelectionFromMarkers = function (context) { var range = context.model._getTrackedRange(this._selTrackedRange); if (this.modelState.selection.getDirection() === 0 /* LTR */) { return new selection_1.Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn); } return new selection_1.Selection(range.endLineNumber, range.endColumn, range.startLineNumber, range.startColumn); }; OneCursor.prototype.ensureValidState = function (context) { this._setState(context, this.modelState, this.viewState); }; OneCursor.prototype.setState = function (context, modelState, viewState) { this._setState(context, modelState, viewState); }; OneCursor.prototype._setState = function (context, modelState, viewState) { if (!modelState) { if (!viewState) { return; } // We only have the view state => compute the model state var selectionStart = context.model.validateRange(context.convertViewRangeToModelRange(viewState.selectionStart)); var position = context.model.validatePosition(context.convertViewPositionToModelPosition(viewState.position.lineNumber, viewState.position.column)); modelState = new cursorCommon_1.SingleCursorState(selectionStart, viewState.selectionStartLeftoverVisibleColumns, position, viewState.leftoverVisibleColumns); } else { // Validate new model state var selectionStart = context.model.validateRange(modelState.selectionStart); var selectionStartLeftoverVisibleColumns = modelState.selectionStart.equalsRange(selectionStart) ? modelState.selectionStartLeftoverVisibleColumns : 0; var position = context.model.validatePosition(modelState.position); var leftoverVisibleColumns = modelState.position.equals(position) ? modelState.leftoverVisibleColumns : 0; modelState = new cursorCommon_1.SingleCursorState(selectionStart, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns); } if (!viewState) { // We only have the model state => compute the view state var viewSelectionStart1 = context.convertModelPositionToViewPosition(new position_1.Position(modelState.selectionStart.startLineNumber, modelState.selectionStart.startColumn)); var viewSelectionStart2 = context.convertModelPositionToViewPosition(new position_1.Position(modelState.selectionStart.endLineNumber, modelState.selectionStart.endColumn)); var viewSelectionStart = new range_1.Range(viewSelectionStart1.lineNumber, viewSelectionStart1.column, viewSelectionStart2.lineNumber, viewSelectionStart2.column); var viewPosition = context.convertModelPositionToViewPosition(modelState.position); viewState = new cursorCommon_1.SingleCursorState(viewSelectionStart, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns); } else { // Validate new view state var viewSelectionStart = context.validateViewRange(viewState.selectionStart, modelState.selectionStart); var viewPosition = context.validateViewPosition(viewState.position, modelState.position); viewState = new cursorCommon_1.SingleCursorState(viewSelectionStart, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns); } this.modelState = modelState; this.viewState = viewState; this._updateTrackedRange(context); }; return OneCursor; }()); exports.OneCursor = OneCursor; }); /*--------------------------------------------------------------------------------------------- * 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/editor/common/controller/cursorCollection*/], __M([0/*require*/,1/*exports*/,40/*vs/editor/common/controller/cursorCommon*/,484/*vs/editor/common/controller/oneCursor*/,22/*vs/editor/common/core/selection*/]), function (require, exports, cursorCommon_1, oneCursor_1, selection_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CursorCollection = /** @class */ (function () { function CursorCollection(context) { this.context = context; this.primaryCursor = new oneCursor_1.OneCursor(context); this.secondaryCursors = []; this.lastAddedCursorIndex = 0; } CursorCollection.prototype.dispose = function () { this.primaryCursor.dispose(this.context); this.killSecondaryCursors(); }; CursorCollection.prototype.startTrackingSelections = function () { this.primaryCursor.startTrackingSelection(this.context); for (var i = 0, len = this.secondaryCursors.length; i < len; i++) { this.secondaryCursors[i].startTrackingSelection(this.context); } }; CursorCollection.prototype.stopTrackingSelections = function () { this.primaryCursor.stopTrackingSelection(this.context); for (var i = 0, len = this.secondaryCursors.length; i < len; i++) { this.secondaryCursors[i].stopTrackingSelection(this.context); } }; CursorCollection.prototype.updateContext = function (context) { this.context = context; }; CursorCollection.prototype.ensureValidState = function () { this.primaryCursor.ensureValidState(this.context); for (var i = 0, len = this.secondaryCursors.length; i < len; i++) { this.secondaryCursors[i].ensureValidState(this.context); } }; CursorCollection.prototype.readSelectionFromMarkers = function () { var result = []; result[0] = this.primaryCursor.readSelectionFromMarkers(this.context); for (var i = 0, len = this.secondaryCursors.length; i < len; i++) { result[i + 1] = this.secondaryCursors[i].readSelectionFromMarkers(this.context); } return result; }; CursorCollection.prototype.getAll = function () { var result = []; result[0] = this.primaryCursor.asCursorState(); for (var i = 0, len = this.secondaryCursors.length; i < len; i++) { result[i + 1] = this.secondaryCursors[i].asCursorState(); } return result; }; CursorCollection.prototype.getViewPositions = function () { var result = []; result[0] = this.primaryCursor.viewState.position; for (var i = 0, len = this.secondaryCursors.length; i < len; i++) { result[i + 1] = this.secondaryCursors[i].viewState.position; } return result; }; CursorCollection.prototype.getSelections = function () { var result = []; result[0] = this.primaryCursor.modelState.selection; for (var i = 0, len = this.secondaryCursors.length; i < len; i++) { result[i + 1] = this.secondaryCursors[i].modelState.selection; } return result; }; CursorCollection.prototype.getViewSelections = function () { var result = []; result[0] = this.primaryCursor.viewState.selection; for (var i = 0, len = this.secondaryCursors.length; i < len; i++) { result[i + 1] = this.secondaryCursors[i].viewState.selection; } return result; }; CursorCollection.prototype.setSelections = function (selections) { this.setStates(cursorCommon_1.CursorState.fromModelSelections(selections)); }; CursorCollection.prototype.getPrimaryCursor = function () { return this.primaryCursor.asCursorState(); }; CursorCollection.prototype.setStates = function (states) { if (states === null) { return; } this.primaryCursor.setState(this.context, states[0].modelState, states[0].viewState); this._setSecondaryStates(states.slice(1)); }; /** * Creates or disposes secondary cursors as necessary to match the number of `secondarySelections`. */ CursorCollection.prototype._setSecondaryStates = function (secondaryStates) { var secondaryCursorsLength = this.secondaryCursors.length; var secondaryStatesLength = secondaryStates.length; if (secondaryCursorsLength < secondaryStatesLength) { var createCnt = secondaryStatesLength - secondaryCursorsLength; for (var i = 0; i < createCnt; i++) { this._addSecondaryCursor(); } } else if (secondaryCursorsLength > secondaryStatesLength) { var removeCnt = secondaryCursorsLength - secondaryStatesLength; for (var i = 0; i < removeCnt; i++) { this._removeSecondaryCursor(this.secondaryCursors.length - 1); } } for (var i = 0; i < secondaryStatesLength; i++) { this.secondaryCursors[i].setState(this.context, secondaryStates[i].modelState, secondaryStates[i].viewState); } }; CursorCollection.prototype.killSecondaryCursors = function () { this._setSecondaryStates([]); }; CursorCollection.prototype._addSecondaryCursor = function () { this.secondaryCursors.push(new oneCursor_1.OneCursor(this.context)); this.lastAddedCursorIndex = this.secondaryCursors.length; }; CursorCollection.prototype.getLastAddedCursorIndex = function () { if (this.secondaryCursors.length === 0 || this.lastAddedCursorIndex === 0) { return 0; } return this.lastAddedCursorIndex; }; CursorCollection.prototype._removeSecondaryCursor = function (removeIndex) { if (this.lastAddedCursorIndex >= removeIndex + 1) { this.lastAddedCursorIndex--; } this.secondaryCursors[removeIndex].dispose(this.context); this.secondaryCursors.splice(removeIndex, 1); }; CursorCollection.prototype._getAll = function () { var result = []; result[0] = this.primaryCursor; for (var i = 0, len = this.secondaryCursors.length; i < len; i++) { result[i + 1] = this.secondaryCursors[i]; } return result; }; CursorCollection.prototype.normalize = function () { if (this.secondaryCursors.length === 0) { return; } var cursors = this._getAll(); var sortedCursors = []; for (var i = 0, len = cursors.length; i < len; i++) { sortedCursors.push({ index: i, selection: cursors[i].modelState.selection, }); } sortedCursors.sort(function (a, b) { if (a.selection.startLineNumber === b.selection.startLineNumber) { return a.selection.startColumn - b.selection.startColumn; } return a.selection.startLineNumber - b.selection.startLineNumber; }); for (var sortedCursorIndex = 0; sortedCursorIndex < sortedCursors.length - 1; sortedCursorIndex++) { var current = sortedCursors[sortedCursorIndex]; var next = sortedCursors[sortedCursorIndex + 1]; var currentSelection = current.selection; var nextSelection = next.selection; if (!this.context.config.multiCursorMergeOverlapping) { continue; } var shouldMergeCursors = void 0; if (nextSelection.isEmpty() || currentSelection.isEmpty()) { // Merge touching cursors if one of them is collapsed shouldMergeCursors = nextSelection.getStartPosition().isBeforeOrEqual(currentSelection.getEndPosition()); } else { // Merge only overlapping cursors (i.e. allow touching ranges) shouldMergeCursors = nextSelection.getStartPosition().isBefore(currentSelection.getEndPosition()); } if (shouldMergeCursors) { var winnerSortedCursorIndex = current.index < next.index ? sortedCursorIndex : sortedCursorIndex + 1; var looserSortedCursorIndex = current.index < next.index ? sortedCursorIndex + 1 : sortedCursorIndex; var looserIndex = sortedCursors[looserSortedCursorIndex].index; var winnerIndex = sortedCursors[winnerSortedCursorIndex].index; var looserSelection = sortedCursors[looserSortedCursorIndex].selection; var winnerSelection = sortedCursors[winnerSortedCursorIndex].selection; if (!looserSelection.equalsSelection(winnerSelection)) { var resultingRange = looserSelection.plusRange(winnerSelection); var looserSelectionIsLTR = (looserSelection.selectionStartLineNumber === looserSelection.startLineNumber && looserSelection.selectionStartColumn === looserSelection.startColumn); var winnerSelectionIsLTR = (winnerSelection.selectionStartLineNumber === winnerSelection.startLineNumber && winnerSelection.selectionStartColumn === winnerSelection.startColumn); // Give more importance to the last added cursor (think Ctrl-dragging + hitting another cursor) var resultingSelectionIsLTR = void 0; if (looserIndex === this.lastAddedCursorIndex) { resultingSelectionIsLTR = looserSelectionIsLTR; this.lastAddedCursorIndex = winnerIndex; } else { // Winner takes it all resultingSelectionIsLTR = winnerSelectionIsLTR; } var resultingSelection = void 0; if (resultingSelectionIsLTR) { resultingSelection = new selection_1.Selection(resultingRange.startLineNumber, resultingRange.startColumn, resultingRange.endLineNumber, resultingRange.endColumn); } else { resultingSelection = new selection_1.Selection(resultingRange.endLineNumber, resultingRange.endColumn, resultingRange.startLineNumber, resultingRange.startColumn); } sortedCursors[winnerSortedCursorIndex].selection = resultingSelection; var resultingState = cursorCommon_1.CursorState.fromModelSelection(resultingSelection); cursors[winnerIndex].setState(this.context, resultingState.modelState, resultingState.viewState); } for (var _i = 0, sortedCursors_1 = sortedCursors; _i < sortedCursors_1.length; _i++) { var sortedCursor = sortedCursors_1[_i]; if (sortedCursor.index > looserIndex) { sortedCursor.index--; } } cursors.splice(looserIndex, 1); sortedCursors.splice(looserSortedCursorIndex, 1); this._removeSecondaryCursor(looserIndex - 1); sortedCursorIndex--; } } }; return CursorCollection; }()); exports.CursorCollection = CursorCollection; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[486/*vs/editor/common/controller/cursor*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,4/*vs/base/common/event*/,5/*vs/base/common/strings*/,485/*vs/editor/common/controller/cursorCollection*/,40/*vs/editor/common/controller/cursorCommon*/,212/*vs/editor/common/controller/cursorDeleteOperations*/,159/*vs/editor/common/controller/cursorTypeOperations*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,68/*vs/editor/common/editorCommon*/,81/*vs/editor/common/view/viewEvents*/,2/*vs/base/common/lifecycle*/]), function (require, exports, errors_1, event_1, strings, cursorCollection_1, cursorCommon_1, cursorDeleteOperations_1, cursorTypeOperations_1, range_1, selection_1, editorCommon, viewEvents, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function containsLineMappingChanged(events) { for (var i = 0, len = events.length; i < len; i++) { if (events[i].type === 8 /* ViewLineMappingChanged */) { return true; } } return false; } var CursorStateChangedEvent = /** @class */ (function () { function CursorStateChangedEvent(selections, modelVersionId, oldSelections, oldModelVersionId, source, reason) { this.selections = selections; this.modelVersionId = modelVersionId; this.oldSelections = oldSelections; this.oldModelVersionId = oldModelVersionId; this.source = source; this.reason = reason; } return CursorStateChangedEvent; }()); exports.CursorStateChangedEvent = CursorStateChangedEvent; /** * A snapshot of the cursor and the model state */ var CursorModelState = /** @class */ (function () { function CursorModelState(model, cursor) { this.modelVersionId = model.getVersionId(); this.cursorState = cursor.getAll(); } CursorModelState.prototype.equals = function (other) { if (!other) { return false; } if (this.modelVersionId !== other.modelVersionId) { return false; } if (this.cursorState.length !== other.cursorState.length) { return false; } for (var i = 0, len = this.cursorState.length; i < len; i++) { if (!this.cursorState[i].equals(other.cursorState[i])) { return false; } } return true; }; return CursorModelState; }()); exports.CursorModelState = CursorModelState; var AutoClosedAction = /** @class */ (function () { function AutoClosedAction(model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations) { this._model = model; this._autoClosedCharactersDecorations = autoClosedCharactersDecorations; this._autoClosedEnclosingDecorations = autoClosedEnclosingDecorations; } AutoClosedAction.getAllAutoClosedCharacters = function (autoClosedActions) { var autoClosedCharacters = []; for (var _i = 0, autoClosedActions_1 = autoClosedActions; _i < autoClosedActions_1.length; _i++) { var autoClosedAction = autoClosedActions_1[_i]; autoClosedCharacters = autoClosedCharacters.concat(autoClosedAction.getAutoClosedCharactersRanges()); } return autoClosedCharacters; }; AutoClosedAction.prototype.dispose = function () { this._autoClosedCharactersDecorations = this._model.deltaDecorations(this._autoClosedCharactersDecorations, []); this._autoClosedEnclosingDecorations = this._model.deltaDecorations(this._autoClosedEnclosingDecorations, []); }; AutoClosedAction.prototype.getAutoClosedCharactersRanges = function () { var result = []; for (var i = 0; i < this._autoClosedCharactersDecorations.length; i++) { var decorationRange = this._model.getDecorationRange(this._autoClosedCharactersDecorations[i]); if (decorationRange) { result.push(decorationRange); } } return result; }; AutoClosedAction.prototype.isValid = function (selections) { var enclosingRanges = []; for (var i = 0; i < this._autoClosedEnclosingDecorations.length; i++) { var decorationRange = this._model.getDecorationRange(this._autoClosedEnclosingDecorations[i]); if (decorationRange) { enclosingRanges.push(decorationRange); if (decorationRange.startLineNumber !== decorationRange.endLineNumber) { // Stop tracking if the range becomes multiline... return false; } } } enclosingRanges.sort(range_1.Range.compareRangesUsingStarts); selections.sort(range_1.Range.compareRangesUsingStarts); for (var i = 0; i < selections.length; i++) { if (i >= enclosingRanges.length) { return false; } if (!enclosingRanges[i].strictContainsRange(selections[i])) { return false; } } return true; }; return AutoClosedAction; }()); var Cursor = /** @class */ (function (_super) { __extends(Cursor, _super); function Cursor(configuration, model, viewModel) { var _this = _super.call(this) || this; _this._onDidReachMaxCursorCount = _this._register(new event_1.Emitter()); _this.onDidReachMaxCursorCount = _this._onDidReachMaxCursorCount.event; _this._onDidAttemptReadOnlyEdit = _this._register(new event_1.Emitter()); _this.onDidAttemptReadOnlyEdit = _this._onDidAttemptReadOnlyEdit.event; _this._onDidChange = _this._register(new event_1.Emitter()); _this.onDidChange = _this._onDidChange.event; _this._configuration = configuration; _this._model = model; _this._knownModelVersionId = _this._model.getVersionId(); _this._viewModel = viewModel; _this.context = new cursorCommon_1.CursorContext(_this._configuration, _this._model, _this._viewModel); _this._cursors = new cursorCollection_1.CursorCollection(_this.context); _this._isHandling = false; _this._isDoingComposition = false; _this._selectionsWhenCompositionStarted = null; _this._columnSelectData = null; _this._autoClosedActions = []; _this._prevEditOperationType = 0 /* Other */; _this._register(_this._model.onDidChangeRawContent(function (e) { _this._knownModelVersionId = e.versionId; if (_this._isHandling) { return; } var hadFlushEvent = e.containsEvent(1 /* Flush */); _this._onModelContentChanged(hadFlushEvent); })); _this._register(viewModel.addEventListener(function (events) { if (!containsLineMappingChanged(events)) { return; } if (_this._knownModelVersionId !== _this._model.getVersionId()) { // There are model change events that I didn't yet receive. // // This can happen when editing the model, and the view model receives the change events first, // and the view model emits line mapping changed events, all before the cursor gets a chance to // recover from markers. // // The model change listener above will be called soon and we'll ensure a valid cursor state there. return; } // Ensure valid state _this.setStates('viewModel', 0 /* NotSet */, _this.getAll()); })); var updateCursorContext = function () { _this.context = new cursorCommon_1.CursorContext(_this._configuration, _this._model, _this._viewModel); _this._cursors.updateContext(_this.context); }; _this._register(_this._model.onDidChangeLanguage(function (e) { updateCursorContext(); })); _this._register(_this._model.onDidChangeLanguageConfiguration(function () { updateCursorContext(); })); _this._register(_this._model.onDidChangeOptions(function () { updateCursorContext(); })); _this._register(_this._configuration.onDidChange(function (e) { if (cursorCommon_1.CursorConfiguration.shouldRecreate(e)) { updateCursorContext(); } })); return _this; } Cursor.prototype.dispose = function () { this._cursors.dispose(); this._autoClosedActions = lifecycle_1.dispose(this._autoClosedActions); _super.prototype.dispose.call(this); }; Cursor.prototype._validateAutoClosedActions = function () { if (this._autoClosedActions.length > 0) { var selections = this._cursors.getSelections(); for (var i = 0; i < this._autoClosedActions.length; i++) { var autoClosedAction = this._autoClosedActions[i]; if (!autoClosedAction.isValid(selections)) { autoClosedAction.dispose(); this._autoClosedActions.splice(i, 1); i--; } } } }; // ------ some getters/setters Cursor.prototype.getPrimaryCursor = function () { return this._cursors.getPrimaryCursor(); }; Cursor.prototype.getLastAddedCursorIndex = function () { return this._cursors.getLastAddedCursorIndex(); }; Cursor.prototype.getAll = function () { return this._cursors.getAll(); }; Cursor.prototype.setStates = function (source, reason, states) { if (states !== null && states.length > Cursor.MAX_CURSOR_COUNT) { states = states.slice(0, Cursor.MAX_CURSOR_COUNT); this._onDidReachMaxCursorCount.fire(undefined); } var oldState = new CursorModelState(this._model, this); this._cursors.setStates(states); this._cursors.normalize(); this._columnSelectData = null; this._validateAutoClosedActions(); this._emitStateChangedIfNecessary(source, reason, oldState); }; Cursor.prototype.setColumnSelectData = function (columnSelectData) { this._columnSelectData = columnSelectData; }; Cursor.prototype.reveal = function (source, horizontal, target, scrollType) { this._revealRange(source, target, 0 /* Simple */, horizontal, scrollType); }; Cursor.prototype.revealRange = function (source, revealHorizontal, viewRange, verticalType, scrollType) { this.emitCursorRevealRange(source, viewRange, verticalType, revealHorizontal, scrollType); }; Cursor.prototype.scrollTo = function (desiredScrollTop) { this._viewModel.viewLayout.setScrollPositionSmooth({ scrollTop: desiredScrollTop }); }; Cursor.prototype.saveState = function () { var result = []; var selections = this._cursors.getSelections(); for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; result.push({ inSelectionMode: !selection.isEmpty(), selectionStart: { lineNumber: selection.selectionStartLineNumber, column: selection.selectionStartColumn, }, position: { lineNumber: selection.positionLineNumber, column: selection.positionColumn, } }); } return result; }; Cursor.prototype.restoreState = function (states) { var desiredSelections = []; for (var i = 0, len = states.length; i < len; i++) { var state = states[i]; var positionLineNumber = 1; var positionColumn = 1; // Avoid missing properties on the literal if (state.position && state.position.lineNumber) { positionLineNumber = state.position.lineNumber; } if (state.position && state.position.column) { positionColumn = state.position.column; } var selectionStartLineNumber = positionLineNumber; var selectionStartColumn = positionColumn; // Avoid missing properties on the literal if (state.selectionStart && state.selectionStart.lineNumber) { selectionStartLineNumber = state.selectionStart.lineNumber; } if (state.selectionStart && state.selectionStart.column) { selectionStartColumn = state.selectionStart.column; } desiredSelections.push({ selectionStartLineNumber: selectionStartLineNumber, selectionStartColumn: selectionStartColumn, positionLineNumber: positionLineNumber, positionColumn: positionColumn }); } this.setStates('restoreState', 0 /* NotSet */, cursorCommon_1.CursorState.fromModelSelections(desiredSelections)); this.reveal('restoreState', true, 0 /* Primary */, 1 /* Immediate */); }; Cursor.prototype._onModelContentChanged = function (hadFlushEvent) { this._prevEditOperationType = 0 /* Other */; if (hadFlushEvent) { // a model.setValue() was called this._cursors.dispose(); this._cursors = new cursorCollection_1.CursorCollection(this.context); this._validateAutoClosedActions(); this._emitStateChangedIfNecessary('model', 1 /* ContentFlush */, null); } else { var selectionsFromMarkers = this._cursors.readSelectionFromMarkers(); this.setStates('modelChange', 2 /* RecoverFromMarkers */, cursorCommon_1.CursorState.fromModelSelections(selectionsFromMarkers)); } }; Cursor.prototype.getSelection = function () { return this._cursors.getPrimaryCursor().modelState.selection; }; Cursor.prototype.getColumnSelectData = function () { if (this._columnSelectData) { return this._columnSelectData; } var primaryCursor = this._cursors.getPrimaryCursor(); var primaryPos = primaryCursor.viewState.selectionStart.getStartPosition(); var viewLineNumber = primaryPos.lineNumber; var viewVisualColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(this.context.config, this.context.viewModel, primaryPos); return { isReal: false, fromViewLineNumber: viewLineNumber, fromViewVisualColumn: viewVisualColumn, toViewLineNumber: viewLineNumber, toViewVisualColumn: viewVisualColumn, }; }; Cursor.prototype.getSelections = function () { return this._cursors.getSelections(); }; Cursor.prototype.getViewSelections = function () { return this._cursors.getViewSelections(); }; Cursor.prototype.getPosition = function () { return this._cursors.getPrimaryCursor().modelState.position; }; Cursor.prototype.setSelections = function (source, selections) { this.setStates(source, 0 /* NotSet */, cursorCommon_1.CursorState.fromModelSelections(selections)); }; Cursor.prototype.getPrevEditOperationType = function () { return this._prevEditOperationType; }; Cursor.prototype.setPrevEditOperationType = function (type) { this._prevEditOperationType = type; }; // ------ auxiliary handling logic Cursor.prototype._pushAutoClosedAction = function (autoClosedCharactersRanges, autoClosedEnclosingRanges) { var autoClosedCharactersDeltaDecorations = []; var autoClosedEnclosingDeltaDecorations = []; for (var i = 0, len = autoClosedCharactersRanges.length; i < len; i++) { autoClosedCharactersDeltaDecorations.push({ range: autoClosedCharactersRanges[i], options: { inlineClassName: 'auto-closed-character', stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ } }); autoClosedEnclosingDeltaDecorations.push({ range: autoClosedEnclosingRanges[i], options: { stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ } }); } var autoClosedCharactersDecorations = this._model.deltaDecorations([], autoClosedCharactersDeltaDecorations); var autoClosedEnclosingDecorations = this._model.deltaDecorations([], autoClosedEnclosingDeltaDecorations); this._autoClosedActions.push(new AutoClosedAction(this._model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations)); }; Cursor.prototype._executeEditOperation = function (opResult) { if (!opResult) { // Nothing to execute return; } if (opResult.shouldPushStackElementBefore) { this._model.pushStackElement(); } var result = CommandExecutor.executeCommands(this._model, this._cursors.getSelections(), opResult.commands); if (result) { // The commands were applied correctly this._interpretCommandResult(result); // Check for auto-closing closed characters var autoClosedCharactersRanges = []; var autoClosedEnclosingRanges = []; for (var i = 0; i < opResult.commands.length; i++) { var command = opResult.commands[i]; if (command instanceof cursorTypeOperations_1.TypeWithAutoClosingCommand && command.enclosingRange && command.closeCharacterRange) { autoClosedCharactersRanges.push(command.closeCharacterRange); autoClosedEnclosingRanges.push(command.enclosingRange); } } if (autoClosedCharactersRanges.length > 0) { this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges); } this._prevEditOperationType = opResult.type; } if (opResult.shouldPushStackElementAfter) { this._model.pushStackElement(); } }; Cursor.prototype._interpretCommandResult = function (cursorState) { if (!cursorState || cursorState.length === 0) { cursorState = this._cursors.readSelectionFromMarkers(); } this._columnSelectData = null; this._cursors.setSelections(cursorState); this._cursors.normalize(); }; // ----------------------------------------------------------------------------------------------------------- // ----- emitting events Cursor.prototype._emitStateChangedIfNecessary = function (source, reason, oldState) { var newState = new CursorModelState(this._model, this); if (newState.equals(oldState)) { return false; } var selections = this._cursors.getSelections(); var viewSelections = this._cursors.getViewSelections(); // Let the view get the event first. try { var eventsCollector = this._beginEmit(); eventsCollector.emit(new viewEvents.ViewCursorStateChangedEvent(viewSelections, selections)); } finally { this._endEmit(); } // Only after the view has been notified, let the rest of the world know... if (!oldState || oldState.cursorState.length !== newState.cursorState.length || newState.cursorState.some(function (newCursorState, i) { return !newCursorState.modelState.equals(oldState.cursorState[i].modelState); })) { var oldSelections = oldState ? oldState.cursorState.map(function (s) { return s.modelState.selection; }) : null; var oldModelVersionId = oldState ? oldState.modelVersionId : 0; this._onDidChange.fire(new CursorStateChangedEvent(selections, newState.modelVersionId, oldSelections, oldModelVersionId, source || 'keyboard', reason)); } return true; }; Cursor.prototype._revealRange = function (source, revealTarget, verticalType, revealHorizontal, scrollType) { var viewPositions = this._cursors.getViewPositions(); var viewPosition = viewPositions[0]; if (revealTarget === 1 /* TopMost */) { for (var i = 1; i < viewPositions.length; i++) { if (viewPositions[i].isBefore(viewPosition)) { viewPosition = viewPositions[i]; } } } else if (revealTarget === 2 /* BottomMost */) { for (var i = 1; i < viewPositions.length; i++) { if (viewPosition.isBeforeOrEqual(viewPositions[i])) { viewPosition = viewPositions[i]; } } } else { if (viewPositions.length > 1) { // no revealing! return; } } var viewRange = new range_1.Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column); this.emitCursorRevealRange(source, viewRange, verticalType, revealHorizontal, scrollType); }; Cursor.prototype.emitCursorRevealRange = function (source, viewRange, verticalType, revealHorizontal, scrollType) { try { var eventsCollector = this._beginEmit(); eventsCollector.emit(new viewEvents.ViewRevealRangeRequestEvent(source, viewRange, verticalType, revealHorizontal, scrollType)); } finally { this._endEmit(); } }; // ----------------------------------------------------------------------------------------------------------- // ----- handlers beyond this point Cursor.prototype._findAutoClosingPairs = function (edits) { if (!edits.length) { return null; } var indices = []; for (var i = 0, len = edits.length; i < len; i++) { var edit = edits[i]; if (!edit.text || edit.text.indexOf('\n') >= 0) { return null; } var m = edit.text.match(/([)\]}>'"`])([^)\]}>'"`]*)$/); if (!m) { return null; } var closeChar = m[1]; var autoClosingPairsCandidates = this.context.config.autoClosingPairsClose2.get(closeChar); if (!autoClosingPairsCandidates || autoClosingPairsCandidates.length !== 1) { return null; } var openChar = autoClosingPairsCandidates[0].open; var closeCharIndex = edit.text.length - m[2].length - 1; var openCharIndex = edit.text.lastIndexOf(openChar, closeCharIndex - 1); if (openCharIndex === -1) { return null; } indices.push([openCharIndex, closeCharIndex]); } return indices; }; Cursor.prototype.executeEdits = function (source, edits, cursorStateComputer) { var _this = this; var autoClosingIndices = null; if (source === 'snippet') { autoClosingIndices = this._findAutoClosingPairs(edits); } if (autoClosingIndices) { edits[0]._isTracked = true; } var autoClosedCharactersRanges = []; var autoClosedEnclosingRanges = []; var selections = this._model.pushEditOperations(this.getSelections(), edits, function (undoEdits) { if (autoClosingIndices) { for (var i = 0, len = autoClosingIndices.length; i < len; i++) { var _a = autoClosingIndices[i], openCharInnerIndex = _a[0], closeCharInnerIndex = _a[1]; var undoEdit = undoEdits[i]; var lineNumber = undoEdit.range.startLineNumber; var openCharIndex = undoEdit.range.startColumn - 1 + openCharInnerIndex; var closeCharIndex = undoEdit.range.startColumn - 1 + closeCharInnerIndex; autoClosedCharactersRanges.push(new range_1.Range(lineNumber, closeCharIndex + 1, lineNumber, closeCharIndex + 2)); autoClosedEnclosingRanges.push(new range_1.Range(lineNumber, openCharIndex + 1, lineNumber, closeCharIndex + 2)); } } var selections = cursorStateComputer(undoEdits); if (selections) { // Don't recover the selection from markers because // we know what it should be. _this._isHandling = true; } return selections; }); if (selections) { this._isHandling = false; this.setSelections(source, selections); } if (autoClosedCharactersRanges.length > 0) { this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges); } }; Cursor.prototype.trigger = function (source, handlerId, payload) { var H = editorCommon.Handler; if (handlerId === H.CompositionStart) { this._isDoingComposition = true; this._selectionsWhenCompositionStarted = this.getSelections().slice(0); return; } if (handlerId === H.CompositionEnd) { this._isDoingComposition = false; } if (this._configuration.options.get(68 /* readOnly */)) { // All the remaining handlers will try to edit the model, // but we cannot edit when read only... this._onDidAttemptReadOnlyEdit.fire(undefined); return; } var oldState = new CursorModelState(this._model, this); var cursorChangeReason = 0 /* NotSet */; if (handlerId !== H.Undo && handlerId !== H.Redo) { // TODO@Alex: if the undo/redo stack contains non-null selections // it would also be OK to stop tracking selections here this._cursors.stopTrackingSelections(); } // ensure valid state on all cursors this._cursors.ensureValidState(); this._isHandling = true; try { switch (handlerId) { case H.Type: this._type(source, payload.text); break; case H.ReplacePreviousChar: this._replacePreviousChar(payload.text, payload.replaceCharCnt); break; case H.Paste: cursorChangeReason = 4 /* Paste */; this._paste(payload.text, payload.pasteOnNewLine, payload.multicursorText || []); break; case H.Cut: this._cut(); break; case H.Undo: cursorChangeReason = 5 /* Undo */; this._interpretCommandResult(this._model.undo()); break; case H.Redo: cursorChangeReason = 6 /* Redo */; this._interpretCommandResult(this._model.redo()); break; case H.ExecuteCommand: this._externalExecuteCommand(payload); break; case H.ExecuteCommands: this._externalExecuteCommands(payload); break; case H.CompositionEnd: this._interpretCompositionEnd(source); break; } } catch (err) { errors_1.onUnexpectedError(err); } this._isHandling = false; if (handlerId !== H.Undo && handlerId !== H.Redo) { this._cursors.startTrackingSelections(); } this._validateAutoClosedActions(); if (this._emitStateChangedIfNecessary(source, cursorChangeReason, oldState)) { this._revealRange(source, 0 /* Primary */, 0 /* Simple */, true, 0 /* Smooth */); } }; Cursor.prototype._interpretCompositionEnd = function (source) { if (!this._isDoingComposition && source === 'keyboard') { // composition finishes, let's check if we need to auto complete if necessary. var autoClosedCharacters = AutoClosedAction.getAllAutoClosedCharacters(this._autoClosedActions); this._executeEditOperation(cursorTypeOperations_1.TypeOperations.compositionEndWithInterceptors(this._prevEditOperationType, this.context.config, this.context.model, this._selectionsWhenCompositionStarted, this.getSelections(), autoClosedCharacters)); this._selectionsWhenCompositionStarted = null; } }; Cursor.prototype._type = function (source, text) { if (!this._isDoingComposition && source === 'keyboard') { // If this event is coming straight from the keyboard, look for electric characters and enter var len = text.length; var offset = 0; while (offset < len) { var charLength = strings.nextCharLength(text, offset); var chr = text.substr(offset, charLength); // Here we must interpret each typed character individually var autoClosedCharacters = AutoClosedAction.getAllAutoClosedCharacters(this._autoClosedActions); this._executeEditOperation(cursorTypeOperations_1.TypeOperations.typeWithInterceptors(this._prevEditOperationType, this.context.config, this.context.model, this.getSelections(), autoClosedCharacters, chr)); offset += charLength; } } else { this._executeEditOperation(cursorTypeOperations_1.TypeOperations.typeWithoutInterceptors(this._prevEditOperationType, this.context.config, this.context.model, this.getSelections(), text)); } }; Cursor.prototype._replacePreviousChar = function (text, replaceCharCnt) { this._executeEditOperation(cursorTypeOperations_1.TypeOperations.replacePreviousChar(this._prevEditOperationType, this.context.config, this.context.model, this.getSelections(), text, replaceCharCnt)); }; Cursor.prototype._paste = function (text, pasteOnNewLine, multicursorText) { this._executeEditOperation(cursorTypeOperations_1.TypeOperations.paste(this.context.config, this.context.model, this.getSelections(), text, pasteOnNewLine, multicursorText)); }; Cursor.prototype._cut = function () { this._executeEditOperation(cursorDeleteOperations_1.DeleteOperations.cut(this.context.config, this.context.model, this.getSelections())); }; Cursor.prototype._externalExecuteCommand = function (command) { this._cursors.killSecondaryCursors(); this._executeEditOperation(new cursorCommon_1.EditOperationResult(0 /* Other */, [command], { shouldPushStackElementBefore: false, shouldPushStackElementAfter: false })); }; Cursor.prototype._externalExecuteCommands = function (commands) { this._executeEditOperation(new cursorCommon_1.EditOperationResult(0 /* Other */, commands, { shouldPushStackElementBefore: false, shouldPushStackElementAfter: false })); }; Cursor.MAX_CURSOR_COUNT = 10000; return Cursor; }(viewEvents.ViewEventEmitter)); exports.Cursor = Cursor; var CommandExecutor = /** @class */ (function () { function CommandExecutor() { } CommandExecutor.executeCommands = function (model, selectionsBefore, commands) { var ctx = { model: model, selectionsBefore: selectionsBefore, trackedRanges: [], trackedRangesDirection: [] }; var result = this._innerExecuteCommands(ctx, commands); for (var i = 0, len = ctx.trackedRanges.length; i < len; i++) { ctx.model._setTrackedRange(ctx.trackedRanges[i], null, 0 /* AlwaysGrowsWhenTypingAtEdges */); } return result; }; CommandExecutor._innerExecuteCommands = function (ctx, commands) { if (this._arrayIsEmpty(commands)) { return null; } var commandsData = this._getEditOperations(ctx, commands); if (commandsData.operations.length === 0) { return null; } var rawOperations = commandsData.operations; var loserCursorsMap = this._getLoserCursorMap(rawOperations); if (loserCursorsMap.hasOwnProperty('0')) { // These commands are very messed up console.warn('Ignoring commands'); return null; } // Remove operations belonging to losing cursors var filteredOperations = []; for (var i = 0, len = rawOperations.length; i < len; i++) { if (!loserCursorsMap.hasOwnProperty(rawOperations[i].identifier.major.toString())) { filteredOperations.push(rawOperations[i]); } } // TODO@Alex: find a better way to do this. // give the hint that edit operations are tracked to the model if (commandsData.hadTrackedEditOperation && filteredOperations.length > 0) { filteredOperations[0]._isTracked = true; } var selectionsAfter = ctx.model.pushEditOperations(ctx.selectionsBefore, filteredOperations, function (inverseEditOperations) { var groupedInverseEditOperations = []; for (var i = 0; i < ctx.selectionsBefore.length; i++) { groupedInverseEditOperations[i] = []; } for (var _i = 0, inverseEditOperations_1 = inverseEditOperations; _i < inverseEditOperations_1.length; _i++) { var op = inverseEditOperations_1[_i]; if (!op.identifier) { // perhaps auto whitespace trim edits continue; } groupedInverseEditOperations[op.identifier.major].push(op); } var minorBasedSorter = function (a, b) { return a.identifier.minor - b.identifier.minor; }; var cursorSelections = []; var _loop_1 = function (i) { if (groupedInverseEditOperations[i].length > 0) { groupedInverseEditOperations[i].sort(minorBasedSorter); cursorSelections[i] = commands[i].computeCursorState(ctx.model, { getInverseEditOperations: function () { return groupedInverseEditOperations[i]; }, getTrackedSelection: function (id) { var idx = parseInt(id, 10); var range = ctx.model._getTrackedRange(ctx.trackedRanges[idx]); if (ctx.trackedRangesDirection[idx] === 0 /* LTR */) { return new selection_1.Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn); } return new selection_1.Selection(range.endLineNumber, range.endColumn, range.startLineNumber, range.startColumn); } }); } else { cursorSelections[i] = ctx.selectionsBefore[i]; } }; for (var i = 0; i < ctx.selectionsBefore.length; i++) { _loop_1(i); } return cursorSelections; }); if (!selectionsAfter) { selectionsAfter = ctx.selectionsBefore; } // Extract losing cursors var losingCursors = []; for (var losingCursorIndex in loserCursorsMap) { if (loserCursorsMap.hasOwnProperty(losingCursorIndex)) { losingCursors.push(parseInt(losingCursorIndex, 10)); } } // Sort losing cursors descending losingCursors.sort(function (a, b) { return b - a; }); // Remove losing cursors for (var _i = 0, losingCursors_1 = losingCursors; _i < losingCursors_1.length; _i++) { var losingCursor = losingCursors_1[_i]; selectionsAfter.splice(losingCursor, 1); } return selectionsAfter; }; CommandExecutor._arrayIsEmpty = function (commands) { for (var i = 0, len = commands.length; i < len; i++) { if (commands[i]) { return false; } } return true; }; CommandExecutor._getEditOperations = function (ctx, commands) { var operations = []; var hadTrackedEditOperation = false; for (var i = 0, len = commands.length; i < len; i++) { var command = commands[i]; if (command) { var r = this._getEditOperationsFromCommand(ctx, i, command); operations = operations.concat(r.operations); hadTrackedEditOperation = hadTrackedEditOperation || r.hadTrackedEditOperation; } } return { operations: operations, hadTrackedEditOperation: hadTrackedEditOperation }; }; CommandExecutor._getEditOperationsFromCommand = function (ctx, majorIdentifier, command) { // This method acts as a transaction, if the command fails // everything it has done is ignored var operations = []; var operationMinor = 0; var addEditOperation = function (selection, text, forceMoveMarkers) { if (forceMoveMarkers === void 0) { forceMoveMarkers = false; } if (selection.isEmpty() && text === '') { // This command wants to add a no-op => no thank you return; } operations.push({ identifier: { major: majorIdentifier, minor: operationMinor++ }, range: selection, text: text, forceMoveMarkers: forceMoveMarkers, isAutoWhitespaceEdit: command.insertsAutoWhitespace }); }; var hadTrackedEditOperation = false; var addTrackedEditOperation = function (selection, text, forceMoveMarkers) { hadTrackedEditOperation = true; addEditOperation(selection, text, forceMoveMarkers); }; var trackSelection = function (selection, trackPreviousOnEmpty) { var stickiness; if (selection.isEmpty()) { if (typeof trackPreviousOnEmpty === 'boolean') { if (trackPreviousOnEmpty) { stickiness = 2 /* GrowsOnlyWhenTypingBefore */; } else { stickiness = 3 /* GrowsOnlyWhenTypingAfter */; } } else { // Try to lock it with surrounding text var maxLineColumn = ctx.model.getLineMaxColumn(selection.startLineNumber); if (selection.startColumn === maxLineColumn) { stickiness = 2 /* GrowsOnlyWhenTypingBefore */; } else { stickiness = 3 /* GrowsOnlyWhenTypingAfter */; } } } else { stickiness = 1 /* NeverGrowsWhenTypingAtEdges */; } var l = ctx.trackedRanges.length; var id = ctx.model._setTrackedRange(null, selection, stickiness); ctx.trackedRanges[l] = id; ctx.trackedRangesDirection[l] = selection.getDirection(); return l.toString(); }; var editOperationBuilder = { addEditOperation: addEditOperation, addTrackedEditOperation: addTrackedEditOperation, trackSelection: trackSelection }; try { command.getEditOperations(ctx.model, editOperationBuilder); } catch (e) { // TODO@Alex use notification service if this should be user facing // e.friendlyMessage = nls.localize('corrupt.commands', "Unexpected exception while executing command."); errors_1.onUnexpectedError(e); return { operations: [], hadTrackedEditOperation: false }; } return { operations: operations, hadTrackedEditOperation: hadTrackedEditOperation }; }; CommandExecutor._getLoserCursorMap = function (operations) { // This is destructive on the array operations = operations.slice(0); // Sort operations with last one first operations.sort(function (a, b) { // Note the minus! return -(range_1.Range.compareRangesUsingEnds(a.range, b.range)); }); // Operations can not overlap! var loserCursorsMap = {}; for (var i = 1; i < operations.length; i++) { var previousOp = operations[i - 1]; var currentOp = operations[i]; if (previousOp.range.getStartPosition().isBefore(currentOp.range.getEndPosition())) { var loserMajor = void 0; if (previousOp.identifier.major > currentOp.identifier.major) { // previousOp loses the battle loserMajor = previousOp.identifier.major; } else { loserMajor = currentOp.identifier.major; } loserCursorsMap[loserMajor.toString()] = true; for (var j = 0; j < operations.length; j++) { if (operations[j].identifier.major === loserMajor) { operations.splice(j, 1); if (j < i) { i--; } j--; } } if (i > 0) { i--; } } } return loserCursorsMap; }; return CommandExecutor; }()); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[214/*vs/editor/common/modes/textToHtmlTokenizer*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,93/*vs/editor/common/core/lineTokens*/,63/*vs/editor/common/modes/nullMode*/]), function (require, exports, strings, lineTokens_1, nullMode_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var fallback = { getInitialState: function () { return nullMode_1.NULL_STATE; }, tokenize2: function (buffer, state, deltaOffset) { return nullMode_1.nullTokenize2(0 /* Null */, buffer, state, deltaOffset); } }; function tokenizeToString(text, tokenizationSupport) { if (tokenizationSupport === void 0) { tokenizationSupport = fallback; } return _tokenizeToString(text, tokenizationSupport || fallback); } exports.tokenizeToString = tokenizeToString; function tokenizeLineToHTML(text, viewLineTokens, colorMap, startOffset, endOffset, tabSize, useNbsp) { var result = "
    "; var charIndex = startOffset; var tabsCharDelta = 0; for (var tokenIndex = 0, tokenCount = viewLineTokens.getCount(); tokenIndex < tokenCount; tokenIndex++) { var tokenEndIndex = viewLineTokens.getEndOffset(tokenIndex); if (tokenEndIndex <= startOffset) { continue; } var partContent = ''; for (; charIndex < tokenEndIndex && charIndex < endOffset; charIndex++) { var charCode = text.charCodeAt(charIndex); switch (charCode) { case 9 /* Tab */: var insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize; tabsCharDelta += insertSpacesCount - 1; while (insertSpacesCount > 0) { partContent += useNbsp ? ' ' : ' '; insertSpacesCount--; } break; case 60 /* LessThan */: partContent += '<'; break; case 62 /* GreaterThan */: partContent += '>'; break; case 38 /* Ampersand */: partContent += '&'; break; case 0 /* Null */: partContent += '�'; break; case 65279 /* UTF8_BOM */: case 8232 /* LINE_SEPARATOR_2028 */: partContent += '\ufffd'; break; case 13 /* CarriageReturn */: // zero width space, because carriage return would introduce a line break partContent += '​'; break; case 32 /* Space */: partContent += useNbsp ? ' ' : ' '; break; default: partContent += String.fromCharCode(charCode); } } result += "" + partContent + ""; if (tokenEndIndex > endOffset || charIndex >= endOffset) { break; } } result += "
    "; return result; } exports.tokenizeLineToHTML = tokenizeLineToHTML; function _tokenizeToString(text, tokenizationSupport) { var result = "
    "; var lines = text.split(/\r\n|\r|\n/); var currentState = tokenizationSupport.getInitialState(); for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (i > 0) { result += "
    "; } var tokenizationResult = tokenizationSupport.tokenize2(line, currentState, 0); lineTokens_1.LineTokens.convertToEndOffset(tokenizationResult.tokens, line.length); var lineTokens = new lineTokens_1.LineTokens(tokenizationResult.tokens, line); var viewLineTokens = lineTokens.inflate(); var startOffset = 0; for (var j = 0, lenJ = viewLineTokens.getCount(); j < lenJ; j++) { var type = viewLineTokens.getClassName(j); var endIndex = viewLineTokens.getEndOffset(j); result += "" + strings.escape(line.substring(startOffset, endIndex)) + ""; startOffset = endIndex; } currentState = tokenizationResult.endState; } result += "
    "; return result; } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[84/*vs/editor/common/services/resolverService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ITextModelService = instantiation_1.createDecorator('textModelService'); }); define(__m[114/*vs/editor/common/services/textResourceConfigurationService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ITextResourceConfigurationService = instantiation_1.createDecorator('textResourceConfigurationService'); exports.ITextResourcePropertiesService = 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[215/*vs/editor/common/viewModel/minimapTokensColorTracker*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,339/*vs/editor/common/core/rgba*/,17/*vs/editor/common/modes*/]), function (require, exports, event_1, rgba_1, modes_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MinimapTokensColorTracker = /** @class */ (function () { function MinimapTokensColorTracker() { var _this = this; this._onDidChange = new event_1.Emitter(); this.onDidChange = this._onDidChange.event; this._updateColorMap(); modes_1.TokenizationRegistry.onDidChange(function (e) { if (e.changedColorMap) { _this._updateColorMap(); } }); } MinimapTokensColorTracker.getInstance = function () { if (!this._INSTANCE) { this._INSTANCE = new MinimapTokensColorTracker(); } return this._INSTANCE; }; MinimapTokensColorTracker.prototype._updateColorMap = function () { var colorMap = modes_1.TokenizationRegistry.getColorMap(); if (!colorMap) { this._colors = [rgba_1.RGBA8.Empty]; this._backgroundIsLight = true; return; } this._colors = [rgba_1.RGBA8.Empty]; for (var colorId = 1; colorId < colorMap.length; colorId++) { var 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)); } var backgroundLuminosity = colorMap[2 /* DefaultBackground */].getRelativeLuminance(); this._backgroundIsLight = backgroundLuminosity >= 0.5; this._onDidChange.fire(undefined); }; MinimapTokensColorTracker.prototype.getColor = function (colorId) { if (colorId < 1 || colorId >= this._colors.length) { // background color (basically invisible) colorId = 2 /* DefaultBackground */; } return this._colors[colorId]; }; MinimapTokensColorTracker.prototype.backgroundIsLight = function () { return this._backgroundIsLight; }; MinimapTokensColorTracker._INSTANCE = null; return MinimapTokensColorTracker; }()); exports.MinimapTokensColorTracker = MinimapTokensColorTracker; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[161/*vs/editor/common/viewModel/splitLinesCollection*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,30/*vs/editor/common/model/textModel*/,81/*vs/editor/common/view/viewEvents*/,194/*vs/editor/common/viewModel/prefixSumComputer*/,69/*vs/editor/common/viewModel/viewModel*/]), function (require, exports, arrays, position_1, range_1, textModel_1, viewEvents, prefixSumComputer_1, viewModel_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var OutputPosition = /** @class */ (function () { function OutputPosition(outputLineIndex, outputOffset) { this.outputLineIndex = outputLineIndex; this.outputOffset = outputOffset; } return OutputPosition; }()); exports.OutputPosition = OutputPosition; var LineBreakData = /** @class */ (function () { function LineBreakData(breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength) { this.breakOffsets = breakOffsets; this.breakOffsetsVisibleColumn = breakOffsetsVisibleColumn; this.wrappedTextIndentLength = wrappedTextIndentLength; } LineBreakData.getInputOffsetOfOutputPosition = function (breakOffsets, outputLineIndex, outputOffset) { if (outputLineIndex === 0) { return outputOffset; } else { return breakOffsets[outputLineIndex - 1] + outputOffset; } }; LineBreakData.getOutputPositionOfInputOffset = function (breakOffsets, inputOffset) { var low = 0; var high = breakOffsets.length - 1; var mid = 0; var midStart = 0; while (low <= high) { mid = low + ((high - low) / 2) | 0; var midStop = breakOffsets[mid]; midStart = mid > 0 ? breakOffsets[mid - 1] : 0; if (inputOffset < midStart) { high = mid - 1; } else if (inputOffset >= midStop) { low = mid + 1; } else { break; } } return new OutputPosition(mid, inputOffset - midStart); }; return LineBreakData; }()); exports.LineBreakData = LineBreakData; var CoordinatesConverter = /** @class */ (function () { function CoordinatesConverter(lines) { this._lines = lines; } // View -> Model conversion and related methods CoordinatesConverter.prototype.convertViewPositionToModelPosition = function (viewPosition) { return this._lines.convertViewPositionToModelPosition(viewPosition.lineNumber, viewPosition.column); }; CoordinatesConverter.prototype.convertViewRangeToModelRange = function (viewRange) { return this._lines.convertViewRangeToModelRange(viewRange); }; CoordinatesConverter.prototype.validateViewPosition = function (viewPosition, expectedModelPosition) { return this._lines.validateViewPosition(viewPosition.lineNumber, viewPosition.column, expectedModelPosition); }; CoordinatesConverter.prototype.validateViewRange = function (viewRange, expectedModelRange) { return this._lines.validateViewRange(viewRange, expectedModelRange); }; // Model -> View conversion and related methods CoordinatesConverter.prototype.convertModelPositionToViewPosition = function (modelPosition) { return this._lines.convertModelPositionToViewPosition(modelPosition.lineNumber, modelPosition.column); }; CoordinatesConverter.prototype.convertModelRangeToViewRange = function (modelRange) { return this._lines.convertModelRangeToViewRange(modelRange); }; CoordinatesConverter.prototype.modelPositionIsVisible = function (modelPosition) { return this._lines.modelPositionIsVisible(modelPosition.lineNumber, modelPosition.column); }; return CoordinatesConverter; }()); exports.CoordinatesConverter = CoordinatesConverter; var LineNumberMapper = /** @class */ (function () { function LineNumberMapper(viewLineCounts) { this._counts = viewLineCounts; this._isValid = false; this._validEndIndex = -1; this._modelToView = []; this._viewToModel = []; } LineNumberMapper.prototype._invalidate = function (index) { this._isValid = false; this._validEndIndex = Math.min(this._validEndIndex, index - 1); }; LineNumberMapper.prototype._ensureValid = function () { if (this._isValid) { return; } for (var i = this._validEndIndex + 1, len = this._counts.length; i < len; i++) { var viewLineCount = this._counts[i]; var viewLinesAbove = (i > 0 ? this._modelToView[i - 1] : 0); this._modelToView[i] = viewLinesAbove + viewLineCount; for (var j = 0; j < viewLineCount; j++) { this._viewToModel[viewLinesAbove + j] = i; } } // trim things this._modelToView.length = this._counts.length; this._viewToModel.length = this._modelToView[this._modelToView.length - 1]; // mark as valid this._isValid = true; this._validEndIndex = this._counts.length - 1; }; LineNumberMapper.prototype.changeValue = function (index, value) { if (this._counts[index] === value) { // no change return; } this._counts[index] = value; this._invalidate(index); }; LineNumberMapper.prototype.removeValues = function (start, deleteCount) { this._counts.splice(start, deleteCount); this._invalidate(start); }; LineNumberMapper.prototype.insertValues = function (insertIndex, insertArr) { this._counts = arrays.arrayInsert(this._counts, insertIndex, insertArr); this._invalidate(insertIndex); }; LineNumberMapper.prototype.getTotalValue = function () { this._ensureValid(); return this._viewToModel.length; }; LineNumberMapper.prototype.getAccumulatedValue = function (index) { this._ensureValid(); return this._modelToView[index]; }; LineNumberMapper.prototype.getIndexOf = function (accumulatedValue) { this._ensureValid(); var modelLineIndex = this._viewToModel[accumulatedValue]; var viewLinesAbove = (modelLineIndex > 0 ? this._modelToView[modelLineIndex - 1] : 0); return new prefixSumComputer_1.PrefixSumIndexOfResult(modelLineIndex, accumulatedValue - viewLinesAbove); }; return LineNumberMapper; }()); var SplitLinesCollection = /** @class */ (function () { function SplitLinesCollection(model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, tabSize, wrappingStrategy, wrappingColumn, wrappingIndent) { this.model = model; this._validModelVersionId = -1; this._domLineBreaksComputerFactory = domLineBreaksComputerFactory; this._monospaceLineBreaksComputerFactory = monospaceLineBreaksComputerFactory; this.fontInfo = fontInfo; this.tabSize = tabSize; this.wrappingStrategy = wrappingStrategy; this.wrappingColumn = wrappingColumn; this.wrappingIndent = wrappingIndent; this._constructLines(/*resetHiddenAreas*/ true, null); } SplitLinesCollection.prototype.dispose = function () { this.hiddenAreasIds = this.model.deltaDecorations(this.hiddenAreasIds, []); }; SplitLinesCollection.prototype.createCoordinatesConverter = function () { return new CoordinatesConverter(this); }; SplitLinesCollection.prototype._constructLines = function (resetHiddenAreas, previousLineBreaks) { var _this = this; this.lines = []; if (resetHiddenAreas) { this.hiddenAreasIds = []; } var linesContent = this.model.getLinesContent(); var lineCount = linesContent.length; var lineBreaksComputer = this.createLineBreaksComputer(); for (var i = 0; i < lineCount; i++) { lineBreaksComputer.addRequest(linesContent[i], previousLineBreaks ? previousLineBreaks[i] : null); } var linesBreaks = lineBreaksComputer.finalize(); var values = []; var hiddenAreas = this.hiddenAreasIds.map(function (areaId) { return _this.model.getDecorationRange(areaId); }).sort(range_1.Range.compareRangesUsingStarts); var hiddenAreaStart = 1, hiddenAreaEnd = 0; var hiddenAreaIdx = -1; var nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : lineCount + 2; for (var i = 0; i < lineCount; i++) { var lineNumber = i + 1; if (lineNumber === nextLineNumberToUpdateHiddenArea) { hiddenAreaIdx++; hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber; hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber; nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : lineCount + 2; } var isInHiddenArea = (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd); var line = createSplitLine(linesBreaks[i], !isInHiddenArea); values[i] = line.getViewLineCount(); this.lines[i] = line; } this._validModelVersionId = this.model.getVersionId(); this.prefixSumComputer = new LineNumberMapper(values); }; SplitLinesCollection.prototype.getHiddenAreas = function () { var _this = this; return this.hiddenAreasIds.map(function (decId) { return _this.model.getDecorationRange(decId); }); }; SplitLinesCollection.prototype._reduceRanges = function (_ranges) { var _this = this; if (_ranges.length === 0) { return []; } var ranges = _ranges.map(function (r) { return _this.model.validateRange(r); }).sort(range_1.Range.compareRangesUsingStarts); var result = []; var currentRangeStart = ranges[0].startLineNumber; var currentRangeEnd = ranges[0].endLineNumber; for (var i = 1, len = ranges.length; i < len; i++) { var range = ranges[i]; if (range.startLineNumber > currentRangeEnd + 1) { result.push(new range_1.Range(currentRangeStart, 1, currentRangeEnd, 1)); currentRangeStart = range.startLineNumber; currentRangeEnd = range.endLineNumber; } else if (range.endLineNumber > currentRangeEnd) { currentRangeEnd = range.endLineNumber; } } result.push(new range_1.Range(currentRangeStart, 1, currentRangeEnd, 1)); return result; }; SplitLinesCollection.prototype.setHiddenAreas = function (_ranges) { var _this = this; var newRanges = this._reduceRanges(_ranges); // BEGIN TODO@Martin: Please stop calling this method on each model change! var oldRanges = this.hiddenAreasIds.map(function (areaId) { return _this.model.getDecorationRange(areaId); }).sort(range_1.Range.compareRangesUsingStarts); if (newRanges.length === oldRanges.length) { var hasDifference = false; for (var i = 0; i < newRanges.length; i++) { if (!newRanges[i].equalsRange(oldRanges[i])) { hasDifference = true; break; } } if (!hasDifference) { return false; } } // END TODO@Martin: Please stop calling this method on each model change! var newDecorations = []; for (var _i = 0, newRanges_1 = newRanges; _i < newRanges_1.length; _i++) { var newRange = newRanges_1[_i]; newDecorations.push({ range: newRange, options: textModel_1.ModelDecorationOptions.EMPTY }); } this.hiddenAreasIds = this.model.deltaDecorations(this.hiddenAreasIds, newDecorations); var hiddenAreas = newRanges; var hiddenAreaStart = 1, hiddenAreaEnd = 0; var hiddenAreaIdx = -1; var nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : this.lines.length + 2; var hasVisibleLine = false; for (var i = 0; i < this.lines.length; i++) { var lineNumber = i + 1; if (lineNumber === nextLineNumberToUpdateHiddenArea) { hiddenAreaIdx++; hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber; hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber; nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : this.lines.length + 2; } var lineChanged = false; if (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd) { // Line should be hidden if (this.lines[i].isVisible()) { this.lines[i] = this.lines[i].setVisible(false); lineChanged = true; } } else { hasVisibleLine = true; // Line should be visible if (!this.lines[i].isVisible()) { this.lines[i] = this.lines[i].setVisible(true); lineChanged = true; } } if (lineChanged) { var newOutputLineCount = this.lines[i].getViewLineCount(); this.prefixSumComputer.changeValue(i, newOutputLineCount); } } if (!hasVisibleLine) { // Cannot have everything be hidden => reveal everything! this.setHiddenAreas([]); } return true; }; SplitLinesCollection.prototype.modelPositionIsVisible = function (modelLineNumber, _modelColumn) { if (modelLineNumber < 1 || modelLineNumber > this.lines.length) { // invalid arguments return false; } return this.lines[modelLineNumber - 1].isVisible(); }; SplitLinesCollection.prototype.setTabSize = function (newTabSize) { if (this.tabSize === newTabSize) { return false; } this.tabSize = newTabSize; this._constructLines(/*resetHiddenAreas*/ false, null); return true; }; SplitLinesCollection.prototype.setWrappingSettings = function (fontInfo, wrappingStrategy, wrappingColumn, wrappingIndent) { var equalFontInfo = this.fontInfo.equals(fontInfo); var equalWrappingStrategy = (this.wrappingStrategy === wrappingStrategy); var equalWrappingColumn = (this.wrappingColumn === wrappingColumn); var equalWrappingIndent = (this.wrappingIndent === wrappingIndent); if (equalFontInfo && equalWrappingStrategy && equalWrappingColumn && equalWrappingIndent) { return false; } var onlyWrappingColumnChanged = (equalFontInfo && equalWrappingStrategy && !equalWrappingColumn && equalWrappingIndent); this.fontInfo = fontInfo; this.wrappingStrategy = wrappingStrategy; this.wrappingColumn = wrappingColumn; this.wrappingIndent = wrappingIndent; var previousLineBreaks = null; if (onlyWrappingColumnChanged) { previousLineBreaks = []; for (var i = 0, len = this.lines.length; i < len; i++) { previousLineBreaks[i] = this.lines[i].getLineBreakData(); } } this._constructLines(/*resetHiddenAreas*/ false, previousLineBreaks); return true; }; SplitLinesCollection.prototype.createLineBreaksComputer = function () { var lineBreaksComputerFactory = (this.wrappingStrategy === 'advanced' ? this._domLineBreaksComputerFactory : this._monospaceLineBreaksComputerFactory); return lineBreaksComputerFactory.createLineBreaksComputer(this.fontInfo, this.tabSize, this.wrappingColumn, this.wrappingIndent); }; SplitLinesCollection.prototype.onModelFlushed = function () { this._constructLines(/*resetHiddenAreas*/ true, null); }; SplitLinesCollection.prototype.onModelLinesDeleted = function (versionId, fromLineNumber, toLineNumber) { if (versionId <= this._validModelVersionId) { // Here we check for versionId in case the lines were reconstructed in the meantime. // We don't want to apply stale change events on top of a newer read model state. return null; } var outputFromLineNumber = (fromLineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(fromLineNumber - 2) + 1); var outputToLineNumber = this.prefixSumComputer.getAccumulatedValue(toLineNumber - 1); this.lines.splice(fromLineNumber - 1, toLineNumber - fromLineNumber + 1); this.prefixSumComputer.removeValues(fromLineNumber - 1, toLineNumber - fromLineNumber + 1); return new viewEvents.ViewLinesDeletedEvent(outputFromLineNumber, outputToLineNumber); }; SplitLinesCollection.prototype.onModelLinesInserted = function (versionId, fromLineNumber, _toLineNumber, lineBreaks) { if (versionId <= this._validModelVersionId) { // Here we check for versionId in case the lines were reconstructed in the meantime. // We don't want to apply stale change events on top of a newer read model state. return null; } var hiddenAreas = this.getHiddenAreas(); var isInHiddenArea = false; var testPosition = new position_1.Position(fromLineNumber, 1); for (var _i = 0, hiddenAreas_1 = hiddenAreas; _i < hiddenAreas_1.length; _i++) { var hiddenArea = hiddenAreas_1[_i]; if (hiddenArea.containsPosition(testPosition)) { isInHiddenArea = true; break; } } var outputFromLineNumber = (fromLineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(fromLineNumber - 2) + 1); var totalOutputLineCount = 0; var insertLines = []; var insertPrefixSumValues = []; for (var i = 0, len = lineBreaks.length; i < len; i++) { var line = createSplitLine(lineBreaks[i], !isInHiddenArea); insertLines.push(line); var outputLineCount = line.getViewLineCount(); totalOutputLineCount += outputLineCount; insertPrefixSumValues[i] = outputLineCount; } // TODO@Alex: use arrays.arrayInsert this.lines = this.lines.slice(0, fromLineNumber - 1).concat(insertLines).concat(this.lines.slice(fromLineNumber - 1)); this.prefixSumComputer.insertValues(fromLineNumber - 1, insertPrefixSumValues); return new viewEvents.ViewLinesInsertedEvent(outputFromLineNumber, outputFromLineNumber + totalOutputLineCount - 1); }; SplitLinesCollection.prototype.onModelLineChanged = function (versionId, lineNumber, lineBreakData) { if (versionId <= this._validModelVersionId) { // Here we check for versionId in case the lines were reconstructed in the meantime. // We don't want to apply stale change events on top of a newer read model state. return [false, null, null, null]; } var lineIndex = lineNumber - 1; var oldOutputLineCount = this.lines[lineIndex].getViewLineCount(); var isVisible = this.lines[lineIndex].isVisible(); var line = createSplitLine(lineBreakData, isVisible); this.lines[lineIndex] = line; var newOutputLineCount = this.lines[lineIndex].getViewLineCount(); var lineMappingChanged = false; var changeFrom = 0; var changeTo = -1; var insertFrom = 0; var insertTo = -1; var deleteFrom = 0; var deleteTo = -1; if (oldOutputLineCount > newOutputLineCount) { changeFrom = (lineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(lineNumber - 2) + 1); changeTo = changeFrom + newOutputLineCount - 1; deleteFrom = changeTo + 1; deleteTo = deleteFrom + (oldOutputLineCount - newOutputLineCount) - 1; lineMappingChanged = true; } else if (oldOutputLineCount < newOutputLineCount) { changeFrom = (lineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(lineNumber - 2) + 1); changeTo = changeFrom + oldOutputLineCount - 1; insertFrom = changeTo + 1; insertTo = insertFrom + (newOutputLineCount - oldOutputLineCount) - 1; lineMappingChanged = true; } else { changeFrom = (lineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(lineNumber - 2) + 1); changeTo = changeFrom + newOutputLineCount - 1; } this.prefixSumComputer.changeValue(lineIndex, newOutputLineCount); var viewLinesChangedEvent = (changeFrom <= changeTo ? new viewEvents.ViewLinesChangedEvent(changeFrom, changeTo) : null); var viewLinesInsertedEvent = (insertFrom <= insertTo ? new viewEvents.ViewLinesInsertedEvent(insertFrom, insertTo) : null); var viewLinesDeletedEvent = (deleteFrom <= deleteTo ? new viewEvents.ViewLinesDeletedEvent(deleteFrom, deleteTo) : null); return [lineMappingChanged, viewLinesChangedEvent, viewLinesInsertedEvent, viewLinesDeletedEvent]; }; SplitLinesCollection.prototype.acceptVersionId = function (versionId) { this._validModelVersionId = versionId; if (this.lines.length === 1 && !this.lines[0].isVisible()) { // At least one line must be visible => reset hidden areas this.setHiddenAreas([]); } }; SplitLinesCollection.prototype.getViewLineCount = function () { return this.prefixSumComputer.getTotalValue(); }; SplitLinesCollection.prototype._toValidViewLineNumber = function (viewLineNumber) { if (viewLineNumber < 1) { return 1; } var viewLineCount = this.getViewLineCount(); if (viewLineNumber > viewLineCount) { return viewLineCount; } return viewLineNumber | 0; }; SplitLinesCollection.prototype.getActiveIndentGuide = function (viewLineNumber, minLineNumber, maxLineNumber) { viewLineNumber = this._toValidViewLineNumber(viewLineNumber); minLineNumber = this._toValidViewLineNumber(minLineNumber); maxLineNumber = this._toValidViewLineNumber(maxLineNumber); var modelPosition = this.convertViewPositionToModelPosition(viewLineNumber, this.getViewLineMinColumn(viewLineNumber)); var modelMinPosition = this.convertViewPositionToModelPosition(minLineNumber, this.getViewLineMinColumn(minLineNumber)); var modelMaxPosition = this.convertViewPositionToModelPosition(maxLineNumber, this.getViewLineMinColumn(maxLineNumber)); var result = this.model.getActiveIndentGuide(modelPosition.lineNumber, modelMinPosition.lineNumber, modelMaxPosition.lineNumber); var viewStartPosition = this.convertModelPositionToViewPosition(result.startLineNumber, 1); var viewEndPosition = this.convertModelPositionToViewPosition(result.endLineNumber, this.model.getLineMaxColumn(result.endLineNumber)); return { startLineNumber: viewStartPosition.lineNumber, endLineNumber: viewEndPosition.lineNumber, indent: result.indent }; }; SplitLinesCollection.prototype.getViewLinesIndentGuides = function (viewStartLineNumber, viewEndLineNumber) { viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber); viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber); var modelStart = this.convertViewPositionToModelPosition(viewStartLineNumber, this.getViewLineMinColumn(viewStartLineNumber)); var modelEnd = this.convertViewPositionToModelPosition(viewEndLineNumber, this.getViewLineMaxColumn(viewEndLineNumber)); var result = []; var resultRepeatCount = []; var resultRepeatOption = []; var modelStartLineIndex = modelStart.lineNumber - 1; var modelEndLineIndex = modelEnd.lineNumber - 1; var reqStart = null; for (var modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) { var line = this.lines[modelLineIndex]; if (line.isVisible()) { var viewLineStartIndex = line.getViewLineNumberOfModelPosition(0, modelLineIndex === modelStartLineIndex ? modelStart.column : 1); var viewLineEndIndex = line.getViewLineNumberOfModelPosition(0, this.model.getLineMaxColumn(modelLineIndex + 1)); var count = viewLineEndIndex - viewLineStartIndex + 1; var option = 0 /* BlockNone */; if (count > 1 && line.getViewLineMinColumn(this.model, modelLineIndex + 1, viewLineEndIndex) === 1) { // wrapped lines should block indent guides option = (viewLineStartIndex === 0 ? 1 /* BlockSubsequent */ : 2 /* BlockAll */); } resultRepeatCount.push(count); resultRepeatOption.push(option); // merge into previous request if (reqStart === null) { reqStart = new position_1.Position(modelLineIndex + 1, 0); } } else { // hit invisible line => flush request if (reqStart !== null) { result = result.concat(this.model.getLinesIndentGuides(reqStart.lineNumber, modelLineIndex)); reqStart = null; } } } if (reqStart !== null) { result = result.concat(this.model.getLinesIndentGuides(reqStart.lineNumber, modelEnd.lineNumber)); reqStart = null; } var viewLineCount = viewEndLineNumber - viewStartLineNumber + 1; var viewIndents = new Array(viewLineCount); var currIndex = 0; for (var i = 0, len = result.length; i < len; i++) { var value = result[i]; var count = Math.min(viewLineCount - currIndex, resultRepeatCount[i]); var option = resultRepeatOption[i]; var blockAtIndex = void 0; if (option === 2 /* BlockAll */) { blockAtIndex = 0; } else if (option === 1 /* BlockSubsequent */) { blockAtIndex = 1; } else { blockAtIndex = count; } for (var j = 0; j < count; j++) { if (j === blockAtIndex) { value = 0; } viewIndents[currIndex++] = value; } } return viewIndents; }; SplitLinesCollection.prototype.getViewLineContent = function (viewLineNumber) { viewLineNumber = this._toValidViewLineNumber(viewLineNumber); var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); var lineIndex = r.index; var remainder = r.remainder; return this.lines[lineIndex].getViewLineContent(this.model, lineIndex + 1, remainder); }; SplitLinesCollection.prototype.getViewLineLength = function (viewLineNumber) { viewLineNumber = this._toValidViewLineNumber(viewLineNumber); var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); var lineIndex = r.index; var remainder = r.remainder; return this.lines[lineIndex].getViewLineLength(this.model, lineIndex + 1, remainder); }; SplitLinesCollection.prototype.getViewLineMinColumn = function (viewLineNumber) { viewLineNumber = this._toValidViewLineNumber(viewLineNumber); var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); var lineIndex = r.index; var remainder = r.remainder; return this.lines[lineIndex].getViewLineMinColumn(this.model, lineIndex + 1, remainder); }; SplitLinesCollection.prototype.getViewLineMaxColumn = function (viewLineNumber) { viewLineNumber = this._toValidViewLineNumber(viewLineNumber); var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); var lineIndex = r.index; var remainder = r.remainder; return this.lines[lineIndex].getViewLineMaxColumn(this.model, lineIndex + 1, remainder); }; SplitLinesCollection.prototype.getViewLineData = function (viewLineNumber) { viewLineNumber = this._toValidViewLineNumber(viewLineNumber); var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); var lineIndex = r.index; var remainder = r.remainder; return this.lines[lineIndex].getViewLineData(this.model, lineIndex + 1, remainder); }; SplitLinesCollection.prototype.getViewLinesData = function (viewStartLineNumber, viewEndLineNumber, needed) { viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber); viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber); var start = this.prefixSumComputer.getIndexOf(viewStartLineNumber - 1); var viewLineNumber = viewStartLineNumber; var startModelLineIndex = start.index; var startRemainder = start.remainder; var result = []; for (var modelLineIndex = startModelLineIndex, len = this.model.getLineCount(); modelLineIndex < len; modelLineIndex++) { var line = this.lines[modelLineIndex]; if (!line.isVisible()) { continue; } var fromViewLineIndex = (modelLineIndex === startModelLineIndex ? startRemainder : 0); var remainingViewLineCount = line.getViewLineCount() - fromViewLineIndex; var lastLine = false; if (viewLineNumber + remainingViewLineCount > viewEndLineNumber) { lastLine = true; remainingViewLineCount = viewEndLineNumber - viewLineNumber + 1; } var toViewLineIndex = fromViewLineIndex + remainingViewLineCount; line.getViewLinesData(this.model, modelLineIndex + 1, fromViewLineIndex, toViewLineIndex, viewLineNumber - viewStartLineNumber, needed, result); viewLineNumber += remainingViewLineCount; if (lastLine) { break; } } return result; }; SplitLinesCollection.prototype.validateViewPosition = function (viewLineNumber, viewColumn, expectedModelPosition) { viewLineNumber = this._toValidViewLineNumber(viewLineNumber); var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); var lineIndex = r.index; var remainder = r.remainder; var line = this.lines[lineIndex]; var minColumn = line.getViewLineMinColumn(this.model, lineIndex + 1, remainder); var maxColumn = line.getViewLineMaxColumn(this.model, lineIndex + 1, remainder); if (viewColumn < minColumn) { viewColumn = minColumn; } if (viewColumn > maxColumn) { viewColumn = maxColumn; } var computedModelColumn = line.getModelColumnOfViewPosition(remainder, viewColumn); var computedModelPosition = this.model.validatePosition(new position_1.Position(lineIndex + 1, computedModelColumn)); if (computedModelPosition.equals(expectedModelPosition)) { return new position_1.Position(viewLineNumber, viewColumn); } return this.convertModelPositionToViewPosition(expectedModelPosition.lineNumber, expectedModelPosition.column); }; SplitLinesCollection.prototype.validateViewRange = function (viewRange, expectedModelRange) { var validViewStart = this.validateViewPosition(viewRange.startLineNumber, viewRange.startColumn, expectedModelRange.getStartPosition()); var validViewEnd = this.validateViewPosition(viewRange.endLineNumber, viewRange.endColumn, expectedModelRange.getEndPosition()); return new range_1.Range(validViewStart.lineNumber, validViewStart.column, validViewEnd.lineNumber, validViewEnd.column); }; SplitLinesCollection.prototype.convertViewPositionToModelPosition = function (viewLineNumber, viewColumn) { viewLineNumber = this._toValidViewLineNumber(viewLineNumber); var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); var lineIndex = r.index; var remainder = r.remainder; var inputColumn = this.lines[lineIndex].getModelColumnOfViewPosition(remainder, viewColumn); // console.log('out -> in ' + viewLineNumber + ',' + viewColumn + ' ===> ' + (lineIndex+1) + ',' + inputColumn); return this.model.validatePosition(new position_1.Position(lineIndex + 1, inputColumn)); }; SplitLinesCollection.prototype.convertViewRangeToModelRange = function (viewRange) { var start = this.convertViewPositionToModelPosition(viewRange.startLineNumber, viewRange.startColumn); var end = this.convertViewPositionToModelPosition(viewRange.endLineNumber, viewRange.endColumn); return new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column); }; SplitLinesCollection.prototype.convertModelPositionToViewPosition = function (_modelLineNumber, _modelColumn) { var validPosition = this.model.validatePosition(new position_1.Position(_modelLineNumber, _modelColumn)); var inputLineNumber = validPosition.lineNumber; var inputColumn = validPosition.column; var lineIndex = inputLineNumber - 1, lineIndexChanged = false; while (lineIndex > 0 && !this.lines[lineIndex].isVisible()) { lineIndex--; lineIndexChanged = true; } if (lineIndex === 0 && !this.lines[lineIndex].isVisible()) { // Could not reach a real line // console.log('in -> out ' + inputLineNumber + ',' + inputColumn + ' ===> ' + 1 + ',' + 1); return new position_1.Position(1, 1); } var deltaLineNumber = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1)); var r; if (lineIndexChanged) { r = this.lines[lineIndex].getViewPositionOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1)); } else { r = this.lines[inputLineNumber - 1].getViewPositionOfModelPosition(deltaLineNumber, inputColumn); } // console.log('in -> out ' + inputLineNumber + ',' + inputColumn + ' ===> ' + r.lineNumber + ',' + r); return r; }; SplitLinesCollection.prototype.convertModelRangeToViewRange = function (modelRange) { var start = this.convertModelPositionToViewPosition(modelRange.startLineNumber, modelRange.startColumn); var end = this.convertModelPositionToViewPosition(modelRange.endLineNumber, modelRange.endColumn); if (modelRange.startLineNumber === modelRange.endLineNumber && start.lineNumber !== end.lineNumber) { // This is a single line range that ends up taking more lines due to wrapping if (end.column === this.getViewLineMinColumn(end.lineNumber)) { // the end column lands on the first column of the next line return new range_1.Range(start.lineNumber, start.column, end.lineNumber - 1, this.getViewLineMaxColumn(end.lineNumber - 1)); } } return new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column); }; SplitLinesCollection.prototype._getViewLineNumberForModelPosition = function (inputLineNumber, inputColumn) { var lineIndex = inputLineNumber - 1; if (this.lines[lineIndex].isVisible()) { // this model line is visible var deltaLineNumber_1 = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1)); return this.lines[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber_1, inputColumn); } // this model line is not visible while (lineIndex > 0 && !this.lines[lineIndex].isVisible()) { lineIndex--; } if (lineIndex === 0 && !this.lines[lineIndex].isVisible()) { // Could not reach a real line return 1; } var deltaLineNumber = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1)); return this.lines[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1)); }; SplitLinesCollection.prototype.getAllOverviewRulerDecorations = function (ownerId, filterOutValidation, theme) { var decorations = this.model.getOverviewRulerDecorations(ownerId, filterOutValidation); var result = new OverviewRulerDecorations(); for (var _i = 0, decorations_1 = decorations; _i < decorations_1.length; _i++) { var decoration = decorations_1[_i]; var opts = decoration.options.overviewRuler; var lane = opts ? opts.position : 0; if (lane === 0) { continue; } var color = opts.getColor(theme); var viewStartLineNumber = this._getViewLineNumberForModelPosition(decoration.range.startLineNumber, decoration.range.startColumn); var viewEndLineNumber = this._getViewLineNumberForModelPosition(decoration.range.endLineNumber, decoration.range.endColumn); result.accept(color, viewStartLineNumber, viewEndLineNumber, lane); } return result.result; }; SplitLinesCollection.prototype.getDecorationsInRange = function (range, ownerId, filterOutValidation) { var modelStart = this.convertViewPositionToModelPosition(range.startLineNumber, range.startColumn); var modelEnd = this.convertViewPositionToModelPosition(range.endLineNumber, range.endColumn); if (modelEnd.lineNumber - modelStart.lineNumber <= range.endLineNumber - range.startLineNumber) { // most likely there are no hidden lines => fast path // fetch decorations from column 1 to cover the case of wrapped lines that have whole line decorations at column 1 return this.model.getDecorationsInRange(new range_1.Range(modelStart.lineNumber, 1, modelEnd.lineNumber, modelEnd.column), ownerId, filterOutValidation); } var result = []; var modelStartLineIndex = modelStart.lineNumber - 1; var modelEndLineIndex = modelEnd.lineNumber - 1; var reqStart = null; for (var modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) { var line = this.lines[modelLineIndex]; if (line.isVisible()) { // merge into previous request if (reqStart === null) { reqStart = new position_1.Position(modelLineIndex + 1, modelLineIndex === modelStartLineIndex ? modelStart.column : 1); } } else { // hit invisible line => flush request if (reqStart !== null) { var maxLineColumn = this.model.getLineMaxColumn(modelLineIndex); result = result.concat(this.model.getDecorationsInRange(new range_1.Range(reqStart.lineNumber, reqStart.column, modelLineIndex, maxLineColumn), ownerId, filterOutValidation)); reqStart = null; } } } if (reqStart !== null) { result = result.concat(this.model.getDecorationsInRange(new range_1.Range(reqStart.lineNumber, reqStart.column, modelEnd.lineNumber, modelEnd.column), ownerId, filterOutValidation)); reqStart = null; } result.sort(function (a, b) { var res = range_1.Range.compareRangesUsingStarts(a.range, b.range); if (res === 0) { if (a.id < b.id) { return -1; } if (a.id > b.id) { return 1; } return 0; } return res; }); // Eliminate duplicate decorations that might have intersected our visible ranges multiple times var finalResult = [], finalResultLen = 0; var prevDecId = null; for (var _i = 0, result_1 = result; _i < result_1.length; _i++) { var dec = result_1[_i]; var decId = dec.id; if (prevDecId === decId) { // skip continue; } prevDecId = decId; finalResult[finalResultLen++] = dec; } return finalResult; }; return SplitLinesCollection; }()); exports.SplitLinesCollection = SplitLinesCollection; var VisibleIdentitySplitLine = /** @class */ (function () { function VisibleIdentitySplitLine() { } VisibleIdentitySplitLine.prototype.isVisible = function () { return true; }; VisibleIdentitySplitLine.prototype.setVisible = function (isVisible) { if (isVisible) { return this; } return InvisibleIdentitySplitLine.INSTANCE; }; VisibleIdentitySplitLine.prototype.getLineBreakData = function () { return null; }; VisibleIdentitySplitLine.prototype.getViewLineCount = function () { return 1; }; VisibleIdentitySplitLine.prototype.getViewLineContent = function (model, modelLineNumber, _outputLineIndex) { return model.getLineContent(modelLineNumber); }; VisibleIdentitySplitLine.prototype.getViewLineLength = function (model, modelLineNumber, _outputLineIndex) { return model.getLineLength(modelLineNumber); }; VisibleIdentitySplitLine.prototype.getViewLineMinColumn = function (model, modelLineNumber, _outputLineIndex) { return model.getLineMinColumn(modelLineNumber); }; VisibleIdentitySplitLine.prototype.getViewLineMaxColumn = function (model, modelLineNumber, _outputLineIndex) { return model.getLineMaxColumn(modelLineNumber); }; VisibleIdentitySplitLine.prototype.getViewLineData = function (model, modelLineNumber, _outputLineIndex) { var lineTokens = model.getLineTokens(modelLineNumber); var lineContent = lineTokens.getLineContent(); return new viewModel_1.ViewLineData(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate()); }; VisibleIdentitySplitLine.prototype.getViewLinesData = function (model, modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, globalStartIndex, needed, result) { if (!needed[globalStartIndex]) { result[globalStartIndex] = null; return; } result[globalStartIndex] = this.getViewLineData(model, modelLineNumber, 0); }; VisibleIdentitySplitLine.prototype.getModelColumnOfViewPosition = function (_outputLineIndex, outputColumn) { return outputColumn; }; VisibleIdentitySplitLine.prototype.getViewPositionOfModelPosition = function (deltaLineNumber, inputColumn) { return new position_1.Position(deltaLineNumber, inputColumn); }; VisibleIdentitySplitLine.prototype.getViewLineNumberOfModelPosition = function (deltaLineNumber, _inputColumn) { return deltaLineNumber; }; VisibleIdentitySplitLine.INSTANCE = new VisibleIdentitySplitLine(); return VisibleIdentitySplitLine; }()); var InvisibleIdentitySplitLine = /** @class */ (function () { function InvisibleIdentitySplitLine() { } InvisibleIdentitySplitLine.prototype.isVisible = function () { return false; }; InvisibleIdentitySplitLine.prototype.setVisible = function (isVisible) { if (!isVisible) { return this; } return VisibleIdentitySplitLine.INSTANCE; }; InvisibleIdentitySplitLine.prototype.getLineBreakData = function () { return null; }; InvisibleIdentitySplitLine.prototype.getViewLineCount = function () { return 0; }; InvisibleIdentitySplitLine.prototype.getViewLineContent = function (_model, _modelLineNumber, _outputLineIndex) { throw new Error('Not supported'); }; InvisibleIdentitySplitLine.prototype.getViewLineLength = function (_model, _modelLineNumber, _outputLineIndex) { throw new Error('Not supported'); }; InvisibleIdentitySplitLine.prototype.getViewLineMinColumn = function (_model, _modelLineNumber, _outputLineIndex) { throw new Error('Not supported'); }; InvisibleIdentitySplitLine.prototype.getViewLineMaxColumn = function (_model, _modelLineNumber, _outputLineIndex) { throw new Error('Not supported'); }; InvisibleIdentitySplitLine.prototype.getViewLineData = function (_model, _modelLineNumber, _outputLineIndex) { throw new Error('Not supported'); }; InvisibleIdentitySplitLine.prototype.getViewLinesData = function (_model, _modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, _globalStartIndex, _needed, _result) { throw new Error('Not supported'); }; InvisibleIdentitySplitLine.prototype.getModelColumnOfViewPosition = function (_outputLineIndex, _outputColumn) { throw new Error('Not supported'); }; InvisibleIdentitySplitLine.prototype.getViewPositionOfModelPosition = function (_deltaLineNumber, _inputColumn) { throw new Error('Not supported'); }; InvisibleIdentitySplitLine.prototype.getViewLineNumberOfModelPosition = function (_deltaLineNumber, _inputColumn) { throw new Error('Not supported'); }; InvisibleIdentitySplitLine.INSTANCE = new InvisibleIdentitySplitLine(); return InvisibleIdentitySplitLine; }()); var SplitLine = /** @class */ (function () { function SplitLine(lineBreakData, isVisible) { this._lineBreakData = lineBreakData; this._isVisible = isVisible; } SplitLine.prototype.isVisible = function () { return this._isVisible; }; SplitLine.prototype.setVisible = function (isVisible) { this._isVisible = isVisible; return this; }; SplitLine.prototype.getLineBreakData = function () { return this._lineBreakData; }; SplitLine.prototype.getViewLineCount = function () { if (!this._isVisible) { return 0; } return this._lineBreakData.breakOffsets.length; }; SplitLine.prototype.getInputStartOffsetOfOutputLineIndex = function (outputLineIndex) { return LineBreakData.getInputOffsetOfOutputPosition(this._lineBreakData.breakOffsets, outputLineIndex, 0); }; SplitLine.prototype.getInputEndOffsetOfOutputLineIndex = function (model, modelLineNumber, outputLineIndex) { if (outputLineIndex + 1 === this._lineBreakData.breakOffsets.length) { return model.getLineMaxColumn(modelLineNumber) - 1; } return LineBreakData.getInputOffsetOfOutputPosition(this._lineBreakData.breakOffsets, outputLineIndex + 1, 0); }; SplitLine.prototype.getViewLineContent = function (model, modelLineNumber, outputLineIndex) { if (!this._isVisible) { throw new Error('Not supported'); } var startOffset = this.getInputStartOffsetOfOutputLineIndex(outputLineIndex); var endOffset = this.getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex); var r = model.getValueInRange({ startLineNumber: modelLineNumber, startColumn: startOffset + 1, endLineNumber: modelLineNumber, endColumn: endOffset + 1 }); if (outputLineIndex > 0) { r = spaces(this._lineBreakData.wrappedTextIndentLength) + r; } return r; }; SplitLine.prototype.getViewLineLength = function (model, modelLineNumber, outputLineIndex) { if (!this._isVisible) { throw new Error('Not supported'); } var startOffset = this.getInputStartOffsetOfOutputLineIndex(outputLineIndex); var endOffset = this.getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex); var r = endOffset - startOffset; if (outputLineIndex > 0) { r = this._lineBreakData.wrappedTextIndentLength + r; } return r; }; SplitLine.prototype.getViewLineMinColumn = function (_model, _modelLineNumber, outputLineIndex) { if (!this._isVisible) { throw new Error('Not supported'); } if (outputLineIndex > 0) { return this._lineBreakData.wrappedTextIndentLength + 1; } return 1; }; SplitLine.prototype.getViewLineMaxColumn = function (model, modelLineNumber, outputLineIndex) { if (!this._isVisible) { throw new Error('Not supported'); } return this.getViewLineContent(model, modelLineNumber, outputLineIndex).length + 1; }; SplitLine.prototype.getViewLineData = function (model, modelLineNumber, outputLineIndex) { if (!this._isVisible) { throw new Error('Not supported'); } var startOffset = this.getInputStartOffsetOfOutputLineIndex(outputLineIndex); var endOffset = this.getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex); var lineContent = model.getValueInRange({ startLineNumber: modelLineNumber, startColumn: startOffset + 1, endLineNumber: modelLineNumber, endColumn: endOffset + 1 }); if (outputLineIndex > 0) { lineContent = spaces(this._lineBreakData.wrappedTextIndentLength) + lineContent; } var minColumn = (outputLineIndex > 0 ? this._lineBreakData.wrappedTextIndentLength + 1 : 1); var maxColumn = lineContent.length + 1; var continuesWithWrappedLine = (outputLineIndex + 1 < this.getViewLineCount()); var deltaStartIndex = 0; if (outputLineIndex > 0) { deltaStartIndex = this._lineBreakData.wrappedTextIndentLength; } var lineTokens = model.getLineTokens(modelLineNumber); var startVisibleColumn = (outputLineIndex === 0 ? 0 : this._lineBreakData.breakOffsetsVisibleColumn[outputLineIndex - 1]); return new viewModel_1.ViewLineData(lineContent, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, lineTokens.sliceAndInflate(startOffset, endOffset, deltaStartIndex)); }; SplitLine.prototype.getViewLinesData = function (model, modelLineNumber, fromOuputLineIndex, toOutputLineIndex, globalStartIndex, needed, result) { if (!this._isVisible) { throw new Error('Not supported'); } for (var outputLineIndex = fromOuputLineIndex; outputLineIndex < toOutputLineIndex; outputLineIndex++) { var globalIndex = globalStartIndex + outputLineIndex - fromOuputLineIndex; if (!needed[globalIndex]) { result[globalIndex] = null; continue; } result[globalIndex] = this.getViewLineData(model, modelLineNumber, outputLineIndex); } }; SplitLine.prototype.getModelColumnOfViewPosition = function (outputLineIndex, outputColumn) { if (!this._isVisible) { throw new Error('Not supported'); } var adjustedColumn = outputColumn - 1; if (outputLineIndex > 0) { if (adjustedColumn < this._lineBreakData.wrappedTextIndentLength) { adjustedColumn = 0; } else { adjustedColumn -= this._lineBreakData.wrappedTextIndentLength; } } return LineBreakData.getInputOffsetOfOutputPosition(this._lineBreakData.breakOffsets, outputLineIndex, adjustedColumn) + 1; }; SplitLine.prototype.getViewPositionOfModelPosition = function (deltaLineNumber, inputColumn) { if (!this._isVisible) { throw new Error('Not supported'); } var r = LineBreakData.getOutputPositionOfInputOffset(this._lineBreakData.breakOffsets, inputColumn - 1); var outputLineIndex = r.outputLineIndex; var outputColumn = r.outputOffset + 1; if (outputLineIndex > 0) { outputColumn += this._lineBreakData.wrappedTextIndentLength; } // console.log('in -> out ' + deltaLineNumber + ',' + inputColumn + ' ===> ' + (deltaLineNumber+outputLineIndex) + ',' + outputColumn); return new position_1.Position(deltaLineNumber + outputLineIndex, outputColumn); }; SplitLine.prototype.getViewLineNumberOfModelPosition = function (deltaLineNumber, inputColumn) { if (!this._isVisible) { throw new Error('Not supported'); } var r = LineBreakData.getOutputPositionOfInputOffset(this._lineBreakData.breakOffsets, inputColumn - 1); return (deltaLineNumber + r.outputLineIndex); }; return SplitLine; }()); exports.SplitLine = SplitLine; var _spaces = ['']; function spaces(count) { if (count >= _spaces.length) { for (var i = 1; i <= count; i++) { _spaces[i] = _makeSpaces(i); } } return _spaces[count]; } function _makeSpaces(count) { return new Array(count + 1).join(' '); } function createSplitLine(lineBreakData, isVisible) { if (lineBreakData === null) { // No mapping needed if (isVisible) { return VisibleIdentitySplitLine.INSTANCE; } return InvisibleIdentitySplitLine.INSTANCE; } else { return new SplitLine(lineBreakData, isVisible); } } var IdentityCoordinatesConverter = /** @class */ (function () { function IdentityCoordinatesConverter(lines) { this._lines = lines; } IdentityCoordinatesConverter.prototype._validPosition = function (pos) { return this._lines.model.validatePosition(pos); }; IdentityCoordinatesConverter.prototype._validRange = function (range) { return this._lines.model.validateRange(range); }; // View -> Model conversion and related methods IdentityCoordinatesConverter.prototype.convertViewPositionToModelPosition = function (viewPosition) { return this._validPosition(viewPosition); }; IdentityCoordinatesConverter.prototype.convertViewRangeToModelRange = function (viewRange) { return this._validRange(viewRange); }; IdentityCoordinatesConverter.prototype.validateViewPosition = function (_viewPosition, expectedModelPosition) { return this._validPosition(expectedModelPosition); }; IdentityCoordinatesConverter.prototype.validateViewRange = function (_viewRange, expectedModelRange) { return this._validRange(expectedModelRange); }; // Model -> View conversion and related methods IdentityCoordinatesConverter.prototype.convertModelPositionToViewPosition = function (modelPosition) { return this._validPosition(modelPosition); }; IdentityCoordinatesConverter.prototype.convertModelRangeToViewRange = function (modelRange) { return this._validRange(modelRange); }; IdentityCoordinatesConverter.prototype.modelPositionIsVisible = function (modelPosition) { var lineCount = this._lines.model.getLineCount(); if (modelPosition.lineNumber < 1 || modelPosition.lineNumber > lineCount) { // invalid arguments return false; } return true; }; return IdentityCoordinatesConverter; }()); exports.IdentityCoordinatesConverter = IdentityCoordinatesConverter; var IdentityLinesCollection = /** @class */ (function () { function IdentityLinesCollection(model) { this.model = model; } IdentityLinesCollection.prototype.dispose = function () { }; IdentityLinesCollection.prototype.createCoordinatesConverter = function () { return new IdentityCoordinatesConverter(this); }; IdentityLinesCollection.prototype.getHiddenAreas = function () { return []; }; IdentityLinesCollection.prototype.setHiddenAreas = function (_ranges) { return false; }; IdentityLinesCollection.prototype.setTabSize = function (_newTabSize) { return false; }; IdentityLinesCollection.prototype.setWrappingSettings = function (_fontInfo, _wrappingStrategy, _wrappingColumn, _wrappingIndent) { return false; }; IdentityLinesCollection.prototype.createLineBreaksComputer = function () { var result = []; return { addRequest: function (lineText, previousLineBreakData) { result.push(null); }, finalize: function () { return result; } }; }; IdentityLinesCollection.prototype.onModelFlushed = function () { }; IdentityLinesCollection.prototype.onModelLinesDeleted = function (_versionId, fromLineNumber, toLineNumber) { return new viewEvents.ViewLinesDeletedEvent(fromLineNumber, toLineNumber); }; IdentityLinesCollection.prototype.onModelLinesInserted = function (_versionId, fromLineNumber, toLineNumber, lineBreaks) { return new viewEvents.ViewLinesInsertedEvent(fromLineNumber, toLineNumber); }; IdentityLinesCollection.prototype.onModelLineChanged = function (_versionId, lineNumber, lineBreakData) { return [false, new viewEvents.ViewLinesChangedEvent(lineNumber, lineNumber), null, null]; }; IdentityLinesCollection.prototype.acceptVersionId = function (_versionId) { }; IdentityLinesCollection.prototype.getViewLineCount = function () { return this.model.getLineCount(); }; IdentityLinesCollection.prototype.getActiveIndentGuide = function (viewLineNumber, _minLineNumber, _maxLineNumber) { return { startLineNumber: viewLineNumber, endLineNumber: viewLineNumber, indent: 0 }; }; IdentityLinesCollection.prototype.getViewLinesIndentGuides = function (viewStartLineNumber, viewEndLineNumber) { var viewLineCount = viewEndLineNumber - viewStartLineNumber + 1; var result = new Array(viewLineCount); for (var i = 0; i < viewLineCount; i++) { result[i] = 0; } return result; }; IdentityLinesCollection.prototype.getViewLineContent = function (viewLineNumber) { return this.model.getLineContent(viewLineNumber); }; IdentityLinesCollection.prototype.getViewLineLength = function (viewLineNumber) { return this.model.getLineLength(viewLineNumber); }; IdentityLinesCollection.prototype.getViewLineMinColumn = function (viewLineNumber) { return this.model.getLineMinColumn(viewLineNumber); }; IdentityLinesCollection.prototype.getViewLineMaxColumn = function (viewLineNumber) { return this.model.getLineMaxColumn(viewLineNumber); }; IdentityLinesCollection.prototype.getViewLineData = function (viewLineNumber) { var lineTokens = this.model.getLineTokens(viewLineNumber); var lineContent = lineTokens.getLineContent(); return new viewModel_1.ViewLineData(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate()); }; IdentityLinesCollection.prototype.getViewLinesData = function (viewStartLineNumber, viewEndLineNumber, needed) { var lineCount = this.model.getLineCount(); viewStartLineNumber = Math.min(Math.max(1, viewStartLineNumber), lineCount); viewEndLineNumber = Math.min(Math.max(1, viewEndLineNumber), lineCount); var result = []; for (var lineNumber = viewStartLineNumber; lineNumber <= viewEndLineNumber; lineNumber++) { var idx = lineNumber - viewStartLineNumber; if (!needed[idx]) { result[idx] = null; } result[idx] = this.getViewLineData(lineNumber); } return result; }; IdentityLinesCollection.prototype.getAllOverviewRulerDecorations = function (ownerId, filterOutValidation, theme) { var decorations = this.model.getOverviewRulerDecorations(ownerId, filterOutValidation); var result = new OverviewRulerDecorations(); for (var _i = 0, decorations_2 = decorations; _i < decorations_2.length; _i++) { var decoration = decorations_2[_i]; var opts = decoration.options.overviewRuler; var lane = opts ? opts.position : 0; if (lane === 0) { continue; } var color = opts.getColor(theme); var viewStartLineNumber = decoration.range.startLineNumber; var viewEndLineNumber = decoration.range.endLineNumber; result.accept(color, viewStartLineNumber, viewEndLineNumber, lane); } return result.result; }; IdentityLinesCollection.prototype.getDecorationsInRange = function (range, ownerId, filterOutValidation) { return this.model.getDecorationsInRange(range, ownerId, filterOutValidation); }; return IdentityLinesCollection; }()); exports.IdentityLinesCollection = IdentityLinesCollection; var OverviewRulerDecorations = /** @class */ (function () { function OverviewRulerDecorations() { this.result = Object.create(null); } OverviewRulerDecorations.prototype.accept = function (color, startLineNumber, endLineNumber, lane) { var prev = this.result[color]; if (prev) { var prevLane = prev[prev.length - 3]; var prevEndLineNumber = prev[prev.length - 1]; if (prevLane === lane && prevEndLineNumber + 1 >= startLineNumber) { // merge into prev if (endLineNumber > prevEndLineNumber) { prev[prev.length - 1] = endLineNumber; } return; } // push prev.push(lane, startLineNumber, endLineNumber); } else { this.result[color] = [lane, startLineNumber, endLineNumber]; } }; return OverviewRulerDecorations; }()); }); /*--------------------------------------------------------------------------------------------- * 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/editor/common/viewModel/monospaceLineBreaksComputer*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,79/*vs/editor/common/core/characterClassifier*/,161/*vs/editor/common/viewModel/splitLinesCollection*/]), function (require, exports, strings, characterClassifier_1, splitLinesCollection_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var WrappingCharacterClassifier = /** @class */ (function (_super) { __extends(WrappingCharacterClassifier, _super); function WrappingCharacterClassifier(BREAK_BEFORE, BREAK_AFTER) { var _this = _super.call(this, 0 /* NONE */) || this; for (var i = 0; i < BREAK_BEFORE.length; i++) { _this.set(BREAK_BEFORE.charCodeAt(i), 1 /* BREAK_BEFORE */); } for (var i = 0; i < BREAK_AFTER.length; i++) { _this.set(BREAK_AFTER.charCodeAt(i), 2 /* BREAK_AFTER */); } return _this; } WrappingCharacterClassifier.prototype.get = function (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); } }; return WrappingCharacterClassifier; }(characterClassifier_1.CharacterClassifier)); var arrPool1 = []; var arrPool2 = []; var MonospaceLineBreaksComputerFactory = /** @class */ (function () { function MonospaceLineBreaksComputerFactory(breakBeforeChars, breakAfterChars) { this.classifier = new WrappingCharacterClassifier(breakBeforeChars, breakAfterChars); } MonospaceLineBreaksComputerFactory.create = function (options) { return new MonospaceLineBreaksComputerFactory(options.get(99 /* wordWrapBreakBeforeCharacters */), options.get(98 /* wordWrapBreakAfterCharacters */)); }; MonospaceLineBreaksComputerFactory.prototype.createLineBreaksComputer = function (fontInfo, tabSize, wrappingColumn, wrappingIndent) { var _this = this; tabSize = tabSize | 0; //@perf wrappingColumn = +wrappingColumn; //@perf var requests = []; var previousBreakingData = []; return { addRequest: function (lineText, previousLineBreakData) { requests.push(lineText); previousBreakingData.push(previousLineBreakData); }, finalize: function () { var columnsForFullWidthChar = fontInfo.typicalFullwidthCharacterWidth / fontInfo.typicalHalfwidthCharacterWidth; //@perf var result = []; for (var i = 0, len = requests.length; i < len; i++) { var previousLineBreakData = previousBreakingData[i]; if (previousLineBreakData) { result[i] = createLineBreaksFromPreviousLineBreaks(_this.classifier, previousLineBreakData, requests[i], tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent); } else { result[i] = createLineBreaks(_this.classifier, requests[i], tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent); } } arrPool1.length = 0; arrPool2.length = 0; return result; } }; }; return MonospaceLineBreaksComputerFactory; }()); exports.MonospaceLineBreaksComputerFactory = MonospaceLineBreaksComputerFactory; function createLineBreaksFromPreviousLineBreaks(classifier, previousBreakingData, lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) { if (firstLineBreakColumn === -1) { return null; } var len = lineText.length; if (len <= 1) { return null; } var prevBreakingOffsets = previousBreakingData.breakOffsets; var prevBreakingOffsetsVisibleColumn = previousBreakingData.breakOffsetsVisibleColumn; var wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent); var wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength; var breakingOffsets = arrPool1; var breakingOffsetsVisibleColumn = arrPool2; var breakingOffsetsCount = 0; var breakingColumn = firstLineBreakColumn; var prevLen = prevBreakingOffsets.length; var prevIndex = 0; if (prevIndex >= 0) { var bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn); while (prevIndex + 1 < prevLen) { var 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) var prevBreakOffset = prevIndex < 0 ? 0 : prevBreakingOffsets[prevIndex]; var prevBreakoffsetVisibleColumn = prevIndex < 0 ? 0 : prevBreakingOffsetsVisibleColumn[prevIndex]; var breakOffset = 0; var breakOffsetVisibleColumn = 0; var forcedBreakOffset = 0; var forcedBreakOffsetVisibleColumn = 0; // initially, we search as much as possible to the right (if it fits) if (prevBreakoffsetVisibleColumn <= breakingColumn) { var visibleColumn = prevBreakoffsetVisibleColumn; var prevCharCode = lineText.charCodeAt(prevBreakOffset - 1); var prevCharCodeClass = classifier.get(prevCharCode); var entireLineFits = true; for (var i = prevBreakOffset; i < len; i++) { var charStartOffset = i; var charCode = lineText.charCodeAt(i); var charCodeClass = void 0; var charWidth = void 0; 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`: forcedBreakOffset = charStartOffset; forcedBreakOffsetVisibleColumn = visibleColumn - charWidth; 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 breakingOffsets[breakingOffsetsCount] = prevBreakingOffsets[prevBreakingOffsets.length - 1]; breakingOffsetsVisibleColumn[breakingOffsetsCount] = prevBreakingOffsetsVisibleColumn[prevBreakingOffsets.length - 1]; breakingOffsetsCount++; } break; } } if (breakOffset === 0) { // must search left var visibleColumn = prevBreakoffsetVisibleColumn; var charCode = lineText.charCodeAt(prevBreakOffset); var charCodeClass = classifier.get(charCode); var hitATabCharacter = false; for (var i = prevBreakOffset - 1; i >= 0; i--) { var charStartOffset = i + 1; var 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; } var prevCharCodeClass = void 0; var prevCharWidth = void 0; 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) { var remainingWidthOfNextLine = wrappedLineBreakColumn - (forcedBreakOffsetVisibleColumn - breakOffsetVisibleColumn); if (remainingWidthOfNextLine <= tabSize) { var charCodeAtForcedBreakOffset = lineText.charCodeAt(forcedBreakOffset); var charWidth = void 0; 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; } breakingOffsets[breakingOffsetsCount] = breakOffset; breakingOffsetsVisibleColumn[breakingOffsetsCount] = breakOffsetVisibleColumn; breakingOffsetsCount++; breakingColumn = breakOffsetVisibleColumn + wrappedLineBreakColumn; while (prevIndex < 0 || (prevIndex < prevLen && prevBreakingOffsetsVisibleColumn[prevIndex] < breakOffsetVisibleColumn)) { prevIndex++; } var bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn); while (prevIndex + 1 < prevLen) { var 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, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) { if (firstLineBreakColumn === -1) { return null; } var len = lineText.length; if (len <= 1) { return null; } var wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent); var wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength; var breakingOffsets = []; var breakingOffsetsVisibleColumn = []; var breakingOffsetsCount = 0; var breakOffset = 0; var breakOffsetVisibleColumn = 0; var breakingColumn = firstLineBreakColumn; var prevCharCode = lineText.charCodeAt(0); var prevCharCodeClass = classifier.get(prevCharCode); var visibleColumn = computeCharWidth(prevCharCode, 0, tabSize, columnsForFullWidthChar); var 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 (var i = startOffset; i < len; i++) { var charStartOffset = i; var charCode = lineText.charCodeAt(i); var charCodeClass = void 0; var charWidth = void 0; 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) { return null; } // Add last segment breakingOffsets[breakingOffsetsCount] = len; breakingOffsetsVisibleColumn[breakingOffsetsCount] = visibleColumn; return new splitLinesCollection_1.LineBreakData(breakingOffsets, breakingOffsetsVisibleColumn, wrappedTextIndentLength); } function computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar) { if (charCode === 9 /* Tab */) { return (tabSize - (visibleColumn % tabSize)); } if (strings.isFullWidthCharacter(charCode)) { 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) { var wrappedTextIndentLength = 0; if (wrappingIndent !== 0 /* None */) { var firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineText); if (firstNonWhitespaceIndex !== -1) { // Track existing indent for (var i = 0; i < firstNonWhitespaceIndex; i++) { var charWidth = (lineText.charCodeAt(i) === 9 /* Tab */ ? tabCharacterWidth(wrappedTextIndentLength, tabSize) : 1); wrappedTextIndentLength += charWidth; } // Increase indent of continuation lines, if desired var numberOfAdditionalTabs = (wrappingIndent === 3 /* DeepIndent */ ? 2 : wrappingIndent === 2 /* Indent */ ? 1 : 0); for (var i = 0; i < numberOfAdditionalTabs; i++) { var 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[488/*vs/editor/common/viewModel/viewModelImpl*/], __M([0/*require*/,1/*exports*/,27/*vs/base/common/color*/,5/*vs/base/common/strings*/,33/*vs/editor/common/config/editorOptions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,17/*vs/editor/common/modes*/,214/*vs/editor/common/modes/textToHtmlTokenizer*/,215/*vs/editor/common/viewModel/minimapTokensColorTracker*/,81/*vs/editor/common/view/viewEvents*/,373/*vs/editor/common/viewLayout/viewLayout*/,161/*vs/editor/common/viewModel/splitLinesCollection*/,69/*vs/editor/common/viewModel/viewModel*/,424/*vs/editor/common/viewModel/viewModelDecorations*/,15/*vs/base/common/async*/,16/*vs/base/common/platform*/]), function (require, exports, color_1, strings, editorOptions_1, position_1, range_1, modes_1, textToHtmlTokenizer_1, minimapTokensColorTracker_1, viewEvents, viewLayout_1, splitLinesCollection_1, viewModel_1, viewModelDecorations_1, async_1, platform) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var USE_IDENTITY_LINES_COLLECTION = true; var ViewModel = /** @class */ (function (_super) { __extends(ViewModel, _super); function ViewModel(editorId, configuration, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, scheduleAtNextAnimationFrame) { var _this = _super.call(this) || this; _this.editorId = editorId; _this.configuration = configuration; _this.model = model; _this._tokenizeViewportSoon = _this._register(new async_1.RunOnceScheduler(function () { return _this.tokenizeViewport(); }, 50)); _this.hasFocus = false; _this.viewportStartLine = -1; _this.viewportStartLineTrackedRange = null; _this.viewportStartLineDelta = 0; if (USE_IDENTITY_LINES_COLLECTION && _this.model.isTooLargeForTokenization()) { _this.lines = new splitLinesCollection_1.IdentityLinesCollection(_this.model); } else { var options = _this.configuration.options; var fontInfo = options.get(34 /* fontInfo */); var wrappingStrategy = options.get(103 /* wrappingStrategy */); var wrappingInfo = options.get(108 /* wrappingInfo */); var wrappingIndent = options.get(102 /* wrappingIndent */); _this.lines = new splitLinesCollection_1.SplitLinesCollection(_this.model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, _this.model.getOptions().tabSize, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent); } _this.coordinatesConverter = _this.lines.createCoordinatesConverter(); _this.viewLayout = _this._register(new viewLayout_1.ViewLayout(_this.configuration, _this.getLineCount(), scheduleAtNextAnimationFrame)); _this._register(_this.viewLayout.onDidScroll(function (e) { if (e.scrollTopChanged) { _this._tokenizeViewportSoon.schedule(); } try { var eventsCollector = _this._beginEmit(); eventsCollector.emit(new viewEvents.ViewScrollChangedEvent(e)); } finally { _this._endEmit(); } })); _this._register(_this.viewLayout.onDidContentSizeChange(function (e) { try { var eventsCollector = _this._beginEmit(); eventsCollector.emit(new viewEvents.ViewContentSizeChangedEvent(e)); } finally { _this._endEmit(); } })); _this.decorations = new viewModelDecorations_1.ViewModelDecorations(_this.editorId, _this.model, _this.configuration, _this.lines, _this.coordinatesConverter); _this._registerModelEvents(); _this._register(_this.configuration.onDidChange(function (e) { try { var eventsCollector = _this._beginEmit(); _this._onConfigurationChanged(eventsCollector, e); } finally { _this._endEmit(); } })); _this._register(minimapTokensColorTracker_1.MinimapTokensColorTracker.getInstance().onDidChange(function () { try { var eventsCollector = _this._beginEmit(); eventsCollector.emit(new viewEvents.ViewTokensColorsChangedEvent()); } finally { _this._endEmit(); } })); return _this; } ViewModel.prototype.dispose = function () { // First remove listeners, as disposing the lines might end up sending // model decoration changed events ... and we no longer care about them ... _super.prototype.dispose.call(this); this.decorations.dispose(); this.lines.dispose(); this.invalidateMinimapColorCache(); this.viewportStartLineTrackedRange = this.model._setTrackedRange(this.viewportStartLineTrackedRange, null, 1 /* NeverGrowsWhenTypingAtEdges */); }; ViewModel.prototype.tokenizeViewport = function () { var linesViewportData = this.viewLayout.getLinesViewportData(); var startPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(linesViewportData.startLineNumber, 1)); var endPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(linesViewportData.endLineNumber, 1)); this.model.tokenizeViewport(startPosition.lineNumber, endPosition.lineNumber); }; ViewModel.prototype.setHasFocus = function (hasFocus) { this.hasFocus = hasFocus; }; ViewModel.prototype._onConfigurationChanged = function (eventsCollector, e) { // We might need to restore the current centered view range, so save it (if available) var previousViewportStartModelPosition = null; if (this.viewportStartLine !== -1) { var previousViewportStartViewPosition = new position_1.Position(this.viewportStartLine, this.getLineMinColumn(this.viewportStartLine)); previousViewportStartModelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(previousViewportStartViewPosition); } var restorePreviousViewportStart = false; var options = this.configuration.options; var fontInfo = options.get(34 /* fontInfo */); var wrappingStrategy = options.get(103 /* wrappingStrategy */); var wrappingInfo = options.get(108 /* wrappingInfo */); var wrappingIndent = options.get(102 /* wrappingIndent */); if (this.lines.setWrappingSettings(fontInfo, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent)) { eventsCollector.emit(new viewEvents.ViewFlushedEvent()); eventsCollector.emit(new viewEvents.ViewLineMappingChangedEvent()); eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent()); this.decorations.onLineMappingChanged(); this.viewLayout.onFlushed(this.getLineCount()); if (this.viewLayout.getCurrentScrollTop() !== 0) { // Never change the scroll position from 0 to something else... restorePreviousViewportStart = true; } } if (e.hasChanged(68 /* readOnly */)) { // Must read again all decorations due to readOnly filtering this.decorations.reset(); eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent()); } eventsCollector.emit(new viewEvents.ViewConfigurationChangedEvent(e)); this.viewLayout.onConfigurationChanged(e); if (restorePreviousViewportStart && previousViewportStartModelPosition) { var viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(previousViewportStartModelPosition); var viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber); this.viewLayout.setScrollPositionNow({ scrollTop: viewPositionTop + this.viewportStartLineDelta }); } }; ViewModel.prototype._registerModelEvents = function () { var _this = this; this._register(this.model.onDidChangeRawContentFast(function (e) { try { var eventsCollector = _this._beginEmit(); var hadOtherModelChange = false; var hadModelLineChangeThatChangedLineMapping = false; var changes = e.changes; var versionId = e.versionId; // Do a first pass to compute line mappings, and a second pass to actually interpret them var lineBreaksComputer = _this.lines.createLineBreaksComputer(); for (var _i = 0, changes_1 = changes; _i < changes_1.length; _i++) { var change = changes_1[_i]; switch (change.changeType) { case 4 /* LinesInserted */: { for (var _a = 0, _b = change.detail; _a < _b.length; _a++) { var line = _b[_a]; lineBreaksComputer.addRequest(line, null); } break; } case 2 /* LineChanged */: { lineBreaksComputer.addRequest(change.detail, null); break; } } } var lineBreaks = lineBreaksComputer.finalize(); var lineBreaksOffset = 0; for (var _c = 0, changes_2 = changes; _c < changes_2.length; _c++) { var change = changes_2[_c]; switch (change.changeType) { case 1 /* Flush */: { _this.lines.onModelFlushed(); eventsCollector.emit(new viewEvents.ViewFlushedEvent()); _this.decorations.reset(); _this.viewLayout.onFlushed(_this.getLineCount()); hadOtherModelChange = true; break; } case 3 /* LinesDeleted */: { var linesDeletedEvent = _this.lines.onModelLinesDeleted(versionId, change.fromLineNumber, change.toLineNumber); if (linesDeletedEvent !== null) { eventsCollector.emit(linesDeletedEvent); _this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber); } hadOtherModelChange = true; break; } case 4 /* LinesInserted */: { var insertedLineBreaks = lineBreaks.slice(lineBreaksOffset, lineBreaksOffset + change.detail.length); lineBreaksOffset += change.detail.length; var linesInsertedEvent = _this.lines.onModelLinesInserted(versionId, change.fromLineNumber, change.toLineNumber, insertedLineBreaks); if (linesInsertedEvent !== null) { eventsCollector.emit(linesInsertedEvent); _this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber); } hadOtherModelChange = true; break; } case 2 /* LineChanged */: { var changedLineBreakData = lineBreaks[lineBreaksOffset]; lineBreaksOffset++; var _d = _this.lines.onModelLineChanged(versionId, change.lineNumber, changedLineBreakData), lineMappingChanged = _d[0], linesChangedEvent = _d[1], linesInsertedEvent = _d[2], linesDeletedEvent = _d[3]; hadModelLineChangeThatChangedLineMapping = lineMappingChanged; if (linesChangedEvent) { eventsCollector.emit(linesChangedEvent); } if (linesInsertedEvent) { eventsCollector.emit(linesInsertedEvent); _this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber); } if (linesDeletedEvent) { eventsCollector.emit(linesDeletedEvent); _this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber); } break; } case 5 /* EOLChanged */: { // Nothing to do. The new version will be accepted below break; } } } _this.lines.acceptVersionId(versionId); _this.viewLayout.onHeightMaybeChanged(); if (!hadOtherModelChange && hadModelLineChangeThatChangedLineMapping) { eventsCollector.emit(new viewEvents.ViewLineMappingChangedEvent()); eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent()); _this.decorations.onLineMappingChanged(); } } finally { _this._endEmit(); } // Update the configuration and reset the centered view line _this.viewportStartLine = -1; _this.configuration.setMaxLineNumber(_this.model.getLineCount()); // Recover viewport if (!_this.hasFocus && _this.model.getAttachedEditorCount() >= 2 && _this.viewportStartLineTrackedRange) { var modelRange = _this.model._getTrackedRange(_this.viewportStartLineTrackedRange); if (modelRange) { var viewPosition = _this.coordinatesConverter.convertModelPositionToViewPosition(modelRange.getStartPosition()); var viewPositionTop = _this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber); _this.viewLayout.setScrollPositionNow({ scrollTop: viewPositionTop + _this.viewportStartLineDelta }); } } })); this._register(this.model.onDidChangeTokens(function (e) { var viewRanges = []; for (var j = 0, lenJ = e.ranges.length; j < lenJ; j++) { var modelRange = e.ranges[j]; var viewStartLineNumber = _this.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.fromLineNumber, 1)).lineNumber; var viewEndLineNumber = _this.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.toLineNumber, _this.model.getLineMaxColumn(modelRange.toLineNumber))).lineNumber; viewRanges[j] = { fromLineNumber: viewStartLineNumber, toLineNumber: viewEndLineNumber }; } try { var eventsCollector = _this._beginEmit(); eventsCollector.emit(new viewEvents.ViewTokensChangedEvent(viewRanges)); } finally { _this._endEmit(); } if (e.tokenizationSupportChanged) { _this._tokenizeViewportSoon.schedule(); } })); this._register(this.model.onDidChangeLanguageConfiguration(function (e) { try { var eventsCollector = _this._beginEmit(); eventsCollector.emit(new viewEvents.ViewLanguageConfigurationEvent()); } finally { _this._endEmit(); } })); this._register(this.model.onDidChangeOptions(function (e) { // A tab size change causes a line mapping changed event => all view parts will repaint OK, no further event needed here if (_this.lines.setTabSize(_this.model.getOptions().tabSize)) { _this.decorations.onLineMappingChanged(); _this.viewLayout.onFlushed(_this.getLineCount()); try { var eventsCollector = _this._beginEmit(); eventsCollector.emit(new viewEvents.ViewFlushedEvent()); eventsCollector.emit(new viewEvents.ViewLineMappingChangedEvent()); eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent()); } finally { _this._endEmit(); } } })); this._register(this.model.onDidChangeDecorations(function (e) { _this.decorations.onModelDecorationsChanged(); try { var eventsCollector = _this._beginEmit(); eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent()); } finally { _this._endEmit(); } })); }; ViewModel.prototype.setHiddenAreas = function (ranges) { try { var eventsCollector = this._beginEmit(); var lineMappingChanged = this.lines.setHiddenAreas(ranges); if (lineMappingChanged) { eventsCollector.emit(new viewEvents.ViewFlushedEvent()); eventsCollector.emit(new viewEvents.ViewLineMappingChangedEvent()); eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent()); this.decorations.onLineMappingChanged(); this.viewLayout.onFlushed(this.getLineCount()); this.viewLayout.onHeightMaybeChanged(); } } finally { this._endEmit(); } }; ViewModel.prototype.getVisibleRanges = function () { var visibleViewRange = this.getCompletelyVisibleViewRange(); var visibleRange = this.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange); var hiddenAreas = this.lines.getHiddenAreas(); if (hiddenAreas.length === 0) { return [visibleRange]; } var result = [], resultLen = 0; var startLineNumber = visibleRange.startLineNumber; var startColumn = visibleRange.startColumn; var endLineNumber = visibleRange.endLineNumber; var endColumn = visibleRange.endColumn; for (var i = 0, len = hiddenAreas.length; i < len; i++) { var hiddenStartLineNumber = hiddenAreas[i].startLineNumber; var hiddenEndLineNumber = hiddenAreas[i].endLineNumber; if (hiddenEndLineNumber < startLineNumber) { continue; } if (hiddenStartLineNumber > endLineNumber) { continue; } if (startLineNumber < hiddenStartLineNumber) { result[resultLen++] = new range_1.Range(startLineNumber, startColumn, hiddenStartLineNumber - 1, this.model.getLineMaxColumn(hiddenStartLineNumber - 1)); } startLineNumber = hiddenEndLineNumber + 1; startColumn = 1; } if (startLineNumber < endLineNumber || (startLineNumber === endLineNumber && startColumn < endColumn)) { result[resultLen++] = new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn); } return result; }; ViewModel.prototype.getCompletelyVisibleViewRange = function () { var partialData = this.viewLayout.getLinesViewportData(); var startViewLineNumber = partialData.completelyVisibleStartLineNumber; var endViewLineNumber = partialData.completelyVisibleEndLineNumber; return new range_1.Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber)); }; ViewModel.prototype.getCompletelyVisibleViewRangeAtScrollTop = function (scrollTop) { var partialData = this.viewLayout.getLinesViewportDataAtScrollTop(scrollTop); var startViewLineNumber = partialData.completelyVisibleStartLineNumber; var endViewLineNumber = partialData.completelyVisibleEndLineNumber; return new range_1.Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber)); }; ViewModel.prototype.saveState = function () { var compatViewState = this.viewLayout.saveState(); var scrollTop = compatViewState.scrollTop; var firstViewLineNumber = this.viewLayout.getLineNumberAtVerticalOffset(scrollTop); var firstPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(firstViewLineNumber, this.getLineMinColumn(firstViewLineNumber))); var firstPositionDeltaTop = this.viewLayout.getVerticalOffsetForLineNumber(firstViewLineNumber) - scrollTop; return { scrollLeft: compatViewState.scrollLeft, firstPosition: firstPosition, firstPositionDeltaTop: firstPositionDeltaTop }; }; ViewModel.prototype.reduceRestoreState = function (state) { if (typeof state.firstPosition === 'undefined') { // This is a view state serialized by an older version return this._reduceRestoreStateCompatibility(state); } var modelPosition = this.model.validatePosition(state.firstPosition); var viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelPosition); var scrollTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber) - state.firstPositionDeltaTop; return { scrollLeft: state.scrollLeft, scrollTop: scrollTop }; }; ViewModel.prototype._reduceRestoreStateCompatibility = function (state) { return { scrollLeft: state.scrollLeft, scrollTop: state.scrollTopWithoutViewZones }; }; ViewModel.prototype.getTabSize = function () { return this.model.getOptions().tabSize; }; ViewModel.prototype.getOptions = function () { return this.model.getOptions(); }; ViewModel.prototype.getLineCount = function () { return this.lines.getViewLineCount(); }; /** * Gives a hint that a lot of requests are about to come in for these line numbers. */ ViewModel.prototype.setViewport = function (startLineNumber, endLineNumber, centeredLineNumber) { this.viewportStartLine = startLineNumber; var position = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(startLineNumber, this.getLineMinColumn(startLineNumber))); this.viewportStartLineTrackedRange = this.model._setTrackedRange(this.viewportStartLineTrackedRange, new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column), 1 /* NeverGrowsWhenTypingAtEdges */); var viewportStartLineTop = this.viewLayout.getVerticalOffsetForLineNumber(startLineNumber); var scrollTop = this.viewLayout.getCurrentScrollTop(); this.viewportStartLineDelta = scrollTop - viewportStartLineTop; }; ViewModel.prototype.getActiveIndentGuide = function (lineNumber, minLineNumber, maxLineNumber) { return this.lines.getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber); }; ViewModel.prototype.getLinesIndentGuides = function (startLineNumber, endLineNumber) { return this.lines.getViewLinesIndentGuides(startLineNumber, endLineNumber); }; ViewModel.prototype.getLineContent = function (lineNumber) { return this.lines.getViewLineContent(lineNumber); }; ViewModel.prototype.getLineLength = function (lineNumber) { return this.lines.getViewLineLength(lineNumber); }; ViewModel.prototype.getLineMinColumn = function (lineNumber) { return this.lines.getViewLineMinColumn(lineNumber); }; ViewModel.prototype.getLineMaxColumn = function (lineNumber) { return this.lines.getViewLineMaxColumn(lineNumber); }; ViewModel.prototype.getLineFirstNonWhitespaceColumn = function (lineNumber) { var result = strings.firstNonWhitespaceIndex(this.getLineContent(lineNumber)); if (result === -1) { return 0; } return result + 1; }; ViewModel.prototype.getLineLastNonWhitespaceColumn = function (lineNumber) { var result = strings.lastNonWhitespaceIndex(this.getLineContent(lineNumber)); if (result === -1) { return 0; } return result + 2; }; ViewModel.prototype.getDecorationsInViewport = function (visibleRange) { return this.decorations.getDecorationsViewportData(visibleRange).decorations; }; ViewModel.prototype.getViewLineRenderingData = function (visibleRange, lineNumber) { var mightContainRTL = this.model.mightContainRTL(); var mightContainNonBasicASCII = this.model.mightContainNonBasicASCII(); var tabSize = this.getTabSize(); var lineData = this.lines.getViewLineData(lineNumber); var allInlineDecorations = this.decorations.getDecorationsViewportData(visibleRange).inlineDecorations; var inlineDecorations = allInlineDecorations[lineNumber - visibleRange.startLineNumber]; return new viewModel_1.ViewLineRenderingData(lineData.minColumn, lineData.maxColumn, lineData.content, lineData.continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, lineData.tokens, inlineDecorations, tabSize, lineData.startVisibleColumn); }; ViewModel.prototype.getViewLineData = function (lineNumber) { return this.lines.getViewLineData(lineNumber); }; ViewModel.prototype.getMinimapLinesRenderingData = function (startLineNumber, endLineNumber, needed) { var result = this.lines.getViewLinesData(startLineNumber, endLineNumber, needed); return new viewModel_1.MinimapLinesRenderingData(this.getTabSize(), result); }; ViewModel.prototype.getAllOverviewRulerDecorations = function (theme) { return this.lines.getAllOverviewRulerDecorations(this.editorId, editorOptions_1.filterValidationDecorations(this.configuration.options), theme); }; ViewModel.prototype.invalidateOverviewRulerColorCache = function () { var decorations = this.model.getOverviewRulerDecorations(); for (var _i = 0, decorations_1 = decorations; _i < decorations_1.length; _i++) { var decoration = decorations_1[_i]; var opts = decoration.options.overviewRuler; if (opts) { opts.invalidateCachedColor(); } } }; ViewModel.prototype.invalidateMinimapColorCache = function () { var decorations = this.model.getAllDecorations(); for (var _i = 0, decorations_2 = decorations; _i < decorations_2.length; _i++) { var decoration = decorations_2[_i]; var opts = decoration.options.minimap; if (opts) { opts.invalidateCachedColor(); } } }; ViewModel.prototype.getValueInRange = function (range, eol) { var modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range); return this.model.getValueInRange(modelRange, eol); }; ViewModel.prototype.getModelLineMaxColumn = function (modelLineNumber) { return this.model.getLineMaxColumn(modelLineNumber); }; ViewModel.prototype.validateModelPosition = function (position) { return this.model.validatePosition(position); }; ViewModel.prototype.validateModelRange = function (range) { return this.model.validateRange(range); }; ViewModel.prototype.deduceModelPositionRelativeToViewPosition = function (viewAnchorPosition, deltaOffset, lineFeedCnt) { var modelAnchor = this.coordinatesConverter.convertViewPositionToModelPosition(viewAnchorPosition); if (this.model.getEOL().length === 2) { // This model uses CRLF, so the delta must take that into account if (deltaOffset < 0) { deltaOffset -= lineFeedCnt; } else { deltaOffset += lineFeedCnt; } } var modelAnchorOffset = this.model.getOffsetAt(modelAnchor); var resultOffset = modelAnchorOffset + deltaOffset; return this.model.getPositionAt(resultOffset); }; ViewModel.prototype.getEOL = function () { return this.model.getEOL(); }; ViewModel.prototype.getPlainTextToCopy = function (modelRanges, emptySelectionClipboard, forceCRLF) { var newLineCharacter = forceCRLF ? '\r\n' : this.model.getEOL(); modelRanges = modelRanges.slice(0); modelRanges.sort(range_1.Range.compareRangesUsingStarts); var hasEmptyRange = false; var hasNonEmptyRange = false; for (var _i = 0, modelRanges_1 = modelRanges; _i < modelRanges_1.length; _i++) { var range = modelRanges_1[_i]; if (range.isEmpty()) { hasEmptyRange = true; } else { hasNonEmptyRange = true; } } if (!hasNonEmptyRange) { // all ranges are empty if (!emptySelectionClipboard) { return ''; } var modelLineNumbers = modelRanges.map(function (r) { return r.startLineNumber; }); var result_1 = ''; for (var i = 0; i < modelLineNumbers.length; i++) { if (i > 0 && modelLineNumbers[i - 1] === modelLineNumbers[i]) { continue; } result_1 += this.model.getLineContent(modelLineNumbers[i]) + newLineCharacter; } return result_1; } if (hasEmptyRange && emptySelectionClipboard) { // mixed empty selections and non-empty selections var result_2 = []; var prevModelLineNumber = 0; for (var _a = 0, modelRanges_2 = modelRanges; _a < modelRanges_2.length; _a++) { var modelRange = modelRanges_2[_a]; var modelLineNumber = modelRange.startLineNumber; if (modelRange.isEmpty()) { if (modelLineNumber !== prevModelLineNumber) { result_2.push(this.model.getLineContent(modelLineNumber)); } } else { result_2.push(this.model.getValueInRange(modelRange, forceCRLF ? 2 /* CRLF */ : 0 /* TextDefined */)); } prevModelLineNumber = modelLineNumber; } return result_2.length === 1 ? result_2[0] : result_2; } var result = []; for (var _b = 0, modelRanges_3 = modelRanges; _b < modelRanges_3.length; _b++) { var modelRange = modelRanges_3[_b]; if (!modelRange.isEmpty()) { result.push(this.model.getValueInRange(modelRange, forceCRLF ? 2 /* CRLF */ : 0 /* TextDefined */)); } } return result.length === 1 ? result[0] : result; }; ViewModel.prototype.getRichTextToCopy = function (modelRanges, emptySelectionClipboard) { var languageId = this.model.getLanguageIdentifier(); if (languageId.id === 1 /* PlainText */) { return null; } if (modelRanges.length !== 1) { // no multiple selection support at this time return null; } var range = modelRanges[0]; if (range.isEmpty()) { if (!emptySelectionClipboard) { // nothing to copy return null; } var lineNumber = range.startLineNumber; range = new range_1.Range(lineNumber, this.model.getLineMinColumn(lineNumber), lineNumber, this.model.getLineMaxColumn(lineNumber)); } var fontInfo = this.configuration.options.get(34 /* fontInfo */); var colorMap = this._getColorMap(); var fontFamily = fontInfo.fontFamily === editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily ? fontInfo.fontFamily : "'" + fontInfo.fontFamily + "', " + editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily; return { mode: languageId.language, html: ("
    " + this._getHTMLToCopy(range, colorMap) + '
    ') }; }; ViewModel.prototype._getHTMLToCopy = function (modelRange, colorMap) { var startLineNumber = modelRange.startLineNumber; var startColumn = modelRange.startColumn; var endLineNumber = modelRange.endLineNumber; var endColumn = modelRange.endColumn; var tabSize = this.getTabSize(); var result = ''; for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { var lineTokens = this.model.getLineTokens(lineNumber); var lineContent = lineTokens.getLineContent(); var startOffset = (lineNumber === startLineNumber ? startColumn - 1 : 0); var endOffset = (lineNumber === endLineNumber ? endColumn - 1 : lineContent.length); if (lineContent === '') { result += '
    '; } else { result += textToHtmlTokenizer_1.tokenizeLineToHTML(lineContent, lineTokens.inflate(), colorMap, startOffset, endOffset, tabSize, platform.isWindows); } } return result; }; ViewModel.prototype._getColorMap = function () { var colorMap = modes_1.TokenizationRegistry.getColorMap(); var result = ['#000000']; if (colorMap) { for (var i = 1, len = colorMap.length; i < len; i++) { result[i] = color_1.Color.Format.CSS.formatHex(colorMap[i]); } } return result; }; return ViewModel; }(viewEvents.ViewEventEmitter)); exports.ViewModel = ViewModel; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[489/*vs/editor/contrib/documentSymbols/outlineModel*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,26/*vs/base/common/cancellation*/,87/*vs/base/common/collections*/,10/*vs/base/common/errors*/,38/*vs/base/common/map*/,17/*vs/editor/common/modes*/]), function (require, exports, arrays_1, cancellation_1, collections_1, errors_1, map_1, modes_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var TreeElement = /** @class */ (function () { function TreeElement() { } TreeElement.prototype.remove = function () { if (this.parent) { delete this.parent.children[this.id]; } }; TreeElement.findId = function (candidate, container) { // complex id-computation which contains the origin/extension, // the parent path, and some dedupe logic when names collide var candidateId; if (typeof candidate === 'string') { candidateId = container.id + "/" + candidate; } else { candidateId = container.id + "/" + candidate.name; if (container.children[candidateId] !== undefined) { candidateId = container.id + "/" + candidate.name + "_" + candidate.range.startLineNumber + "_" + candidate.range.startColumn; } } var id = candidateId; for (var i = 0; container.children[id] !== undefined; i++) { id = candidateId + "_" + i; } return id; }; TreeElement.empty = function (element) { for (var _key in element.children) { return false; } return true; }; return TreeElement; }()); exports.TreeElement = TreeElement; var OutlineElement = /** @class */ (function (_super) { __extends(OutlineElement, _super); function OutlineElement(id, parent, symbol) { var _this = _super.call(this) || this; _this.id = id; _this.parent = parent; _this.symbol = symbol; _this.children = Object.create(null); return _this; } return OutlineElement; }(TreeElement)); exports.OutlineElement = OutlineElement; var OutlineGroup = /** @class */ (function (_super) { __extends(OutlineGroup, _super); function OutlineGroup(id, parent, provider, providerIndex) { var _this = _super.call(this) || this; _this.id = id; _this.parent = parent; _this.provider = provider; _this.providerIndex = providerIndex; _this.children = Object.create(null); return _this; } return OutlineGroup; }(TreeElement)); exports.OutlineGroup = OutlineGroup; var MovingAverage = /** @class */ (function () { function MovingAverage() { this._n = 1; this._val = 0; } MovingAverage.prototype.update = function (value) { this._val = this._val + (value - this._val) / this._n; this._n += 1; return this; }; return MovingAverage; }()); var OutlineModel = /** @class */ (function (_super) { __extends(OutlineModel, _super); function OutlineModel(textModel) { var _this = _super.call(this) || this; _this.textModel = textModel; _this.id = 'root'; _this.parent = undefined; _this._groups = Object.create(null); _this.children = Object.create(null); _this.id = 'root'; _this.parent = undefined; return _this; } OutlineModel.create = function (textModel, token) { var _this = this; var key = this._keys.for(textModel, true); var data = OutlineModel._requests.get(key); if (!data) { var source = new cancellation_1.CancellationTokenSource(); data = { promiseCnt: 0, source: source, promise: OutlineModel._create(textModel, source.token), model: undefined, }; OutlineModel._requests.set(key, data); // keep moving average of request durations var now_1 = Date.now(); data.promise.then(function () { var key = _this._keys.for(textModel, false); var avg = _this._requestDurations.get(key); if (!avg) { avg = new MovingAverage(); _this._requestDurations.set(key, avg); } avg.update(Date.now() - now_1); }); } if (data.model) { // resolved -> return data return Promise.resolve(data.model); } // increase usage counter data.promiseCnt += 1; token.onCancellationRequested(function () { // last -> cancel provider request, remove cached promise if (--data.promiseCnt === 0) { data.source.cancel(); OutlineModel._requests.delete(key); } }); return new Promise(function (resolve, reject) { data.promise.then(function (model) { data.model = model; resolve(model); }, function (err) { OutlineModel._requests.delete(key); reject(err); }); }); }; OutlineModel._create = function (textModel, token) { var cts = new cancellation_1.CancellationTokenSource(token); var result = new OutlineModel(textModel); var provider = modes_1.DocumentSymbolProviderRegistry.ordered(textModel); var promises = provider.map(function (provider, index) { var id = TreeElement.findId("provider_" + index, result); var group = new OutlineGroup(id, result, provider, index); return Promise.resolve(provider.provideDocumentSymbols(result.textModel, cts.token)).then(function (result) { for (var _i = 0, _a = result || []; _i < _a.length; _i++) { var info = _a[_i]; OutlineModel._makeOutlineElement(info, group); } return group; }, function (err) { errors_1.onUnexpectedExternalError(err); return group; }).then(function (group) { if (!TreeElement.empty(group)) { result._groups[id] = group; } else { group.remove(); } }); }); var listener = modes_1.DocumentSymbolProviderRegistry.onDidChange(function () { var newProvider = modes_1.DocumentSymbolProviderRegistry.ordered(textModel); if (!arrays_1.equals(newProvider, provider)) { cts.cancel(); } }); return Promise.all(promises).then(function () { if (cts.token.isCancellationRequested && !token.isCancellationRequested) { return OutlineModel._create(textModel, token); } else { return result._compact(); } }).finally(function () { listener.dispose(); }); }; OutlineModel._makeOutlineElement = function (info, container) { var id = TreeElement.findId(info, container); var res = new OutlineElement(id, container, info); if (info.children) { for (var _i = 0, _a = info.children; _i < _a.length; _i++) { var childInfo = _a[_i]; OutlineModel._makeOutlineElement(childInfo, res); } } container.children[res.id] = res; }; OutlineModel.prototype._compact = function () { var count = 0; for (var key in this._groups) { var group = this._groups[key]; if (collections_1.first(group.children) === undefined) { // empty delete this._groups[key]; } else { count += 1; } } if (count !== 1) { // this.children = this._groups; } else { // adopt all elements of the first group var group = collections_1.first(this._groups); for (var key in group.children) { var child = group.children[key]; child.parent = this; this.children[child.id] = child; } } return this; }; OutlineModel._requestDurations = new map_1.LRUCache(50, 0.7); OutlineModel._requests = new map_1.LRUCache(9, 0.75); OutlineModel._keys = new /** @class */ (function () { function class_1() { this._counter = 1; this._data = new WeakMap(); } class_1.prototype.for = function (textModel, version) { return textModel.id + "/" + (version ? textModel.getVersionId() : '') + "/" + this._hash(modes_1.DocumentSymbolProviderRegistry.all(textModel)); }; class_1.prototype._hash = function (providers) { var result = ''; for (var _i = 0, providers_1 = providers; _i < providers_1.length; _i++) { var provider = providers_1[_i]; var n = this._data.get(provider); if (typeof n === 'undefined') { n = this._counter++; this._data.set(provider, n); } result += n; } return result; }; return class_1; }()); return OutlineModel; }(TreeElement)); exports.OutlineModel = OutlineModel; }); /*--------------------------------------------------------------------------------------------- * 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/editor/contrib/folding/foldingDecorations*/], __M([0/*require*/,1/*exports*/,30/*vs/editor/common/model/textModel*/]), function (require, exports, textModel_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var FoldingDecorationProvider = /** @class */ (function () { function FoldingDecorationProvider(editor) { this.editor = editor; this.autoHideFoldingControls = true; this.showFoldingHighlights = true; } FoldingDecorationProvider.prototype.getDecorationOption = function (isCollapsed) { if (isCollapsed) { return this.showFoldingHighlights ? FoldingDecorationProvider.COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION : FoldingDecorationProvider.COLLAPSED_VISUAL_DECORATION; } else if (this.autoHideFoldingControls) { return FoldingDecorationProvider.EXPANDED_AUTO_HIDE_VISUAL_DECORATION; } else { return FoldingDecorationProvider.EXPANDED_VISUAL_DECORATION; } }; FoldingDecorationProvider.prototype.deltaDecorations = function (oldDecorations, newDecorations) { return this.editor.deltaDecorations(oldDecorations, newDecorations); }; FoldingDecorationProvider.prototype.changeDecorations = function (callback) { return this.editor.changeDecorations(callback); }; FoldingDecorationProvider.COLLAPSED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, afterContentClassName: 'inline-folded', linesDecorationsClassName: 'codicon codicon-chevron-right' }); FoldingDecorationProvider.COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, afterContentClassName: 'inline-folded', className: 'folded-background', isWholeLine: true, linesDecorationsClassName: 'codicon codicon-chevron-right' }); FoldingDecorationProvider.EXPANDED_AUTO_HIDE_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, linesDecorationsClassName: 'codicon codicon-chevron-down' }); FoldingDecorationProvider.EXPANDED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, linesDecorationsClassName: 'codicon codicon-chevron-down alwaysShowFoldIcons' }); return FoldingDecorationProvider; }()); exports.FoldingDecorationProvider = FoldingDecorationProvider; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[491/*vs/editor/contrib/folding/indentRangeProvider*/], __M([0/*require*/,1/*exports*/,150/*vs/editor/contrib/folding/foldingRanges*/,30/*vs/editor/common/model/textModel*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, foldingRanges_1, textModel_1, languageConfigurationRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MAX_FOLDING_REGIONS_FOR_INDENT_LIMIT = 5000; exports.ID_INDENT_PROVIDER = 'indent'; var IndentRangeProvider = /** @class */ (function () { function IndentRangeProvider(editorModel) { this.editorModel = editorModel; this.id = exports.ID_INDENT_PROVIDER; } IndentRangeProvider.prototype.dispose = function () { }; IndentRangeProvider.prototype.compute = function (cancelationToken) { var foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(this.editorModel.getLanguageIdentifier().id); var offSide = foldingRules && !!foldingRules.offSide; var markers = foldingRules && foldingRules.markers; return Promise.resolve(computeRanges(this.editorModel, offSide, markers)); }; return IndentRangeProvider; }()); exports.IndentRangeProvider = IndentRangeProvider; // public only for testing var RangesCollector = /** @class */ (function () { function RangesCollector(foldingRangesLimit) { this._startIndexes = []; this._endIndexes = []; this._indentOccurrences = []; this._length = 0; this._foldingRangesLimit = foldingRangesLimit; } RangesCollector.prototype.insertFirst = function (startLineNumber, endLineNumber, indent) { if (startLineNumber > foldingRanges_1.MAX_LINE_NUMBER || endLineNumber > foldingRanges_1.MAX_LINE_NUMBER) { return; } var index = this._length; this._startIndexes[index] = startLineNumber; this._endIndexes[index] = endLineNumber; this._length++; if (indent < 1000) { this._indentOccurrences[indent] = (this._indentOccurrences[indent] || 0) + 1; } }; RangesCollector.prototype.toIndentRanges = function (model) { if (this._length <= this._foldingRangesLimit) { // reverse and create arrays of the exact length var startIndexes = new Uint32Array(this._length); var endIndexes = new Uint32Array(this._length); for (var 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 { var entries = 0; var maxIndent = this._indentOccurrences.length; for (var i = 0; i < this._indentOccurrences.length; i++) { var n = this._indentOccurrences[i]; if (n) { if (n + entries > this._foldingRangesLimit) { maxIndent = i; break; } entries += n; } } var tabSize = model.getOptions().tabSize; // reverse and create arrays of the exact length var startIndexes = new Uint32Array(this._foldingRangesLimit); var endIndexes = new Uint32Array(this._foldingRangesLimit); for (var i = this._length - 1, k = 0; i >= 0; i--) { var startIndex = this._startIndexes[i]; var lineContent = model.getLineContent(startIndex); var indent = textModel_1.TextModel.computeIndentLevel(lineContent, tabSize); if (indent < maxIndent || (indent === maxIndent && entries++ < this._foldingRangesLimit)) { startIndexes[k] = startIndex; endIndexes[k] = this._endIndexes[i]; k++; } } return new foldingRanges_1.FoldingRegions(startIndexes, endIndexes); } }; return RangesCollector; }()); exports.RangesCollector = RangesCollector; function computeRanges(model, offSide, markers, foldingRangesLimit) { if (foldingRangesLimit === void 0) { foldingRangesLimit = MAX_FOLDING_REGIONS_FOR_INDENT_LIMIT; } var tabSize = model.getOptions().tabSize; var result = new RangesCollector(foldingRangesLimit); var pattern = undefined; if (markers) { pattern = new RegExp("(" + markers.start.source + ")|(?:" + markers.end.source + ")"); } var previousRegions = []; var line = model.getLineCount() + 1; previousRegions.push({ indent: -1, endAbove: line, line: line }); // sentinel, to make sure there's at least one entry for (var line_1 = model.getLineCount(); line_1 > 0; line_1--) { var lineContent = model.getLineContent(line_1); var indent = textModel_1.TextModel.computeIndentLevel(lineContent, tabSize); var 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_1; } continue; // only whitespace } var m = void 0; if (pattern && (m = lineContent.match(pattern))) { // folding pattern match if (m[1]) { // start pattern match // discard all regions until the folding pattern var 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_1, previous.line, indent); previous.line = line_1; previous.indent = indent; previous.endAbove = line_1; continue; } else { // no end marker found, treat line as a regular line } } else { // end pattern match previousRegions.push({ indent: -2, endAbove: line_1, line: line_1 }); 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 var endLineNumber = previous.endAbove - 1; if (endLineNumber - line_1 >= 1) { // needs at east size 1 result.insertFirst(line_1, endLineNumber, indent); } } if (previous.indent === indent) { previous.endAbove = line_1; } else { // previous.indent < indent // new region with a bigger indent previousRegions.push({ indent: indent, endAbove: line_1, line: line_1 }); } } 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[492/*vs/editor/contrib/linesOperations/moveLinesCommand*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,211/*vs/editor/common/commands/shiftCommand*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,90/*vs/editor/common/modes/languageConfiguration*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/,385/*vs/editor/contrib/indentation/indentUtils*/]), function (require, exports, strings, shiftCommand_1, range_1, selection_1, languageConfiguration_1, languageConfigurationRegistry_1, indentUtils) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MoveLinesCommand = /** @class */ (function () { function MoveLinesCommand(selection, isMovingDown, autoIndent) { this._selection = selection; this._isMovingDown = isMovingDown; this._autoIndent = autoIndent; this._selectionId = null; this._moveEndLineSelectionShrink = false; } MoveLinesCommand.prototype.getEditOperations = function (model, builder) { var 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; var 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)); } var _a = model.getOptions(), tabSize = _a.tabSize, indentSize = _a.indentSize, insertSpaces = _a.insertSpaces; var indentConverter = this.buildIndentConverter(tabSize, indentSize, insertSpaces); var virtualModel = { getLineTokens: function (lineNumber) { return model.getLineTokens(lineNumber); }, getLanguageIdentifier: function () { return model.getLanguageIdentifier(); }, getLanguageIdAtPosition: function (lineNumber, column) { return model.getLanguageIdAtPosition(lineNumber, column); }, getLineContent: null, }; if (s.startLineNumber === s.endLineNumber && model.getLineMaxColumn(s.startLineNumber) === 1) { // Current line is empty var lineNumber = s.startLineNumber; var 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 { var movingLineNumber_1; var movingLineText = void 0; if (this._isMovingDown) { movingLineNumber_1 = s.endLineNumber + 1; movingLineText = model.getLineContent(movingLineNumber_1); // Delete line that needs to be moved builder.addEditOperation(new range_1.Range(movingLineNumber_1 - 1, model.getLineMaxColumn(movingLineNumber_1 - 1), movingLineNumber_1, model.getLineMaxColumn(movingLineNumber_1)), null); var insertingText_1 = movingLineText; if (this.shouldAutoIndent(model, s)) { var movingLineMatchResult = this.matchEnterRule(model, indentConverter, tabSize, movingLineNumber_1, s.startLineNumber - 1); // if s.startLineNumber - 1 matches onEnter rule, we still honor that. if (movingLineMatchResult !== null) { var oldIndentation = strings.getLeadingWhitespace(model.getLineContent(movingLineNumber_1)); var newSpaceCnt = movingLineMatchResult + indentUtils.getSpaceCnt(oldIndentation, tabSize); var newIndentation = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces); insertingText_1 = newIndentation + this.trimLeft(movingLineText); } else { // no enter rule matches, let's check indentatin rules then. virtualModel.getLineContent = function (lineNumber) { if (lineNumber === s.startLineNumber) { return model.getLineContent(movingLineNumber_1); } else { return model.getLineContent(lineNumber); } }; var indentOfMovingLine = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber_1, 1), s.startLineNumber, indentConverter); if (indentOfMovingLine !== null) { var oldIndentation = strings.getLeadingWhitespace(model.getLineContent(movingLineNumber_1)); var newSpaceCnt = indentUtils.getSpaceCnt(indentOfMovingLine, tabSize); var oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize); if (newSpaceCnt !== oldSpaceCnt) { var newIndentation = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces); insertingText_1 = 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_1 + '\n'); var ret = this.matchEnterRule(model, indentConverter, tabSize, s.startLineNumber, s.startLineNumber, insertingText_1); // 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 = function (lineNumber) { if (lineNumber === s.startLineNumber) { return insertingText_1; } else if (lineNumber >= s.startLineNumber + 1 && lineNumber <= s.endLineNumber + 1) { return model.getLineContent(lineNumber - 1); } else { return model.getLineContent(lineNumber); } }; var newIndentatOfMovingBlock = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber_1, 1), s.startLineNumber + 1, indentConverter); if (newIndentatOfMovingBlock !== null) { var oldIndentation = strings.getLeadingWhitespace(model.getLineContent(s.startLineNumber)); var newSpaceCnt = indentUtils.getSpaceCnt(newIndentatOfMovingBlock, tabSize); var oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize); if (newSpaceCnt !== oldSpaceCnt) { var 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_1 + '\n'); } } else { movingLineNumber_1 = s.startLineNumber - 1; movingLineText = model.getLineContent(movingLineNumber_1); // Delete line that needs to be moved builder.addEditOperation(new range_1.Range(movingLineNumber_1, 1, movingLineNumber_1 + 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 = function (lineNumber) { if (lineNumber === movingLineNumber_1) { return model.getLineContent(s.startLineNumber); } else { return model.getLineContent(lineNumber); } }; var 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. var indentOfFirstLine = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(s.startLineNumber, 1), movingLineNumber_1, indentConverter); if (indentOfFirstLine !== null) { // adjust the indentation of the moving block var oldIndent = strings.getLeadingWhitespace(model.getLineContent(s.startLineNumber)); var newSpaceCnt = indentUtils.getSpaceCnt(indentOfFirstLine, tabSize); var oldSpaceCnt = indentUtils.getSpaceCnt(oldIndent, tabSize); if (newSpaceCnt !== oldSpaceCnt) { var spaceCntOffset = newSpaceCnt - oldSpaceCnt; this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, spaceCntOffset); } } } } } } this._selectionId = builder.trackSelection(s); }; MoveLinesCommand.prototype.buildIndentConverter = function (tabSize, indentSize, insertSpaces) { return { shiftIndent: function (indentation) { return shiftCommand_1.ShiftCommand.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces); }, unshiftIndent: function (indentation) { return shiftCommand_1.ShiftCommand.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces); } }; }; MoveLinesCommand.prototype.matchEnterRule = function (model, indentConverter, tabSize, line, oneLineAbove, oneLineAboveText) { var validPrecedingLine = oneLineAbove; while (validPrecedingLine >= 1) { // ship empty lines as empty lines just inherit indentation var lineContent = void 0; if (validPrecedingLine === oneLineAbove && oneLineAboveText !== undefined) { lineContent = oneLineAboveText; } else { lineContent = model.getLineContent(validPrecedingLine); } var nonWhitespaceIdx = strings.lastNonWhitespaceIndex(lineContent); if (nonWhitespaceIdx >= 0) { break; } validPrecedingLine--; } if (validPrecedingLine < 1 || line > model.getLineCount()) { return null; } var maxColumn = model.getLineMaxColumn(validPrecedingLine); var enter = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(this._autoIndent, model, new range_1.Range(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn)); if (enter) { var 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; } var movingLineText = model.getLineContent(line); if (this.trimLeft(movingLineText).indexOf(this.trimLeft(enterPrefix)) >= 0) { var oldIndentation = strings.getLeadingWhitespace(model.getLineContent(line)); var newIndentation = strings.getLeadingWhitespace(enterPrefix); var indentMetadataOfMovelingLine = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentMetadata(model, line); if (indentMetadataOfMovelingLine !== null && indentMetadataOfMovelingLine & 2 /* DECREASE_MASK */) { newIndentation = indentConverter.unshiftIndent(newIndentation); } var newSpaceCnt = indentUtils.getSpaceCnt(newIndentation, tabSize); var oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize); return newSpaceCnt - oldSpaceCnt; } } return null; }; MoveLinesCommand.prototype.trimLeft = function (str) { return str.replace(/^\s+/, ''); }; MoveLinesCommand.prototype.shouldAutoIndent = function (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; } var languageAtSelectionStart = model.getLanguageIdAtPosition(selection.startLineNumber, 1); var languageAtSelectionEnd = model.getLanguageIdAtPosition(selection.endLineNumber, 1); if (languageAtSelectionStart !== languageAtSelectionEnd) { return false; } if (languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentRulesSupport(languageAtSelectionStart) === null) { return false; } return true; }; MoveLinesCommand.prototype.getIndentEditsOfMovingBlock = function (model, builder, s, tabSize, insertSpaces, offset) { for (var i = s.startLineNumber; i <= s.endLineNumber; i++) { var lineContent = model.getLineContent(i); var originalIndent = strings.getLeadingWhitespace(lineContent); var originalSpacesCnt = indentUtils.getSpaceCnt(originalIndent, tabSize); var newSpacesCnt = originalSpacesCnt + offset; var 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; } } } }; MoveLinesCommand.prototype.computeCursorState = function (model, helper) { var 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; }; return MoveLinesCommand; }()); 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[493/*vs/editor/contrib/zoneWidget/zoneWidget*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,104/*vs/base/browser/ui/sash/sash*/,27/*vs/base/common/color*/,127/*vs/base/common/idGenerator*/,2/*vs/base/common/lifecycle*/,31/*vs/base/common/objects*/,3/*vs/editor/common/core/range*/,30/*vs/editor/common/model/textModel*/,324/*vs/css!vs/editor/contrib/zoneWidget/zoneWidget*/]), function (require, exports, dom, sash_1, color_1, idGenerator_1, lifecycle_1, objects, range_1, textModel_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var defaultColor = new color_1.Color(new color_1.RGBA(0, 122, 204)); var defaultOptions = { showArrow: true, showFrame: true, className: '', frameColor: defaultColor, arrowColor: defaultColor, keepEditorSelection: false }; var WIDGET_ID = 'vs.editor.contrib.zoneWidget'; var ViewZoneDelegate = /** @class */ (function () { function ViewZoneDelegate(domNode, afterLineNumber, afterColumn, heightInLines, onDomNodeTop, onComputedHeight) { this.id = ''; // A valid zone id should be greater than 0 this.domNode = domNode; this.afterLineNumber = afterLineNumber; this.afterColumn = afterColumn; this.heightInLines = heightInLines; this._onDomNodeTop = onDomNodeTop; this._onComputedHeight = onComputedHeight; } ViewZoneDelegate.prototype.onDomNodeTop = function (top) { this._onDomNodeTop(top); }; ViewZoneDelegate.prototype.onComputedHeight = function (height) { this._onComputedHeight(height); }; return ViewZoneDelegate; }()); exports.ViewZoneDelegate = ViewZoneDelegate; var OverlayWidgetDelegate = /** @class */ (function () { function OverlayWidgetDelegate(id, domNode) { this._id = id; this._domNode = domNode; } OverlayWidgetDelegate.prototype.getId = function () { return this._id; }; OverlayWidgetDelegate.prototype.getDomNode = function () { return this._domNode; }; OverlayWidgetDelegate.prototype.getPosition = function () { return null; }; return OverlayWidgetDelegate; }()); exports.OverlayWidgetDelegate = OverlayWidgetDelegate; var Arrow = /** @class */ (function () { function Arrow(_editor) { this._editor = _editor; this._ruleName = Arrow._IdGenerator.nextId(); this._decorations = []; this._color = null; this._height = -1; // } Arrow.prototype.dispose = function () { this.hide(); dom.removeCSSRulesContainingSelector(this._ruleName); }; Object.defineProperty(Arrow.prototype, "color", { set: function (value) { if (this._color !== value) { this._color = value; this._updateStyle(); } }, enumerable: true, configurable: true }); Object.defineProperty(Arrow.prototype, "height", { set: function (value) { if (this._height !== value) { this._height = value; this._updateStyle(); } }, enumerable: true, configurable: true }); Arrow.prototype._updateStyle = function () { dom.removeCSSRulesContainingSelector(this._ruleName); dom.createCSSRule(".monaco-editor " + this._ruleName, "border-style: solid; border-color: transparent; border-bottom-color: " + this._color + "; border-width: " + this._height + "px; bottom: -" + this._height + "px; margin-left: -" + this._height + "px; "); }; Arrow.prototype.show = function (where) { this._decorations = this._editor.deltaDecorations(this._decorations, [{ range: range_1.Range.fromPositions(where), options: { className: this._ruleName, stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ } }]); }; Arrow.prototype.hide = function () { this._editor.deltaDecorations(this._decorations, []); }; Arrow._IdGenerator = new idGenerator_1.IdGenerator('.arrow-decoration-'); return Arrow; }()); var ZoneWidget = /** @class */ (function () { function ZoneWidget(editor, options) { var _this = this; if (options === void 0) { options = {}; } this._arrow = null; this._overlayWidget = null; this._resizeSash = null; this._positionMarkerId = []; this._viewZone = null; this._disposables = new lifecycle_1.DisposableStore(); this.container = null; this._isShowing = false; this.editor = editor; this.options = objects.deepClone(options); objects.mixin(this.options, defaultOptions, false); this.domNode = document.createElement('div'); if (!this.options.isAccessible) { this.domNode.setAttribute('aria-hidden', 'true'); this.domNode.setAttribute('role', 'presentation'); } this._disposables.add(this.editor.onDidLayoutChange(function (info) { var width = _this._getWidth(info); _this.domNode.style.width = width + 'px'; _this.domNode.style.left = _this._getLeft(info) + 'px'; _this._onWidth(width); })); } ZoneWidget.prototype.dispose = function () { var _this = this; if (this._overlayWidget) { this.editor.removeOverlayWidget(this._overlayWidget); this._overlayWidget = null; } if (this._viewZone) { this.editor.changeViewZones(function (accessor) { if (_this._viewZone) { accessor.removeZone(_this._viewZone.id); } _this._viewZone = null; }); } this.editor.deltaDecorations(this._positionMarkerId, []); this._positionMarkerId = []; this._disposables.dispose(); }; ZoneWidget.prototype.create = function () { dom.addClass(this.domNode, 'zone-widget'); if (this.options.className) { dom.addClass(this.domNode, this.options.className); } this.container = document.createElement('div'); dom.addClass(this.container, 'zone-widget-container'); this.domNode.appendChild(this.container); if (this.options.showArrow) { this._arrow = new Arrow(this.editor); this._disposables.add(this._arrow); } this._fillContainer(this.container); this._initSash(); this._applyStyles(); }; ZoneWidget.prototype.style = function (styles) { if (styles.frameColor) { this.options.frameColor = styles.frameColor; } if (styles.arrowColor) { this.options.arrowColor = styles.arrowColor; } this._applyStyles(); }; ZoneWidget.prototype._applyStyles = function () { if (this.container && this.options.frameColor) { var frameColor = this.options.frameColor.toString(); this.container.style.borderTopColor = frameColor; this.container.style.borderBottomColor = frameColor; } if (this._arrow && this.options.arrowColor) { var arrowColor = this.options.arrowColor.toString(); this._arrow.color = arrowColor; } }; ZoneWidget.prototype._getWidth = function (info) { return info.width - info.minimapWidth - info.verticalScrollbarWidth; }; ZoneWidget.prototype._getLeft = function (info) { // If minimap is to the left, we move beyond it if (info.minimapWidth > 0 && info.minimapLeft === 0) { return info.minimapWidth; } return 0; }; ZoneWidget.prototype._onViewZoneTop = function (top) { this.domNode.style.top = top + 'px'; }; ZoneWidget.prototype._onViewZoneHeight = function (height) { this.domNode.style.height = height + "px"; if (this.container) { var containerHeight = height - this._decoratingElementsHeight(); this.container.style.height = containerHeight + "px"; var layoutInfo = this.editor.getLayoutInfo(); this._doLayout(containerHeight, this._getWidth(layoutInfo)); } if (this._resizeSash) { this._resizeSash.layout(); } }; Object.defineProperty(ZoneWidget.prototype, "position", { get: function () { var id = this._positionMarkerId[0]; if (!id) { return undefined; } var model = this.editor.getModel(); if (!model) { return undefined; } var range = model.getDecorationRange(id); if (!range) { return undefined; } return range.getStartPosition(); }, enumerable: true, configurable: true }); ZoneWidget.prototype.show = function (rangeOrPos, heightInLines) { var range = range_1.Range.isIRange(rangeOrPos) ? range_1.Range.lift(rangeOrPos) : range_1.Range.fromPositions(rangeOrPos); this._isShowing = true; this._showImpl(range, heightInLines); this._isShowing = false; this._positionMarkerId = this.editor.deltaDecorations(this._positionMarkerId, [{ range: range, options: textModel_1.ModelDecorationOptions.EMPTY }]); }; ZoneWidget.prototype.hide = function () { var _this = this; if (this._viewZone) { this.editor.changeViewZones(function (accessor) { if (_this._viewZone) { accessor.removeZone(_this._viewZone.id); } }); this._viewZone = null; } if (this._overlayWidget) { this.editor.removeOverlayWidget(this._overlayWidget); this._overlayWidget = null; } if (this._arrow) { this._arrow.hide(); } }; ZoneWidget.prototype._decoratingElementsHeight = function () { var lineHeight = this.editor.getOption(49 /* lineHeight */); var result = 0; if (this.options.showArrow) { var arrowHeight = Math.round(lineHeight / 3); result += 2 * arrowHeight; } if (this.options.showFrame) { var frameThickness = Math.round(lineHeight / 9); result += 2 * frameThickness; } return result; }; ZoneWidget.prototype._showImpl = function (where, heightInLines) { var _this = this; var position = where.getStartPosition(); var layoutInfo = this.editor.getLayoutInfo(); var width = this._getWidth(layoutInfo); this.domNode.style.width = width + "px"; this.domNode.style.left = this._getLeft(layoutInfo) + 'px'; // Render the widget as zone (rendering) and widget (lifecycle) var viewZoneDomNode = document.createElement('div'); viewZoneDomNode.style.overflow = 'hidden'; var lineHeight = this.editor.getOption(49 /* lineHeight */); // adjust heightInLines to viewport var maxHeightInLines = (this.editor.getLayoutInfo().height / lineHeight) * 0.8; if (heightInLines >= maxHeightInLines) { heightInLines = maxHeightInLines; } var arrowHeight = 0; var frameThickness = 0; // Render the arrow one 1/3 of an editor line height if (this._arrow && this.options.showArrow) { arrowHeight = Math.round(lineHeight / 3); this._arrow.height = arrowHeight; this._arrow.show(position); } // Render the frame as 1/9 of an editor line height if (this.options.showFrame) { frameThickness = Math.round(lineHeight / 9); } // insert zone widget this.editor.changeViewZones(function (accessor) { if (_this._viewZone) { accessor.removeZone(_this._viewZone.id); } if (_this._overlayWidget) { _this.editor.removeOverlayWidget(_this._overlayWidget); _this._overlayWidget = null; } _this.domNode.style.top = '-1000px'; _this._viewZone = new ViewZoneDelegate(viewZoneDomNode, position.lineNumber, position.column, heightInLines, function (top) { return _this._onViewZoneTop(top); }, function (height) { return _this._onViewZoneHeight(height); }); _this._viewZone.id = accessor.addZone(_this._viewZone); _this._overlayWidget = new OverlayWidgetDelegate(WIDGET_ID + _this._viewZone.id, _this.domNode); _this.editor.addOverlayWidget(_this._overlayWidget); }); if (this.container && this.options.showFrame) { var width_1 = this.options.frameWidth ? this.options.frameWidth : frameThickness; this.container.style.borderTopWidth = width_1 + 'px'; this.container.style.borderBottomWidth = width_1 + 'px'; } var containerHeight = heightInLines * lineHeight - this._decoratingElementsHeight(); if (this.container) { this.container.style.top = arrowHeight + 'px'; this.container.style.height = containerHeight + 'px'; this.container.style.overflow = 'hidden'; } this._doLayout(containerHeight, width); if (!this.options.keepEditorSelection) { this.editor.setSelection(where); } var model = this.editor.getModel(); if (model) { var revealLine = where.endLineNumber + 1; if (revealLine <= model.getLineCount()) { // reveal line below the zone widget this.revealLine(revealLine, false); } else { // reveal last line atop this.revealLine(model.getLineCount(), true); } } }; ZoneWidget.prototype.revealLine = function (lineNumber, isLastLine) { if (isLastLine) { this.editor.revealLineInCenter(lineNumber, 0 /* Smooth */); } else { this.editor.revealLine(lineNumber, 0 /* Smooth */); } }; ZoneWidget.prototype.setCssClass = function (className, classToReplace) { if (!this.container) { return; } if (classToReplace) { this.container.classList.remove(classToReplace); } dom.addClass(this.container, className); }; ZoneWidget.prototype._onWidth = function (widthInPixel) { // implement in subclass }; ZoneWidget.prototype._doLayout = function (heightInPixel, widthInPixel) { // implement in subclass }; ZoneWidget.prototype._relayout = function (newHeightInLines) { var _this = this; if (this._viewZone && this._viewZone.heightInLines !== newHeightInLines) { this.editor.changeViewZones(function (accessor) { if (_this._viewZone) { _this._viewZone.heightInLines = newHeightInLines; accessor.layoutZone(_this._viewZone.id); } }); } }; // --- sash ZoneWidget.prototype._initSash = function () { var _this = this; if (this._resizeSash) { return; } this._resizeSash = this._disposables.add(new sash_1.Sash(this.domNode, this, { orientation: 1 /* HORIZONTAL */ })); if (!this.options.isResizeable) { this._resizeSash.hide(); this._resizeSash.state = 0 /* Disabled */; } var data; this._disposables.add(this._resizeSash.onDidStart(function (e) { if (_this._viewZone) { data = { startY: e.startY, heightInLines: _this._viewZone.heightInLines, }; } })); this._disposables.add(this._resizeSash.onDidEnd(function () { data = undefined; })); this._disposables.add(this._resizeSash.onDidChange(function (evt) { if (data) { var lineDelta = (evt.currentY - data.startY) / _this.editor.getOption(49 /* lineHeight */); var roundedLineDelta = lineDelta < 0 ? Math.ceil(lineDelta) : Math.floor(lineDelta); var newHeightInLines = data.heightInLines + roundedLineDelta; if (newHeightInLines > 5 && newHeightInLines < 35) { _this._relayout(newHeightInLines); } } })); }; ZoneWidget.prototype.getHorizontalSashLeft = function () { return 0; }; ZoneWidget.prototype.getHorizontalSashTop = function () { return (this.domNode.style.height === null ? 0 : parseInt(this.domNode.style.height)) - (this._decoratingElementsHeight() / 2); }; ZoneWidget.prototype.getHorizontalSashWidth = function () { var layoutInfo = this.editor.getLayoutInfo(); return layoutInfo.width - layoutInfo.minimapWidth; }; return ZoneWidget; }()); exports.ZoneWidget = ZoneWidget; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[216/*vs/editor/standalone/common/monarch/monarchLexer*/], __M([0/*require*/,1/*exports*/,107/*vs/editor/common/core/token*/,17/*vs/editor/common/modes*/,63/*vs/editor/common/modes/nullMode*/,203/*vs/editor/standalone/common/monarch/monarchCommon*/]), function (require, exports, token_1, modes, nullMode_1, monarchCommon) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CACHE_STACK_DEPTH = 5; /** * Reuse the same stack elements up to a certain depth. */ var MonarchStackElementFactory = /** @class */ (function () { function MonarchStackElementFactory(maxCacheDepth) { this._maxCacheDepth = maxCacheDepth; this._entries = Object.create(null); } MonarchStackElementFactory.create = function (parent, state) { return this._INSTANCE.create(parent, state); }; MonarchStackElementFactory.prototype.create = function (parent, state) { if (parent !== null && parent.depth >= this._maxCacheDepth) { // no caching above a certain depth return new MonarchStackElement(parent, state); } var stackElementId = MonarchStackElement.getStackElementId(parent); if (stackElementId.length > 0) { stackElementId += '|'; } stackElementId += state; var 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); return MonarchStackElementFactory; }()); var MonarchStackElement = /** @class */ (function () { function MonarchStackElement(parent, state) { this.parent = parent; this.state = state; this.depth = (this.parent ? this.parent.depth : 0) + 1; } MonarchStackElement.getStackElementId = function (element) { var result = ''; while (element !== null) { if (result.length > 0) { result += '|'; } result += element.state; element = element.parent; } return result; }; MonarchStackElement._equals = function (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; }; MonarchStackElement.prototype.equals = function (other) { return MonarchStackElement._equals(this, other); }; MonarchStackElement.prototype.push = function (state) { return MonarchStackElementFactory.create(this, state); }; MonarchStackElement.prototype.pop = function () { return this.parent; }; MonarchStackElement.prototype.popall = function () { var result = this; while (result.parent) { result = result.parent; } return result; }; MonarchStackElement.prototype.switchTo = function (state) { return MonarchStackElementFactory.create(this.parent, state); }; return MonarchStackElement; }()); var EmbeddedModeData = /** @class */ (function () { function EmbeddedModeData(modeId, state) { this.modeId = modeId; this.state = state; } EmbeddedModeData.prototype.equals = function (other) { return (this.modeId === other.modeId && this.state.equals(other.state)); }; EmbeddedModeData.prototype.clone = function () { var stateClone = this.state.clone(); // save an object if (stateClone === this.state) { return this; } return new EmbeddedModeData(this.modeId, this.state); }; return EmbeddedModeData; }()); /** * Reuse the same line states up to a certain depth. */ var MonarchLineStateFactory = /** @class */ (function () { function MonarchLineStateFactory(maxCacheDepth) { this._maxCacheDepth = maxCacheDepth; this._entries = Object.create(null); } MonarchLineStateFactory.create = function (stack, embeddedModeData) { return this._INSTANCE.create(stack, embeddedModeData); }; MonarchLineStateFactory.prototype.create = function (stack, embeddedModeData) { if (embeddedModeData !== null) { // no caching when embedding return new MonarchLineState(stack, embeddedModeData); } if (stack !== null && stack.depth >= this._maxCacheDepth) { // no caching above a certain depth return new MonarchLineState(stack, embeddedModeData); } var stackElementId = MonarchStackElement.getStackElementId(stack); var 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); return MonarchLineStateFactory; }()); var MonarchLineState = /** @class */ (function () { function MonarchLineState(stack, embeddedModeData) { this.stack = stack; this.embeddedModeData = embeddedModeData; } MonarchLineState.prototype.clone = function () { var embeddedModeDataClone = this.embeddedModeData ? this.embeddedModeData.clone() : null; // save an object if (embeddedModeDataClone === this.embeddedModeData) { return this; } return MonarchLineStateFactory.create(this.stack, this.embeddedModeData); }; MonarchLineState.prototype.equals = function (other) { if (!(other instanceof MonarchLineState)) { return false; } if (!this.stack.equals(other.stack)) { return false; } if (this.embeddedModeData === null && other.embeddedModeData === null) { return true; } if (this.embeddedModeData === null || other.embeddedModeData === null) { return false; } return this.embeddedModeData.equals(other.embeddedModeData); }; return MonarchLineState; }()); var MonarchClassicTokensCollector = /** @class */ (function () { function MonarchClassicTokensCollector() { this._tokens = []; this._language = null; this._lastTokenType = null; this._lastTokenLanguage = null; } MonarchClassicTokensCollector.prototype.enterMode = function (startOffset, modeId) { this._language = modeId; }; MonarchClassicTokensCollector.prototype.emit = function (startOffset, type) { if (this._lastTokenType === type && this._lastTokenLanguage === this._language) { return; } this._lastTokenType = type; this._lastTokenLanguage = this._language; this._tokens.push(new token_1.Token(startOffset, type, this._language)); }; MonarchClassicTokensCollector.prototype.nestedModeTokenize = function (embeddedModeLine, embeddedModeData, offsetDelta) { var nestedModeId = embeddedModeData.modeId; var embeddedModeState = embeddedModeData.state; var nestedModeTokenizationSupport = modes.TokenizationRegistry.get(nestedModeId); if (!nestedModeTokenizationSupport) { this.enterMode(offsetDelta, nestedModeId); this.emit(offsetDelta, ''); return embeddedModeState; } var nestedResult = nestedModeTokenizationSupport.tokenize(embeddedModeLine, embeddedModeState, offsetDelta); this._tokens = this._tokens.concat(nestedResult.tokens); this._lastTokenType = null; this._lastTokenLanguage = null; this._language = null; return nestedResult.endState; }; MonarchClassicTokensCollector.prototype.finalize = function (endState) { return new token_1.TokenizationResult(this._tokens, endState); }; return MonarchClassicTokensCollector; }()); var MonarchModernTokensCollector = /** @class */ (function () { function MonarchModernTokensCollector(modeService, theme) { this._modeService = modeService; this._theme = theme; this._prependTokens = null; this._tokens = []; this._currentLanguageId = 0 /* Null */; this._lastTokenMetadata = 0; } MonarchModernTokensCollector.prototype.enterMode = function (startOffset, modeId) { this._currentLanguageId = this._modeService.getLanguageIdentifier(modeId).id; }; MonarchModernTokensCollector.prototype.emit = function (startOffset, type) { var metadata = this._theme.match(this._currentLanguageId, type); if (this._lastTokenMetadata === metadata) { return; } this._lastTokenMetadata = metadata; this._tokens.push(startOffset); this._tokens.push(metadata); }; MonarchModernTokensCollector._merge = function (a, b, c) { var aLen = (a !== null ? a.length : 0); var bLen = b.length; var 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; } var result = new Uint32Array(aLen + bLen + cLen); if (a !== null) { result.set(a); } for (var i = 0; i < bLen; i++) { result[aLen + i] = b[i]; } if (c !== null) { result.set(c, aLen + bLen); } return result; }; MonarchModernTokensCollector.prototype.nestedModeTokenize = function (embeddedModeLine, embeddedModeData, offsetDelta) { var nestedModeId = embeddedModeData.modeId; var embeddedModeState = embeddedModeData.state; var nestedModeTokenizationSupport = modes.TokenizationRegistry.get(nestedModeId); if (!nestedModeTokenizationSupport) { this.enterMode(offsetDelta, nestedModeId); this.emit(offsetDelta, ''); return embeddedModeState; } var nestedResult = nestedModeTokenizationSupport.tokenize2(embeddedModeLine, embeddedModeState, offsetDelta); this._prependTokens = MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, nestedResult.tokens); this._tokens = []; this._currentLanguageId = 0; this._lastTokenMetadata = 0; return nestedResult.endState; }; MonarchModernTokensCollector.prototype.finalize = function (endState) { return new token_1.TokenizationResult2(MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, null), endState); }; return MonarchModernTokensCollector; }()); var MonarchTokenizer = /** @class */ (function () { function MonarchTokenizer(modeService, standaloneThemeService, modeId, lexer) { var _this = this; this._modeService = modeService; this._standaloneThemeService = standaloneThemeService; this._modeId = modeId; this._lexer = lexer; this._embeddedModes = Object.create(null); this.embeddedLoaded = Promise.resolve(undefined); // Set up listening for embedded modes var emitting = false; this._tokenizationRegistryListener = modes.TokenizationRegistry.onDidChange(function (e) { if (emitting) { return; } var isOneOfMyEmbeddedModes = false; for (var i = 0, len = e.changedLanguages.length; i < len; i++) { var language = e.changedLanguages[i]; if (_this._embeddedModes[language]) { isOneOfMyEmbeddedModes = true; break; } } if (isOneOfMyEmbeddedModes) { emitting = true; modes.TokenizationRegistry.fire([_this._modeId]); emitting = false; } }); } MonarchTokenizer.prototype.dispose = function () { this._tokenizationRegistryListener.dispose(); }; MonarchTokenizer.prototype.getLoadStatus = function () { var promises = []; for (var nestedModeId in this._embeddedModes) { var tokenizationSupport = modes.TokenizationRegistry.get(nestedModeId); if (tokenizationSupport) { // The nested mode is already loaded if (tokenizationSupport instanceof MonarchTokenizer) { var nestedModeStatus = tokenizationSupport.getLoadStatus(); if (nestedModeStatus.loaded === false) { promises.push(nestedModeStatus.promise); } } continue; } var tokenizationSupportPromise = modes.TokenizationRegistry.getPromise(nestedModeId); if (tokenizationSupportPromise) { // The nested mode is in the process of being loaded promises.push(tokenizationSupportPromise); } } if (promises.length === 0) { return { loaded: true }; } return { loaded: false, promise: Promise.all(promises).then(function (_) { return undefined; }) }; }; MonarchTokenizer.prototype.getInitialState = function () { var rootState = MonarchStackElementFactory.create(null, this._lexer.start); return MonarchLineStateFactory.create(rootState, null); }; MonarchTokenizer.prototype.tokenize = function (line, lineState, offsetDelta) { var tokensCollector = new MonarchClassicTokensCollector(); var endLineState = this._tokenize(line, lineState, offsetDelta, tokensCollector); return tokensCollector.finalize(endLineState); }; MonarchTokenizer.prototype.tokenize2 = function (line, lineState, offsetDelta) { var tokensCollector = new MonarchModernTokensCollector(this._modeService, this._standaloneThemeService.getTheme().tokenTheme); var endLineState = this._tokenize(line, lineState, offsetDelta, tokensCollector); return tokensCollector.finalize(endLineState); }; MonarchTokenizer.prototype._tokenize = function (line, lineState, offsetDelta, collector) { if (lineState.embeddedModeData) { return this._nestedTokenize(line, lineState, offsetDelta, collector); } else { return this._myTokenize(line, lineState, offsetDelta, collector); } }; MonarchTokenizer.prototype._findLeavingNestedModeOffset = function (line, state) { var 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); } } var popOffset = -1; var hasEmbeddedPopRule = false; for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) { var rule = rules_1[_i]; if (!monarchCommon.isIAction(rule.action) || rule.action.nextEmbedded !== '@pop') { continue; } hasEmbeddedPopRule = true; var regex = rule.regex; var regexSource = rule.regex.source; if (regexSource.substr(0, 4) === '^(?:' && regexSource.substr(regexSource.length - 1, 1) === ')') { regex = new RegExp(regexSource.substr(4, regexSource.length - 5), regex.ignoreCase ? 'i' : ''); } var 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; }; MonarchTokenizer.prototype._nestedTokenize = function (line, lineState, offsetDelta, tokensCollector) { var popOffset = this._findLeavingNestedModeOffset(line, lineState); if (popOffset === -1) { // tokenization will not leave nested mode var nestedEndState = tokensCollector.nestedModeTokenize(line, lineState.embeddedModeData, offsetDelta); return MonarchLineStateFactory.create(lineState.stack, new EmbeddedModeData(lineState.embeddedModeData.modeId, nestedEndState)); } var nestedModeLine = line.substring(0, popOffset); if (nestedModeLine.length > 0) { // tokenize with the nested mode tokensCollector.nestedModeTokenize(nestedModeLine, lineState.embeddedModeData, offsetDelta); } var restOfTheLine = line.substring(popOffset); return this._myTokenize(restOfTheLine, lineState, offsetDelta + popOffset, tokensCollector); }; MonarchTokenizer.prototype._safeRuleName = function (rule) { if (rule) { return rule.name; } return '(unknown)'; }; MonarchTokenizer.prototype._myTokenize = function (line, lineState, offsetDelta, tokensCollector) { tokensCollector.enterMode(offsetDelta, this._modeId); var lineLength = line.length; var embeddedModeData = lineState.embeddedModeData; var stack = lineState.stack; var pos = 0; var groupMatching = null; // See https://github.com/Microsoft/monaco-editor/issues/1235: // Evaluate rules at least once for an empty line var forceEvaluation = true; while (forceEvaluation || pos < lineLength) { var pos0 = pos; var stackLen0 = stack.depth; var groupLen0 = groupMatching ? groupMatching.groups.length : 0; var state = stack.state; var matches = null; var matched = null; var action = null; var rule = null; var enteringEmbeddedMode = null; // check if we need to process group matches first if (groupMatching) { matches = groupMatching.matches; var 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 var 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 var restOfLine = line.substr(pos); for (var _i = 0, rules_2 = rules; _i < rules_2.length; _i++) { var rule_1 = rules_2[_i]; if (pos === 0 || !rule_1.matchOnlyAtLineStart) { matches = restOfLine.match(rule_1.regex); if (matches) { matched = matches[0]; action = rule_1.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); } var result = null; // set the result: either a string or an array of actions if (typeof action === 'string' || Array.isArray(action)) { result = action; } else if (action.group) { result = action.group; } else if (action.token !== null && action.token !== undefined) { // do $n replacements? if (action.tokenSubst) { result = monarchCommon.substituteMatches(this._lexer, action.token, matched, matches, state); } else { result = action.token; } // enter embedded mode? if (action.nextEmbedded) { if (action.nextEmbedded === '@pop') { if (!embeddedModeData) { throw monarchCommon.createError(this._lexer, 'cannot pop embedded mode if not inside one'); } embeddedModeData = null; } else if (embeddedModeData) { throw monarchCommon.createError(this._lexer, 'cannot enter embedded mode from within an embedded mode'); } else { enteringEmbeddedMode = monarchCommon.substituteMatches(this._lexer, action.nextEmbedded, matched, matches, state); } } // state transformations if (action.goBack) { // back up the stream.. pos = Math.max(0, pos - action.goBack); } if (action.switchTo && typeof action.switchTo === 'string') { var 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 { var 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)); } // 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)); } var totalLen = 0; for (var 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 (var 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 = ''; } // 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 var tokenType = null; if (monarchCommon.isString(result) && result.indexOf('@brackets') === 0) { var rest = result.substr('@brackets'.length); var 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 { var token = (result === '' ? '' : result + this._lexer.tokenPostfix); tokenType = monarchCommon.sanitize(token); } tokensCollector.emit(pos0 + offsetDelta, tokenType); } if (enteringEmbeddedMode !== null) { // substitute language alias to known modes to support syntax highlighting var enteringEmbeddedModeId = this._modeService.getModeIdForLanguageName(enteringEmbeddedMode); if (enteringEmbeddedModeId) { enteringEmbeddedMode = enteringEmbeddedModeId; } var embeddedModeData_1 = this._getNestedEmbeddedModeData(enteringEmbeddedMode); if (pos < lineLength) { // there is content from the embedded mode on this line var restOfLine = line.substr(pos); return this._nestedTokenize(restOfLine, MonarchLineStateFactory.create(stack, embeddedModeData_1), offsetDelta + pos, tokensCollector); } else { return MonarchLineStateFactory.create(stack, embeddedModeData_1); } } } return MonarchLineStateFactory.create(stack, embeddedModeData); }; MonarchTokenizer.prototype._getNestedEmbeddedModeData = function (mimetypeOrModeId) { var nestedModeId = this._locateMode(mimetypeOrModeId); if (nestedModeId) { var tokenizationSupport = modes.TokenizationRegistry.get(nestedModeId); if (tokenizationSupport) { return new EmbeddedModeData(nestedModeId, tokenizationSupport.getInitialState()); } } return new EmbeddedModeData(nestedModeId || nullMode_1.NULL_MODE_ID, nullMode_1.NULL_STATE); }; MonarchTokenizer.prototype._locateMode = function (mimetypeOrModeId) { if (!mimetypeOrModeId || !this._modeService.isRegisteredMode(mimetypeOrModeId)) { return null; } if (mimetypeOrModeId === this._modeId) { // embedding myself... return mimetypeOrModeId; } var modeId = this._modeService.getModeId(mimetypeOrModeId); if (modeId) { // Fire mode loading event this._modeService.triggerMode(modeId); this._embeddedModes[modeId] = true; } return modeId; }; return MonarchTokenizer; }()); 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); var brackets = lexer.brackets; for (var _i = 0, brackets_1 = brackets; _i < brackets_1.length; _i++) { var bracket = brackets_1[_i]; if (bracket.open === matched) { return { token: bracket.token, bracketType: 1 /* Open */ }; } else if (bracket.close === matched) { return { token: bracket.token, bracketType: -1 /* Close */ }; } } return null; } function createTokenizationSupport(modeService, standaloneThemeService, modeId, lexer) { return new MonarchTokenizer(modeService, standaloneThemeService, modeId, lexer); } exports.createTokenizationSupport = createTokenizationSupport; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[494/*vs/editor/standalone/browser/colorizer*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,5/*vs/base/common/strings*/,93/*vs/editor/common/core/lineTokens*/,17/*vs/editor/common/modes*/,110/*vs/editor/common/viewLayout/viewLineRenderer*/,69/*vs/editor/common/viewModel/viewModel*/,216/*vs/editor/standalone/common/monarch/monarchLexer*/]), function (require, exports, async_1, strings, lineTokens_1, modes_1, viewLineRenderer_1, viewModel_1, monarchLexer_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Colorizer = /** @class */ (function () { function Colorizer() { } Colorizer.colorizeElement = function (themeService, modeService, domNode, options) { options = options || {}; var theme = options.theme || 'vs'; var mimeType = options.mimeType || domNode.getAttribute('lang') || domNode.getAttribute('data-lang'); if (!mimeType) { console.error('Mode not detected'); return Promise.resolve(); } themeService.setTheme(theme); var text = domNode.firstChild ? domNode.firstChild.nodeValue : ''; domNode.className += ' ' + theme; var render = function (str) { domNode.innerHTML = str; }; return this.colorize(modeService, text || '', mimeType, options).then(render, function (err) { return console.error(err); }); }; Colorizer.colorize = function (modeService, text, mimeType, options) { var tabSize = 4; if (options && typeof options.tabSize === 'number') { tabSize = options.tabSize; } if (strings.startsWithUTF8BOM(text)) { text = text.substr(1); } var lines = text.split(/\r\n|\r|\n/); var language = modeService.getModeId(mimeType); if (!language) { return Promise.resolve(_fakeColorize(lines, tabSize)); } // Send out the event to create the mode modeService.triggerMode(language); var tokenizationSupport = modes_1.TokenizationRegistry.get(language); if (tokenizationSupport) { return _colorize(lines, tabSize, tokenizationSupport); } var tokenizationSupportPromise = modes_1.TokenizationRegistry.getPromise(language); if (tokenizationSupportPromise) { // A tokenizer will be registered soon return new Promise(function (resolve, reject) { tokenizationSupportPromise.then(function (tokenizationSupport) { _colorize(lines, tabSize, tokenizationSupport).then(resolve, reject); }, reject); }); } return new Promise(function (resolve, reject) { var listener = null; var timeout = null; var execute = function () { if (listener) { listener.dispose(); listener = null; } if (timeout) { timeout.dispose(); timeout = null; } var tokenizationSupport = modes_1.TokenizationRegistry.get(language); if (tokenizationSupport) { _colorize(lines, tabSize, tokenizationSupport).then(resolve, reject); return; } resolve(_fakeColorize(lines, tabSize)); }; // wait 500ms for mode to load, then give up timeout = new async_1.TimeoutTimer(); timeout.cancelAndSet(execute, 500); listener = modes_1.TokenizationRegistry.onDidChange(function (e) { if (e.changedLanguages.indexOf(language) >= 0) { execute(); } }); }); }; Colorizer.colorizeLine = function (line, mightContainNonBasicASCII, mightContainRTL, tokens, tabSize) { if (tabSize === void 0) { tabSize = 4; } var isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, mightContainNonBasicASCII); var containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, mightContainRTL); var renderResult = viewLineRenderer_1.renderViewLine2(new viewLineRenderer_1.RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, tokens, [], tabSize, 0, 0, 0, -1, 'none', false, false, null)); return renderResult.html; }; Colorizer.colorizeModelLine = function (model, lineNumber, tabSize) { if (tabSize === void 0) { tabSize = 4; } var content = model.getLineContent(lineNumber); model.forceTokenization(lineNumber); var tokens = model.getLineTokens(lineNumber); var inflatedTokens = tokens.inflate(); return this.colorizeLine(content, model.mightContainNonBasicASCII(), model.mightContainRTL(), inflatedTokens, tabSize); }; return Colorizer; }()); exports.Colorizer = Colorizer; function _colorize(lines, tabSize, tokenizationSupport) { return new Promise(function (c, e) { var execute = function () { var result = _actualColorize(lines, tabSize, tokenizationSupport); if (tokenizationSupport instanceof monarchLexer_1.MonarchTokenizer) { var status_1 = tokenizationSupport.getLoadStatus(); if (status_1.loaded === false) { status_1.promise.then(execute, e); return; } } c(result); }; execute(); }); } function _fakeColorize(lines, tabSize) { var html = []; var defaultMetadata = ((0 /* None */ << 11 /* FONT_STYLE_OFFSET */) | (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */) | (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0; var tokens = new Uint32Array(2); tokens[0] = 0; tokens[1] = defaultMetadata; for (var i = 0, length_1 = lines.length; i < length_1; i++) { var line = lines[i]; tokens[0] = line.length; var lineTokens = new lineTokens_1.LineTokens(tokens, line); var isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true); var containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true); var renderResult = viewLineRenderer_1.renderViewLine2(new viewLineRenderer_1.RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens, [], tabSize, 0, 0, 0, -1, 'none', false, false, null)); html = html.concat(renderResult.html); html.push('
    '); } return html.join(''); } function _actualColorize(lines, tabSize, tokenizationSupport) { var html = []; var state = tokenizationSupport.getInitialState(); for (var i = 0, length_2 = lines.length; i < length_2; i++) { var line = lines[i]; var tokenizeResult = tokenizationSupport.tokenize2(line, state, 0); lineTokens_1.LineTokens.convertToEndOffset(tokenizeResult.tokens, line.length); var lineTokens = new lineTokens_1.LineTokens(tokenizeResult.tokens, line); var isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true); var containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true); var renderResult = viewLineRenderer_1.renderViewLine2(new viewLineRenderer_1.RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens.inflate(), [], tabSize, 0, 0, 0, -1, 'none', false, false, null)); html = html.concat(renderResult.html); html.push('
    '); state = tokenizeResult.endState; } return html.join(''); } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[94/*vs/editor/standalone/common/standaloneThemeService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IStandaloneThemeService = instantiation_1.createDecorator('themeService'); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[162/*vs/platform/clipboard/common/clipboardService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IClipboardService = 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. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[29/*vs/platform/commands/common/commands*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/types*/,11/*vs/platform/instantiation/common/instantiation*/,4/*vs/base/common/event*/,76/*vs/base/common/linkedList*/,38/*vs/base/common/map*/]), function (require, exports, lifecycle_1, types_1, instantiation_1, event_1, linkedList_1, map_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ICommandService = instantiation_1.createDecorator('commandService'); exports.CommandsRegistry = new /** @class */ (function () { function class_1() { this._commands = new Map(); this._onDidRegisterCommand = new event_1.Emitter(); this.onDidRegisterCommand = this._onDidRegisterCommand.event; } class_1.prototype.registerCommand = function (idOrCommand, handler) { var _this = this; if (!idOrCommand) { throw new Error("invalid command"); } if (typeof idOrCommand === 'string') { if (!handler) { throw new Error("invalid command"); } return this.registerCommand({ id: idOrCommand, handler: handler }); } // add argument validation if rich command metadata is provided if (idOrCommand.description) { var constraints_1 = []; for (var _i = 0, _a = idOrCommand.description.args; _i < _a.length; _i++) { var arg = _a[_i]; constraints_1.push(arg.constraint); } var actualHandler_1 = idOrCommand.handler; idOrCommand.handler = function (accessor) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } types_1.validateConstraints(args, constraints_1); return actualHandler_1.apply(void 0, __spreadArrays([accessor], args)); }; } // find a place to store the command var id = idOrCommand.id; var commands = this._commands.get(id); if (!commands) { commands = new linkedList_1.LinkedList(); this._commands.set(id, commands); } var removeFn = commands.unshift(idOrCommand); var ret = lifecycle_1.toDisposable(function () { removeFn(); var 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; }; class_1.prototype.registerCommandAlias = function (oldId, newId) { return exports.CommandsRegistry.registerCommand(oldId, function (accessor) { var _a; var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } return (_a = accessor.get(exports.ICommandService)).executeCommand.apply(_a, __spreadArrays([newId], args)); }); }; class_1.prototype.getCommand = function (id) { var list = this._commands.get(id); if (!list || list.isEmpty()) { return undefined; } return list.iterator().next().value; }; class_1.prototype.getCommands = function () { var result = new Map(); for (var _i = 0, _a = map_1.keys(this._commands); _i < _a.length; _i++) { var key = _a[_i]; var command = this.getCommand(key); if (command) { result.set(key, command); } } return result; }; return class_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[495/*vs/editor/contrib/links/getLinks*/], __M([0/*require*/,1/*exports*/,26/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,25/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,17/*vs/editor/common/modes*/,49/*vs/editor/common/services/modelService*/,29/*vs/platform/commands/common/commands*/,2/*vs/base/common/lifecycle*/,19/*vs/base/common/arrays*/]), function (require, exports, cancellation_1, errors_1, uri_1, range_1, modes_1, modelService_1, commands_1, lifecycle_1, arrays_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Link = /** @class */ (function () { function Link(link, provider) { this._link = link; this._provider = provider; } Link.prototype.toJSON = function () { return { range: this.range, url: this.url, tooltip: this.tooltip }; }; Object.defineProperty(Link.prototype, "range", { get: function () { return this._link.range; }, enumerable: true, configurable: true }); Object.defineProperty(Link.prototype, "url", { get: function () { return this._link.url; }, enumerable: true, configurable: true }); Object.defineProperty(Link.prototype, "tooltip", { get: function () { return this._link.tooltip; }, enumerable: true, configurable: true }); Link.prototype.resolve = function (token) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { if (this._link.url) { return [2 /*return*/, this._link.url]; } if (typeof this._provider.resolveLink === 'function') { return [2 /*return*/, Promise.resolve(this._provider.resolveLink(this._link, token)).then(function (value) { _this._link = value || _this._link; if (_this._link.url) { // recurse return _this.resolve(token); } return Promise.reject(new Error('missing')); })]; } return [2 /*return*/, Promise.reject(new Error('missing'))]; }); }); }; return Link; }()); exports.Link = Link; var LinksList = /** @class */ (function (_super) { __extends(LinksList, _super); function LinksList(tuples) { var _this = _super.call(this) || this; var links = []; var _loop_1 = function (list, provider) { // merge all links var newLinks = list.links.map(function (link) { return new Link(link, provider); }); links = LinksList._union(links, newLinks); // register disposables if (lifecycle_1.isDisposable(provider)) { this_1._register(provider); } }; var this_1 = this; for (var _i = 0, tuples_1 = tuples; _i < tuples_1.length; _i++) { var _a = tuples_1[_i], list = _a[0], provider = _a[1]; _loop_1(list, provider); } _this.links = links; return _this; } LinksList._union = function (oldLinks, newLinks) { // reunite oldLinks with newLinks and remove duplicates var result = []; var oldIndex; var oldLen; var newIndex; var newLen; for (oldIndex = 0, newIndex = 0, oldLen = oldLinks.length, newLen = newLinks.length; oldIndex < oldLen && newIndex < newLen;) { var oldLink = oldLinks[oldIndex]; var newLink = newLinks[newIndex]; if (range_1.Range.areIntersectingOrTouching(oldLink.range, newLink.range)) { // Remove the oldLink oldIndex++; continue; } var 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; }; return LinksList; }(lifecycle_1.Disposable)); exports.LinksList = LinksList; function getLinks(model, token) { var lists = []; // ask all providers for links in parallel var promises = modes_1.LinkProviderRegistry.ordered(model).reverse().map(function (provider, i) { return Promise.resolve(provider.provideLinks(model, token)).then(function (result) { if (result) { lists[i] = [result, provider]; } }, errors_1.onUnexpectedExternalError); }); return Promise.all(promises).then(function () { var result = new LinksList(arrays_1.coalesce(lists)); if (!token.isCancellationRequested) { return result; } result.dispose(); return new LinksList([]); }); } exports.getLinks = getLinks; commands_1.CommandsRegistry.registerCommand('_executeLinkProvider', function (accessor) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } return __awaiter(void 0, void 0, void 0, function () { var uri, model, list, result; return __generator(this, function (_a) { switch (_a.label) { case 0: uri = args[0]; if (!(uri instanceof uri_1.URI)) { return [2 /*return*/, []]; } model = accessor.get(modelService_1.IModelService).getModel(uri); if (!model) { return [2 /*return*/, []]; } return [4 /*yield*/, getLinks(model, cancellation_1.CancellationToken.None)]; case 1: list = _a.sent(); if (!list) { return [2 /*return*/, []]; } result = list.links.slice(0); list.dispose(); return [2 /*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[496/*vs/editor/contrib/quickOpen/quickOpen*/], __M([0/*require*/,1/*exports*/,25/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,49/*vs/editor/common/services/modelService*/,26/*vs/base/common/cancellation*/,84/*vs/editor/common/services/resolverService*/,489/*vs/editor/contrib/documentSymbols/outlineModel*/,87/*vs/base/common/collections*/,29/*vs/platform/commands/common/commands*/,21/*vs/base/common/types*/]), function (require, exports, uri_1, range_1, modelService_1, cancellation_1, resolverService_1, outlineModel_1, collections_1, commands_1, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function getDocumentSymbols(document, flat, token) { return __awaiter(this, void 0, void 0, function () { var model, roots, _i, _a, child, flatEntries; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, outlineModel_1.OutlineModel.create(document, token)]; case 1: model = _b.sent(); roots = []; for (_i = 0, _a = collections_1.values(model.children); _i < _a.length; _i++) { child = _a[_i]; if (child instanceof outlineModel_1.OutlineElement) { roots.push(child.symbol); } else { roots.push.apply(roots, collections_1.values(child.children).map(function (child) { return child.symbol; })); } } flatEntries = []; if (token.isCancellationRequested) { return [2 /*return*/, flatEntries]; } if (flat) { flatten(flatEntries, roots, ''); } else { flatEntries = roots; } return [2 /*return*/, flatEntries.sort(compareEntriesUsingStart)]; } }); }); } exports.getDocumentSymbols = getDocumentSymbols; function compareEntriesUsingStart(a, b) { return range_1.Range.compareRangesUsingStarts(a.range, b.range); } function flatten(bucket, entries, overrideContainerLabel) { for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { var entry = entries_1[_i]; 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, }); if (entry.children) { flatten(bucket, entry.children, entry.name); } } } commands_1.CommandsRegistry.registerCommand('_executeDocumentSymbolProvider', function (accessor) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } return __awaiter(this, void 0, void 0, function () { var resource, model, reference; return __generator(this, function (_a) { switch (_a.label) { case 0: resource = args[0]; types_1.assertType(uri_1.URI.isUri(resource)); model = accessor.get(modelService_1.IModelService).getModel(resource); if (model) { return [2 /*return*/, getDocumentSymbols(model, false, cancellation_1.CancellationToken.None)]; } return [4 /*yield*/, accessor.get(resolverService_1.ITextModelService).createModelReference(resource)]; case 1: reference = _a.sent(); _a.label = 2; case 2: _a.trys.push([2, , 4, 5]); return [4 /*yield*/, getDocumentSymbols(reference.object.textEditorModel, false, cancellation_1.CancellationToken.None)]; case 3: return [2 /*return*/, _a.sent()]; case 4: reference.dispose(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }); }); /*--------------------------------------------------------------------------------------------- * 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/platform/contextkey/common/contextkey*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, strings_1, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ContextKeyExpr = /** @class */ (function () { function ContextKeyExpr() { } ContextKeyExpr.has = function (key) { return ContextKeyDefinedExpr.create(key); }; ContextKeyExpr.equals = function (key, value) { return ContextKeyEqualsExpr.create(key, value); }; ContextKeyExpr.regex = function (key, value) { return ContextKeyRegexExpr.create(key, value); }; ContextKeyExpr.not = function (key) { return ContextKeyNotExpr.create(key); }; ContextKeyExpr.and = function () { var expr = []; for (var _i = 0; _i < arguments.length; _i++) { expr[_i] = arguments[_i]; } return ContextKeyAndExpr.create(expr); }; ContextKeyExpr.or = function () { var expr = []; for (var _i = 0; _i < arguments.length; _i++) { expr[_i] = arguments[_i]; } return ContextKeyOrExpr.create(expr); }; ContextKeyExpr.deserialize = function (serialized, strict) { if (strict === void 0) { strict = false; } if (!serialized) { return undefined; } return this._deserializeOrExpression(serialized, strict); }; ContextKeyExpr._deserializeOrExpression = function (serialized, strict) { var _this = this; var pieces = serialized.split('||'); return ContextKeyOrExpr.create(pieces.map(function (p) { return _this._deserializeAndExpression(p, strict); })); }; ContextKeyExpr._deserializeAndExpression = function (serialized, strict) { var _this = this; var pieces = serialized.split('&&'); return ContextKeyAndExpr.create(pieces.map(function (p) { return _this._deserializeOne(p, strict); })); }; ContextKeyExpr._deserializeOne = function (serializedOne, strict) { serializedOne = serializedOne.trim(); if (serializedOne.indexOf('!=') >= 0) { var pieces = serializedOne.split('!='); return ContextKeyNotEqualsExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict)); } if (serializedOne.indexOf('==') >= 0) { var pieces = serializedOne.split('=='); return ContextKeyEqualsExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict)); } if (serializedOne.indexOf('=~') >= 0) { var pieces = serializedOne.split('=~'); return ContextKeyRegexExpr.create(pieces[0].trim(), this._deserializeRegexValue(pieces[1], strict)); } if (/^\!\s*/.test(serializedOne)) { return ContextKeyNotExpr.create(serializedOne.substr(1).trim()); } return ContextKeyDefinedExpr.create(serializedOne); }; ContextKeyExpr._deserializeValue = function (serializedValue, strict) { serializedValue = serializedValue.trim(); if (serializedValue === 'true') { return true; } if (serializedValue === 'false') { return false; } var m = /^'([^']*)'$/.exec(serializedValue); if (m) { return m[1].trim(); } return serializedValue; }; ContextKeyExpr._deserializeRegexValue = function (serializedValue, strict) { if (strings_1.isFalsyOrWhitespace(serializedValue)) { if (strict) { throw new Error('missing regexp-value for =~-expression'); } else { console.warn('missing regexp-value for =~-expression'); } return null; } var start = serializedValue.indexOf('/'); var 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; } var value = serializedValue.slice(start + 1, end); var 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; } }; return ContextKeyExpr; }()); exports.ContextKeyExpr = ContextKeyExpr; function cmp(a, b) { var aType = a.getType(); var bType = b.getType(); if (aType !== bType) { return aType - bType; } switch (aType) { case 1 /* Defined */: return a.cmp(b); case 2 /* Not */: return a.cmp(b); case 3 /* Equals */: return a.cmp(b); case 4 /* NotEquals */: return a.cmp(b); case 6 /* Regex */: return a.cmp(b); case 7 /* NotRegex */: return a.cmp(b); case 5 /* And */: return a.cmp(b); default: throw new Error('Unknown ContextKeyExpr!'); } } var ContextKeyDefinedExpr = /** @class */ (function () { function ContextKeyDefinedExpr(key) { this.key = key; } ContextKeyDefinedExpr.create = function (key) { return new ContextKeyDefinedExpr(key); }; ContextKeyDefinedExpr.prototype.getType = function () { return 1 /* Defined */; }; ContextKeyDefinedExpr.prototype.cmp = function (other) { if (this.key < other.key) { return -1; } if (this.key > other.key) { return 1; } return 0; }; ContextKeyDefinedExpr.prototype.equals = function (other) { if (other instanceof ContextKeyDefinedExpr) { return (this.key === other.key); } return false; }; ContextKeyDefinedExpr.prototype.evaluate = function (context) { return (!!context.getValue(this.key)); }; ContextKeyDefinedExpr.prototype.keys = function () { return [this.key]; }; ContextKeyDefinedExpr.prototype.negate = function () { return ContextKeyNotExpr.create(this.key); }; return ContextKeyDefinedExpr; }()); exports.ContextKeyDefinedExpr = ContextKeyDefinedExpr; var ContextKeyEqualsExpr = /** @class */ (function () { function ContextKeyEqualsExpr(key, value) { this.key = key; this.value = value; } ContextKeyEqualsExpr.create = function (key, value) { if (typeof value === 'boolean') { if (value) { return ContextKeyDefinedExpr.create(key); } return ContextKeyNotExpr.create(key); } return new ContextKeyEqualsExpr(key, value); }; ContextKeyEqualsExpr.prototype.getType = function () { return 3 /* Equals */; }; ContextKeyEqualsExpr.prototype.cmp = function (other) { if (this.key < other.key) { return -1; } if (this.key > other.key) { return 1; } if (this.value < other.value) { return -1; } if (this.value > other.value) { return 1; } return 0; }; ContextKeyEqualsExpr.prototype.equals = function (other) { if (other instanceof ContextKeyEqualsExpr) { return (this.key === other.key && this.value === other.value); } return false; }; ContextKeyEqualsExpr.prototype.evaluate = function (context) { // Intentional == // eslint-disable-next-line eqeqeq return (context.getValue(this.key) == this.value); }; ContextKeyEqualsExpr.prototype.keys = function () { return [this.key]; }; ContextKeyEqualsExpr.prototype.negate = function () { return ContextKeyNotEqualsExpr.create(this.key, this.value); }; return ContextKeyEqualsExpr; }()); exports.ContextKeyEqualsExpr = ContextKeyEqualsExpr; var ContextKeyNotEqualsExpr = /** @class */ (function () { function ContextKeyNotEqualsExpr(key, value) { this.key = key; this.value = value; } ContextKeyNotEqualsExpr.create = function (key, value) { if (typeof value === 'boolean') { if (value) { return ContextKeyNotExpr.create(key); } return ContextKeyDefinedExpr.create(key); } return new ContextKeyNotEqualsExpr(key, value); }; ContextKeyNotEqualsExpr.prototype.getType = function () { return 4 /* NotEquals */; }; ContextKeyNotEqualsExpr.prototype.cmp = function (other) { if (this.key < other.key) { return -1; } if (this.key > other.key) { return 1; } if (this.value < other.value) { return -1; } if (this.value > other.value) { return 1; } return 0; }; ContextKeyNotEqualsExpr.prototype.equals = function (other) { if (other instanceof ContextKeyNotEqualsExpr) { return (this.key === other.key && this.value === other.value); } return false; }; ContextKeyNotEqualsExpr.prototype.evaluate = function (context) { // Intentional != // eslint-disable-next-line eqeqeq return (context.getValue(this.key) != this.value); }; ContextKeyNotEqualsExpr.prototype.keys = function () { return [this.key]; }; ContextKeyNotEqualsExpr.prototype.negate = function () { return ContextKeyEqualsExpr.create(this.key, this.value); }; return ContextKeyNotEqualsExpr; }()); exports.ContextKeyNotEqualsExpr = ContextKeyNotEqualsExpr; var ContextKeyNotExpr = /** @class */ (function () { function ContextKeyNotExpr(key) { this.key = key; } ContextKeyNotExpr.create = function (key) { return new ContextKeyNotExpr(key); }; ContextKeyNotExpr.prototype.getType = function () { return 2 /* Not */; }; ContextKeyNotExpr.prototype.cmp = function (other) { if (this.key < other.key) { return -1; } if (this.key > other.key) { return 1; } return 0; }; ContextKeyNotExpr.prototype.equals = function (other) { if (other instanceof ContextKeyNotExpr) { return (this.key === other.key); } return false; }; ContextKeyNotExpr.prototype.evaluate = function (context) { return (!context.getValue(this.key)); }; ContextKeyNotExpr.prototype.keys = function () { return [this.key]; }; ContextKeyNotExpr.prototype.negate = function () { return ContextKeyDefinedExpr.create(this.key); }; return ContextKeyNotExpr; }()); exports.ContextKeyNotExpr = ContextKeyNotExpr; var ContextKeyRegexExpr = /** @class */ (function () { function ContextKeyRegexExpr(key, regexp) { this.key = key; this.regexp = regexp; // } ContextKeyRegexExpr.create = function (key, regexp) { return new ContextKeyRegexExpr(key, regexp); }; ContextKeyRegexExpr.prototype.getType = function () { return 6 /* Regex */; }; ContextKeyRegexExpr.prototype.cmp = function (other) { if (this.key < other.key) { return -1; } if (this.key > other.key) { return 1; } var thisSource = this.regexp ? this.regexp.source : ''; var otherSource = other.regexp ? other.regexp.source : ''; if (thisSource < otherSource) { return -1; } if (thisSource > otherSource) { return 1; } return 0; }; ContextKeyRegexExpr.prototype.equals = function (other) { if (other instanceof ContextKeyRegexExpr) { var thisSource = this.regexp ? this.regexp.source : ''; var otherSource = other.regexp ? other.regexp.source : ''; return (this.key === other.key && thisSource === otherSource); } return false; }; ContextKeyRegexExpr.prototype.evaluate = function (context) { var value = context.getValue(this.key); return this.regexp ? this.regexp.test(value) : false; }; ContextKeyRegexExpr.prototype.keys = function () { return [this.key]; }; ContextKeyRegexExpr.prototype.negate = function () { return ContextKeyNotRegexExpr.create(this); }; return ContextKeyRegexExpr; }()); exports.ContextKeyRegexExpr = ContextKeyRegexExpr; var ContextKeyNotRegexExpr = /** @class */ (function () { function ContextKeyNotRegexExpr(_actual) { this._actual = _actual; // } ContextKeyNotRegexExpr.create = function (actual) { return new ContextKeyNotRegexExpr(actual); }; ContextKeyNotRegexExpr.prototype.getType = function () { return 7 /* NotRegex */; }; ContextKeyNotRegexExpr.prototype.cmp = function (other) { return this._actual.cmp(other._actual); }; ContextKeyNotRegexExpr.prototype.equals = function (other) { if (other instanceof ContextKeyNotRegexExpr) { return this._actual.equals(other._actual); } return false; }; ContextKeyNotRegexExpr.prototype.evaluate = function (context) { return !this._actual.evaluate(context); }; ContextKeyNotRegexExpr.prototype.keys = function () { return this._actual.keys(); }; ContextKeyNotRegexExpr.prototype.negate = function () { return this._actual; }; return ContextKeyNotRegexExpr; }()); exports.ContextKeyNotRegexExpr = ContextKeyNotRegexExpr; var ContextKeyAndExpr = /** @class */ (function () { function ContextKeyAndExpr(expr) { this.expr = expr; } ContextKeyAndExpr.create = function (_expr) { var expr = ContextKeyAndExpr._normalizeArr(_expr); if (expr.length === 0) { return undefined; } if (expr.length === 1) { return expr[0]; } return new ContextKeyAndExpr(expr); }; ContextKeyAndExpr.prototype.getType = function () { return 5 /* And */; }; ContextKeyAndExpr.prototype.cmp = function (other) { if (this.expr.length < other.expr.length) { return -1; } if (this.expr.length > other.expr.length) { return 1; } for (var i = 0, len = this.expr.length; i < len; i++) { var r = cmp(this.expr[i], other.expr[i]); if (r !== 0) { return r; } } return 0; }; ContextKeyAndExpr.prototype.equals = function (other) { if (other instanceof ContextKeyAndExpr) { if (this.expr.length !== other.expr.length) { return false; } for (var i = 0, len = this.expr.length; i < len; i++) { if (!this.expr[i].equals(other.expr[i])) { return false; } } return true; } return false; }; ContextKeyAndExpr.prototype.evaluate = function (context) { for (var i = 0, len = this.expr.length; i < len; i++) { if (!this.expr[i].evaluate(context)) { return false; } } return true; }; ContextKeyAndExpr._normalizeArr = function (arr) { var expr = []; if (arr) { for (var i = 0, len = arr.length; i < len; i++) { var e = arr[i]; if (!e) { continue; } if (e instanceof ContextKeyAndExpr) { expr = expr.concat(e.expr); continue; } if (e instanceof ContextKeyOrExpr) { // Not allowed, because we don't have parens! throw new Error("It is not allowed to have an or expression here due to lack of parens! For example \"a && (b||c)\" is not supported, use \"(a&&b) || (a&&c)\" instead."); } expr.push(e); } expr.sort(cmp); } return expr; }; ContextKeyAndExpr.prototype.keys = function () { var result = []; for (var _i = 0, _a = this.expr; _i < _a.length; _i++) { var expr = _a[_i]; result.push.apply(result, expr.keys()); } return result; }; ContextKeyAndExpr.prototype.negate = function () { var result = []; for (var _i = 0, _a = this.expr; _i < _a.length; _i++) { var expr = _a[_i]; result.push(expr.negate()); } return ContextKeyOrExpr.create(result); }; return ContextKeyAndExpr; }()); exports.ContextKeyAndExpr = ContextKeyAndExpr; var ContextKeyOrExpr = /** @class */ (function () { function ContextKeyOrExpr(expr) { this.expr = expr; } ContextKeyOrExpr.create = function (_expr) { var expr = ContextKeyOrExpr._normalizeArr(_expr); if (expr.length === 0) { return undefined; } if (expr.length === 1) { return expr[0]; } return new ContextKeyOrExpr(expr); }; ContextKeyOrExpr.prototype.getType = function () { return 8 /* Or */; }; ContextKeyOrExpr.prototype.equals = function (other) { if (other instanceof ContextKeyOrExpr) { if (this.expr.length !== other.expr.length) { return false; } for (var i = 0, len = this.expr.length; i < len; i++) { if (!this.expr[i].equals(other.expr[i])) { return false; } } return true; } return false; }; ContextKeyOrExpr.prototype.evaluate = function (context) { for (var i = 0, len = this.expr.length; i < len; i++) { if (this.expr[i].evaluate(context)) { return true; } } return false; }; ContextKeyOrExpr._normalizeArr = function (arr) { var expr = []; if (arr) { for (var i = 0, len = arr.length; i < len; i++) { var e = arr[i]; if (!e) { continue; } if (e instanceof ContextKeyOrExpr) { expr = expr.concat(e.expr); continue; } expr.push(e); } expr.sort(cmp); } return expr; }; ContextKeyOrExpr.prototype.keys = function () { var result = []; for (var _i = 0, _a = this.expr; _i < _a.length; _i++) { var expr = _a[_i]; result.push.apply(result, expr.keys()); } return result; }; ContextKeyOrExpr.prototype.negate = function () { var result = []; for (var _i = 0, _a = this.expr; _i < _a.length; _i++) { var expr = _a[_i]; result.push(expr.negate()); } var terminals = function (node) { if (node instanceof ContextKeyOrExpr) { return node.expr; } return [node]; }; // We don't support parens, so here we distribute the AND over the OR terminals // We always take the first 2 AND pairs and distribute them while (result.length > 1) { var LEFT = result.shift(); var RIGHT = result.shift(); var all = []; for (var _b = 0, _c = terminals(LEFT); _b < _c.length; _b++) { var left = _c[_b]; for (var _d = 0, _e = terminals(RIGHT); _d < _e.length; _d++) { var right = _e[_d]; all.push(ContextKeyExpr.and(left, right)); } } result.unshift(ContextKeyExpr.or.apply(ContextKeyExpr, all)); } return result[0]; }; return ContextKeyOrExpr; }()); exports.ContextKeyOrExpr = ContextKeyOrExpr; var RawContextKey = /** @class */ (function (_super) { __extends(RawContextKey, _super); function RawContextKey(key, defaultValue) { var _this = _super.call(this, key) || this; _this._defaultValue = defaultValue; return _this; } RawContextKey.prototype.bindTo = function (target) { return target.createKey(this.key, this._defaultValue); }; RawContextKey.prototype.getValue = function (target) { return target.getContextKeyValue(this.key); }; RawContextKey.prototype.toNegated = function () { return ContextKeyExpr.not(this.key); }; return RawContextKey; }(ContextKeyDefinedExpr)); exports.RawContextKey = RawContextKey; exports.IContextKeyService = instantiation_1.createDecorator('contextKeyService'); exports.SET_CONTEXT_COMMAND_ID = 'setContext'; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[23/*vs/editor/common/editorContextKeys*/], __M([0/*require*/,1/*exports*/,18/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, contextkey_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var EditorContextKeys; (function (EditorContextKeys) { EditorContextKeys.editorSimpleInput = new contextkey_1.RawContextKey('editorSimpleInput', false); /** * A context key that is set when the editor's text has focus (cursor is blinking). */ EditorContextKeys.editorTextFocus = new contextkey_1.RawContextKey('editorTextFocus', false); /** * 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); /** * A context key that is set when any editor input has focus (regular editor, repl input...). */ EditorContextKeys.textInputFocus = new contextkey_1.RawContextKey('textInputFocus', false); EditorContextKeys.readOnly = new contextkey_1.RawContextKey('editorReadonly', false); EditorContextKeys.writable = EditorContextKeys.readOnly.toNegated(); EditorContextKeys.hasNonEmptySelection = new contextkey_1.RawContextKey('editorHasSelection', false); EditorContextKeys.hasOnlyEmptySelection = EditorContextKeys.hasNonEmptySelection.toNegated(); EditorContextKeys.hasMultipleSelections = new contextkey_1.RawContextKey('editorHasMultipleSelections', false); EditorContextKeys.hasSingleSelection = EditorContextKeys.hasMultipleSelections.toNegated(); EditorContextKeys.tabMovesFocus = new contextkey_1.RawContextKey('editorTabMovesFocus', false); EditorContextKeys.tabDoesNotMoveFocus = EditorContextKeys.tabMovesFocus.toNegated(); EditorContextKeys.isInEmbeddedEditor = new contextkey_1.RawContextKey('isInEmbeddedEditor', false); EditorContextKeys.canUndo = new contextkey_1.RawContextKey('canUndo', false); EditorContextKeys.canRedo = new contextkey_1.RawContextKey('canRedo', false); // -- mode context keys EditorContextKeys.languageId = new contextkey_1.RawContextKey('editorLangId', ''); EditorContextKeys.hasCompletionItemProvider = new contextkey_1.RawContextKey('editorHasCompletionItemProvider', false); EditorContextKeys.hasCodeActionsProvider = new contextkey_1.RawContextKey('editorHasCodeActionsProvider', false); EditorContextKeys.hasCodeLensProvider = new contextkey_1.RawContextKey('editorHasCodeLensProvider', false); EditorContextKeys.hasDefinitionProvider = new contextkey_1.RawContextKey('editorHasDefinitionProvider', false); EditorContextKeys.hasDeclarationProvider = new contextkey_1.RawContextKey('editorHasDeclarationProvider', false); EditorContextKeys.hasImplementationProvider = new contextkey_1.RawContextKey('editorHasImplementationProvider', false); EditorContextKeys.hasTypeDefinitionProvider = new contextkey_1.RawContextKey('editorHasTypeDefinitionProvider', false); EditorContextKeys.hasHoverProvider = new contextkey_1.RawContextKey('editorHasHoverProvider', false); EditorContextKeys.hasDocumentHighlightProvider = new contextkey_1.RawContextKey('editorHasDocumentHighlightProvider', false); EditorContextKeys.hasDocumentSymbolProvider = new contextkey_1.RawContextKey('editorHasDocumentSymbolProvider', false); EditorContextKeys.hasReferenceProvider = new contextkey_1.RawContextKey('editorHasReferenceProvider', false); EditorContextKeys.hasRenameProvider = new contextkey_1.RawContextKey('editorHasRenameProvider', false); EditorContextKeys.hasSignatureHelpProvider = new contextkey_1.RawContextKey('editorHasSignatureHelpProvider', false); // -- mode context keys: formatting EditorContextKeys.hasDocumentFormattingProvider = new contextkey_1.RawContextKey('editorHasDocumentFormattingProvider', false); EditorContextKeys.hasDocumentSelectionFormattingProvider = new contextkey_1.RawContextKey('editorHasDocumentSelectionFormattingProvider', false); EditorContextKeys.hasMultipleDocumentFormattingProvider = new contextkey_1.RawContextKey('editorHasMultipleDocumentFormattingProvider', false); EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider = new contextkey_1.RawContextKey('editorHasMultipleDocumentSelectionFormattingProvider', false); })(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. *--------------------------------------------------------------------------------------------*/ var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; define(__m[497/*vs/editor/contrib/suggest/suggestAlternatives*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,18/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, lifecycle_1, contextkey_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var SuggestAlternatives = /** @class */ (function () { function SuggestAlternatives(_editor, contextKeyService) { this._editor = _editor; this._index = 0; this._ckOtherSuggestions = SuggestAlternatives.OtherSuggestions.bindTo(contextKeyService); } SuggestAlternatives.prototype.dispose = function () { this.reset(); }; SuggestAlternatives.prototype.reset = function () { this._ckOtherSuggestions.reset(); lifecycle_1.dispose(this._listener); this._model = undefined; this._acceptNext = undefined; this._ignore = false; }; SuggestAlternatives.prototype.set = function (_a, acceptNext) { var _this = this; var model = _a.model, index = _a.index; // no suggestions -> nothing to do if (model.items.length === 0) { this.reset(); return; } // no alternative suggestions -> nothing to do var 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(function () { if (!_this._ignore) { _this.reset(); } }); this._ckOtherSuggestions.set(true); }; SuggestAlternatives._moveIndex = function (fwd, model, index) { var 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; }; SuggestAlternatives.prototype.next = function () { this._move(true); }; SuggestAlternatives.prototype.prev = function () { this._move(false); }; SuggestAlternatives.prototype._move = function (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); return 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[498/*vs/editor/contrib/suggest/wordContextKey*/], __M([0/*require*/,1/*exports*/,18/*vs/platform/contextkey/common/contextkey*/,2/*vs/base/common/lifecycle*/]), function (require, exports, contextkey_1, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var WordContextKey = /** @class */ (function (_super) { __extends(WordContextKey, _super); function WordContextKey(_editor, contextKeyService) { var _this = _super.call(this) || this; _this._editor = _editor; _this._enabled = false; _this._ckAtEnd = WordContextKey.AtEnd.bindTo(contextKeyService); _this._register(_this._editor.onDidChangeConfiguration(function (e) { return e.hasChanged(94 /* tabCompletion */) && _this._update(); })); _this._update(); return _this; } WordContextKey.prototype.dispose = function () { _super.prototype.dispose.call(this); lifecycle_1.dispose(this._selectionListener); this._ckAtEnd.reset(); }; WordContextKey.prototype._update = function () { var _this = this; // only update this when tab completions are enabled var enabled = this._editor.getOption(94 /* tabCompletion */) === 'on'; if (this._enabled === enabled) { return; } this._enabled = enabled; if (this._enabled) { var checkForWordEnd = function () { if (!_this._editor.hasModel()) { _this._ckAtEnd.set(false); return; } var model = _this._editor.getModel(); var selection = _this._editor.getSelection(); var 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); return WordContextKey; }(lifecycle_1.Disposable)); exports.WordContextKey = WordContextKey; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[64/*vs/platform/accessibility/common/accessibility*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/,18/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, instantiation_1, contextkey_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IAccessibilityService = 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. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[65/*vs/platform/actions/common/actions*/], __M([0/*require*/,1/*exports*/,55/*vs/base/common/actions*/,11/*vs/platform/instantiation/common/instantiation*/,18/*vs/platform/contextkey/common/contextkey*/,29/*vs/platform/commands/common/commands*/,4/*vs/base/common/event*/]), function (require, exports, actions_1, instantiation_1, contextkey_1, commands_1, event_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isIMenuItem(item) { return item.command !== undefined; } exports.isIMenuItem = isIMenuItem; exports.IMenuService = instantiation_1.createDecorator('menuService'); exports.MenuRegistry = new /** @class */ (function () { function class_1() { this._commands = new Map(); this._menuItems = new Map(); this._onDidChangeMenu = new event_1.Emitter(); this.onDidChangeMenu = this._onDidChangeMenu.event; } class_1.prototype.addCommand = function (command) { var _this = this; this._commands.set(command.id, command); this._onDidChangeMenu.fire(0 /* CommandPalette */); return { dispose: function () { if (_this._commands.delete(command.id)) { _this._onDidChangeMenu.fire(0 /* CommandPalette */); } } }; }; class_1.prototype.getCommand = function (id) { return this._commands.get(id); }; class_1.prototype.getCommands = function () { var map = new Map(); this._commands.forEach(function (value, key) { return map.set(key, value); }); return map; }; class_1.prototype.appendMenuItem = function (id, item) { var _this = this; var array = this._menuItems.get(id); if (!array) { array = [item]; this._menuItems.set(id, array); } else { array.push(item); } this._onDidChangeMenu.fire(id); return { dispose: function () { var idx = array.indexOf(item); if (idx >= 0) { array.splice(idx, 1); _this._onDidChangeMenu.fire(id); } } }; }; class_1.prototype.getMenuItems = function (id) { var result = (this._menuItems.get(id) || []).slice(0); if (id === 0 /* CommandPalette */) { // CommandPalette is special because it shows // all commands by default this._appendImplicitItems(result); } return result; }; class_1.prototype._appendImplicitItems = function (result) { var set = new Set(); var temp = result.filter(function (item) { return isIMenuItem(item); }); for (var _i = 0, temp_1 = temp; _i < temp_1.length; _i++) { var _a = temp_1[_i], command = _a.command, alt = _a.alt; set.add(command.id); if (alt) { set.add(alt.id); } } this._commands.forEach(function (command, id) { if (!set.has(id)) { result.push({ command: command }); } }); }; return class_1; }()); var ExecuteCommandAction = /** @class */ (function (_super) { __extends(ExecuteCommandAction, _super); function ExecuteCommandAction(id, label, _commandService) { var _this = _super.call(this, id, label) || this; _this._commandService = _commandService; return _this; } ExecuteCommandAction.prototype.run = function () { var _a; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return (_a = this._commandService).executeCommand.apply(_a, __spreadArrays([this.id], args)); }; ExecuteCommandAction = __decorate([ __param(2, commands_1.ICommandService) ], ExecuteCommandAction); return ExecuteCommandAction; }(actions_1.Action)); exports.ExecuteCommandAction = ExecuteCommandAction; var SubmenuItemAction = /** @class */ (function (_super) { __extends(SubmenuItemAction, _super); function SubmenuItemAction(item) { var _this = this; typeof item.title === 'string' ? _this = _super.call(this, '', item.title, 'submenu') || this : _this = _super.call(this, '', item.title.value, 'submenu') || this; _this.item = item; return _this; } return SubmenuItemAction; }(actions_1.Action)); exports.SubmenuItemAction = SubmenuItemAction; var MenuItemAction = /** @class */ (function (_super) { __extends(MenuItemAction, _super); function MenuItemAction(item, alt, options, contextKeyService, commandService) { var _this = this; typeof item.title === 'string' ? _this = _super.call(this, item.id, item.title, commandService) || this : _this = _super.call(this, item.id, item.title.value, commandService) || this; _this._cssClass = undefined; _this._enabled = !item.precondition || contextKeyService.contextMatchesRules(item.precondition); _this._checked = Boolean(item.toggled && contextKeyService.contextMatchesRules(item.toggled)); _this._options = options || {}; _this.item = item; _this.alt = alt ? new MenuItemAction(alt, undefined, _this._options, contextKeyService, commandService) : undefined; return _this; } MenuItemAction.prototype.dispose = function () { if (this.alt) { this.alt.dispose(); } _super.prototype.dispose.call(this); }; MenuItemAction.prototype.run = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var runArgs = []; if (this._options.arg) { runArgs = __spreadArrays(runArgs, [this._options.arg]); } if (this._options.shouldForwardArgs) { runArgs = __spreadArrays(runArgs, args); } return _super.prototype.run.apply(this, runArgs); }; MenuItemAction = __decorate([ __param(3, contextkey_1.IContextKeyService), __param(4, commands_1.ICommandService) ], MenuItemAction); return MenuItemAction; }(ExecuteCommandAction)); exports.MenuItemAction = MenuItemAction; }); //#endregion /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[499/*vs/platform/actions/common/menuService*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,65/*vs/platform/actions/common/actions*/,29/*vs/platform/commands/common/commands*/,18/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, event_1, lifecycle_1, actions_1, commands_1, contextkey_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MenuService = /** @class */ (function () { function MenuService(_commandService) { this._commandService = _commandService; // } MenuService.prototype.createMenu = function (id, contextKeyService) { return new Menu(id, this._commandService, contextKeyService); }; MenuService = __decorate([ __param(0, commands_1.ICommandService) ], MenuService); return MenuService; }()); exports.MenuService = MenuService; var Menu = /** @class */ (function () { function Menu(_id, _commandService, _contextKeyService) { var _this = this; this._id = _id; this._commandService = _commandService; this._contextKeyService = _contextKeyService; this._onDidChange = new event_1.Emitter(); this._dispoables = new lifecycle_1.DisposableStore(); this._menuGroups = []; this._contextKeys = new Set(); this._build(); // rebuild this menu whenever the menu registry reports an // event for this MenuId this._dispoables.add(event_1.Event.debounce(event_1.Event.filter(actions_1.MenuRegistry.onDidChangeMenu, function (menuId) { return menuId === _this._id; }), function () { }, 50)(this._build, this)); // when context keys change we need to check if the menu also // has changed this._dispoables.add(event_1.Event.debounce(this._contextKeyService.onDidChangeContext, function (last, event) { return last || event.affectsSome(_this._contextKeys); }, 50)(function (e) { return e && _this._onDidChange.fire(undefined); }, this)); } Menu.prototype.dispose = function () { this._dispoables.dispose(); this._onDidChange.dispose(); }; Menu.prototype._build = function () { // reset this._menuGroups.length = 0; this._contextKeys.clear(); var menuItems = actions_1.MenuRegistry.getMenuItems(this._id); var group; menuItems.sort(Menu._compareMenuItems); for (var _i = 0, menuItems_1 = menuItems; _i < menuItems_1.length; _i++) { var item = menuItems_1[_i]; // group by groupId var groupName = item.group || ''; if (!group || group[0] !== groupName) { group = [groupName, []]; this._menuGroups.push(group); } group[1].push(item); // keep keys for eventing Menu._fillInKbExprKeys(item.when, this._contextKeys); // keep precondition keys for event if applicable if (actions_1.isIMenuItem(item) && item.command.precondition) { Menu._fillInKbExprKeys(item.command.precondition, this._contextKeys); } // keep toggled keys for event if applicable if (actions_1.isIMenuItem(item) && item.command.toggled) { Menu._fillInKbExprKeys(item.command.toggled, this._contextKeys); } } this._onDidChange.fire(this); }; Menu.prototype.getActions = function (options) { var result = []; for (var _i = 0, _a = this._menuGroups; _i < _a.length; _i++) { var group = _a[_i]; var id = group[0], items = group[1]; var activeActions = []; for (var _b = 0, items_1 = items; _b < items_1.length; _b++) { var item = items_1[_b]; if (this._contextKeyService.contextMatchesRules(item.when)) { var action = actions_1.isIMenuItem(item) ? new actions_1.MenuItemAction(item.command, item.alt, options, this._contextKeyService, this._commandService) : new actions_1.SubmenuItemAction(item); activeActions.push(action); } } if (activeActions.length > 0) { result.push([id, activeActions]); } } return result; }; Menu._fillInKbExprKeys = function (exp, set) { if (exp) { for (var _i = 0, _a = exp.keys(); _i < _a.length; _i++) { var key = _a[_i]; set.add(key); } } }; Menu._compareMenuItems = function (a, b) { var aGroup = a.group; var bGroup = b.group; if (aGroup !== bGroup) { // Falsy groups come last if (!aGroup) { return 1; } else if (!bGroup) { return -1; } // 'navigation' group comes first if (aGroup === 'navigation') { return -1; } else if (bGroup === 'navigation') { return 1; } // lexical sort for groups var value = aGroup.localeCompare(bGroup); if (value !== 0) { return value; } } // sort on priority - default is 0 var aPrio = a.order || 0; var bPrio = b.order || 0; if (aPrio < bPrio) { return -1; } else if (aPrio > bPrio) { return 1; } // sort on titles return Menu._compareTitles(actions_1.isIMenuItem(a) ? a.command.title : a.title, actions_1.isIMenuItem(b) ? b.command.title : b.title); }; Menu._compareTitles = function (a, b) { var aStr = typeof a === 'string' ? a : a.value; var bStr = typeof b === 'string' ? b : b.value; return aStr.localeCompare(bStr); }; Menu = __decorate([ __param(1, commands_1.ICommandService), __param(2, contextkey_1.IContextKeyService) ], Menu); return Menu; }()); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[66/*vs/platform/contextview/browser/contextView*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IContextViewService = instantiation_1.createDecorator('contextViewService'); exports.IContextMenuService = instantiation_1.createDecorator('contextMenuService'); }); define(__m[500/*vs/platform/dialogs/common/dialogs*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IDialogService = 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[115/*vs/platform/instantiation/common/serviceCollection*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ServiceCollection = /** @class */ (function () { function ServiceCollection() { var entries = []; for (var _i = 0; _i < arguments.length; _i++) { entries[_i] = arguments[_i]; } this._entries = new Map(); for (var _a = 0, entries_1 = entries; _a < entries_1.length; _a++) { var _b = entries_1[_a], id = _b[0], service = _b[1]; this.set(id, service); } } ServiceCollection.prototype.set = function (id, instanceOrDescriptor) { var result = this._entries.get(id); this._entries.set(id, instanceOrDescriptor); return result; }; ServiceCollection.prototype.has = function (id) { return this._entries.has(id); }; ServiceCollection.prototype.get = function (id) { return this._entries.get(id); }; return ServiceCollection; }()); 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. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[501/*vs/platform/instantiation/common/instantiationService*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,480/*vs/platform/instantiation/common/graph*/,209/*vs/platform/instantiation/common/descriptors*/,11/*vs/platform/instantiation/common/instantiation*/,115/*vs/platform/instantiation/common/serviceCollection*/,15/*vs/base/common/async*/]), function (require, exports, errors_1, graph_1, descriptors_1, instantiation_1, serviceCollection_1, async_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // TRACING var _enableTracing = false; var _canUseProxy = typeof Proxy === 'function'; var CyclicDependencyError = /** @class */ (function (_super) { __extends(CyclicDependencyError, _super); function CyclicDependencyError(graph) { var _this = _super.call(this, 'cyclic dependency between services') || this; _this.message = graph.toString(); return _this; } return CyclicDependencyError; }(Error)); var InstantiationService = /** @class */ (function () { function InstantiationService(services, strict, parent) { if (services === void 0) { services = new serviceCollection_1.ServiceCollection(); } if (strict === void 0) { strict = false; } this._services = services; this._strict = strict; this._parent = parent; this._services.set(instantiation_1.IInstantiationService, this); } InstantiationService.prototype.createChild = function (services) { return new InstantiationService(services, this._strict, this); }; InstantiationService.prototype.invokeFunction = function (fn) { var _this = this; var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var _trace = Trace.traceInvocation(fn); var _done = false; try { var accessor = { get: function (id, isOptional) { if (_done) { throw errors_1.illegalState('service accessor is only valid during the invocation of its target method'); } var result = _this._getOrCreateServiceInstance(id, _trace); if (!result && isOptional !== instantiation_1.optional) { throw new Error("[invokeFunction] unknown service '" + id + "'"); } return result; } }; return fn.apply(undefined, __spreadArrays([accessor], args)); } finally { _done = true; _trace.stop(); } }; InstantiationService.prototype.createInstance = function (ctorOrDescriptor) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } var _trace; var 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; }; InstantiationService.prototype._createInstance = function (ctor, args, _trace) { if (args === void 0) { args = []; } // arguments defined by service decorators var serviceDependencies = instantiation_1._util.getServiceDependencies(ctor).sort(function (a, b) { return a.index - b.index; }); var serviceArgs = []; for (var _i = 0, serviceDependencies_1 = serviceDependencies; _i < serviceDependencies_1.length; _i++) { var dependency = serviceDependencies_1[_i]; var 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); } var 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"); var 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.bind.apply(ctor, __spreadArrays([void 0], __spreadArrays(args, serviceArgs))))(); }; InstantiationService.prototype._setServiceInstance = function (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'); } }; InstantiationService.prototype._getServiceInstanceOrDescriptor = function (id) { var instanceOrDesc = this._services.get(id); if (!instanceOrDesc && this._parent) { return this._parent._getServiceInstanceOrDescriptor(id); } else { return instanceOrDesc; } }; InstantiationService.prototype._getOrCreateServiceInstance = function (id, _trace) { var thing = this._getServiceInstanceOrDescriptor(id); if (thing instanceof descriptors_1.SyncDescriptor) { return this._createAndCacheServiceInstance(id, thing, _trace.branch(id, true)); } else { _trace.branch(id, false); return thing; } }; InstantiationService.prototype._createAndCacheServiceInstance = function (id, desc, _trace) { var graph = new graph_1.Graph(function (data) { return data.id.toString(); }); var cycleCount = 0; var stack = [{ id: id, desc: desc, _trace: _trace }]; while (stack.length) { var item = stack.pop(); graph.lookupOrInsertNode(item); // a weak but working heuristic for cycle checks if (cycleCount++ > 150) { throw new CyclicDependencyError(graph); } // check all dependencies for existence and if they need to be created first for (var _i = 0, _a = instantiation_1._util.getServiceDependencies(item.desc.ctor); _i < _a.length; _i++) { var dependency = _a[_i]; var 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) { var d = { id: dependency.id, desc: instanceOrDesc, _trace: item._trace.branch(dependency.id, true) }; graph.insertEdge(item, d); stack.push(d); } } } while (true) { var 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 (var _b = 0, roots_1 = roots; _b < roots_1.length; _b++) { var data = roots_1[_b].data; // create instance and overwrite the service collections var 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); }; InstantiationService.prototype._createServiceInstanceWithOwner = function (id, ctor, args, supportsDelayedInstantiation, _trace) { if (args === void 0) { args = []; } 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); } }; InstantiationService.prototype._createServiceInstance = function (ctor, args, _supportsDelayedInstantiation, _trace) { var _this = this; if (args === void 0) { args = []; } if (!_supportsDelayedInstantiation || !_canUseProxy) { // eager instantiation or no support JS proxies (e.g. IE11) 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 var idle_1 = new async_1.IdleValue(function () { return _this._createInstance(ctor, args, _trace); }); return new Proxy(Object.create(null), { get: function (target, key) { if (key in target) { return target[key]; } var obj = idle_1.getValue(); var prop = obj[key]; if (typeof prop !== 'function') { return prop; } prop = prop.bind(obj); target[key] = prop; return prop; }, set: function (_target, p, value) { idle_1.getValue()[p] = value; return true; } }); } }; return InstantiationService; }()); exports.InstantiationService = InstantiationService; var Trace = /** @class */ (function () { function Trace(type, name) { this.type = type; this.name = name; this._start = Date.now(); this._dep = []; } Trace.traceInvocation = function (ctor) { return !_enableTracing ? Trace._None : new Trace(1 /* Invocation */, ctor.name || ctor.toString().substring(0, 42).replace(/\n/g, '')); }; Trace.traceCreation = function (ctor) { return !_enableTracing ? Trace._None : new Trace(0 /* Creation */, ctor.name); }; Trace.prototype.branch = function (id, first) { var child = new Trace(2 /* Branch */, id.toString()); this._dep.push([id, first, child]); return child; }; Trace.prototype.stop = function () { var dur = Date.now() - this._start; Trace._totals += dur; var causedCreation = false; function printChild(n, trace) { var res = []; var prefix = new Array(n + 1).join('\t'); for (var _i = 0, _a = trace._dep; _i < _a.length; _i++) { var _b = _a[_i], id = _b[0], first = _b[1], child = _b[2]; if (first && child) { causedCreation = true; res.push(prefix + "CREATES -> " + id); var nested = printChild(n + 1, child); if (nested) { res.push(nested); } } else { res.push(prefix + "uses -> " + id); } } return res.join('\n'); } var lines = [ (this.type === 0 /* Creation */ ? 'CREATE' : 'CALL') + " " + this.name, "" + printChild(1, this), "DONE, took " + dur.toFixed(2) + "ms (grand total " + Trace._totals.toFixed(2) + "ms)" ]; if (dur > 2 || causedCreation) { console.log(lines.join('\n')); } }; Trace._None = new /** @class */ (function (_super) { __extends(class_1, _super); function class_1() { return _super.call(this, -1, null) || this; } class_1.prototype.stop = function () { }; class_1.prototype.branch = function () { return this; }; return class_1; }(Trace)); Trace._totals = 0; return Trace; }()); }); //#endregion /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[502/*vs/platform/keybinding/common/abstractKeybindingService*/], __M([0/*require*/,1/*exports*/,473/*vs/nls!vs/platform/keybinding/common/abstractKeybindingService*/,15/*vs/base/common/async*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, nls, async_1, event_1, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var AbstractKeybindingService = /** @class */ (function (_super) { __extends(AbstractKeybindingService, _super); function AbstractKeybindingService(_contextKeyService, _commandService, _telemetryService, _notificationService) { var _this = _super.call(this) || this; _this._contextKeyService = _contextKeyService; _this._commandService = _commandService; _this._telemetryService = _telemetryService; _this._notificationService = _notificationService; _this._onDidUpdateKeybindings = _this._register(new event_1.Emitter()); _this._currentChord = null; _this._currentChordChecker = new async_1.IntervalTimer(); _this._currentChordStatusMessage = null; return _this; } Object.defineProperty(AbstractKeybindingService.prototype, "onDidUpdateKeybindings", { get: function () { return this._onDidUpdateKeybindings ? this._onDidUpdateKeybindings.event : event_1.Event.None; // Sinon stubbing walks properties on prototype }, enumerable: true, configurable: true }); AbstractKeybindingService.prototype.dispose = function () { _super.prototype.dispose.call(this); }; AbstractKeybindingService.prototype.getKeybindings = function () { return this._getResolver().getKeybindings(); }; AbstractKeybindingService.prototype.lookupKeybinding = function (commandId) { var result = this._getResolver().lookupPrimaryKeybinding(commandId); if (!result) { return undefined; } return result.resolvedKeybinding; }; AbstractKeybindingService.prototype.softDispatch = function (e, target) { var keybinding = this.resolveKeyboardEvent(e); if (keybinding.isChord()) { console.warn('Unexpected keyboard event mapped to a chord'); return null; } var firstPart = keybinding.getDispatchParts()[0]; if (firstPart === null) { // cannot be dispatched, probably only modifier keys return null; } var contextValue = this._contextKeyService.getContext(target); var currentChord = this._currentChord ? this._currentChord.keypress : null; return this._getResolver().resolve(contextValue, currentChord, firstPart); }; AbstractKeybindingService.prototype._enterChordMode = function (firstPart, keypressLabel) { var _this = this; this._currentChord = { keypress: firstPart, label: keypressLabel }; this._currentChordStatusMessage = this._notificationService.status(nls.localize(0, null, keypressLabel)); var chordEnterTime = Date.now(); this._currentChordChecker.cancelAndSet(function () { 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); }; AbstractKeybindingService.prototype._leaveChordMode = function () { if (this._currentChordStatusMessage) { this._currentChordStatusMessage.dispose(); this._currentChordStatusMessage = null; } this._currentChordChecker.cancel(); this._currentChord = null; }; AbstractKeybindingService.prototype._dispatch = function (e, target) { return this._doDispatch(this.resolveKeyboardEvent(e), target); }; AbstractKeybindingService.prototype._doDispatch = function (keybinding, target) { var _this = this; var shouldPreventDefault = false; if (keybinding.isChord()) { console.warn('Unexpected keyboard event mapped to a chord'); return false; } var firstPart = keybinding.getDispatchParts()[0]; if (firstPart === null) { // cannot be dispatched, probably only modifier keys return shouldPreventDefault; } var contextValue = this._contextKeyService.getContext(target); var currentChord = this._currentChord ? this._currentChord.keypress : null; var keypressLabel = keybinding.getLabel(); var resolveResult = this._getResolver().resolve(contextValue, currentChord, firstPart); 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, function (err) { return _this._notificationService.warn(err); }); } else { this._commandService.executeCommand(resolveResult.commandId, resolveResult.commandArgs).then(undefined, function (err) { return _this._notificationService.warn(err); }); } this._telemetryService.publicLog2('workbenchActionExecuted', { id: resolveResult.commandId, from: 'keybinding' }); } return shouldPreventDefault; }; AbstractKeybindingService.prototype.mightProducePrintableCharacter = function (event) { if (event.ctrlKey || event.metaKey) { // ignore ctrl/cmd-combination but not shift/alt-combinatios return false; } // weak check for certain ranges. this is properly implemented in a subclass // with access to the KeyboardMapperFactory. if ((event.keyCode >= 31 /* KEY_A */ && event.keyCode <= 56 /* KEY_Z */) || (event.keyCode >= 21 /* KEY_0 */ && event.keyCode <= 30 /* KEY_9 */)) { return true; } return false; }; return AbstractKeybindingService; }(lifecycle_1.Disposable)); exports.AbstractKeybindingService = AbstractKeybindingService; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[503/*vs/platform/keybinding/common/baseResolvedKeybinding*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,207/*vs/base/common/keybindingLabels*/,36/*vs/base/common/keyCodes*/]), function (require, exports, errors_1, keybindingLabels_1, keyCodes_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var BaseResolvedKeybinding = /** @class */ (function (_super) { __extends(BaseResolvedKeybinding, _super); function BaseResolvedKeybinding(os, parts) { var _this = _super.call(this) || this; if (parts.length === 0) { throw errors_1.illegalArgument("parts"); } _this._os = os; _this._parts = parts; return _this; } BaseResolvedKeybinding.prototype.getLabel = function () { var _this = this; return keybindingLabels_1.UILabelProvider.toLabel(this._os, this._parts, function (keybinding) { return _this._getLabel(keybinding); }); }; BaseResolvedKeybinding.prototype.getAriaLabel = function () { var _this = this; return keybindingLabels_1.AriaLabelProvider.toLabel(this._os, this._parts, function (keybinding) { return _this._getAriaLabel(keybinding); }); }; BaseResolvedKeybinding.prototype.isChord = function () { return (this._parts.length > 1); }; BaseResolvedKeybinding.prototype.getParts = function () { var _this = this; return this._parts.map(function (keybinding) { return _this._getPart(keybinding); }); }; BaseResolvedKeybinding.prototype._getPart = function (keybinding) { return new keyCodes_1.ResolvedKeybindingPart(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.metaKey, this._getLabel(keybinding), this._getAriaLabel(keybinding)); }; BaseResolvedKeybinding.prototype.getDispatchParts = function () { var _this = this; return this._parts.map(function (keybinding) { return _this._getDispatchPart(keybinding); }); }; return BaseResolvedKeybinding; }(keyCodes_1.ResolvedKeybinding)); 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[34/*vs/platform/keybinding/common/keybinding*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IKeybindingService = instantiation_1.createDecorator('keybindingService'); }); define(__m[217/*vs/platform/keybinding/common/keybindingResolver*/], __M([0/*require*/,1/*exports*/,18/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, contextkey_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var KeybindingResolver = /** @class */ (function () { function KeybindingResolver(defaultKeybindings, overrides) { this._defaultKeybindings = defaultKeybindings; this._defaultBoundCommands = new Map(); for (var i = 0, len = defaultKeybindings.length; i < len; i++) { var command = defaultKeybindings[i].command; if (command) { this._defaultBoundCommands.set(command, true); } } this._map = new Map(); this._lookupMap = new Map(); this._keybindings = KeybindingResolver.combine(defaultKeybindings, overrides); for (var i = 0, len = this._keybindings.length; i < len; i++) { var k = this._keybindings[i]; if (k.keypressParts.length === 0) { // unbound continue; } // TODO@chords this._addKeyPress(k.keypressParts[0], k); } } KeybindingResolver._isTargetedForRemoval = function (defaultKb, keypressFirstPart, keypressChordPart, command, when) { if (defaultKb.command !== command) { return false; } // TODO@chords if (keypressFirstPart && defaultKb.keypressParts[0] !== keypressFirstPart) { return false; } // TODO@chords if (keypressChordPart && defaultKb.keypressParts[1] !== keypressChordPart) { return false; } if (when) { if (!defaultKb.when) { return false; } if (!when.equals(defaultKb.when)) { return false; } } return true; }; /** * Looks for rules containing -command in `overrides` and removes them directly from `defaults`. */ KeybindingResolver.combine = function (defaults, rawOverrides) { defaults = defaults.slice(0); var overrides = []; for (var _i = 0, rawOverrides_1 = rawOverrides; _i < rawOverrides_1.length; _i++) { var override = rawOverrides_1[_i]; if (!override.command || override.command.length === 0 || override.command.charAt(0) !== '-') { overrides.push(override); continue; } var command = override.command.substr(1); // TODO@chords var keypressFirstPart = override.keypressParts[0]; var keypressChordPart = override.keypressParts[1]; var when = override.when; for (var j = defaults.length - 1; j >= 0; j--) { if (this._isTargetedForRemoval(defaults[j], keypressFirstPart, keypressChordPart, command, when)) { defaults.splice(j, 1); } } } return defaults.concat(overrides); }; KeybindingResolver.prototype._addKeyPress = function (keypress, item) { var 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 (var i = conflicts.length - 1; i >= 0; i--) { var conflict = conflicts[i]; if (conflict.command === item.command) { continue; } var conflictIsChord = (conflict.keypressParts.length > 1); var 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); }; KeybindingResolver.prototype._addToLookupMap = function (item) { if (!item.command) { return; } var arr = this._lookupMap.get(item.command); if (typeof arr === 'undefined') { arr = [item]; this._lookupMap.set(item.command, arr); } else { arr.push(item); } }; KeybindingResolver.prototype._removeFromLookupMap = function (item) { if (!item.command) { return; } var arr = this._lookupMap.get(item.command); if (typeof arr === 'undefined') { return; } for (var 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`. */ KeybindingResolver.whenIsEntirelyIncluded = function (a, b) { if (!b) { return true; } if (!a) { return false; } return this._implies(a, b); }; /** * Returns true if it is provable `p` implies `q`. */ KeybindingResolver._implies = function (p, q) { var notP = p.negate(); var terminals = function (node) { if (node instanceof contextkey_1.ContextKeyOrExpr) { return node.expr; } return [node]; }; var expr = terminals(notP).concat(terminals(q)); for (var i = 0; i < expr.length; i++) { var a = expr[i]; var notA = a.negate(); for (var j = i + 1; j < expr.length; j++) { var b = expr[j]; if (notA.equals(b)) { return true; } } } return false; }; KeybindingResolver.prototype.getKeybindings = function () { return this._keybindings; }; KeybindingResolver.prototype.lookupPrimaryKeybinding = function (commandId) { var items = this._lookupMap.get(commandId); if (typeof items === 'undefined' || items.length === 0) { return null; } return items[items.length - 1]; }; KeybindingResolver.prototype.resolve = function (context, currentChord, keypress) { var lookupMap = null; if (currentChord !== null) { // Fetch all chord bindings for `currentChord` var candidates = this._map.get(currentChord); if (typeof candidates === 'undefined') { // No chords starting with `currentChord` return null; } lookupMap = []; for (var i = 0, len = candidates.length; i < len; i++) { var candidate = candidates[i]; // TODO@chords if (candidate.keypressParts[1] === keypress) { lookupMap.push(candidate); } } } else { var candidates = this._map.get(keypress); if (typeof candidates === 'undefined') { // No bindings with `keypress` return null; } lookupMap = candidates; } var result = this._findCommand(context, lookupMap); if (!result) { return null; } // TODO@chords if (currentChord === null && result.keypressParts.length > 1 && result.keypressParts[1] !== null) { return { enterChord: true, commandId: null, commandArgs: null, bubble: false }; } return { enterChord: false, commandId: result.command, commandArgs: result.commandArgs, bubble: result.bubble }; }; KeybindingResolver.prototype._findCommand = function (context, matches) { for (var i = matches.length - 1; i >= 0; i--) { var k = matches[i]; if (!KeybindingResolver.contextMatchesRules(context, k.when)) { continue; } return k; } return null; }; KeybindingResolver.contextMatchesRules = function (context, rules) { if (!rules) { return true; } return rules.evaluate(context); }; return KeybindingResolver; }()); exports.KeybindingResolver = KeybindingResolver; }); /*--------------------------------------------------------------------------------------------- * 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/platform/keybinding/common/resolvedKeybindingItem*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ResolvedKeybindingItem = /** @class */ (function () { function ResolvedKeybindingItem(resolvedKeybinding, command, commandArgs, when, isDefault) { this.resolvedKeybinding = resolvedKeybinding; this.keypressParts = resolvedKeybinding ? removeElementsAfterNulls(resolvedKeybinding.getDispatchParts()) : []; 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; } return ResolvedKeybindingItem; }()); exports.ResolvedKeybindingItem = ResolvedKeybindingItem; function removeElementsAfterNulls(arr) { var result = []; for (var i = 0, len = arr.length; i < len; i++) { var 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[505/*vs/platform/keybinding/common/usLayoutResolvedKeybinding*/], __M([0/*require*/,1/*exports*/,36/*vs/base/common/keyCodes*/,503/*vs/platform/keybinding/common/baseResolvedKeybinding*/]), function (require, exports, keyCodes_1, baseResolvedKeybinding_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Do not instantiate. Use KeybindingService to get a ResolvedKeybinding seeded with information about the current kb layout. */ var USLayoutResolvedKeybinding = /** @class */ (function (_super) { __extends(USLayoutResolvedKeybinding, _super); function USLayoutResolvedKeybinding(actual, os) { return _super.call(this, os, actual.parts) || this; } USLayoutResolvedKeybinding.prototype._keyCodeToUILabel = function (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); }; USLayoutResolvedKeybinding.prototype._getLabel = function (keybinding) { if (keybinding.isDuplicateModifierCase()) { return ''; } return this._keyCodeToUILabel(keybinding.keyCode); }; USLayoutResolvedKeybinding.prototype._getAriaLabel = function (keybinding) { if (keybinding.isDuplicateModifierCase()) { return ''; } return keyCodes_1.KeyCodeUtils.toString(keybinding.keyCode); }; USLayoutResolvedKeybinding.prototype._getDispatchPart = function (keybinding) { return USLayoutResolvedKeybinding.getDispatchStr(keybinding); }; USLayoutResolvedKeybinding.getDispatchStr = function (keybinding) { if (keybinding.isModifierKey()) { return null; } var 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; }; return USLayoutResolvedKeybinding; }(baseResolvedKeybinding_1.BaseResolvedKeybinding)); exports.USLayoutResolvedKeybinding = USLayoutResolvedKeybinding; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[116/*vs/platform/label/common/label*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LABEL_SERVICE_ID = 'label'; exports.ILabelService = instantiation_1.createDecorator(LABEL_SERVICE_ID); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[218/*vs/platform/layout/browser/layoutService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ILayoutService = 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[506/*vs/platform/contextview/browser/contextViewService*/], __M([0/*require*/,1/*exports*/,265/*vs/base/browser/ui/contextview/contextview*/,2/*vs/base/common/lifecycle*/,218/*vs/platform/layout/browser/layoutService*/]), function (require, exports, contextview_1, lifecycle_1, layoutService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ContextViewService = /** @class */ (function (_super) { __extends(ContextViewService, _super); function ContextViewService(layoutService) { var _this = _super.call(this) || this; _this.layoutService = layoutService; _this.contextView = _this._register(new contextview_1.ContextView(layoutService.container)); _this.layout(); _this._register(layoutService.onLayout(function () { return _this.layout(); })); return _this; } // ContextView ContextViewService.prototype.setContainer = function (container) { this.contextView.setContainer(container); }; ContextViewService.prototype.showContextView = function (delegate) { this.contextView.show(delegate); }; ContextViewService.prototype.layout = function () { this.contextView.layout(); }; ContextViewService.prototype.hideContextView = function (data) { this.contextView.hide(data); }; ContextViewService = __decorate([ __param(0, layoutService_1.ILayoutService) ], ContextViewService); return ContextViewService; }(lifecycle_1.Disposable)); exports.ContextViewService = ContextViewService; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[95/*vs/platform/log/common/log*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ILogService = 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 = {})); var NullLogService = /** @class */ (function () { function NullLogService() { } NullLogService.prototype.getLevel = function () { return LogLevel.Info; }; NullLogService.prototype.trace = function (message) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } }; NullLogService.prototype.error = function (message) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } }; NullLogService.prototype.dispose = function () { }; return NullLogService; }()); exports.NullLogService = NullLogService; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[219/*vs/editor/common/services/editorWorkerServiceImpl*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,182/*vs/base/common/worker/simpleWorker*/,258/*vs/base/worker/defaultWorkerFactory*/,3/*vs/editor/common/core/range*/,17/*vs/editor/common/modes*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/,365/*vs/editor/common/services/editorSimpleWorker*/,49/*vs/editor/common/services/modelService*/,114/*vs/editor/common/services/textResourceConfigurationService*/,5/*vs/base/common/strings*/,19/*vs/base/common/arrays*/,95/*vs/platform/log/common/log*/,132/*vs/base/common/stopwatch*/]), function (require, exports, async_1, lifecycle_1, simpleWorker_1, defaultWorkerFactory_1, range_1, modes, languageConfigurationRegistry_1, editorSimpleWorker_1, modelService_1, textResourceConfigurationService_1, strings_1, arrays_1, log_1, stopwatch_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Stop syncing a model to the worker if it was not needed for 1 min. */ var STOP_SYNC_MODEL_DELTA_TIME_MS = 60 * 1000; /** * Stop the worker if it was not needed for 5 min. */ var STOP_WORKER_DELTA_TIME_MS = 5 * 60 * 1000; function canSyncModel(modelService, resource) { var model = modelService.getModel(resource); if (!model) { return false; } if (model.isTooLargeForSyncing()) { return false; } return true; } var EditorWorkerServiceImpl = /** @class */ (function (_super) { __extends(EditorWorkerServiceImpl, _super); function EditorWorkerServiceImpl(modelService, configurationService, logService) { var _this = _super.call(this) || this; _this._modelService = modelService; _this._workerManager = _this._register(new WorkerManager(_this._modelService)); _this._logService = logService; // todo@joh make sure this happens only once _this._register(modes.LinkProviderRegistry.register('*', { provideLinks: function (model, token) { if (!canSyncModel(_this._modelService, model.uri)) { return Promise.resolve({ links: [] }); // File too large } return _this._workerManager.withWorker().then(function (client) { return client.computeLinks(model.uri); }).then(function (links) { return links && { links: links }; }); } })); _this._register(modes.CompletionProviderRegistry.register('*', new WordBasedCompletionItemProvider(_this._workerManager, configurationService, _this._modelService))); return _this; } EditorWorkerServiceImpl.prototype.dispose = function () { _super.prototype.dispose.call(this); }; EditorWorkerServiceImpl.prototype.canComputeDiff = function (original, modified) { return (canSyncModel(this._modelService, original) && canSyncModel(this._modelService, modified)); }; EditorWorkerServiceImpl.prototype.computeDiff = function (original, modified, ignoreTrimWhitespace, maxComputationTime) { return this._workerManager.withWorker().then(function (client) { return client.computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime); }); }; EditorWorkerServiceImpl.prototype.computeMoreMinimalEdits = function (resource, edits) { var _this = this; if (arrays_1.isNonEmptyArray(edits)) { if (!canSyncModel(this._modelService, resource)) { return Promise.resolve(edits); // File too large } var sw_1 = stopwatch_1.StopWatch.create(true); var result = this._workerManager.withWorker().then(function (client) { return client.computeMoreMinimalEdits(resource, edits); }); result.finally(function () { return _this._logService.trace('FORMAT#computeMoreMinimalEdits', resource.toString(true), sw_1.elapsed()); }); return result; } else { return Promise.resolve(undefined); } }; EditorWorkerServiceImpl.prototype.canNavigateValueSet = function (resource) { return (canSyncModel(this._modelService, resource)); }; EditorWorkerServiceImpl.prototype.navigateValueSet = function (resource, range, up) { return this._workerManager.withWorker().then(function (client) { return client.navigateValueSet(resource, range, up); }); }; EditorWorkerServiceImpl.prototype.canComputeWordRanges = function (resource) { return canSyncModel(this._modelService, resource); }; EditorWorkerServiceImpl.prototype.computeWordRanges = function (resource, range) { return this._workerManager.withWorker().then(function (client) { return client.computeWordRanges(resource, range); }); }; EditorWorkerServiceImpl = __decorate([ __param(0, modelService_1.IModelService), __param(1, textResourceConfigurationService_1.ITextResourceConfigurationService), __param(2, log_1.ILogService) ], EditorWorkerServiceImpl); return EditorWorkerServiceImpl; }(lifecycle_1.Disposable)); exports.EditorWorkerServiceImpl = EditorWorkerServiceImpl; var WordBasedCompletionItemProvider = /** @class */ (function () { function WordBasedCompletionItemProvider(workerManager, configurationService, modelService) { this._debugDisplayName = 'wordbasedCompletions'; this._workerManager = workerManager; this._configurationService = configurationService; this._modelService = modelService; } WordBasedCompletionItemProvider.prototype.provideCompletionItems = function (model, position) { return __awaiter(this, void 0, void 0, function () { var wordBasedSuggestions, word, replace, insert, client, words; return __generator(this, function (_a) { switch (_a.label) { case 0: wordBasedSuggestions = this._configurationService.getValue(model.uri, position, 'editor').wordBasedSuggestions; if (!wordBasedSuggestions) { return [2 /*return*/, undefined]; } if (!canSyncModel(this._modelService, model.uri)) { return [2 /*return*/, undefined]; // File too large } word = model.getWordAtPosition(position); replace = !word ? range_1.Range.fromPositions(position) : new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn); insert = replace.setEndPosition(position.lineNumber, position.column); return [4 /*yield*/, this._workerManager.withWorker()]; case 1: client = _a.sent(); return [4 /*yield*/, client.textualSuggest(model.uri, position)]; case 2: words = _a.sent(); if (!words) { return [2 /*return*/, undefined]; } return [2 /*return*/, { suggestions: words.map(function (word) { return { kind: 18 /* Text */, label: word, insertText: word, range: { insert: insert, replace: replace } }; }) }]; } }); }); }; return WordBasedCompletionItemProvider; }()); var WorkerManager = /** @class */ (function (_super) { __extends(WorkerManager, _super); function WorkerManager(modelService) { var _this = _super.call(this) || this; _this._modelService = modelService; _this._editorWorkerClient = null; _this._lastWorkerUsedTime = (new Date()).getTime(); var stopWorkerInterval = _this._register(new async_1.IntervalTimer()); stopWorkerInterval.cancelAndSet(function () { return _this._checkStopIdleWorker(); }, Math.round(STOP_WORKER_DELTA_TIME_MS / 2)); _this._register(_this._modelService.onModelRemoved(function (_) { return _this._checkStopEmptyWorker(); })); return _this; } WorkerManager.prototype.dispose = function () { if (this._editorWorkerClient) { this._editorWorkerClient.dispose(); this._editorWorkerClient = null; } _super.prototype.dispose.call(this); }; /** * Check if the model service has no more models and stop the worker if that is the case. */ WorkerManager.prototype._checkStopEmptyWorker = function () { if (!this._editorWorkerClient) { return; } var 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. */ WorkerManager.prototype._checkStopIdleWorker = function () { if (!this._editorWorkerClient) { return; } var timeSinceLastWorkerUsedTime = (new Date()).getTime() - this._lastWorkerUsedTime; if (timeSinceLastWorkerUsedTime > STOP_WORKER_DELTA_TIME_MS) { this._editorWorkerClient.dispose(); this._editorWorkerClient = null; } }; WorkerManager.prototype.withWorker = function () { this._lastWorkerUsedTime = (new Date()).getTime(); if (!this._editorWorkerClient) { this._editorWorkerClient = new EditorWorkerClient(this._modelService, false, 'editorWorkerService'); } return Promise.resolve(this._editorWorkerClient); }; return WorkerManager; }(lifecycle_1.Disposable)); var EditorModelManager = /** @class */ (function (_super) { __extends(EditorModelManager, _super); function EditorModelManager(proxy, modelService, keepIdleModels) { var _this = _super.call(this) || this; _this._syncedModels = Object.create(null); _this._syncedModelsLastUsedTime = Object.create(null); _this._proxy = proxy; _this._modelService = modelService; if (!keepIdleModels) { var timer = new async_1.IntervalTimer(); timer.cancelAndSet(function () { return _this._checkStopModelSync(); }, Math.round(STOP_SYNC_MODEL_DELTA_TIME_MS / 2)); _this._register(timer); } return _this; } EditorModelManager.prototype.dispose = function () { for (var modelUrl in this._syncedModels) { lifecycle_1.dispose(this._syncedModels[modelUrl]); } this._syncedModels = Object.create(null); this._syncedModelsLastUsedTime = Object.create(null); _super.prototype.dispose.call(this); }; EditorModelManager.prototype.ensureSyncedResources = function (resources) { for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) { var resource = resources_1[_i]; var resourceStr = resource.toString(); if (!this._syncedModels[resourceStr]) { this._beginModelSync(resource); } if (this._syncedModels[resourceStr]) { this._syncedModelsLastUsedTime[resourceStr] = (new Date()).getTime(); } } }; EditorModelManager.prototype._checkStopModelSync = function () { var currentTime = (new Date()).getTime(); var toRemove = []; for (var modelUrl in this._syncedModelsLastUsedTime) { var elapsedTime = currentTime - this._syncedModelsLastUsedTime[modelUrl]; if (elapsedTime > STOP_SYNC_MODEL_DELTA_TIME_MS) { toRemove.push(modelUrl); } } for (var _i = 0, toRemove_1 = toRemove; _i < toRemove_1.length; _i++) { var e = toRemove_1[_i]; this._stopModelSync(e); } }; EditorModelManager.prototype._beginModelSync = function (resource) { var _this = this; var model = this._modelService.getModel(resource); if (!model) { return; } if (model.isTooLargeForSyncing()) { return; } var modelUrl = resource.toString(); this._proxy.acceptNewModel({ url: model.uri.toString(), lines: model.getLinesContent(), EOL: model.getEOL(), versionId: model.getVersionId() }); var toDispose = new lifecycle_1.DisposableStore(); toDispose.add(model.onDidChangeContent(function (e) { _this._proxy.acceptModelChanged(modelUrl.toString(), e); })); toDispose.add(model.onWillDispose(function () { _this._stopModelSync(modelUrl); })); toDispose.add(lifecycle_1.toDisposable(function () { _this._proxy.acceptRemovedModel(modelUrl); })); this._syncedModels[modelUrl] = toDispose; }; EditorModelManager.prototype._stopModelSync = function (modelUrl) { var toDispose = this._syncedModels[modelUrl]; delete this._syncedModels[modelUrl]; delete this._syncedModelsLastUsedTime[modelUrl]; lifecycle_1.dispose(toDispose); }; return EditorModelManager; }(lifecycle_1.Disposable)); var SynchronousWorkerClient = /** @class */ (function () { function SynchronousWorkerClient(instance) { this._instance = instance; this._proxyObj = Promise.resolve(this._instance); } SynchronousWorkerClient.prototype.dispose = function () { this._instance.dispose(); }; SynchronousWorkerClient.prototype.getProxyObject = function () { return this._proxyObj; }; return SynchronousWorkerClient; }()); var EditorWorkerHost = /** @class */ (function () { function EditorWorkerHost(workerClient) { this._workerClient = workerClient; } // foreign host request EditorWorkerHost.prototype.fhr = function (method, args) { return this._workerClient.fhr(method, args); }; return EditorWorkerHost; }()); exports.EditorWorkerHost = EditorWorkerHost; var EditorWorkerClient = /** @class */ (function (_super) { __extends(EditorWorkerClient, _super); function EditorWorkerClient(modelService, keepIdleModels, label) { var _this = _super.call(this) || this; _this._modelService = modelService; _this._keepIdleModels = keepIdleModels; _this._workerFactory = new defaultWorkerFactory_1.DefaultWorkerFactory(label); _this._worker = null; _this._modelManager = null; return _this; } // foreign host request EditorWorkerClient.prototype.fhr = function (method, args) { throw new Error("Not implemented!"); }; EditorWorkerClient.prototype._getOrCreateWorker = function () { if (!this._worker) { try { this._worker = this._register(new simpleWorker_1.SimpleWorkerClient(this._workerFactory, 'vs/editor/common/services/editorSimpleWorker', new EditorWorkerHost(this))); } catch (err) { simpleWorker_1.logOnceWebWorkerWarning(err); this._worker = new SynchronousWorkerClient(new editorSimpleWorker_1.EditorSimpleWorker(new EditorWorkerHost(this), null)); } } return this._worker; }; EditorWorkerClient.prototype._getProxy = function () { var _this = this; return this._getOrCreateWorker().getProxyObject().then(undefined, function (err) { simpleWorker_1.logOnceWebWorkerWarning(err); _this._worker = new SynchronousWorkerClient(new editorSimpleWorker_1.EditorSimpleWorker(new EditorWorkerHost(_this), null)); return _this._getOrCreateWorker().getProxyObject(); }); }; EditorWorkerClient.prototype._getOrCreateModelManager = function (proxy) { if (!this._modelManager) { this._modelManager = this._register(new EditorModelManager(proxy, this._modelService, this._keepIdleModels)); } return this._modelManager; }; EditorWorkerClient.prototype._withSyncedResources = function (resources) { var _this = this; return this._getProxy().then(function (proxy) { _this._getOrCreateModelManager(proxy).ensureSyncedResources(resources); return proxy; }); }; EditorWorkerClient.prototype.computeDiff = function (original, modified, ignoreTrimWhitespace, maxComputationTime) { return this._withSyncedResources([original, modified]).then(function (proxy) { return proxy.computeDiff(original.toString(), modified.toString(), ignoreTrimWhitespace, maxComputationTime); }); }; EditorWorkerClient.prototype.computeMoreMinimalEdits = function (resource, edits) { return this._withSyncedResources([resource]).then(function (proxy) { return proxy.computeMoreMinimalEdits(resource.toString(), edits); }); }; EditorWorkerClient.prototype.computeLinks = function (resource) { return this._withSyncedResources([resource]).then(function (proxy) { return proxy.computeLinks(resource.toString()); }); }; EditorWorkerClient.prototype.textualSuggest = function (resource, position) { var _this = this; return this._withSyncedResources([resource]).then(function (proxy) { var model = _this._modelService.getModel(resource); if (!model) { return null; } var wordDefRegExp = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id); var wordDef = wordDefRegExp.source; var wordDefFlags = strings_1.regExpFlags(wordDefRegExp); return proxy.textualSuggest(resource.toString(), position, wordDef, wordDefFlags); }); }; EditorWorkerClient.prototype.computeWordRanges = function (resource, range) { var _this = this; return this._withSyncedResources([resource]).then(function (proxy) { var model = _this._modelService.getModel(resource); if (!model) { return Promise.resolve(null); } var wordDefRegExp = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id); var wordDef = wordDefRegExp.source; var wordDefFlags = strings_1.regExpFlags(wordDefRegExp); return proxy.computeWordRanges(resource.toString(), range, wordDef, wordDefFlags); }); }; EditorWorkerClient.prototype.navigateValueSet = function (resource, range, up) { var _this = this; return this._withSyncedResources([resource]).then(function (proxy) { var model = _this._modelService.getModel(resource); if (!model) { return null; } var wordDefRegExp = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id); var wordDef = wordDefRegExp.source; var wordDefFlags = strings_1.regExpFlags(wordDefRegExp); return proxy.navigateValueSet(resource.toString(), range, up, wordDef, wordDefFlags); }); }; return EditorWorkerClient; }(lifecycle_1.Disposable)); 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[507/*vs/editor/common/services/webWorker*/], __M([0/*require*/,1/*exports*/,219/*vs/editor/common/services/editorWorkerServiceImpl*/,21/*vs/base/common/types*/]), function (require, exports, editorWorkerServiceImpl_1, types) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Create a new web worker that has model syncing capabilities built in. * Specify an AMD module to load that will `create` an object that will be proxied. */ function createWebWorker(modelService, opts) { return new MonacoWebWorkerImpl(modelService, opts); } exports.createWebWorker = createWebWorker; var MonacoWebWorkerImpl = /** @class */ (function (_super) { __extends(MonacoWebWorkerImpl, _super); function MonacoWebWorkerImpl(modelService, opts) { var _this = _super.call(this, modelService, opts.keepIdleModels || false, opts.label) || this; _this._foreignModuleId = opts.moduleId; _this._foreignModuleCreateData = opts.createData || null; _this._foreignModuleHost = opts.host || null; _this._foreignProxy = null; return _this; } // foreign host request MonacoWebWorkerImpl.prototype.fhr = function (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); } }; MonacoWebWorkerImpl.prototype._getForeignProxy = function () { var _this = this; if (!this._foreignProxy) { this._foreignProxy = this._getProxy().then(function (proxy) { var foreignHostMethods = _this._foreignModuleHost ? types.getAllMethodNames(_this._foreignModuleHost) : []; return proxy.loadForeignModule(_this._foreignModuleId, _this._foreignModuleCreateData, foreignHostMethods).then(function (foreignMethods) { _this._foreignModuleCreateData = null; var proxyMethodRequest = function (method, args) { return proxy.fmr(method, args); }; var createProxyMethod = function (method, proxyMethodRequest) { return function () { var args = Array.prototype.slice.call(arguments, 0); return proxyMethodRequest(method, args); }; }; var foreignProxy = {}; for (var _i = 0, foreignMethods_1 = foreignMethods; _i < foreignMethods_1.length; _i++) { var foreignMethod = foreignMethods_1[_i]; foreignProxy[foreignMethod] = createProxyMethod(foreignMethod, proxyMethodRequest); } return foreignProxy; }); }); } return this._foreignProxy; }; MonacoWebWorkerImpl.prototype.getProxy = function () { return this._getForeignProxy(); }; MonacoWebWorkerImpl.prototype.withSyncedResources = function (resources) { var _this = this; return this._withSyncedResources(resources).then(function (_) { return _this.getProxy(); }); }; return MonacoWebWorkerImpl; }(editorWorkerServiceImpl_1.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[72/*vs/platform/markers/common/markers*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/,475/*vs/nls!vs/platform/markers/common/markers*/,112/*vs/base/common/severity*/]), function (require, exports, instantiation_1, nls_1, severity_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; var _displayStrings = Object.create(null); _displayStrings[MarkerSeverity.Error] = nls_1.localize(0, null); _displayStrings[MarkerSeverity.Warning] = nls_1.localize(1, null); _displayStrings[MarkerSeverity.Info] = 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) { var emptyString = ''; function makeKey(markerData) { return makeKeyOptionalMessage(markerData, true); } IMarkerData.makeKey = makeKey; function makeKeyOptionalMessage(markerData, useMessage) { var 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 = 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[508/*vs/platform/markers/common/markerService*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,46/*vs/base/common/network*/,21/*vs/base/common/types*/,4/*vs/base/common/event*/,72/*vs/platform/markers/common/markers*/]), function (require, exports, arrays_1, network_1, types_1, event_1, markers_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MapMap; (function (MapMap) { function get(map, key1, key2) { if (map[key1]) { return map[key1][key2]; } return undefined; } MapMap.get = get; function set(map, key1, key2, value) { if (!map[key1]) { map[key1] = Object.create(null); } map[key1][key2] = value; } MapMap.set = set; function remove(map, key1, key2) { if (map[key1] && map[key1][key2]) { delete map[key1][key2]; if (types_1.isEmptyObject(map[key1])) { delete map[key1]; } return true; } return false; } MapMap.remove = remove; })(MapMap || (MapMap = {})); var MarkerStats = /** @class */ (function () { function MarkerStats(service) { this.errors = 0; this.infos = 0; this.warnings = 0; this.unknowns = 0; this._data = Object.create(null); this._service = service; this._subscription = service.onMarkerChanged(this._update, this); } MarkerStats.prototype.dispose = function () { this._subscription.dispose(); this._data = undefined; }; MarkerStats.prototype._update = function (resources) { if (!this._data) { return; } for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) { var resource = resources_1[_i]; var key = resource.toString(); var oldStats = this._data[key]; if (oldStats) { this._substract(oldStats); } var newStats = this._resourceStats(resource); this._add(newStats); this._data[key] = newStats; } }; MarkerStats.prototype._resourceStats = function (resource) { var 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 (var _i = 0, _a = this._service.read({ resource: resource }); _i < _a.length; _i++) { var severity = _a[_i].severity; 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; }; MarkerStats.prototype._substract = function (op) { this.errors -= op.errors; this.warnings -= op.warnings; this.infos -= op.infos; this.unknowns -= op.unknowns; }; MarkerStats.prototype._add = function (op) { this.errors += op.errors; this.warnings += op.warnings; this.infos += op.infos; this.unknowns += op.unknowns; }; return MarkerStats; }()); var MarkerService = /** @class */ (function () { function MarkerService() { this._onMarkerChanged = new event_1.Emitter(); this._onMarkerChangedEvent = event_1.Event.debounce(this._onMarkerChanged.event, MarkerService._debouncer, 0); this._byResource = Object.create(null); this._byOwner = Object.create(null); this._stats = new MarkerStats(this); } MarkerService.prototype.dispose = function () { this._stats.dispose(); }; Object.defineProperty(MarkerService.prototype, "onMarkerChanged", { get: function () { return this._onMarkerChangedEvent; }, enumerable: true, configurable: true }); MarkerService.prototype.remove = function (owner, resources) { for (var _i = 0, _a = resources || []; _i < _a.length; _i++) { var resource = _a[_i]; this.changeOne(owner, resource, []); } }; MarkerService.prototype.changeOne = function (owner, resource, markerData) { if (arrays_1.isFalsyOrEmpty(markerData)) { // remove marker for this (owner,resource)-tuple var a = MapMap.remove(this._byResource, resource.toString(), owner); var b = MapMap.remove(this._byOwner, owner, resource.toString()); if (a !== b) { throw new Error('invalid marker service state'); } if (a && b) { this._onMarkerChanged.fire([resource]); } } else { // insert marker for this (owner,resource)-tuple var markers = []; for (var _i = 0, markerData_1 = markerData; _i < markerData_1.length; _i++) { var data = markerData_1[_i]; var marker = MarkerService._toMarker(owner, resource, data); if (marker) { markers.push(marker); } } MapMap.set(this._byResource, resource.toString(), owner, markers); MapMap.set(this._byOwner, owner, resource.toString(), markers); this._onMarkerChanged.fire([resource]); } }; MarkerService._toMarker = function (owner, resource, data) { var code = data.code, severity = data.severity, message = data.message, source = data.source, startLineNumber = data.startLineNumber, startColumn = data.startColumn, endLineNumber = data.endLineNumber, endColumn = data.endColumn, relatedInformation = data.relatedInformation, tags = data.tags; 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: resource, owner: owner, code: code, severity: severity, message: message, source: source, startLineNumber: startLineNumber, startColumn: startColumn, endLineNumber: endLineNumber, endColumn: endColumn, relatedInformation: relatedInformation, tags: tags, }; }; MarkerService.prototype.read = function (filter) { if (filter === void 0) { filter = Object.create(null); } var owner = filter.owner, resource = filter.resource, severities = filter.severities, take = filter.take; if (!take || take < 0) { take = -1; } if (owner && resource) { // exactly one owner AND resource var data = MapMap.get(this._byResource, resource.toString(), owner); if (!data) { return []; } else { var result = []; for (var _i = 0, data_1 = data; _i < data_1.length; _i++) { var marker = data_1[_i]; if (MarkerService._accept(marker, severities)) { var newLen = result.push(marker); if (take > 0 && newLen === take) { break; } } } return result; } } else if (!owner && !resource) { // all var result = []; for (var key1 in this._byResource) { for (var key2 in this._byResource[key1]) { for (var _a = 0, _b = this._byResource[key1][key2]; _a < _b.length; _a++) { var data = _b[_a]; if (MarkerService._accept(data, severities)) { var newLen = result.push(data); if (take > 0 && newLen === take) { return result; } } } } } return result; } else { // of one resource OR owner var map = owner ? this._byOwner[owner] : resource ? this._byResource[resource.toString()] : undefined; if (!map) { return []; } var result = []; for (var key in map) { for (var _c = 0, _d = map[key]; _c < _d.length; _c++) { var data = _d[_c]; if (MarkerService._accept(data, severities)) { var newLen = result.push(data); if (take > 0 && newLen === take) { return result; } } } } return result; } }; MarkerService._accept = function (marker, severities) { return severities === undefined || (severities & marker.severity) === marker.severity; }; MarkerService._debouncer = function (last, event) { if (!last) { MarkerService._dedupeMap = Object.create(null); last = []; } for (var _i = 0, event_2 = event; _i < event_2.length; _i++) { var uri = event_2[_i]; if (MarkerService._dedupeMap[uri.toString()] === undefined) { MarkerService._dedupeMap[uri.toString()] = true; last.push(uri); } } return last; }; return MarkerService; }()); exports.MarkerService = MarkerService; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[35/*vs/platform/notification/common/notification*/], __M([0/*require*/,1/*exports*/,112/*vs/base/common/severity*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, severity_1, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Severity = severity_1.default; exports.INotificationService = instantiation_1.createDecorator('notificationService'); var NoOpNotification = /** @class */ (function () { function NoOpNotification() { } return 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([0/*require*/,1/*exports*/,25/*vs/base/common/uri*/,11/*vs/platform/instantiation/common/instantiation*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/]), function (require, exports, uri_1, instantiation_1, lifecycle_1, strings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IOpenerService = instantiation_1.createDecorator('openerService'); exports.NullOpenerService = Object.freeze({ _serviceBrand: undefined, registerOpener: function () { return lifecycle_1.Disposable.None; }, registerValidator: function () { return lifecycle_1.Disposable.None; }, registerExternalUriResolver: function () { return lifecycle_1.Disposable.None; }, setExternalOpener: function () { }, open: function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, false]; }); }); }, resolveExternalUri: function (uri) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, { resolved: uri, dispose: function () { } }]; }); }); }, }); function matchesScheme(target, scheme) { if (uri_1.URI.isUri(target)) { return strings_1.equalsIgnoreCase(target.scheme, scheme); } else { return strings_1.startsWithIgnoreCase(target, scheme + ':'); } } exports.matchesScheme = matchesScheme; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[509/*vs/editor/browser/services/openerService*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,76/*vs/base/common/linkedList*/,180/*vs/base/common/marshalling*/,46/*vs/base/common/network*/,39/*vs/base/common/resources*/,25/*vs/base/common/uri*/,32/*vs/editor/browser/services/codeEditorService*/,29/*vs/platform/commands/common/commands*/,51/*vs/platform/opener/common/opener*/,478/*vs/platform/editor/common/editor*/]), function (require, exports, dom, linkedList_1, marshalling_1, network_1, resources_1, uri_1, codeEditorService_1, commands_1, opener_1, editor_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CommandOpener = /** @class */ (function () { function CommandOpener(_commandService) { this._commandService = _commandService; } CommandOpener.prototype.open = function (target) { return __awaiter(this, void 0, void 0, function () { var args; var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!opener_1.matchesScheme(target, network_1.Schemas.command)) { return [2 /*return*/, false]; } // run command or bail out if command isn't known if (typeof target === 'string') { target = uri_1.URI.parse(target); } if (!commands_1.CommandsRegistry.getCommand(target.path)) { throw new Error("command '" + target.path + "' NOT known"); } args = []; try { args = marshalling_1.parse(decodeURIComponent(target.query)); } catch (_c) { // ignore and retry try { args = marshalling_1.parse(target.query); } catch (_d) { // ignore error } } if (!Array.isArray(args)) { args = [args]; } return [4 /*yield*/, (_a = this._commandService).executeCommand.apply(_a, __spreadArrays([target.path], args))]; case 1: _b.sent(); return [2 /*return*/, true]; } }); }); }; CommandOpener = __decorate([ __param(0, commands_1.ICommandService) ], CommandOpener); return CommandOpener; }()); var EditorOpener = /** @class */ (function () { function EditorOpener(_editorService) { this._editorService = _editorService; } EditorOpener.prototype.open = function (target, options) { return __awaiter(this, void 0, void 0, function () { var selection, match; return __generator(this, function (_a) { switch (_a.label) { case 0: if (typeof target === 'string') { target = uri_1.URI.parse(target); } selection = undefined; match = /^L?(\d+)(?:,(\d+))?/.exec(target.fragment); if (match) { // support file:///some/file.js#73,84 // support file:///some/file.js#L73 selection = { startLineNumber: parseInt(match[1]), startColumn: match[2] ? parseInt(match[2]) : 1 }; // remove fragment target = target.with({ fragment: '' }); } if (target.scheme === network_1.Schemas.file) { target = resources_1.normalizePath(target); // workaround for non-normalized paths (https://github.com/Microsoft/vscode/issues/12954) } return [4 /*yield*/, this._editorService.openCodeEditor({ resource: target, options: { selection: selection, context: (options === null || options === void 0 ? void 0 : options.fromUserGesture) ? editor_1.EditorOpenContext.USER : editor_1.EditorOpenContext.API } }, this._editorService.getFocusedCodeEditor(), options === null || options === void 0 ? void 0 : options.openToSide)]; case 1: _a.sent(); return [2 /*return*/, true]; } }); }); }; EditorOpener = __decorate([ __param(0, codeEditorService_1.ICodeEditorService) ], EditorOpener); return EditorOpener; }()); var OpenerService = /** @class */ (function () { function OpenerService(editorService, commandService) { var _this = this; this._openers = new linkedList_1.LinkedList(); this._validators = new linkedList_1.LinkedList(); this._resolvers = new linkedList_1.LinkedList(); // Default external opener is going through window.open() this._externalOpener = { openExternal: function (href) { dom.windowOpenNoOpener(href); return Promise.resolve(true); } }; // Default opener: maito, http(s), command, and catch-all-editors this._openers.push({ open: function (target, options) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: if (!((options === null || options === void 0 ? void 0 : options.openExternal) || opener_1.matchesScheme(target, network_1.Schemas.mailto) || opener_1.matchesScheme(target, network_1.Schemas.http) || opener_1.matchesScheme(target, network_1.Schemas.https))) return [3 /*break*/, 2]; // open externally return [4 /*yield*/, this._doOpenExternal(target, options)]; case 1: // open externally _a.sent(); return [2 /*return*/, true]; case 2: return [2 /*return*/, false]; } }); }); } }); this._openers.push(new CommandOpener(commandService)); this._openers.push(new EditorOpener(editorService)); } OpenerService.prototype.open = function (target, options) { return __awaiter(this, void 0, void 0, function () { var _i, _a, validator, _b, _c, opener_2, handled; return __generator(this, function (_d) { switch (_d.label) { case 0: _i = 0, _a = this._validators.toArray(); _d.label = 1; case 1: if (!(_i < _a.length)) return [3 /*break*/, 4]; validator = _a[_i]; return [4 /*yield*/, validator.shouldOpen(target)]; case 2: if (!(_d.sent())) { return [2 /*return*/, false]; } _d.label = 3; case 3: _i++; return [3 /*break*/, 1]; case 4: _b = 0, _c = this._openers.toArray(); _d.label = 5; case 5: if (!(_b < _c.length)) return [3 /*break*/, 8]; opener_2 = _c[_b]; return [4 /*yield*/, opener_2.open(target, options)]; case 6: handled = _d.sent(); if (handled) { return [2 /*return*/, true]; } _d.label = 7; case 7: _b++; return [3 /*break*/, 5]; case 8: return [2 /*return*/, false]; } }); }); }; OpenerService.prototype.resolveExternalUri = function (resource, options) { return __awaiter(this, void 0, void 0, function () { var _i, _a, resolver, result; return __generator(this, function (_b) { switch (_b.label) { case 0: _i = 0, _a = this._resolvers.toArray(); _b.label = 1; case 1: if (!(_i < _a.length)) return [3 /*break*/, 4]; resolver = _a[_i]; return [4 /*yield*/, resolver.resolveExternalUri(resource, options)]; case 2: result = _b.sent(); if (result) { return [2 /*return*/, result]; } _b.label = 3; case 3: _i++; return [3 /*break*/, 1]; case 4: return [2 /*return*/, { resolved: resource, dispose: function () { } }]; } }); }); }; OpenerService.prototype._doOpenExternal = function (resource, options) { return __awaiter(this, void 0, void 0, function () { var uri, resolved; return __generator(this, function (_a) { switch (_a.label) { case 0: uri = typeof resource === 'string' ? uri_1.URI.parse(resource) : resource; return [4 /*yield*/, this.resolveExternalUri(uri, options)]; case 1: resolved = (_a.sent()).resolved; if (typeof resource === 'string' && uri.toString() === resolved.toString()) { // open the url-string AS IS return [2 /*return*/, this._externalOpener.openExternal(resource)]; } else { // open URI using the toString(noEncode)+encodeURI-trick return [2 /*return*/, this._externalOpener.openExternal(encodeURI(resolved.toString(true)))]; } return [2 /*return*/]; } }); }); }; OpenerService.prototype.dispose = function () { this._validators.clear(); }; OpenerService = __decorate([ __param(0, codeEditorService_1.ICodeEditorService), __param(1, commands_1.ICommandService) ], OpenerService); return OpenerService; }()); exports.OpenerService = OpenerService; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[117/*vs/editor/contrib/markdown/markdownRenderer*/], __M([0/*require*/,1/*exports*/,248/*vs/base/browser/markdownRenderer*/,51/*vs/platform/opener/common/opener*/,71/*vs/editor/common/services/modeService*/,10/*vs/base/common/errors*/,214/*vs/editor/common/modes/textToHtmlTokenizer*/,11/*vs/platform/instantiation/common/instantiation*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/editor/common/modes*/]), function (require, exports, markdownRenderer_1, opener_1, modeService_1, errors_1, textToHtmlTokenizer_1, instantiation_1, event_1, lifecycle_1, modes_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MarkdownRenderer = /** @class */ (function (_super) { __extends(MarkdownRenderer, _super); function MarkdownRenderer(_editor, _modeService, _openerService) { if (_openerService === void 0) { _openerService = opener_1.NullOpenerService; } var _this = _super.call(this) || this; _this._editor = _editor; _this._modeService = _modeService; _this._openerService = _openerService; _this._onDidRenderCodeBlock = _this._register(new event_1.Emitter()); _this.onDidRenderCodeBlock = _this._onDidRenderCodeBlock.event; return _this; } MarkdownRenderer.prototype.getOptions = function (disposeables) { var _this = this; return { codeBlockRenderer: function (languageAlias, value) { // In markdown, // it is possible that we stumble upon language aliases (e.g.js instead of javascript) // it is possible no alias is given in which case we fall back to the current editor lang var modeId = null; if (languageAlias) { modeId = _this._modeService.getModeIdForLanguageName(languageAlias); } else { var model = _this._editor.getModel(); if (model) { modeId = model.getLanguageIdentifier().language; } } _this._modeService.triggerMode(modeId || ''); return Promise.resolve(true).then(function (_) { var promise = modes_1.TokenizationRegistry.getPromise(modeId || ''); if (promise) { return promise.then(function (support) { return textToHtmlTokenizer_1.tokenizeToString(value, support); }); } return textToHtmlTokenizer_1.tokenizeToString(value, undefined); }).then(function (code) { return "" + code + ""; }); }, codeBlockRenderCallback: function () { return _this._onDidRenderCodeBlock.fire(); }, actionHandler: { callback: function (content) { _this._openerService.open(content, { fromUserGesture: true }).catch(errors_1.onUnexpectedError); }, disposeables: disposeables } }; }; MarkdownRenderer.prototype.render = function (markdown) { var disposeables = new lifecycle_1.DisposableStore(); var element; if (!markdown) { element = document.createElement('span'); } else { element = markdownRenderer_1.renderMarkdown(markdown, this.getOptions(disposeables)); } return { element: element, dispose: function () { return disposeables.dispose(); } }; }; MarkdownRenderer = __decorate([ __param(1, modeService_1.IModeService), __param(2, instantiation_1.optional(opener_1.IOpenerService)) ], MarkdownRenderer); return MarkdownRenderer; }(lifecycle_1.Disposable)); 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[510/*vs/editor/contrib/hover/modesGlyphHover*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,75/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,200/*vs/editor/contrib/hover/hoverOperation*/,201/*vs/editor/contrib/hover/hoverWidgets*/,117/*vs/editor/contrib/markdown/markdownRenderer*/,51/*vs/platform/opener/common/opener*/,19/*vs/base/common/arrays*/]), function (require, exports, dom_1, htmlContent_1, lifecycle_1, hoverOperation_1, hoverWidgets_1, markdownRenderer_1, opener_1, arrays_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MarginComputer = /** @class */ (function () { function MarginComputer(editor) { this._editor = editor; this._lineNumber = -1; this._result = []; } MarginComputer.prototype.setLineNumber = function (lineNumber) { this._lineNumber = lineNumber; this._result = []; }; MarginComputer.prototype.clearResult = function () { this._result = []; }; MarginComputer.prototype.computeSync = function () { var toHoverMessage = function (contents) { return { value: contents }; }; var lineDecorations = this._editor.getLineDecorations(this._lineNumber); var result = []; if (!lineDecorations) { return result; } for (var _i = 0, lineDecorations_1 = lineDecorations; _i < lineDecorations_1.length; _i++) { var d = lineDecorations_1[_i]; if (!d.options.glyphMarginClassName) { continue; } var hoverMessage = d.options.glyphMarginHoverMessage; if (!hoverMessage || htmlContent_1.isEmptyMarkdownString(hoverMessage)) { continue; } result.push.apply(result, arrays_1.asArray(hoverMessage).map(toHoverMessage)); } return result; }; MarginComputer.prototype.onResult = function (result, isFromSynchronousComputation) { this._result = this._result.concat(result); }; MarginComputer.prototype.getResult = function () { return this._result; }; MarginComputer.prototype.getResultWithLoadingMessage = function () { return this.getResult(); }; return MarginComputer; }()); var ModesGlyphHoverWidget = /** @class */ (function (_super) { __extends(ModesGlyphHoverWidget, _super); function ModesGlyphHoverWidget(editor, modeService, openerService) { if (openerService === void 0) { openerService = opener_1.NullOpenerService; } var _this = _super.call(this, ModesGlyphHoverWidget.ID, editor) || this; _this._renderDisposeables = _this._register(new lifecycle_1.DisposableStore()); _this._messages = []; _this._lastLineNumber = -1; _this._markdownRenderer = _this._register(new markdownRenderer_1.MarkdownRenderer(_this._editor, modeService, openerService)); _this._computer = new MarginComputer(_this._editor); _this._hoverOperation = new hoverOperation_1.HoverOperation(_this._computer, function (result) { return _this._withResult(result); }, undefined, function (result) { return _this._withResult(result); }, 300); return _this; } ModesGlyphHoverWidget.prototype.dispose = function () { this._hoverOperation.cancel(); _super.prototype.dispose.call(this); }; ModesGlyphHoverWidget.prototype.onModelDecorationsChanged = function () { if (this.isVisible) { // The decorations have changed and the hover is visible, // we need to recompute the displayed text this._hoverOperation.cancel(); this._computer.clearResult(); this._hoverOperation.start(0 /* Delayed */); } }; ModesGlyphHoverWidget.prototype.startShowingAt = function (lineNumber) { if (this._lastLineNumber === lineNumber) { // We have to show the widget at the exact same line number as before, so no work is needed return; } this._hoverOperation.cancel(); this.hide(); this._lastLineNumber = lineNumber; this._computer.setLineNumber(lineNumber); this._hoverOperation.start(0 /* Delayed */); }; ModesGlyphHoverWidget.prototype.hide = function () { this._lastLineNumber = -1; this._hoverOperation.cancel(); _super.prototype.hide.call(this); }; ModesGlyphHoverWidget.prototype._withResult = function (result) { this._messages = result; if (this._messages.length > 0) { this._renderMessages(this._lastLineNumber, this._messages); } else { this.hide(); } }; ModesGlyphHoverWidget.prototype._renderMessages = function (lineNumber, messages) { this._renderDisposeables.clear(); var fragment = document.createDocumentFragment(); for (var _i = 0, messages_1 = messages; _i < messages_1.length; _i++) { var msg = messages_1[_i]; var renderedContents = this._markdownRenderer.render(msg.value); this._renderDisposeables.add(renderedContents); fragment.appendChild(dom_1.$('div.hover-row', undefined, renderedContents.element)); } this.updateContents(fragment); this.showAt(lineNumber); }; ModesGlyphHoverWidget.ID = 'editor.contrib.modesGlyphHoverWidget'; return ModesGlyphHoverWidget; }(hoverWidgets_1.GlyphHoverWidget)); exports.ModesGlyphHoverWidget = ModesGlyphHoverWidget; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[73/*vs/platform/progress/common/progress*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IEditorProgressService = 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[42/*vs/platform/registry/common/platform*/], __M([0/*require*/,1/*exports*/,21/*vs/base/common/types*/,124/*vs/base/common/assert*/]), function (require, exports, Types, Assert) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var RegistryImpl = /** @class */ (function () { function RegistryImpl() { this.data = new Map(); } RegistryImpl.prototype.add = function (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); }; RegistryImpl.prototype.as = function (id) { return this.data.get(id) || null; }; return RegistryImpl; }()); 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[118/*vs/editor/common/modes/modesRegistry*/], __M([0/*require*/,1/*exports*/,425/*vs/nls!vs/editor/common/modes/modesRegistry*/,4/*vs/base/common/event*/,17/*vs/editor/common/modes*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/,42/*vs/platform/registry/common/platform*/]), function (require, exports, nls, event_1, modes_1, languageConfigurationRegistry_1, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // Define extension point ids exports.Extensions = { ModesRegistry: 'editor.modesRegistry' }; var EditorModesRegistry = /** @class */ (function () { function EditorModesRegistry() { this._onDidChangeLanguages = new event_1.Emitter(); this.onDidChangeLanguages = this._onDidChangeLanguages.event; this._languages = []; this._dynamicLanguages = []; } // --- languages EditorModesRegistry.prototype.registerLanguage = function (def) { this._languages.push(def); this._onDidChangeLanguages.fire(undefined); }; EditorModesRegistry.prototype.getLanguages = function () { return [].concat(this._languages).concat(this._dynamicLanguages); }; return EditorModesRegistry; }()); exports.EditorModesRegistry = EditorModesRegistry; exports.ModesRegistry = new EditorModesRegistry(); platform_1.Registry.add(exports.Extensions.ModesRegistry, exports.ModesRegistry); exports.PLAINTEXT_MODE_ID = 'plaintext'; exports.PLAINTEXT_LANGUAGE_IDENTIFIER = new modes_1.LanguageIdentifier(exports.PLAINTEXT_MODE_ID, 1 /* PlainText */); exports.ModesRegistry.registerLanguage({ id: exports.PLAINTEXT_MODE_ID, extensions: ['.txt', '.gitignore'], aliases: [nls.localize(0, null), 'text'], mimetypes: ['text/plain'] }); languageConfigurationRegistry_1.LanguageConfigurationRegistry.register(exports.PLAINTEXT_LANGUAGE_IDENTIFIER, { brackets: [ ['(', ')'], ['[', ']'], ['{', '}'], ], surroundingPairs: [ { open: '{', close: '}' }, { open: '[', close: ']' }, { open: '(', close: ')' }, { open: '<', close: '>' }, { open: '\"', close: '\"' }, { open: '\'', close: '\'' }, { open: '`', close: '`' }, ], folding: { offSide: true } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[511/*vs/editor/common/services/getIconClasses*/], __M([0/*require*/,1/*exports*/,46/*vs/base/common/network*/,39/*vs/base/common/resources*/,118/*vs/editor/common/modes/modesRegistry*/,208/*vs/platform/files/common/files*/]), function (require, exports, network_1, resources_1, modesRegistry_1, files_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function getIconClasses(modelService, modeService, resource, fileKind) { // we always set these base classes even if we do not have a path var 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 var name_1; if (resource.scheme === network_1.Schemas.data) { var metadata = resources_1.DataUri.parseMetaData(resource); name_1 = metadata.get(resources_1.DataUri.META_DATA_LABEL); } else { name_1 = cssEscape(resources_1.basenameOrAuthority(resource).toLowerCase()); } // Folders if (fileKind === files_1.FileKind.FOLDER) { classes.push(name_1 + "-name-folder-icon"); } // Files else { // Name & Extension(s) if (name_1) { classes.push(name_1 + "-name-file-icon"); var dotSegments = name_1.split('.'); for (var 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 var detectedModeId = detectModeId(modelService, modeService, resource); if (detectedModeId) { classes.push(cssEscape(detectedModeId) + "-lang-file-icon"); } } } return classes; } exports.getIconClasses = getIconClasses; function detectModeId(modelService, modeService, resource) { if (!resource) { return null; // we need a resource at least } var modeId = null; // Data URI: check for encoded metadata if (resource.scheme === network_1.Schemas.data) { var metadata = resources_1.DataUri.parseMetaData(resource); var mime = metadata.get(resources_1.DataUri.META_DATA_MIME); if (mime) { modeId = modeService.getModeId(mime); } } // Any other URI: check for model if existing else { var model = modelService.getModel(resource); if (model) { modeId = model.getModeId(); } } // only take if the mode is specific (aka no just plain text) if (modeId && modeId !== modesRegistry_1.PLAINTEXT_MODE_ID) { return modeId; } // otherwise fallback to path based detection return modeService.getModeIdByFilepathOrFirstLine(resource); } exports.detectModeId = detectModeId; function cssEscape(val) { return val.replace(/\s/g, '\\$&'); // make sure to not introduce CSS classes from files that contain whitespace } 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[220/*vs/platform/jsonschemas/common/jsonContributionRegistry*/], __M([0/*require*/,1/*exports*/,42/*vs/platform/registry/common/platform*/,4/*vs/base/common/event*/]), function (require, exports, platform, event_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; } var JSONContributionRegistry = /** @class */ (function () { function JSONContributionRegistry() { this._onDidChangeSchema = new event_1.Emitter(); this.schemasById = {}; } JSONContributionRegistry.prototype.registerSchema = function (uri, unresolvedSchemaContent) { this.schemasById[normalizeId(uri)] = unresolvedSchemaContent; this._onDidChangeSchema.fire(uri); }; JSONContributionRegistry.prototype.notifySchemaChanged = function (uri) { this._onDidChangeSchema.fire(uri); }; return JSONContributionRegistry; }()); var 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[85/*vs/platform/configuration/common/configurationRegistry*/], __M([0/*require*/,1/*exports*/,472/*vs/nls!vs/platform/configuration/common/configurationRegistry*/,4/*vs/base/common/event*/,42/*vs/platform/registry/common/platform*/,21/*vs/base/common/types*/,220/*vs/platform/jsonschemas/common/jsonContributionRegistry*/,38/*vs/base/common/map*/]), function (require, exports, nls, event_1, platform_1, types, jsonContributionRegistry_1, map_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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'; var contributionRegistry = platform_1.Registry.as(jsonContributionRegistry_1.Extensions.JSONContribution); var ConfigurationRegistry = /** @class */ (function () { function ConfigurationRegistry() { this.overrideIdentifiers = new Set(); this._onDidSchemaChange = new event_1.Emitter(); this._onDidUpdateConfiguration = new event_1.Emitter(); this.defaultOverridesConfigurationNode = { id: 'defaultOverrides', title: nls.localize(0, null), properties: {} }; this.configurationContributors = [this.defaultOverridesConfigurationNode]; 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); } ConfigurationRegistry.prototype.registerConfiguration = function (configuration, validate) { if (validate === void 0) { validate = true; } this.registerConfigurations([configuration], validate); }; ConfigurationRegistry.prototype.registerConfigurations = function (configurations, validate) { var _this = this; if (validate === void 0) { validate = true; } var properties = []; configurations.forEach(function (configuration) { properties.push.apply(properties, _this.validateAndRegisterProperties(configuration, validate)); // fills in defaults _this.configurationContributors.push(configuration); _this.registerJSONConfiguration(configuration); }); contributionRegistry.registerSchema(exports.resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema); this._onDidSchemaChange.fire(); this._onDidUpdateConfiguration.fire(properties); }; ConfigurationRegistry.prototype.registerOverrideIdentifiers = function (overrideIdentifiers) { for (var _i = 0, overrideIdentifiers_1 = overrideIdentifiers; _i < overrideIdentifiers_1.length; _i++) { var overrideIdentifier = overrideIdentifiers_1[_i]; this.overrideIdentifiers.add(overrideIdentifier); } this.updateOverridePropertyPatternKey(); }; ConfigurationRegistry.prototype.validateAndRegisterProperties = function (configuration, validate, scope) { if (validate === void 0) { validate = true; } if (scope === void 0) { scope = 3 /* WINDOW */; } scope = types.isUndefinedOrNull(configuration.scope) ? scope : configuration.scope; var propertyKeys = []; var properties = configuration.properties; if (properties) { for (var key in properties) { if (validate && validateProperty(key)) { delete properties[key]; continue; } // fill in default values var property = properties[key]; var defaultValue = property.default; if (types.isUndefined(defaultValue)) { property.default = getDefaultValue(property.type); } if (exports.OVERRIDE_PROPERTY_PATTERN.test(key)) { property.scope = undefined; // No scope for overridable properties `[${identifier}]` } else { property.scope = types.isUndefinedOrNull(property.scope) ? scope : property.scope; } // 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]; } propertyKeys.push(key); } } var subNodes = configuration.allOf; if (subNodes) { for (var _i = 0, subNodes_1 = subNodes; _i < subNodes_1.length; _i++) { var node = subNodes_1[_i]; propertyKeys.push.apply(propertyKeys, this.validateAndRegisterProperties(node, validate, scope)); } } return propertyKeys; }; ConfigurationRegistry.prototype.getConfigurationProperties = function () { return this.configurationProperties; }; ConfigurationRegistry.prototype.registerJSONConfiguration = function (configuration) { var _this = this; var register = function (configuration) { var properties = configuration.properties; if (properties) { for (var key in properties) { exports.allSettings.properties[key] = properties[key]; switch (properties[key].scope) { case 1 /* APPLICATION */: exports.applicationSettings.properties[key] = properties[key]; break; case 2 /* MACHINE */: exports.machineSettings.properties[key] = properties[key]; break; case 6 /* MACHINE_OVERRIDABLE */: exports.machineOverridableSettings.properties[key] = properties[key]; break; case 3 /* WINDOW */: exports.windowSettings.properties[key] = properties[key]; break; case 4 /* RESOURCE */: exports.resourceSettings.properties[key] = properties[key]; break; case 5 /* LANGUAGE_OVERRIDABLE */: exports.resourceSettings.properties[key] = properties[key]; _this.resourceLanguageSettingsSchema.properties[key] = properties[key]; break; } } } var subNodes = configuration.allOf; if (subNodes) { subNodes.forEach(register); } }; register(configuration); }; ConfigurationRegistry.prototype.updateOverridePropertyPatternKey = function () { var _a; for (var _i = 0, _b = map_1.values(this.overrideIdentifiers); _i < _b.length; _i++) { var overrideIdentifier = _b[_i]; var overrideIdentifierProperty = "[" + overrideIdentifier + "]"; var resourceLanguagePropertiesSchema = { type: 'object', description: nls.localize(1, null), errorMessage: nls.localize(2, null), $ref: exports.resourceLanguageSettingsSchemaId, default: (_a = this.defaultOverridesConfigurationNode.properties[overrideIdentifierProperty]) === null || _a === void 0 ? void 0 : _a.default }; 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(); }; return ConfigurationRegistry; }()); var OVERRIDE_PROPERTY = '\\[.*\\]$'; exports.OVERRIDE_PROPERTY_PATTERN = new RegExp(OVERRIDE_PROPERTY); function getDefaultValue(type) { var 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; var configurationRegistry = new ConfigurationRegistry(); platform_1.Registry.add(exports.Extensions.Configuration, configurationRegistry); function validateProperty(property) { if (exports.OVERRIDE_PROPERTY_PATTERN.test(property)) { return nls.localize(3, null, property); } if (configurationRegistry.getConfigurationProperties()[property] !== undefined) { return nls.localize(4, 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[163/*vs/editor/common/config/commonEditorConfig*/], __M([0/*require*/,1/*exports*/,422/*vs/nls!vs/editor/common/config/commonEditorConfig*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,31/*vs/base/common/objects*/,19/*vs/base/common/arrays*/,33/*vs/editor/common/config/editorOptions*/,105/*vs/editor/common/config/editorZoom*/,142/*vs/editor/common/config/fontInfo*/,85/*vs/platform/configuration/common/configurationRegistry*/,42/*vs/platform/registry/common/platform*/,87/*vs/base/common/collections*/]), function (require, exports, nls, event_1, lifecycle_1, objects, arrays, editorOptions_1, editorZoom_1, fontInfo_1, configurationRegistry_1, platform_1, collections_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TabFocus = new /** @class */ (function () { function class_1() { this._tabFocus = false; this._onDidChangeTabFocus = new event_1.Emitter(); this.onDidChangeTabFocus = this._onDidChangeTabFocus.event; } class_1.prototype.getTabFocusMode = function () { return this._tabFocus; }; class_1.prototype.setTabFocusMode = function (tabFocusMode) { if (this._tabFocus === tabFocusMode) { return; } this._tabFocus = tabFocusMode; this._onDidChangeTabFocus.fire(this._tabFocus); }; return class_1; }()); var hasOwnProperty = Object.hasOwnProperty; var ComputedEditorOptions = /** @class */ (function () { function ComputedEditorOptions() { this._values = []; } ComputedEditorOptions.prototype._read = function (id) { return this._values[id]; }; ComputedEditorOptions.prototype.get = function (id) { return this._values[id]; }; ComputedEditorOptions.prototype._write = function (id, value) { this._values[id] = value; }; return ComputedEditorOptions; }()); exports.ComputedEditorOptions = ComputedEditorOptions; var RawEditorOptions = /** @class */ (function () { function RawEditorOptions() { this._values = []; } RawEditorOptions.prototype._read = function (id) { return this._values[id]; }; RawEditorOptions.prototype._write = function (id, value) { this._values[id] = value; }; return RawEditorOptions; }()); var EditorConfiguration2 = /** @class */ (function () { function EditorConfiguration2() { } EditorConfiguration2.readOptions = function (_options) { var options = _options; var result = new RawEditorOptions(); for (var _i = 0, editorOptionsRegistry_2 = editorOptions_1.editorOptionsRegistry; _i < editorOptionsRegistry_2.length; _i++) { var editorOption = editorOptionsRegistry_2[_i]; var value = (editorOption.name === '_never_' ? undefined : options[editorOption.name]); result._write(editorOption.id, value); } return result; }; EditorConfiguration2.validateOptions = function (options) { var result = new editorOptions_1.ValidatedEditorOptions(); for (var _i = 0, editorOptionsRegistry_3 = editorOptions_1.editorOptionsRegistry; _i < editorOptionsRegistry_3.length; _i++) { var editorOption = editorOptionsRegistry_3[_i]; result._write(editorOption.id, editorOption.validate(options._read(editorOption.id))); } return result; }; EditorConfiguration2.computeOptions = function (options, env) { var result = new ComputedEditorOptions(); for (var _i = 0, editorOptionsRegistry_4 = editorOptions_1.editorOptionsRegistry; _i < editorOptionsRegistry_4.length; _i++) { var editorOption = editorOptionsRegistry_4[_i]; result._write(editorOption.id, editorOption.compute(env, result, options._read(editorOption.id))); } return result; }; EditorConfiguration2._deepEquals = function (a, b) { if (typeof a !== 'object' || typeof b !== 'object') { return (a === b); } if (Array.isArray(a) || Array.isArray(b)) { return (Array.isArray(a) && Array.isArray(b) ? arrays.equals(a, b) : false); } for (var key in a) { if (!EditorConfiguration2._deepEquals(a[key], b[key])) { return false; } } return true; }; EditorConfiguration2.checkEquals = function (a, b) { var result = []; var somethingChanged = false; for (var _i = 0, editorOptionsRegistry_5 = editorOptions_1.editorOptionsRegistry; _i < editorOptionsRegistry_5.length; _i++) { var editorOption = editorOptionsRegistry_5[_i]; var changed = !EditorConfiguration2._deepEquals(a._read(editorOption.id), b._read(editorOption.id)); result[editorOption.id] = changed; if (changed) { somethingChanged = true; } } return (somethingChanged ? new editorOptions_1.ConfigurationChangedEvent(result) : null); }; return EditorConfiguration2; }()); /** * Compatibility with old options */ function migrateOptions(options) { var wordWrap = options.wordWrap; if (wordWrap === true) { options.wordWrap = 'on'; } else if (wordWrap === false) { options.wordWrap = 'off'; } var lineNumbers = options.lineNumbers; if (lineNumbers === true) { options.lineNumbers = 'on'; } else if (lineNumbers === false) { options.lineNumbers = 'off'; } var autoClosingBrackets = options.autoClosingBrackets; if (autoClosingBrackets === false) { options.autoClosingBrackets = 'never'; options.autoClosingQuotes = 'never'; options.autoSurround = 'never'; } var cursorBlinking = options.cursorBlinking; if (cursorBlinking === 'visible') { options.cursorBlinking = 'solid'; } var renderWhitespace = options.renderWhitespace; if (renderWhitespace === true) { options.renderWhitespace = 'boundary'; } else if (renderWhitespace === false) { options.renderWhitespace = 'none'; } var renderLineHighlight = options.renderLineHighlight; if (renderLineHighlight === true) { options.renderLineHighlight = 'line'; } else if (renderLineHighlight === false) { options.renderLineHighlight = 'none'; } var acceptSuggestionOnEnter = options.acceptSuggestionOnEnter; if (acceptSuggestionOnEnter === true) { options.acceptSuggestionOnEnter = 'on'; } else if (acceptSuggestionOnEnter === false) { options.acceptSuggestionOnEnter = 'off'; } var tabCompletion = options.tabCompletion; if (tabCompletion === false) { options.tabCompletion = 'off'; } else if (tabCompletion === true) { options.tabCompletion = 'onlySnippets'; } var suggest = options.suggest; if (suggest && typeof suggest.filteredTypes === 'object' && suggest.filteredTypes) { var mapping = {}; mapping['method'] = 'showMethods'; mapping['function'] = 'showFunctions'; mapping['constructor'] = 'showConstructors'; 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'; collections_1.forEach(mapping, function (entry) { var value = suggest.filteredTypes[entry.key]; if (value === false) { suggest[entry.value] = value; } }); // delete (suggest).filteredTypes; } var hover = options.hover; if (hover === true) { options.hover = { enabled: true }; } else if (hover === false) { options.hover = { enabled: false }; } var parameterHints = options.parameterHints; if (parameterHints === true) { options.parameterHints = { enabled: true }; } else if (parameterHints === false) { options.parameterHints = { enabled: false }; } var autoIndent = options.autoIndent; if (autoIndent === true) { options.autoIndent = 'full'; } else if (autoIndent === false) { options.autoIndent = 'advanced'; } var matchBrackets = options.matchBrackets; if (matchBrackets === true) { options.matchBrackets = 'always'; } else if (matchBrackets === false) { options.matchBrackets = 'never'; } } function deepCloneAndMigrateOptions(_options) { var options = objects.deepClone(_options); migrateOptions(options); return options; } var CommonEditorConfiguration = /** @class */ (function (_super) { __extends(CommonEditorConfiguration, _super); function CommonEditorConfiguration(isSimpleWidget, _options) { var _this = _super.call(this) || this; _this._onDidChange = _this._register(new event_1.Emitter()); _this.onDidChange = _this._onDidChange.event; _this.isSimpleWidget = isSimpleWidget; _this._isDominatedByLongLines = false; _this._lineNumbersDigitCount = 1; _this._rawOptions = deepCloneAndMigrateOptions(_options); _this._readOptions = EditorConfiguration2.readOptions(_this._rawOptions); _this._validatedOptions = EditorConfiguration2.validateOptions(_this._readOptions); _this._register(editorZoom_1.EditorZoom.onDidChangeZoomLevel(function (_) { return _this._recomputeOptions(); })); _this._register(exports.TabFocus.onDidChangeTabFocus(function (_) { return _this._recomputeOptions(); })); return _this; } CommonEditorConfiguration.prototype.observeReferenceElement = function (dimension) { }; CommonEditorConfiguration.prototype.dispose = function () { _super.prototype.dispose.call(this); }; CommonEditorConfiguration.prototype._recomputeOptions = function () { var oldOptions = this.options; var newOptions = this._computeInternalOptions(); if (!oldOptions) { this.options = newOptions; } else { var changeEvent = EditorConfiguration2.checkEquals(oldOptions, newOptions); if (changeEvent === null) { // nothing changed! return; } this.options = newOptions; this._onDidChange.fire(changeEvent); } }; CommonEditorConfiguration.prototype.getRawOptions = function () { return this._rawOptions; }; CommonEditorConfiguration.prototype._computeInternalOptions = function () { var partialEnv = this._getEnvConfiguration(); var bareFontInfo = fontInfo_1.BareFontInfo.createFromValidatedSettings(this._validatedOptions, partialEnv.zoomLevel, this.isSimpleWidget); var env = { outerWidth: partialEnv.outerWidth, outerHeight: partialEnv.outerHeight, fontInfo: this.readConfiguration(bareFontInfo), extraEditorClassName: partialEnv.extraEditorClassName, isDominatedByLongLines: this._isDominatedByLongLines, lineNumbersDigitCount: this._lineNumbersDigitCount, emptySelectionClipboard: partialEnv.emptySelectionClipboard, pixelRatio: partialEnv.pixelRatio, tabFocusMode: exports.TabFocus.getTabFocusMode(), accessibilitySupport: partialEnv.accessibilitySupport }; return EditorConfiguration2.computeOptions(this._validatedOptions, env); }; CommonEditorConfiguration._subsetEquals = function (base, subset) { for (var key in subset) { if (hasOwnProperty.call(subset, key)) { var subsetValue = subset[key]; var baseValue = base[key]; if (baseValue === subsetValue) { continue; } if (Array.isArray(baseValue) && Array.isArray(subsetValue)) { if (!arrays.equals(baseValue, subsetValue)) { return false; } continue; } if (typeof baseValue === 'object' && typeof subsetValue === 'object') { if (!this._subsetEquals(baseValue, subsetValue)) { return false; } continue; } return false; } } return true; }; CommonEditorConfiguration.prototype.updateOptions = function (_newOptions) { if (typeof _newOptions === 'undefined') { return; } var newOptions = deepCloneAndMigrateOptions(_newOptions); if (CommonEditorConfiguration._subsetEquals(this._rawOptions, newOptions)) { return; } this._rawOptions = objects.mixin(this._rawOptions, newOptions || {}); this._readOptions = EditorConfiguration2.readOptions(this._rawOptions); this._validatedOptions = EditorConfiguration2.validateOptions(this._readOptions); this._recomputeOptions(); }; CommonEditorConfiguration.prototype.setIsDominatedByLongLines = function (isDominatedByLongLines) { this._isDominatedByLongLines = isDominatedByLongLines; this._recomputeOptions(); }; CommonEditorConfiguration.prototype.setMaxLineNumber = function (maxLineNumber) { var digitCount = CommonEditorConfiguration._digitCount(maxLineNumber); if (this._lineNumbersDigitCount === digitCount) { return; } this._lineNumbersDigitCount = digitCount; this._recomputeOptions(); }; CommonEditorConfiguration._digitCount = function (n) { var r = 0; while (n) { n = Math.floor(n / 10); r++; } return r ? r : 1; }; return CommonEditorConfiguration; }(lifecycle_1.Disposable)); exports.CommonEditorConfiguration = CommonEditorConfiguration; exports.editorConfigurationBaseNode = Object.freeze({ id: 'editor', order: 5, type: 'object', title: nls.localize(0, null), scope: 5 /* LANGUAGE_OVERRIDABLE */, }); var configurationRegistry = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration); var editorConfiguration = __assign(__assign({}, exports.editorConfigurationBaseNode), { properties: { 'editor.tabSize': { type: 'number', default: editorOptions_1.EDITOR_MODEL_DEFAULTS.tabSize, minimum: 1, markdownDescription: nls.localize(1, null) }, // 'editor.indentSize': { // 'anyOf': [ // { // type: 'string', // enum: ['tabSize'] // }, // { // type: 'number', // minimum: 1 // } // ], // default: 'tabSize', // markdownDescription: nls.localize('indentSize', "The number of spaces used for indentation or 'tabSize' to use the value from `#editor.tabSize#`. This setting is overridden based on the file contents when `#editor.detectIndentation#` is on.") // }, 'editor.insertSpaces': { type: 'boolean', default: editorOptions_1.EDITOR_MODEL_DEFAULTS.insertSpaces, markdownDescription: nls.localize(2, null) }, 'editor.detectIndentation': { type: 'boolean', default: editorOptions_1.EDITOR_MODEL_DEFAULTS.detectIndentation, markdownDescription: nls.localize(3, null) }, 'editor.trimAutoWhitespace': { type: 'boolean', default: editorOptions_1.EDITOR_MODEL_DEFAULTS.trimAutoWhitespace, description: nls.localize(4, null) }, 'editor.largeFileOptimizations': { type: 'boolean', default: editorOptions_1.EDITOR_MODEL_DEFAULTS.largeFileOptimizations, description: nls.localize(5, null) }, 'editor.wordBasedSuggestions': { type: 'boolean', default: true, description: nls.localize(6, null) }, 'editor.semanticHighlighting.enabled': { type: 'boolean', default: false, description: nls.localize(7, null) }, 'editor.stablePeek': { type: 'boolean', default: false, markdownDescription: nls.localize(8, null) }, 'editor.maxTokenizationLineLength': { type: 'integer', default: 20000, description: nls.localize(9, null) }, 'diffEditor.maxComputationTime': { type: 'number', default: 5000, description: nls.localize(10, null) }, 'diffEditor.renderSideBySide': { type: 'boolean', default: true, description: nls.localize(11, null) }, 'diffEditor.ignoreTrimWhitespace': { type: 'boolean', default: true, description: nls.localize(12, null) }, 'diffEditor.renderIndicators': { type: 'boolean', default: true, description: nls.localize(13, null) } } }); function isConfigurationPropertySchema(x) { return (typeof x.type !== 'undefined' || typeof x.anyOf !== 'undefined'); } // Add properties from the Editor Option Registry for (var _i = 0, editorOptionsRegistry_1 = editorOptions_1.editorOptionsRegistry; _i < editorOptionsRegistry_1.length; _i++) { var editorOption = editorOptionsRegistry_1[_i]; var schema = editorOption.schema; if (typeof schema !== 'undefined') { if (isConfigurationPropertySchema(schema)) { // This is a single schema contribution editorConfiguration.properties["editor." + editorOption.name] = schema; } else { for (var key in schema) { if (hasOwnProperty.call(schema, key)) { editorConfiguration.properties[key] = schema[key]; } } } } } var cachedEditorConfigurationKeys = null; function getEditorConfigurationKeys() { if (cachedEditorConfigurationKeys === null) { cachedEditorConfigurationKeys = Object.create(null); Object.keys(editorConfiguration.properties).forEach(function (prop) { cachedEditorConfigurationKeys[prop] = true; }); } return cachedEditorConfigurationKeys; } function isEditorConfigurationKey(key) { var editorConfigurationKeys = getEditorConfigurationKeys(); return (editorConfigurationKeys["editor." + key] || false); } exports.isEditorConfigurationKey = isEditorConfigurationKey; function isDiffEditorConfigurationKey(key) { var editorConfigurationKeys = getEditorConfigurationKeys(); return (editorConfigurationKeys["diffEditor." + key] || false); } exports.isDiffEditorConfigurationKey = isDiffEditorConfigurationKey; configurationRegistry.registerConfiguration(editorConfiguration); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[60/*vs/editor/browser/config/configuration*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,333/*vs/editor/browser/config/charWidthReader*/,185/*vs/editor/browser/config/elementSizeObserver*/,163/*vs/editor/common/config/commonEditorConfig*/,33/*vs/editor/common/config/editorOptions*/,142/*vs/editor/common/config/fontInfo*/]), function (require, exports, browser, event_1, lifecycle_1, platform, charWidthReader_1, elementSizeObserver_1, commonEditorConfig_1, editorOptions_1, fontInfo_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CSSBasedConfigurationCache = /** @class */ (function () { function CSSBasedConfigurationCache() { this._keys = Object.create(null); this._values = Object.create(null); } CSSBasedConfigurationCache.prototype.has = function (item) { var itemId = item.getId(); return !!this._values[itemId]; }; CSSBasedConfigurationCache.prototype.get = function (item) { var itemId = item.getId(); return this._values[itemId]; }; CSSBasedConfigurationCache.prototype.put = function (item, value) { var itemId = item.getId(); this._keys[itemId] = item; this._values[itemId] = value; }; CSSBasedConfigurationCache.prototype.remove = function (item) { var itemId = item.getId(); delete this._keys[itemId]; delete this._values[itemId]; }; CSSBasedConfigurationCache.prototype.getValues = function () { var _this = this; return Object.keys(this._keys).map(function (id) { return _this._values[id]; }); }; return CSSBasedConfigurationCache; }()); function clearAllFontInfos() { CSSBasedConfiguration.INSTANCE.clearCache(); } exports.clearAllFontInfos = clearAllFontInfos; var CSSBasedConfiguration = /** @class */ (function (_super) { __extends(CSSBasedConfiguration, _super); function CSSBasedConfiguration() { var _this = _super.call(this) || this; _this._onDidChange = _this._register(new event_1.Emitter()); _this.onDidChange = _this._onDidChange.event; _this._cache = new CSSBasedConfigurationCache(); _this._evictUntrustedReadingsTimeout = -1; return _this; } CSSBasedConfiguration.prototype.dispose = function () { if (this._evictUntrustedReadingsTimeout !== -1) { clearTimeout(this._evictUntrustedReadingsTimeout); this._evictUntrustedReadingsTimeout = -1; } _super.prototype.dispose.call(this); }; CSSBasedConfiguration.prototype.clearCache = function () { this._cache = new CSSBasedConfigurationCache(); this._onDidChange.fire(); }; CSSBasedConfiguration.prototype._writeToCache = function (item, value) { var _this = this; this._cache.put(item, value); if (!value.isTrusted && this._evictUntrustedReadingsTimeout === -1) { // Try reading again after some time this._evictUntrustedReadingsTimeout = setTimeout(function () { _this._evictUntrustedReadingsTimeout = -1; _this._evictUntrustedReadings(); }, 5000); } }; CSSBasedConfiguration.prototype._evictUntrustedReadings = function () { var values = this._cache.getValues(); var somethingRemoved = false; for (var i = 0, len = values.length; i < len; i++) { var item = values[i]; if (!item.isTrusted) { somethingRemoved = true; this._cache.remove(item); } } if (somethingRemoved) { this._onDidChange.fire(); } }; CSSBasedConfiguration.prototype.readConfiguration = function (bareFontInfo) { if (!this._cache.has(bareFontInfo)) { var readConfig = CSSBasedConfiguration._actualReadConfiguration(bareFontInfo); if (readConfig.typicalHalfwidthCharacterWidth <= 2 || readConfig.typicalFullwidthCharacterWidth <= 2 || readConfig.spaceWidth <= 2 || readConfig.maxDigitWidth <= 2) { // Hey, it's Bug 14341 ... we couldn't read readConfig = new fontInfo_1.FontInfo({ zoomLevel: browser.getZoomLevel(), 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), maxDigitWidth: Math.max(readConfig.maxDigitWidth, 5), }, false); } this._writeToCache(bareFontInfo, readConfig); } return this._cache.get(bareFontInfo); }; CSSBasedConfiguration.createRequest = function (chr, type, all, monospace) { var result = new charWidthReader_1.CharWidthRequest(chr, type); all.push(result); if (monospace) { monospace.push(result); } return result; }; CSSBasedConfiguration._actualReadConfiguration = function (bareFontInfo) { var all = []; var monospace = []; var typicalHalfwidthCharacter = this.createRequest('n', 0 /* Regular */, all, monospace); var typicalFullwidthCharacter = this.createRequest('\uff4d', 0 /* Regular */, all, null); var space = this.createRequest(' ', 0 /* Regular */, all, monospace); var digit0 = this.createRequest('0', 0 /* Regular */, all, monospace); var digit1 = this.createRequest('1', 0 /* Regular */, all, monospace); var digit2 = this.createRequest('2', 0 /* Regular */, all, monospace); var digit3 = this.createRequest('3', 0 /* Regular */, all, monospace); var digit4 = this.createRequest('4', 0 /* Regular */, all, monospace); var digit5 = this.createRequest('5', 0 /* Regular */, all, monospace); var digit6 = this.createRequest('6', 0 /* Regular */, all, monospace); var digit7 = this.createRequest('7', 0 /* Regular */, all, monospace); var digit8 = this.createRequest('8', 0 /* Regular */, all, monospace); var digit9 = this.createRequest('9', 0 /* Regular */, all, monospace); // monospace test: used for whitespace rendering var rightwardsArrow = this.createRequest('→', 0 /* Regular */, all, monospace); var halfwidthRightwardsArrow = this.createRequest('→', 0 /* Regular */, all, null); // middle dot character var middot = this.createRequest('·', 0 /* Regular */, all, monospace); // monospace test: some characters this.createRequest('|', 0 /* Regular */, all, monospace); this.createRequest('/', 0 /* Regular */, all, monospace); this.createRequest('-', 0 /* Regular */, all, monospace); this.createRequest('_', 0 /* Regular */, all, monospace); this.createRequest('i', 0 /* Regular */, all, monospace); this.createRequest('l', 0 /* Regular */, all, monospace); this.createRequest('m', 0 /* Regular */, all, monospace); // monospace italic test this.createRequest('|', 1 /* Italic */, all, monospace); this.createRequest('_', 1 /* Italic */, all, monospace); this.createRequest('i', 1 /* Italic */, all, monospace); this.createRequest('l', 1 /* Italic */, all, monospace); this.createRequest('m', 1 /* Italic */, all, monospace); this.createRequest('n', 1 /* Italic */, all, monospace); // monospace bold test this.createRequest('|', 2 /* Bold */, all, monospace); this.createRequest('_', 2 /* Bold */, all, monospace); this.createRequest('i', 2 /* Bold */, all, monospace); this.createRequest('l', 2 /* Bold */, all, monospace); this.createRequest('m', 2 /* Bold */, all, monospace); this.createRequest('n', 2 /* Bold */, all, monospace); charWidthReader_1.readCharWidths(bareFontInfo, all); var maxDigitWidth = Math.max(digit0.width, digit1.width, digit2.width, digit3.width, digit4.width, digit5.width, digit6.width, digit7.width, digit8.width, digit9.width); var isMonospace = (bareFontInfo.fontFeatureSettings === editorOptions_1.EditorFontLigatures.OFF); var referenceWidth = monospace[0].width; for (var i = 1, len = monospace.length; isMonospace && i < len; i++) { var diff = referenceWidth - monospace[i].width; if (diff < -0.001 || diff > 0.001) { isMonospace = false; break; } } var canUseHalfwidthRightwardsArrow = true; if (isMonospace && halfwidthRightwardsArrow.width !== referenceWidth) { // using a halfwidth rightwards arrow would break monospace... canUseHalfwidthRightwardsArrow = false; } if (halfwidthRightwardsArrow.width > rightwardsArrow.width) { // using a halfwidth rightwards arrow would paint a larger arrow than a regular rightwards arrow canUseHalfwidthRightwardsArrow = false; } // let's trust the zoom level only 2s after it was changed. var canTrustBrowserZoomLevel = (browser.getTimeSinceLastZoomLevelChanged() > 2000); return new fontInfo_1.FontInfo({ zoomLevel: browser.getZoomLevel(), 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, maxDigitWidth: maxDigitWidth }, canTrustBrowserZoomLevel); }; CSSBasedConfiguration.INSTANCE = new CSSBasedConfiguration(); return CSSBasedConfiguration; }(lifecycle_1.Disposable)); var Configuration = /** @class */ (function (_super) { __extends(Configuration, _super); function Configuration(isSimpleWidget, options, referenceDomElement, accessibilityService) { if (referenceDomElement === void 0) { referenceDomElement = null; } var _this = _super.call(this, isSimpleWidget, options) || this; _this.accessibilityService = accessibilityService; _this._elementSizeObserver = _this._register(new elementSizeObserver_1.ElementSizeObserver(referenceDomElement, options.dimension, function () { return _this._onReferenceDomElementSizeChanged(); })); _this._register(CSSBasedConfiguration.INSTANCE.onDidChange(function () { return _this._onCSSBasedConfigurationChanged(); })); if (_this._validatedOptions.get(9 /* automaticLayout */)) { _this._elementSizeObserver.startObserving(); } _this._register(browser.onDidChangeZoomLevel(function (_) { return _this._recomputeOptions(); })); _this._register(_this.accessibilityService.onDidChangeScreenReaderOptimized(function () { return _this._recomputeOptions(); })); _this._recomputeOptions(); return _this; } Configuration.applyFontInfoSlow = function (domNode, fontInfo) { domNode.style.fontFamily = fontInfo.getMassagedFontFamily(); domNode.style.fontWeight = fontInfo.fontWeight; domNode.style.fontSize = fontInfo.fontSize + 'px'; domNode.style.fontFeatureSettings = fontInfo.fontFeatureSettings; domNode.style.lineHeight = fontInfo.lineHeight + 'px'; domNode.style.letterSpacing = fontInfo.letterSpacing + 'px'; }; Configuration.applyFontInfo = function (domNode, fontInfo) { domNode.setFontFamily(fontInfo.getMassagedFontFamily()); domNode.setFontWeight(fontInfo.fontWeight); domNode.setFontSize(fontInfo.fontSize); domNode.setFontFeatureSettings(fontInfo.fontFeatureSettings); domNode.setLineHeight(fontInfo.lineHeight); domNode.setLetterSpacing(fontInfo.letterSpacing); }; Configuration.prototype._onReferenceDomElementSizeChanged = function () { this._recomputeOptions(); }; Configuration.prototype._onCSSBasedConfigurationChanged = function () { this._recomputeOptions(); }; Configuration.prototype.observeReferenceElement = function (dimension) { this._elementSizeObserver.observe(dimension); }; Configuration.prototype.dispose = function () { _super.prototype.dispose.call(this); }; Configuration.prototype._getExtraEditorClassName = function () { var extra = ''; if (!browser.isSafari && !browser.isWebkitWebView) { // Use user-select: none in all browsers except Safari and native macOS WebView extra += 'no-user-select '; } if (platform.isMacintosh) { extra += 'mac '; } return extra; }; Configuration.prototype._getEnvConfiguration = function () { return { extraEditorClassName: this._getExtraEditorClassName(), outerWidth: this._elementSizeObserver.getWidth(), outerHeight: this._elementSizeObserver.getHeight(), emptySelectionClipboard: browser.isWebKit || browser.isFirefox, pixelRatio: browser.getPixelRatio(), zoomLevel: browser.getZoomLevel(), accessibilitySupport: (this.accessibilityService.isScreenReaderOptimized() ? 2 /* Enabled */ : this.accessibilityService.getAccessibilitySupport()) }; }; Configuration.prototype.readConfiguration = function (bareFontInfo) { return CSSBasedConfiguration.INSTANCE.readConfiguration(bareFontInfo); }; return Configuration; }(commonEditorConfig_1.CommonEditorConfiguration)); exports.Configuration = Configuration; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[512/*vs/editor/browser/view/domLineBreaksComputer*/], __M([0/*require*/,1/*exports*/,161/*vs/editor/common/viewModel/splitLinesCollection*/,106/*vs/editor/common/core/stringBuilder*/,5/*vs/base/common/strings*/,60/*vs/editor/browser/config/configuration*/]), function (require, exports, splitLinesCollection_1, stringBuilder_1, strings, configuration_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DOMLineBreaksComputerFactory = /** @class */ (function () { function DOMLineBreaksComputerFactory() { } DOMLineBreaksComputerFactory.create = function () { return new DOMLineBreaksComputerFactory(); }; DOMLineBreaksComputerFactory.prototype.createLineBreaksComputer = function (fontInfo, tabSize, wrappingColumn, wrappingIndent) { tabSize = tabSize | 0; //@perf wrappingColumn = +wrappingColumn; //@perf var requests = []; return { addRequest: function (lineText, previousLineBreakData) { requests.push(lineText); }, finalize: function () { return createLineBreaks(requests, fontInfo, tabSize, wrappingColumn, wrappingIndent); } }; }; return DOMLineBreaksComputerFactory; }()); exports.DOMLineBreaksComputerFactory = DOMLineBreaksComputerFactory; function createLineBreaks(requests, fontInfo, tabSize, firstLineBreakColumn, wrappingIndent) { if (firstLineBreakColumn === -1) { var result_1 = []; for (var i = 0, len = requests.length; i < len; i++) { result_1[i] = null; } return result_1; } var overallWidth = Math.round(firstLineBreakColumn * fontInfo.typicalHalfwidthCharacterWidth); // Cannot respect WrappingIndent.Indent and WrappingIndent.DeepIndent because that would require // two dom layouts, in order to first set the width of the first line, and then set the width of the wrapped lines if (wrappingIndent === 2 /* Indent */ || wrappingIndent === 3 /* DeepIndent */) { wrappingIndent = 1 /* Same */; } var containerDomNode = document.createElement('div'); configuration_1.Configuration.applyFontInfoSlow(containerDomNode, fontInfo); var sb = stringBuilder_1.createStringBuilder(10000); var firstNonWhitespaceIndices = []; var wrappedTextIndentLengths = []; var renderLineContents = []; var allCharOffsets = []; var allVisibleColumns = []; for (var i = 0; i < requests.length; i++) { var lineContent = requests[i]; var firstNonWhitespaceIndex = 0; var wrappedTextIndentLength = 0; var width = overallWidth; if (wrappingIndent !== 0 /* None */) { firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent); if (firstNonWhitespaceIndex === -1) { // all whitespace line firstNonWhitespaceIndex = 0; } else { // Track existing indent for (var i_1 = 0; i_1 < firstNonWhitespaceIndex; i_1++) { var charWidth = (lineContent.charCodeAt(i_1) === 9 /* Tab */ ? (tabSize - (wrappedTextIndentLength % tabSize)) : 1); wrappedTextIndentLength += charWidth; } var 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; } } } var renderLineContent = lineContent.substr(firstNonWhitespaceIndex); var tmp = renderLine(renderLineContent, wrappedTextIndentLength, tabSize, width, sb); firstNonWhitespaceIndices[i] = firstNonWhitespaceIndex; wrappedTextIndentLengths[i] = wrappedTextIndentLength; renderLineContents[i] = renderLineContent; allCharOffsets[i] = tmp[0]; allVisibleColumns[i] = tmp[1]; } containerDomNode.innerHTML = sb.build(); containerDomNode.style.position = 'absolute'; containerDomNode.style.top = '10000'; containerDomNode.style.wordWrap = 'break-word'; document.body.appendChild(containerDomNode); var range = document.createRange(); var lineDomNodes = Array.prototype.slice.call(containerDomNode.children, 0); var result = []; for (var i = 0; i < requests.length; i++) { var lineDomNode = lineDomNodes[i]; var breakOffsets = readLineBreaks(range, lineDomNode, renderLineContents[i], allCharOffsets[i]); if (breakOffsets === null) { result[i] = null; continue; } var firstNonWhitespaceIndex = firstNonWhitespaceIndices[i]; var wrappedTextIndentLength = wrappedTextIndentLengths[i]; var visibleColumns = allVisibleColumns[i]; var breakOffsetsVisibleColumn = []; for (var 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 (var j = 0, len = breakOffsets.length; j < len; j++) { breakOffsets[j] += firstNonWhitespaceIndex; } } result[i] = new splitLinesCollection_1.LineBreakData(breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength); } document.body.removeChild(containerDomNode); return result; } function renderLine(lineContent, initialVisibleColumn, tabSize, width, sb) { sb.appendASCIIString('
    '); // if (containsRTL) { // sb.appendASCIIString('" dir="ltr'); // } var len = lineContent.length; var visibleColumn = initialVisibleColumn; var charOffset = 0; var charOffsets = []; var visibleColumns = []; var nextCharCode = (0 < len ? lineContent.charCodeAt(0) : 0 /* Null */); for (var charIndex = 0; charIndex < len; charIndex++) { charOffsets[charIndex] = charOffset; visibleColumns[charIndex] = visibleColumn; var charCode = nextCharCode; nextCharCode = (charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0 /* Null */); var producedCharacters = 1; var charWidth = 1; switch (charCode) { case 9 /* Tab */: producedCharacters = (tabSize - (visibleColumn % tabSize)); charWidth = producedCharacters; for (var 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_2028 */: sb.write1(0xFFFD); break; default: if (strings.isFullWidthCharacter(charCode)) { charWidth++; } // if (renderControlCharacters && charCode < 32) { // sb.write1(9216 + charCode); // } else { sb.write1(charCode); // } } charOffset += producedCharacters; visibleColumn += charWidth; } 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; } var textContentNode = lineDomNode.firstChild; var breakOffsets = []; discoverBreaks(range, textContentNode, charOffsets, 0, null, lineContent.length - 1, null, breakOffsets); if (breakOffsets.length === 0) { return null; } breakOffsets.push(lineContent.length); return breakOffsets; } function discoverBreaks(range, textContentNode, charOffsets, low, lowRects, high, highRects, result) { if (low === high) { return; } lowRects = lowRects || readClientRect(range, textContentNode, charOffsets[low], charOffsets[low + 1]); highRects = highRects || readClientRect(range, textContentNode, 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; } var mid = low + ((high - low) / 2) | 0; var midRects = readClientRect(range, textContentNode, charOffsets[mid], charOffsets[mid + 1]); discoverBreaks(range, textContentNode, charOffsets, low, lowRects, mid, midRects, result); discoverBreaks(range, textContentNode, charOffsets, mid, midRects, high, highRects, result); } function readClientRect(range, textContentNode, startOffset, endOffset) { range.setStart(textContentNode, startOffset); range.setEnd(textContentNode, endOffset); 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[513/*vs/editor/browser/view/viewOverlays*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,60/*vs/editor/browser/config/configuration*/,143/*vs/editor/browser/view/viewLayer*/,37/*vs/editor/browser/view/viewPart*/]), function (require, exports, fastDomNode_1, configuration_1, viewLayer_1, viewPart_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ViewOverlays = /** @class */ (function (_super) { __extends(ViewOverlays, _super); function ViewOverlays(context) { var _this = _super.call(this, context) || this; _this._visibleLines = new viewLayer_1.VisibleLinesCollection(_this); _this.domNode = _this._visibleLines.domNode; _this._dynamicOverlays = []; _this._isFocused = false; _this.domNode.setClassName('view-overlays'); return _this; } ViewOverlays.prototype.shouldRender = function () { if (_super.prototype.shouldRender.call(this)) { return true; } for (var i = 0, len = this._dynamicOverlays.length; i < len; i++) { var dynamicOverlay = this._dynamicOverlays[i]; if (dynamicOverlay.shouldRender()) { return true; } } return false; }; ViewOverlays.prototype.dispose = function () { _super.prototype.dispose.call(this); for (var i = 0, len = this._dynamicOverlays.length; i < len; i++) { var dynamicOverlay = this._dynamicOverlays[i]; dynamicOverlay.dispose(); } this._dynamicOverlays = []; }; ViewOverlays.prototype.getDomNode = function () { return this.domNode; }; // ---- begin IVisibleLinesHost ViewOverlays.prototype.createVisibleLine = function () { return new ViewOverlayLine(this._context.configuration, this._dynamicOverlays); }; // ---- end IVisibleLinesHost ViewOverlays.prototype.addDynamicOverlay = function (overlay) { this._dynamicOverlays.push(overlay); }; // ----- event handlers ViewOverlays.prototype.onConfigurationChanged = function (e) { this._visibleLines.onConfigurationChanged(e); var startLineNumber = this._visibleLines.getStartLineNumber(); var endLineNumber = this._visibleLines.getEndLineNumber(); for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { var line = this._visibleLines.getVisibleLine(lineNumber); line.onConfigurationChanged(e); } return true; }; ViewOverlays.prototype.onFlushed = function (e) { return this._visibleLines.onFlushed(e); }; ViewOverlays.prototype.onFocusChanged = function (e) { this._isFocused = e.isFocused; return true; }; ViewOverlays.prototype.onLinesChanged = function (e) { return this._visibleLines.onLinesChanged(e); }; ViewOverlays.prototype.onLinesDeleted = function (e) { return this._visibleLines.onLinesDeleted(e); }; ViewOverlays.prototype.onLinesInserted = function (e) { return this._visibleLines.onLinesInserted(e); }; ViewOverlays.prototype.onScrollChanged = function (e) { return this._visibleLines.onScrollChanged(e) || true; }; ViewOverlays.prototype.onTokensChanged = function (e) { return this._visibleLines.onTokensChanged(e); }; ViewOverlays.prototype.onZonesChanged = function (e) { return this._visibleLines.onZonesChanged(e); }; // ----- end event handlers ViewOverlays.prototype.prepareRender = function (ctx) { var toRender = this._dynamicOverlays.filter(function (overlay) { return overlay.shouldRender(); }); for (var i = 0, len = toRender.length; i < len; i++) { var dynamicOverlay = toRender[i]; dynamicOverlay.prepareRender(ctx); dynamicOverlay.onDidRender(); } }; ViewOverlays.prototype.render = function (ctx) { // Overwriting to bypass `shouldRender` flag this._viewOverlaysRender(ctx); this.domNode.toggleClassName('focused', this._isFocused); }; ViewOverlays.prototype._viewOverlaysRender = function (ctx) { this._visibleLines.renderLines(ctx.viewportData); }; return ViewOverlays; }(viewPart_1.ViewPart)); exports.ViewOverlays = ViewOverlays; var ViewOverlayLine = /** @class */ (function () { function ViewOverlayLine(configuration, dynamicOverlays) { this._configuration = configuration; this._lineHeight = this._configuration.options.get(49 /* lineHeight */); this._dynamicOverlays = dynamicOverlays; this._domNode = null; this._renderedContent = null; } ViewOverlayLine.prototype.getDomNode = function () { if (!this._domNode) { return null; } return this._domNode.domNode; }; ViewOverlayLine.prototype.setDomNode = function (domNode) { this._domNode = fastDomNode_1.createFastDomNode(domNode); }; ViewOverlayLine.prototype.onContentChanged = function () { // Nothing }; ViewOverlayLine.prototype.onTokensChanged = function () { // Nothing }; ViewOverlayLine.prototype.onConfigurationChanged = function (e) { this._lineHeight = this._configuration.options.get(49 /* lineHeight */); }; ViewOverlayLine.prototype.renderLine = function (lineNumber, deltaTop, viewportData, sb) { var result = ''; for (var i = 0, len = this._dynamicOverlays.length; i < len; i++) { var 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; }; ViewOverlayLine.prototype.layoutLine = function (lineNumber, deltaTop) { if (this._domNode) { this._domNode.setTop(deltaTop); this._domNode.setHeight(this._lineHeight); } }; return ViewOverlayLine; }()); exports.ViewOverlayLine = ViewOverlayLine; var ContentViewOverlays = /** @class */ (function (_super) { __extends(ContentViewOverlays, _super); function ContentViewOverlays(context) { var _this = _super.call(this, context) || this; var options = _this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); _this._contentWidth = layoutInfo.contentWidth; _this.domNode.setHeight(0); return _this; } // --- begin event handlers ContentViewOverlays.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); this._contentWidth = layoutInfo.contentWidth; return _super.prototype.onConfigurationChanged.call(this, e) || true; }; ContentViewOverlays.prototype.onScrollChanged = function (e) { return _super.prototype.onScrollChanged.call(this, e) || e.scrollWidthChanged; }; // --- end event handlers ContentViewOverlays.prototype._viewOverlaysRender = function (ctx) { _super.prototype._viewOverlaysRender.call(this, ctx); this.domNode.setWidth(Math.max(ctx.scrollWidth, this._contentWidth)); }; return ContentViewOverlays; }(ViewOverlays)); exports.ContentViewOverlays = ContentViewOverlays; var MarginViewOverlays = /** @class */ (function (_super) { __extends(MarginViewOverlays, _super); function MarginViewOverlays(context) { var _this = _super.call(this, context) || this; var options = _this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); _this._contentLeft = layoutInfo.contentLeft; _this.domNode.setClassName('margin-view-overlays'); _this.domNode.setWidth(1); configuration_1.Configuration.applyFontInfo(_this.domNode, options.get(34 /* fontInfo */)); return _this; } MarginViewOverlays.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; configuration_1.Configuration.applyFontInfo(this.domNode, options.get(34 /* fontInfo */)); var layoutInfo = options.get(107 /* layoutInfo */); this._contentLeft = layoutInfo.contentLeft; return _super.prototype.onConfigurationChanged.call(this, e) || true; }; MarginViewOverlays.prototype.onScrollChanged = function (e) { return _super.prototype.onScrollChanged.call(this, e) || e.scrollHeightChanged; }; MarginViewOverlays.prototype._viewOverlaysRender = function (ctx) { _super.prototype._viewOverlaysRender.call(this, ctx); var height = Math.min(ctx.scrollHeight, 1000000); this.domNode.setHeight(height); this.domNode.setWidth(this._contentLeft); }; return MarginViewOverlays; }(ViewOverlays)); 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[514/*vs/editor/browser/viewParts/viewCursors/viewCursor*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,28/*vs/base/browser/fastDomNode*/,5/*vs/base/common/strings*/,60/*vs/editor/browser/config/configuration*/,33/*vs/editor/common/config/editorOptions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, dom, fastDomNode_1, strings, configuration_1, editorOptions_1, position_1, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ViewCursorRenderData = /** @class */ (function () { function ViewCursorRenderData(top, left, width, height, textContent, textContentClassName) { this.top = top; this.left = left; this.width = width; this.height = height; this.textContent = textContent; this.textContentClassName = textContentClassName; } return ViewCursorRenderData; }()); var ViewCursor = /** @class */ (function () { function ViewCursor(context) { this._context = context; var options = this._context.configuration.options; var fontInfo = options.get(34 /* fontInfo */); this._cursorStyle = options.get(18 /* cursorStyle */); this._lineHeight = options.get(49 /* lineHeight */); this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth; this._lineCursorWidth = Math.min(options.get(21 /* cursorWidth */), this._typicalHalfwidthCharacterWidth); this._isVisible = true; // Create the dom node this._domNode = fastDomNode_1.createFastDomNode(document.createElement('div')); this._domNode.setClassName('cursor'); this._domNode.setHeight(this._lineHeight); this._domNode.setTop(0); this._domNode.setLeft(0); configuration_1.Configuration.applyFontInfo(this._domNode, fontInfo); this._domNode.setDisplay('none'); this._position = new position_1.Position(1, 1); this._lastRenderedContent = ''; this._renderData = null; } ViewCursor.prototype.getDomNode = function () { return this._domNode; }; ViewCursor.prototype.getPosition = function () { return this._position; }; ViewCursor.prototype.show = function () { if (!this._isVisible) { this._domNode.setVisibility('inherit'); this._isVisible = true; } }; ViewCursor.prototype.hide = function () { if (this._isVisible) { this._domNode.setVisibility('hidden'); this._isVisible = false; } }; ViewCursor.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; var fontInfo = options.get(34 /* fontInfo */); this._cursorStyle = options.get(18 /* cursorStyle */); this._lineHeight = options.get(49 /* lineHeight */); this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth; this._lineCursorWidth = Math.min(options.get(21 /* cursorWidth */), this._typicalHalfwidthCharacterWidth); configuration_1.Configuration.applyFontInfo(this._domNode, fontInfo); return true; }; ViewCursor.prototype.onCursorPositionChanged = function (position) { this._position = position; return true; }; ViewCursor.prototype._prepareRender = function (ctx) { var textContent = ''; if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Line || this._cursorStyle === editorOptions_1.TextEditorCursorStyle.LineThin) { var visibleRange = ctx.visibleRangeForPosition(this._position); if (!visibleRange || visibleRange.outsideRenderedLine) { // Outside viewport return null; } var width_1; if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Line) { width_1 = dom.computeScreenAwareSize(this._lineCursorWidth > 0 ? this._lineCursorWidth : 2); if (width_1 > 2) { var lineContent_1 = this._context.model.getLineContent(this._position.lineNumber); var nextCharLength_1 = strings.nextCharLength(lineContent_1, this._position.column - 1); textContent = lineContent_1.substr(this._position.column - 1, nextCharLength_1); } } else { width_1 = dom.computeScreenAwareSize(1); } var left = visibleRange.left; if (width_1 >= 2 && left >= 1) { // try to center cursor left -= 1; } var top_1 = ctx.getVerticalOffsetForLineNumber(this._position.lineNumber) - ctx.bigNumbersDelta; return new ViewCursorRenderData(top_1, left, width_1, this._lineHeight, textContent, ''); } var lineContent = this._context.model.getLineContent(this._position.lineNumber); var nextCharLength = strings.nextCharLength(lineContent, this._position.column - 1); var visibleRangeForCharacter = ctx.linesVisibleRangesForRange(new range_1.Range(this._position.lineNumber, this._position.column, this._position.lineNumber, this._position.column + nextCharLength), false); if (!visibleRangeForCharacter || visibleRangeForCharacter.length === 0) { // Outside viewport return null; } var firstVisibleRangeForCharacter = visibleRangeForCharacter[0]; if (firstVisibleRangeForCharacter.outsideRenderedLine || firstVisibleRangeForCharacter.ranges.length === 0) { // Outside viewport return null; } var range = firstVisibleRangeForCharacter.ranges[0]; var width = range.width < 1 ? this._typicalHalfwidthCharacterWidth : range.width; var textContentClassName = ''; if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Block) { var lineData = this._context.model.getViewLineData(this._position.lineNumber); textContent = lineContent.substr(this._position.column - 1, nextCharLength); var tokenIndex = lineData.tokens.findTokenIndexAtOffset(this._position.column - 1); textContentClassName = lineData.tokens.getClassName(tokenIndex); } var top = ctx.getVerticalOffsetForLineNumber(this._position.lineNumber) - ctx.bigNumbersDelta; var 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); }; ViewCursor.prototype.prepareRender = function (ctx) { this._renderData = this._prepareRender(ctx); }; ViewCursor.prototype.render = function (ctx) { if (!this._renderData) { this._domNode.setDisplay('none'); return null; } if (this._lastRenderedContent !== this._renderData.textContent) { this._lastRenderedContent = this._renderData.textContent; this._domNode.domNode.textContent = this._lastRenderedContent; } this._domNode.setClassName('cursor ' + this._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 }; }; return ViewCursor; }()); 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[515/*vs/editor/common/services/languagesRegistry*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,252/*vs/base/common/mime*/,5/*vs/base/common/strings*/,17/*vs/editor/common/modes*/,118/*vs/editor/common/modes/modesRegistry*/,63/*vs/editor/common/modes/nullMode*/,85/*vs/platform/configuration/common/configurationRegistry*/,42/*vs/platform/registry/common/platform*/]), function (require, exports, errors_1, event_1, lifecycle_1, mime, strings, modes_1, modesRegistry_1, nullMode_1, configurationRegistry_1, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var hasOwnProperty = Object.prototype.hasOwnProperty; var LanguagesRegistry = /** @class */ (function (_super) { __extends(LanguagesRegistry, _super); function LanguagesRegistry(useModesRegistry, warnOnOverwrite) { if (useModesRegistry === void 0) { useModesRegistry = true; } if (warnOnOverwrite === void 0) { warnOnOverwrite = false; } var _this = _super.call(this) || this; _this._onDidChange = _this._register(new event_1.Emitter()); _this.onDidChange = _this._onDidChange.event; _this._warnOnOverwrite = warnOnOverwrite; _this._nextLanguageId2 = 1; _this._languageIdToLanguage = []; _this._languageToLanguageId = Object.create(null); _this._languages = {}; _this._mimeTypesMap = {}; _this._nameMap = {}; _this._lowercaseNameMap = {}; if (useModesRegistry) { _this._initializeFromRegistry(); _this._register(modesRegistry_1.ModesRegistry.onDidChangeLanguages(function (m) { return _this._initializeFromRegistry(); })); } return _this; } LanguagesRegistry.prototype._initializeFromRegistry = function () { this._languages = {}; this._mimeTypesMap = {}; this._nameMap = {}; this._lowercaseNameMap = {}; var desc = modesRegistry_1.ModesRegistry.getLanguages(); this._registerLanguages(desc); }; LanguagesRegistry.prototype._registerLanguages = function (desc) { var _this = this; for (var _i = 0, desc_1 = desc; _i < desc_1.length; _i++) { var d = desc_1[_i]; this._registerLanguage(d); } // Rebuild fast path maps this._mimeTypesMap = {}; this._nameMap = {}; this._lowercaseNameMap = {}; Object.keys(this._languages).forEach(function (langId) { var language = _this._languages[langId]; if (language.name) { _this._nameMap[language.name] = language.identifier; } language.aliases.forEach(function (alias) { _this._lowercaseNameMap[alias.toLowerCase()] = language.identifier; }); language.mimetypes.forEach(function (mimetype) { _this._mimeTypesMap[mimetype] = language.identifier; }); }); platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).registerOverrideIdentifiers(modesRegistry_1.ModesRegistry.getLanguages().map(function (language) { return language.id; })); this._onDidChange.fire(); }; LanguagesRegistry.prototype._getLanguageId = function (language) { if (this._languageToLanguageId[language]) { return this._languageToLanguageId[language]; } var languageId = this._nextLanguageId2++; this._languageIdToLanguage[languageId] = language; this._languageToLanguageId[language] = languageId; return languageId; }; LanguagesRegistry.prototype._registerLanguage = function (lang) { var langId = lang.id; var resolvedLanguage; if (hasOwnProperty.call(this._languages, langId)) { resolvedLanguage = this._languages[langId]; } else { var languageId = this._getLanguageId(langId); resolvedLanguage = { identifier: new modes_1.LanguageIdentifier(langId, languageId), name: null, mimetypes: [], aliases: [], extensions: [], filenames: [], configurationFiles: [] }; this._languages[langId] = resolvedLanguage; } this._mergeLanguage(resolvedLanguage, lang); }; LanguagesRegistry.prototype._mergeLanguage = function (resolvedLanguage, lang) { var _a; var langId = lang.id; var primaryMime = null; if (Array.isArray(lang.mimetypes) && lang.mimetypes.length > 0) { (_a = resolvedLanguage.mimetypes).push.apply(_a, lang.mimetypes); primaryMime = lang.mimetypes[0]; } if (!primaryMime) { primaryMime = "text/x-" + langId; resolvedLanguage.mimetypes.push(primaryMime); } if (Array.isArray(lang.extensions)) { for (var _i = 0, _b = lang.extensions; _i < _b.length; _i++) { var extension = _b[_i]; mime.registerTextMime({ id: langId, mime: primaryMime, extension: extension }, this._warnOnOverwrite); resolvedLanguage.extensions.push(extension); } } if (Array.isArray(lang.filenames)) { for (var _c = 0, _d = lang.filenames; _c < _d.length; _c++) { var filename = _d[_c]; mime.registerTextMime({ id: langId, mime: primaryMime, filename: filename }, this._warnOnOverwrite); resolvedLanguage.filenames.push(filename); } } if (Array.isArray(lang.filenamePatterns)) { for (var _e = 0, _f = lang.filenamePatterns; _e < _f.length; _e++) { var filenamePattern = _f[_e]; mime.registerTextMime({ id: langId, mime: primaryMime, filepattern: filenamePattern }, this._warnOnOverwrite); } } if (typeof lang.firstLine === 'string' && lang.firstLine.length > 0) { var firstLineRegexStr = lang.firstLine; if (firstLineRegexStr.charAt(0) !== '^') { firstLineRegexStr = '^' + firstLineRegexStr; } try { var firstLineRegex = new RegExp(firstLineRegexStr); if (!strings.regExpLeadsToEndlessLoop(firstLineRegex)) { mime.registerTextMime({ id: langId, mime: primaryMime, firstline: firstLineRegex }, this._warnOnOverwrite); } } catch (err) { // Most likely, the regex was bad errors_1.onUnexpectedError(err); } } resolvedLanguage.aliases.push(langId); var 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 (var _g = 0, langAliases_1 = langAliases; _g < langAliases_1.length; _g++) { var langAlias = langAliases_1[_g]; if (!langAlias || langAlias.length === 0) { continue; } resolvedLanguage.aliases.push(langAlias); } } var containsAliases = (langAliases !== null && langAliases.length > 0); if (containsAliases && langAliases[0] === null) { // signal that this language should not get a name } else { var bestName = (containsAliases ? langAliases[0] : null) || langId; if (containsAliases || !resolvedLanguage.name) { resolvedLanguage.name = bestName; } } if (lang.configuration) { resolvedLanguage.configurationFiles.push(lang.configuration); } }; LanguagesRegistry.prototype.isRegisteredMode = function (mimetypeOrModeId) { // Is this a known mime type ? if (hasOwnProperty.call(this._mimeTypesMap, mimetypeOrModeId)) { return true; } // Is this a known mode id ? return hasOwnProperty.call(this._languages, mimetypeOrModeId); }; LanguagesRegistry.prototype.getModeIdForLanguageNameLowercase = function (languageNameLower) { if (!hasOwnProperty.call(this._lowercaseNameMap, languageNameLower)) { return null; } return this._lowercaseNameMap[languageNameLower].language; }; LanguagesRegistry.prototype.extractModeIds = function (commaSeparatedMimetypesOrCommaSeparatedIds) { var _this = this; if (!commaSeparatedMimetypesOrCommaSeparatedIds) { return []; } return (commaSeparatedMimetypesOrCommaSeparatedIds. split(','). map(function (mimeTypeOrId) { return mimeTypeOrId.trim(); }). map(function (mimeTypeOrId) { if (hasOwnProperty.call(_this._mimeTypesMap, mimeTypeOrId)) { return _this._mimeTypesMap[mimeTypeOrId].language; } return mimeTypeOrId; }). filter(function (modeId) { return hasOwnProperty.call(_this._languages, modeId); })); }; LanguagesRegistry.prototype.getLanguageIdentifier = function (_modeId) { if (_modeId === nullMode_1.NULL_MODE_ID || _modeId === 0 /* Null */) { return nullMode_1.NULL_LANGUAGE_IDENTIFIER; } var modeId; if (typeof _modeId === 'string') { modeId = _modeId; } else { modeId = this._languageIdToLanguage[_modeId]; if (!modeId) { return null; } } if (!hasOwnProperty.call(this._languages, modeId)) { return null; } return this._languages[modeId].identifier; }; LanguagesRegistry.prototype.getModeIdsFromFilepathOrFirstLine = function (resource, firstLine) { if (!resource && !firstLine) { return []; } var mimeTypes = mime.guessMimeTypes(resource, firstLine); return this.extractModeIds(mimeTypes.join(',')); }; return LanguagesRegistry; }(lifecycle_1.Disposable)); exports.LanguagesRegistry = LanguagesRegistry; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[516/*vs/editor/common/services/modeServiceImpl*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,349/*vs/editor/common/modes/abstractMode*/,63/*vs/editor/common/modes/nullMode*/,515/*vs/editor/common/services/languagesRegistry*/,19/*vs/base/common/arrays*/]), function (require, exports, event_1, lifecycle_1, abstractMode_1, nullMode_1, languagesRegistry_1, arrays_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LanguageSelection = /** @class */ (function (_super) { __extends(LanguageSelection, _super); function LanguageSelection(onLanguagesMaybeChanged, selector) { var _this = _super.call(this) || this; _this._onDidChange = _this._register(new event_1.Emitter()); _this.onDidChange = _this._onDidChange.event; _this._selector = selector; _this.languageIdentifier = _this._selector(); _this._register(onLanguagesMaybeChanged(function () { return _this._evaluate(); })); return _this; } LanguageSelection.prototype._evaluate = function () { var languageIdentifier = this._selector(); if (languageIdentifier.id === this.languageIdentifier.id) { // no change return; } this.languageIdentifier = languageIdentifier; this._onDidChange.fire(this.languageIdentifier); }; return LanguageSelection; }(lifecycle_1.Disposable)); var ModeServiceImpl = /** @class */ (function () { function ModeServiceImpl(warnOnOverwrite) { var _this = this; if (warnOnOverwrite === void 0) { warnOnOverwrite = false; } this._onDidCreateMode = new event_1.Emitter(); this.onDidCreateMode = this._onDidCreateMode.event; this._onLanguagesMaybeChanged = new event_1.Emitter(); this.onLanguagesMaybeChanged = this._onLanguagesMaybeChanged.event; this._instantiatedModes = {}; this._registry = new languagesRegistry_1.LanguagesRegistry(true, warnOnOverwrite); this._registry.onDidChange(function () { return _this._onLanguagesMaybeChanged.fire(); }); } ModeServiceImpl.prototype.isRegisteredMode = function (mimetypeOrModeId) { return this._registry.isRegisteredMode(mimetypeOrModeId); }; ModeServiceImpl.prototype.getModeIdForLanguageName = function (alias) { return this._registry.getModeIdForLanguageNameLowercase(alias); }; ModeServiceImpl.prototype.getModeIdByFilepathOrFirstLine = function (resource, firstLine) { var modeIds = this._registry.getModeIdsFromFilepathOrFirstLine(resource, firstLine); return arrays_1.firstOrDefault(modeIds, null); }; ModeServiceImpl.prototype.getModeId = function (commaSeparatedMimetypesOrCommaSeparatedIds) { var modeIds = this._registry.extractModeIds(commaSeparatedMimetypesOrCommaSeparatedIds); return arrays_1.firstOrDefault(modeIds, null); }; ModeServiceImpl.prototype.getLanguageIdentifier = function (modeId) { return this._registry.getLanguageIdentifier(modeId); }; // --- instantiation ModeServiceImpl.prototype.create = function (commaSeparatedMimetypesOrCommaSeparatedIds) { var _this = this; return new LanguageSelection(this.onLanguagesMaybeChanged, function () { var modeId = _this.getModeId(commaSeparatedMimetypesOrCommaSeparatedIds); return _this._createModeAndGetLanguageIdentifier(modeId); }); }; ModeServiceImpl.prototype.createByFilepathOrFirstLine = function (resource, firstLine) { var _this = this; return new LanguageSelection(this.onLanguagesMaybeChanged, function () { var modeId = _this.getModeIdByFilepathOrFirstLine(resource, firstLine); return _this._createModeAndGetLanguageIdentifier(modeId); }); }; ModeServiceImpl.prototype._createModeAndGetLanguageIdentifier = function (modeId) { // Fall back to plain text if no mode was found var languageIdentifier = this.getLanguageIdentifier(modeId || 'plaintext') || nullMode_1.NULL_LANGUAGE_IDENTIFIER; this._getOrCreateMode(languageIdentifier.language); return languageIdentifier; }; ModeServiceImpl.prototype.triggerMode = function (commaSeparatedMimetypesOrCommaSeparatedIds) { var modeId = this.getModeId(commaSeparatedMimetypesOrCommaSeparatedIds); // Fall back to plain text if no mode was found this._getOrCreateMode(modeId || 'plaintext'); }; ModeServiceImpl.prototype._getOrCreateMode = function (modeId) { if (!this._instantiatedModes.hasOwnProperty(modeId)) { var languageIdentifier = this.getLanguageIdentifier(modeId) || nullMode_1.NULL_LANGUAGE_IDENTIFIER; this._instantiatedModes[modeId] = new abstractMode_1.FrankensteinMode(languageIdentifier); this._onDidCreateMode.fire(this._instantiatedModes[modeId]); } return this._instantiatedModes[modeId]; }; return ModeServiceImpl; }()); exports.ModeServiceImpl = ModeServiceImpl; }); define(__m[43/*vs/platform/configuration/common/configuration*/], __M([0/*require*/,1/*exports*/,42/*vs/platform/registry/common/platform*/,11/*vs/platform/instantiation/common/instantiation*/,85/*vs/platform/configuration/common/configurationRegistry*/]), function (require, exports, platform_1, instantiation_1, configurationRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IConfigurationService = instantiation_1.createDecorator('configurationService'); function toValuesTree(properties, conflictReporter) { var root = Object.create(null); for (var key in properties) { addToValueTree(root, key, properties[key], conflictReporter); } return root; } exports.toValuesTree = toValuesTree; function addToValueTree(settingsTreeRoot, key, value, conflictReporter) { var segments = key.split('.'); var last = segments.pop(); var curr = settingsTreeRoot; for (var i = 0; i < segments.length; i++) { var s = segments[i]; var 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[last] = value; // workaround https://github.com/Microsoft/vscode/issues/13606 } else { conflictReporter("Ignoring " + key + " as " + segments.join('.') + " is " + JSON.stringify(curr)); } } exports.addToValueTree = addToValueTree; function removeFromValueTree(valueTree, key) { var segments = key.split('.'); doRemoveFromValueTree(valueTree, segments); } exports.removeFromValueTree = removeFromValueTree; function doRemoveFromValueTree(valueTree, segments) { var first = segments.shift(); if (segments.length === 0) { // Reached last segment delete valueTree[first]; return; } if (Object.keys(valueTree).indexOf(first) !== -1) { var 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) { var current = config; for (var _i = 0, path_1 = path; _i < path_1.length; _i++) { var component = path_1[_i]; if (typeof current !== 'object' || current === null) { return undefined; } current = current[component]; } return current; } var path = settingPath.split('.'); var result = accessSetting(config, path); return typeof result === 'undefined' ? defaultValue : result; } exports.getConfigurationValue = getConfigurationValue; function getConfigurationKeys() { var properties = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).getConfigurationProperties(); return Object.keys(properties); } exports.getConfigurationKeys = getConfigurationKeys; function getDefaultValues() { var valueTreeRoot = Object.create(null); var properties = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).getConfigurationProperties(); for (var key in properties) { var value = properties[key].default; addToValueTree(valueTreeRoot, key, value, function (message) { return console.error("Conflict in default settings: " + message); }); } return valueTreeRoot; } exports.getDefaultValues = getDefaultValues; function overrideIdentifierFromKey(key) { return key.substring(1, key.length - 1); } exports.overrideIdentifierFromKey = overrideIdentifierFromKey; function getMigratedSettingValue(configurationService, currentSettingName, legacySettingName) { var setting = configurationService.inspect(currentSettingName); var legacySetting = configurationService.inspect(legacySettingName); if (typeof setting.userValue !== 'undefined' || typeof setting.workspaceValue !== 'undefined' || typeof setting.workspaceFolderValue !== 'undefined') { return setting.value; } else if (typeof legacySetting.userValue !== 'undefined' || typeof legacySetting.workspaceValue !== 'undefined' || typeof legacySetting.workspaceFolderValue !== 'undefined') { return legacySetting.value; } else { return setting.defaultValue; } } exports.getMigratedSettingValue = getMigratedSettingValue; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[517/*vs/platform/accessibility/common/accessibilityService*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,64/*vs/platform/accessibility/common/accessibility*/,4/*vs/base/common/event*/,18/*vs/platform/contextkey/common/contextkey*/,43/*vs/platform/configuration/common/configuration*/]), function (require, exports, lifecycle_1, accessibility_1, event_1, contextkey_1, configuration_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var AccessibilityService = /** @class */ (function (_super) { __extends(AccessibilityService, _super); function AccessibilityService(_contextKeyService, _configurationService) { var _this = _super.call(this) || this; _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); var updateContextKey = function () { return _this._accessibilityModeEnabledContext.set(_this.isScreenReaderOptimized()); }; _this._register(_this._configurationService.onDidChangeConfiguration(function (e) { if (e.affectsConfiguration('editor.accessibilitySupport')) { updateContextKey(); _this._onDidChangeScreenReaderOptimized.fire(); } })); updateContextKey(); _this.onDidChangeScreenReaderOptimized(function () { return updateContextKey(); }); return _this; } Object.defineProperty(AccessibilityService.prototype, "onDidChangeScreenReaderOptimized", { get: function () { return this._onDidChangeScreenReaderOptimized.event; }, enumerable: true, configurable: true }); AccessibilityService.prototype.isScreenReaderOptimized = function () { var config = this._configurationService.getValue('editor.accessibilitySupport'); return config === 'on' || (config === 'auto' && this._accessibilitySupport === 2 /* Enabled */); }; AccessibilityService.prototype.getAccessibilitySupport = function () { return this._accessibilitySupport; }; AccessibilityService = __decorate([ __param(0, contextkey_1.IContextKeyService), __param(1, configuration_1.IConfigurationService) ], AccessibilityService); return AccessibilityService; }(lifecycle_1.Disposable)); exports.AccessibilityService = AccessibilityService; }); 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; }; define(__m[518/*vs/platform/configuration/common/configurationModels*/], __M([0/*require*/,1/*exports*/,38/*vs/base/common/map*/,19/*vs/base/common/arrays*/,21/*vs/base/common/types*/,31/*vs/base/common/objects*/,85/*vs/platform/configuration/common/configurationRegistry*/,43/*vs/platform/configuration/common/configuration*/]), function (require, exports, map_1, arrays, types, objects, configurationRegistry_1, configuration_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ConfigurationModel = /** @class */ (function () { function ConfigurationModel(_contents, _keys, _overrides) { if (_contents === void 0) { _contents = {}; } if (_keys === void 0) { _keys = []; } if (_overrides === void 0) { _overrides = []; } this._contents = _contents; this._keys = _keys; this._overrides = _overrides; this.isFrozen = false; } Object.defineProperty(ConfigurationModel.prototype, "contents", { get: function () { return this.checkAndFreeze(this._contents); }, enumerable: true, configurable: true }); Object.defineProperty(ConfigurationModel.prototype, "overrides", { get: function () { return this.checkAndFreeze(this._overrides); }, enumerable: true, configurable: true }); Object.defineProperty(ConfigurationModel.prototype, "keys", { get: function () { return this.checkAndFreeze(this._keys); }, enumerable: true, configurable: true }); ConfigurationModel.prototype.isEmpty = function () { return this._keys.length === 0 && Object.keys(this._contents).length === 0 && this._overrides.length === 0; }; ConfigurationModel.prototype.getValue = function (section) { return section ? configuration_1.getConfigurationValue(this.contents, section) : this.contents; }; ConfigurationModel.prototype.getOverrideValue = function (section, overrideIdentifier) { var overrideContents = this.getContentsForOverrideIdentifer(overrideIdentifier); return overrideContents ? section ? configuration_1.getConfigurationValue(overrideContents, section) : overrideContents : undefined; }; ConfigurationModel.prototype.override = function (identifier) { var overrideContents = this.getContentsForOverrideIdentifer(identifier); if (!overrideContents || typeof overrideContents !== 'object' || !Object.keys(overrideContents).length) { // If there are no valid overrides, return self return this; } var contents = {}; for (var _i = 0, _a = arrays.distinct(__spreadArrays(Object.keys(this.contents), Object.keys(overrideContents))); _i < _a.length; _i++) { var key = _a[_i]; var contentsForKey = this.contents[key]; var 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); }; ConfigurationModel.prototype.merge = function () { var others = []; for (var _i = 0; _i < arguments.length; _i++) { others[_i] = arguments[_i]; } var contents = objects.deepClone(this.contents); var overrides = objects.deepClone(this.overrides); var keys = __spreadArrays(this.keys); for (var _a = 0, others_1 = others; _a < others_1.length; _a++) { var other = others_1[_a]; this.mergeContents(contents, other.contents); var _loop_1 = function (otherOverride) { var override = overrides.filter(function (o) { return arrays.equals(o.identifiers, otherOverride.identifiers); })[0]; if (override) { this_1.mergeContents(override.contents, otherOverride.contents); } else { overrides.push(objects.deepClone(otherOverride)); } }; var this_1 = this; for (var _b = 0, _c = other.overrides; _b < _c.length; _b++) { var otherOverride = _c[_b]; _loop_1(otherOverride); } for (var _d = 0, _e = other.keys; _d < _e.length; _d++) { var key = _e[_d]; if (keys.indexOf(key) === -1) { keys.push(key); } } } return new ConfigurationModel(contents, keys, overrides); }; ConfigurationModel.prototype.freeze = function () { this.isFrozen = true; return this; }; ConfigurationModel.prototype.mergeContents = function (source, target) { for (var _i = 0, _a = Object.keys(target); _i < _a.length; _i++) { var key = _a[_i]; 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]); } }; ConfigurationModel.prototype.checkAndFreeze = function (data) { if (this.isFrozen && !Object.isFrozen(data)) { return objects.deepFreeze(data); } return data; }; ConfigurationModel.prototype.getContentsForOverrideIdentifer = function (identifier) { for (var _i = 0, _a = this.overrides; _i < _a.length; _i++) { var override = _a[_i]; if (override.identifiers.indexOf(identifier) !== -1) { return override.contents; } } return null; }; ConfigurationModel.prototype.toJSON = function () { return { contents: this.contents, overrides: this.overrides, keys: this.keys }; }; // Update methods ConfigurationModel.prototype.setValue = function (key, value) { this.addKey(key); configuration_1.addToValueTree(this.contents, key, value, function (e) { throw new Error(e); }); }; ConfigurationModel.prototype.removeValue = function (key) { if (this.removeKey(key)) { configuration_1.removeFromValueTree(this.contents, key); } }; ConfigurationModel.prototype.addKey = function (key) { var index = this.keys.length; for (var i = 0; i < index; i++) { if (key.indexOf(this.keys[i]) === 0) { index = i; } } this.keys.splice(index, 1, key); }; ConfigurationModel.prototype.removeKey = function (key) { var index = this.keys.indexOf(key); if (index !== -1) { this.keys.splice(index, 1); return true; } return false; }; return ConfigurationModel; }()); exports.ConfigurationModel = ConfigurationModel; var DefaultConfigurationModel = /** @class */ (function (_super) { __extends(DefaultConfigurationModel, _super); function DefaultConfigurationModel() { var _this = this; var contents = configuration_1.getDefaultValues(); var keys = configuration_1.getConfigurationKeys(); var overrides = []; for (var _i = 0, _a = Object.keys(contents); _i < _a.length; _i++) { var key = _a[_i]; if (configurationRegistry_1.OVERRIDE_PROPERTY_PATTERN.test(key)) { overrides.push({ identifiers: [configuration_1.overrideIdentifierFromKey(key).trim()], keys: Object.keys(contents[key]), contents: configuration_1.toValuesTree(contents[key], function (message) { return console.error("Conflict in default settings file: " + message); }), }); } } _this = _super.call(this, contents, keys, overrides) || this; return _this; } return DefaultConfigurationModel; }(ConfigurationModel)); exports.DefaultConfigurationModel = DefaultConfigurationModel; var Configuration = /** @class */ (function () { function Configuration(_defaultConfiguration, _localUserConfiguration, _remoteUserConfiguration, _workspaceConfiguration, _folderConfigurations, _memoryConfiguration, _memoryConfigurationByResource, _freeze) { if (_remoteUserConfiguration === void 0) { _remoteUserConfiguration = new ConfigurationModel(); } if (_workspaceConfiguration === void 0) { _workspaceConfiguration = new ConfigurationModel(); } if (_folderConfigurations === void 0) { _folderConfigurations = new map_1.ResourceMap(); } if (_memoryConfiguration === void 0) { _memoryConfiguration = new ConfigurationModel(); } if (_memoryConfigurationByResource === void 0) { _memoryConfigurationByResource = new map_1.ResourceMap(); } if (_freeze === void 0) { _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; } Configuration.prototype.getValue = function (section, overrides, workspace) { var consolidateConfigurationModel = this.getConsolidateConfigurationModel(overrides, workspace); return consolidateConfigurationModel.getValue(section); }; Configuration.prototype.updateValue = function (key, value, overrides) { if (overrides === void 0) { overrides = {}; } var 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; } }; Configuration.prototype.inspect = function (key, overrides, workspace) { var consolidateConfigurationModel = this.getConsolidateConfigurationModel(overrides, workspace); var folderConfigurationModel = this.getFolderConfigurationModelForResource(overrides.resource, workspace); var memoryConfigurationModel = overrides.resource ? this._memoryConfigurationByResource.get(overrides.resource) || this._memoryConfiguration : this._memoryConfiguration; var defaultValue = overrides.overrideIdentifier ? this._defaultConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this._defaultConfiguration.freeze().getValue(key); var userValue = overrides.overrideIdentifier ? this.userConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this.userConfiguration.freeze().getValue(key); var userLocalValue = overrides.overrideIdentifier ? this.localUserConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this.localUserConfiguration.freeze().getValue(key); var userRemoteValue = overrides.overrideIdentifier ? this.remoteUserConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this.remoteUserConfiguration.freeze().getValue(key); var 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 var workspaceFolderValue = folderConfigurationModel ? overrides.overrideIdentifier ? folderConfigurationModel.freeze().override(overrides.overrideIdentifier).getValue(key) : folderConfigurationModel.freeze().getValue(key) : undefined; var memoryValue = overrides.overrideIdentifier ? memoryConfigurationModel.override(overrides.overrideIdentifier).getValue(key) : memoryConfigurationModel.getValue(key); var value = consolidateConfigurationModel.getValue(key); var overrideIdentifiers = arrays.distinct(arrays.flatten(consolidateConfigurationModel.overrides.map(function (override) { return override.identifiers; }))).filter(function (overrideIdentifier) { return consolidateConfigurationModel.getOverrideValue(key, overrideIdentifier) !== undefined; }); return { defaultValue: defaultValue, userValue: userValue, userLocalValue: userLocalValue, userRemoteValue: userRemoteValue, workspaceValue: workspaceValue, workspaceFolderValue: workspaceFolderValue, memoryValue: memoryValue, value: 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 }; }; Object.defineProperty(Configuration.prototype, "userConfiguration", { get: function () { if (!this._userConfiguration) { this._userConfiguration = this._remoteUserConfiguration.isEmpty() ? this._localUserConfiguration : this._localUserConfiguration.merge(this._remoteUserConfiguration); if (this._freeze) { this._userConfiguration.freeze(); } } return this._userConfiguration; }, enumerable: true, configurable: true }); Object.defineProperty(Configuration.prototype, "localUserConfiguration", { get: function () { return this._localUserConfiguration; }, enumerable: true, configurable: true }); Object.defineProperty(Configuration.prototype, "remoteUserConfiguration", { get: function () { return this._remoteUserConfiguration; }, enumerable: true, configurable: true }); Configuration.prototype.getConsolidateConfigurationModel = function (overrides, workspace) { var configurationModel = this.getConsolidatedConfigurationModelForResource(overrides, workspace); return overrides.overrideIdentifier ? configurationModel.override(overrides.overrideIdentifier) : configurationModel; }; Configuration.prototype.getConsolidatedConfigurationModelForResource = function (_a, workspace) { var resource = _a.resource; var consolidateConfiguration = this.getWorkspaceConsolidatedConfiguration(); if (workspace && resource) { var root = workspace.getFolder(resource); if (root) { consolidateConfiguration = this.getFolderConsolidatedConfiguration(root.uri) || consolidateConfiguration; } var memoryConfigurationForResource = this._memoryConfigurationByResource.get(resource); if (memoryConfigurationForResource) { consolidateConfiguration = consolidateConfiguration.merge(memoryConfigurationForResource); } } return consolidateConfiguration; }; Configuration.prototype.getWorkspaceConsolidatedConfiguration = function () { 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; }; Configuration.prototype.getFolderConsolidatedConfiguration = function (folder) { var folderConsolidatedConfiguration = this._foldersConsolidatedConfigurations.get(folder); if (!folderConsolidatedConfiguration) { var workspaceConsolidateConfiguration = this.getWorkspaceConsolidatedConfiguration(); var 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; }; Configuration.prototype.getFolderConfigurationModelForResource = function (resource, workspace) { if (workspace && resource) { var root = workspace.getFolder(resource); if (root) { return this._folderConfigurations.get(root.uri); } } return undefined; }; return Configuration; }()); exports.Configuration = Configuration; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[519/*vs/platform/contextkey/browser/contextKeyService*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,38/*vs/base/common/map*/,29/*vs/platform/commands/common/commands*/,43/*vs/platform/configuration/common/configuration*/,18/*vs/platform/contextkey/common/contextkey*/,217/*vs/platform/keybinding/common/keybindingResolver*/]), function (require, exports, event_1, lifecycle_1, map_1, commands_1, configuration_1, contextkey_1, keybindingResolver_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context'; var Context = /** @class */ (function () { function Context(id, parent) { this._id = id; this._parent = parent; this._value = Object.create(null); this._value['_contextId'] = id; } Context.prototype.setValue = function (key, value) { // console.log('SET ' + key + ' = ' + value + ' ON ' + this._id); if (this._value[key] !== value) { this._value[key] = value; return true; } return false; }; Context.prototype.removeValue = function (key) { // console.log('REMOVE ' + key + ' FROM ' + this._id); if (key in this._value) { delete this._value[key]; return true; } return false; }; Context.prototype.getValue = function (key) { var ret = this._value[key]; if (typeof ret === 'undefined' && this._parent) { return this._parent.getValue(key); } return ret; }; return Context; }()); exports.Context = Context; var NullContext = /** @class */ (function (_super) { __extends(NullContext, _super); function NullContext() { return _super.call(this, -1, null) || this; } NullContext.prototype.setValue = function (key, value) { return false; }; NullContext.prototype.removeValue = function (key) { return false; }; NullContext.prototype.getValue = function (key) { return undefined; }; NullContext.INSTANCE = new NullContext(); return NullContext; }(Context)); var ConfigAwareContextValuesContainer = /** @class */ (function (_super) { __extends(ConfigAwareContextValuesContainer, _super); function ConfigAwareContextValuesContainer(id, _configurationService, emitter) { var _this = _super.call(this, id, null) || this; _this._configurationService = _configurationService; _this._values = new Map(); _this._listener = _this._configurationService.onDidChangeConfiguration(function (event) { if (event.source === 6 /* DEFAULT */) { // new setting, reset everything var allKeys = map_1.keys(_this._values); _this._values.clear(); emitter.fire(new ArrayContextKeyChangeEvent(allKeys)); } else { var changedKeys = []; for (var _i = 0, _a = event.affectedKeys; _i < _a.length; _i++) { var configKey = _a[_i]; var contextKey = "config." + configKey; if (_this._values.has(contextKey)) { _this._values.delete(contextKey); changedKeys.push(contextKey); } } emitter.fire(new ArrayContextKeyChangeEvent(changedKeys)); } }); return _this; } ConfigAwareContextValuesContainer.prototype.dispose = function () { this._listener.dispose(); }; ConfigAwareContextValuesContainer.prototype.getValue = function (key) { if (key.indexOf(ConfigAwareContextValuesContainer._keyPrefix) !== 0) { return _super.prototype.getValue.call(this, key); } if (this._values.has(key)) { return this._values.get(key); } var configKey = key.substr(ConfigAwareContextValuesContainer._keyPrefix.length); var configValue = this._configurationService.getValue(configKey); var value = undefined; switch (typeof configValue) { case 'number': case 'boolean': case 'string': value = configValue; break; } this._values.set(key, value); return value; }; ConfigAwareContextValuesContainer.prototype.setValue = function (key, value) { return _super.prototype.setValue.call(this, key, value); }; ConfigAwareContextValuesContainer.prototype.removeValue = function (key) { return _super.prototype.removeValue.call(this, key); }; ConfigAwareContextValuesContainer._keyPrefix = 'config.'; return ConfigAwareContextValuesContainer; }(Context)); var ContextKey = /** @class */ (function () { function ContextKey(service, key, defaultValue) { this._service = service; this._key = key; this._defaultValue = defaultValue; this.reset(); } ContextKey.prototype.set = function (value) { this._service.setContext(this._key, value); }; ContextKey.prototype.reset = function () { if (typeof this._defaultValue === 'undefined') { this._service.removeContext(this._key); } else { this._service.setContext(this._key, this._defaultValue); } }; ContextKey.prototype.get = function () { return this._service.getContextKeyValue(this._key); }; return ContextKey; }()); var SimpleContextKeyChangeEvent = /** @class */ (function () { function SimpleContextKeyChangeEvent(key) { this.key = key; } SimpleContextKeyChangeEvent.prototype.affectsSome = function (keys) { return keys.has(this.key); }; return SimpleContextKeyChangeEvent; }()); var ArrayContextKeyChangeEvent = /** @class */ (function () { function ArrayContextKeyChangeEvent(keys) { this.keys = keys; } ArrayContextKeyChangeEvent.prototype.affectsSome = function (keys) { for (var _i = 0, _a = this.keys; _i < _a.length; _i++) { var key = _a[_i]; if (keys.has(key)) { return true; } } return false; }; return ArrayContextKeyChangeEvent; }()); var CompositeContextKeyChangeEvent = /** @class */ (function () { function CompositeContextKeyChangeEvent(events) { this.events = events; } CompositeContextKeyChangeEvent.prototype.affectsSome = function (keys) { for (var _i = 0, _a = this.events; _i < _a.length; _i++) { var e = _a[_i]; if (e.affectsSome(keys)) { return true; } } return false; }; return CompositeContextKeyChangeEvent; }()); var AbstractContextKeyService = /** @class */ (function () { function AbstractContextKeyService(myContextId) { this._onDidChangeContext = new event_1.PauseableEmitter({ merge: function (input) { return new CompositeContextKeyChangeEvent(input); } }); this._isDisposed = false; this._myContextId = myContextId; } AbstractContextKeyService.prototype.createKey = function (key, defaultValue) { if (this._isDisposed) { throw new Error("AbstractContextKeyService has been disposed"); } return new ContextKey(this, key, defaultValue); }; Object.defineProperty(AbstractContextKeyService.prototype, "onDidChangeContext", { get: function () { return this._onDidChangeContext.event; }, enumerable: true, configurable: true }); AbstractContextKeyService.prototype.bufferChangeEvents = function (callback) { this._onDidChangeContext.pause(); try { callback(); } finally { this._onDidChangeContext.resume(); } }; AbstractContextKeyService.prototype.createScoped = function (domNode) { if (this._isDisposed) { throw new Error("AbstractContextKeyService has been disposed"); } return new ScopedContextKeyService(this, domNode); }; AbstractContextKeyService.prototype.contextMatchesRules = function (rules) { if (this._isDisposed) { throw new Error("AbstractContextKeyService has been disposed"); } var context = this.getContextValuesContainer(this._myContextId); var result = keybindingResolver_1.KeybindingResolver.contextMatchesRules(context, rules); // console.group(rules.serialize() + ' -> ' + result); // rules.keys().forEach(key => { console.log(key, ctx[key]); }); // console.groupEnd(); return result; }; AbstractContextKeyService.prototype.getContextKeyValue = function (key) { if (this._isDisposed) { return undefined; } return this.getContextValuesContainer(this._myContextId).getValue(key); }; AbstractContextKeyService.prototype.setContext = function (key, value) { if (this._isDisposed) { return; } var myContext = this.getContextValuesContainer(this._myContextId); if (!myContext) { return; } if (myContext.setValue(key, value)) { this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key)); } }; AbstractContextKeyService.prototype.removeContext = function (key) { if (this._isDisposed) { return; } if (this.getContextValuesContainer(this._myContextId).removeValue(key)) { this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key)); } }; AbstractContextKeyService.prototype.getContext = function (target) { if (this._isDisposed) { return NullContext.INSTANCE; } return this.getContextValuesContainer(findContextAttr(target)); }; return AbstractContextKeyService; }()); exports.AbstractContextKeyService = AbstractContextKeyService; var ContextKeyService = /** @class */ (function (_super) { __extends(ContextKeyService, _super); function ContextKeyService(configurationService) { var _this = _super.call(this, 0) || this; _this._contexts = new Map(); _this._toDispose = new lifecycle_1.DisposableStore(); _this._lastContextId = 0; var myContext = new ConfigAwareContextValuesContainer(_this._myContextId, configurationService, _this._onDidChangeContext); _this._contexts.set(_this._myContextId, myContext); _this._toDispose.add(myContext); return _this; // 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); } ContextKeyService.prototype.dispose = function () { this._isDisposed = true; this._toDispose.dispose(); }; ContextKeyService.prototype.getContextValuesContainer = function (contextId) { if (this._isDisposed) { return NullContext.INSTANCE; } return this._contexts.get(contextId) || NullContext.INSTANCE; }; ContextKeyService.prototype.createChildContext = function (parentContextId) { if (parentContextId === void 0) { parentContextId = this._myContextId; } if (this._isDisposed) { throw new Error("ContextKeyService has been disposed"); } var id = (++this._lastContextId); this._contexts.set(id, new Context(id, this.getContextValuesContainer(parentContextId))); return id; }; ContextKeyService.prototype.disposeContext = function (contextId) { if (!this._isDisposed) { this._contexts.delete(contextId); } }; ContextKeyService = __decorate([ __param(0, configuration_1.IConfigurationService) ], ContextKeyService); return ContextKeyService; }(AbstractContextKeyService)); exports.ContextKeyService = ContextKeyService; var ScopedContextKeyService = /** @class */ (function (_super) { __extends(ScopedContextKeyService, _super); function ScopedContextKeyService(parent, domNode) { var _this = _super.call(this, parent.createChildContext()) || this; _this._parent = parent; if (domNode) { _this._domNode = domNode; _this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(_this._myContextId)); } return _this; } ScopedContextKeyService.prototype.dispose = function () { this._isDisposed = true; this._parent.disposeContext(this._myContextId); if (this._domNode) { this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR); this._domNode = undefined; } }; Object.defineProperty(ScopedContextKeyService.prototype, "onDidChangeContext", { get: function () { return event_1.Event.any(this._parent.onDidChangeContext, this._onDidChangeContext.event); }, enumerable: true, configurable: true }); ScopedContextKeyService.prototype.getContextValuesContainer = function (contextId) { if (this._isDisposed) { return NullContext.INSTANCE; } return this._parent.getContextValuesContainer(contextId); }; ScopedContextKeyService.prototype.createChildContext = function (parentContextId) { if (parentContextId === void 0) { parentContextId = this._myContextId; } if (this._isDisposed) { throw new Error("ScopedContextKeyService has been disposed"); } return this._parent.createChildContext(parentContextId); }; ScopedContextKeyService.prototype.disposeContext = function (contextId) { if (this._isDisposed) { return; } this._parent.disposeContext(contextId); }; return ScopedContextKeyService; }(AbstractContextKeyService)); function findContextAttr(domNode) { while (domNode) { if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) { var 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); }); }); /*--------------------------------------------------------------------------------------------- * 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([0/*require*/,1/*exports*/,36/*vs/base/common/keyCodes*/,16/*vs/base/common/platform*/,29/*vs/platform/commands/common/commands*/,42/*vs/platform/registry/common/platform*/]), function (require, exports, keyCodes_1, platform_1, commands_1, platform_2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var KeybindingsRegistryImpl = /** @class */ (function () { function KeybindingsRegistryImpl() { this._coreKeybindings = []; this._extensionKeybindings = []; this._cachedMergedKeybindings = null; } /** * Take current platform into account and reduce to primary & secondary. */ KeybindingsRegistryImpl.bindToCurrentPlatform = function (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; }; KeybindingsRegistryImpl.prototype.registerKeybindingRule = function (rule) { var actualKb = KeybindingsRegistryImpl.bindToCurrentPlatform(rule); if (actualKb && actualKb.primary) { var kk = keyCodes_1.createKeybinding(actualKb.primary, platform_1.OS); if (kk) { this._registerDefaultKeybinding(kk, rule.id, rule.args, rule.weight, 0, rule.when); } } if (actualKb && Array.isArray(actualKb.secondary)) { for (var i = 0, len = actualKb.secondary.length; i < len; i++) { var k = actualKb.secondary[i]; var kk = keyCodes_1.createKeybinding(k, platform_1.OS); if (kk) { this._registerDefaultKeybinding(kk, rule.id, rule.args, rule.weight, -i - 1, rule.when); } } } }; KeybindingsRegistryImpl.prototype.registerCommandAndKeybindingRule = function (desc) { this.registerKeybindingRule(desc); commands_1.CommandsRegistry.registerCommand(desc); }; KeybindingsRegistryImpl._mightProduceChar = function (keyCode) { if (keyCode >= 21 /* KEY_0 */ && keyCode <= 30 /* KEY_9 */) { return true; } if (keyCode >= 31 /* KEY_A */ && keyCode <= 56 /* KEY_Z */) { return true; } return (keyCode === 80 /* US_SEMICOLON */ || keyCode === 81 /* US_EQUAL */ || keyCode === 82 /* US_COMMA */ || keyCode === 83 /* US_MINUS */ || keyCode === 84 /* US_DOT */ || keyCode === 85 /* US_SLASH */ || keyCode === 86 /* US_BACKTICK */ || keyCode === 110 /* ABNT_C1 */ || keyCode === 111 /* ABNT_C2 */ || keyCode === 87 /* US_OPEN_SQUARE_BRACKET */ || keyCode === 88 /* US_BACKSLASH */ || keyCode === 89 /* US_CLOSE_SQUARE_BRACKET */ || keyCode === 90 /* US_QUOTE */ || keyCode === 91 /* OEM_8 */ || keyCode === 92 /* OEM_102 */); }; KeybindingsRegistryImpl.prototype._assertNoCtrlAlt = function (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); } } }; KeybindingsRegistryImpl.prototype._registerDefaultKeybinding = function (keybinding, commandId, commandArgs, weight1, weight2, when) { if (platform_1.OS === 1 /* Windows */) { this._assertNoCtrlAlt(keybinding.parts[0], commandId); } this._coreKeybindings.push({ keybinding: keybinding, command: commandId, commandArgs: commandArgs, when: when, weight1: weight1, weight2: weight2 }); this._cachedMergedKeybindings = null; }; KeybindingsRegistryImpl.prototype.getDefaultKeybindings = function () { if (!this._cachedMergedKeybindings) { this._cachedMergedKeybindings = [].concat(this._coreKeybindings).concat(this._extensionKeybindings); this._cachedMergedKeybindings.sort(sorter); } return this._cachedMergedKeybindings.slice(0); }; return KeybindingsRegistryImpl; }()); 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[520/*vs/platform/browser/contextScopedHistoryWidget*/], __M([0/*require*/,1/*exports*/,18/*vs/platform/contextkey/common/contextkey*/,400/*vs/base/browser/ui/findinput/findInput*/,86/*vs/platform/keybinding/common/keybindingsRegistry*/,401/*vs/base/browser/ui/findinput/replaceInput*/]), function (require, exports, contextkey_1, findInput_1, keybindingsRegistry_1, replaceInput_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HistoryNavigationWidgetContext = 'historyNavigationWidget'; exports.HistoryNavigationEnablementContext = 'historyNavigationEnabled'; function bindContextScopedWidget(contextKeyService, widget, contextKey) { new contextkey_1.RawContextKey(contextKey, widget).bindTo(contextKeyService); } function createWidgetScopedContextKeyService(contextKeyService, widget) { return contextKeyService.createScoped(widget.target); } function getContextScopedWidget(contextKeyService, contextKey) { return contextKeyService.getContext(document.activeElement).getValue(contextKey); } function createAndBindHistoryNavigationWidgetScopedContextKeyService(contextKeyService, widget) { var scopedContextKeyService = createWidgetScopedContextKeyService(contextKeyService, widget); bindContextScopedWidget(scopedContextKeyService, widget, exports.HistoryNavigationWidgetContext); var historyNavigationEnablement = new contextkey_1.RawContextKey(exports.HistoryNavigationEnablementContext, true).bindTo(scopedContextKeyService); return { scopedContextKeyService: scopedContextKeyService, historyNavigationEnablement: historyNavigationEnablement }; } exports.createAndBindHistoryNavigationWidgetScopedContextKeyService = createAndBindHistoryNavigationWidgetScopedContextKeyService; var ContextScopedFindInput = /** @class */ (function (_super) { __extends(ContextScopedFindInput, _super); function ContextScopedFindInput(container, contextViewProvider, options, contextKeyService, showFindOptions) { if (showFindOptions === void 0) { showFindOptions = false; } var _this = _super.call(this, container, contextViewProvider, showFindOptions, options) || this; _this._register(createAndBindHistoryNavigationWidgetScopedContextKeyService(contextKeyService, { target: _this.inputBox.element, historyNavigator: _this.inputBox }).scopedContextKeyService); return _this; } ContextScopedFindInput = __decorate([ __param(3, contextkey_1.IContextKeyService) ], ContextScopedFindInput); return ContextScopedFindInput; }(findInput_1.FindInput)); exports.ContextScopedFindInput = ContextScopedFindInput; var ContextScopedReplaceInput = /** @class */ (function (_super) { __extends(ContextScopedReplaceInput, _super); function ContextScopedReplaceInput(container, contextViewProvider, options, contextKeyService, showReplaceOptions) { if (showReplaceOptions === void 0) { showReplaceOptions = false; } var _this = _super.call(this, container, contextViewProvider, showReplaceOptions, options) || this; _this._register(createAndBindHistoryNavigationWidgetScopedContextKeyService(contextKeyService, { target: _this.inputBox.element, historyNavigator: _this.inputBox }).scopedContextKeyService); return _this; } ContextScopedReplaceInput = __decorate([ __param(3, contextkey_1.IContextKeyService) ], ContextScopedReplaceInput); return ContextScopedReplaceInput; }(replaceInput_1.ReplaceInput)); exports.ContextScopedReplaceInput = ContextScopedReplaceInput; keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'history.showPrevious', weight: 200 /* WorkbenchContrib */, when: contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.has(exports.HistoryNavigationWidgetContext), contextkey_1.ContextKeyExpr.equals(exports.HistoryNavigationEnablementContext, true)), primary: 16 /* UpArrow */, secondary: [512 /* Alt */ | 16 /* UpArrow */], handler: function (accessor, arg2) { var widget = getContextScopedWidget(accessor.get(contextkey_1.IContextKeyService), exports.HistoryNavigationWidgetContext); if (widget) { var historyInputBox = widget.historyNavigator; historyInputBox.showPreviousValue(); } } }); keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'history.showNext', weight: 200 /* WorkbenchContrib */, when: contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.has(exports.HistoryNavigationWidgetContext), contextkey_1.ContextKeyExpr.equals(exports.HistoryNavigationEnablementContext, true)), primary: 18 /* DownArrow */, secondary: [512 /* Alt */ | 18 /* DownArrow */], handler: function (accessor, arg2) { var widget = getContextScopedWidget(accessor.get(contextkey_1.IContextKeyService), exports.HistoryNavigationWidgetContext); if (widget) { var 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[74/*vs/platform/storage/common/storage*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/types*/]), function (require, exports, instantiation_1, event_1, lifecycle_1, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IStorageService = instantiation_1.createDecorator('storageService'); var WillSaveStateReason; (function (WillSaveStateReason) { WillSaveStateReason[WillSaveStateReason["NONE"] = 0] = "NONE"; WillSaveStateReason[WillSaveStateReason["SHUTDOWN"] = 1] = "SHUTDOWN"; })(WillSaveStateReason = exports.WillSaveStateReason || (exports.WillSaveStateReason = {})); var InMemoryStorageService = /** @class */ (function (_super) { __extends(InMemoryStorageService, _super); function InMemoryStorageService() { var _this = _super !== null && _super.apply(this, arguments) || this; _this._onDidChangeStorage = _this._register(new event_1.Emitter()); _this.onDidChangeStorage = _this._onDidChangeStorage.event; _this._onWillSaveState = _this._register(new event_1.Emitter()); _this.onWillSaveState = _this._onWillSaveState.event; _this.globalCache = new Map(); _this.workspaceCache = new Map(); return _this; } InMemoryStorageService.prototype.getCache = function (scope) { return scope === 0 /* GLOBAL */ ? this.globalCache : this.workspaceCache; }; InMemoryStorageService.prototype.get = function (key, scope, fallbackValue) { var value = this.getCache(scope).get(key); if (types_1.isUndefinedOrNull(value)) { return fallbackValue; } return value; }; InMemoryStorageService.prototype.getBoolean = function (key, scope, fallbackValue) { var value = this.getCache(scope).get(key); if (types_1.isUndefinedOrNull(value)) { return fallbackValue; } return value === 'true'; }; InMemoryStorageService.prototype.store = function (key, value, scope) { // We remove the key for undefined/null values if (types_1.isUndefinedOrNull(value)) { return this.remove(key, scope); } // Otherwise, convert to String and store var valueStr = String(value); // Return early if value already set var currentValue = this.getCache(scope).get(key); if (currentValue === valueStr) { return Promise.resolve(); } // Update in cache this.getCache(scope).set(key, valueStr); // Events this._onDidChangeStorage.fire({ scope: scope, key: key }); return Promise.resolve(); }; InMemoryStorageService.prototype.remove = function (key, scope) { var wasDeleted = this.getCache(scope).delete(key); if (!wasDeleted) { return Promise.resolve(); // Return early if value already deleted } // Events this._onDidChangeStorage.fire({ scope: scope, key: key }); return Promise.resolve(); }; return InMemoryStorageService; }(lifecycle_1.Disposable)); 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[521/*vs/editor/contrib/suggest/suggestMemory*/], __M([0/*require*/,1/*exports*/,38/*vs/base/common/map*/,74/*vs/platform/storage/common/storage*/,17/*vs/editor/common/modes*/,2/*vs/base/common/lifecycle*/,15/*vs/base/common/async*/,11/*vs/platform/instantiation/common/instantiation*/,43/*vs/platform/configuration/common/configuration*/,83/*vs/platform/instantiation/common/extensions*/]), function (require, exports, map_1, storage_1, modes_1, lifecycle_1, async_1, instantiation_1, configuration_1, extensions_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Memory = /** @class */ (function () { function Memory() { } Memory.prototype.select = function (model, pos, items) { if (items.length === 0) { return 0; } var topScore = items[0].score[0]; for (var i = 1; i < items.length; i++) { var _a = items[i], score = _a.score, suggestion = _a.completion; 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; }; return Memory; }()); exports.Memory = Memory; var NoMemory = /** @class */ (function (_super) { __extends(NoMemory, _super); function NoMemory() { return _super !== null && _super.apply(this, arguments) || this; } NoMemory.prototype.memorize = function (model, pos, item) { // no-op }; NoMemory.prototype.toJSON = function () { return undefined; }; NoMemory.prototype.fromJSON = function () { // }; return NoMemory; }(Memory)); exports.NoMemory = NoMemory; var LRUMemory = /** @class */ (function (_super) { __extends(LRUMemory, _super); function LRUMemory() { var _this = _super !== null && _super.apply(this, arguments) || this; _this._cache = new map_1.LRUCache(300, 0.66); _this._seq = 0; return _this; } LRUMemory.prototype.memorize = function (model, pos, item) { var label = item.completion.label; var key = model.getLanguageIdentifier().language + "/" + label; this._cache.set(key, { touch: this._seq++, type: item.completion.kind, insertText: item.completion.insertText }); }; LRUMemory.prototype.select = function (model, pos, items) { if (items.length === 0) { return 0; } var lineSuffix = model.getLineContent(pos.lineNumber).substr(pos.column - 10, pos.column - 1); if (/\s$/.test(lineSuffix)) { return _super.prototype.select.call(this, model, pos, items); } var topScore = items[0].score[0]; var indexPreselect = -1; var indexRecency = -1; var seq = -1; for (var i = 0; i < items.length; i++) { if (items[i].score[0] !== topScore) { // consider only top items break; } var key = model.getLanguageIdentifier().language + "/" + items[i].completion.label; var 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; } }; LRUMemory.prototype.toJSON = function () { var data = []; this._cache.forEach(function (value, key) { data.push([key, value]); }); return data; }; LRUMemory.prototype.fromJSON = function (data) { this._cache.clear(); var seq = 0; for (var _i = 0, data_1 = data; _i < data_1.length; _i++) { var _a = data_1[_i], key = _a[0], value = _a[1]; value.touch = seq; value.type = typeof value.type === 'number' ? value.type : modes_1.completionKindFromString(value.type); this._cache.set(key, value); } this._seq = this._cache.size; }; return LRUMemory; }(Memory)); exports.LRUMemory = LRUMemory; var PrefixMemory = /** @class */ (function (_super) { __extends(PrefixMemory, _super); function PrefixMemory() { var _this = _super !== null && _super.apply(this, arguments) || this; _this._trie = map_1.TernarySearchTree.forStrings(); _this._seq = 0; return _this; } PrefixMemory.prototype.memorize = function (model, pos, item) { var word = model.getWordUntilPosition(pos).word; var key = model.getLanguageIdentifier().language + "/" + word; this._trie.set(key, { type: item.completion.kind, insertText: item.completion.insertText, touch: this._seq++ }); }; PrefixMemory.prototype.select = function (model, pos, items) { var word = model.getWordUntilPosition(pos).word; if (!word) { return _super.prototype.select.call(this, model, pos, items); } var key = model.getLanguageIdentifier().language + "/" + word; var item = this._trie.get(key); if (!item) { item = this._trie.findSubstr(key); } if (item) { for (var i = 0; i < items.length; i++) { var _a = items[i].completion, kind = _a.kind, insertText = _a.insertText; if (kind === item.type && insertText === item.insertText) { return i; } } } return _super.prototype.select.call(this, model, pos, items); }; PrefixMemory.prototype.toJSON = function () { var entries = []; this._trie.forEach(function (value, key) { return entries.push([key, value]); }); // sort by last recently used (touch), then // take the top 200 item and normalize their // touch entries .sort(function (a, b) { return -(a[1].touch - b[1].touch); }) .forEach(function (value, i) { return value[1].touch = i; }); return entries.slice(0, 200); }; PrefixMemory.prototype.fromJSON = function (data) { this._trie.clear(); if (data.length > 0) { this._seq = data[0][1].touch + 1; for (var _i = 0, data_2 = data; _i < data_2.length; _i++) { var _a = data_2[_i], key = _a[0], value = _a[1]; value.type = typeof value.type === 'number' ? value.type : modes_1.completionKindFromString(value.type); this._trie.set(key, value); } } }; return PrefixMemory; }(Memory)); exports.PrefixMemory = PrefixMemory; var SuggestMemoryService = /** @class */ (function (_super) { __extends(SuggestMemoryService, _super); function SuggestMemoryService(_storageService, _configService) { var _this = _super.call(this) || this; _this._storageService = _storageService; _this._configService = _configService; _this._storagePrefix = 'suggest/memories'; var update = function () { var mode = _this._configService.getValue('editor.suggestSelection'); var share = _this._configService.getValue('editor.suggest.shareSuggestSelections'); _this._update(mode, share, false); }; _this._persistSoon = _this._register(new async_1.RunOnceScheduler(function () { return _this._saveState(); }, 500)); _this._register(_storageService.onWillSaveState(function (e) { if (e.reason === storage_1.WillSaveStateReason.SHUTDOWN) { _this._saveState(); } })); _this._register(_this._configService.onDidChangeConfiguration(function (e) { if (e.affectsConfiguration('editor.suggestSelection') || e.affectsConfiguration('editor.suggest.shareSuggestSelections')) { update(); } })); _this._register(_this._storageService.onDidChangeStorage(function (e) { if (e.scope === 0 /* GLOBAL */ && e.key.indexOf(_this._storagePrefix) === 0) { if (!document.hasFocus()) { // windows that aren't focused have to drop their current // storage value and accept what's stored now _this._update(_this._mode, _this._shareMem, true); } } })); update(); return _this; } SuggestMemoryService.prototype._update = function (mode, shareMem, force) { if (!force && this._mode === mode && this._shareMem === shareMem) { return; } this._shareMem = shareMem; this._mode = mode; this._strategy = mode === 'recentlyUsedByPrefix' ? new PrefixMemory() : mode === 'recentlyUsed' ? new LRUMemory() : new NoMemory(); try { var scope = shareMem ? 0 /* GLOBAL */ : 1 /* WORKSPACE */; var raw = this._storageService.get(this._storagePrefix + "/" + this._mode, scope); if (raw) { this._strategy.fromJSON(JSON.parse(raw)); } } catch (e) { // things can go wrong with JSON... } }; SuggestMemoryService.prototype.memorize = function (model, pos, item) { this._strategy.memorize(model, pos, item); this._persistSoon.schedule(); }; SuggestMemoryService.prototype.select = function (model, pos, items) { return this._strategy.select(model, pos, items); }; SuggestMemoryService.prototype._saveState = function () { var raw = JSON.stringify(this._strategy); var scope = this._shareMem ? 0 /* GLOBAL */ : 1 /* WORKSPACE */; this._storageService.store(this._storagePrefix + "/" + this._mode, raw, scope); }; SuggestMemoryService = __decorate([ __param(0, storage_1.IStorageService), __param(1, configuration_1.IConfigurationService) ], SuggestMemoryService); return SuggestMemoryService; }(lifecycle_1.Disposable)); exports.SuggestMemoryService = SuggestMemoryService; exports.ISuggestMemoryService = instantiation_1.createDecorator('ISuggestMemories'); 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[96/*vs/platform/telemetry/common/telemetry*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ITelemetryService = 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[12/*vs/editor/browser/editorExtensions*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,25/*vs/base/common/uri*/,32/*vs/editor/browser/services/codeEditorService*/,13/*vs/editor/common/core/position*/,49/*vs/editor/common/services/modelService*/,84/*vs/editor/common/services/resolverService*/,65/*vs/platform/actions/common/actions*/,29/*vs/platform/commands/common/commands*/,18/*vs/platform/contextkey/common/contextkey*/,86/*vs/platform/keybinding/common/keybindingsRegistry*/,42/*vs/platform/registry/common/platform*/,96/*vs/platform/telemetry/common/telemetry*/,21/*vs/base/common/types*/]), function (require, exports, errors_1, uri_1, codeEditorService_1, position_1, modelService_1, resolverService_1, actions_1, commands_1, contextkey_1, keybindingsRegistry_1, platform_1, telemetry_1, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Command = /** @class */ (function () { function Command(opts) { this.id = opts.id; this.precondition = opts.precondition; this._kbOpts = opts.kbOpts; this._menuOpts = opts.menuOpts; this._description = opts.description; } Command.prototype.register = function () { var _this = this; if (Array.isArray(this._menuOpts)) { this._menuOpts.forEach(this._registerMenuItem, this); } else if (this._menuOpts) { this._registerMenuItem(this._menuOpts); } if (this._kbOpts) { var kbWhen = this._kbOpts.kbExpr; if (this.precondition) { if (kbWhen) { kbWhen = contextkey_1.ContextKeyExpr.and(kbWhen, this.precondition); } else { kbWhen = this.precondition; } } keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ id: this.id, handler: function (accessor, args) { return _this.runCommand(accessor, args); }, weight: this._kbOpts.weight, when: kbWhen, primary: this._kbOpts.primary, secondary: this._kbOpts.secondary, win: this._kbOpts.win, linux: this._kbOpts.linux, mac: this._kbOpts.mac, description: this._description }); } else { commands_1.CommandsRegistry.registerCommand({ id: this.id, handler: function (accessor, args) { return _this.runCommand(accessor, args); }, description: this._description }); } }; Command.prototype._registerMenuItem = function (item) { actions_1.MenuRegistry.appendMenuItem(item.menuId, { group: item.group, command: { id: this.id, title: item.title, }, when: item.when, order: item.order }); }; return Command; }()); exports.Command = Command; var EditorCommand = /** @class */ (function (_super) { __extends(EditorCommand, _super); function EditorCommand() { return _super !== null && _super.apply(this, arguments) || this; } /** * Create a command class that is bound to a certain editor contribution. */ EditorCommand.bindToContribution = function (controllerGetter) { return /** @class */ (function (_super) { __extends(EditorControllerCommandImpl, _super); function EditorControllerCommandImpl(opts) { var _this = _super.call(this, opts) || this; _this._callback = opts.handler; return _this; } EditorControllerCommandImpl.prototype.runEditorCommand = function (accessor, editor, args) { var controller = controllerGetter(editor); if (controller) { this._callback(controllerGetter(editor), args); } }; return EditorControllerCommandImpl; }(EditorCommand)); }; EditorCommand.prototype.runCommand = function (accessor, args) { var _this = this; var codeEditorService = accessor.get(codeEditorService_1.ICodeEditorService); // Find the editor with text focus or active var editor = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor(); if (!editor) { // well, at least we tried... return; } return editor.invokeWithinContext(function (editorAccessor) { var kbService = editorAccessor.get(contextkey_1.IContextKeyService); if (!kbService.contextMatchesRules(types_1.withNullAsUndefined(_this.precondition))) { // precondition does not hold return; } return _this.runEditorCommand(editorAccessor, editor, args); }); }; return EditorCommand; }(Command)); exports.EditorCommand = EditorCommand; var EditorAction = /** @class */ (function (_super) { __extends(EditorAction, _super); function EditorAction(opts) { var _this = _super.call(this, EditorAction.convertOptions(opts)) || this; _this.label = opts.label; _this.alias = opts.alias; return _this; } EditorAction.convertOptions = function (opts) { var menuOpts; if (Array.isArray(opts.menuOpts)) { menuOpts = opts.menuOpts; } else if (opts.menuOpts) { menuOpts = [opts.menuOpts]; } else { menuOpts = []; } function withDefaults(item) { if (!item.menuId) { item.menuId = 7 /* EditorContext */; } if (!item.title) { item.title = opts.label; } item.when = contextkey_1.ContextKeyExpr.and(opts.precondition, item.when); return item; } if (Array.isArray(opts.contextMenuOpts)) { menuOpts.push.apply(menuOpts, opts.contextMenuOpts.map(withDefaults)); } else if (opts.contextMenuOpts) { menuOpts.push(withDefaults(opts.contextMenuOpts)); } opts.menuOpts = menuOpts; return opts; }; EditorAction.prototype.runEditorCommand = function (accessor, editor, args) { this.reportTelemetry(accessor, editor); return this.run(accessor, editor, args || {}); }; EditorAction.prototype.reportTelemetry = function (accessor, editor) { accessor.get(telemetry_1.ITelemetryService).publicLog2('editorActionInvoked', { name: this.label, id: this.id }); }; return EditorAction; }(EditorCommand)); exports.EditorAction = EditorAction; //#endregion EditorAction // --- Registration of commands and actions function registerLanguageCommand(id, handler) { commands_1.CommandsRegistry.registerCommand(id, function (accessor, args) { return handler(accessor, args || {}); }); } exports.registerLanguageCommand = registerLanguageCommand; function registerDefaultLanguageCommand(id, handler) { registerLanguageCommand(id, function (accessor, args) { var resource = args.resource, position = args.position; if (!(resource instanceof uri_1.URI)) { throw errors_1.illegalArgument('resource'); } if (!position_1.Position.isIPosition(position)) { throw errors_1.illegalArgument('position'); } var model = accessor.get(modelService_1.IModelService).getModel(resource); if (model) { var editorPosition = position_1.Position.lift(position); return handler(model, editorPosition, args); } return accessor.get(resolverService_1.ITextModelService).createModelReference(resource).then(function (reference) { return new Promise(function (resolve, reject) { try { var result = handler(reference.object.textEditorModel, position_1.Position.lift(position), args); resolve(result); } catch (err) { reject(err); } }).finally(function () { reference.dispose(); }); }); }); } exports.registerDefaultLanguageCommand = registerDefaultLanguageCommand; function registerModelAndPositionCommand(id, handler) { commands_1.CommandsRegistry.registerCommand(id, function (accessor) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var resource = args[0], position = args[1]; types_1.assertType(uri_1.URI.isUri(resource)); types_1.assertType(position_1.Position.isIPosition(position)); var model = accessor.get(modelService_1.IModelService).getModel(resource); if (model) { var editorPosition = position_1.Position.lift(position); return handler(model, editorPosition, args.slice(2)); } return accessor.get(resolverService_1.ITextModelService).createModelReference(resource).then(function (reference) { return new Promise(function (resolve, reject) { try { var result = handler(reference.object.textEditorModel, position_1.Position.lift(position), args.slice(2)); resolve(result); } catch (err) { reject(err); } }).finally(function () { reference.dispose(); }); }); }); } exports.registerModelAndPositionCommand = registerModelAndPositionCommand; function registerModelCommand(id, handler) { commands_1.CommandsRegistry.registerCommand(id, function (accessor) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var resource = args[0]; types_1.assertType(uri_1.URI.isUri(resource)); var model = accessor.get(modelService_1.IModelService).getModel(resource); if (model) { return handler(model, args.slice(1)); } return accessor.get(resolverService_1.ITextModelService).createModelReference(resource).then(function (reference) { return new Promise(function (resolve, reject) { try { var result = handler(reference.object.textEditorModel, args.slice(1)); resolve(result); } catch (err) { reject(err); } }).finally(function () { reference.dispose(); }); }); }); } exports.registerModelCommand = registerModelCommand; function registerEditorCommand(editorCommand) { EditorContributionRegistry.INSTANCE.registerEditorCommand(editorCommand); return editorCommand; } exports.registerEditorCommand = registerEditorCommand; function registerEditorAction(ctor) { EditorContributionRegistry.INSTANCE.registerEditorAction(new ctor()); } exports.registerEditorAction = registerEditorAction; function registerInstantiatedEditorAction(editorAction) { EditorContributionRegistry.INSTANCE.registerEditorAction(editorAction); } exports.registerInstantiatedEditorAction = registerInstantiatedEditorAction; function registerEditorContribution(id, ctor) { EditorContributionRegistry.INSTANCE.registerEditorContribution(id, ctor); } exports.registerEditorContribution = registerEditorContribution; var EditorExtensionsRegistry; (function (EditorExtensionsRegistry) { function getEditorCommand(commandId) { return EditorContributionRegistry.INSTANCE.getEditorCommand(commandId); } EditorExtensionsRegistry.getEditorCommand = getEditorCommand; function getEditorActions() { return EditorContributionRegistry.INSTANCE.getEditorActions(); } EditorExtensionsRegistry.getEditorActions = getEditorActions; function getEditorContributions() { return EditorContributionRegistry.INSTANCE.getEditorContributions(); } EditorExtensionsRegistry.getEditorContributions = getEditorContributions; function getSomeEditorContributions(ids) { return EditorContributionRegistry.INSTANCE.getEditorContributions().filter(function (c) { return ids.indexOf(c.id) >= 0; }); } EditorExtensionsRegistry.getSomeEditorContributions = getSomeEditorContributions; function getDiffEditorContributions() { return EditorContributionRegistry.INSTANCE.getDiffEditorContributions(); } EditorExtensionsRegistry.getDiffEditorContributions = getDiffEditorContributions; })(EditorExtensionsRegistry = exports.EditorExtensionsRegistry || (exports.EditorExtensionsRegistry = {})); // Editor extension points var Extensions = { EditorCommonContributions: 'editor.contributions' }; var EditorContributionRegistry = /** @class */ (function () { function EditorContributionRegistry() { this.editorContributions = []; this.diffEditorContributions = []; this.editorActions = []; this.editorCommands = Object.create(null); } EditorContributionRegistry.prototype.registerEditorContribution = function (id, ctor) { this.editorContributions.push({ id: id, ctor: ctor }); }; EditorContributionRegistry.prototype.getEditorContributions = function () { return this.editorContributions.slice(0); }; EditorContributionRegistry.prototype.getDiffEditorContributions = function () { return this.diffEditorContributions.slice(0); }; EditorContributionRegistry.prototype.registerEditorAction = function (action) { action.register(); this.editorActions.push(action); }; EditorContributionRegistry.prototype.getEditorActions = function () { return this.editorActions.slice(0); }; EditorContributionRegistry.prototype.registerEditorCommand = function (editorCommand) { editorCommand.register(); this.editorCommands[editorCommand.id] = editorCommand; }; EditorContributionRegistry.prototype.getEditorCommand = function (commandId) { return (this.editorCommands[commandId] || null); }; EditorContributionRegistry.INSTANCE = new EditorContributionRegistry(); return EditorContributionRegistry; }()); platform_1.Registry.add(Extensions.EditorCommonContributions, EditorContributionRegistry.INSTANCE); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[164/*vs/editor/browser/controller/coreCommands*/], __M([0/*require*/,1/*exports*/,415/*vs/nls!vs/editor/browser/controller/coreCommands*/,21/*vs/base/common/types*/,12/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,483/*vs/editor/common/controller/cursorColumnSelection*/,40/*vs/editor/common/controller/cursorCommon*/,212/*vs/editor/common/controller/cursorDeleteOperations*/,213/*vs/editor/common/controller/cursorMoveCommands*/,159/*vs/editor/common/controller/cursorTypeOperations*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,68/*vs/editor/common/editorCommon*/,23/*vs/editor/common/editorContextKeys*/,18/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, nls, types, editorExtensions_1, codeEditorService_1, cursorColumnSelection_1, cursorCommon_1, cursorDeleteOperations_1, cursorMoveCommands_1, cursorTypeOperations_1, position_1, range_1, editorCommon_1, editorContextKeys_1, contextkey_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CORE_WEIGHT = 0 /* EditorCore */; var CoreEditorCommand = /** @class */ (function (_super) { __extends(CoreEditorCommand, _super); function CoreEditorCommand() { return _super !== null && _super.apply(this, arguments) || this; } CoreEditorCommand.prototype.runEditorCommand = function (accessor, editor, args) { var cursors = editor._getCursors(); if (!cursors) { // the editor has no view => has no cursors return; } this.runCoreEditorCommand(cursors, args || {}); }; return CoreEditorCommand; }(editorExtensions_1.EditorCommand)); exports.CoreEditorCommand = CoreEditorCommand; var EditorScroll_; (function (EditorScroll_) { var isEditorScrollArgs = function (arg) { if (!types.isObject(arg)) { return false; } var scrollArg = arg; if (!types.isString(scrollArg.to)) { return false; } if (!types.isUndefined(scrollArg.by) && !types.isString(scrollArg.by)) { return false; } if (!types.isUndefined(scrollArg.value) && !types.isNumber(scrollArg.value)) { return false; } if (!types.isUndefined(scrollArg.revealCursor) && !types.isBoolean(scrollArg.revealCursor)) { return false; } return true; }; EditorScroll_.description = { description: 'Scroll editor in the given direction', args: [ { name: 'Editor scroll argument object', description: "Property-value pairs that can be passed through this argument:\n\t\t\t\t\t* 'to': A mandatory direction value.\n\t\t\t\t\t\t```\n\t\t\t\t\t\t'up', 'down'\n\t\t\t\t\t\t```\n\t\t\t\t\t* 'by': Unit to move. Default is computed based on 'to' value.\n\t\t\t\t\t\t```\n\t\t\t\t\t\t'line', 'wrappedLine', 'page', 'halfPage'\n\t\t\t\t\t\t```\n\t\t\t\t\t* 'value': Number of units to move. Default is '1'.\n\t\t\t\t\t* 'revealCursor': If 'true' reveals the cursor if it is outside view port.\n\t\t\t\t", constraint: isEditorScrollArgs, schema: { 'type': 'object', 'required': ['to'], 'properties': { 'to': { 'type': 'string', 'enum': ['up', 'down'] }, 'by': { 'type': 'string', 'enum': ['line', 'wrappedLine', 'page', 'halfPage'] }, 'value': { 'type': 'number', 'default': 1 }, 'revealCursor': { 'type': 'boolean', } } } } ] }; /** * Directions in the view for editor scroll command. */ EditorScroll_.RawDirection = { Up: 'up', Down: 'down', }; /** * Units for editor scroll 'by' argument */ EditorScroll_.RawUnit = { Line: 'line', WrappedLine: 'wrappedLine', Page: 'page', HalfPage: 'halfPage' }; function parse(args) { var direction; switch (args.to) { case EditorScroll_.RawDirection.Up: direction = 1 /* Up */; break; case EditorScroll_.RawDirection.Down: direction = 2 /* Down */; break; default: // Illegal arguments return null; } var unit; switch (args.by) { case EditorScroll_.RawUnit.Line: unit = 1 /* Line */; break; case EditorScroll_.RawUnit.WrappedLine: unit = 2 /* WrappedLine */; break; case EditorScroll_.RawUnit.Page: unit = 3 /* Page */; break; case EditorScroll_.RawUnit.HalfPage: unit = 4 /* HalfPage */; break; default: unit = 2 /* WrappedLine */; } var value = Math.floor(args.value || 1); var revealCursor = !!args.revealCursor; return { direction: direction, unit: unit, value: value, revealCursor: revealCursor, select: (!!args.select) }; } EditorScroll_.parse = parse; })(EditorScroll_ = exports.EditorScroll_ || (exports.EditorScroll_ = {})); var RevealLine_; (function (RevealLine_) { var isRevealLineArgs = function (arg) { if (!types.isObject(arg)) { return false; } var reveaLineArg = arg; if (!types.isNumber(reveaLineArg.lineNumber)) { return false; } if (!types.isUndefined(reveaLineArg.at) && !types.isString(reveaLineArg.at)) { return false; } return true; }; RevealLine_.description = { description: 'Reveal the given line at the given logical position', args: [ { name: 'Reveal line argument object', description: "Property-value pairs that can be passed through this argument:\n\t\t\t\t\t* 'lineNumber': A mandatory line number value.\n\t\t\t\t\t* 'at': Logical position at which line has to be revealed .\n\t\t\t\t\t\t```\n\t\t\t\t\t\t'top', 'center', 'bottom'\n\t\t\t\t\t\t```\n\t\t\t\t", constraint: isRevealLineArgs, schema: { 'type': 'object', 'required': ['lineNumber'], 'properties': { 'lineNumber': { 'type': 'number', }, 'at': { 'type': 'string', 'enum': ['top', 'center', 'bottom'] } } } } ] }; /** * Values for reveal line 'at' argument */ RevealLine_.RawAtArgument = { Top: 'top', Center: 'center', Bottom: 'bottom' }; })(RevealLine_ = exports.RevealLine_ || (exports.RevealLine_ = {})); var CoreNavigationCommands; (function (CoreNavigationCommands) { var BaseMoveToCommand = /** @class */ (function (_super) { __extends(BaseMoveToCommand, _super); function BaseMoveToCommand(opts) { var _this = _super.call(this, opts) || this; _this._inSelectionMode = opts.inSelectionMode; return _this; } BaseMoveToCommand.prototype.runCoreEditorCommand = function (cursors, args) { cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, [ cursorMoveCommands_1.CursorMoveCommands.moveTo(cursors.context, cursors.getPrimaryCursor(), this._inSelectionMode, args.position, args.viewPosition) ]); cursors.reveal(args.source, true, 0 /* Primary */, 0 /* Smooth */); }; return BaseMoveToCommand; }(CoreEditorCommand)); CoreNavigationCommands.MoveTo = editorExtensions_1.registerEditorCommand(new BaseMoveToCommand({ id: '_moveTo', inSelectionMode: false, precondition: undefined })); CoreNavigationCommands.MoveToSelect = editorExtensions_1.registerEditorCommand(new BaseMoveToCommand({ id: '_moveToSelect', inSelectionMode: true, precondition: undefined })); var ColumnSelectCommand = /** @class */ (function (_super) { __extends(ColumnSelectCommand, _super); function ColumnSelectCommand() { return _super !== null && _super.apply(this, arguments) || this; } ColumnSelectCommand.prototype.runCoreEditorCommand = function (cursors, args) { cursors.context.model.pushStackElement(); var result = this._getColumnSelectResult(cursors.context, cursors.getPrimaryCursor(), cursors.getColumnSelectData(), args); cursors.setStates(args.source, 3 /* Explicit */, result.viewStates.map(function (viewState) { return cursorCommon_1.CursorState.fromViewState(viewState); })); cursors.setColumnSelectData({ isReal: true, fromViewLineNumber: result.fromLineNumber, fromViewVisualColumn: result.fromVisualColumn, toViewLineNumber: result.toLineNumber, toViewVisualColumn: result.toVisualColumn }); cursors.reveal(args.source, true, (result.reversed ? 1 /* TopMost */ : 2 /* BottomMost */), 0 /* Smooth */); }; return ColumnSelectCommand; }(CoreEditorCommand)); CoreNavigationCommands.ColumnSelect = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_1, _super); function class_1() { return _super.call(this, { id: 'columnSelect', precondition: undefined }) || this; } class_1.prototype._getColumnSelectResult = function (context, primary, prevColumnSelectData, args) { // validate `args` var validatedPosition = context.model.validatePosition(args.position); var validatedViewPosition = context.validateViewPosition(new position_1.Position(args.viewPosition.lineNumber, args.viewPosition.column), validatedPosition); var fromViewLineNumber = args.doColumnSelect ? prevColumnSelectData.fromViewLineNumber : validatedViewPosition.lineNumber; var fromViewVisualColumn = args.doColumnSelect ? prevColumnSelectData.fromViewVisualColumn : args.mouseColumn - 1; return cursorColumnSelection_1.ColumnSelection.columnSelect(context.config, context.viewModel, fromViewLineNumber, fromViewVisualColumn, validatedViewPosition.lineNumber, args.mouseColumn - 1); }; return class_1; }(ColumnSelectCommand))); CoreNavigationCommands.CursorColumnSelectLeft = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_2, _super); function class_2() { return _super.call(this, { id: 'cursorColumnSelectLeft', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 15 /* LeftArrow */, linux: { primary: 0 } } }) || this; } class_2.prototype._getColumnSelectResult = function (context, primary, prevColumnSelectData, args) { return cursorColumnSelection_1.ColumnSelection.columnSelectLeft(context.config, context.viewModel, prevColumnSelectData); }; return class_2; }(ColumnSelectCommand))); CoreNavigationCommands.CursorColumnSelectRight = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_3, _super); function class_3() { return _super.call(this, { id: 'cursorColumnSelectRight', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 17 /* RightArrow */, linux: { primary: 0 } } }) || this; } class_3.prototype._getColumnSelectResult = function (context, primary, prevColumnSelectData, args) { return cursorColumnSelection_1.ColumnSelection.columnSelectRight(context.config, context.viewModel, prevColumnSelectData); }; return class_3; }(ColumnSelectCommand))); var ColumnSelectUpCommand = /** @class */ (function (_super) { __extends(ColumnSelectUpCommand, _super); function ColumnSelectUpCommand(opts) { var _this = _super.call(this, opts) || this; _this._isPaged = opts.isPaged; return _this; } ColumnSelectUpCommand.prototype._getColumnSelectResult = function (context, primary, prevColumnSelectData, args) { return cursorColumnSelection_1.ColumnSelection.columnSelectUp(context.config, context.viewModel, prevColumnSelectData, this._isPaged); }; return ColumnSelectUpCommand; }(ColumnSelectCommand)); CoreNavigationCommands.CursorColumnSelectUp = editorExtensions_1.registerEditorCommand(new ColumnSelectUpCommand({ isPaged: false, id: 'cursorColumnSelectUp', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 16 /* UpArrow */, linux: { primary: 0 } } })); CoreNavigationCommands.CursorColumnSelectPageUp = editorExtensions_1.registerEditorCommand(new ColumnSelectUpCommand({ isPaged: true, id: 'cursorColumnSelectPageUp', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 11 /* PageUp */, linux: { primary: 0 } } })); var ColumnSelectDownCommand = /** @class */ (function (_super) { __extends(ColumnSelectDownCommand, _super); function ColumnSelectDownCommand(opts) { var _this = _super.call(this, opts) || this; _this._isPaged = opts.isPaged; return _this; } ColumnSelectDownCommand.prototype._getColumnSelectResult = function (context, primary, prevColumnSelectData, args) { return cursorColumnSelection_1.ColumnSelection.columnSelectDown(context.config, context.viewModel, prevColumnSelectData, this._isPaged); }; return ColumnSelectDownCommand; }(ColumnSelectCommand)); CoreNavigationCommands.CursorColumnSelectDown = editorExtensions_1.registerEditorCommand(new ColumnSelectDownCommand({ isPaged: false, id: 'cursorColumnSelectDown', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 18 /* DownArrow */, linux: { primary: 0 } } })); CoreNavigationCommands.CursorColumnSelectPageDown = editorExtensions_1.registerEditorCommand(new ColumnSelectDownCommand({ isPaged: true, id: 'cursorColumnSelectPageDown', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 12 /* PageDown */, linux: { primary: 0 } } })); var CursorMoveImpl = /** @class */ (function (_super) { __extends(CursorMoveImpl, _super); function CursorMoveImpl() { return _super.call(this, { id: 'cursorMove', precondition: undefined, description: cursorMoveCommands_1.CursorMove.description }) || this; } CursorMoveImpl.prototype.runCoreEditorCommand = function (cursors, args) { var parsed = cursorMoveCommands_1.CursorMove.parse(args); if (!parsed) { // illegal arguments return; } this._runCursorMove(cursors, args.source, parsed); }; CursorMoveImpl.prototype._runCursorMove = function (cursors, source, args) { cursors.context.model.pushStackElement(); cursors.setStates(source, 3 /* Explicit */, cursorMoveCommands_1.CursorMoveCommands.move(cursors.context, cursors.getAll(), args)); cursors.reveal(source, true, 0 /* Primary */, 0 /* Smooth */); }; return CursorMoveImpl; }(CoreEditorCommand)); CoreNavigationCommands.CursorMoveImpl = CursorMoveImpl; CoreNavigationCommands.CursorMove = editorExtensions_1.registerEditorCommand(new CursorMoveImpl()); var CursorMoveBasedCommand = /** @class */ (function (_super) { __extends(CursorMoveBasedCommand, _super); function CursorMoveBasedCommand(opts) { var _this = _super.call(this, opts) || this; _this._staticArgs = opts.args; return _this; } CursorMoveBasedCommand.prototype.runCoreEditorCommand = function (cursors, dynamicArgs) { var args = this._staticArgs; if (this._staticArgs.value === -1 /* PAGE_SIZE_MARKER */) { // -1 is a marker for page size args = { direction: this._staticArgs.direction, unit: this._staticArgs.unit, select: this._staticArgs.select, value: cursors.context.config.pageSize }; } CoreNavigationCommands.CursorMove._runCursorMove(cursors, dynamicArgs.source, args); }; return CursorMoveBasedCommand; }(CoreEditorCommand)); CoreNavigationCommands.CursorLeft = editorExtensions_1.registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 0 /* Left */, unit: 0 /* None */, select: false, value: 1 }, id: 'cursorLeft', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 15 /* LeftArrow */, mac: { primary: 15 /* LeftArrow */, secondary: [256 /* WinCtrl */ | 32 /* KEY_B */] } } })); CoreNavigationCommands.CursorLeftSelect = editorExtensions_1.registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 0 /* Left */, unit: 0 /* None */, select: true, value: 1 }, id: 'cursorLeftSelect', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 1024 /* Shift */ | 15 /* LeftArrow */ } })); CoreNavigationCommands.CursorRight = editorExtensions_1.registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 1 /* Right */, unit: 0 /* None */, select: false, value: 1 }, id: 'cursorRight', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 17 /* RightArrow */, mac: { primary: 17 /* RightArrow */, secondary: [256 /* WinCtrl */ | 36 /* KEY_F */] } } })); CoreNavigationCommands.CursorRightSelect = editorExtensions_1.registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 1 /* Right */, unit: 0 /* None */, select: true, value: 1 }, id: 'cursorRightSelect', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 1024 /* Shift */ | 17 /* RightArrow */ } })); CoreNavigationCommands.CursorUp = editorExtensions_1.registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 2 /* Up */, unit: 2 /* WrappedLine */, select: false, value: 1 }, id: 'cursorUp', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 16 /* UpArrow */, mac: { primary: 16 /* UpArrow */, secondary: [256 /* WinCtrl */ | 46 /* KEY_P */] } } })); CoreNavigationCommands.CursorUpSelect = editorExtensions_1.registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 2 /* Up */, unit: 2 /* WrappedLine */, select: true, value: 1 }, id: 'cursorUpSelect', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 1024 /* Shift */ | 16 /* UpArrow */, secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 16 /* UpArrow */], mac: { primary: 1024 /* Shift */ | 16 /* UpArrow */ }, linux: { primary: 1024 /* Shift */ | 16 /* UpArrow */ } } })); CoreNavigationCommands.CursorPageUp = editorExtensions_1.registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 2 /* Up */, unit: 2 /* WrappedLine */, select: false, value: -1 /* PAGE_SIZE_MARKER */ }, id: 'cursorPageUp', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 11 /* PageUp */ } })); CoreNavigationCommands.CursorPageUpSelect = editorExtensions_1.registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 2 /* Up */, unit: 2 /* WrappedLine */, select: true, value: -1 /* PAGE_SIZE_MARKER */ }, id: 'cursorPageUpSelect', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 1024 /* Shift */ | 11 /* PageUp */ } })); CoreNavigationCommands.CursorDown = editorExtensions_1.registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 3 /* Down */, unit: 2 /* WrappedLine */, select: false, value: 1 }, id: 'cursorDown', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 18 /* DownArrow */, mac: { primary: 18 /* DownArrow */, secondary: [256 /* WinCtrl */ | 44 /* KEY_N */] } } })); CoreNavigationCommands.CursorDownSelect = editorExtensions_1.registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 3 /* Down */, unit: 2 /* WrappedLine */, select: true, value: 1 }, id: 'cursorDownSelect', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 1024 /* Shift */ | 18 /* DownArrow */, secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 18 /* DownArrow */], mac: { primary: 1024 /* Shift */ | 18 /* DownArrow */ }, linux: { primary: 1024 /* Shift */ | 18 /* DownArrow */ } } })); CoreNavigationCommands.CursorPageDown = editorExtensions_1.registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 3 /* Down */, unit: 2 /* WrappedLine */, select: false, value: -1 /* PAGE_SIZE_MARKER */ }, id: 'cursorPageDown', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 12 /* PageDown */ } })); CoreNavigationCommands.CursorPageDownSelect = editorExtensions_1.registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 3 /* Down */, unit: 2 /* WrappedLine */, select: true, value: -1 /* PAGE_SIZE_MARKER */ }, id: 'cursorPageDownSelect', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 1024 /* Shift */ | 12 /* PageDown */ } })); CoreNavigationCommands.CreateCursor = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_4, _super); function class_4() { return _super.call(this, { id: 'createCursor', precondition: undefined }) || this; } class_4.prototype.runCoreEditorCommand = function (cursors, args) { var context = cursors.context; var newState; if (args.wholeLine) { newState = cursorMoveCommands_1.CursorMoveCommands.line(context, cursors.getPrimaryCursor(), false, args.position, args.viewPosition); } else { newState = cursorMoveCommands_1.CursorMoveCommands.moveTo(context, cursors.getPrimaryCursor(), false, args.position, args.viewPosition); } var states = cursors.getAll(); // Check if we should remove a cursor (sort of like a toggle) if (states.length > 1) { var newModelPosition = (newState.modelState ? newState.modelState.position : null); var newViewPosition = (newState.viewState ? newState.viewState.position : null); for (var i = 0, len = states.length; i < len; i++) { var state = states[i]; if (newModelPosition && !state.modelState.selection.containsPosition(newModelPosition)) { continue; } if (newViewPosition && !state.viewState.selection.containsPosition(newViewPosition)) { continue; } // => Remove the cursor states.splice(i, 1); cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, states); return; } } // => Add the new cursor states.push(newState); cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, states); }; return class_4; }(CoreEditorCommand))); CoreNavigationCommands.LastCursorMoveToSelect = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_5, _super); function class_5() { return _super.call(this, { id: '_lastCursorMoveToSelect', precondition: undefined }) || this; } class_5.prototype.runCoreEditorCommand = function (cursors, args) { var context = cursors.context; var lastAddedCursorIndex = cursors.getLastAddedCursorIndex(); var states = cursors.getAll(); var newStates = states.slice(0); newStates[lastAddedCursorIndex] = cursorMoveCommands_1.CursorMoveCommands.moveTo(context, states[lastAddedCursorIndex], true, args.position, args.viewPosition); cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, newStates); }; return class_5; }(CoreEditorCommand))); var HomeCommand = /** @class */ (function (_super) { __extends(HomeCommand, _super); function HomeCommand(opts) { var _this = _super.call(this, opts) || this; _this._inSelectionMode = opts.inSelectionMode; return _this; } HomeCommand.prototype.runCoreEditorCommand = function (cursors, args) { cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, cursorMoveCommands_1.CursorMoveCommands.moveToBeginningOfLine(cursors.context, cursors.getAll(), this._inSelectionMode)); cursors.reveal(args.source, true, 0 /* Primary */, 0 /* Smooth */); }; return HomeCommand; }(CoreEditorCommand)); CoreNavigationCommands.CursorHome = editorExtensions_1.registerEditorCommand(new HomeCommand({ inSelectionMode: false, id: 'cursorHome', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 14 /* Home */, mac: { primary: 14 /* Home */, secondary: [2048 /* CtrlCmd */ | 15 /* LeftArrow */] } } })); CoreNavigationCommands.CursorHomeSelect = editorExtensions_1.registerEditorCommand(new HomeCommand({ inSelectionMode: true, id: 'cursorHomeSelect', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 1024 /* Shift */ | 14 /* Home */, mac: { primary: 1024 /* Shift */ | 14 /* Home */, secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 15 /* LeftArrow */] } } })); CoreNavigationCommands.CursorLineStart = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_6, _super); function class_6() { return _super.call(this, { id: 'cursorLineStart', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 /* WinCtrl */ | 31 /* KEY_A */ } } }) || this; } class_6.prototype.runCoreEditorCommand = function (cursors, args) { cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, this._exec(cursors.context, cursors.getAll())); cursors.reveal(args.source, true, 0 /* Primary */, 0 /* Smooth */); }; class_6.prototype._exec = function (context, cursors) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; var lineNumber = cursor.modelState.position.lineNumber; result[i] = cursorCommon_1.CursorState.fromModelState(cursor.modelState.move(false, lineNumber, 1, 0)); } return result; }; return class_6; }(CoreEditorCommand))); var EndCommand = /** @class */ (function (_super) { __extends(EndCommand, _super); function EndCommand(opts) { var _this = _super.call(this, opts) || this; _this._inSelectionMode = opts.inSelectionMode; return _this; } EndCommand.prototype.runCoreEditorCommand = function (cursors, args) { cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, cursorMoveCommands_1.CursorMoveCommands.moveToEndOfLine(cursors.context, cursors.getAll(), this._inSelectionMode)); cursors.reveal(args.source, true, 0 /* Primary */, 0 /* Smooth */); }; return EndCommand; }(CoreEditorCommand)); CoreNavigationCommands.CursorEnd = editorExtensions_1.registerEditorCommand(new EndCommand({ inSelectionMode: false, id: 'cursorEnd', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 13 /* End */, mac: { primary: 13 /* End */, secondary: [2048 /* CtrlCmd */ | 17 /* RightArrow */] } } })); CoreNavigationCommands.CursorEndSelect = editorExtensions_1.registerEditorCommand(new EndCommand({ inSelectionMode: true, id: 'cursorEndSelect', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 1024 /* Shift */ | 13 /* End */, mac: { primary: 1024 /* Shift */ | 13 /* End */, secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 17 /* RightArrow */] } } })); CoreNavigationCommands.CursorLineEnd = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_7, _super); function class_7() { return _super.call(this, { id: 'cursorLineEnd', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 /* WinCtrl */ | 35 /* KEY_E */ } } }) || this; } class_7.prototype.runCoreEditorCommand = function (cursors, args) { cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, this._exec(cursors.context, cursors.getAll())); cursors.reveal(args.source, true, 0 /* Primary */, 0 /* Smooth */); }; class_7.prototype._exec = function (context, cursors) { var result = []; for (var i = 0, len = cursors.length; i < len; i++) { var cursor = cursors[i]; var lineNumber = cursor.modelState.position.lineNumber; var maxColumn = context.model.getLineMaxColumn(lineNumber); result[i] = cursorCommon_1.CursorState.fromModelState(cursor.modelState.move(false, lineNumber, maxColumn, 0)); } return result; }; return class_7; }(CoreEditorCommand))); var TopCommand = /** @class */ (function (_super) { __extends(TopCommand, _super); function TopCommand(opts) { var _this = _super.call(this, opts) || this; _this._inSelectionMode = opts.inSelectionMode; return _this; } TopCommand.prototype.runCoreEditorCommand = function (cursors, args) { cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, cursorMoveCommands_1.CursorMoveCommands.moveToBeginningOfBuffer(cursors.context, cursors.getAll(), this._inSelectionMode)); cursors.reveal(args.source, true, 0 /* Primary */, 0 /* Smooth */); }; return TopCommand; }(CoreEditorCommand)); CoreNavigationCommands.CursorTop = editorExtensions_1.registerEditorCommand(new TopCommand({ inSelectionMode: false, id: 'cursorTop', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 14 /* Home */, mac: { primary: 2048 /* CtrlCmd */ | 16 /* UpArrow */ } } })); CoreNavigationCommands.CursorTopSelect = editorExtensions_1.registerEditorCommand(new TopCommand({ inSelectionMode: true, id: 'cursorTopSelect', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 14 /* Home */, mac: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 16 /* UpArrow */ } } })); var BottomCommand = /** @class */ (function (_super) { __extends(BottomCommand, _super); function BottomCommand(opts) { var _this = _super.call(this, opts) || this; _this._inSelectionMode = opts.inSelectionMode; return _this; } BottomCommand.prototype.runCoreEditorCommand = function (cursors, args) { cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, cursorMoveCommands_1.CursorMoveCommands.moveToEndOfBuffer(cursors.context, cursors.getAll(), this._inSelectionMode)); cursors.reveal(args.source, true, 0 /* Primary */, 0 /* Smooth */); }; return BottomCommand; }(CoreEditorCommand)); CoreNavigationCommands.CursorBottom = editorExtensions_1.registerEditorCommand(new BottomCommand({ inSelectionMode: false, id: 'cursorBottom', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 13 /* End */, mac: { primary: 2048 /* CtrlCmd */ | 18 /* DownArrow */ } } })); CoreNavigationCommands.CursorBottomSelect = editorExtensions_1.registerEditorCommand(new BottomCommand({ inSelectionMode: true, id: 'cursorBottomSelect', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 13 /* End */, mac: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 18 /* DownArrow */ } } })); var EditorScrollImpl = /** @class */ (function (_super) { __extends(EditorScrollImpl, _super); function EditorScrollImpl() { return _super.call(this, { id: 'editorScroll', precondition: undefined, description: EditorScroll_.description }) || this; } EditorScrollImpl.prototype.runCoreEditorCommand = function (cursors, args) { var parsed = EditorScroll_.parse(args); if (!parsed) { // illegal arguments return; } this._runEditorScroll(cursors, args.source, parsed); }; EditorScrollImpl.prototype._runEditorScroll = function (cursors, source, args) { var desiredScrollTop = this._computeDesiredScrollTop(cursors.context, args); if (args.revealCursor) { // must ensure cursor is in new visible range var desiredVisibleViewRange = cursors.context.getCompletelyVisibleViewRangeAtScrollTop(desiredScrollTop); cursors.setStates(source, 3 /* Explicit */, [ cursorMoveCommands_1.CursorMoveCommands.findPositionInViewportIfOutside(cursors.context, cursors.getPrimaryCursor(), desiredVisibleViewRange, args.select) ]); } cursors.scrollTo(desiredScrollTop); }; EditorScrollImpl.prototype._computeDesiredScrollTop = function (context, args) { if (args.unit === 1 /* Line */) { // scrolling by model lines var visibleModelRange = context.getCompletelyVisibleModelRange(); var desiredTopModelLineNumber = void 0; if (args.direction === 1 /* Up */) { // must go x model lines up desiredTopModelLineNumber = Math.max(1, visibleModelRange.startLineNumber - args.value); } else { // must go x model lines down desiredTopModelLineNumber = Math.min(context.model.getLineCount(), visibleModelRange.startLineNumber + args.value); } var desiredTopViewPosition = context.convertModelPositionToViewPosition(new position_1.Position(desiredTopModelLineNumber, 1)); return context.getVerticalOffsetForViewLine(desiredTopViewPosition.lineNumber); } var noOfLines; if (args.unit === 3 /* Page */) { noOfLines = context.config.pageSize * args.value; } else if (args.unit === 4 /* HalfPage */) { noOfLines = Math.round(context.config.pageSize / 2) * args.value; } else { noOfLines = args.value; } var deltaLines = (args.direction === 1 /* Up */ ? -1 : 1) * noOfLines; return context.getCurrentScrollTop() + deltaLines * context.config.lineHeight; }; return EditorScrollImpl; }(CoreEditorCommand)); CoreNavigationCommands.EditorScrollImpl = EditorScrollImpl; CoreNavigationCommands.EditorScroll = editorExtensions_1.registerEditorCommand(new EditorScrollImpl()); CoreNavigationCommands.ScrollLineUp = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_8, _super); function class_8() { return _super.call(this, { id: 'scrollLineUp', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 16 /* UpArrow */, mac: { primary: 256 /* WinCtrl */ | 11 /* PageUp */ } } }) || this; } class_8.prototype.runCoreEditorCommand = function (cursors, args) { CoreNavigationCommands.EditorScroll._runEditorScroll(cursors, args.source, { direction: 1 /* Up */, unit: 2 /* WrappedLine */, value: 1, revealCursor: false, select: false }); }; return class_8; }(CoreEditorCommand))); CoreNavigationCommands.ScrollPageUp = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_9, _super); function class_9() { return _super.call(this, { id: 'scrollPageUp', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 11 /* PageUp */, win: { primary: 512 /* Alt */ | 11 /* PageUp */ }, linux: { primary: 512 /* Alt */ | 11 /* PageUp */ } } }) || this; } class_9.prototype.runCoreEditorCommand = function (cursors, args) { CoreNavigationCommands.EditorScroll._runEditorScroll(cursors, args.source, { direction: 1 /* Up */, unit: 3 /* Page */, value: 1, revealCursor: false, select: false }); }; return class_9; }(CoreEditorCommand))); CoreNavigationCommands.ScrollLineDown = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_10, _super); function class_10() { return _super.call(this, { id: 'scrollLineDown', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 18 /* DownArrow */, mac: { primary: 256 /* WinCtrl */ | 12 /* PageDown */ } } }) || this; } class_10.prototype.runCoreEditorCommand = function (cursors, args) { CoreNavigationCommands.EditorScroll._runEditorScroll(cursors, args.source, { direction: 2 /* Down */, unit: 2 /* WrappedLine */, value: 1, revealCursor: false, select: false }); }; return class_10; }(CoreEditorCommand))); CoreNavigationCommands.ScrollPageDown = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_11, _super); function class_11() { return _super.call(this, { id: 'scrollPageDown', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 12 /* PageDown */, win: { primary: 512 /* Alt */ | 12 /* PageDown */ }, linux: { primary: 512 /* Alt */ | 12 /* PageDown */ } } }) || this; } class_11.prototype.runCoreEditorCommand = function (cursors, args) { CoreNavigationCommands.EditorScroll._runEditorScroll(cursors, args.source, { direction: 2 /* Down */, unit: 3 /* Page */, value: 1, revealCursor: false, select: false }); }; return class_11; }(CoreEditorCommand))); var WordCommand = /** @class */ (function (_super) { __extends(WordCommand, _super); function WordCommand(opts) { var _this = _super.call(this, opts) || this; _this._inSelectionMode = opts.inSelectionMode; return _this; } WordCommand.prototype.runCoreEditorCommand = function (cursors, args) { cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, [ cursorMoveCommands_1.CursorMoveCommands.word(cursors.context, cursors.getPrimaryCursor(), this._inSelectionMode, args.position) ]); cursors.reveal(args.source, true, 0 /* Primary */, 0 /* Smooth */); }; return WordCommand; }(CoreEditorCommand)); CoreNavigationCommands.WordSelect = editorExtensions_1.registerEditorCommand(new WordCommand({ inSelectionMode: false, id: '_wordSelect', precondition: undefined })); CoreNavigationCommands.WordSelectDrag = editorExtensions_1.registerEditorCommand(new WordCommand({ inSelectionMode: true, id: '_wordSelectDrag', precondition: undefined })); CoreNavigationCommands.LastCursorWordSelect = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_12, _super); function class_12() { return _super.call(this, { id: 'lastCursorWordSelect', precondition: undefined }) || this; } class_12.prototype.runCoreEditorCommand = function (cursors, args) { var context = cursors.context; var lastAddedCursorIndex = cursors.getLastAddedCursorIndex(); var states = cursors.getAll(); var newStates = states.slice(0); var lastAddedState = states[lastAddedCursorIndex]; newStates[lastAddedCursorIndex] = cursorMoveCommands_1.CursorMoveCommands.word(context, lastAddedState, lastAddedState.modelState.hasSelection(), args.position); context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, newStates); }; return class_12; }(CoreEditorCommand))); var LineCommand = /** @class */ (function (_super) { __extends(LineCommand, _super); function LineCommand(opts) { var _this = _super.call(this, opts) || this; _this._inSelectionMode = opts.inSelectionMode; return _this; } LineCommand.prototype.runCoreEditorCommand = function (cursors, args) { cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, [ cursorMoveCommands_1.CursorMoveCommands.line(cursors.context, cursors.getPrimaryCursor(), this._inSelectionMode, args.position, args.viewPosition) ]); cursors.reveal(args.source, false, 0 /* Primary */, 0 /* Smooth */); }; return LineCommand; }(CoreEditorCommand)); CoreNavigationCommands.LineSelect = editorExtensions_1.registerEditorCommand(new LineCommand({ inSelectionMode: false, id: '_lineSelect', precondition: undefined })); CoreNavigationCommands.LineSelectDrag = editorExtensions_1.registerEditorCommand(new LineCommand({ inSelectionMode: true, id: '_lineSelectDrag', precondition: undefined })); var LastCursorLineCommand = /** @class */ (function (_super) { __extends(LastCursorLineCommand, _super); function LastCursorLineCommand(opts) { var _this = _super.call(this, opts) || this; _this._inSelectionMode = opts.inSelectionMode; return _this; } LastCursorLineCommand.prototype.runCoreEditorCommand = function (cursors, args) { var lastAddedCursorIndex = cursors.getLastAddedCursorIndex(); var states = cursors.getAll(); var newStates = states.slice(0); newStates[lastAddedCursorIndex] = cursorMoveCommands_1.CursorMoveCommands.line(cursors.context, states[lastAddedCursorIndex], this._inSelectionMode, args.position, args.viewPosition); cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, newStates); }; return LastCursorLineCommand; }(CoreEditorCommand)); CoreNavigationCommands.LastCursorLineSelect = editorExtensions_1.registerEditorCommand(new LastCursorLineCommand({ inSelectionMode: false, id: 'lastCursorLineSelect', precondition: undefined })); CoreNavigationCommands.LastCursorLineSelectDrag = editorExtensions_1.registerEditorCommand(new LastCursorLineCommand({ inSelectionMode: true, id: 'lastCursorLineSelectDrag', precondition: undefined })); CoreNavigationCommands.ExpandLineSelection = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_13, _super); function class_13() { return _super.call(this, { id: 'expandLineSelection', precondition: undefined, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 42 /* KEY_L */ } }) || this; } class_13.prototype.runCoreEditorCommand = function (cursors, args) { cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, cursorMoveCommands_1.CursorMoveCommands.expandLineSelection(cursors.context, cursors.getAll())); cursors.reveal(args.source, true, 0 /* Primary */, 0 /* Smooth */); }; return class_13; }(CoreEditorCommand))); CoreNavigationCommands.CancelSelection = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_14, _super); function class_14() { return _super.call(this, { id: 'cancelSelection', precondition: editorContextKeys_1.EditorContextKeys.hasNonEmptySelection, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 9 /* Escape */, secondary: [1024 /* Shift */ | 9 /* Escape */] } }) || this; } class_14.prototype.runCoreEditorCommand = function (cursors, args) { cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, [ cursorMoveCommands_1.CursorMoveCommands.cancelSelection(cursors.context, cursors.getPrimaryCursor()) ]); cursors.reveal(args.source, true, 0 /* Primary */, 0 /* Smooth */); }; return class_14; }(CoreEditorCommand))); CoreNavigationCommands.RemoveSecondaryCursors = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_15, _super); function class_15() { return _super.call(this, { id: 'removeSecondaryCursors', precondition: editorContextKeys_1.EditorContextKeys.hasMultipleSelections, kbOpts: { weight: CORE_WEIGHT + 1, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 9 /* Escape */, secondary: [1024 /* Shift */ | 9 /* Escape */] } }) || this; } class_15.prototype.runCoreEditorCommand = function (cursors, args) { cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, [ cursors.getPrimaryCursor() ]); cursors.reveal(args.source, true, 0 /* Primary */, 0 /* Smooth */); }; return class_15; }(CoreEditorCommand))); CoreNavigationCommands.RevealLine = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_16, _super); function class_16() { return _super.call(this, { id: 'revealLine', precondition: undefined, description: RevealLine_.description }) || this; } class_16.prototype.runCoreEditorCommand = function (cursors, args) { var revealLineArg = args; var lineNumber = (revealLineArg.lineNumber || 0) + 1; if (lineNumber < 1) { lineNumber = 1; } var lineCount = cursors.context.model.getLineCount(); if (lineNumber > lineCount) { lineNumber = lineCount; } var range = new range_1.Range(lineNumber, 1, lineNumber, cursors.context.model.getLineMaxColumn(lineNumber)); var revealAt = 0 /* Simple */; if (revealLineArg.at) { switch (revealLineArg.at) { case RevealLine_.RawAtArgument.Top: revealAt = 3 /* Top */; break; case RevealLine_.RawAtArgument.Center: revealAt = 1 /* Center */; break; case RevealLine_.RawAtArgument.Bottom: revealAt = 4 /* Bottom */; break; default: break; } } var viewRange = cursors.context.convertModelRangeToViewRange(range); cursors.revealRange(args.source, false, viewRange, revealAt, 0 /* Smooth */); }; return class_16; }(CoreEditorCommand))); CoreNavigationCommands.SelectAll = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_17, _super); function class_17() { return _super.call(this, { id: 'selectAll', precondition: undefined }) || this; } class_17.prototype.runCoreEditorCommand = function (cursors, args) { cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, [ cursorMoveCommands_1.CursorMoveCommands.selectAll(cursors.context, cursors.getPrimaryCursor()) ]); }; return class_17; }(CoreEditorCommand))); CoreNavigationCommands.SetSelection = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_18, _super); function class_18() { return _super.call(this, { id: 'setSelection', precondition: undefined }) || this; } class_18.prototype.runCoreEditorCommand = function (cursors, args) { cursors.context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, [ cursorCommon_1.CursorState.fromModelSelection(args.selection) ]); }; return class_18; }(CoreEditorCommand))); })(CoreNavigationCommands = exports.CoreNavigationCommands || (exports.CoreNavigationCommands = {})); var CoreEditingCommands; (function (CoreEditingCommands) { var CoreEditingCommand = /** @class */ (function (_super) { __extends(CoreEditingCommand, _super); function CoreEditingCommand() { return _super !== null && _super.apply(this, arguments) || this; } CoreEditingCommand.prototype.runEditorCommand = function (accessor, editor, args) { var cursors = editor._getCursors(); if (!cursors) { // the editor has no view => has no cursors return; } this.runCoreEditingCommand(editor, cursors, args || {}); }; return CoreEditingCommand; }(editorExtensions_1.EditorCommand)); CoreEditingCommands.CoreEditingCommand = CoreEditingCommand; CoreEditingCommands.LineBreakInsert = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_19, _super); function class_19() { return _super.call(this, { id: 'lineBreakInsert', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 /* WinCtrl */ | 45 /* KEY_O */ } } }) || this; } class_19.prototype.runCoreEditingCommand = function (editor, cursors, args) { editor.pushUndoStop(); editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.lineBreakInsert(cursors.context.config, cursors.context.model, cursors.getAll().map(function (s) { return s.modelState.selection; }))); }; return class_19; }(CoreEditingCommand))); CoreEditingCommands.Outdent = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_20, _super); function class_20() { return _super.call(this, { id: 'outdent', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { weight: CORE_WEIGHT, kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.editorTextFocus, editorContextKeys_1.EditorContextKeys.tabDoesNotMoveFocus), primary: 1024 /* Shift */ | 2 /* Tab */ } }) || this; } class_20.prototype.runCoreEditingCommand = function (editor, cursors, args) { editor.pushUndoStop(); editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.outdent(cursors.context.config, cursors.context.model, cursors.getAll().map(function (s) { return s.modelState.selection; }))); editor.pushUndoStop(); }; return class_20; }(CoreEditingCommand))); CoreEditingCommands.Tab = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_21, _super); function class_21() { return _super.call(this, { id: 'tab', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { weight: CORE_WEIGHT, kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.editorTextFocus, editorContextKeys_1.EditorContextKeys.tabDoesNotMoveFocus), primary: 2 /* Tab */ } }) || this; } class_21.prototype.runCoreEditingCommand = function (editor, cursors, args) { editor.pushUndoStop(); editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.tab(cursors.context.config, cursors.context.model, cursors.getAll().map(function (s) { return s.modelState.selection; }))); editor.pushUndoStop(); }; return class_21; }(CoreEditingCommand))); CoreEditingCommands.DeleteLeft = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_22, _super); function class_22() { return _super.call(this, { id: 'deleteLeft', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 1 /* Backspace */, secondary: [1024 /* Shift */ | 1 /* Backspace */], mac: { primary: 1 /* Backspace */, secondary: [1024 /* Shift */ | 1 /* Backspace */, 256 /* WinCtrl */ | 38 /* KEY_H */, 256 /* WinCtrl */ | 1 /* Backspace */] } } }) || this; } class_22.prototype.runCoreEditingCommand = function (editor, cursors, args) { var _a = cursorDeleteOperations_1.DeleteOperations.deleteLeft(cursors.getPrevEditOperationType(), cursors.context.config, cursors.context.model, cursors.getAll().map(function (s) { return s.modelState.selection; })), shouldPushStackElementBefore = _a[0], commands = _a[1]; if (shouldPushStackElementBefore) { editor.pushUndoStop(); } editor.executeCommands(this.id, commands); cursors.setPrevEditOperationType(2 /* DeletingLeft */); }; return class_22; }(CoreEditingCommand))); CoreEditingCommands.DeleteRight = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_23, _super); function class_23() { return _super.call(this, { id: 'deleteRight', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 20 /* Delete */, mac: { primary: 20 /* Delete */, secondary: [256 /* WinCtrl */ | 34 /* KEY_D */, 256 /* WinCtrl */ | 20 /* Delete */] } } }) || this; } class_23.prototype.runCoreEditingCommand = function (editor, cursors, args) { var _a = cursorDeleteOperations_1.DeleteOperations.deleteRight(cursors.getPrevEditOperationType(), cursors.context.config, cursors.context.model, cursors.getAll().map(function (s) { return s.modelState.selection; })), shouldPushStackElementBefore = _a[0], commands = _a[1]; if (shouldPushStackElementBefore) { editor.pushUndoStop(); } editor.executeCommands(this.id, commands); cursors.setPrevEditOperationType(3 /* DeletingRight */); }; return class_23; }(CoreEditingCommand))); })(CoreEditingCommands = exports.CoreEditingCommands || (exports.CoreEditingCommands = {})); function registerCommand(command) { command.register(); } /** * A command that will: * 1. invoke a command on the focused editor. * 2. otherwise, invoke a browser built-in command on the `activeElement`. * 3. otherwise, invoke a command on the workbench active editor. */ var EditorOrNativeTextInputCommand = /** @class */ (function (_super) { __extends(EditorOrNativeTextInputCommand, _super); function EditorOrNativeTextInputCommand(opts) { var _this = _super.call(this, opts) || this; _this._editorHandler = opts.editorHandler; _this._inputHandler = opts.inputHandler; return _this; } EditorOrNativeTextInputCommand.prototype.runCommand = function (accessor, args) { var focusedEditor = accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor(); // Only if editor text focus (i.e. not if editor has widget focus). if (focusedEditor && focusedEditor.hasTextFocus()) { return this._runEditorHandler(accessor, focusedEditor, args); } // Ignore this action when user is focused on an element that allows for entering text var activeElement = document.activeElement; if (activeElement && ['input', 'textarea'].indexOf(activeElement.tagName.toLowerCase()) >= 0) { document.execCommand(this._inputHandler); return; } // Redirecting to active editor var activeEditor = accessor.get(codeEditorService_1.ICodeEditorService).getActiveCodeEditor(); if (activeEditor) { activeEditor.focus(); return this._runEditorHandler(accessor, activeEditor, args); } }; EditorOrNativeTextInputCommand.prototype._runEditorHandler = function (accessor, editor, args) { var HANDLER = this._editorHandler; if (typeof HANDLER === 'string') { editor.trigger('keyboard', HANDLER, args); } else { args = args || {}; args.source = 'keyboard'; HANDLER.runEditorCommand(accessor, editor, args); } }; return EditorOrNativeTextInputCommand; }(editorExtensions_1.Command)); /** * A command that will invoke a command on the focused editor. */ var EditorHandlerCommand = /** @class */ (function (_super) { __extends(EditorHandlerCommand, _super); function EditorHandlerCommand(id, handlerId, description) { var _this = _super.call(this, { id: id, precondition: undefined, description: description }) || this; _this._handlerId = handlerId; return _this; } EditorHandlerCommand.prototype.runCommand = function (accessor, args) { var editor = accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor(); if (!editor) { return; } editor.trigger('keyboard', this._handlerId, args); }; return EditorHandlerCommand; }(editorExtensions_1.Command)); registerCommand(new EditorOrNativeTextInputCommand({ editorHandler: CoreNavigationCommands.SelectAll, inputHandler: 'selectAll', id: 'editor.action.selectAll', precondition: editorContextKeys_1.EditorContextKeys.textInputFocus, kbOpts: { weight: CORE_WEIGHT, kbExpr: null, primary: 2048 /* CtrlCmd */ | 31 /* KEY_A */ }, menuOpts: { menuId: 25 /* MenubarSelectionMenu */, group: '1_basic', title: nls.localize(0, null), order: 1 } })); registerCommand(new EditorOrNativeTextInputCommand({ editorHandler: editorCommon_1.Handler.Undo, inputHandler: 'undo', id: editorCommon_1.Handler.Undo, precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 56 /* KEY_Z */ }, menuOpts: { menuId: 17 /* MenubarEditMenu */, group: '1_do', title: nls.localize(1, null), order: 1 } })); registerCommand(new EditorHandlerCommand('default:' + editorCommon_1.Handler.Undo, editorCommon_1.Handler.Undo)); registerCommand(new EditorOrNativeTextInputCommand({ editorHandler: editorCommon_1.Handler.Redo, inputHandler: 'redo', id: editorCommon_1.Handler.Redo, precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { weight: CORE_WEIGHT, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 55 /* KEY_Y */, secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 56 /* KEY_Z */], mac: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 56 /* KEY_Z */ } }, menuOpts: { menuId: 17 /* MenubarEditMenu */, group: '1_do', title: nls.localize(2, null), order: 2 } })); registerCommand(new EditorHandlerCommand('default:' + editorCommon_1.Handler.Redo, editorCommon_1.Handler.Redo)); function registerOverwritableCommand(handlerId, description) { registerCommand(new EditorHandlerCommand('default:' + handlerId, handlerId)); registerCommand(new EditorHandlerCommand(handlerId, handlerId, description)); } registerOverwritableCommand(editorCommon_1.Handler.Type, { description: "Type", args: [{ name: 'args', schema: { 'type': 'object', 'required': ['text'], 'properties': { 'text': { 'type': 'string' } }, } }] }); registerOverwritableCommand(editorCommon_1.Handler.ReplacePreviousChar); registerOverwritableCommand(editorCommon_1.Handler.CompositionStart); registerOverwritableCommand(editorCommon_1.Handler.CompositionEnd); registerOverwritableCommand(editorCommon_1.Handler.Paste); registerOverwritableCommand(editorCommon_1.Handler.Cut); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[522/*vs/editor/browser/core/keybindingCancellation*/], __M([0/*require*/,1/*exports*/,12/*vs/editor/browser/editorExtensions*/,18/*vs/platform/contextkey/common/contextkey*/,26/*vs/base/common/cancellation*/,76/*vs/base/common/linkedList*/,11/*vs/platform/instantiation/common/instantiation*/,83/*vs/platform/instantiation/common/extensions*/]), function (require, exports, editorExtensions_1, contextkey_1, cancellation_1, linkedList_1, instantiation_1, extensions_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var IEditorCancellationTokens = instantiation_1.createDecorator('IEditorCancelService'); var ctxCancellableOperation = new contextkey_1.RawContextKey('cancellableOperation', false); extensions_1.registerSingleton(IEditorCancellationTokens, /** @class */ (function () { function class_1() { this._tokens = new WeakMap(); } class_1.prototype.add = function (editor, cts) { var data = this._tokens.get(editor); if (!data) { data = editor.invokeWithinContext(function (accessor) { var key = ctxCancellableOperation.bindTo(accessor.get(contextkey_1.IContextKeyService)); var tokens = new linkedList_1.LinkedList(); return { key: key, tokens: tokens }; }); this._tokens.set(editor, data); } var removeFn; data.key.set(true); removeFn = data.tokens.push(cts); return function () { // remove w/o cancellation if (removeFn) { removeFn(); data.key.set(!data.tokens.isEmpty()); removeFn = undefined; } }; }; class_1.prototype.cancel = function (editor) { var data = this._tokens.get(editor); if (!data) { return; } // remove with cancellation var cts = data.tokens.pop(); if (cts) { cts.cancel(); data.key.set(!data.tokens.isEmpty()); } }; return class_1; }()), true); var EditorKeybindingCancellationTokenSource = /** @class */ (function (_super) { __extends(EditorKeybindingCancellationTokenSource, _super); function EditorKeybindingCancellationTokenSource(editor, parent) { var _this = _super.call(this, parent) || this; _this.editor = editor; _this._unregister = editor.invokeWithinContext(function (accessor) { return accessor.get(IEditorCancellationTokens).add(editor, _this); }); return _this; } EditorKeybindingCancellationTokenSource.prototype.dispose = function () { this._unregister(); _super.prototype.dispose.call(this); }; return EditorKeybindingCancellationTokenSource; }(cancellation_1.CancellationTokenSource)); exports.EditorKeybindingCancellationTokenSource = EditorKeybindingCancellationTokenSource; editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_2, _super); function class_2() { return _super.call(this, { id: 'editor.cancelOperation', kbOpts: { weight: 100 /* EditorContrib */, primary: 9 /* Escape */ }, precondition: ctxCancellableOperation }) || this; } class_2.prototype.runEditorCommand = function (accessor, editor) { accessor.get(IEditorCancellationTokens).cancel(editor); }; return class_2; }(editorExtensions_1.EditorCommand))); }); /*--------------------------------------------------------------------------------------------- * 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/editor/browser/core/editorState*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,26/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,522/*vs/editor/browser/core/keybindingCancellation*/]), function (require, exports, strings, cancellation_1, lifecycle_1, keybindingCancellation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var EditorState = /** @class */ (function () { function EditorState(editor, flags) { this.flags = flags; if ((this.flags & 1 /* Value */) !== 0) { var model = editor.getModel(); this.modelVersionId = model ? strings.format('{0}#{1}', model.uri.toString(), model.getVersionId()) : null; } else { this.modelVersionId = null; } if ((this.flags & 4 /* Position */) !== 0) { this.position = editor.getPosition(); } else { this.position = null; } if ((this.flags & 2 /* Selection */) !== 0) { this.selection = editor.getSelection(); } else { this.selection = null; } if ((this.flags & 8 /* Scroll */) !== 0) { this.scrollLeft = editor.getScrollLeft(); this.scrollTop = editor.getScrollTop(); } else { this.scrollLeft = -1; this.scrollTop = -1; } } EditorState.prototype._equals = function (other) { if (!(other instanceof EditorState)) { return false; } var state = other; if (this.modelVersionId !== state.modelVersionId) { return false; } if (this.scrollLeft !== state.scrollLeft || this.scrollTop !== state.scrollTop) { return false; } if (!this.position && state.position || this.position && !state.position || this.position && state.position && !this.position.equals(state.position)) { return false; } if (!this.selection && state.selection || this.selection && !state.selection || this.selection && state.selection && !this.selection.equalsRange(state.selection)) { return false; } return true; }; EditorState.prototype.validate = function (editor) { return this._equals(new EditorState(editor, this.flags)); }; return EditorState; }()); exports.EditorState = EditorState; /** * A cancellation token source that cancels when the editor changes as expressed * by the provided flags */ var EditorStateCancellationTokenSource = /** @class */ (function (_super) { __extends(EditorStateCancellationTokenSource, _super); function EditorStateCancellationTokenSource(editor, flags, parent) { var _this = _super.call(this, editor, parent) || this; _this.editor = editor; _this._listener = new lifecycle_1.DisposableStore(); if (flags & 4 /* Position */) { _this._listener.add(editor.onDidChangeCursorPosition(function (_) { return _this.cancel(); })); } if (flags & 2 /* Selection */) { _this._listener.add(editor.onDidChangeCursorSelection(function (_) { return _this.cancel(); })); } if (flags & 8 /* Scroll */) { _this._listener.add(editor.onDidScrollChange(function (_) { return _this.cancel(); })); } if (flags & 1 /* Value */) { _this._listener.add(editor.onDidChangeModel(function (_) { return _this.cancel(); })); _this._listener.add(editor.onDidChangeModelContent(function (_) { return _this.cancel(); })); } return _this; } EditorStateCancellationTokenSource.prototype.dispose = function () { this._listener.dispose(); _super.prototype.dispose.call(this); }; return EditorStateCancellationTokenSource; }(keybindingCancellation_1.EditorKeybindingCancellationTokenSource)); exports.EditorStateCancellationTokenSource = EditorStateCancellationTokenSource; /** * A cancellation token source that cancels when the provided model changes */ var TextModelCancellationTokenSource = /** @class */ (function (_super) { __extends(TextModelCancellationTokenSource, _super); function TextModelCancellationTokenSource(model, parent) { var _this = _super.call(this, parent) || this; _this._listener = model.onDidChangeContent(function () { return _this.cancel(); }); return _this; } TextModelCancellationTokenSource.prototype.dispose = function () { this._listener.dispose(); _super.prototype.dispose.call(this); }; return TextModelCancellationTokenSource; }(cancellation_1.CancellationTokenSource)); exports.TextModelCancellationTokenSource = TextModelCancellationTokenSource; var StableEditorScrollState = /** @class */ (function () { function StableEditorScrollState(_visiblePosition, _visiblePositionScrollDelta) { this._visiblePosition = _visiblePosition; this._visiblePositionScrollDelta = _visiblePositionScrollDelta; } StableEditorScrollState.capture = function (editor) { var visiblePosition = null; var visiblePositionScrollDelta = 0; if (editor.getScrollTop() !== 0) { var visibleRanges = editor.getVisibleRanges(); if (visibleRanges.length > 0) { visiblePosition = visibleRanges[0].getStartPosition(); var visiblePositionScrollTop = editor.getTopForPosition(visiblePosition.lineNumber, visiblePosition.column); visiblePositionScrollDelta = editor.getScrollTop() - visiblePositionScrollTop; } } return new StableEditorScrollState(visiblePosition, visiblePositionScrollDelta); }; StableEditorScrollState.prototype.restore = function (editor) { if (this._visiblePosition) { var visiblePositionScrollTop = editor.getTopForPosition(this._visiblePosition.lineNumber, this._visiblePosition.column); editor.setScrollTop(visiblePositionScrollTop + this._visiblePositionScrollDelta); } }; return StableEditorScrollState; }()); 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[523/*vs/editor/browser/view/viewController*/], __M([0/*require*/,1/*exports*/,164/*vs/editor/browser/controller/coreCommands*/,13/*vs/editor/common/core/position*/,16/*vs/base/common/platform*/]), function (require, exports, coreCommands_1, position_1, platform) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ViewController = /** @class */ (function () { function ViewController(configuration, viewModel, outgoingEvents, commandDelegate) { this.configuration = configuration; this.viewModel = viewModel; this.outgoingEvents = outgoingEvents; this.commandDelegate = commandDelegate; } ViewController.prototype._execMouseCommand = function (editorCommand, args) { args.source = 'mouse'; this.commandDelegate.executeEditorCommand(editorCommand, args); }; ViewController.prototype.paste = function (source, text, pasteOnNewLine, multicursorText, mode) { this.commandDelegate.paste(source, text, pasteOnNewLine, multicursorText, mode); }; ViewController.prototype.type = function (source, text) { this.commandDelegate.type(source, text); }; ViewController.prototype.replacePreviousChar = function (source, text, replaceCharCnt) { this.commandDelegate.replacePreviousChar(source, text, replaceCharCnt); }; ViewController.prototype.compositionStart = function (source) { this.commandDelegate.compositionStart(source); }; ViewController.prototype.compositionEnd = function (source) { this.commandDelegate.compositionEnd(source); }; ViewController.prototype.cut = function (source) { this.commandDelegate.cut(source); }; ViewController.prototype.setSelection = function (source, modelSelection) { this.commandDelegate.executeEditorCommand(coreCommands_1.CoreNavigationCommands.SetSelection, { source: source, selection: modelSelection }); }; ViewController.prototype._validateViewColumn = function (viewPosition) { var minColumn = this.viewModel.getLineMinColumn(viewPosition.lineNumber); if (viewPosition.column < minColumn) { return new position_1.Position(viewPosition.lineNumber, minColumn); } return viewPosition; }; ViewController.prototype._hasMulticursorModifier = function (data) { switch (this.configuration.options.get(59 /* multiCursorModifier */)) { case 'altKey': return data.altKey; case 'ctrlKey': return data.ctrlKey; case 'metaKey': return data.metaKey; } return false; }; ViewController.prototype._hasNonMulticursorModifier = function (data) { switch (this.configuration.options.get(59 /* multiCursorModifier */)) { case 'altKey': return data.ctrlKey || data.metaKey; case 'ctrlKey': return data.altKey || data.metaKey; case 'metaKey': return data.ctrlKey || data.altKey; } return false; }; ViewController.prototype.dispatchMouse = function (data) { var selectionClipboardIsOn = (platform.isLinux && this.configuration.options.get(81 /* selectionClipboard */)); if (data.middleButton && !selectionClipboardIsOn) { this._columnSelect(data.position, data.mouseColumn, data.inSelectionMode); } else if (data.startedOnLineNumbers) { // If the dragging started on the gutter, then have operations work on the entire line if (this._hasMulticursorModifier(data)) { if (data.inSelectionMode) { this._lastCursorLineSelect(data.position); } else { this._createCursor(data.position, true); } } else { if (data.inSelectionMode) { this._lineSelectDrag(data.position); } else { this._lineSelect(data.position); } } } else if (data.mouseDownCount >= 4) { this._selectAll(); } else if (data.mouseDownCount === 3) { if (this._hasMulticursorModifier(data)) { if (data.inSelectionMode) { this._lastCursorLineSelectDrag(data.position); } else { this._lastCursorLineSelect(data.position); } } else { if (data.inSelectionMode) { this._lineSelectDrag(data.position); } else { this._lineSelect(data.position); } } } else if (data.mouseDownCount === 2) { if (this._hasMulticursorModifier(data)) { this._lastCursorWordSelect(data.position); } else { if (data.inSelectionMode) { this._wordSelectDrag(data.position); } else { this._wordSelect(data.position); } } } else { if (this._hasMulticursorModifier(data)) { if (!this._hasNonMulticursorModifier(data)) { if (data.shiftKey) { this._columnSelect(data.position, data.mouseColumn, true); } else { // Do multi-cursor operations only when purely alt is pressed if (data.inSelectionMode) { this._lastCursorMoveToSelect(data.position); } else { this._createCursor(data.position, false); } } } } else { if (data.inSelectionMode) { if (data.altKey) { this._columnSelect(data.position, data.mouseColumn, true); } else { this._moveToSelect(data.position); } } else { this.moveTo(data.position); } } } }; ViewController.prototype._usualArgs = function (viewPosition) { viewPosition = this._validateViewColumn(viewPosition); return { position: this._convertViewToModelPosition(viewPosition), viewPosition: viewPosition }; }; ViewController.prototype.moveTo = function (viewPosition) { this._execMouseCommand(coreCommands_1.CoreNavigationCommands.MoveTo, this._usualArgs(viewPosition)); }; ViewController.prototype._moveToSelect = function (viewPosition) { this._execMouseCommand(coreCommands_1.CoreNavigationCommands.MoveToSelect, this._usualArgs(viewPosition)); }; ViewController.prototype._columnSelect = function (viewPosition, mouseColumn, doColumnSelect) { viewPosition = this._validateViewColumn(viewPosition); this._execMouseCommand(coreCommands_1.CoreNavigationCommands.ColumnSelect, { position: this._convertViewToModelPosition(viewPosition), viewPosition: viewPosition, mouseColumn: mouseColumn, doColumnSelect: doColumnSelect }); }; ViewController.prototype._createCursor = function (viewPosition, wholeLine) { viewPosition = this._validateViewColumn(viewPosition); this._execMouseCommand(coreCommands_1.CoreNavigationCommands.CreateCursor, { position: this._convertViewToModelPosition(viewPosition), viewPosition: viewPosition, wholeLine: wholeLine }); }; ViewController.prototype._lastCursorMoveToSelect = function (viewPosition) { this._execMouseCommand(coreCommands_1.CoreNavigationCommands.LastCursorMoveToSelect, this._usualArgs(viewPosition)); }; ViewController.prototype._wordSelect = function (viewPosition) { this._execMouseCommand(coreCommands_1.CoreNavigationCommands.WordSelect, this._usualArgs(viewPosition)); }; ViewController.prototype._wordSelectDrag = function (viewPosition) { this._execMouseCommand(coreCommands_1.CoreNavigationCommands.WordSelectDrag, this._usualArgs(viewPosition)); }; ViewController.prototype._lastCursorWordSelect = function (viewPosition) { this._execMouseCommand(coreCommands_1.CoreNavigationCommands.LastCursorWordSelect, this._usualArgs(viewPosition)); }; ViewController.prototype._lineSelect = function (viewPosition) { this._execMouseCommand(coreCommands_1.CoreNavigationCommands.LineSelect, this._usualArgs(viewPosition)); }; ViewController.prototype._lineSelectDrag = function (viewPosition) { this._execMouseCommand(coreCommands_1.CoreNavigationCommands.LineSelectDrag, this._usualArgs(viewPosition)); }; ViewController.prototype._lastCursorLineSelect = function (viewPosition) { this._execMouseCommand(coreCommands_1.CoreNavigationCommands.LastCursorLineSelect, this._usualArgs(viewPosition)); }; ViewController.prototype._lastCursorLineSelectDrag = function (viewPosition) { this._execMouseCommand(coreCommands_1.CoreNavigationCommands.LastCursorLineSelectDrag, this._usualArgs(viewPosition)); }; ViewController.prototype._selectAll = function () { this._execMouseCommand(coreCommands_1.CoreNavigationCommands.SelectAll, {}); }; // ---------------------- ViewController.prototype._convertViewToModelPosition = function (viewPosition) { return this.viewModel.coordinatesConverter.convertViewPositionToModelPosition(viewPosition); }; ViewController.prototype.emitKeyDown = function (e) { this.outgoingEvents.emitKeyDown(e); }; ViewController.prototype.emitKeyUp = function (e) { this.outgoingEvents.emitKeyUp(e); }; ViewController.prototype.emitContextMenu = function (e) { this.outgoingEvents.emitContextMenu(e); }; ViewController.prototype.emitMouseMove = function (e) { this.outgoingEvents.emitMouseMove(e); }; ViewController.prototype.emitMouseLeave = function (e) { this.outgoingEvents.emitMouseLeave(e); }; ViewController.prototype.emitMouseUp = function (e) { this.outgoingEvents.emitMouseUp(e); }; ViewController.prototype.emitMouseDown = function (e) { this.outgoingEvents.emitMouseDown(e); }; ViewController.prototype.emitMouseDrag = function (e) { this.outgoingEvents.emitMouseDrag(e); }; ViewController.prototype.emitMouseDrop = function (e) { this.outgoingEvents.emitMouseDrop(e); }; ViewController.prototype.emitMouseWheel = function (e) { this.outgoingEvents.emitMouseWheel(e); }; return ViewController; }()); exports.ViewController = ViewController; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[524/*vs/editor/contrib/caretOperations/caretOperations*/], __M([0/*require*/,1/*exports*/,429/*vs/nls!vs/editor/contrib/caretOperations/caretOperations*/,12/*vs/editor/browser/editorExtensions*/,23/*vs/editor/common/editorContextKeys*/,374/*vs/editor/contrib/caretOperations/moveCaretCommand*/]), function (require, exports, nls, editorExtensions_1, editorContextKeys_1, moveCaretCommand_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MoveCaretAction = /** @class */ (function (_super) { __extends(MoveCaretAction, _super); function MoveCaretAction(left, opts) { var _this = _super.call(this, opts) || this; _this.left = left; return _this; } MoveCaretAction.prototype.run = function (accessor, editor) { if (!editor.hasModel()) { return; } var commands = []; var selections = editor.getSelections(); for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) { var selection = selections_1[_i]; commands.push(new moveCaretCommand_1.MoveCaretCommand(selection, this.left)); } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); }; return MoveCaretAction; }(editorExtensions_1.EditorAction)); var MoveCaretLeftAction = /** @class */ (function (_super) { __extends(MoveCaretLeftAction, _super); function MoveCaretLeftAction() { return _super.call(this, true, { id: 'editor.action.moveCarretLeftAction', label: nls.localize(0, null), alias: 'Move Caret Left', precondition: editorContextKeys_1.EditorContextKeys.writable }) || this; } return MoveCaretLeftAction; }(MoveCaretAction)); var MoveCaretRightAction = /** @class */ (function (_super) { __extends(MoveCaretRightAction, _super); function MoveCaretRightAction() { return _super.call(this, false, { id: 'editor.action.moveCarretRightAction', label: nls.localize(1, null), alias: 'Move Caret Right', precondition: editorContextKeys_1.EditorContextKeys.writable }) || this; } return MoveCaretRightAction; }(MoveCaretAction)); editorExtensions_1.registerEditorAction(MoveCaretLeftAction); editorExtensions_1.registerEditorAction(MoveCaretRightAction); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[525/*vs/editor/contrib/caretOperations/transpose*/], __M([0/*require*/,1/*exports*/,430/*vs/nls!vs/editor/contrib/caretOperations/transpose*/,12/*vs/editor/browser/editorExtensions*/,80/*vs/editor/common/commands/replaceCommand*/,3/*vs/editor/common/core/range*/,23/*vs/editor/common/editorContextKeys*/,158/*vs/editor/common/controller/cursorMoveOperations*/]), function (require, exports, nls, editorExtensions_1, replaceCommand_1, range_1, editorContextKeys_1, cursorMoveOperations_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var TransposeLettersAction = /** @class */ (function (_super) { __extends(TransposeLettersAction, _super); function TransposeLettersAction() { return _super.call(this, { id: 'editor.action.transposeLetters', label: nls.localize(0, null), alias: 'Transpose Letters', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 /* WinCtrl */ | 50 /* KEY_T */ }, weight: 100 /* EditorContrib */ } }) || this; } TransposeLettersAction.prototype.run = function (accessor, editor) { if (!editor.hasModel()) { return; } var model = editor.getModel(); var commands = []; var selections = editor.getSelections(); for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) { var selection = selections_1[_i]; if (!selection.isEmpty()) { continue; } var lineNumber = selection.startLineNumber; var column = selection.startColumn; var lastColumn = model.getLineMaxColumn(lineNumber); if (lineNumber === 1 && (column === 1 || (column === 2 && lastColumn === 2))) { // at beginning of file, nothing to do continue; } // handle special case: when at end of line, transpose left two chars // otherwise, transpose left and right chars var endPosition = (column === lastColumn) ? selection.getPosition() : cursorMoveOperations_1.MoveOperations.rightPosition(model, selection.getPosition().lineNumber, selection.getPosition().column); var middlePosition = cursorMoveOperations_1.MoveOperations.leftPosition(model, endPosition.lineNumber, endPosition.column); var beginPosition = cursorMoveOperations_1.MoveOperations.leftPosition(model, middlePosition.lineNumber, middlePosition.column); var leftChar = model.getValueInRange(range_1.Range.fromPositions(beginPosition, middlePosition)); var rightChar = model.getValueInRange(range_1.Range.fromPositions(middlePosition, endPosition)); var replaceRange = range_1.Range.fromPositions(beginPosition, endPosition); commands.push(new replaceCommand_1.ReplaceCommand(replaceRange, rightChar + leftChar)); } if (commands.length > 0) { editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); } }; return TransposeLettersAction; }(editorExtensions_1.EditorAction)); editorExtensions_1.registerEditorAction(TransposeLettersAction); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[526/*vs/editor/contrib/clipboard/clipboard*/], __M([0/*require*/,1/*exports*/,431/*vs/nls!vs/editor/contrib/clipboard/clipboard*/,24/*vs/base/browser/browser*/,16/*vs/base/common/platform*/,189/*vs/editor/browser/controller/textAreaInput*/,12/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,23/*vs/editor/common/editorContextKeys*/,303/*vs/css!vs/editor/contrib/clipboard/clipboard*/]), function (require, exports, nls, browser, platform, textAreaInput_1, editorExtensions_1, codeEditorService_1, editorContextKeys_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CLIPBOARD_CONTEXT_MENU_GROUP = '9_cutcopypaste'; var supportsCut = (platform.isNative || document.queryCommandSupported('cut')); var supportsCopy = (platform.isNative || document.queryCommandSupported('copy')); // IE and Edge have trouble with setting html content in clipboard var supportsCopyWithSyntaxHighlighting = (supportsCopy && !browser.isEdgeOrIE); // Chrome incorrectly returns true for document.queryCommandSupported('paste') // when the paste feature is available but the calling script has insufficient // privileges to actually perform the action var supportsPaste = (platform.isNative || (!browser.isChrome && document.queryCommandSupported('paste'))); var ExecCommandAction = /** @class */ (function (_super) { __extends(ExecCommandAction, _super); function ExecCommandAction(browserCommand, opts) { var _this = _super.call(this, opts) || this; _this.browserCommand = browserCommand; return _this; } ExecCommandAction.prototype.runCommand = function (accessor, args) { var focusedEditor = accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor(); // Only if editor text focus (i.e. not if editor has widget focus). if (focusedEditor && focusedEditor.hasTextFocus()) { focusedEditor.trigger('keyboard', this.id, args); return; } document.execCommand(this.browserCommand); }; ExecCommandAction.prototype.run = function (accessor, editor) { editor.focus(); document.execCommand(this.browserCommand); }; return ExecCommandAction; }(editorExtensions_1.EditorAction)); var ExecCommandCutAction = /** @class */ (function (_super) { __extends(ExecCommandCutAction, _super); function ExecCommandCutAction() { var _this = this; var kbOpts = { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 54 /* KEY_X */, win: { primary: 2048 /* CtrlCmd */ | 54 /* KEY_X */, secondary: [1024 /* Shift */ | 20 /* Delete */] }, weight: 100 /* EditorContrib */ }; // Do not bind cut keybindings in the browser, // since browsers do that for us and it avoids security prompts if (!platform.isNative) { kbOpts = undefined; } _this = _super.call(this, 'cut', { id: 'editor.action.clipboardCutAction', label: nls.localize(0, null), alias: 'Cut', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: kbOpts, contextMenuOpts: { group: CLIPBOARD_CONTEXT_MENU_GROUP, order: 1 }, menuOpts: { menuId: 17 /* MenubarEditMenu */, group: '2_ccp', title: nls.localize(1, null), order: 1 } }) || this; return _this; } ExecCommandCutAction.prototype.run = function (accessor, editor) { if (!editor.hasModel()) { return; } var emptySelectionClipboard = editor.getOption(25 /* emptySelectionClipboard */); if (!emptySelectionClipboard && editor.getSelection().isEmpty()) { return; } _super.prototype.run.call(this, accessor, editor); }; return ExecCommandCutAction; }(ExecCommandAction)); var ExecCommandCopyAction = /** @class */ (function (_super) { __extends(ExecCommandCopyAction, _super); function ExecCommandCopyAction() { var _this = this; var kbOpts = { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 33 /* KEY_C */, win: { primary: 2048 /* CtrlCmd */ | 33 /* KEY_C */, secondary: [2048 /* CtrlCmd */ | 19 /* Insert */] }, weight: 100 /* EditorContrib */ }; // Do not bind copy keybindings in the browser, // since browsers do that for us and it avoids security prompts if (!platform.isNative) { kbOpts = undefined; } _this = _super.call(this, 'copy', { id: 'editor.action.clipboardCopyAction', label: nls.localize(2, null), alias: 'Copy', precondition: undefined, kbOpts: kbOpts, contextMenuOpts: { group: CLIPBOARD_CONTEXT_MENU_GROUP, order: 2 }, menuOpts: { menuId: 17 /* MenubarEditMenu */, group: '2_ccp', title: nls.localize(3, null), order: 2 } }) || this; return _this; } ExecCommandCopyAction.prototype.run = function (accessor, editor) { if (!editor.hasModel()) { return; } var emptySelectionClipboard = editor.getOption(25 /* emptySelectionClipboard */); if (!emptySelectionClipboard && editor.getSelection().isEmpty()) { return; } _super.prototype.run.call(this, accessor, editor); }; return ExecCommandCopyAction; }(ExecCommandAction)); var ExecCommandPasteAction = /** @class */ (function (_super) { __extends(ExecCommandPasteAction, _super); function ExecCommandPasteAction() { var _this = this; var kbOpts = { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 52 /* KEY_V */, win: { primary: 2048 /* CtrlCmd */ | 52 /* KEY_V */, secondary: [1024 /* Shift */ | 19 /* Insert */] }, weight: 100 /* EditorContrib */ }; // Do not bind paste keybindings in the browser, // since browsers do that for us and it avoids security prompts if (!platform.isNative) { kbOpts = undefined; } _this = _super.call(this, 'paste', { id: 'editor.action.clipboardPasteAction', label: nls.localize(4, null), alias: 'Paste', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: kbOpts, contextMenuOpts: { group: CLIPBOARD_CONTEXT_MENU_GROUP, order: 3 }, menuOpts: { menuId: 17 /* MenubarEditMenu */, group: '2_ccp', title: nls.localize(5, null), order: 3 } }) || this; return _this; } return ExecCommandPasteAction; }(ExecCommandAction)); var ExecCommandCopyWithSyntaxHighlightingAction = /** @class */ (function (_super) { __extends(ExecCommandCopyWithSyntaxHighlightingAction, _super); function ExecCommandCopyWithSyntaxHighlightingAction() { return _super.call(this, 'copy', { id: 'editor.action.clipboardCopyWithSyntaxHighlightingAction', label: nls.localize(6, null), alias: 'Copy With Syntax Highlighting', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 0, weight: 100 /* EditorContrib */ } }) || this; } ExecCommandCopyWithSyntaxHighlightingAction.prototype.run = function (accessor, editor) { if (!editor.hasModel()) { return; } var emptySelectionClipboard = editor.getOption(25 /* emptySelectionClipboard */); if (!emptySelectionClipboard && editor.getSelection().isEmpty()) { return; } textAreaInput_1.CopyOptions.forceCopyWithSyntaxHighlighting = true; _super.prototype.run.call(this, accessor, editor); textAreaInput_1.CopyOptions.forceCopyWithSyntaxHighlighting = false; }; return ExecCommandCopyWithSyntaxHighlightingAction; }(ExecCommandAction)); if (supportsCut) { editorExtensions_1.registerEditorAction(ExecCommandCutAction); } if (supportsCopy) { editorExtensions_1.registerEditorAction(ExecCommandCopyAction); } if (supportsPaste) { editorExtensions_1.registerEditorAction(ExecCommandPasteAction); } if (supportsCopyWithSyntaxHighlighting) { editorExtensions_1.registerEditorAction(ExecCommandCopyWithSyntaxHighlightingAction); } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[119/*vs/editor/contrib/codeAction/codeAction*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,26/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,25/*vs/base/common/uri*/,67/*vs/editor/browser/core/editorState*/,12/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,17/*vs/editor/common/modes*/,49/*vs/editor/common/services/modelService*/,111/*vs/editor/contrib/codeAction/types*/]), function (require, exports, arrays_1, cancellation_1, errors_1, lifecycle_1, uri_1, editorState_1, editorExtensions_1, range_1, selection_1, modes, modelService_1, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.codeActionCommandId = 'editor.action.codeAction'; exports.refactorCommandId = 'editor.action.refactor'; exports.sourceActionCommandId = 'editor.action.sourceAction'; exports.organizeImportsCommandId = 'editor.action.organizeImports'; exports.fixAllCommandId = 'editor.action.fixAll'; var ManagedCodeActionSet = /** @class */ (function (_super) { __extends(ManagedCodeActionSet, _super); function ManagedCodeActionSet(actions, disposables) { var _this = _super.call(this) || this; _this._register(disposables); _this.allActions = arrays_1.mergeSort(__spreadArrays(actions), ManagedCodeActionSet.codeActionsComparator); _this.validActions = _this.allActions.filter(function (action) { return !action.disabled; }); return _this; } ManagedCodeActionSet.codeActionsComparator = function (a, b) { if (arrays_1.isNonEmptyArray(a.diagnostics)) { if (arrays_1.isNonEmptyArray(b.diagnostics)) { return a.diagnostics[0].message.localeCompare(b.diagnostics[0].message); } else { return -1; } } else if (arrays_1.isNonEmptyArray(b.diagnostics)) { return 1; } else { return 0; // both have no diagnostics } }; Object.defineProperty(ManagedCodeActionSet.prototype, "hasAutoFix", { get: function () { return this.validActions.some(function (fix) { return !!fix.kind && types_1.CodeActionKind.QuickFix.contains(new types_1.CodeActionKind(fix.kind)) && !!fix.isPreferred; }); }, enumerable: true, configurable: true }); return ManagedCodeActionSet; }(lifecycle_1.Disposable)); function getCodeActions(model, rangeOrSelection, trigger, token) { var _this = this; var _a; var filter = trigger.filter || {}; var codeActionContext = { only: (_a = filter.include) === null || _a === void 0 ? void 0 : _a.value, trigger: trigger.type, }; var cts = new editorState_1.TextModelCancellationTokenSource(model, token); var providers = getCodeActionProviders(model, filter); var disposables = new lifecycle_1.DisposableStore(); var promises = providers.map(function (provider) { return __awaiter(_this, void 0, void 0, function () { var providedCodeActions, err_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, provider.provideCodeActions(model, rangeOrSelection, codeActionContext, cts.token)]; case 1: providedCodeActions = _a.sent(); if (cts.token.isCancellationRequested || !providedCodeActions) { return [2 /*return*/, []]; } disposables.add(providedCodeActions); return [2 /*return*/, providedCodeActions.actions.filter(function (action) { return action && types_1.filtersAction(filter, action); })]; case 2: err_1 = _a.sent(); if (errors_1.isPromiseCanceledError(err_1)) { throw err_1; } errors_1.onUnexpectedExternalError(err_1); return [2 /*return*/, []]; case 3: return [2 /*return*/]; } }); }); }); var listener = modes.CodeActionProviderRegistry.onDidChange(function () { var newProviders = modes.CodeActionProviderRegistry.all(model); if (!arrays_1.equals(newProviders, providers)) { cts.cancel(); } }); return Promise.all(promises) .then(arrays_1.flatten) .then(function (actions) { return new ManagedCodeActionSet(actions, disposables); }) .finally(function () { listener.dispose(); cts.dispose(); }); } exports.getCodeActions = getCodeActions; function getCodeActionProviders(model, filter) { return modes.CodeActionProviderRegistry.all(model) // Don't include providers that we know will not return code actions of interest .filter(function (provider) { if (!provider.providedCodeActionKinds) { // We don't know what type of actions this provider will return. return true; } return provider.providedCodeActionKinds.some(function (kind) { return types_1.mayIncludeActionsOfKind(filter, new types_1.CodeActionKind(kind)); }); }); } editorExtensions_1.registerLanguageCommand('_executeCodeActionProvider', function (accessor, args) { return __awaiter(this, void 0, void 0, function () { var resource, rangeOrSelection, kind, model, validatedRangeOrSelection, codeActionSet; return __generator(this, function (_a) { switch (_a.label) { case 0: resource = args.resource, rangeOrSelection = args.rangeOrSelection, kind = args.kind; if (!(resource instanceof uri_1.URI)) { throw errors_1.illegalArgument(); } model = accessor.get(modelService_1.IModelService).getModel(resource); if (!model) { throw errors_1.illegalArgument(); } validatedRangeOrSelection = selection_1.Selection.isISelection(rangeOrSelection) ? selection_1.Selection.liftSelection(rangeOrSelection) : range_1.Range.isIRange(rangeOrSelection) ? model.validateRange(rangeOrSelection) : undefined; if (!validatedRangeOrSelection) { throw errors_1.illegalArgument(); } return [4 /*yield*/, getCodeActions(model, validatedRangeOrSelection, { type: 2 /* Manual */, filter: { includeSourceActions: true, include: kind && kind.value ? new types_1.CodeActionKind(kind.value) : undefined } }, cancellation_1.CancellationToken.None)]; case 1: codeActionSet = _a.sent(); setTimeout(function () { return codeActionSet.dispose(); }, 100); return [2 /*return*/, codeActionSet.validActions]; } }); }); }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[527/*vs/editor/contrib/codeAction/codeActionMenu*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,70/*vs/base/browser/ui/actionbar/actionbar*/,55/*vs/base/common/actions*/,10/*vs/base/common/errors*/,128/*vs/base/common/lazy*/,2/*vs/base/common/lifecycle*/,13/*vs/editor/common/core/position*/,17/*vs/editor/common/modes*/,119/*vs/editor/contrib/codeAction/codeAction*/,111/*vs/editor/contrib/codeAction/types*/,66/*vs/platform/contextview/browser/contextView*/,34/*vs/platform/keybinding/common/keybinding*/]), function (require, exports, dom_1, actionbar_1, actions_1, errors_1, lazy_1, lifecycle_1, position_1, modes_1, codeAction_1, types_1, contextView_1, keybinding_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CodeActionAction = /** @class */ (function (_super) { __extends(CodeActionAction, _super); function CodeActionAction(action, callback) { var _this = _super.call(this, action.command ? action.command.id : action.title, action.title, undefined, !action.disabled, callback) || this; _this.action = action; return _this; } return CodeActionAction; }(actions_1.Action)); var CodeActionMenu = /** @class */ (function (_super) { __extends(CodeActionMenu, _super); function CodeActionMenu(_editor, _delegate, _contextMenuService, keybindingService) { var _this = _super.call(this) || this; _this._editor = _editor; _this._delegate = _delegate; _this._contextMenuService = _contextMenuService; _this._visible = false; _this._showingActions = _this._register(new lifecycle_1.MutableDisposable()); _this._keybindingResolver = new CodeActionKeybindingResolver({ getKeybindings: function () { return keybindingService.getKeybindings(); } }); return _this; } Object.defineProperty(CodeActionMenu.prototype, "isVisible", { get: function () { return this._visible; }, enumerable: true, configurable: true }); CodeActionMenu.prototype.show = function (trigger, codeActions, at, options) { return __awaiter(this, void 0, void 0, function () { var actionsToShow, menuActions, anchor, resolver; var _this = this; return __generator(this, function (_a) { actionsToShow = options.includeDisabledActions ? codeActions.allActions : codeActions.validActions; if (!actionsToShow.length) { this._visible = false; return [2 /*return*/]; } if (!this._editor.getDomNode()) { // cancel when editor went off-dom this._visible = false; throw errors_1.canceled(); } this._visible = true; this._showingActions.value = codeActions; menuActions = this.getMenuActions(trigger, actionsToShow); anchor = position_1.Position.isIPosition(at) ? this._toCoords(at) : at || { x: 0, y: 0 }; resolver = this._keybindingResolver.getResolver(); this._contextMenuService.showContextMenu({ getAnchor: function () { return anchor; }, getActions: function () { return menuActions; }, onHide: function () { _this._visible = false; _this._editor.focus(); }, autoSelectFirstItem: true, getKeyBinding: function (action) { return action instanceof CodeActionAction ? resolver(action.action) : undefined; }, }); return [2 /*return*/]; }); }); }; CodeActionMenu.prototype.getMenuActions = function (trigger, actionsToShow) { var _this = this; var _a, _b; var toCodeActionAction = function (action) { return new CodeActionAction(action, function () { return _this._delegate.onSelectCodeAction(action); }); }; var result = actionsToShow .map(toCodeActionAction); var model = this._editor.getModel(); if (model && result.length) { for (var _i = 0, _c = modes_1.CodeActionProviderRegistry.all(model); _i < _c.length; _i++) { var provider = _c[_i]; if (provider._getAdditionalMenuItems) { var items = provider._getAdditionalMenuItems({ trigger: trigger.type, only: (_b = (_a = trigger.filter) === null || _a === void 0 ? void 0 : _a.include) === null || _b === void 0 ? void 0 : _b.value }, actionsToShow); if (items.length) { result.push.apply(result, __spreadArrays([new actionbar_1.Separator()], items.map(function (command) { return toCodeActionAction({ title: command.title, command: command, }); }))); } } } } return result; }; CodeActionMenu.prototype._toCoords = function (position) { if (!this._editor.hasModel()) { return { x: 0, y: 0 }; } this._editor.revealPosition(position, 1 /* Immediate */); this._editor.render(); // Translate to absolute editor position var cursorCoords = this._editor.getScrolledVisiblePosition(position); var editorCoords = dom_1.getDomNodePagePosition(this._editor.getDomNode()); var x = editorCoords.left + cursorCoords.left; var y = editorCoords.top + cursorCoords.top + cursorCoords.height; return { x: x, y: y }; }; CodeActionMenu = __decorate([ __param(2, contextView_1.IContextMenuService), __param(3, keybinding_1.IKeybindingService) ], CodeActionMenu); return CodeActionMenu; }(lifecycle_1.Disposable)); exports.CodeActionMenu = CodeActionMenu; var CodeActionKeybindingResolver = /** @class */ (function () { function CodeActionKeybindingResolver(_keybindingProvider) { this._keybindingProvider = _keybindingProvider; } CodeActionKeybindingResolver.prototype.getResolver = function () { var _this = this; // Lazy since we may not actually ever read the value var allCodeActionBindings = new lazy_1.Lazy(function () { return _this._keybindingProvider.getKeybindings() .filter(function (item) { return CodeActionKeybindingResolver.codeActionCommands.indexOf(item.command) >= 0; }) .filter(function (item) { return item.resolvedKeybinding; }) .map(function (item) { // Special case these commands since they come built-in with VS Code and don't use 'commandArgs' var commandArgs = item.commandArgs; if (item.command === codeAction_1.organizeImportsCommandId) { commandArgs = { kind: types_1.CodeActionKind.SourceOrganizeImports.value }; } else if (item.command === codeAction_1.fixAllCommandId) { commandArgs = { kind: types_1.CodeActionKind.SourceFixAll.value }; } return __assign({ resolvedKeybinding: item.resolvedKeybinding }, types_1.CodeActionCommandArgs.fromUser(commandArgs, { kind: types_1.CodeActionKind.None, apply: "never" /* Never */ })); }); }); return function (action) { if (action.kind) { var binding = _this.bestKeybindingForCodeAction(action, allCodeActionBindings.getValue()); return binding === null || binding === void 0 ? void 0 : binding.resolvedKeybinding; } return undefined; }; }; CodeActionKeybindingResolver.prototype.bestKeybindingForCodeAction = function (action, candidates) { if (!action.kind) { return undefined; } var kind = new types_1.CodeActionKind(action.kind); return candidates .filter(function (candidate) { return candidate.kind.contains(kind); }) .filter(function (candidate) { if (candidate.preferred) { // If the candidate keybinding only applies to preferred actions, the this action must also be preferred return action.isPreferred; } return true; }) .reduceRight(function (currentBest, candidate) { if (!currentBest) { return candidate; } // Select the more specific binding return currentBest.kind.contains(candidate.kind) ? candidate : currentBest; }, undefined); }; CodeActionKeybindingResolver.codeActionCommands = [ codeAction_1.refactorCommandId, codeAction_1.codeActionCommandId, codeAction_1.sourceActionCommandId, codeAction_1.organizeImportsCommandId, codeAction_1.fixAllCommandId ]; return CodeActionKeybindingResolver; }()); exports.CodeActionKeybindingResolver = CodeActionKeybindingResolver; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[528/*vs/editor/contrib/codeAction/codeActionModel*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/,17/*vs/editor/common/modes*/,18/*vs/platform/contextkey/common/contextkey*/,119/*vs/editor/contrib/codeAction/codeAction*/,39/*vs/base/common/resources*/]), function (require, exports, async_1, event_1, lifecycle_1, range_1, modes_1, contextkey_1, codeAction_1, resources_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SUPPORTED_CODE_ACTIONS = new contextkey_1.RawContextKey('supportedCodeAction', ''); var CodeActionOracle = /** @class */ (function (_super) { __extends(CodeActionOracle, _super); function CodeActionOracle(_editor, _markerService, _signalChange, _delay) { if (_delay === void 0) { _delay = 250; } var _this = _super.call(this) || this; _this._editor = _editor; _this._markerService = _markerService; _this._signalChange = _signalChange; _this._delay = _delay; _this._autoTriggerTimer = _this._register(new async_1.TimeoutTimer()); _this._register(_this._markerService.onMarkerChanged(function (e) { return _this._onMarkerChanges(e); })); _this._register(_this._editor.onDidChangeCursorPosition(function () { return _this._onCursorChange(); })); return _this; } CodeActionOracle.prototype.trigger = function (trigger) { var selection = this._getRangeOfSelectionUnlessWhitespaceEnclosed(trigger); return this._createEventAndSignalChange(trigger, selection); }; CodeActionOracle.prototype._onMarkerChanges = function (resources) { var _this = this; var model = this._editor.getModel(); if (!model) { return; } if (resources.some(function (resource) { return resources_1.isEqual(resource, model.uri); })) { this._autoTriggerTimer.cancelAndSet(function () { _this.trigger({ type: 1 /* Auto */ }); }, this._delay); } }; CodeActionOracle.prototype._onCursorChange = function () { var _this = this; this._autoTriggerTimer.cancelAndSet(function () { _this.trigger({ type: 1 /* Auto */ }); }, this._delay); }; CodeActionOracle.prototype._getRangeOfMarker = function (selection) { var model = this._editor.getModel(); if (!model) { return undefined; } for (var _i = 0, _a = this._markerService.read({ resource: model.uri }); _i < _a.length; _i++) { var marker = _a[_i]; var markerRange = model.validateRange(marker); if (range_1.Range.intersectRanges(markerRange, selection)) { return range_1.Range.lift(markerRange); } } return undefined; }; CodeActionOracle.prototype._getRangeOfSelectionUnlessWhitespaceEnclosed = function (trigger) { if (!this._editor.hasModel()) { return undefined; } var model = this._editor.getModel(); var selection = this._editor.getSelection(); if (selection.isEmpty() && trigger.type === 1 /* Auto */) { var _a = selection.getPosition(), lineNumber = _a.lineNumber, column = _a.column; var line = model.getLineContent(lineNumber); if (line.length === 0) { // empty line return undefined; } else if (column === 1) { // look only right if (/\s/.test(line[0])) { return undefined; } } else if (column === model.getLineMaxColumn(lineNumber)) { // look only left if (/\s/.test(line[line.length - 1])) { return undefined; } } else { // look left and right if (/\s/.test(line[column - 2]) && /\s/.test(line[column - 1])) { return undefined; } } } return selection; }; CodeActionOracle.prototype._createEventAndSignalChange = function (trigger, selection) { var model = this._editor.getModel(); if (!selection || !model) { // cancel this._signalChange(undefined); return undefined; } var markerRange = this._getRangeOfMarker(selection); var position = markerRange ? markerRange.getStartPosition() : selection.getStartPosition(); var e = { trigger: trigger, selection: selection, position: position }; this._signalChange(e); return e; }; return CodeActionOracle; }(lifecycle_1.Disposable)); var CodeActionsState; (function (CodeActionsState) { CodeActionsState.Empty = { type: 0 /* Empty */ }; var Triggered = /** @class */ (function () { function Triggered(trigger, rangeOrSelection, position, actions) { this.trigger = trigger; this.rangeOrSelection = rangeOrSelection; this.position = position; this.actions = actions; this.type = 1 /* Triggered */; } return Triggered; }()); CodeActionsState.Triggered = Triggered; })(CodeActionsState = exports.CodeActionsState || (exports.CodeActionsState = {})); var CodeActionModel = /** @class */ (function (_super) { __extends(CodeActionModel, _super); function CodeActionModel(_editor, _markerService, contextKeyService, _progressService) { var _this = _super.call(this) || this; _this._editor = _editor; _this._markerService = _markerService; _this._progressService = _progressService; _this._codeActionOracle = _this._register(new lifecycle_1.MutableDisposable()); _this._state = CodeActionsState.Empty; _this._onDidChangeState = _this._register(new event_1.Emitter()); _this.onDidChangeState = _this._onDidChangeState.event; _this._supportedCodeActions = exports.SUPPORTED_CODE_ACTIONS.bindTo(contextKeyService); _this._register(_this._editor.onDidChangeModel(function () { return _this._update(); })); _this._register(_this._editor.onDidChangeModelLanguage(function () { return _this._update(); })); _this._register(modes_1.CodeActionProviderRegistry.onDidChange(function () { return _this._update(); })); _this._update(); return _this; } CodeActionModel.prototype.dispose = function () { _super.prototype.dispose.call(this); this.setState(CodeActionsState.Empty, true); }; CodeActionModel.prototype._update = function () { var _this = this; this._codeActionOracle.value = undefined; this.setState(CodeActionsState.Empty); var model = this._editor.getModel(); if (model && modes_1.CodeActionProviderRegistry.has(model) && !this._editor.getOption(68 /* readOnly */)) { var supportedActions = []; for (var _i = 0, _a = modes_1.CodeActionProviderRegistry.all(model); _i < _a.length; _i++) { var provider = _a[_i]; if (Array.isArray(provider.providedCodeActionKinds)) { supportedActions.push.apply(supportedActions, provider.providedCodeActionKinds); } } this._supportedCodeActions.set(supportedActions.join(' ')); this._codeActionOracle.value = new CodeActionOracle(this._editor, this._markerService, function (trigger) { if (!trigger) { _this.setState(CodeActionsState.Empty); return; } var actions = async_1.createCancelablePromise(function (token) { return codeAction_1.getCodeActions(model, trigger.selection, trigger.trigger, token); }); if (_this._progressService && trigger.trigger.type === 2 /* Manual */) { _this._progressService.showWhile(actions, 250); } _this.setState(new CodeActionsState.Triggered(trigger.trigger, trigger.selection, trigger.position, actions)); }, undefined); this._codeActionOracle.value.trigger({ type: 1 /* Auto */ }); } else { this._supportedCodeActions.reset(); } }; CodeActionModel.prototype.trigger = function (trigger) { if (this._codeActionOracle.value) { this._codeActionOracle.value.trigger(trigger); } }; CodeActionModel.prototype.setState = function (newState, skipNotify) { if (newState === this._state) { return; } // Cancel old request if (this._state.type === 1 /* Triggered */) { this._state.actions.cancel(); } this._state = newState; if (!skipNotify) { this._onDidChangeState.fire(newState); } }; return CodeActionModel; }(lifecycle_1.Disposable)); exports.CodeActionModel = CodeActionModel; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[221/*vs/editor/contrib/codelens/codelens*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,26/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,25/*vs/base/common/uri*/,12/*vs/editor/browser/editorExtensions*/,17/*vs/editor/common/modes*/,49/*vs/editor/common/services/modelService*/,2/*vs/base/common/lifecycle*/]), function (require, exports, arrays_1, cancellation_1, errors_1, uri_1, editorExtensions_1, modes_1, modelService_1, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CodeLensModel = /** @class */ (function () { function CodeLensModel() { this.lenses = []; this._disposables = new lifecycle_1.DisposableStore(); } CodeLensModel.prototype.dispose = function () { this._disposables.dispose(); }; CodeLensModel.prototype.add = function (list, provider) { this._disposables.add(list); for (var _i = 0, _a = list.lenses; _i < _a.length; _i++) { var symbol = _a[_i]; this.lenses.push({ symbol: symbol, provider: provider }); } }; return CodeLensModel; }()); exports.CodeLensModel = CodeLensModel; function getCodeLensData(model, token) { var provider = modes_1.CodeLensProviderRegistry.ordered(model); var providerRanks = new Map(); var result = new CodeLensModel(); var promises = provider.map(function (provider, i) { providerRanks.set(provider, i); return Promise.resolve(provider.provideCodeLenses(model, token)) .then(function (list) { return list && result.add(list, provider); }) .catch(errors_1.onUnexpectedExternalError); }); return Promise.all(promises).then(function () { result.lenses = arrays_1.mergeSort(result.lenses, function (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.getCodeLensData = getCodeLensData; editorExtensions_1.registerLanguageCommand('_executeCodeLensProvider', function (accessor, args) { var resource = args.resource, itemResolveCount = args.itemResolveCount; if (!(resource instanceof uri_1.URI)) { throw errors_1.illegalArgument(); } var model = accessor.get(modelService_1.IModelService).getModel(resource); if (!model) { throw errors_1.illegalArgument(); } var result = []; var disposables = new lifecycle_1.DisposableStore(); return getCodeLensData(model, cancellation_1.CancellationToken.None).then(function (value) { disposables.add(value); var resolve = []; var _loop_1 = function (item) { if (typeof itemResolveCount === 'undefined' || 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(function (symbol) { return result.push(symbol || item.symbol); })); } }; for (var _i = 0, _a = value.lenses; _i < _a.length; _i++) { var item = _a[_i]; _loop_1(item); } return Promise.all(resolve); }).then(function () { return result; }).finally(function () { // make sure to return results, then (on next tick) // dispose the results setTimeout(function () { return 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[529/*vs/editor/contrib/codelens/codeLensCache*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/,83/*vs/platform/instantiation/common/extensions*/,221/*vs/editor/contrib/codelens/codelens*/,38/*vs/base/common/map*/,74/*vs/platform/storage/common/storage*/,3/*vs/editor/common/core/range*/,15/*vs/base/common/async*/,102/*vs/base/common/functional*/]), function (require, exports, instantiation_1, extensions_1, codelens_1, map_1, storage_1, range_1, async_1, functional_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ICodeLensCache = instantiation_1.createDecorator('ICodeLensCache'); var CacheItem = /** @class */ (function () { function CacheItem(lineCount, data) { this.lineCount = lineCount; this.data = data; } return CacheItem; }()); var CodeLensCache = /** @class */ (function () { function CodeLensCache(storageService) { var _this = this; this._fakeProvider = new /** @class */ (function () { function class_1() { } class_1.prototype.provideCodeLenses = function () { throw new Error('not supported'); }; return class_1; }()); this._cache = new map_1.LRUCache(20, 0.75); // remove old data var oldkey = 'codelens/cache'; async_1.runWhenIdle(function () { return storageService.remove(oldkey, 1 /* WORKSPACE */); }); // restore lens data on start var key = 'codelens/cache2'; var raw = storageService.get(key, 1 /* WORKSPACE */, '{}'); this._deserialize(raw); // store lens data on shutdown functional_1.once(storageService.onWillSaveState)(function (e) { if (e.reason === storage_1.WillSaveStateReason.SHUTDOWN) { storageService.store(key, _this._serialize(), 1 /* WORKSPACE */); } }); } CodeLensCache.prototype.put = function (model, data) { // create a copy of the model that is without command-ids // but with comand-labels var copyItems = data.lenses.map(function (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 }, }; }); var copyModel = new codelens_1.CodeLensModel(); copyModel.add({ lenses: copyItems, dispose: function () { } }, this._fakeProvider); var item = new CacheItem(model.getLineCount(), copyModel); this._cache.set(model.uri.toString(), item); }; CodeLensCache.prototype.get = function (model) { var item = this._cache.get(model.uri.toString()); return item && item.lineCount === model.getLineCount() ? item.data : undefined; }; CodeLensCache.prototype.delete = function (model) { this._cache.delete(model.uri.toString()); }; // --- persistence CodeLensCache.prototype._serialize = function () { var data = Object.create(null); this._cache.forEach(function (value, key) { var lines = new Set(); for (var _i = 0, _a = value.data.lenses; _i < _a.length; _i++) { var d = _a[_i]; lines.add(d.symbol.range.startLineNumber); } data[key] = { lineCount: value.lineCount, lines: map_1.values(lines) }; }); return JSON.stringify(data); }; CodeLensCache.prototype._deserialize = function (raw) { try { var data = JSON.parse(raw); for (var key in data) { var element = data[key]; var lenses = []; for (var _i = 0, _a = element.lines; _i < _a.length; _i++) { var line = _a[_i]; lenses.push({ range: new range_1.Range(line, 1, line, 11) }); } var model = new codelens_1.CodeLensModel(); model.add({ lenses: lenses, dispose: function () { } }, this._fakeProvider); this._cache.set(key, new CacheItem(element.lineCount, model)); } } catch (_b) { // ignore... } }; CodeLensCache = __decorate([ __param(0, storage_1.IStorageService) ], CodeLensCache); return CodeLensCache; }()); exports.CodeLensCache = CodeLensCache; 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[222/*vs/editor/contrib/colorPicker/color*/], __M([0/*require*/,1/*exports*/,26/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,25/*vs/base/common/uri*/,12/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,17/*vs/editor/common/modes*/,49/*vs/editor/common/services/modelService*/]), function (require, exports, cancellation_1, errors_1, uri_1, editorExtensions_1, range_1, modes_1, modelService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function getColors(model, token) { var colors = []; var providers = modes_1.ColorProviderRegistry.ordered(model).reverse(); var promises = providers.map(function (provider) { return Promise.resolve(provider.provideDocumentColors(model, token)).then(function (result) { if (Array.isArray(result)) { for (var _i = 0, result_1 = result; _i < result_1.length; _i++) { var colorInfo = result_1[_i]; colors.push({ colorInfo: colorInfo, provider: provider }); } } }); }); return Promise.all(promises).then(function () { return colors; }); } exports.getColors = getColors; function getColorPresentations(model, colorInfo, provider, token) { return Promise.resolve(provider.provideColorPresentations(model, colorInfo, token)); } exports.getColorPresentations = getColorPresentations; editorExtensions_1.registerLanguageCommand('_executeDocumentColorProvider', function (accessor, args) { var resource = args.resource; if (!(resource instanceof uri_1.URI)) { throw errors_1.illegalArgument(); } var model = accessor.get(modelService_1.IModelService).getModel(resource); if (!model) { throw errors_1.illegalArgument(); } var rawCIs = []; var providers = modes_1.ColorProviderRegistry.ordered(model).reverse(); var promises = providers.map(function (provider) { return Promise.resolve(provider.provideDocumentColors(model, cancellation_1.CancellationToken.None)).then(function (result) { if (Array.isArray(result)) { for (var _i = 0, result_2 = result; _i < result_2.length; _i++) { var ci = result_2[_i]; rawCIs.push({ range: ci.range, color: [ci.color.red, ci.color.green, ci.color.blue, ci.color.alpha] }); } } }); }); return Promise.all(promises).then(function () { return rawCIs; }); }); editorExtensions_1.registerLanguageCommand('_executeColorPresentationProvider', function (accessor, args) { var resource = args.resource, color = args.color, range = args.range; if (!(resource instanceof uri_1.URI) || !Array.isArray(color) || color.length !== 4 || !range_1.Range.isIRange(range)) { throw errors_1.illegalArgument(); } var red = color[0], green = color[1], blue = color[2], alpha = color[3]; var model = accessor.get(modelService_1.IModelService).getModel(resource); if (!model) { throw errors_1.illegalArgument(); } var colorInfo = { range: range, color: { red: red, green: green, blue: blue, alpha: alpha } }; var presentations = []; var providers = modes_1.ColorProviderRegistry.ordered(model).reverse(); var promises = providers.map(function (provider) { return Promise.resolve(provider.provideColorPresentations(model, colorInfo, cancellation_1.CancellationToken.None)).then(function (result) { if (Array.isArray(result)) { presentations.push.apply(presentations, result); } }); }); return Promise.all(promises).then(function () { return 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[223/*vs/editor/contrib/colorPicker/colorDetector*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,27/*vs/base/common/color*/,10/*vs/base/common/errors*/,125/*vs/base/common/hash*/,2/*vs/base/common/lifecycle*/,12/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,3/*vs/editor/common/core/range*/,30/*vs/editor/common/model/textModel*/,17/*vs/editor/common/modes*/,222/*vs/editor/contrib/colorPicker/color*/,43/*vs/platform/configuration/common/configuration*/]), function (require, exports, async_1, color_1, errors_1, hash_1, lifecycle_1, editorExtensions_1, codeEditorService_1, range_1, textModel_1, modes_1, color_2, configuration_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MAX_DECORATORS = 500; var ColorDetector = /** @class */ (function (_super) { __extends(ColorDetector, _super); function ColorDetector(_editor, _codeEditorService, _configurationService) { var _this = _super.call(this) || this; _this._editor = _editor; _this._codeEditorService = _codeEditorService; _this._configurationService = _configurationService; _this._localToDispose = _this._register(new lifecycle_1.DisposableStore()); _this._decorationsIds = []; _this._colorDatas = new Map(); _this._colorDecoratorIds = []; _this._decorationsTypes = new Set(); _this._register(_editor.onDidChangeModel(function (e) { _this._isEnabled = _this.isEnabled(); _this.onModelChanged(); })); _this._register(_editor.onDidChangeModelLanguage(function (e) { return _this.onModelChanged(); })); _this._register(modes_1.ColorProviderRegistry.onDidChange(function (e) { return _this.onModelChanged(); })); _this._register(_editor.onDidChangeConfiguration(function (e) { var prevIsEnabled = _this._isEnabled; _this._isEnabled = _this.isEnabled(); if (prevIsEnabled !== _this._isEnabled) { if (_this._isEnabled) { _this.onModelChanged(); } else { _this.removeAllDecorations(); } } })); _this._timeoutTimer = null; _this._computePromise = null; _this._isEnabled = _this.isEnabled(); _this.onModelChanged(); return _this; } ColorDetector.prototype.isEnabled = function () { var model = this._editor.getModel(); if (!model) { return false; } var languageId = model.getLanguageIdentifier(); // handle deprecated settings. [languageId].colorDecorators.enable var deprecatedConfig = this._configurationService.getValue(languageId.language); if (deprecatedConfig) { var colorDecorators = deprecatedConfig['colorDecorators']; // deprecatedConfig.valueOf('.colorDecorators.enable'); if (colorDecorators && colorDecorators['enable'] !== undefined && !colorDecorators['enable']) { return colorDecorators['enable']; } } return this._editor.getOption(12 /* colorDecorators */); }; ColorDetector.get = function (editor) { return editor.getContribution(this.ID); }; ColorDetector.prototype.dispose = function () { this.stop(); this.removeAllDecorations(); _super.prototype.dispose.call(this); }; ColorDetector.prototype.onModelChanged = function () { var _this = this; this.stop(); if (!this._isEnabled) { return; } var model = this._editor.getModel(); if (!model || !modes_1.ColorProviderRegistry.has(model)) { return; } this._localToDispose.add(this._editor.onDidChangeModelContent(function (e) { if (!_this._timeoutTimer) { _this._timeoutTimer = new async_1.TimeoutTimer(); _this._timeoutTimer.cancelAndSet(function () { _this._timeoutTimer = null; _this.beginCompute(); }, ColorDetector.RECOMPUTE_TIME); } })); this.beginCompute(); }; ColorDetector.prototype.beginCompute = function () { var _this = this; this._computePromise = async_1.createCancelablePromise(function (token) { var model = _this._editor.getModel(); if (!model) { return Promise.resolve([]); } return color_2.getColors(model, token); }); this._computePromise.then(function (colorInfos) { _this.updateDecorations(colorInfos); _this.updateColorDecorators(colorInfos); _this._computePromise = null; }, errors_1.onUnexpectedError); }; ColorDetector.prototype.stop = function () { if (this._timeoutTimer) { this._timeoutTimer.cancel(); this._timeoutTimer = null; } if (this._computePromise) { this._computePromise.cancel(); this._computePromise = null; } this._localToDispose.clear(); }; ColorDetector.prototype.updateDecorations = function (colorDatas) { var _this = this; var decorations = colorDatas.map(function (c) { return ({ range: { startLineNumber: c.colorInfo.range.startLineNumber, startColumn: c.colorInfo.range.startColumn, endLineNumber: c.colorInfo.range.endLineNumber, endColumn: c.colorInfo.range.endColumn }, options: textModel_1.ModelDecorationOptions.EMPTY }); }); this._decorationsIds = this._editor.deltaDecorations(this._decorationsIds, decorations); this._colorDatas = new Map(); this._decorationsIds.forEach(function (id, i) { return _this._colorDatas.set(id, colorDatas[i]); }); }; ColorDetector.prototype.updateColorDecorators = function (colorData) { var _this = this; var decorations = []; var newDecorationsTypes = {}; for (var i = 0; i < colorData.length && decorations.length < MAX_DECORATORS; i++) { var _a = colorData[i].colorInfo.color, red = _a.red, green = _a.green, blue = _a.blue, alpha = _a.alpha; var rgba = new color_1.RGBA(Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255), alpha); var subKey = hash_1.hash(rgba).toString(16); var color = "rgba(" + rgba.r + ", " + rgba.g + ", " + rgba.b + ", " + rgba.a + ")"; var key = 'colorBox-' + subKey; if (!this._decorationsTypes.has(key) && !newDecorationsTypes[key]) { this._codeEditorService.registerDecorationType(key, { before: { contentText: ' ', border: 'solid 0.1em #000', margin: '0.1em 0.2em 0 0.2em', width: '0.8em', height: '0.8em', backgroundColor: color }, dark: { before: { border: 'solid 0.1em #eee' } } }, undefined, this._editor); } newDecorationsTypes[key] = true; decorations.push({ range: { startLineNumber: colorData[i].colorInfo.range.startLineNumber, startColumn: colorData[i].colorInfo.range.startColumn, endLineNumber: colorData[i].colorInfo.range.endLineNumber, endColumn: colorData[i].colorInfo.range.endColumn }, options: this._codeEditorService.resolveDecorationOptions(key, true) }); } this._decorationsTypes.forEach(function (subType) { if (!newDecorationsTypes[subType]) { _this._codeEditorService.removeDecorationType(subType); } }); this._colorDecoratorIds = this._editor.deltaDecorations(this._colorDecoratorIds, decorations); }; ColorDetector.prototype.removeAllDecorations = function () { var _this = this; this._decorationsIds = this._editor.deltaDecorations(this._decorationsIds, []); this._colorDecoratorIds = this._editor.deltaDecorations(this._colorDecoratorIds, []); this._decorationsTypes.forEach(function (subType) { _this._codeEditorService.removeDecorationType(subType); }); }; ColorDetector.prototype.getColorData = function (position) { var _this = this; var model = this._editor.getModel(); if (!model) { return null; } var decorations = model .getDecorationsInRange(range_1.Range.fromPositions(position, position)) .filter(function (d) { return _this._colorDatas.has(d.id); }); if (decorations.length === 0) { return null; } return this._colorDatas.get(decorations[0].id); }; ColorDetector.ID = 'editor.contrib.colorDetector'; ColorDetector.RECOMPUTE_TIME = 1000; // ms ColorDetector = __decorate([ __param(1, codeEditorService_1.ICodeEditorService), __param(2, configuration_1.IConfigurationService) ], ColorDetector); return ColorDetector; }(lifecycle_1.Disposable)); exports.ColorDetector = ColorDetector; editorExtensions_1.registerEditorContribution(ColorDetector.ID, ColorDetector); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[530/*vs/editor/contrib/comment/comment*/], __M([0/*require*/,1/*exports*/,434/*vs/nls!vs/editor/contrib/comment/comment*/,36/*vs/base/common/keyCodes*/,12/*vs/editor/browser/editorExtensions*/,23/*vs/editor/common/editorContextKeys*/,196/*vs/editor/contrib/comment/blockCommentCommand*/,376/*vs/editor/contrib/comment/lineCommentCommand*/]), function (require, exports, nls, keyCodes_1, editorExtensions_1, editorContextKeys_1, blockCommentCommand_1, lineCommentCommand_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CommentLineAction = /** @class */ (function (_super) { __extends(CommentLineAction, _super); function CommentLineAction(type, opts) { var _this = _super.call(this, opts) || this; _this._type = type; return _this; } CommentLineAction.prototype.run = function (accessor, editor) { if (!editor.hasModel()) { return; } var model = editor.getModel(); var commands = []; var selections = editor.getSelections(); var modelOptions = model.getOptions(); var commentsOptions = editor.getOption(13 /* comments */); for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) { var selection = selections_1[_i]; commands.push(new lineCommentCommand_1.LineCommentCommand(selection, modelOptions.tabSize, this._type, commentsOptions.insertSpace)); } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); }; return CommentLineAction; }(editorExtensions_1.EditorAction)); var ToggleCommentLineAction = /** @class */ (function (_super) { __extends(ToggleCommentLineAction, _super); function ToggleCommentLineAction() { return _super.call(this, 0 /* Toggle */, { id: 'editor.action.commentLine', label: nls.localize(0, null), alias: 'Toggle Line Comment', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 85 /* US_SLASH */, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 17 /* MenubarEditMenu */, group: '5_insert', title: nls.localize(1, null), order: 1 } }) || this; } return ToggleCommentLineAction; }(CommentLineAction)); var AddLineCommentAction = /** @class */ (function (_super) { __extends(AddLineCommentAction, _super); function AddLineCommentAction() { return _super.call(this, 1 /* ForceAdd */, { id: 'editor.action.addCommentLine', label: nls.localize(2, null), alias: 'Add Line Comment', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 33 /* KEY_C */), weight: 100 /* EditorContrib */ } }) || this; } return AddLineCommentAction; }(CommentLineAction)); var RemoveLineCommentAction = /** @class */ (function (_super) { __extends(RemoveLineCommentAction, _super); function RemoveLineCommentAction() { return _super.call(this, 2 /* ForceRemove */, { id: 'editor.action.removeCommentLine', label: nls.localize(3, null), alias: 'Remove Line Comment', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 51 /* KEY_U */), weight: 100 /* EditorContrib */ } }) || this; } return RemoveLineCommentAction; }(CommentLineAction)); var BlockCommentAction = /** @class */ (function (_super) { __extends(BlockCommentAction, _super); function BlockCommentAction() { return _super.call(this, { id: 'editor.action.blockComment', label: nls.localize(4, null), alias: 'Toggle Block Comment', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 1024 /* Shift */ | 512 /* Alt */ | 31 /* KEY_A */, linux: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 31 /* KEY_A */ }, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 17 /* MenubarEditMenu */, group: '5_insert', title: nls.localize(5, null), order: 2 } }) || this; } BlockCommentAction.prototype.run = function (accessor, editor) { if (!editor.hasModel()) { return; } var commentsOptions = editor.getOption(13 /* comments */); var commands = []; var selections = editor.getSelections(); for (var _i = 0, selections_2 = selections; _i < selections_2.length; _i++) { var selection = selections_2[_i]; commands.push(new blockCommentCommand_1.BlockCommentCommand(selection, commentsOptions.insertSpace)); } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); }; return BlockCommentAction; }(editorExtensions_1.EditorAction)); editorExtensions_1.registerEditorAction(ToggleCommentLineAction); editorExtensions_1.registerEditorAction(AddLineCommentAction); editorExtensions_1.registerEditorAction(RemoveLineCommentAction); editorExtensions_1.registerEditorAction(BlockCommentAction); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[531/*vs/editor/contrib/contextmenu/contextmenu*/], __M([0/*require*/,1/*exports*/,435/*vs/nls!vs/editor/contrib/contextmenu/contextmenu*/,6/*vs/base/browser/dom*/,70/*vs/base/browser/ui/actionbar/actionbar*/,2/*vs/base/common/lifecycle*/,12/*vs/editor/browser/editorExtensions*/,23/*vs/editor/common/editorContextKeys*/,65/*vs/platform/actions/common/actions*/,18/*vs/platform/contextkey/common/contextkey*/,66/*vs/platform/contextview/browser/contextView*/,34/*vs/platform/keybinding/common/keybinding*/,405/*vs/base/browser/contextmenu*/]), function (require, exports, nls, dom, actionbar_1, lifecycle_1, editorExtensions_1, editorContextKeys_1, actions_1, contextkey_1, contextView_1, keybinding_1, contextmenu_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ContextMenuController = /** @class */ (function () { function ContextMenuController(editor, _contextMenuService, _contextViewService, _contextKeyService, _keybindingService, _menuService) { var _this = this; this._contextMenuService = _contextMenuService; this._contextViewService = _contextViewService; this._contextKeyService = _contextKeyService; this._keybindingService = _keybindingService; this._menuService = _menuService; this._toDispose = new lifecycle_1.DisposableStore(); this._contextMenuIsBeingShownCount = 0; this._editor = editor; this._toDispose.add(this._editor.onContextMenu(function (e) { return _this._onContextMenu(e); })); this._toDispose.add(this._editor.onMouseWheel(function (e) { if (_this._contextMenuIsBeingShownCount > 0) { _this._contextViewService.hideContextView(); } })); this._toDispose.add(this._editor.onKeyDown(function (e) { if (e.keyCode === 58 /* ContextMenu */) { // Chrome is funny like that e.preventDefault(); e.stopPropagation(); _this.showContextMenu(); } })); } ContextMenuController.get = function (editor) { return editor.getContribution(ContextMenuController.ID); }; ContextMenuController.prototype._onContextMenu = function (e) { if (!this._editor.hasModel()) { return; } if (!this._editor.getOption(14 /* contextmenu */)) { this._editor.focus(); // Ensure the cursor is at the position of the mouse click if (e.target.position && !this._editor.getSelection().containsPosition(e.target.position)) { this._editor.setPosition(e.target.position); } return; // Context menu is turned off through configuration } if (e.target.type === 12 /* OVERLAY_WIDGET */) { return; // allow native menu on widgets to support right click on input field for example in find } e.event.preventDefault(); if (e.target.type !== 6 /* CONTENT_TEXT */ && e.target.type !== 7 /* CONTENT_EMPTY */ && e.target.type !== 1 /* TEXTAREA */) { return; // only support mouse click into text or native context menu key for now } // Ensure the editor gets focus if it hasn't, so the right events are being sent to other contributions this._editor.focus(); // Ensure the cursor is at the position of the mouse click if (e.target.position) { var hasSelectionAtPosition = false; for (var _i = 0, _a = this._editor.getSelections(); _i < _a.length; _i++) { var selection = _a[_i]; if (selection.containsPosition(e.target.position)) { hasSelectionAtPosition = true; break; } } if (!hasSelectionAtPosition) { this._editor.setPosition(e.target.position); } } // Unless the user triggerd the context menu through Shift+F10, use the mouse position as menu position var anchor = null; if (e.target.type !== 1 /* TEXTAREA */) { anchor = { x: e.event.posx - 1, width: 2, y: e.event.posy - 1, height: 2 }; } // Show the context menu this.showContextMenu(anchor); }; ContextMenuController.prototype.showContextMenu = function (anchor) { if (!this._editor.getOption(14 /* contextmenu */)) { return; // Context menu is turned off through configuration } if (!this._editor.hasModel()) { return; } if (!this._contextMenuService) { this._editor.focus(); return; // We need the context menu service to function } // Find actions available for menu var menuActions = this._getMenuActions(this._editor.getModel(), 7 /* EditorContext */); // Show menu if we have actions to show if (menuActions.length > 0) { this._doShowContextMenu(menuActions, anchor); } }; ContextMenuController.prototype._getMenuActions = function (model, menuId) { var result = []; // get menu groups var menu = this._menuService.createMenu(menuId, this._contextKeyService); var groups = menu.getActions({ arg: model.uri }); menu.dispose(); // translate them into other actions for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) { var group = groups_1[_i]; var actions = group[1]; var addedItems = 0; for (var _a = 0, actions_2 = actions; _a < actions_2.length; _a++) { var action = actions_2[_a]; if (action instanceof actions_1.SubmenuItemAction) { var subActions = this._getMenuActions(model, action.item.submenu); if (subActions.length > 0) { result.push(new contextmenu_1.ContextSubMenu(action.label, subActions)); addedItems++; } } else { result.push(action); addedItems++; } } if (addedItems) { result.push(new actionbar_1.Separator()); } } if (result.length) { result.pop(); // remove last separator } return result; }; ContextMenuController.prototype._doShowContextMenu = function (actions, anchor) { var _this = this; if (anchor === void 0) { anchor = null; } if (!this._editor.hasModel()) { return; } // Disable hover var oldHoverSetting = this._editor.getOption(44 /* hover */); this._editor.updateOptions({ hover: { enabled: false } }); if (!anchor) { // Ensure selection is visible this._editor.revealPosition(this._editor.getPosition(), 1 /* Immediate */); this._editor.render(); var cursorCoords = this._editor.getScrolledVisiblePosition(this._editor.getPosition()); // Translate to absolute editor position var editorCoords = dom.getDomNodePagePosition(this._editor.getDomNode()); var posx = editorCoords.left + cursorCoords.left; var posy = editorCoords.top + cursorCoords.top + cursorCoords.height; anchor = { x: posx, y: posy }; } // Show menu this._contextMenuIsBeingShownCount++; this._contextMenuService.showContextMenu({ getAnchor: function () { return anchor; }, getActions: function () { return actions; }, getActionViewItem: function (action) { var keybinding = _this._keybindingFor(action); if (keybinding) { return new actionbar_1.ActionViewItem(action, action, { label: true, keybinding: keybinding.getLabel(), isMenu: true }); } var customActionViewItem = action; if (typeof customActionViewItem.getActionViewItem === 'function') { return customActionViewItem.getActionViewItem(); } return new actionbar_1.ActionViewItem(action, action, { icon: true, label: true, isMenu: true }); }, getKeyBinding: function (action) { return _this._keybindingFor(action); }, onHide: function (wasCancelled) { _this._contextMenuIsBeingShownCount--; _this._editor.focus(); _this._editor.updateOptions({ hover: oldHoverSetting }); } }); }; ContextMenuController.prototype._keybindingFor = function (action) { return this._keybindingService.lookupKeybinding(action.id); }; ContextMenuController.prototype.dispose = function () { if (this._contextMenuIsBeingShownCount > 0) { this._contextViewService.hideContextView(); } this._toDispose.dispose(); }; ContextMenuController.ID = 'editor.contrib.contextmenu'; ContextMenuController = __decorate([ __param(1, contextView_1.IContextMenuService), __param(2, contextView_1.IContextViewService), __param(3, contextkey_1.IContextKeyService), __param(4, keybinding_1.IKeybindingService), __param(5, actions_1.IMenuService) ], ContextMenuController); return ContextMenuController; }()); exports.ContextMenuController = ContextMenuController; var ShowContextMenu = /** @class */ (function (_super) { __extends(ShowContextMenu, _super); function ShowContextMenu() { return _super.call(this, { id: 'editor.action.showContextMenu', label: nls.localize(0, null), alias: 'Show Editor Context Menu', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 1024 /* Shift */ | 68 /* F10 */, weight: 100 /* EditorContrib */ } }) || this; } ShowContextMenu.prototype.run = function (accessor, editor) { var contribution = ContextMenuController.get(editor); contribution.showContextMenu(); }; return ShowContextMenu; }(editorExtensions_1.EditorAction)); editorExtensions_1.registerEditorContribution(ContextMenuController.ID, ContextMenuController); editorExtensions_1.registerEditorAction(ShowContextMenu); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[532/*vs/editor/contrib/cursorUndo/cursorUndo*/], __M([0/*require*/,1/*exports*/,436/*vs/nls!vs/editor/contrib/cursorUndo/cursorUndo*/,2/*vs/base/common/lifecycle*/,12/*vs/editor/browser/editorExtensions*/,23/*vs/editor/common/editorContextKeys*/]), function (require, exports, nls, lifecycle_1, editorExtensions_1, editorContextKeys_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CursorState = /** @class */ (function () { function CursorState(selections) { this.selections = selections; } CursorState.prototype.equals = function (other) { var thisLen = this.selections.length; var otherLen = other.selections.length; if (thisLen !== otherLen) { return false; } for (var i = 0; i < thisLen; i++) { if (!this.selections[i].equalsSelection(other.selections[i])) { return false; } } return true; }; return CursorState; }()); var StackElement = /** @class */ (function () { function StackElement(cursorState, scrollTop, scrollLeft) { this.cursorState = cursorState; this.scrollTop = scrollTop; this.scrollLeft = scrollLeft; } return StackElement; }()); var CursorUndoRedoController = /** @class */ (function (_super) { __extends(CursorUndoRedoController, _super); function CursorUndoRedoController(editor) { var _this = _super.call(this) || this; _this._editor = editor; _this._isCursorUndoRedo = false; _this._undoStack = []; _this._redoStack = []; _this._register(editor.onDidChangeModel(function (e) { _this._undoStack = []; _this._redoStack = []; })); _this._register(editor.onDidChangeModelContent(function (e) { _this._undoStack = []; _this._redoStack = []; })); _this._register(editor.onDidChangeCursorSelection(function (e) { if (_this._isCursorUndoRedo) { return; } if (!e.oldSelections) { return; } if (e.oldModelVersionId !== e.modelVersionId) { return; } var prevState = new CursorState(e.oldSelections); var isEqualToLastUndoStack = (_this._undoStack.length > 0 && _this._undoStack[_this._undoStack.length - 1].cursorState.equals(prevState)); if (!isEqualToLastUndoStack) { _this._undoStack.push(new StackElement(prevState, editor.getScrollTop(), editor.getScrollLeft())); _this._redoStack = []; if (_this._undoStack.length > 50) { // keep the cursor undo stack bounded _this._undoStack.shift(); } } })); return _this; } CursorUndoRedoController.get = function (editor) { return editor.getContribution(CursorUndoRedoController.ID); }; CursorUndoRedoController.prototype.cursorUndo = function () { if (!this._editor.hasModel() || this._undoStack.length === 0) { return; } this._redoStack.push(new StackElement(new CursorState(this._editor.getSelections()), this._editor.getScrollTop(), this._editor.getScrollLeft())); this._applyState(this._undoStack.pop()); }; CursorUndoRedoController.prototype.cursorRedo = function () { if (!this._editor.hasModel() || this._redoStack.length === 0) { return; } this._undoStack.push(new StackElement(new CursorState(this._editor.getSelections()), this._editor.getScrollTop(), this._editor.getScrollLeft())); this._applyState(this._redoStack.pop()); }; CursorUndoRedoController.prototype._applyState = function (stackElement) { this._isCursorUndoRedo = true; this._editor.setSelections(stackElement.cursorState.selections); this._editor.setScrollPosition({ scrollTop: stackElement.scrollTop, scrollLeft: stackElement.scrollLeft }); this._isCursorUndoRedo = false; }; CursorUndoRedoController.ID = 'editor.contrib.cursorUndoRedoController'; return CursorUndoRedoController; }(lifecycle_1.Disposable)); exports.CursorUndoRedoController = CursorUndoRedoController; var CursorUndo = /** @class */ (function (_super) { __extends(CursorUndo, _super); function CursorUndo() { return _super.call(this, { id: 'cursorUndo', label: nls.localize(0, null), alias: 'Cursor Undo', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 51 /* KEY_U */, weight: 100 /* EditorContrib */ } }) || this; } CursorUndo.prototype.run = function (accessor, editor, args) { CursorUndoRedoController.get(editor).cursorUndo(); }; return CursorUndo; }(editorExtensions_1.EditorAction)); exports.CursorUndo = CursorUndo; var CursorRedo = /** @class */ (function (_super) { __extends(CursorRedo, _super); function CursorRedo() { return _super.call(this, { id: 'cursorRedo', label: nls.localize(1, null), alias: 'Cursor Redo', precondition: undefined }) || this; } CursorRedo.prototype.run = function (accessor, editor, args) { CursorUndoRedoController.get(editor).cursorRedo(); }; return CursorRedo; }(editorExtensions_1.EditorAction)); exports.CursorRedo = CursorRedo; editorExtensions_1.registerEditorContribution(CursorUndoRedoController.ID, CursorUndoRedoController); editorExtensions_1.registerEditorAction(CursorUndo); editorExtensions_1.registerEditorAction(CursorRedo); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[533/*vs/editor/contrib/dnd/dnd*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,12/*vs/editor/browser/editorExtensions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,377/*vs/editor/contrib/dnd/dragAndDropCommand*/,30/*vs/editor/common/model/textModel*/,307/*vs/css!vs/editor/contrib/dnd/dnd*/]), function (require, exports, lifecycle_1, platform_1, editorExtensions_1, position_1, range_1, selection_1, dragAndDropCommand_1, textModel_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function hasTriggerModifier(e) { if (platform_1.isMacintosh) { return e.altKey; } else { return e.ctrlKey; } } var DragAndDropController = /** @class */ (function (_super) { __extends(DragAndDropController, _super); function DragAndDropController(editor) { var _this = _super.call(this) || this; _this._editor = editor; _this._register(_this._editor.onMouseDown(function (e) { return _this._onEditorMouseDown(e); })); _this._register(_this._editor.onMouseUp(function (e) { return _this._onEditorMouseUp(e); })); _this._register(_this._editor.onMouseDrag(function (e) { return _this._onEditorMouseDrag(e); })); _this._register(_this._editor.onMouseDrop(function (e) { return _this._onEditorMouseDrop(e); })); _this._register(_this._editor.onKeyDown(function (e) { return _this.onEditorKeyDown(e); })); _this._register(_this._editor.onKeyUp(function (e) { return _this.onEditorKeyUp(e); })); _this._register(_this._editor.onDidBlurEditorWidget(function () { return _this.onEditorBlur(); })); _this._dndDecorationIds = []; _this._mouseDown = false; _this._modifierPressed = false; _this._dragSelection = null; return _this; } DragAndDropController.prototype.onEditorBlur = function () { this._removeDecoration(); this._dragSelection = null; this._mouseDown = false; this._modifierPressed = false; }; DragAndDropController.prototype.onEditorKeyDown = function (e) { if (!this._editor.getOption(24 /* dragAndDrop */)) { return; } if (hasTriggerModifier(e)) { this._modifierPressed = true; } if (this._mouseDown && hasTriggerModifier(e)) { this._editor.updateOptions({ mouseStyle: 'copy' }); } }; DragAndDropController.prototype.onEditorKeyUp = function (e) { if (!this._editor.getOption(24 /* dragAndDrop */)) { return; } if (hasTriggerModifier(e)) { this._modifierPressed = false; } if (this._mouseDown && e.keyCode === DragAndDropController.TRIGGER_KEY_VALUE) { this._editor.updateOptions({ mouseStyle: 'default' }); } }; DragAndDropController.prototype._onEditorMouseDown = function (mouseEvent) { this._mouseDown = true; }; DragAndDropController.prototype._onEditorMouseUp = function (mouseEvent) { this._mouseDown = false; // Whenever users release the mouse, the drag and drop operation should finish and the cursor should revert to text. this._editor.updateOptions({ mouseStyle: 'text' }); }; DragAndDropController.prototype._onEditorMouseDrag = function (mouseEvent) { var target = mouseEvent.target; if (this._dragSelection === null) { var selections = this._editor.getSelections() || []; var possibleSelections = selections.filter(function (selection) { return target.position && selection.containsPosition(target.position); }); if (possibleSelections.length === 1) { this._dragSelection = possibleSelections[0]; } else { return; } } if (hasTriggerModifier(mouseEvent.event)) { this._editor.updateOptions({ mouseStyle: 'copy' }); } else { this._editor.updateOptions({ mouseStyle: 'default' }); } if (target.position) { if (this._dragSelection.containsPosition(target.position)) { this._removeDecoration(); } else { this.showAt(target.position); } } }; DragAndDropController.prototype._onEditorMouseDrop = function (mouseEvent) { if (mouseEvent.target && (this._hitContent(mouseEvent.target) || this._hitMargin(mouseEvent.target)) && mouseEvent.target.position) { var newCursorPosition_1 = new position_1.Position(mouseEvent.target.position.lineNumber, mouseEvent.target.position.column); if (this._dragSelection === null) { var newSelections = null; if (mouseEvent.event.shiftKey) { var primarySelection = this._editor.getSelection(); if (primarySelection) { var selectionStartLineNumber = primarySelection.selectionStartLineNumber, selectionStartColumn = primarySelection.selectionStartColumn; newSelections = [new selection_1.Selection(selectionStartLineNumber, selectionStartColumn, newCursorPosition_1.lineNumber, newCursorPosition_1.column)]; } } else { newSelections = (this._editor.getSelections() || []).map(function (selection) { if (selection.containsPosition(newCursorPosition_1)) { return new selection_1.Selection(newCursorPosition_1.lineNumber, newCursorPosition_1.column, newCursorPosition_1.lineNumber, newCursorPosition_1.column); } else { return selection; } }); } // Use `mouse` as the source instead of `api`. this._editor.setSelections(newSelections || [], 'mouse'); } else if (!this._dragSelection.containsPosition(newCursorPosition_1) || ((hasTriggerModifier(mouseEvent.event) || this._modifierPressed) && (this._dragSelection.getEndPosition().equals(newCursorPosition_1) || this._dragSelection.getStartPosition().equals(newCursorPosition_1)) // we allow users to paste content beside the selection )) { this._editor.pushUndoStop(); this._editor.executeCommand(DragAndDropController.ID, new dragAndDropCommand_1.DragAndDropCommand(this._dragSelection, newCursorPosition_1, hasTriggerModifier(mouseEvent.event) || this._modifierPressed)); this._editor.pushUndoStop(); } } this._editor.updateOptions({ mouseStyle: 'text' }); this._removeDecoration(); this._dragSelection = null; this._mouseDown = false; }; DragAndDropController.prototype.showAt = function (position) { var newDecorations = [{ range: new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column), options: DragAndDropController._DECORATION_OPTIONS }]; this._dndDecorationIds = this._editor.deltaDecorations(this._dndDecorationIds, newDecorations); this._editor.revealPosition(position, 1 /* Immediate */); }; DragAndDropController.prototype._removeDecoration = function () { this._dndDecorationIds = this._editor.deltaDecorations(this._dndDecorationIds, []); }; DragAndDropController.prototype._hitContent = function (target) { return target.type === 6 /* CONTENT_TEXT */ || target.type === 7 /* CONTENT_EMPTY */; }; DragAndDropController.prototype._hitMargin = function (target) { return target.type === 2 /* GUTTER_GLYPH_MARGIN */ || target.type === 3 /* GUTTER_LINE_NUMBERS */ || target.type === 4 /* GUTTER_LINE_DECORATIONS */; }; DragAndDropController.prototype.dispose = function () { this._removeDecoration(); this._dragSelection = null; this._mouseDown = false; this._modifierPressed = false; _super.prototype.dispose.call(this); }; DragAndDropController.ID = 'editor.contrib.dragAndDrop'; DragAndDropController.TRIGGER_KEY_VALUE = platform_1.isMacintosh ? 6 /* Alt */ : 5 /* Ctrl */; DragAndDropController._DECORATION_OPTIONS = textModel_1.ModelDecorationOptions.register({ className: 'dnd-target' }); return DragAndDropController; }(lifecycle_1.Disposable)); exports.DragAndDropController = DragAndDropController; editorExtensions_1.registerEditorContribution(DragAndDropController.ID, DragAndDropController); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[534/*vs/editor/contrib/fontZoom/fontZoom*/], __M([0/*require*/,1/*exports*/,441/*vs/nls!vs/editor/contrib/fontZoom/fontZoom*/,12/*vs/editor/browser/editorExtensions*/,105/*vs/editor/common/config/editorZoom*/]), function (require, exports, nls, editorExtensions_1, editorZoom_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var EditorFontZoomIn = /** @class */ (function (_super) { __extends(EditorFontZoomIn, _super); function EditorFontZoomIn() { return _super.call(this, { id: 'editor.action.fontZoomIn', label: nls.localize(0, null), alias: 'Editor Font Zoom In', precondition: undefined }) || this; } EditorFontZoomIn.prototype.run = function (accessor, editor) { editorZoom_1.EditorZoom.setZoomLevel(editorZoom_1.EditorZoom.getZoomLevel() + 1); }; return EditorFontZoomIn; }(editorExtensions_1.EditorAction)); var EditorFontZoomOut = /** @class */ (function (_super) { __extends(EditorFontZoomOut, _super); function EditorFontZoomOut() { return _super.call(this, { id: 'editor.action.fontZoomOut', label: nls.localize(1, null), alias: 'Editor Font Zoom Out', precondition: undefined }) || this; } EditorFontZoomOut.prototype.run = function (accessor, editor) { editorZoom_1.EditorZoom.setZoomLevel(editorZoom_1.EditorZoom.getZoomLevel() - 1); }; return EditorFontZoomOut; }(editorExtensions_1.EditorAction)); var EditorFontZoomReset = /** @class */ (function (_super) { __extends(EditorFontZoomReset, _super); function EditorFontZoomReset() { return _super.call(this, { id: 'editor.action.fontZoomReset', label: nls.localize(2, null), alias: 'Editor Font Zoom Reset', precondition: undefined }) || this; } EditorFontZoomReset.prototype.run = function (accessor, editor) { editorZoom_1.EditorZoom.setZoomLevel(0); }; return EditorFontZoomReset; }(editorExtensions_1.EditorAction)); editorExtensions_1.registerEditorAction(EditorFontZoomIn); editorExtensions_1.registerEditorAction(EditorFontZoomOut); editorExtensions_1.registerEditorAction(EditorFontZoomReset); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[535/*vs/editor/contrib/format/format*/], __M([0/*require*/,1/*exports*/,50/*vs/base/browser/ui/aria/aria*/,19/*vs/base/common/arrays*/,26/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,25/*vs/base/common/uri*/,67/*vs/editor/browser/core/editorState*/,108/*vs/editor/browser/editorBrowser*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,17/*vs/editor/common/modes*/,62/*vs/editor/common/services/editorWorkerService*/,49/*vs/editor/common/services/modelService*/,198/*vs/editor/contrib/format/formattingEdit*/,442/*vs/nls!vs/editor/contrib/format/format*/,479/*vs/platform/extensions/common/extensions*/,11/*vs/platform/instantiation/common/instantiation*/,76/*vs/base/common/linkedList*/,29/*vs/platform/commands/common/commands*/,21/*vs/base/common/types*/]), function (require, exports, aria_1, arrays_1, cancellation_1, errors_1, uri_1, editorState_1, editorBrowser_1, position_1, range_1, selection_1, modes_1, editorWorkerService_1, modelService_1, formattingEdit_1, nls, extensions_1, instantiation_1, linkedList_1, commands_1, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function alertFormattingEdits(edits) { edits = edits.filter(function (edit) { return edit.range; }); if (!edits.length) { return; } var range = edits[0].range; for (var i = 1; i < edits.length; i++) { range = range_1.Range.plusRange(range, edits[i].range); } var startLineNumber = range.startLineNumber, endLineNumber = range.endLineNumber; if (startLineNumber === endLineNumber) { if (edits.length === 1) { aria_1.alert(nls.localize(0, null, startLineNumber)); } else { aria_1.alert(nls.localize(1, null, edits.length, startLineNumber)); } } else { if (edits.length === 1) { aria_1.alert(nls.localize(2, null, startLineNumber, endLineNumber)); } else { aria_1.alert(nls.localize(3, null, edits.length, startLineNumber, endLineNumber)); } } } exports.alertFormattingEdits = alertFormattingEdits; function getRealAndSyntheticDocumentFormattersOrdered(model) { var result = []; var seen = new Set(); // (1) add all document formatter var docFormatter = modes_1.DocumentFormattingEditProviderRegistry.ordered(model); for (var _i = 0, docFormatter_1 = docFormatter; _i < docFormatter_1.length; _i++) { var formatter = docFormatter_1[_i]; result.push(formatter); if (formatter.extensionId) { seen.add(extensions_1.ExtensionIdentifier.toKey(formatter.extensionId)); } } // (2) add all range formatter as document formatter (unless the same extension already did that) var rangeFormatter = modes_1.DocumentRangeFormattingEditProviderRegistry.ordered(model); var _loop_1 = function (formatter) { if (formatter.extensionId) { if (seen.has(extensions_1.ExtensionIdentifier.toKey(formatter.extensionId))) { return "continue"; } seen.add(extensions_1.ExtensionIdentifier.toKey(formatter.extensionId)); } result.push({ displayName: formatter.displayName, extensionId: formatter.extensionId, provideDocumentFormattingEdits: function (model, options, token) { return formatter.provideDocumentRangeFormattingEdits(model, model.getFullModelRange(), options, token); } }); }; for (var _a = 0, rangeFormatter_1 = rangeFormatter; _a < rangeFormatter_1.length; _a++) { var formatter = rangeFormatter_1[_a]; _loop_1(formatter); } return result; } exports.getRealAndSyntheticDocumentFormattersOrdered = getRealAndSyntheticDocumentFormattersOrdered; var FormattingConflicts = /** @class */ (function () { function FormattingConflicts() { } FormattingConflicts.select = function (formatter, document, mode) { return __awaiter(this, void 0, void 0, function () { var selector; return __generator(this, function (_a) { switch (_a.label) { case 0: if (formatter.length === 0) { return [2 /*return*/, undefined]; } selector = FormattingConflicts._selectors.iterator().next().value; if (!selector) return [3 /*break*/, 2]; return [4 /*yield*/, selector(formatter, document, mode)]; case 1: return [2 /*return*/, _a.sent()]; case 2: return [2 /*return*/, formatter[0]]; } }); }); }; FormattingConflicts._selectors = new linkedList_1.LinkedList(); return FormattingConflicts; }()); exports.FormattingConflicts = FormattingConflicts; function formatDocumentRangeWithSelectedProvider(accessor, editorOrModel, range, mode, token) { return __awaiter(this, void 0, void 0, function () { var instaService, model, provider, selected; return __generator(this, function (_a) { switch (_a.label) { case 0: instaService = accessor.get(instantiation_1.IInstantiationService); model = editorBrowser_1.isCodeEditor(editorOrModel) ? editorOrModel.getModel() : editorOrModel; provider = modes_1.DocumentRangeFormattingEditProviderRegistry.ordered(model); return [4 /*yield*/, FormattingConflicts.select(provider, model, mode)]; case 1: selected = _a.sent(); if (!selected) return [3 /*break*/, 3]; return [4 /*yield*/, instaService.invokeFunction(formatDocumentRangeWithProvider, selected, editorOrModel, range, token)]; case 2: _a.sent(); _a.label = 3; case 3: return [2 /*return*/]; } }); }); } exports.formatDocumentRangeWithSelectedProvider = formatDocumentRangeWithSelectedProvider; function formatDocumentRangeWithProvider(accessor, provider, editorOrModel, range, token) { return __awaiter(this, void 0, void 0, function () { var workerService, model, cts, edits, rawEdits, range_2, initialSelection_1; return __generator(this, function (_a) { switch (_a.label) { case 0: workerService = accessor.get(editorWorkerService_1.IEditorWorkerService); if (editorBrowser_1.isCodeEditor(editorOrModel)) { model = editorOrModel.getModel(); cts = new editorState_1.EditorStateCancellationTokenSource(editorOrModel, 1 /* Value */ | 4 /* Position */, token); } else { model = editorOrModel; cts = new editorState_1.TextModelCancellationTokenSource(editorOrModel, token); } _a.label = 1; case 1: _a.trys.push([1, , 4, 5]); return [4 /*yield*/, provider.provideDocumentRangeFormattingEdits(model, range, model.getFormattingOptions(), cts.token)]; case 2: rawEdits = _a.sent(); return [4 /*yield*/, workerService.computeMoreMinimalEdits(model.uri, rawEdits)]; case 3: edits = _a.sent(); if (cts.token.isCancellationRequested) { return [2 /*return*/, true]; } return [3 /*break*/, 5]; case 4: cts.dispose(); return [7 /*endfinally*/]; case 5: if (!edits || edits.length === 0) { return [2 /*return*/, false]; } if (editorBrowser_1.isCodeEditor(editorOrModel)) { // use editor to apply edits formattingEdit_1.FormattingEdit.execute(editorOrModel, edits); alertFormattingEdits(edits); editorOrModel.pushUndoStop(); editorOrModel.revealPositionInCenterIfOutsideViewport(editorOrModel.getPosition(), 1 /* Immediate */); } else { range_2 = edits[0].range; initialSelection_1 = new selection_1.Selection(range_2.startLineNumber, range_2.startColumn, range_2.endLineNumber, range_2.endColumn); model.pushEditOperations([initialSelection_1], edits.map(function (edit) { return { text: edit.text, range: range_1.Range.lift(edit.range), forceMoveMarkers: true }; }), function (undoEdits) { for (var _i = 0, undoEdits_1 = undoEdits; _i < undoEdits_1.length; _i++) { var range_3 = undoEdits_1[_i].range; if (range_1.Range.areIntersectingOrTouching(range_3, initialSelection_1)) { return [new selection_1.Selection(range_3.startLineNumber, range_3.startColumn, range_3.endLineNumber, range_3.endColumn)]; } } return null; }); } return [2 /*return*/, true]; } }); }); } exports.formatDocumentRangeWithProvider = formatDocumentRangeWithProvider; function formatDocumentWithSelectedProvider(accessor, editorOrModel, mode, token) { return __awaiter(this, void 0, void 0, function () { var instaService, model, provider, selected; return __generator(this, function (_a) { switch (_a.label) { case 0: instaService = accessor.get(instantiation_1.IInstantiationService); model = editorBrowser_1.isCodeEditor(editorOrModel) ? editorOrModel.getModel() : editorOrModel; provider = getRealAndSyntheticDocumentFormattersOrdered(model); return [4 /*yield*/, FormattingConflicts.select(provider, model, mode)]; case 1: selected = _a.sent(); if (!selected) return [3 /*break*/, 3]; return [4 /*yield*/, instaService.invokeFunction(formatDocumentWithProvider, selected, editorOrModel, mode, token)]; case 2: _a.sent(); _a.label = 3; case 3: return [2 /*return*/]; } }); }); } exports.formatDocumentWithSelectedProvider = formatDocumentWithSelectedProvider; function formatDocumentWithProvider(accessor, provider, editorOrModel, mode, token) { return __awaiter(this, void 0, void 0, function () { var workerService, model, cts, edits, rawEdits, range, initialSelection_2; return __generator(this, function (_a) { switch (_a.label) { case 0: workerService = accessor.get(editorWorkerService_1.IEditorWorkerService); if (editorBrowser_1.isCodeEditor(editorOrModel)) { model = editorOrModel.getModel(); cts = new editorState_1.EditorStateCancellationTokenSource(editorOrModel, 1 /* Value */ | 4 /* Position */, token); } else { model = editorOrModel; cts = new editorState_1.TextModelCancellationTokenSource(editorOrModel, token); } _a.label = 1; case 1: _a.trys.push([1, , 4, 5]); return [4 /*yield*/, provider.provideDocumentFormattingEdits(model, model.getFormattingOptions(), cts.token)]; case 2: rawEdits = _a.sent(); return [4 /*yield*/, workerService.computeMoreMinimalEdits(model.uri, rawEdits)]; case 3: edits = _a.sent(); if (cts.token.isCancellationRequested) { return [2 /*return*/, true]; } return [3 /*break*/, 5]; case 4: cts.dispose(); return [7 /*endfinally*/]; case 5: if (!edits || edits.length === 0) { return [2 /*return*/, false]; } if (editorBrowser_1.isCodeEditor(editorOrModel)) { // use editor to apply edits formattingEdit_1.FormattingEdit.execute(editorOrModel, edits); if (mode !== 2 /* Silent */) { alertFormattingEdits(edits); editorOrModel.pushUndoStop(); editorOrModel.revealPositionInCenterIfOutsideViewport(editorOrModel.getPosition(), 1 /* Immediate */); } } else { range = edits[0].range; initialSelection_2 = new selection_1.Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn); model.pushEditOperations([initialSelection_2], edits.map(function (edit) { return { text: edit.text, range: range_1.Range.lift(edit.range), forceMoveMarkers: true }; }), function (undoEdits) { for (var _i = 0, undoEdits_2 = undoEdits; _i < undoEdits_2.length; _i++) { var range_4 = undoEdits_2[_i].range; if (range_1.Range.areIntersectingOrTouching(range_4, initialSelection_2)) { return [new selection_1.Selection(range_4.startLineNumber, range_4.startColumn, range_4.endLineNumber, range_4.endColumn)]; } } return null; }); } return [2 /*return*/, true]; } }); }); } exports.formatDocumentWithProvider = formatDocumentWithProvider; function getDocumentRangeFormattingEditsUntilResult(workerService, model, range, options, token) { return __awaiter(this, void 0, void 0, function () { var providers, _i, providers_1, provider, rawEdits; return __generator(this, function (_a) { switch (_a.label) { case 0: providers = modes_1.DocumentRangeFormattingEditProviderRegistry.ordered(model); _i = 0, providers_1 = providers; _a.label = 1; case 1: if (!(_i < providers_1.length)) return [3 /*break*/, 5]; provider = providers_1[_i]; return [4 /*yield*/, Promise.resolve(provider.provideDocumentRangeFormattingEdits(model, range, options, token)).catch(errors_1.onUnexpectedExternalError)]; case 2: rawEdits = _a.sent(); if (!arrays_1.isNonEmptyArray(rawEdits)) return [3 /*break*/, 4]; return [4 /*yield*/, workerService.computeMoreMinimalEdits(model.uri, rawEdits)]; case 3: return [2 /*return*/, _a.sent()]; case 4: _i++; return [3 /*break*/, 1]; case 5: return [2 /*return*/, undefined]; } }); }); } exports.getDocumentRangeFormattingEditsUntilResult = getDocumentRangeFormattingEditsUntilResult; function getDocumentFormattingEditsUntilResult(workerService, model, options, token) { return __awaiter(this, void 0, void 0, function () { var providers, _i, providers_2, provider, rawEdits; return __generator(this, function (_a) { switch (_a.label) { case 0: providers = getRealAndSyntheticDocumentFormattersOrdered(model); _i = 0, providers_2 = providers; _a.label = 1; case 1: if (!(_i < providers_2.length)) return [3 /*break*/, 5]; provider = providers_2[_i]; return [4 /*yield*/, Promise.resolve(provider.provideDocumentFormattingEdits(model, options, token)).catch(errors_1.onUnexpectedExternalError)]; case 2: rawEdits = _a.sent(); if (!arrays_1.isNonEmptyArray(rawEdits)) return [3 /*break*/, 4]; return [4 /*yield*/, workerService.computeMoreMinimalEdits(model.uri, rawEdits)]; case 3: return [2 /*return*/, _a.sent()]; case 4: _i++; return [3 /*break*/, 1]; case 5: return [2 /*return*/, undefined]; } }); }); } exports.getDocumentFormattingEditsUntilResult = getDocumentFormattingEditsUntilResult; function getOnTypeFormattingEdits(workerService, model, position, ch, options) { var providers = modes_1.OnTypeFormattingEditProviderRegistry.ordered(model); if (providers.length === 0) { return Promise.resolve(undefined); } if (providers[0].autoFormatTriggerCharacters.indexOf(ch) < 0) { return Promise.resolve(undefined); } return Promise.resolve(providers[0].provideOnTypeFormattingEdits(model, position, ch, options, cancellation_1.CancellationToken.None)).catch(errors_1.onUnexpectedExternalError).then(function (edits) { return workerService.computeMoreMinimalEdits(model.uri, edits); }); } exports.getOnTypeFormattingEdits = getOnTypeFormattingEdits; commands_1.CommandsRegistry.registerCommand('_executeFormatRangeProvider', function (accessor) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var resource = args[0], range = args[1], options = args[2]; types_1.assertType(uri_1.URI.isUri(resource)); types_1.assertType(range_1.Range.isIRange(range)); var model = accessor.get(modelService_1.IModelService).getModel(resource); if (!model) { throw errors_1.illegalArgument('resource'); } return getDocumentRangeFormattingEditsUntilResult(accessor.get(editorWorkerService_1.IEditorWorkerService), model, range_1.Range.lift(range), options, cancellation_1.CancellationToken.None); }); commands_1.CommandsRegistry.registerCommand('_executeFormatDocumentProvider', function (accessor) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var resource = args[0], options = args[1]; types_1.assertType(uri_1.URI.isUri(resource)); var model = accessor.get(modelService_1.IModelService).getModel(resource); if (!model) { throw errors_1.illegalArgument('resource'); } return getDocumentFormattingEditsUntilResult(accessor.get(editorWorkerService_1.IEditorWorkerService), model, options, cancellation_1.CancellationToken.None); }); commands_1.CommandsRegistry.registerCommand('_executeFormatOnTypeProvider', function (accessor) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var resource = args[0], position = args[1], ch = args[2], options = args[3]; types_1.assertType(uri_1.URI.isUri(resource)); types_1.assertType(position_1.Position.isIPosition(position)); types_1.assertType(typeof ch === 'string'); var model = accessor.get(modelService_1.IModelService).getModel(resource); if (!model) { throw errors_1.illegalArgument('resource'); } return getOnTypeFormattingEdits(accessor.get(editorWorkerService_1.IEditorWorkerService), model, position_1.Position.lift(position), ch, options); }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[536/*vs/editor/contrib/format/formatActions*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,26/*vs/base/common/cancellation*/,36/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,12/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,79/*vs/editor/common/core/characterClassifier*/,3/*vs/editor/common/core/range*/,23/*vs/editor/common/editorContextKeys*/,17/*vs/editor/common/modes*/,62/*vs/editor/common/services/editorWorkerService*/,535/*vs/editor/contrib/format/format*/,198/*vs/editor/contrib/format/formattingEdit*/,443/*vs/nls!vs/editor/contrib/format/formatActions*/,29/*vs/platform/commands/common/commands*/,18/*vs/platform/contextkey/common/contextkey*/,11/*vs/platform/instantiation/common/instantiation*/,10/*vs/base/common/errors*/]), function (require, exports, arrays_1, cancellation_1, keyCodes_1, lifecycle_1, editorExtensions_1, codeEditorService_1, characterClassifier_1, range_1, editorContextKeys_1, modes_1, editorWorkerService_1, format_1, formattingEdit_1, nls, commands_1, contextkey_1, instantiation_1, errors_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var FormatOnType = /** @class */ (function () { function FormatOnType(editor, _workerService) { var _this = this; this._workerService = _workerService; this._callOnDispose = new lifecycle_1.DisposableStore(); this._callOnModel = new lifecycle_1.DisposableStore(); this._editor = editor; this._callOnDispose.add(editor.onDidChangeConfiguration(function () { return _this._update(); })); this._callOnDispose.add(editor.onDidChangeModel(function () { return _this._update(); })); this._callOnDispose.add(editor.onDidChangeModelLanguage(function () { return _this._update(); })); this._callOnDispose.add(modes_1.OnTypeFormattingEditProviderRegistry.onDidChange(this._update, this)); } FormatOnType.prototype.dispose = function () { this._callOnDispose.dispose(); this._callOnModel.dispose(); }; FormatOnType.prototype._update = function () { var _this = this; // clean up this._callOnModel.clear(); // we are disabled if (!this._editor.getOption(39 /* formatOnType */)) { return; } // no model if (!this._editor.hasModel()) { return; } var model = this._editor.getModel(); // no support var support = modes_1.OnTypeFormattingEditProviderRegistry.ordered(model)[0]; if (!support || !support.autoFormatTriggerCharacters) { return; } // register typing listeners that will trigger the format var triggerChars = new characterClassifier_1.CharacterSet(); for (var _i = 0, _a = support.autoFormatTriggerCharacters; _i < _a.length; _i++) { var ch = _a[_i]; triggerChars.add(ch.charCodeAt(0)); } this._callOnModel.add(this._editor.onDidType(function (text) { var lastCharCode = text.charCodeAt(text.length - 1); if (triggerChars.has(lastCharCode)) { _this._trigger(String.fromCharCode(lastCharCode)); } })); }; FormatOnType.prototype._trigger = function (ch) { var _this = this; if (!this._editor.hasModel()) { return; } if (this._editor.getSelections().length > 1) { return; } var model = this._editor.getModel(); var position = this._editor.getPosition(); var canceled = false; // install a listener that checks if edits happens before the // position on which we format right now. If so, we won't // apply the format edits var unbind = this._editor.onDidChangeModelContent(function (e) { if (e.isFlush) { // a model.setValue() was called // cancel only once canceled = true; unbind.dispose(); return; } for (var i = 0, len = e.changes.length; i < len; i++) { var change = e.changes[i]; if (change.range.endLineNumber <= position.lineNumber) { // cancel only once canceled = true; unbind.dispose(); return; } } }); format_1.getOnTypeFormattingEdits(this._workerService, model, position, ch, model.getFormattingOptions()).then(function (edits) { unbind.dispose(); if (canceled) { return; } if (arrays_1.isNonEmptyArray(edits)) { formattingEdit_1.FormattingEdit.execute(_this._editor, edits); format_1.alertFormattingEdits(edits); } }, function (err) { unbind.dispose(); throw err; }); }; FormatOnType.ID = 'editor.contrib.autoFormat'; FormatOnType = __decorate([ __param(1, editorWorkerService_1.IEditorWorkerService) ], FormatOnType); return FormatOnType; }()); var FormatOnPaste = /** @class */ (function () { function FormatOnPaste(editor, _instantiationService) { var _this = this; this.editor = editor; this._instantiationService = _instantiationService; this._callOnDispose = new lifecycle_1.DisposableStore(); this._callOnModel = new lifecycle_1.DisposableStore(); this._callOnDispose.add(editor.onDidChangeConfiguration(function () { return _this._update(); })); this._callOnDispose.add(editor.onDidChangeModel(function () { return _this._update(); })); this._callOnDispose.add(editor.onDidChangeModelLanguage(function () { return _this._update(); })); this._callOnDispose.add(modes_1.DocumentRangeFormattingEditProviderRegistry.onDidChange(this._update, this)); } FormatOnPaste.prototype.dispose = function () { this._callOnDispose.dispose(); this._callOnModel.dispose(); }; FormatOnPaste.prototype._update = function () { var _this = this; // clean up this._callOnModel.clear(); // we are disabled if (!this.editor.getOption(38 /* formatOnPaste */)) { return; } // no model if (!this.editor.hasModel()) { return; } // no formatter if (!modes_1.DocumentRangeFormattingEditProviderRegistry.has(this.editor.getModel())) { return; } this._callOnModel.add(this.editor.onDidPaste(function (_a) { var range = _a.range; return _this._trigger(range); })); }; FormatOnPaste.prototype._trigger = function (range) { if (!this.editor.hasModel()) { return; } if (this.editor.getSelections().length > 1) { return; } this._instantiationService.invokeFunction(format_1.formatDocumentRangeWithSelectedProvider, this.editor, range, 2 /* Silent */, cancellation_1.CancellationToken.None).catch(errors_1.onUnexpectedError); }; FormatOnPaste.ID = 'editor.contrib.formatOnPaste'; FormatOnPaste = __decorate([ __param(1, instantiation_1.IInstantiationService) ], FormatOnPaste); return FormatOnPaste; }()); var FormatDocumentAction = /** @class */ (function (_super) { __extends(FormatDocumentAction, _super); function FormatDocumentAction() { return _super.call(this, { id: 'editor.action.formatDocument', label: nls.localize(0, null), alias: 'Format Document', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasDocumentFormattingProvider), kbOpts: { kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.editorTextFocus, editorContextKeys_1.EditorContextKeys.hasDocumentFormattingProvider), primary: 1024 /* Shift */ | 512 /* Alt */ | 36 /* KEY_F */, linux: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 39 /* KEY_I */ }, weight: 100 /* EditorContrib */ }, contextMenuOpts: { when: editorContextKeys_1.EditorContextKeys.hasDocumentFormattingProvider, group: '1_modification', order: 1.3 } }) || this; } FormatDocumentAction.prototype.run = function (accessor, editor) { return __awaiter(this, void 0, void 0, function () { var instaService; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!editor.hasModel()) return [3 /*break*/, 2]; instaService = accessor.get(instantiation_1.IInstantiationService); return [4 /*yield*/, instaService.invokeFunction(format_1.formatDocumentWithSelectedProvider, editor, 1 /* Explicit */, cancellation_1.CancellationToken.None)]; case 1: _a.sent(); _a.label = 2; case 2: return [2 /*return*/]; } }); }); }; return FormatDocumentAction; }(editorExtensions_1.EditorAction)); var FormatSelectionAction = /** @class */ (function (_super) { __extends(FormatSelectionAction, _super); function FormatSelectionAction() { return _super.call(this, { id: 'editor.action.formatSelection', label: nls.localize(1, null), alias: 'Format Selection', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasDocumentSelectionFormattingProvider), kbOpts: { kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.editorTextFocus, editorContextKeys_1.EditorContextKeys.hasDocumentSelectionFormattingProvider), primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 36 /* KEY_F */), weight: 100 /* EditorContrib */ }, contextMenuOpts: { when: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDocumentSelectionFormattingProvider, editorContextKeys_1.EditorContextKeys.hasNonEmptySelection), group: '1_modification', order: 1.31 } }) || this; } FormatSelectionAction.prototype.run = function (accessor, editor) { return __awaiter(this, void 0, void 0, function () { var instaService, model, range; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!editor.hasModel()) { return [2 /*return*/]; } instaService = accessor.get(instantiation_1.IInstantiationService); model = editor.getModel(); range = editor.getSelection(); if (range.isEmpty()) { range = new range_1.Range(range.startLineNumber, 1, range.startLineNumber, model.getLineMaxColumn(range.startLineNumber)); } return [4 /*yield*/, instaService.invokeFunction(format_1.formatDocumentRangeWithSelectedProvider, editor, range, 1 /* Explicit */, cancellation_1.CancellationToken.None)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; return FormatSelectionAction; }(editorExtensions_1.EditorAction)); editorExtensions_1.registerEditorContribution(FormatOnType.ID, FormatOnType); editorExtensions_1.registerEditorContribution(FormatOnPaste.ID, FormatOnPaste); editorExtensions_1.registerEditorAction(FormatDocumentAction); editorExtensions_1.registerEditorAction(FormatSelectionAction); // this is the old format action that does both (format document OR format selection) // and we keep it here such that existing keybinding configurations etc will still work commands_1.CommandsRegistry.registerCommand('editor.action.format', function (accessor) { return __awaiter(void 0, void 0, void 0, function () { var editor, commandService; return __generator(this, function (_a) { switch (_a.label) { case 0: editor = accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor(); if (!editor || !editor.hasModel()) { return [2 /*return*/]; } commandService = accessor.get(commands_1.ICommandService); if (!editor.getSelection().isEmpty()) return [3 /*break*/, 2]; return [4 /*yield*/, commandService.executeCommand('editor.action.formatDocument')]; case 1: _a.sent(); return [3 /*break*/, 4]; case 2: return [4 /*yield*/, commandService.executeCommand('editor.action.formatSelection')]; case 3: _a.sent(); _a.label = 4; case 4: return [2 /*return*/]; } }); }); }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[224/*vs/editor/contrib/gotoSymbol/goToSymbol*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,26/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,12/*vs/editor/browser/editorExtensions*/,17/*vs/editor/common/modes*/]), function (require, exports, arrays_1, cancellation_1, errors_1, editorExtensions_1, modes_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function getLocationLinks(model, position, registry, provide) { var provider = registry.ordered(model); // get results var promises = provider.map(function (provider) { return Promise.resolve(provide(provider, model, position)).then(undefined, function (err) { errors_1.onUnexpectedExternalError(err); return undefined; }); }); return Promise.all(promises) .then(arrays_1.flatten) .then(arrays_1.coalesce); } function getDefinitionsAtPosition(model, position, token) { return getLocationLinks(model, position, modes_1.DefinitionProviderRegistry, function (provider, model, position) { return provider.provideDefinition(model, position, token); }); } exports.getDefinitionsAtPosition = getDefinitionsAtPosition; function getDeclarationsAtPosition(model, position, token) { return getLocationLinks(model, position, modes_1.DeclarationProviderRegistry, function (provider, model, position) { return provider.provideDeclaration(model, position, token); }); } exports.getDeclarationsAtPosition = getDeclarationsAtPosition; function getImplementationsAtPosition(model, position, token) { return getLocationLinks(model, position, modes_1.ImplementationProviderRegistry, function (provider, model, position) { return provider.provideImplementation(model, position, token); }); } exports.getImplementationsAtPosition = getImplementationsAtPosition; function getTypeDefinitionsAtPosition(model, position, token) { return getLocationLinks(model, position, modes_1.TypeDefinitionProviderRegistry, function (provider, model, position) { return provider.provideTypeDefinition(model, position, token); }); } exports.getTypeDefinitionsAtPosition = getTypeDefinitionsAtPosition; function getReferencesAtPosition(model, position, compact, token) { var _this = this; return getLocationLinks(model, position, modes_1.ReferenceProviderRegistry, function (provider, model, position) { return __awaiter(_this, void 0, void 0, function () { var result, resultWithoutDeclaration; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, provider.provideReferences(model, position, { includeDeclaration: true }, token)]; case 1: result = _a.sent(); if (!compact || !result || result.length !== 2) { return [2 /*return*/, result]; } return [4 /*yield*/, provider.provideReferences(model, position, { includeDeclaration: false }, token)]; case 2: resultWithoutDeclaration = _a.sent(); if (resultWithoutDeclaration && resultWithoutDeclaration.length === 1) { return [2 /*return*/, resultWithoutDeclaration]; } return [2 /*return*/, result]; } }); }); }); } exports.getReferencesAtPosition = getReferencesAtPosition; editorExtensions_1.registerModelAndPositionCommand('_executeDefinitionProvider', function (model, position) { return getDefinitionsAtPosition(model, position, cancellation_1.CancellationToken.None); }); editorExtensions_1.registerModelAndPositionCommand('_executeDeclarationProvider', function (model, position) { return getDeclarationsAtPosition(model, position, cancellation_1.CancellationToken.None); }); editorExtensions_1.registerModelAndPositionCommand('_executeImplementationProvider', function (model, position) { return getImplementationsAtPosition(model, position, cancellation_1.CancellationToken.None); }); editorExtensions_1.registerModelAndPositionCommand('_executeTypeDefinitionProvider', function (model, position) { return getTypeDefinitionsAtPosition(model, position, cancellation_1.CancellationToken.None); }); editorExtensions_1.registerModelAndPositionCommand('_executeReferenceProvider', function (model, position) { return getReferencesAtPosition(model, position, false, cancellation_1.CancellationToken.None); }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[537/*vs/editor/contrib/gotoSymbol/symbolNavigation*/], __M([0/*require*/,1/*exports*/,18/*vs/platform/contextkey/common/contextkey*/,11/*vs/platform/instantiation/common/instantiation*/,83/*vs/platform/instantiation/common/extensions*/,86/*vs/platform/keybinding/common/keybindingsRegistry*/,12/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,3/*vs/editor/common/core/range*/,2/*vs/base/common/lifecycle*/,4/*vs/base/common/event*/,452/*vs/nls!vs/editor/contrib/gotoSymbol/symbolNavigation*/,34/*vs/platform/keybinding/common/keybinding*/,35/*vs/platform/notification/common/notification*/,39/*vs/base/common/resources*/]), function (require, exports, contextkey_1, instantiation_1, extensions_1, keybindingsRegistry_1, editorExtensions_1, codeEditorService_1, range_1, lifecycle_1, event_1, nls_1, keybinding_1, notification_1, resources_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ctxHasSymbols = new contextkey_1.RawContextKey('hasSymbols', false); exports.ISymbolNavigationService = instantiation_1.createDecorator('ISymbolNavigationService'); var SymbolNavigationService = /** @class */ (function () { function SymbolNavigationService(contextKeyService, _editorService, _notificationService, _keybindingService) { this._editorService = _editorService; this._notificationService = _notificationService; this._keybindingService = _keybindingService; this._currentModel = undefined; this._currentIdx = -1; this._ignoreEditorChange = false; this._ctxHasSymbols = exports.ctxHasSymbols.bindTo(contextKeyService); } SymbolNavigationService.prototype.reset = function () { this._ctxHasSymbols.reset(); lifecycle_1.dispose(this._currentState); lifecycle_1.dispose(this._currentMessage); this._currentModel = undefined; this._currentIdx = -1; }; SymbolNavigationService.prototype.put = function (anchor) { var _this = this; var refModel = anchor.parent.parent; if (refModel.references.length <= 1) { this.reset(); return; } this._currentModel = refModel; this._currentIdx = refModel.references.indexOf(anchor); this._ctxHasSymbols.set(true); this._showMessage(); var editorState = new EditorState(this._editorService); var listener = editorState.onDidChange(function (_) { if (_this._ignoreEditorChange) { return; } var editor = _this._editorService.getActiveCodeEditor(); if (!editor) { return; } var model = editor.getModel(); var position = editor.getPosition(); if (!model || !position) { return; } var seenUri = false; var seenPosition = false; for (var _i = 0, _a = refModel.references; _i < _a.length; _i++) { var reference = _a[_i]; if (resources_1.isEqual(reference.uri, model.uri)) { seenUri = true; seenPosition = seenPosition || range_1.Range.containsPosition(reference.range, position); } else if (seenUri) { break; } } if (!seenUri || !seenPosition) { _this.reset(); } }); this._currentState = lifecycle_1.combinedDisposable(editorState, listener); }; SymbolNavigationService.prototype.revealNext = function (source) { var _this = this; if (!this._currentModel) { return Promise.resolve(); } // get next result and advance this._currentIdx += 1; this._currentIdx %= this._currentModel.references.length; var reference = this._currentModel.references[this._currentIdx]; // status this._showMessage(); // open editor, ignore events while that happens this._ignoreEditorChange = true; return this._editorService.openCodeEditor({ resource: reference.uri, options: { selection: range_1.Range.collapseToStart(reference.range), revealInCenterIfOutsideViewport: true } }, source).finally(function () { _this._ignoreEditorChange = false; }); }; SymbolNavigationService.prototype._showMessage = function () { lifecycle_1.dispose(this._currentMessage); var kb = this._keybindingService.lookupKeybinding('editor.gotoNextSymbolFromResult'); var message = kb ? nls_1.localize(0, null, this._currentIdx + 1, this._currentModel.references.length, kb.getLabel()) : nls_1.localize(1, null, this._currentIdx + 1, this._currentModel.references.length); this._currentMessage = this._notificationService.status(message); }; SymbolNavigationService = __decorate([ __param(0, contextkey_1.IContextKeyService), __param(1, codeEditorService_1.ICodeEditorService), __param(2, notification_1.INotificationService), __param(3, keybinding_1.IKeybindingService) ], SymbolNavigationService); return SymbolNavigationService; }()); extensions_1.registerSingleton(exports.ISymbolNavigationService, SymbolNavigationService, true); editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_1, _super); function class_1() { return _super.call(this, { id: 'editor.gotoNextSymbolFromResult', precondition: exports.ctxHasSymbols, kbOpts: { weight: 100 /* EditorContrib */, primary: 70 /* F12 */ } }) || this; } class_1.prototype.runEditorCommand = function (accessor, editor) { return accessor.get(exports.ISymbolNavigationService).revealNext(editor); }; return class_1; }(editorExtensions_1.EditorCommand))); keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'editor.gotoNextSymbolFromResult.cancel', weight: 100 /* EditorContrib */, when: exports.ctxHasSymbols, primary: 9 /* Escape */, handler: function (accessor) { accessor.get(exports.ISymbolNavigationService).reset(); } }); // var EditorState = /** @class */ (function () { function EditorState(editorService) { this._listener = new Map(); this._disposables = new lifecycle_1.DisposableStore(); this._onDidChange = new event_1.Emitter(); this.onDidChange = this._onDidChange.event; this._disposables.add(editorService.onCodeEditorRemove(this._onDidRemoveEditor, this)); this._disposables.add(editorService.onCodeEditorAdd(this._onDidAddEditor, this)); editorService.listCodeEditors().forEach(this._onDidAddEditor, this); } EditorState.prototype.dispose = function () { this._disposables.dispose(); this._onDidChange.dispose(); this._listener.forEach(lifecycle_1.dispose); }; EditorState.prototype._onDidAddEditor = function (editor) { var _this = this; this._listener.set(editor, lifecycle_1.combinedDisposable(editor.onDidChangeCursorPosition(function (_) { return _this._onDidChange.fire({ editor: editor }); }), editor.onDidChangeModelContent(function (_) { return _this._onDidChange.fire({ editor: editor }); }))); }; EditorState.prototype._onDidRemoveEditor = function (editor) { lifecycle_1.dispose(this._listener.get(editor)); this._listener.delete(editor); }; EditorState = __decorate([ __param(0, codeEditorService_1.ICodeEditorService) ], EditorState); return EditorState; }()); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[538/*vs/editor/contrib/hover/getHover*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,26/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,12/*vs/editor/browser/editorExtensions*/,17/*vs/editor/common/modes*/]), function (require, exports, arrays_1, cancellation_1, errors_1, editorExtensions_1, modes_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function getHover(model, position, token) { var supports = modes_1.HoverProviderRegistry.ordered(model); var promises = supports.map(function (support) { return Promise.resolve(support.provideHover(model, position, token)).then(function (hover) { return hover && isValid(hover) ? hover : undefined; }, function (err) { errors_1.onUnexpectedExternalError(err); return undefined; }); }); return Promise.all(promises).then(arrays_1.coalesce); } exports.getHover = getHover; editorExtensions_1.registerModelAndPositionCommand('_executeHoverProvider', function (model, position) { return getHover(model, position, cancellation_1.CancellationToken.None); }); function isValid(result) { var hasRange = (typeof result.range !== 'undefined'); var hasHtmlContent = typeof result.contents !== 'undefined' && result.contents && result.contents.length > 0; return hasRange && hasHtmlContent; } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[539/*vs/editor/contrib/linesOperations/linesOperations*/], __M([0/*require*/,1/*exports*/,456/*vs/nls!vs/editor/contrib/linesOperations/linesOperations*/,36/*vs/base/common/keyCodes*/,164/*vs/editor/browser/controller/coreCommands*/,12/*vs/editor/browser/editorExtensions*/,80/*vs/editor/common/commands/replaceCommand*/,338/*vs/editor/common/commands/trimTrailingWhitespaceCommand*/,159/*vs/editor/common/controller/cursorTypeOperations*/,58/*vs/editor/common/core/editOperation*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,23/*vs/editor/common/editorContextKeys*/,386/*vs/editor/contrib/linesOperations/copyLinesCommand*/,492/*vs/editor/contrib/linesOperations/moveLinesCommand*/,387/*vs/editor/contrib/linesOperations/sortLinesCommand*/]), function (require, exports, nls, keyCodes_1, coreCommands_1, editorExtensions_1, replaceCommand_1, trimTrailingWhitespaceCommand_1, cursorTypeOperations_1, editOperation_1, position_1, range_1, selection_1, editorContextKeys_1, copyLinesCommand_1, moveLinesCommand_1, sortLinesCommand_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // copy lines var AbstractCopyLinesAction = /** @class */ (function (_super) { __extends(AbstractCopyLinesAction, _super); function AbstractCopyLinesAction(down, opts) { var _this = _super.call(this, opts) || this; _this.down = down; return _this; } AbstractCopyLinesAction.prototype.run = function (_accessor, editor) { var commands = []; var selections = editor.getSelections() || []; for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) { var selection = selections_1[_i]; commands.push(new copyLinesCommand_1.CopyLinesCommand(selection, this.down)); } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); }; return AbstractCopyLinesAction; }(editorExtensions_1.EditorAction)); var CopyLinesUpAction = /** @class */ (function (_super) { __extends(CopyLinesUpAction, _super); function CopyLinesUpAction() { return _super.call(this, false, { id: 'editor.action.copyLinesUpAction', label: nls.localize(0, null), alias: 'Copy Line Up', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 512 /* Alt */ | 1024 /* Shift */ | 16 /* UpArrow */, linux: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 1024 /* Shift */ | 16 /* UpArrow */ }, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 25 /* MenubarSelectionMenu */, group: '2_line', title: nls.localize(1, null), order: 1 } }) || this; } return CopyLinesUpAction; }(AbstractCopyLinesAction)); var CopyLinesDownAction = /** @class */ (function (_super) { __extends(CopyLinesDownAction, _super); function CopyLinesDownAction() { return _super.call(this, true, { id: 'editor.action.copyLinesDownAction', label: nls.localize(2, null), alias: 'Copy Line Down', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 512 /* Alt */ | 1024 /* Shift */ | 18 /* DownArrow */, linux: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 1024 /* Shift */ | 18 /* DownArrow */ }, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 25 /* MenubarSelectionMenu */, group: '2_line', title: nls.localize(3, null), order: 2 } }) || this; } return CopyLinesDownAction; }(AbstractCopyLinesAction)); var DuplicateSelectionAction = /** @class */ (function (_super) { __extends(DuplicateSelectionAction, _super); function DuplicateSelectionAction() { return _super.call(this, { id: 'editor.action.duplicateSelection', label: nls.localize(4, null), alias: 'Duplicate Selection', precondition: editorContextKeys_1.EditorContextKeys.writable, menuOpts: { menuId: 25 /* MenubarSelectionMenu */, group: '2_line', title: nls.localize(5, null), order: 5 } }) || this; } DuplicateSelectionAction.prototype.run = function (accessor, editor, args) { if (!editor.hasModel()) { return; } var commands = []; var selections = editor.getSelections(); var model = editor.getModel(); for (var _i = 0, selections_2 = selections; _i < selections_2.length; _i++) { var selection = selections_2[_i]; if (selection.isEmpty()) { commands.push(new copyLinesCommand_1.CopyLinesCommand(selection, true)); } else { var insertSelection = new selection_1.Selection(selection.endLineNumber, selection.endColumn, selection.endLineNumber, selection.endColumn); commands.push(new replaceCommand_1.ReplaceCommandThatSelectsText(insertSelection, model.getValueInRange(selection))); } } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); }; return DuplicateSelectionAction; }(editorExtensions_1.EditorAction)); exports.DuplicateSelectionAction = DuplicateSelectionAction; // move lines var AbstractMoveLinesAction = /** @class */ (function (_super) { __extends(AbstractMoveLinesAction, _super); function AbstractMoveLinesAction(down, opts) { var _this = _super.call(this, opts) || this; _this.down = down; return _this; } AbstractMoveLinesAction.prototype.run = function (_accessor, editor) { var commands = []; var selections = editor.getSelections() || []; var autoIndent = editor.getOption(8 /* autoIndent */); for (var _i = 0, selections_3 = selections; _i < selections_3.length; _i++) { var selection = selections_3[_i]; commands.push(new moveLinesCommand_1.MoveLinesCommand(selection, this.down, autoIndent)); } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); }; return AbstractMoveLinesAction; }(editorExtensions_1.EditorAction)); var MoveLinesUpAction = /** @class */ (function (_super) { __extends(MoveLinesUpAction, _super); function MoveLinesUpAction() { return _super.call(this, false, { id: 'editor.action.moveLinesUpAction', label: nls.localize(6, null), alias: 'Move Line Up', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 512 /* Alt */ | 16 /* UpArrow */, linux: { primary: 512 /* Alt */ | 16 /* UpArrow */ }, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 25 /* MenubarSelectionMenu */, group: '2_line', title: nls.localize(7, null), order: 3 } }) || this; } return MoveLinesUpAction; }(AbstractMoveLinesAction)); var MoveLinesDownAction = /** @class */ (function (_super) { __extends(MoveLinesDownAction, _super); function MoveLinesDownAction() { return _super.call(this, true, { id: 'editor.action.moveLinesDownAction', label: nls.localize(8, null), alias: 'Move Line Down', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 512 /* Alt */ | 18 /* DownArrow */, linux: { primary: 512 /* Alt */ | 18 /* DownArrow */ }, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 25 /* MenubarSelectionMenu */, group: '2_line', title: nls.localize(9, null), order: 4 } }) || this; } return MoveLinesDownAction; }(AbstractMoveLinesAction)); var AbstractSortLinesAction = /** @class */ (function (_super) { __extends(AbstractSortLinesAction, _super); function AbstractSortLinesAction(descending, opts) { var _this = _super.call(this, opts) || this; _this.descending = descending; return _this; } AbstractSortLinesAction.prototype.run = function (_accessor, editor) { var selections = editor.getSelections() || []; for (var _i = 0, selections_4 = selections; _i < selections_4.length; _i++) { var selection = selections_4[_i]; if (!sortLinesCommand_1.SortLinesCommand.canRun(editor.getModel(), selection, this.descending)) { return; } } var commands = []; for (var i = 0, len = selections.length; i < len; i++) { commands[i] = new sortLinesCommand_1.SortLinesCommand(selections[i], this.descending); } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); }; return AbstractSortLinesAction; }(editorExtensions_1.EditorAction)); exports.AbstractSortLinesAction = AbstractSortLinesAction; var SortLinesAscendingAction = /** @class */ (function (_super) { __extends(SortLinesAscendingAction, _super); function SortLinesAscendingAction() { return _super.call(this, false, { id: 'editor.action.sortLinesAscending', label: nls.localize(10, null), alias: 'Sort Lines Ascending', precondition: editorContextKeys_1.EditorContextKeys.writable }) || this; } return SortLinesAscendingAction; }(AbstractSortLinesAction)); exports.SortLinesAscendingAction = SortLinesAscendingAction; var SortLinesDescendingAction = /** @class */ (function (_super) { __extends(SortLinesDescendingAction, _super); function SortLinesDescendingAction() { return _super.call(this, true, { id: 'editor.action.sortLinesDescending', label: nls.localize(11, null), alias: 'Sort Lines Descending', precondition: editorContextKeys_1.EditorContextKeys.writable }) || this; } return SortLinesDescendingAction; }(AbstractSortLinesAction)); exports.SortLinesDescendingAction = SortLinesDescendingAction; var TrimTrailingWhitespaceAction = /** @class */ (function (_super) { __extends(TrimTrailingWhitespaceAction, _super); function TrimTrailingWhitespaceAction() { return _super.call(this, { id: TrimTrailingWhitespaceAction.ID, label: nls.localize(12, null), alias: 'Trim Trailing Whitespace', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 54 /* KEY_X */), weight: 100 /* EditorContrib */ } }) || this; } TrimTrailingWhitespaceAction.prototype.run = function (_accessor, editor, args) { var cursors = []; if (args.reason === 'auto-save') { // See https://github.com/editorconfig/editorconfig-vscode/issues/47 // It is very convenient for the editor config extension to invoke this action. // So, if we get a reason:'auto-save' passed in, let's preserve cursor positions. cursors = (editor.getSelections() || []).map(function (s) { return new position_1.Position(s.positionLineNumber, s.positionColumn); }); } var selection = editor.getSelection(); if (selection === null) { return; } var command = new trimTrailingWhitespaceCommand_1.TrimTrailingWhitespaceCommand(selection, cursors); editor.pushUndoStop(); editor.executeCommands(this.id, [command]); editor.pushUndoStop(); }; TrimTrailingWhitespaceAction.ID = 'editor.action.trimTrailingWhitespace'; return TrimTrailingWhitespaceAction; }(editorExtensions_1.EditorAction)); exports.TrimTrailingWhitespaceAction = TrimTrailingWhitespaceAction; var DeleteLinesAction = /** @class */ (function (_super) { __extends(DeleteLinesAction, _super); function DeleteLinesAction() { return _super.call(this, { id: 'editor.action.deleteLines', label: nls.localize(13, null), alias: 'Delete Line', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 41 /* KEY_K */, weight: 100 /* EditorContrib */ } }) || this; } DeleteLinesAction.prototype.run = function (_accessor, editor) { if (!editor.hasModel()) { return; } var ops = this._getLinesToRemove(editor); var model = editor.getModel(); if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) { // Model is empty return; } var linesDeleted = 0; var edits = []; var cursorState = []; for (var i = 0, len = ops.length; i < len; i++) { var op = ops[i]; var startLineNumber = op.startLineNumber; var endLineNumber = op.endLineNumber; var startColumn = 1; var endColumn = model.getLineMaxColumn(endLineNumber); if (endLineNumber < model.getLineCount()) { endLineNumber += 1; endColumn = 1; } else if (startLineNumber > 1) { startLineNumber -= 1; startColumn = model.getLineMaxColumn(startLineNumber); } edits.push(editOperation_1.EditOperation.replace(new selection_1.Selection(startLineNumber, startColumn, endLineNumber, endColumn), '')); cursorState.push(new selection_1.Selection(startLineNumber - linesDeleted, op.positionColumn, startLineNumber - linesDeleted, op.positionColumn)); linesDeleted += (op.endLineNumber - op.startLineNumber + 1); } editor.pushUndoStop(); editor.executeEdits(this.id, edits, cursorState); editor.pushUndoStop(); }; DeleteLinesAction.prototype._getLinesToRemove = function (editor) { // Construct delete operations var operations = editor.getSelections().map(function (s) { var endLineNumber = s.endLineNumber; if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) { endLineNumber -= 1; } return { startLineNumber: s.startLineNumber, selectionStartColumn: s.selectionStartColumn, endLineNumber: endLineNumber, positionColumn: s.positionColumn }; }); // Sort delete operations operations.sort(function (a, b) { if (a.startLineNumber === b.startLineNumber) { return a.endLineNumber - b.endLineNumber; } return a.startLineNumber - b.startLineNumber; }); // Merge delete operations which are adjacent or overlapping var mergedOperations = []; var previousOperation = operations[0]; for (var i = 1; i < operations.length; i++) { if (previousOperation.endLineNumber + 1 >= operations[i].startLineNumber) { // Merge current operations into the previous one previousOperation.endLineNumber = operations[i].endLineNumber; } else { // Push previous operation mergedOperations.push(previousOperation); previousOperation = operations[i]; } } // Push the last operation mergedOperations.push(previousOperation); return mergedOperations; }; return DeleteLinesAction; }(editorExtensions_1.EditorAction)); exports.DeleteLinesAction = DeleteLinesAction; var IndentLinesAction = /** @class */ (function (_super) { __extends(IndentLinesAction, _super); function IndentLinesAction() { return _super.call(this, { id: 'editor.action.indentLines', label: nls.localize(14, null), alias: 'Indent Line', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 89 /* US_CLOSE_SQUARE_BRACKET */, weight: 100 /* EditorContrib */ } }) || this; } IndentLinesAction.prototype.run = function (_accessor, editor) { var cursors = editor._getCursors(); if (!cursors) { return; } editor.pushUndoStop(); editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.indent(cursors.context.config, editor.getModel(), editor.getSelections())); editor.pushUndoStop(); }; return IndentLinesAction; }(editorExtensions_1.EditorAction)); exports.IndentLinesAction = IndentLinesAction; var OutdentLinesAction = /** @class */ (function (_super) { __extends(OutdentLinesAction, _super); function OutdentLinesAction() { return _super.call(this, { id: 'editor.action.outdentLines', label: nls.localize(15, null), alias: 'Outdent Line', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 87 /* US_OPEN_SQUARE_BRACKET */, weight: 100 /* EditorContrib */ } }) || this; } OutdentLinesAction.prototype.run = function (_accessor, editor) { coreCommands_1.CoreEditingCommands.Outdent.runEditorCommand(_accessor, editor, null); }; return OutdentLinesAction; }(editorExtensions_1.EditorAction)); var InsertLineBeforeAction = /** @class */ (function (_super) { __extends(InsertLineBeforeAction, _super); function InsertLineBeforeAction() { return _super.call(this, { id: 'editor.action.insertLineBefore', label: nls.localize(16, null), alias: 'Insert Line Above', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 3 /* Enter */, weight: 100 /* EditorContrib */ } }) || this; } InsertLineBeforeAction.prototype.run = function (_accessor, editor) { var cursors = editor._getCursors(); if (!cursors) { return; } editor.pushUndoStop(); editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.lineInsertBefore(cursors.context.config, editor.getModel(), editor.getSelections())); }; return InsertLineBeforeAction; }(editorExtensions_1.EditorAction)); exports.InsertLineBeforeAction = InsertLineBeforeAction; var InsertLineAfterAction = /** @class */ (function (_super) { __extends(InsertLineAfterAction, _super); function InsertLineAfterAction() { return _super.call(this, { id: 'editor.action.insertLineAfter', label: nls.localize(17, null), alias: 'Insert Line Below', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 3 /* Enter */, weight: 100 /* EditorContrib */ } }) || this; } InsertLineAfterAction.prototype.run = function (_accessor, editor) { var cursors = editor._getCursors(); if (!cursors) { return; } editor.pushUndoStop(); editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.lineInsertAfter(cursors.context.config, editor.getModel(), editor.getSelections())); }; return InsertLineAfterAction; }(editorExtensions_1.EditorAction)); exports.InsertLineAfterAction = InsertLineAfterAction; var AbstractDeleteAllToBoundaryAction = /** @class */ (function (_super) { __extends(AbstractDeleteAllToBoundaryAction, _super); function AbstractDeleteAllToBoundaryAction() { return _super !== null && _super.apply(this, arguments) || this; } AbstractDeleteAllToBoundaryAction.prototype.run = function (_accessor, editor) { if (!editor.hasModel()) { return; } var primaryCursor = editor.getSelection(); var rangesToDelete = this._getRangesToDelete(editor); // merge overlapping selections var effectiveRanges = []; for (var i = 0, count = rangesToDelete.length - 1; i < count; i++) { var range = rangesToDelete[i]; var nextRange = rangesToDelete[i + 1]; if (range_1.Range.intersectRanges(range, nextRange) === null) { effectiveRanges.push(range); } else { rangesToDelete[i + 1] = range_1.Range.plusRange(range, nextRange); } } effectiveRanges.push(rangesToDelete[rangesToDelete.length - 1]); var endCursorState = this._getEndCursorState(primaryCursor, effectiveRanges); var edits = effectiveRanges.map(function (range) { return editOperation_1.EditOperation.replace(range, ''); }); editor.pushUndoStop(); editor.executeEdits(this.id, edits, endCursorState); editor.pushUndoStop(); }; return AbstractDeleteAllToBoundaryAction; }(editorExtensions_1.EditorAction)); exports.AbstractDeleteAllToBoundaryAction = AbstractDeleteAllToBoundaryAction; var DeleteAllLeftAction = /** @class */ (function (_super) { __extends(DeleteAllLeftAction, _super); function DeleteAllLeftAction() { return _super.call(this, { id: 'deleteAllLeft', label: nls.localize(18, null), alias: 'Delete All Left', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 2048 /* CtrlCmd */ | 1 /* Backspace */ }, weight: 100 /* EditorContrib */ } }) || this; } DeleteAllLeftAction.prototype._getEndCursorState = function (primaryCursor, rangesToDelete) { var endPrimaryCursor = null; var endCursorState = []; var deletedLines = 0; rangesToDelete.forEach(function (range) { var endCursor; if (range.endColumn === 1 && deletedLines > 0) { var newStartLine = range.startLineNumber - deletedLines; endCursor = new selection_1.Selection(newStartLine, range.startColumn, newStartLine, range.startColumn); } else { endCursor = new selection_1.Selection(range.startLineNumber, range.startColumn, range.startLineNumber, range.startColumn); } deletedLines += range.endLineNumber - range.startLineNumber; if (range.intersectRanges(primaryCursor)) { endPrimaryCursor = endCursor; } else { endCursorState.push(endCursor); } }); if (endPrimaryCursor) { endCursorState.unshift(endPrimaryCursor); } return endCursorState; }; DeleteAllLeftAction.prototype._getRangesToDelete = function (editor) { var selections = editor.getSelections(); if (selections === null) { return []; } var rangesToDelete = selections; var model = editor.getModel(); if (model === null) { return []; } rangesToDelete.sort(range_1.Range.compareRangesUsingStarts); rangesToDelete = rangesToDelete.map(function (selection) { if (selection.isEmpty()) { if (selection.startColumn === 1) { var deleteFromLine = Math.max(1, selection.startLineNumber - 1); var deleteFromColumn = selection.startLineNumber === 1 ? 1 : model.getLineContent(deleteFromLine).length + 1; return new range_1.Range(deleteFromLine, deleteFromColumn, selection.startLineNumber, 1); } else { return new range_1.Range(selection.startLineNumber, 1, selection.startLineNumber, selection.startColumn); } } else { return new range_1.Range(selection.startLineNumber, 1, selection.endLineNumber, selection.endColumn); } }); return rangesToDelete; }; return DeleteAllLeftAction; }(AbstractDeleteAllToBoundaryAction)); exports.DeleteAllLeftAction = DeleteAllLeftAction; var DeleteAllRightAction = /** @class */ (function (_super) { __extends(DeleteAllRightAction, _super); function DeleteAllRightAction() { return _super.call(this, { id: 'deleteAllRight', label: nls.localize(19, null), alias: 'Delete All Right', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 /* WinCtrl */ | 41 /* KEY_K */, secondary: [2048 /* CtrlCmd */ | 20 /* Delete */] }, weight: 100 /* EditorContrib */ } }) || this; } DeleteAllRightAction.prototype._getEndCursorState = function (primaryCursor, rangesToDelete) { var endPrimaryCursor = null; var endCursorState = []; for (var i = 0, len = rangesToDelete.length, offset = 0; i < len; i++) { var range = rangesToDelete[i]; var endCursor = new selection_1.Selection(range.startLineNumber - offset, range.startColumn, range.startLineNumber - offset, range.startColumn); if (range.intersectRanges(primaryCursor)) { endPrimaryCursor = endCursor; } else { endCursorState.push(endCursor); } } if (endPrimaryCursor) { endCursorState.unshift(endPrimaryCursor); } return endCursorState; }; DeleteAllRightAction.prototype._getRangesToDelete = function (editor) { var model = editor.getModel(); if (model === null) { return []; } var selections = editor.getSelections(); if (selections === null) { return []; } var rangesToDelete = selections.map(function (sel) { if (sel.isEmpty()) { var maxColumn = model.getLineMaxColumn(sel.startLineNumber); if (sel.startColumn === maxColumn) { return new range_1.Range(sel.startLineNumber, sel.startColumn, sel.startLineNumber + 1, 1); } else { return new range_1.Range(sel.startLineNumber, sel.startColumn, sel.startLineNumber, maxColumn); } } return sel; }); rangesToDelete.sort(range_1.Range.compareRangesUsingStarts); return rangesToDelete; }; return DeleteAllRightAction; }(AbstractDeleteAllToBoundaryAction)); exports.DeleteAllRightAction = DeleteAllRightAction; var JoinLinesAction = /** @class */ (function (_super) { __extends(JoinLinesAction, _super); function JoinLinesAction() { return _super.call(this, { id: 'editor.action.joinLines', label: nls.localize(20, null), alias: 'Join Lines', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 0, mac: { primary: 256 /* WinCtrl */ | 40 /* KEY_J */ }, weight: 100 /* EditorContrib */ } }) || this; } JoinLinesAction.prototype.run = function (_accessor, editor) { var selections = editor.getSelections(); if (selections === null) { return; } var primaryCursor = editor.getSelection(); if (primaryCursor === null) { return; } selections.sort(range_1.Range.compareRangesUsingStarts); var reducedSelections = []; var lastSelection = selections.reduce(function (previousValue, currentValue) { if (previousValue.isEmpty()) { if (previousValue.endLineNumber === currentValue.startLineNumber) { if (primaryCursor.equalsSelection(previousValue)) { primaryCursor = currentValue; } return currentValue; } if (currentValue.startLineNumber > previousValue.endLineNumber + 1) { reducedSelections.push(previousValue); return currentValue; } else { return new selection_1.Selection(previousValue.startLineNumber, previousValue.startColumn, currentValue.endLineNumber, currentValue.endColumn); } } else { if (currentValue.startLineNumber > previousValue.endLineNumber) { reducedSelections.push(previousValue); return currentValue; } else { return new selection_1.Selection(previousValue.startLineNumber, previousValue.startColumn, currentValue.endLineNumber, currentValue.endColumn); } } }); reducedSelections.push(lastSelection); var model = editor.getModel(); if (model === null) { return; } var edits = []; var endCursorState = []; var endPrimaryCursor = primaryCursor; var lineOffset = 0; for (var i = 0, len = reducedSelections.length; i < len; i++) { var selection = reducedSelections[i]; var startLineNumber = selection.startLineNumber; var startColumn = 1; var columnDeltaOffset = 0; var endLineNumber = void 0, endColumn = void 0; var selectionEndPositionOffset = model.getLineContent(selection.endLineNumber).length - selection.endColumn; if (selection.isEmpty() || selection.startLineNumber === selection.endLineNumber) { var position = selection.getStartPosition(); if (position.lineNumber < model.getLineCount()) { endLineNumber = startLineNumber + 1; endColumn = model.getLineMaxColumn(endLineNumber); } else { endLineNumber = position.lineNumber; endColumn = model.getLineMaxColumn(position.lineNumber); } } else { endLineNumber = selection.endLineNumber; endColumn = model.getLineMaxColumn(endLineNumber); } var trimmedLinesContent = model.getLineContent(startLineNumber); for (var i_1 = startLineNumber + 1; i_1 <= endLineNumber; i_1++) { var lineText = model.getLineContent(i_1); var firstNonWhitespaceIdx = model.getLineFirstNonWhitespaceColumn(i_1); if (firstNonWhitespaceIdx >= 1) { var insertSpace = true; if (trimmedLinesContent === '') { insertSpace = false; } if (insertSpace && (trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === ' ' || trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === '\t')) { insertSpace = false; trimmedLinesContent = trimmedLinesContent.replace(/[\s\uFEFF\xA0]+$/g, ' '); } var lineTextWithoutIndent = lineText.substr(firstNonWhitespaceIdx - 1); trimmedLinesContent += (insertSpace ? ' ' : '') + lineTextWithoutIndent; if (insertSpace) { columnDeltaOffset = lineTextWithoutIndent.length + 1; } else { columnDeltaOffset = lineTextWithoutIndent.length; } } else { columnDeltaOffset = 0; } } var deleteSelection = new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn); if (!deleteSelection.isEmpty()) { var resultSelection = void 0; if (selection.isEmpty()) { edits.push(editOperation_1.EditOperation.replace(deleteSelection, trimmedLinesContent)); resultSelection = new selection_1.Selection(deleteSelection.startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1, startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1); } else { if (selection.startLineNumber === selection.endLineNumber) { edits.push(editOperation_1.EditOperation.replace(deleteSelection, trimmedLinesContent)); resultSelection = new selection_1.Selection(selection.startLineNumber - lineOffset, selection.startColumn, selection.endLineNumber - lineOffset, selection.endColumn); } else { edits.push(editOperation_1.EditOperation.replace(deleteSelection, trimmedLinesContent)); resultSelection = new selection_1.Selection(selection.startLineNumber - lineOffset, selection.startColumn, selection.startLineNumber - lineOffset, trimmedLinesContent.length - selectionEndPositionOffset); } } if (range_1.Range.intersectRanges(deleteSelection, primaryCursor) !== null) { endPrimaryCursor = resultSelection; } else { endCursorState.push(resultSelection); } } lineOffset += deleteSelection.endLineNumber - deleteSelection.startLineNumber; } endCursorState.unshift(endPrimaryCursor); editor.pushUndoStop(); editor.executeEdits(this.id, edits, endCursorState); editor.pushUndoStop(); }; return JoinLinesAction; }(editorExtensions_1.EditorAction)); exports.JoinLinesAction = JoinLinesAction; var TransposeAction = /** @class */ (function (_super) { __extends(TransposeAction, _super); function TransposeAction() { return _super.call(this, { id: 'editor.action.transpose', label: nls.localize(21, null), alias: 'Transpose characters around the cursor', precondition: editorContextKeys_1.EditorContextKeys.writable }) || this; } TransposeAction.prototype.run = function (_accessor, editor) { var selections = editor.getSelections(); if (selections === null) { return; } var model = editor.getModel(); if (model === null) { return; } var commands = []; for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; if (!selection.isEmpty()) { continue; } var cursor = selection.getStartPosition(); var maxColumn = model.getLineMaxColumn(cursor.lineNumber); if (cursor.column >= maxColumn) { if (cursor.lineNumber === model.getLineCount()) { continue; } // The cursor is at the end of current line and current line is not empty // then we transpose the character before the cursor and the line break if there is any following line. var deleteSelection = new range_1.Range(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1); var chars = model.getValueInRange(deleteSelection).split('').reverse().join(''); commands.push(new replaceCommand_1.ReplaceCommand(new selection_1.Selection(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1), chars)); } else { var deleteSelection = new range_1.Range(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber, cursor.column + 1); var chars = model.getValueInRange(deleteSelection).split('').reverse().join(''); commands.push(new replaceCommand_1.ReplaceCommandThatPreservesSelection(deleteSelection, chars, new selection_1.Selection(cursor.lineNumber, cursor.column + 1, cursor.lineNumber, cursor.column + 1))); } } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); }; return TransposeAction; }(editorExtensions_1.EditorAction)); exports.TransposeAction = TransposeAction; var AbstractCaseAction = /** @class */ (function (_super) { __extends(AbstractCaseAction, _super); function AbstractCaseAction() { return _super !== null && _super.apply(this, arguments) || this; } AbstractCaseAction.prototype.run = function (_accessor, editor) { var selections = editor.getSelections(); if (selections === null) { return; } var model = editor.getModel(); if (model === null) { return; } var wordSeparators = editor.getOption(96 /* wordSeparators */); var commands = []; for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; if (selection.isEmpty()) { var cursor = selection.getStartPosition(); var word = model.getWordAtPosition(cursor); if (!word) { continue; } var wordRange = new range_1.Range(cursor.lineNumber, word.startColumn, cursor.lineNumber, word.endColumn); var text = model.getValueInRange(wordRange); commands.push(new replaceCommand_1.ReplaceCommandThatPreservesSelection(wordRange, this._modifyText(text, wordSeparators), new selection_1.Selection(cursor.lineNumber, cursor.column, cursor.lineNumber, cursor.column))); } else { var text = model.getValueInRange(selection); commands.push(new replaceCommand_1.ReplaceCommandThatPreservesSelection(selection, this._modifyText(text, wordSeparators), selection)); } } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); }; return AbstractCaseAction; }(editorExtensions_1.EditorAction)); exports.AbstractCaseAction = AbstractCaseAction; var UpperCaseAction = /** @class */ (function (_super) { __extends(UpperCaseAction, _super); function UpperCaseAction() { return _super.call(this, { id: 'editor.action.transformToUppercase', label: nls.localize(22, null), alias: 'Transform to Uppercase', precondition: editorContextKeys_1.EditorContextKeys.writable }) || this; } UpperCaseAction.prototype._modifyText = function (text, wordSeparators) { return text.toLocaleUpperCase(); }; return UpperCaseAction; }(AbstractCaseAction)); exports.UpperCaseAction = UpperCaseAction; var LowerCaseAction = /** @class */ (function (_super) { __extends(LowerCaseAction, _super); function LowerCaseAction() { return _super.call(this, { id: 'editor.action.transformToLowercase', label: nls.localize(23, null), alias: 'Transform to Lowercase', precondition: editorContextKeys_1.EditorContextKeys.writable }) || this; } LowerCaseAction.prototype._modifyText = function (text, wordSeparators) { return text.toLocaleLowerCase(); }; return LowerCaseAction; }(AbstractCaseAction)); exports.LowerCaseAction = LowerCaseAction; var TitleCaseAction = /** @class */ (function (_super) { __extends(TitleCaseAction, _super); function TitleCaseAction() { return _super.call(this, { id: 'editor.action.transformToTitlecase', label: nls.localize(24, null), alias: 'Transform to Title Case', precondition: editorContextKeys_1.EditorContextKeys.writable }) || this; } TitleCaseAction.prototype._modifyText = function (text, wordSeparators) { var separators = '\r\n\t ' + wordSeparators; var excludedChars = separators.split(''); var title = ''; var startUpperCase = true; for (var i = 0; i < text.length; i++) { var currentChar = text[i]; if (excludedChars.indexOf(currentChar) >= 0) { startUpperCase = true; title += currentChar; } else if (startUpperCase) { startUpperCase = false; title += currentChar.toLocaleUpperCase(); } else { title += currentChar.toLocaleLowerCase(); } } return title; }; return TitleCaseAction; }(AbstractCaseAction)); exports.TitleCaseAction = TitleCaseAction; editorExtensions_1.registerEditorAction(CopyLinesUpAction); editorExtensions_1.registerEditorAction(CopyLinesDownAction); editorExtensions_1.registerEditorAction(DuplicateSelectionAction); editorExtensions_1.registerEditorAction(MoveLinesUpAction); editorExtensions_1.registerEditorAction(MoveLinesDownAction); editorExtensions_1.registerEditorAction(SortLinesAscendingAction); editorExtensions_1.registerEditorAction(SortLinesDescendingAction); editorExtensions_1.registerEditorAction(TrimTrailingWhitespaceAction); editorExtensions_1.registerEditorAction(DeleteLinesAction); editorExtensions_1.registerEditorAction(IndentLinesAction); editorExtensions_1.registerEditorAction(OutdentLinesAction); editorExtensions_1.registerEditorAction(InsertLineBeforeAction); editorExtensions_1.registerEditorAction(InsertLineAfterAction); editorExtensions_1.registerEditorAction(DeleteAllLeftAction); editorExtensions_1.registerEditorAction(DeleteAllRightAction); editorExtensions_1.registerEditorAction(JoinLinesAction); editorExtensions_1.registerEditorAction(TransposeAction); editorExtensions_1.registerEditorAction(UpperCaseAction); editorExtensions_1.registerEditorAction(LowerCaseAction); editorExtensions_1.registerEditorAction(TitleCaseAction); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[165/*vs/editor/contrib/parameterHints/provideSignatureHelp*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,10/*vs/base/common/errors*/,12/*vs/editor/browser/editorExtensions*/,17/*vs/editor/common/modes*/,18/*vs/platform/contextkey/common/contextkey*/,26/*vs/base/common/cancellation*/]), function (require, exports, async_1, errors_1, editorExtensions_1, modes, contextkey_1, cancellation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Context = { Visible: new contextkey_1.RawContextKey('parameterHintsVisible', false), MultipleSignatures: new contextkey_1.RawContextKey('parameterHintsMultipleSignatures', false), }; function provideSignatureHelp(model, position, context, token) { var supports = modes.SignatureHelpProviderRegistry.ordered(model); return async_1.first(supports.map(function (support) { return function () { return Promise.resolve(support.provideSignatureHelp(model, position, token, context)) .catch(function (e) { return errors_1.onUnexpectedExternalError(e); }); }; })); } exports.provideSignatureHelp = provideSignatureHelp; editorExtensions_1.registerDefaultLanguageCommand('_executeSignatureHelpProvider', function (model, position, args) { return __awaiter(void 0, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, provideSignatureHelp(model, position, { triggerKind: modes.SignatureHelpTriggerKind.Invoke, isRetrigger: false, triggerCharacter: args['triggerCharacter'] }, cancellation_1.CancellationToken.None)]; case 1: result = _a.sent(); if (!result) { return [2 /*return*/, undefined]; } setTimeout(function () { return result.dispose(); }, 0); return [2 /*return*/, result.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[540/*vs/editor/contrib/parameterHints/parameterHintsModel*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,10/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,79/*vs/editor/common/core/characterClassifier*/,17/*vs/editor/common/modes*/,165/*vs/editor/contrib/parameterHints/provideSignatureHelp*/]), function (require, exports, async_1, errors_1, event_1, lifecycle_1, characterClassifier_1, modes, provideSignatureHelp_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ParameterHintState; (function (ParameterHintState) { ParameterHintState.Default = { type: 0 /* Default */ }; var Pending = /** @class */ (function () { function Pending(request) { this.request = request; this.type = 2 /* Pending */; } return Pending; }()); ParameterHintState.Pending = Pending; var Active = /** @class */ (function () { function Active(hints) { this.hints = hints; this.type = 1 /* Active */; } return Active; }()); ParameterHintState.Active = Active; })(ParameterHintState || (ParameterHintState = {})); var ParameterHintsModel = /** @class */ (function (_super) { __extends(ParameterHintsModel, _super); function ParameterHintsModel(editor, delay) { if (delay === void 0) { delay = ParameterHintsModel.DEFAULT_DELAY; } var _this = _super.call(this) || this; _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.onDidChangeConfiguration(function () { return _this.onEditorConfigurationChange(); })); _this._register(_this.editor.onDidChangeModel(function (e) { return _this.onModelChanged(); })); _this._register(_this.editor.onDidChangeModelLanguage(function (_) { return _this.onModelChanged(); })); _this._register(_this.editor.onDidChangeCursorSelection(function (e) { return _this.onCursorChange(e); })); _this._register(_this.editor.onDidChangeModelContent(function (e) { return _this.onModelContentChange(); })); _this._register(modes.SignatureHelpProviderRegistry.onDidChange(_this.onModelChanged, _this)); _this._register(_this.editor.onDidType(function (text) { return _this.onDidType(text); })); _this.onEditorConfigurationChange(); _this.onModelChanged(); return _this; } Object.defineProperty(ParameterHintsModel.prototype, "state", { get: function () { return this._state; }, set: function (value) { if (this._state.type === 2 /* Pending */) { this._state.request.cancel(); } this._state = value; }, enumerable: true, configurable: true }); ParameterHintsModel.prototype.cancel = function (silent) { if (silent === void 0) { silent = false; } this.state = ParameterHintState.Default; this.throttledDelayer.cancel(); if (!silent) { this._onChangedHints.fire(undefined); } }; ParameterHintsModel.prototype.trigger = function (context, delay) { var _this = this; var model = this.editor.getModel(); if (!model || !modes.SignatureHelpProviderRegistry.has(model)) { return; } var triggerId = ++this.triggerId; this._pendingTriggers.push(context); this.throttledDelayer.trigger(function () { return _this.doTrigger(triggerId); }, delay) .catch(errors_1.onUnexpectedError); }; ParameterHintsModel.prototype.next = function () { if (this.state.type !== 1 /* Active */) { return; } var length = this.state.hints.signatures.length; var activeSignature = this.state.hints.activeSignature; var last = (activeSignature % length) === (length - 1); var cycle = this.editor.getOption(64 /* 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); }; ParameterHintsModel.prototype.previous = function () { if (this.state.type !== 1 /* Active */) { return; } var length = this.state.hints.signatures.length; var activeSignature = this.state.hints.activeSignature; var first = activeSignature === 0; var cycle = this.editor.getOption(64 /* 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); }; ParameterHintsModel.prototype.updateActiveSignature = function (activeSignature) { if (this.state.type !== 1 /* Active */) { return; } this.state = new ParameterHintState.Active(__assign(__assign({}, this.state.hints), { activeSignature: activeSignature })); this._onChangedHints.fire(this.state.hints); }; ParameterHintsModel.prototype.doTrigger = function (triggerId) { return __awaiter(this, void 0, void 0, function () { var isRetrigger, activeSignatureHelp, context, triggerContext, model, position, result, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: isRetrigger = this.state.type === 1 /* Active */ || this.state.type === 2 /* Pending */; activeSignatureHelp = this.state.type === 1 /* Active */ ? this.state.hints : undefined; this.cancel(true); if (this._pendingTriggers.length === 0) { return [2 /*return*/, false]; } context = this._pendingTriggers.reduce(mergeTriggerContexts); this._pendingTriggers = []; triggerContext = { triggerKind: context.triggerKind, triggerCharacter: context.triggerCharacter, isRetrigger: isRetrigger, activeSignatureHelp: activeSignatureHelp }; if (!this.editor.hasModel()) { return [2 /*return*/, false]; } model = this.editor.getModel(); position = this.editor.getPosition(); this.state = new ParameterHintState.Pending(async_1.createCancelablePromise(function (token) { return provideSignatureHelp_1.provideSignatureHelp(model, position, triggerContext, token); })); _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, this.state.request]; case 2: result = _a.sent(); // Check that we are still resolving the correct signature help if (triggerId !== this.triggerId) { result === null || result === void 0 ? void 0 : result.dispose(); return [2 /*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 [2 /*return*/, false]; } else { this.state = new ParameterHintState.Active(result.value); this._lastSignatureHelpResult.value = result; this._onChangedHints.fire(this.state.hints); return [2 /*return*/, true]; } return [3 /*break*/, 4]; case 3: error_1 = _a.sent(); if (triggerId === this.triggerId) { this.state = ParameterHintState.Default; } errors_1.onUnexpectedError(error_1); return [2 /*return*/, false]; case 4: return [2 /*return*/]; } }); }); }; Object.defineProperty(ParameterHintsModel.prototype, "isTriggered", { get: function () { return this.state.type === 1 /* Active */ || this.state.type === 2 /* Pending */ || this.throttledDelayer.isTriggered(); }, enumerable: true, configurable: true }); ParameterHintsModel.prototype.onModelChanged = function () { this.cancel(); // Update trigger characters this.triggerChars = new characterClassifier_1.CharacterSet(); this.retriggerChars = new characterClassifier_1.CharacterSet(); var model = this.editor.getModel(); if (!model) { return; } for (var _i = 0, _a = modes.SignatureHelpProviderRegistry.ordered(model); _i < _a.length; _i++) { var support = _a[_i]; for (var _b = 0, _c = support.signatureHelpTriggerCharacters || []; _b < _c.length; _b++) { var ch = _c[_b]; this.triggerChars.add(ch.charCodeAt(0)); // All trigger characters are also considered retrigger characters this.retriggerChars.add(ch.charCodeAt(0)); } for (var _d = 0, _e = support.signatureHelpRetriggerCharacters || []; _d < _e.length; _d++) { var ch = _e[_d]; this.retriggerChars.add(ch.charCodeAt(0)); } } }; ParameterHintsModel.prototype.onDidType = function (text) { if (!this.triggerOnType) { return; } var lastCharIndex = text.length - 1; var 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), }); } }; ParameterHintsModel.prototype.onCursorChange = function (e) { if (e.source === 'mouse') { this.cancel(); } else if (this.isTriggered) { this.trigger({ triggerKind: modes.SignatureHelpTriggerKind.ContentChange }); } }; ParameterHintsModel.prototype.onModelContentChange = function () { if (this.isTriggered) { this.trigger({ triggerKind: modes.SignatureHelpTriggerKind.ContentChange }); } }; ParameterHintsModel.prototype.onEditorConfigurationChange = function () { this.triggerOnType = this.editor.getOption(64 /* parameterHints */).enabled; if (!this.triggerOnType) { this.cancel(); } }; ParameterHintsModel.prototype.dispose = function () { this.cancel(true); _super.prototype.dispose.call(this); }; ParameterHintsModel.DEFAULT_DELAY = 120; // ms return ParameterHintsModel; }(lifecycle_1.Disposable)); exports.ParameterHintsModel = ParameterHintsModel; 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[541/*vs/editor/contrib/smartSelect/smartSelect*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,26/*vs/base/common/cancellation*/,12/*vs/editor/browser/editorExtensions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,23/*vs/editor/common/editorContextKeys*/,17/*vs/editor/common/modes*/,465/*vs/nls!vs/editor/contrib/smartSelect/smartSelect*/,2/*vs/base/common/lifecycle*/,388/*vs/editor/contrib/smartSelect/wordSelections*/,202/*vs/editor/contrib/smartSelect/bracketSelections*/,29/*vs/platform/commands/common/commands*/,10/*vs/base/common/errors*/]), function (require, exports, arrays, cancellation_1, editorExtensions_1, position_1, range_1, selection_1, editorContextKeys_1, modes, nls, lifecycle_1, wordSelections_1, bracketSelections_1, commands_1, errors_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var SelectionRanges = /** @class */ (function () { function SelectionRanges(index, ranges) { this.index = index; this.ranges = ranges; } SelectionRanges.prototype.mov = function (fwd) { var index = this.index + (fwd ? 1 : -1); if (index < 0 || index >= this.ranges.length) { return this; } var res = new SelectionRanges(index, this.ranges); if (res.ranges[index].equalsRange(this.ranges[this.index])) { // next range equals this range, retry with next-next return res.mov(fwd); } return res; }; return SelectionRanges; }()); var SmartSelectController = /** @class */ (function () { function SmartSelectController(editor) { this._ignoreSelection = false; this._editor = editor; } SmartSelectController.get = function (editor) { return editor.getContribution(SmartSelectController.ID); }; SmartSelectController.prototype.dispose = function () { lifecycle_1.dispose(this._selectionListener); }; SmartSelectController.prototype.run = function (forward) { var _this = this; if (!this._editor.hasModel()) { return; } var selections = this._editor.getSelections(); var model = this._editor.getModel(); if (!modes.SelectionRangeRegistry.has(model)) { return; } var promise = Promise.resolve(undefined); if (!this._state) { promise = provideSelectionRanges(model, selections.map(function (s) { return s.getPosition(); }), cancellation_1.CancellationToken.None).then(function (ranges) { if (!arrays.isNonEmptyArray(ranges) || ranges.length !== selections.length) { // invalid result return; } if (!_this._editor.hasModel() || !arrays.equals(_this._editor.getSelections(), selections, function (a, b) { return a.equalsSelection(b); })) { // invalid editor state return; } var _loop_1 = function (i) { ranges[i] = ranges[i].filter(function (range) { // filter ranges inside the selection return range.containsPosition(selections[i].getStartPosition()) && range.containsPosition(selections[i].getEndPosition()); }); // prepend current selection ranges[i].unshift(selections[i]); }; for (var i = 0; i < ranges.length; i++) { _loop_1(i); } _this._state = ranges.map(function (ranges) { return new SelectionRanges(0, ranges); }); // listen to caret move and forget about state lifecycle_1.dispose(_this._selectionListener); _this._selectionListener = _this._editor.onDidChangeCursorPosition(function () { if (!_this._ignoreSelection) { lifecycle_1.dispose(_this._selectionListener); _this._state = undefined; } }); }); } return promise.then(function () { if (!_this._state) { // no state return; } _this._state = _this._state.map(function (state) { return state.mov(forward); }); var selections = _this._state.map(function (state) { return selection_1.Selection.fromPositions(state.ranges[state.index].getStartPosition(), state.ranges[state.index].getEndPosition()); }); _this._ignoreSelection = true; try { _this._editor.setSelections(selections); } finally { _this._ignoreSelection = false; } }); }; SmartSelectController.ID = 'editor.contrib.smartSelectController'; return SmartSelectController; }()); var AbstractSmartSelect = /** @class */ (function (_super) { __extends(AbstractSmartSelect, _super); function AbstractSmartSelect(forward, opts) { var _this = _super.call(this, opts) || this; _this._forward = forward; return _this; } AbstractSmartSelect.prototype.run = function (_accessor, editor) { return __awaiter(this, void 0, void 0, function () { var controller; return __generator(this, function (_a) { switch (_a.label) { case 0: controller = SmartSelectController.get(editor); if (!controller) return [3 /*break*/, 2]; return [4 /*yield*/, controller.run(this._forward)]; case 1: _a.sent(); _a.label = 2; case 2: return [2 /*return*/]; } }); }); }; return AbstractSmartSelect; }(editorExtensions_1.EditorAction)); var GrowSelectionAction = /** @class */ (function (_super) { __extends(GrowSelectionAction, _super); function GrowSelectionAction() { return _super.call(this, true, { id: 'editor.action.smartSelect.expand', label: nls.localize(0, null), alias: 'Expand Selection', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 1024 /* Shift */ | 512 /* Alt */ | 17 /* RightArrow */, mac: { primary: 2048 /* CtrlCmd */ | 256 /* WinCtrl */ | 1024 /* Shift */ | 17 /* RightArrow */, secondary: [256 /* WinCtrl */ | 1024 /* Shift */ | 17 /* RightArrow */], }, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 25 /* MenubarSelectionMenu */, group: '1_basic', title: nls.localize(1, null), order: 2 } }) || this; } return GrowSelectionAction; }(AbstractSmartSelect)); // renamed command id commands_1.CommandsRegistry.registerCommandAlias('editor.action.smartSelect.grow', 'editor.action.smartSelect.expand'); var ShrinkSelectionAction = /** @class */ (function (_super) { __extends(ShrinkSelectionAction, _super); function ShrinkSelectionAction() { return _super.call(this, false, { id: 'editor.action.smartSelect.shrink', label: nls.localize(2, null), alias: 'Shrink Selection', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 1024 /* Shift */ | 512 /* Alt */ | 15 /* LeftArrow */, mac: { primary: 2048 /* CtrlCmd */ | 256 /* WinCtrl */ | 1024 /* Shift */ | 15 /* LeftArrow */, secondary: [256 /* WinCtrl */ | 1024 /* Shift */ | 15 /* LeftArrow */], }, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 25 /* MenubarSelectionMenu */, group: '1_basic', title: nls.localize(3, null), order: 3 } }) || this; } return ShrinkSelectionAction; }(AbstractSmartSelect)); editorExtensions_1.registerEditorContribution(SmartSelectController.ID, SmartSelectController); editorExtensions_1.registerEditorAction(GrowSelectionAction); editorExtensions_1.registerEditorAction(ShrinkSelectionAction); // word selection modes.SelectionRangeRegistry.register('*', new wordSelections_1.WordSelectionRangeProvider()); function provideSelectionRanges(model, positions, token) { var providers = modes.SelectionRangeRegistry.all(model); if (providers.length === 1) { // add word selection and bracket selection when no provider exists providers.unshift(new bracketSelections_1.BracketSelectionRangeProvider()); } var work = []; var allRawRanges = []; for (var _i = 0, providers_1 = providers; _i < providers_1.length; _i++) { var provider = providers_1[_i]; work.push(Promise.resolve(provider.provideSelectionRanges(model, positions, token)).then(function (allProviderRanges) { if (arrays.isNonEmptyArray(allProviderRanges) && allProviderRanges.length === positions.length) { for (var i = 0; i < positions.length; i++) { if (!allRawRanges[i]) { allRawRanges[i] = []; } for (var _i = 0, _a = allProviderRanges[i]; _i < _a.length; _i++) { var oneProviderRanges = _a[_i]; if (range_1.Range.isIRange(oneProviderRanges.range) && range_1.Range.containsPosition(oneProviderRanges.range, positions[i])) { allRawRanges[i].push(range_1.Range.lift(oneProviderRanges.range)); } } } } }, errors_1.onUnexpectedExternalError)); } return Promise.all(work).then(function () { return allRawRanges.map(function (oneRawRanges) { if (oneRawRanges.length === 0) { return []; } // sort all by start/end position oneRawRanges.sort(function (a, b) { if (position_1.Position.isBefore(a.getStartPosition(), b.getStartPosition())) { return 1; } else if (position_1.Position.isBefore(b.getStartPosition(), a.getStartPosition())) { return -1; } else if (position_1.Position.isBefore(a.getEndPosition(), b.getEndPosition())) { return -1; } else if (position_1.Position.isBefore(b.getEndPosition(), a.getEndPosition())) { return 1; } else { return 0; } }); // remove ranges that don't contain the former range or that are equal to the // former range var oneRanges = []; var last; for (var _i = 0, oneRawRanges_1 = oneRawRanges; _i < oneRawRanges_1.length; _i++) { var range = oneRawRanges_1[_i]; if (!last || (range_1.Range.containsRange(range, last) && !range_1.Range.equalsRange(range, last))) { oneRanges.push(range); last = range; } } // add ranges that expand trivia at line starts and ends whenever a range // wraps onto the a new line var oneRangesWithTrivia = [oneRanges[0]]; for (var i = 1; i < oneRanges.length; i++) { var prev = oneRanges[i - 1]; var cur = oneRanges[i]; if (cur.startLineNumber !== prev.startLineNumber || cur.endLineNumber !== prev.endLineNumber) { // add line/block range without leading/failing whitespace var rangeNoWhitespace = new range_1.Range(prev.startLineNumber, model.getLineFirstNonWhitespaceColumn(prev.startLineNumber), prev.endLineNumber, model.getLineLastNonWhitespaceColumn(prev.endLineNumber)); if (rangeNoWhitespace.containsRange(prev) && !rangeNoWhitespace.equalsRange(prev) && cur.containsRange(rangeNoWhitespace) && !cur.equalsRange(rangeNoWhitespace)) { oneRangesWithTrivia.push(rangeNoWhitespace); } // add line/block range var rangeFull = new range_1.Range(prev.startLineNumber, 1, prev.endLineNumber, model.getLineMaxColumn(prev.endLineNumber)); if (rangeFull.containsRange(prev) && !rangeFull.equalsRange(rangeNoWhitespace) && cur.containsRange(rangeFull) && !cur.equalsRange(rangeFull)) { oneRangesWithTrivia.push(rangeFull); } } oneRangesWithTrivia.push(cur); } return oneRangesWithTrivia; }); }); } exports.provideSelectionRanges = provideSelectionRanges; editorExtensions_1.registerModelCommand('_executeSelectionRangeProvider', function (model) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var positions = args[0]; return provideSelectionRanges(model, positions, cancellation_1.CancellationToken.None); }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[120/*vs/editor/contrib/suggest/suggest*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,31/*vs/base/common/objects*/,10/*vs/base/common/errors*/,12/*vs/editor/browser/editorExtensions*/,17/*vs/editor/common/modes*/,13/*vs/editor/common/core/position*/,18/*vs/platform/contextkey/common/contextkey*/,26/*vs/base/common/cancellation*/,3/*vs/editor/common/core/range*/,61/*vs/base/common/filters*/,2/*vs/base/common/lifecycle*/]), function (require, exports, async_1, objects_1, errors_1, editorExtensions_1, modes, position_1, contextkey_1, cancellation_1, range_1, filters_1, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Context = { Visible: new contextkey_1.RawContextKey('suggestWidgetVisible', false), MultipleSuggestions: new contextkey_1.RawContextKey('suggestWidgetMultipleSuggestions', false), MakesTextEdit: new contextkey_1.RawContextKey('suggestionMakesTextEdit', true), AcceptSuggestionsOnEnter: new contextkey_1.RawContextKey('acceptSuggestionOnEnter', true) }; var CompletionItem = /** @class */ (function () { function CompletionItem(position, completion, container, provider, model) { var _this = this; this.position = position; this.completion = completion; this.container = container; this.provider = provider; this.isResolved = false; // sorting, filtering this.score = filters_1.FuzzyScore.Default; this.distance = 0; this.textLabel = typeof completion.label === 'string' ? completion.label : completion.label.name; // ensure lower-variants (perf) this.labelLow = this.textLabel.toLowerCase(); this.sortTextLow = completion.sortText && completion.sortText.toLowerCase(); this.filterTextLow = completion.filterText && completion.filterText.toLowerCase(); // normalize ranges if (range_1.Range.isIRange(completion.range)) { this.editStart = new position_1.Position(completion.range.startLineNumber, completion.range.startColumn); this.editInsertEnd = new position_1.Position(completion.range.endLineNumber, completion.range.endColumn); this.editReplaceEnd = new position_1.Position(completion.range.endLineNumber, completion.range.endColumn); } else { this.editStart = new position_1.Position(completion.range.insert.startLineNumber, completion.range.insert.startColumn); this.editInsertEnd = new position_1.Position(completion.range.insert.endLineNumber, completion.range.insert.endColumn); this.editReplaceEnd = new position_1.Position(completion.range.replace.endLineNumber, completion.range.replace.endColumn); } // create the suggestion resolver var resolveCompletionItem = provider.resolveCompletionItem; if (typeof resolveCompletionItem !== 'function') { this.resolve = function () { return Promise.resolve(); }; this.isResolved = true; } else { var cached_1; this.resolve = function (token) { if (!cached_1) { cached_1 = Promise.resolve(resolveCompletionItem.call(provider, model, position, completion, token)).then(function (value) { objects_1.assign(completion, value); _this.isResolved = true; }, function (err) { if (errors_1.isPromiseCanceledError(err)) { // the IPC queue will reject the request with the // cancellation error -> reset cached cached_1 = undefined; } }); token.onCancellationRequested(function () { if (!_this.isResolved) { // cancellation after the request has been // dispatched -> reset cache cached_1 = undefined; } }); } return cached_1; }; } } return CompletionItem; }()); exports.CompletionItem = CompletionItem; var CompletionOptions = /** @class */ (function () { function CompletionOptions(snippetSortOrder, kindFilter, providerFilter) { if (snippetSortOrder === void 0) { snippetSortOrder = 2 /* Bottom */; } if (kindFilter === void 0) { kindFilter = new Set(); } if (providerFilter === void 0) { providerFilter = new Set(); } this.snippetSortOrder = snippetSortOrder; this.kindFilter = kindFilter; this.providerFilter = providerFilter; } CompletionOptions.default = new CompletionOptions(); return CompletionOptions; }()); exports.CompletionOptions = CompletionOptions; var _snippetSuggestSupport; function getSnippetSuggestSupport() { return _snippetSuggestSupport; } exports.getSnippetSuggestSupport = getSnippetSuggestSupport; function provideSuggestionItems(model, position, options, context, token) { if (options === void 0) { options = CompletionOptions.default; } if (context === void 0) { context = { triggerKind: 0 /* Invoke */ }; } if (token === void 0) { token = cancellation_1.CancellationToken.None; } var word = model.getWordAtPosition(position); var defaultReplaceRange = word ? new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn) : range_1.Range.fromPositions(position); var defaultInsertRange = defaultReplaceRange.setEndPosition(position.lineNumber, position.column); // const wordUntil = model.getWordUntilPosition(position); // const defaultRange = new Range(position.lineNumber, wordUntil.startColumn, position.lineNumber, wordUntil.endColumn); position = position.clone(); // get provider groups, always add snippet suggestion provider var supports = modes.CompletionProviderRegistry.orderedGroups(model); // add snippets provider unless turned off if (!options.kindFilter.has(25 /* Snippet */) && _snippetSuggestSupport) { supports.unshift([_snippetSuggestSupport]); } var allSuggestions = []; var disposables = new lifecycle_1.DisposableStore(); var hasResult = false; // add suggestions from contributed providers - providers are ordered in groups of // equal score and once a group produces a result the process stops var factory = supports.map(function (supports) { return function () { // for each support in the group ask for suggestions return Promise.all(supports.map(function (provider) { if (options.providerFilter.size > 0 && !options.providerFilter.has(provider)) { return undefined; } return Promise.resolve(provider.provideCompletionItems(model, position, context, token)).then(function (container) { var len = allSuggestions.length; if (container) { for (var _i = 0, _a = container.suggestions || []; _i < _a.length; _i++) { var suggestion = _a[_i]; if (!options.kindFilter.has(suggestion.kind)) { // fill in default range when missing if (!suggestion.range) { suggestion.range = { insert: defaultInsertRange, replace: defaultReplaceRange }; } // fill in default sortText when missing if (!suggestion.sortText) { suggestion.sortText = typeof suggestion.label === 'string' ? suggestion.label : suggestion.label.name; } allSuggestions.push(new CompletionItem(position, suggestion, container, provider, model)); } } if (lifecycle_1.isDisposable(container)) { disposables.add(container); } } if (len !== allSuggestions.length && provider !== _snippetSuggestSupport) { hasResult = true; } }, errors_1.onUnexpectedExternalError); })); }; }); var result = async_1.first(factory, function () { // stop on result or cancellation return hasResult || token.isCancellationRequested; }).then(function () { if (token.isCancellationRequested) { disposables.dispose(); return Promise.reject(errors_1.canceled()); } return allSuggestions.sort(getSuggestionComparator(options.snippetSortOrder)); }); // result.then(items => { // console.log(model.getWordUntilPosition(position), items.map(item => `${item.suggestion.label}, type=${item.suggestion.type}, incomplete?${item.container.incomplete}, overwriteBefore=${item.suggestion.overwriteBefore}`)); // return items; // }, err => { // console.warn(model.getWordUntilPosition(position), err); // }); return result; } exports.provideSuggestionItems = provideSuggestionItems; function defaultComparator(a, b) { // check with 'sortText' if (a.sortTextLow && b.sortTextLow) { if (a.sortTextLow < b.sortTextLow) { return -1; } else if (a.sortTextLow > b.sortTextLow) { return 1; } } // check with 'label' if (a.completion.label < b.completion.label) { return -1; } else if (a.completion.label > b.completion.label) { return 1; } // check with 'type' return a.completion.kind - b.completion.kind; } function snippetUpComparator(a, b) { if (a.completion.kind !== b.completion.kind) { if (a.completion.kind === 25 /* Snippet */) { return -1; } else if (b.completion.kind === 25 /* Snippet */) { return 1; } } return defaultComparator(a, b); } function snippetDownComparator(a, b) { if (a.completion.kind !== b.completion.kind) { if (a.completion.kind === 25 /* Snippet */) { return 1; } else if (b.completion.kind === 25 /* Snippet */) { return -1; } } return defaultComparator(a, b); } var _snippetComparators = new Map(); _snippetComparators.set(0 /* Top */, snippetUpComparator); _snippetComparators.set(2 /* Bottom */, snippetDownComparator); _snippetComparators.set(1 /* Inline */, defaultComparator); function getSuggestionComparator(snippetConfig) { return _snippetComparators.get(snippetConfig); } exports.getSuggestionComparator = getSuggestionComparator; editorExtensions_1.registerDefaultLanguageCommand('_executeCompletionItemProvider', function (model, position, args) { return __awaiter(void 0, void 0, void 0, function () { var result, disposables, resolving, maxItemsToResolve, items, _i, items_1, item; return __generator(this, function (_a) { switch (_a.label) { case 0: result = { incomplete: false, suggestions: [] }; disposables = new lifecycle_1.DisposableStore(); resolving = []; maxItemsToResolve = args['maxItemsToResolve'] || 0; return [4 /*yield*/, provideSuggestionItems(model, position)]; case 1: items = _a.sent(); for (_i = 0, items_1 = items; _i < items_1.length; _i++) { item = items_1[_i]; if (resolving.length < maxItemsToResolve) { resolving.push(item.resolve(cancellation_1.CancellationToken.None)); } result.incomplete = result.incomplete || item.container.incomplete; result.suggestions.push(item.completion); if (lifecycle_1.isDisposable(item.container)) { disposables.add(item.container); } } _a.label = 2; case 2: _a.trys.push([2, , 4, 5]); return [4 /*yield*/, Promise.all(resolving)]; case 3: _a.sent(); return [2 /*return*/, result]; case 4: setTimeout(function () { return disposables.dispose(); }, 100); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }); var _provider = new /** @class */ (function () { function class_1() { this.onlyOnceSuggestions = []; } class_1.prototype.provideCompletionItems = function () { var suggestions = this.onlyOnceSuggestions.slice(0); var result = { suggestions: suggestions }; this.onlyOnceSuggestions.length = 0; return result; }; return class_1; }()); modes.CompletionProviderRegistry.register('*', _provider); function showSimpleSuggestions(editor, suggestions) { setTimeout(function () { var _a; (_a = _provider.onlyOnceSuggestions).push.apply(_a, suggestions); editor.getContribution('editor.contrib.suggestController').triggerSuggest(new Set().add(_provider)); }, 0); } exports.showSimpleSuggestions = showSimpleSuggestions; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[225/*vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/], __M([0/*require*/,1/*exports*/,469/*vs/nls!vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/,50/*vs/base/browser/ui/aria/aria*/,12/*vs/editor/browser/editorExtensions*/,163/*vs/editor/common/config/commonEditorConfig*/]), function (require, exports, nls, aria_1, editorExtensions_1, commonEditorConfig_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ToggleTabFocusModeAction = /** @class */ (function (_super) { __extends(ToggleTabFocusModeAction, _super); function ToggleTabFocusModeAction() { return _super.call(this, { id: ToggleTabFocusModeAction.ID, label: nls.localize(0, null), alias: 'Toggle Tab Key Moves Focus', precondition: undefined, kbOpts: { kbExpr: null, primary: 2048 /* CtrlCmd */ | 43 /* KEY_M */, mac: { primary: 256 /* WinCtrl */ | 1024 /* Shift */ | 43 /* KEY_M */ }, weight: 100 /* EditorContrib */ } }) || this; } ToggleTabFocusModeAction.prototype.run = function (accessor, editor) { var oldValue = commonEditorConfig_1.TabFocus.getTabFocusMode(); var newValue = !oldValue; commonEditorConfig_1.TabFocus.setTabFocusMode(newValue); if (newValue) { aria_1.alert(nls.localize(1, null)); } else { aria_1.alert(nls.localize(2, null)); } }; ToggleTabFocusModeAction.ID = 'editor.action.toggleTabFocusMode'; return ToggleTabFocusModeAction; }(editorExtensions_1.EditorAction)); exports.ToggleTabFocusModeAction = ToggleTabFocusModeAction; editorExtensions_1.registerEditorAction(ToggleTabFocusModeAction); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[542/*vs/editor/contrib/tokenization/tokenization*/], __M([0/*require*/,1/*exports*/,470/*vs/nls!vs/editor/contrib/tokenization/tokenization*/,12/*vs/editor/browser/editorExtensions*/,132/*vs/base/common/stopwatch*/]), function (require, exports, nls, editorExtensions_1, stopwatch_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ForceRetokenizeAction = /** @class */ (function (_super) { __extends(ForceRetokenizeAction, _super); function ForceRetokenizeAction() { return _super.call(this, { id: 'editor.action.forceRetokenize', label: nls.localize(0, null), alias: 'Developer: Force Retokenize', precondition: undefined }) || this; } ForceRetokenizeAction.prototype.run = function (accessor, editor) { if (!editor.hasModel()) { return; } var model = editor.getModel(); model.resetTokenization(); var sw = new stopwatch_1.StopWatch(true); model.forceTokenization(model.getLineCount()); sw.stop(); console.log("tokenization took " + sw.elapsed()); }; return ForceRetokenizeAction; }(editorExtensions_1.EditorAction)); editorExtensions_1.registerEditorAction(ForceRetokenizeAction); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[226/*vs/editor/contrib/wordOperations/wordOperations*/], __M([0/*require*/,1/*exports*/,12/*vs/editor/browser/editorExtensions*/,80/*vs/editor/common/commands/replaceCommand*/,40/*vs/editor/common/controller/cursorCommon*/,160/*vs/editor/common/controller/cursorWordOperations*/,89/*vs/editor/common/controller/wordCharacterClassifier*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,23/*vs/editor/common/editorContextKeys*/,64/*vs/platform/accessibility/common/accessibility*/,18/*vs/platform/contextkey/common/contextkey*/,33/*vs/editor/common/config/editorOptions*/]), function (require, exports, editorExtensions_1, replaceCommand_1, cursorCommon_1, cursorWordOperations_1, wordCharacterClassifier_1, position_1, range_1, selection_1, editorContextKeys_1, accessibility_1, contextkey_1, editorOptions_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MoveWordCommand = /** @class */ (function (_super) { __extends(MoveWordCommand, _super); function MoveWordCommand(opts) { var _this = _super.call(this, opts) || this; _this._inSelectionMode = opts.inSelectionMode; _this._wordNavigationType = opts.wordNavigationType; return _this; } MoveWordCommand.prototype.runEditorCommand = function (accessor, editor, args) { var _this = this; if (!editor.hasModel()) { return; } var wordSeparators = wordCharacterClassifier_1.getMapForWordSeparators(editor.getOption(96 /* wordSeparators */)); var model = editor.getModel(); var selections = editor.getSelections(); var result = selections.map(function (sel) { var inPosition = new position_1.Position(sel.positionLineNumber, sel.positionColumn); var outPosition = _this._move(wordSeparators, model, inPosition, _this._wordNavigationType); return _this._moveTo(sel, outPosition, _this._inSelectionMode); }); editor._getCursors().setStates('moveWordCommand', 0 /* NotSet */, result.map(function (r) { return cursorCommon_1.CursorState.fromModelSelection(r); })); if (result.length === 1) { var pos = new position_1.Position(result[0].positionLineNumber, result[0].positionColumn); editor.revealPosition(pos, 0 /* Smooth */); } }; MoveWordCommand.prototype._moveTo = function (from, to, inSelectionMode) { if (inSelectionMode) { // move just position return new selection_1.Selection(from.selectionStartLineNumber, from.selectionStartColumn, to.lineNumber, to.column); } else { // move everything return new selection_1.Selection(to.lineNumber, to.column, to.lineNumber, to.column); } }; return MoveWordCommand; }(editorExtensions_1.EditorCommand)); exports.MoveWordCommand = MoveWordCommand; var WordLeftCommand = /** @class */ (function (_super) { __extends(WordLeftCommand, _super); function WordLeftCommand() { return _super !== null && _super.apply(this, arguments) || this; } WordLeftCommand.prototype._move = function (wordSeparators, model, position, wordNavigationType) { return cursorWordOperations_1.WordOperations.moveWordLeft(wordSeparators, model, position, wordNavigationType); }; return WordLeftCommand; }(MoveWordCommand)); exports.WordLeftCommand = WordLeftCommand; var WordRightCommand = /** @class */ (function (_super) { __extends(WordRightCommand, _super); function WordRightCommand() { return _super !== null && _super.apply(this, arguments) || this; } WordRightCommand.prototype._move = function (wordSeparators, model, position, wordNavigationType) { return cursorWordOperations_1.WordOperations.moveWordRight(wordSeparators, model, position, wordNavigationType); }; return WordRightCommand; }(MoveWordCommand)); exports.WordRightCommand = WordRightCommand; var CursorWordStartLeft = /** @class */ (function (_super) { __extends(CursorWordStartLeft, _super); function CursorWordStartLeft() { return _super.call(this, { inSelectionMode: false, wordNavigationType: 0 /* WordStart */, id: 'cursorWordStartLeft', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 15 /* LeftArrow */, mac: { primary: 512 /* Alt */ | 15 /* LeftArrow */ }, weight: 100 /* EditorContrib */ } }) || this; } return CursorWordStartLeft; }(WordLeftCommand)); exports.CursorWordStartLeft = CursorWordStartLeft; var CursorWordEndLeft = /** @class */ (function (_super) { __extends(CursorWordEndLeft, _super); function CursorWordEndLeft() { return _super.call(this, { inSelectionMode: false, wordNavigationType: 2 /* WordEnd */, id: 'cursorWordEndLeft', precondition: undefined }) || this; } return CursorWordEndLeft; }(WordLeftCommand)); exports.CursorWordEndLeft = CursorWordEndLeft; var CursorWordLeft = /** @class */ (function (_super) { __extends(CursorWordLeft, _super); function CursorWordLeft() { return _super.call(this, { inSelectionMode: false, wordNavigationType: 1 /* WordStartFast */, id: 'cursorWordLeft', precondition: undefined }) || this; } return CursorWordLeft; }(WordLeftCommand)); exports.CursorWordLeft = CursorWordLeft; var CursorWordStartLeftSelect = /** @class */ (function (_super) { __extends(CursorWordStartLeftSelect, _super); function CursorWordStartLeftSelect() { return _super.call(this, { inSelectionMode: true, wordNavigationType: 0 /* WordStart */, id: 'cursorWordStartLeftSelect', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 15 /* LeftArrow */, mac: { primary: 512 /* Alt */ | 1024 /* Shift */ | 15 /* LeftArrow */ }, weight: 100 /* EditorContrib */ } }) || this; } return CursorWordStartLeftSelect; }(WordLeftCommand)); exports.CursorWordStartLeftSelect = CursorWordStartLeftSelect; var CursorWordEndLeftSelect = /** @class */ (function (_super) { __extends(CursorWordEndLeftSelect, _super); function CursorWordEndLeftSelect() { return _super.call(this, { inSelectionMode: true, wordNavigationType: 2 /* WordEnd */, id: 'cursorWordEndLeftSelect', precondition: undefined }) || this; } return CursorWordEndLeftSelect; }(WordLeftCommand)); exports.CursorWordEndLeftSelect = CursorWordEndLeftSelect; var CursorWordLeftSelect = /** @class */ (function (_super) { __extends(CursorWordLeftSelect, _super); function CursorWordLeftSelect() { return _super.call(this, { inSelectionMode: true, wordNavigationType: 1 /* WordStartFast */, id: 'cursorWordLeftSelect', precondition: undefined }) || this; } return CursorWordLeftSelect; }(WordLeftCommand)); exports.CursorWordLeftSelect = CursorWordLeftSelect; // Accessibility navigation commands should only be enabled on windows since they are tuned to what NVDA expects var CursorWordAccessibilityLeft = /** @class */ (function (_super) { __extends(CursorWordAccessibilityLeft, _super); function CursorWordAccessibilityLeft() { return _super.call(this, { inSelectionMode: false, wordNavigationType: 3 /* WordAccessibility */, id: 'cursorWordAccessibilityLeft', precondition: undefined, kbOpts: { kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, accessibility_1.CONTEXT_ACCESSIBILITY_MODE_ENABLED), win: { primary: 2048 /* CtrlCmd */ | 15 /* LeftArrow */ }, weight: 100 /* EditorContrib */ + 1 } }) || this; } CursorWordAccessibilityLeft.prototype._move = function (_, model, position, wordNavigationType) { return _super.prototype._move.call(this, wordCharacterClassifier_1.getMapForWordSeparators(editorOptions_1.EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType); }; return CursorWordAccessibilityLeft; }(WordLeftCommand)); exports.CursorWordAccessibilityLeft = CursorWordAccessibilityLeft; var CursorWordAccessibilityLeftSelect = /** @class */ (function (_super) { __extends(CursorWordAccessibilityLeftSelect, _super); function CursorWordAccessibilityLeftSelect() { return _super.call(this, { inSelectionMode: true, wordNavigationType: 3 /* WordAccessibility */, id: 'cursorWordAccessibilityLeftSelect', precondition: undefined, kbOpts: { kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, accessibility_1.CONTEXT_ACCESSIBILITY_MODE_ENABLED), win: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 15 /* LeftArrow */ }, weight: 100 /* EditorContrib */ + 1 } }) || this; } CursorWordAccessibilityLeftSelect.prototype._move = function (_, model, position, wordNavigationType) { return _super.prototype._move.call(this, wordCharacterClassifier_1.getMapForWordSeparators(editorOptions_1.EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType); }; return CursorWordAccessibilityLeftSelect; }(WordLeftCommand)); exports.CursorWordAccessibilityLeftSelect = CursorWordAccessibilityLeftSelect; var CursorWordStartRight = /** @class */ (function (_super) { __extends(CursorWordStartRight, _super); function CursorWordStartRight() { return _super.call(this, { inSelectionMode: false, wordNavigationType: 0 /* WordStart */, id: 'cursorWordStartRight', precondition: undefined }) || this; } return CursorWordStartRight; }(WordRightCommand)); exports.CursorWordStartRight = CursorWordStartRight; var CursorWordEndRight = /** @class */ (function (_super) { __extends(CursorWordEndRight, _super); function CursorWordEndRight() { return _super.call(this, { inSelectionMode: false, wordNavigationType: 2 /* WordEnd */, id: 'cursorWordEndRight', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 17 /* RightArrow */, mac: { primary: 512 /* Alt */ | 17 /* RightArrow */ }, weight: 100 /* EditorContrib */ } }) || this; } return CursorWordEndRight; }(WordRightCommand)); exports.CursorWordEndRight = CursorWordEndRight; var CursorWordRight = /** @class */ (function (_super) { __extends(CursorWordRight, _super); function CursorWordRight() { return _super.call(this, { inSelectionMode: false, wordNavigationType: 2 /* WordEnd */, id: 'cursorWordRight', precondition: undefined }) || this; } return CursorWordRight; }(WordRightCommand)); exports.CursorWordRight = CursorWordRight; var CursorWordStartRightSelect = /** @class */ (function (_super) { __extends(CursorWordStartRightSelect, _super); function CursorWordStartRightSelect() { return _super.call(this, { inSelectionMode: true, wordNavigationType: 0 /* WordStart */, id: 'cursorWordStartRightSelect', precondition: undefined }) || this; } return CursorWordStartRightSelect; }(WordRightCommand)); exports.CursorWordStartRightSelect = CursorWordStartRightSelect; var CursorWordEndRightSelect = /** @class */ (function (_super) { __extends(CursorWordEndRightSelect, _super); function CursorWordEndRightSelect() { return _super.call(this, { inSelectionMode: true, wordNavigationType: 2 /* WordEnd */, id: 'cursorWordEndRightSelect', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 17 /* RightArrow */, mac: { primary: 512 /* Alt */ | 1024 /* Shift */ | 17 /* RightArrow */ }, weight: 100 /* EditorContrib */ } }) || this; } return CursorWordEndRightSelect; }(WordRightCommand)); exports.CursorWordEndRightSelect = CursorWordEndRightSelect; var CursorWordRightSelect = /** @class */ (function (_super) { __extends(CursorWordRightSelect, _super); function CursorWordRightSelect() { return _super.call(this, { inSelectionMode: true, wordNavigationType: 2 /* WordEnd */, id: 'cursorWordRightSelect', precondition: undefined }) || this; } return CursorWordRightSelect; }(WordRightCommand)); exports.CursorWordRightSelect = CursorWordRightSelect; var CursorWordAccessibilityRight = /** @class */ (function (_super) { __extends(CursorWordAccessibilityRight, _super); function CursorWordAccessibilityRight() { return _super.call(this, { inSelectionMode: false, wordNavigationType: 3 /* WordAccessibility */, id: 'cursorWordAccessibilityRight', precondition: undefined, kbOpts: { kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, accessibility_1.CONTEXT_ACCESSIBILITY_MODE_ENABLED), win: { primary: 2048 /* CtrlCmd */ | 17 /* RightArrow */ }, weight: 100 /* EditorContrib */ + 1 } }) || this; } CursorWordAccessibilityRight.prototype._move = function (_, model, position, wordNavigationType) { return _super.prototype._move.call(this, wordCharacterClassifier_1.getMapForWordSeparators(editorOptions_1.EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType); }; return CursorWordAccessibilityRight; }(WordRightCommand)); exports.CursorWordAccessibilityRight = CursorWordAccessibilityRight; var CursorWordAccessibilityRightSelect = /** @class */ (function (_super) { __extends(CursorWordAccessibilityRightSelect, _super); function CursorWordAccessibilityRightSelect() { return _super.call(this, { inSelectionMode: true, wordNavigationType: 3 /* WordAccessibility */, id: 'cursorWordAccessibilityRightSelect', precondition: undefined, kbOpts: { kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, accessibility_1.CONTEXT_ACCESSIBILITY_MODE_ENABLED), win: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 17 /* RightArrow */ }, weight: 100 /* EditorContrib */ + 1 } }) || this; } CursorWordAccessibilityRightSelect.prototype._move = function (_, model, position, wordNavigationType) { return _super.prototype._move.call(this, wordCharacterClassifier_1.getMapForWordSeparators(editorOptions_1.EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType); }; return CursorWordAccessibilityRightSelect; }(WordRightCommand)); exports.CursorWordAccessibilityRightSelect = CursorWordAccessibilityRightSelect; var DeleteWordCommand = /** @class */ (function (_super) { __extends(DeleteWordCommand, _super); function DeleteWordCommand(opts) { var _this = _super.call(this, opts) || this; _this._whitespaceHeuristics = opts.whitespaceHeuristics; _this._wordNavigationType = opts.wordNavigationType; return _this; } DeleteWordCommand.prototype.runEditorCommand = function (accessor, editor, args) { var _this = this; if (!editor.hasModel()) { return; } var wordSeparators = wordCharacterClassifier_1.getMapForWordSeparators(editor.getOption(96 /* wordSeparators */)); var model = editor.getModel(); var selections = editor.getSelections(); var commands = selections.map(function (sel) { var deleteRange = _this._delete(wordSeparators, model, sel, _this._whitespaceHeuristics, _this._wordNavigationType); return new replaceCommand_1.ReplaceCommand(deleteRange, ''); }); editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); }; return DeleteWordCommand; }(editorExtensions_1.EditorCommand)); exports.DeleteWordCommand = DeleteWordCommand; var DeleteWordLeftCommand = /** @class */ (function (_super) { __extends(DeleteWordLeftCommand, _super); function DeleteWordLeftCommand() { return _super !== null && _super.apply(this, arguments) || this; } DeleteWordLeftCommand.prototype._delete = function (wordSeparators, model, selection, whitespaceHeuristics, wordNavigationType) { var r = cursorWordOperations_1.WordOperations.deleteWordLeft(wordSeparators, model, selection, whitespaceHeuristics, wordNavigationType); if (r) { return r; } return new range_1.Range(1, 1, 1, 1); }; return DeleteWordLeftCommand; }(DeleteWordCommand)); exports.DeleteWordLeftCommand = DeleteWordLeftCommand; var DeleteWordRightCommand = /** @class */ (function (_super) { __extends(DeleteWordRightCommand, _super); function DeleteWordRightCommand() { return _super !== null && _super.apply(this, arguments) || this; } DeleteWordRightCommand.prototype._delete = function (wordSeparators, model, selection, whitespaceHeuristics, wordNavigationType) { var r = cursorWordOperations_1.WordOperations.deleteWordRight(wordSeparators, model, selection, whitespaceHeuristics, wordNavigationType); if (r) { return r; } var lineCount = model.getLineCount(); var maxColumn = model.getLineMaxColumn(lineCount); return new range_1.Range(lineCount, maxColumn, lineCount, maxColumn); }; return DeleteWordRightCommand; }(DeleteWordCommand)); exports.DeleteWordRightCommand = DeleteWordRightCommand; var DeleteWordStartLeft = /** @class */ (function (_super) { __extends(DeleteWordStartLeft, _super); function DeleteWordStartLeft() { return _super.call(this, { whitespaceHeuristics: false, wordNavigationType: 0 /* WordStart */, id: 'deleteWordStartLeft', precondition: editorContextKeys_1.EditorContextKeys.writable }) || this; } return DeleteWordStartLeft; }(DeleteWordLeftCommand)); exports.DeleteWordStartLeft = DeleteWordStartLeft; var DeleteWordEndLeft = /** @class */ (function (_super) { __extends(DeleteWordEndLeft, _super); function DeleteWordEndLeft() { return _super.call(this, { whitespaceHeuristics: false, wordNavigationType: 2 /* WordEnd */, id: 'deleteWordEndLeft', precondition: editorContextKeys_1.EditorContextKeys.writable }) || this; } return DeleteWordEndLeft; }(DeleteWordLeftCommand)); exports.DeleteWordEndLeft = DeleteWordEndLeft; var DeleteWordLeft = /** @class */ (function (_super) { __extends(DeleteWordLeft, _super); function DeleteWordLeft() { return _super.call(this, { whitespaceHeuristics: true, wordNavigationType: 0 /* WordStart */, id: 'deleteWordLeft', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 1 /* Backspace */, mac: { primary: 512 /* Alt */ | 1 /* Backspace */ }, weight: 100 /* EditorContrib */ } }) || this; } return DeleteWordLeft; }(DeleteWordLeftCommand)); exports.DeleteWordLeft = DeleteWordLeft; var DeleteWordStartRight = /** @class */ (function (_super) { __extends(DeleteWordStartRight, _super); function DeleteWordStartRight() { return _super.call(this, { whitespaceHeuristics: false, wordNavigationType: 0 /* WordStart */, id: 'deleteWordStartRight', precondition: editorContextKeys_1.EditorContextKeys.writable }) || this; } return DeleteWordStartRight; }(DeleteWordRightCommand)); exports.DeleteWordStartRight = DeleteWordStartRight; var DeleteWordEndRight = /** @class */ (function (_super) { __extends(DeleteWordEndRight, _super); function DeleteWordEndRight() { return _super.call(this, { whitespaceHeuristics: false, wordNavigationType: 2 /* WordEnd */, id: 'deleteWordEndRight', precondition: editorContextKeys_1.EditorContextKeys.writable }) || this; } return DeleteWordEndRight; }(DeleteWordRightCommand)); exports.DeleteWordEndRight = DeleteWordEndRight; var DeleteWordRight = /** @class */ (function (_super) { __extends(DeleteWordRight, _super); function DeleteWordRight() { return _super.call(this, { whitespaceHeuristics: true, wordNavigationType: 2 /* WordEnd */, id: 'deleteWordRight', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 20 /* Delete */, mac: { primary: 512 /* Alt */ | 20 /* Delete */ }, weight: 100 /* EditorContrib */ } }) || this; } return DeleteWordRight; }(DeleteWordRightCommand)); exports.DeleteWordRight = DeleteWordRight; editorExtensions_1.registerEditorCommand(new CursorWordStartLeft()); editorExtensions_1.registerEditorCommand(new CursorWordEndLeft()); editorExtensions_1.registerEditorCommand(new CursorWordLeft()); editorExtensions_1.registerEditorCommand(new CursorWordStartLeftSelect()); editorExtensions_1.registerEditorCommand(new CursorWordEndLeftSelect()); editorExtensions_1.registerEditorCommand(new CursorWordLeftSelect()); editorExtensions_1.registerEditorCommand(new CursorWordStartRight()); editorExtensions_1.registerEditorCommand(new CursorWordEndRight()); editorExtensions_1.registerEditorCommand(new CursorWordRight()); editorExtensions_1.registerEditorCommand(new CursorWordStartRightSelect()); editorExtensions_1.registerEditorCommand(new CursorWordEndRightSelect()); editorExtensions_1.registerEditorCommand(new CursorWordRightSelect()); editorExtensions_1.registerEditorCommand(new CursorWordAccessibilityLeft()); editorExtensions_1.registerEditorCommand(new CursorWordAccessibilityLeftSelect()); editorExtensions_1.registerEditorCommand(new CursorWordAccessibilityRight()); editorExtensions_1.registerEditorCommand(new CursorWordAccessibilityRightSelect()); editorExtensions_1.registerEditorCommand(new DeleteWordStartLeft()); editorExtensions_1.registerEditorCommand(new DeleteWordEndLeft()); editorExtensions_1.registerEditorCommand(new DeleteWordLeft()); editorExtensions_1.registerEditorCommand(new DeleteWordStartRight()); editorExtensions_1.registerEditorCommand(new DeleteWordEndRight()); editorExtensions_1.registerEditorCommand(new DeleteWordRight()); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[543/*vs/editor/contrib/wordPartOperations/wordPartOperations*/], __M([0/*require*/,1/*exports*/,12/*vs/editor/browser/editorExtensions*/,160/*vs/editor/common/controller/cursorWordOperations*/,3/*vs/editor/common/core/range*/,23/*vs/editor/common/editorContextKeys*/,226/*vs/editor/contrib/wordOperations/wordOperations*/,29/*vs/platform/commands/common/commands*/]), function (require, exports, editorExtensions_1, cursorWordOperations_1, range_1, editorContextKeys_1, wordOperations_1, commands_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DeleteWordPartLeft = /** @class */ (function (_super) { __extends(DeleteWordPartLeft, _super); function DeleteWordPartLeft() { return _super.call(this, { whitespaceHeuristics: true, wordNavigationType: 0 /* WordStart */, id: 'deleteWordPartLeft', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 /* WinCtrl */ | 512 /* Alt */ | 1 /* Backspace */ }, weight: 100 /* EditorContrib */ } }) || this; } DeleteWordPartLeft.prototype._delete = function (wordSeparators, model, selection, whitespaceHeuristics, wordNavigationType) { var r = cursorWordOperations_1.WordPartOperations.deleteWordPartLeft(wordSeparators, model, selection, whitespaceHeuristics); if (r) { return r; } return new range_1.Range(1, 1, 1, 1); }; return DeleteWordPartLeft; }(wordOperations_1.DeleteWordCommand)); exports.DeleteWordPartLeft = DeleteWordPartLeft; var DeleteWordPartRight = /** @class */ (function (_super) { __extends(DeleteWordPartRight, _super); function DeleteWordPartRight() { return _super.call(this, { whitespaceHeuristics: true, wordNavigationType: 2 /* WordEnd */, id: 'deleteWordPartRight', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 /* WinCtrl */ | 512 /* Alt */ | 20 /* Delete */ }, weight: 100 /* EditorContrib */ } }) || this; } DeleteWordPartRight.prototype._delete = function (wordSeparators, model, selection, whitespaceHeuristics, wordNavigationType) { var r = cursorWordOperations_1.WordPartOperations.deleteWordPartRight(wordSeparators, model, selection, whitespaceHeuristics); if (r) { return r; } var lineCount = model.getLineCount(); var maxColumn = model.getLineMaxColumn(lineCount); return new range_1.Range(lineCount, maxColumn, lineCount, maxColumn); }; return DeleteWordPartRight; }(wordOperations_1.DeleteWordCommand)); exports.DeleteWordPartRight = DeleteWordPartRight; var WordPartLeftCommand = /** @class */ (function (_super) { __extends(WordPartLeftCommand, _super); function WordPartLeftCommand() { return _super !== null && _super.apply(this, arguments) || this; } WordPartLeftCommand.prototype._move = function (wordSeparators, model, position, wordNavigationType) { return cursorWordOperations_1.WordPartOperations.moveWordPartLeft(wordSeparators, model, position); }; return WordPartLeftCommand; }(wordOperations_1.MoveWordCommand)); exports.WordPartLeftCommand = WordPartLeftCommand; var CursorWordPartLeft = /** @class */ (function (_super) { __extends(CursorWordPartLeft, _super); function CursorWordPartLeft() { return _super.call(this, { inSelectionMode: false, wordNavigationType: 0 /* WordStart */, id: 'cursorWordPartLeft', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 /* WinCtrl */ | 512 /* Alt */ | 15 /* LeftArrow */ }, weight: 100 /* EditorContrib */ } }) || this; } return CursorWordPartLeft; }(WordPartLeftCommand)); exports.CursorWordPartLeft = CursorWordPartLeft; // Register previous id for compatibility purposes commands_1.CommandsRegistry.registerCommandAlias('cursorWordPartStartLeft', 'cursorWordPartLeft'); var CursorWordPartLeftSelect = /** @class */ (function (_super) { __extends(CursorWordPartLeftSelect, _super); function CursorWordPartLeftSelect() { return _super.call(this, { inSelectionMode: true, wordNavigationType: 0 /* WordStart */, id: 'cursorWordPartLeftSelect', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 /* WinCtrl */ | 512 /* Alt */ | 1024 /* Shift */ | 15 /* LeftArrow */ }, weight: 100 /* EditorContrib */ } }) || this; } return CursorWordPartLeftSelect; }(WordPartLeftCommand)); exports.CursorWordPartLeftSelect = CursorWordPartLeftSelect; // Register previous id for compatibility purposes commands_1.CommandsRegistry.registerCommandAlias('cursorWordPartStartLeftSelect', 'cursorWordPartLeftSelect'); var WordPartRightCommand = /** @class */ (function (_super) { __extends(WordPartRightCommand, _super); function WordPartRightCommand() { return _super !== null && _super.apply(this, arguments) || this; } WordPartRightCommand.prototype._move = function (wordSeparators, model, position, wordNavigationType) { return cursorWordOperations_1.WordPartOperations.moveWordPartRight(wordSeparators, model, position); }; return WordPartRightCommand; }(wordOperations_1.MoveWordCommand)); exports.WordPartRightCommand = WordPartRightCommand; var CursorWordPartRight = /** @class */ (function (_super) { __extends(CursorWordPartRight, _super); function CursorWordPartRight() { return _super.call(this, { inSelectionMode: false, wordNavigationType: 2 /* WordEnd */, id: 'cursorWordPartRight', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 /* WinCtrl */ | 512 /* Alt */ | 17 /* RightArrow */ }, weight: 100 /* EditorContrib */ } }) || this; } return CursorWordPartRight; }(WordPartRightCommand)); exports.CursorWordPartRight = CursorWordPartRight; var CursorWordPartRightSelect = /** @class */ (function (_super) { __extends(CursorWordPartRightSelect, _super); function CursorWordPartRightSelect() { return _super.call(this, { inSelectionMode: true, wordNavigationType: 2 /* WordEnd */, id: 'cursorWordPartRightSelect', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 /* WinCtrl */ | 512 /* Alt */ | 1024 /* Shift */ | 17 /* RightArrow */ }, weight: 100 /* EditorContrib */ } }) || this; } return CursorWordPartRightSelect; }(WordPartRightCommand)); exports.CursorWordPartRightSelect = CursorWordPartRightSelect; editorExtensions_1.registerEditorCommand(new DeleteWordPartLeft()); editorExtensions_1.registerEditorCommand(new DeleteWordPartRight()); editorExtensions_1.registerEditorCommand(new CursorWordPartLeft()); editorExtensions_1.registerEditorCommand(new CursorWordPartLeftSelect()); editorExtensions_1.registerEditorCommand(new CursorWordPartRight()); editorExtensions_1.registerEditorCommand(new CursorWordPartRightSelect()); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[544/*vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,6/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,12/*vs/editor/browser/editorExtensions*/,326/*vs/css!vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/]), function (require, exports, browser, dom, lifecycle_1, editorExtensions_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var IPadShowKeyboard = /** @class */ (function (_super) { __extends(IPadShowKeyboard, _super); function IPadShowKeyboard(editor) { var _this = _super.call(this) || this; _this.editor = editor; _this.widget = null; if (browser.isIPad) { _this._register(editor.onDidChangeConfiguration(function () { return _this.update(); })); _this.update(); } return _this; } IPadShowKeyboard.prototype.update = function () { var shouldHaveWidget = (!this.editor.getOption(68 /* readOnly */)); if (!this.widget && shouldHaveWidget) { this.widget = new ShowKeyboardWidget(this.editor); } else if (this.widget && !shouldHaveWidget) { this.widget.dispose(); this.widget = null; } }; IPadShowKeyboard.prototype.dispose = function () { _super.prototype.dispose.call(this); if (this.widget) { this.widget.dispose(); this.widget = null; } }; IPadShowKeyboard.ID = 'editor.contrib.iPadShowKeyboard'; return IPadShowKeyboard; }(lifecycle_1.Disposable)); exports.IPadShowKeyboard = IPadShowKeyboard; var ShowKeyboardWidget = /** @class */ (function (_super) { __extends(ShowKeyboardWidget, _super); function ShowKeyboardWidget(editor) { var _this = _super.call(this) || this; _this.editor = editor; _this._domNode = document.createElement('textarea'); _this._domNode.className = 'iPadShowKeyboard'; _this._register(dom.addDisposableListener(_this._domNode, 'touchstart', function (e) { _this.editor.focus(); })); _this._register(dom.addDisposableListener(_this._domNode, 'focus', function (e) { _this.editor.focus(); })); _this.editor.addOverlayWidget(_this); return _this; } ShowKeyboardWidget.prototype.dispose = function () { this.editor.removeOverlayWidget(this); _super.prototype.dispose.call(this); }; // ----- IOverlayWidget API ShowKeyboardWidget.prototype.getId = function () { return ShowKeyboardWidget.ID; }; ShowKeyboardWidget.prototype.getDomNode = function () { return this._domNode; }; ShowKeyboardWidget.prototype.getPosition = function () { return { preference: 1 /* BOTTOM_RIGHT_CORNER */ }; }; ShowKeyboardWidget.ID = 'editor.contrib.ShowKeyboardWidget'; return ShowKeyboardWidget; }(lifecycle_1.Disposable)); editorExtensions_1.registerEditorContribution(IPadShowKeyboard.ID, IPadShowKeyboard); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[545/*vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast*/], __M([0/*require*/,1/*exports*/,12/*vs/editor/browser/editorExtensions*/,94/*vs/editor/standalone/common/standaloneThemeService*/,59/*vs/editor/common/standaloneStrings*/]), function (require, exports, editorExtensions_1, standaloneThemeService_1, standaloneStrings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ToggleHighContrast = /** @class */ (function (_super) { __extends(ToggleHighContrast, _super); function ToggleHighContrast() { var _this = _super.call(this, { id: 'editor.action.toggleHighContrast', label: standaloneStrings_1.ToggleHighContrastNLS.toggleHighContrast, alias: 'Toggle High Contrast Theme', precondition: undefined }) || this; _this._originalThemeName = null; return _this; } ToggleHighContrast.prototype.run = function (accessor, editor) { var standaloneThemeService = accessor.get(standaloneThemeService_1.IStandaloneThemeService); if (this._originalThemeName) { // We must toggle back to the integrator's theme standaloneThemeService.setTheme(this._originalThemeName); this._originalThemeName = null; } else { this._originalThemeName = standaloneThemeService.getTheme().themeName; standaloneThemeService.setTheme('hc-black'); } }; return ToggleHighContrast; }(editorExtensions_1.EditorAction)); editorExtensions_1.registerEditorAction(ToggleHighContrast); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[20/*vs/platform/theme/common/colorRegistry*/], __M([0/*require*/,1/*exports*/,42/*vs/platform/registry/common/platform*/,27/*vs/base/common/color*/,4/*vs/base/common/event*/,476/*vs/nls!vs/platform/theme/common/colorRegistry*/,220/*vs/platform/jsonschemas/common/jsonContributionRegistry*/,15/*vs/base/common/async*/]), function (require, exports, platform, color_1, event_1, nls, jsonContributionRegistry_1, async_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // color registry exports.Extensions = { ColorContribution: 'base.contributions.colors' }; var ColorRegistry = /** @class */ (function () { function ColorRegistry() { this._onDidChangeSchema = new event_1.Emitter(); this.onDidChangeSchema = this._onDidChangeSchema.event; this.colorSchema = { type: 'object', properties: {} }; this.colorReferenceSchema = { type: 'string', enum: [], enumDescriptions: [] }; this.colorsById = {}; } ColorRegistry.prototype.registerColor = function (id, defaults, description, needsTransparency, deprecationMessage) { if (needsTransparency === void 0) { needsTransparency = false; } var colorContribution = { id: id, description: description, defaults: defaults, needsTransparency: needsTransparency, deprecationMessage: deprecationMessage }; this.colorsById[id] = colorContribution; var propertySchema = { type: 'string', description: 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; }; ColorRegistry.prototype.resolveDefaultColor = function (id, theme) { var colorDesc = this.colorsById[id]; if (colorDesc && colorDesc.defaults) { var colorValue = colorDesc.defaults[theme.type]; return resolveColorValue(colorValue, theme); } return undefined; }; ColorRegistry.prototype.getColorSchema = function () { return this.colorSchema; }; ColorRegistry.prototype.toString = function () { var _this = this; var sorter = function (a, b) { var cat1 = a.indexOf('.') === -1 ? 0 : 1; var cat2 = b.indexOf('.') === -1 ? 0 : 1; if (cat1 !== cat2) { return cat1 - cat2; } return a.localeCompare(b); }; return Object.keys(this.colorsById).sort(sorter).map(function (k) { return "- `" + k + "`: " + _this.colorsById[k].description; }).join('\n'); }; return ColorRegistry; }()); var 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.focusBorder = registerColor('focusBorder', { dark: color_1.Color.fromHex('#0E639C').transparent(0.8), light: color_1.Color.fromHex('#007ACC').transparent(0.4), hc: '#F38518' }, nls.localize(2, null)); exports.contrastBorder = registerColor('contrastBorder', { light: null, dark: null, hc: '#6FC3DF' }, nls.localize(3, null)); exports.activeContrastBorder = registerColor('contrastActiveBorder', { light: null, dark: null, hc: exports.focusBorder }, nls.localize(4, null)); exports.textLinkForeground = registerColor('textLink.foreground', { light: '#006AB1', dark: '#3794FF', hc: '#3794FF' }, nls.localize(5, null)); exports.textCodeBlockBackground = registerColor('textCodeBlock.background', { light: '#dcdcdc66', dark: '#0a0a0a66', hc: color_1.Color.black }, nls.localize(6, null)); // ----- widgets exports.widgetShadow = registerColor('widget.shadow', { dark: '#000000', light: '#A8A8A8', hc: null }, nls.localize(7, null)); exports.inputBackground = registerColor('input.background', { dark: '#3C3C3C', light: color_1.Color.white, hc: color_1.Color.black }, nls.localize(8, null)); exports.inputForeground = registerColor('input.foreground', { dark: exports.foreground, light: exports.foreground, hc: exports.foreground }, nls.localize(9, null)); exports.inputBorder = registerColor('input.border', { dark: null, light: null, hc: exports.contrastBorder }, nls.localize(10, null)); exports.inputActiveOptionBorder = registerColor('inputOption.activeBorder', { dark: '#007ACC00', light: '#007ACC00', hc: exports.contrastBorder }, nls.localize(11, null)); exports.inputActiveOptionBackground = registerColor('inputOption.activeBackground', { dark: transparent(exports.focusBorder, 0.5), light: transparent(exports.focusBorder, 0.3), hc: null }, nls.localize(12, null)); exports.inputValidationInfoBackground = registerColor('inputValidation.infoBackground', { dark: '#063B49', light: '#D6ECF2', hc: color_1.Color.black }, nls.localize(13, null)); exports.inputValidationInfoForeground = registerColor('inputValidation.infoForeground', { dark: null, light: null, hc: null }, nls.localize(14, null)); exports.inputValidationInfoBorder = registerColor('inputValidation.infoBorder', { dark: '#007acc', light: '#007acc', hc: exports.contrastBorder }, nls.localize(15, null)); exports.inputValidationWarningBackground = registerColor('inputValidation.warningBackground', { dark: '#352A05', light: '#F6F5D2', hc: color_1.Color.black }, nls.localize(16, null)); exports.inputValidationWarningForeground = registerColor('inputValidation.warningForeground', { dark: null, light: null, hc: null }, nls.localize(17, null)); exports.inputValidationWarningBorder = registerColor('inputValidation.warningBorder', { dark: '#B89500', light: '#B89500', hc: exports.contrastBorder }, nls.localize(18, null)); exports.inputValidationErrorBackground = registerColor('inputValidation.errorBackground', { dark: '#5A1D1D', light: '#F2DEDE', hc: color_1.Color.black }, nls.localize(19, null)); exports.inputValidationErrorForeground = registerColor('inputValidation.errorForeground', { dark: null, light: null, hc: null }, nls.localize(20, null)); exports.inputValidationErrorBorder = registerColor('inputValidation.errorBorder', { dark: '#BE1100', light: '#BE1100', hc: exports.contrastBorder }, nls.localize(21, null)); exports.selectBackground = registerColor('dropdown.background', { dark: '#3C3C3C', light: color_1.Color.white, hc: color_1.Color.black }, nls.localize(22, null)); exports.selectForeground = registerColor('dropdown.foreground', { dark: '#F0F0F0', light: null, hc: color_1.Color.white }, nls.localize(23, null)); exports.pickerGroupForeground = registerColor('pickerGroup.foreground', { dark: '#3794FF', light: '#0066BF', hc: color_1.Color.white }, nls.localize(24, null)); exports.pickerGroupBorder = registerColor('pickerGroup.border', { dark: '#3F3F46', light: '#CCCEDB', hc: color_1.Color.white }, nls.localize(25, null)); exports.badgeBackground = registerColor('badge.background', { dark: '#4D4D4D', light: '#C4C4C4', hc: color_1.Color.black }, nls.localize(26, null)); exports.badgeForeground = registerColor('badge.foreground', { dark: color_1.Color.white, light: '#333', hc: color_1.Color.white }, nls.localize(27, null)); exports.scrollbarShadow = registerColor('scrollbar.shadow', { dark: '#000000', light: '#DDDDDD', hc: null }, nls.localize(28, 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(29, 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(30, 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(31, null)); exports.progressBarBackground = registerColor('progressBar.background', { dark: color_1.Color.fromHex('#0E70C0'), light: color_1.Color.fromHex('#0E70C0'), hc: exports.contrastBorder }, nls.localize(32, null)); exports.editorErrorForeground = registerColor('editorError.foreground', { dark: '#F48771', light: '#E51400', hc: null }, nls.localize(33, null)); exports.editorErrorBorder = registerColor('editorError.border', { dark: null, light: null, hc: color_1.Color.fromHex('#E47777').transparent(0.8) }, nls.localize(34, null)); exports.editorWarningForeground = registerColor('editorWarning.foreground', { dark: '#CCA700', light: '#E9A700', hc: null }, nls.localize(35, null)); exports.editorWarningBorder = registerColor('editorWarning.border', { dark: null, light: null, hc: color_1.Color.fromHex('#FFCC00').transparent(0.8) }, nls.localize(36, null)); exports.editorInfoForeground = registerColor('editorInfo.foreground', { dark: '#75BEFF', light: '#75BEFF', hc: null }, nls.localize(37, null)); exports.editorInfoBorder = registerColor('editorInfo.border', { dark: null, light: null, hc: color_1.Color.fromHex('#75BEFF').transparent(0.8) }, nls.localize(38, null)); exports.editorHintForeground = registerColor('editorHint.foreground', { dark: color_1.Color.fromHex('#eeeeee').transparent(0.7), light: '#6c6c6c', hc: null }, nls.localize(39, null)); exports.editorHintBorder = registerColor('editorHint.border', { dark: null, light: null, hc: color_1.Color.fromHex('#eeeeee').transparent(0.8) }, nls.localize(40, 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(41, null)); /** * Editor foreground color. */ exports.editorForeground = registerColor('editor.foreground', { light: '#333333', dark: '#BBBBBB', hc: color_1.Color.white }, nls.localize(42, null)); /** * Editor widgets */ exports.editorWidgetBackground = registerColor('editorWidget.background', { dark: '#252526', light: '#F3F3F3', hc: '#0C141F' }, nls.localize(43, null)); exports.editorWidgetForeground = registerColor('editorWidget.foreground', { dark: exports.foreground, light: exports.foreground, hc: exports.foreground }, nls.localize(44, null)); exports.editorWidgetBorder = registerColor('editorWidget.border', { dark: '#454545', light: '#C8C8C8', hc: exports.contrastBorder }, nls.localize(45, null)); exports.editorWidgetResizeBorder = registerColor('editorWidget.resizeBorder', { light: null, dark: null, hc: null }, nls.localize(46, null)); /** * Editor selection colors. */ exports.editorSelectionBackground = registerColor('editor.selectionBackground', { light: '#ADD6FF', dark: '#264F78', hc: '#f3f518' }, nls.localize(47, null)); exports.editorSelectionForeground = registerColor('editor.selectionForeground', { light: null, dark: null, hc: '#000000' }, nls.localize(48, 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(49, 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(50, null), true); exports.editorSelectionHighlightBorder = registerColor('editor.selectionHighlightBorder', { light: null, dark: null, hc: exports.activeContrastBorder }, nls.localize(51, null)); /** * Editor find match colors. */ exports.editorFindMatch = registerColor('editor.findMatchBackground', { light: '#A8AC94', dark: '#515C6A', hc: null }, nls.localize(52, null)); exports.editorFindMatchHighlight = registerColor('editor.findMatchHighlightBackground', { light: '#EA5C0055', dark: '#EA5C0055', hc: null }, nls.localize(53, null), true); exports.editorFindRangeHighlight = registerColor('editor.findRangeHighlightBackground', { dark: '#3a3d4166', light: '#b4b4b44d', hc: null }, nls.localize(54, null), true); exports.editorFindMatchBorder = registerColor('editor.findMatchBorder', { light: null, dark: null, hc: exports.activeContrastBorder }, nls.localize(55, null)); exports.editorFindMatchHighlightBorder = registerColor('editor.findMatchHighlightBorder', { light: null, dark: null, hc: exports.activeContrastBorder }, nls.localize(56, null)); exports.editorFindRangeHighlightBorder = registerColor('editor.findRangeHighlightBorder', { dark: null, light: null, hc: transparent(exports.activeContrastBorder, 0.4) }, nls.localize(57, null), true); /** * Editor hover */ exports.editorHoverHighlight = registerColor('editor.hoverHighlightBackground', { light: '#ADD6FF26', dark: '#264f7840', hc: '#ADD6FF26' }, nls.localize(58, null), true); exports.editorHoverBackground = registerColor('editorHoverWidget.background', { light: exports.editorWidgetBackground, dark: exports.editorWidgetBackground, hc: exports.editorWidgetBackground }, nls.localize(59, null)); exports.editorHoverForeground = registerColor('editorHoverWidget.foreground', { light: exports.editorWidgetForeground, dark: exports.editorWidgetForeground, hc: exports.editorWidgetForeground }, nls.localize(60, null)); exports.editorHoverBorder = registerColor('editorHoverWidget.border', { light: exports.editorWidgetBorder, dark: exports.editorWidgetBorder, hc: exports.editorWidgetBorder }, nls.localize(61, null)); exports.editorHoverStatusBarBackground = registerColor('editorHoverWidget.statusBarBackground', { dark: lighten(exports.editorHoverBackground, 0.2), light: darken(exports.editorHoverBackground, 0.05), hc: exports.editorWidgetBackground }, nls.localize(62, null)); /** * Editor link colors */ exports.editorActiveLinkForeground = registerColor('editorLink.activeForeground', { dark: '#4E94CE', light: color_1.Color.blue, hc: color_1.Color.cyan }, nls.localize(63, null)); /** * Editor lighbulb icon colors */ exports.editorLightBulbForeground = registerColor('editorLightBulb.foreground', { dark: '#FFCC00', light: '#DDB100', hc: '#FFCC00' }, nls.localize(64, null)); exports.editorLightBulbAutoFixForeground = registerColor('editorLightBulbAutoFix.foreground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, nls.localize(65, 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(66, null), true); exports.diffRemoved = registerColor('diffEditor.removedTextBackground', { dark: exports.defaultRemoveColor, light: exports.defaultRemoveColor, hc: null }, nls.localize(67, null), true); exports.diffInsertedOutline = registerColor('diffEditor.insertedTextBorder', { dark: null, light: null, hc: '#33ff2eff' }, nls.localize(68, null)); exports.diffRemovedOutline = registerColor('diffEditor.removedTextBorder', { dark: null, light: null, hc: '#FF008F' }, nls.localize(69, null)); exports.diffBorder = registerColor('diffEditor.border', { dark: null, light: null, hc: exports.contrastBorder }, nls.localize(70, null)); /** * List and tree colors */ exports.listFocusBackground = registerColor('list.focusBackground', { dark: '#062F4A', light: '#D6EBFF', hc: null }, nls.localize(71, null)); exports.listFocusForeground = registerColor('list.focusForeground', { dark: null, light: null, hc: null }, nls.localize(72, null)); exports.listActiveSelectionBackground = registerColor('list.activeSelectionBackground', { dark: '#094771', light: '#0074E8', hc: null }, nls.localize(73, null)); exports.listActiveSelectionForeground = registerColor('list.activeSelectionForeground', { dark: color_1.Color.white, light: color_1.Color.white, hc: null }, nls.localize(74, null)); exports.listInactiveSelectionBackground = registerColor('list.inactiveSelectionBackground', { dark: '#37373D', light: '#E4E6F1', hc: null }, nls.localize(75, null)); exports.listInactiveSelectionForeground = registerColor('list.inactiveSelectionForeground', { dark: null, light: null, hc: null }, nls.localize(76, null)); exports.listInactiveFocusBackground = registerColor('list.inactiveFocusBackground', { dark: null, light: null, hc: null }, nls.localize(77, null)); exports.listHoverBackground = registerColor('list.hoverBackground', { dark: '#2A2D2E', light: '#F0F0F0', hc: null }, nls.localize(78, null)); exports.listHoverForeground = registerColor('list.hoverForeground', { dark: null, light: null, hc: null }, nls.localize(79, null)); exports.listDropBackground = registerColor('list.dropBackground', { dark: exports.listFocusBackground, light: exports.listFocusBackground, hc: null }, nls.localize(80, null)); exports.listHighlightForeground = registerColor('list.highlightForeground', { dark: '#0097fb', light: '#0066BF', hc: exports.focusBorder }, nls.localize(81, null)); exports.listFilterWidgetBackground = registerColor('listFilterWidget.background', { light: '#efc1ad', dark: '#653723', hc: color_1.Color.black }, nls.localize(82, null)); exports.listFilterWidgetOutline = registerColor('listFilterWidget.outline', { dark: color_1.Color.transparent, light: color_1.Color.transparent, hc: '#f38518' }, nls.localize(83, null)); exports.listFilterWidgetNoMatchesOutline = registerColor('listFilterWidget.noMatchesOutline', { dark: '#BE1100', light: '#BE1100', hc: exports.contrastBorder }, nls.localize(84, null)); exports.treeIndentGuidesStroke = registerColor('tree.indentGuidesStroke', { dark: '#585858', light: '#a9a9a9', hc: '#a9a9a9' }, nls.localize(85, null)); /** * Menu colors */ exports.menuBorder = registerColor('menu.border', { dark: null, light: null, hc: exports.contrastBorder }, nls.localize(86, null)); exports.menuForeground = registerColor('menu.foreground', { dark: exports.selectForeground, light: exports.foreground, hc: exports.selectForeground }, nls.localize(87, null)); exports.menuBackground = registerColor('menu.background', { dark: exports.selectBackground, light: exports.selectBackground, hc: exports.selectBackground }, nls.localize(88, null)); exports.menuSelectionForeground = registerColor('menu.selectionForeground', { dark: exports.listActiveSelectionForeground, light: exports.listActiveSelectionForeground, hc: exports.listActiveSelectionForeground }, nls.localize(89, null)); exports.menuSelectionBackground = registerColor('menu.selectionBackground', { dark: exports.listActiveSelectionBackground, light: exports.listActiveSelectionBackground, hc: exports.listActiveSelectionBackground }, nls.localize(90, null)); exports.menuSelectionBorder = registerColor('menu.selectionBorder', { dark: null, light: null, hc: exports.activeContrastBorder }, nls.localize(91, null)); exports.menuSeparatorBackground = registerColor('menu.separatorBackground', { dark: '#BBBBBB', light: '#888888', hc: exports.contrastBorder }, nls.localize(92, 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(93, null)); exports.snippetTabstopHighlightBorder = registerColor('editor.snippetTabstopHighlightBorder', { dark: null, light: null, hc: null }, nls.localize(94, null)); exports.snippetFinalTabstopHighlightBackground = registerColor('editor.snippetFinalTabstopHighlightBackground', { dark: null, light: null, hc: null }, nls.localize(95, 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(96, null)); exports.overviewRulerFindMatchForeground = registerColor('editorOverviewRuler.findMatchForeground', { dark: '#d186167e', light: '#d186167e', hc: '#AB5A00' }, nls.localize(97, null), true); exports.overviewRulerSelectionHighlightForeground = registerColor('editorOverviewRuler.selectionHighlightForeground', { dark: '#A0A0A0CC', light: '#A0A0A0CC', hc: '#A0A0A0CC' }, nls.localize(98, null), true); exports.minimapFindMatch = registerColor('minimap.findMatchHighlight', { light: '#d18616', dark: '#d18616', hc: '#AB5A00' }, nls.localize(99, null), true); exports.minimapSelection = registerColor('minimap.selectionHighlight', { light: '#ADD6FF', dark: '#264F78', hc: '#ffffff' }, nls.localize(100, 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(101, null)); exports.minimapWarning = registerColor('minimap.warningHighlight', { dark: exports.editorWarningForeground, light: exports.editorWarningForeground, hc: exports.editorWarningBorder }, nls.localize(102, null)); exports.problemsErrorIconForeground = registerColor('problemsErrorIcon.foreground', { dark: exports.editorErrorForeground, light: exports.editorErrorForeground, hc: exports.editorErrorForeground }, nls.localize(103, null)); exports.problemsWarningIconForeground = registerColor('problemsWarningIcon.foreground', { dark: exports.editorWarningForeground, light: exports.editorWarningForeground, hc: exports.editorWarningForeground }, nls.localize(104, null)); exports.problemsInfoIconForeground = registerColor('problemsInfoIcon.foreground', { dark: exports.editorInfoForeground, light: exports.editorInfoForeground, hc: exports.editorInfoForeground }, nls.localize(105, null)); // ----- color functions function darken(colorValue, factor) { return function (theme) { var color = resolveColorValue(colorValue, theme); if (color) { return color.darken(factor); } return undefined; }; } exports.darken = darken; function lighten(colorValue, factor) { return function (theme) { var color = resolveColorValue(colorValue, theme); if (color) { return color.lighten(factor); } return undefined; }; } exports.lighten = lighten; function transparent(colorValue, factor) { return function (theme) { var color = resolveColorValue(colorValue, theme); if (color) { return color.transparent(factor); } return undefined; }; } exports.transparent = transparent; function oneOf() { var colorValues = []; for (var _i = 0; _i < arguments.length; _i++) { colorValues[_i] = arguments[_i]; } return function (theme) { for (var _i = 0, colorValues_1 = colorValues; _i < colorValues_1.length; _i++) { var colorValue = colorValues_1[_i]; var color = resolveColorValue(colorValue, theme); if (color) { return color; } } return undefined; }; } exports.oneOf = oneOf; function lessProminent(colorValue, backgroundColorValue, factor, transparency) { return function (theme) { var from = resolveColorValue(colorValue, theme); if (from) { var backgroundColor = resolveColorValue(backgroundColorValue, theme); if (backgroundColor) { if (from.isDarkerThan(backgroundColor)) { return color_1.Color.getLighterColor(from, backgroundColor, factor).transparent(transparency); } return color_1.Color.getDarkerColor(from, backgroundColor, factor).transparent(transparency); } return from.transparent(factor * transparency); } return undefined; }; } // ----- 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 === 'function') { return colorValue(theme); } return undefined; } exports.resolveColorValue = resolveColorValue; exports.workbenchColorsSchemaId = 'vscode://schemas/workbench-colors'; var schemaRegistry = platform.Registry.as(jsonContributionRegistry_1.Extensions.JSONContribution); schemaRegistry.registerSchema(exports.workbenchColorsSchemaId, colorRegistry.getColorSchema()); var delayer = new async_1.RunOnceScheduler(function () { return schemaRegistry.notifySchemaChanged(exports.workbenchColorsSchemaId); }, 200); colorRegistry.onDidChangeSchema(function () { 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[97/*vs/platform/theme/common/styler*/], __M([0/*require*/,1/*exports*/,20/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, colorRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function computeStyles(theme, styleMap) { var styles = Object.create(null); for (var key in styleMap) { var value = styleMap[key]; if (value) { styles[key] = colorRegistry_1.resolveColorValue(value, theme); } } return styles; } exports.computeStyles = computeStyles; function attachStyler(themeService, styleMap, widgetOrCallback) { function applyStyles(theme) { var styles = computeStyles(themeService.getTheme(), styleMap); if (typeof widgetOrCallback === 'function') { widgetOrCallback(styles); } else { widgetOrCallback.style(styles); } } applyStyles(themeService.getTheme()); return themeService.onThemeChange(applyStyles); } exports.attachStyler = attachStyler; function attachBadgeStyler(widget, themeService, style) { return attachStyler(themeService, { badgeBackground: (style && style.badgeBackground) || colorRegistry_1.badgeBackground, badgeForeground: (style && style.badgeForeground) || colorRegistry_1.badgeForeground, badgeBorder: colorRegistry_1.contrastBorder }, widget); } exports.attachBadgeStyler = attachBadgeStyler; function attachQuickOpenStyler(widget, themeService, style) { return attachStyler(themeService, { foreground: (style && style.foreground) || colorRegistry_1.foreground, background: (style && style.background) || colorRegistry_1.editorBackground, borderColor: style && style.borderColor || colorRegistry_1.contrastBorder, widgetShadow: style && style.widgetShadow || colorRegistry_1.widgetShadow, progressBarBackground: style && style.progressBarBackground || colorRegistry_1.progressBarBackground, pickerGroupForeground: style && style.pickerGroupForeground || colorRegistry_1.pickerGroupForeground, pickerGroupBorder: style && style.pickerGroupBorder || colorRegistry_1.pickerGroupBorder, inputBackground: (style && style.inputBackground) || colorRegistry_1.inputBackground, inputForeground: (style && style.inputForeground) || colorRegistry_1.inputForeground, inputBorder: (style && style.inputBorder) || colorRegistry_1.inputBorder, inputValidationInfoBorder: (style && style.inputValidationInfoBorder) || colorRegistry_1.inputValidationInfoBorder, inputValidationInfoBackground: (style && style.inputValidationInfoBackground) || colorRegistry_1.inputValidationInfoBackground, inputValidationInfoForeground: (style && style.inputValidationInfoForeground) || colorRegistry_1.inputValidationInfoForeground, inputValidationWarningBorder: (style && style.inputValidationWarningBorder) || colorRegistry_1.inputValidationWarningBorder, inputValidationWarningBackground: (style && style.inputValidationWarningBackground) || colorRegistry_1.inputValidationWarningBackground, inputValidationWarningForeground: (style && style.inputValidationWarningForeground) || colorRegistry_1.inputValidationWarningForeground, inputValidationErrorBorder: (style && style.inputValidationErrorBorder) || colorRegistry_1.inputValidationErrorBorder, inputValidationErrorBackground: (style && style.inputValidationErrorBackground) || colorRegistry_1.inputValidationErrorBackground, inputValidationErrorForeground: (style && style.inputValidationErrorForeground) || colorRegistry_1.inputValidationErrorForeground, listFocusBackground: (style && style.listFocusBackground) || colorRegistry_1.listFocusBackground, listFocusForeground: (style && style.listFocusForeground) || colorRegistry_1.listFocusForeground, listActiveSelectionBackground: (style && style.listActiveSelectionBackground) || colorRegistry_1.darken(colorRegistry_1.listActiveSelectionBackground, 0.1), listActiveSelectionForeground: (style && style.listActiveSelectionForeground) || colorRegistry_1.listActiveSelectionForeground, listFocusAndSelectionBackground: style && style.listFocusAndSelectionBackground || colorRegistry_1.listActiveSelectionBackground, listFocusAndSelectionForeground: (style && style.listFocusAndSelectionForeground) || colorRegistry_1.listActiveSelectionForeground, listInactiveSelectionBackground: (style && style.listInactiveSelectionBackground) || colorRegistry_1.listInactiveSelectionBackground, listInactiveSelectionForeground: (style && style.listInactiveSelectionForeground) || colorRegistry_1.listInactiveSelectionForeground, listInactiveFocusBackground: (style && style.listInactiveFocusBackground) || colorRegistry_1.listInactiveFocusBackground, listHoverBackground: (style && style.listHoverBackground) || colorRegistry_1.listHoverBackground, listHoverForeground: (style && style.listHoverForeground) || colorRegistry_1.listHoverForeground, listDropBackground: (style && style.listDropBackground) || colorRegistry_1.listDropBackground, listFocusOutline: (style && style.listFocusOutline) || colorRegistry_1.activeContrastBorder, listSelectionOutline: (style && style.listSelectionOutline) || colorRegistry_1.activeContrastBorder, listHoverOutline: (style && style.listHoverOutline) || colorRegistry_1.activeContrastBorder }, widget); } exports.attachQuickOpenStyler = attachQuickOpenStyler; function attachListStyler(widget, themeService, overrides) { return attachStyler(themeService, __assign(__assign({}, exports.defaultListStyles), (overrides || {})), widget); } exports.attachListStyler = attachListStyler; exports.defaultListStyles = { listFocusBackground: colorRegistry_1.listFocusBackground, listFocusForeground: colorRegistry_1.listFocusForeground, listActiveSelectionBackground: colorRegistry_1.darken(colorRegistry_1.listActiveSelectionBackground, 0.1), listActiveSelectionForeground: colorRegistry_1.listActiveSelectionForeground, listFocusAndSelectionBackground: colorRegistry_1.listActiveSelectionBackground, listFocusAndSelectionForeground: colorRegistry_1.listActiveSelectionForeground, listInactiveSelectionBackground: colorRegistry_1.listInactiveSelectionBackground, listInactiveSelectionForeground: colorRegistry_1.listInactiveSelectionForeground, listInactiveFocusBackground: colorRegistry_1.listInactiveFocusBackground, listHoverBackground: colorRegistry_1.listHoverBackground, listHoverForeground: colorRegistry_1.listHoverForeground, listDropBackground: colorRegistry_1.listDropBackground, listFocusOutline: colorRegistry_1.activeContrastBorder, 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 }; exports.defaultMenuStyles = { shadowColor: colorRegistry_1.widgetShadow, borderColor: colorRegistry_1.menuBorder, foregroundColor: colorRegistry_1.menuForeground, backgroundColor: colorRegistry_1.menuBackground, selectionForegroundColor: colorRegistry_1.menuSelectionForeground, selectionBackgroundColor: colorRegistry_1.menuSelectionBackground, selectionBorderColor: colorRegistry_1.menuSelectionBorder, separatorColor: colorRegistry_1.menuSeparatorBackground }; function attachMenuStyler(widget, themeService, style) { return attachStyler(themeService, __assign(__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[546/*vs/editor/standalone/browser/quickOpen/quickOpenEditorWidget*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,414/*vs/base/parts/quickopen/browser/quickOpenWidget*/,20/*vs/platform/theme/common/colorRegistry*/,97/*vs/platform/theme/common/styler*/]), function (require, exports, dom_1, quickOpenWidget_1, colorRegistry_1, styler_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var QuickOpenEditorWidget = /** @class */ (function () { function QuickOpenEditorWidget(codeEditor, onOk, onCancel, onType, configuration, themeService) { this.codeEditor = codeEditor; this.themeService = themeService; this.visible = false; this.domNode = document.createElement('div'); this.quickOpenWidget = new quickOpenWidget_1.QuickOpenWidget(this.domNode, { onOk: onOk, onCancel: onCancel, onType: onType }, { inputPlaceHolder: undefined, inputAriaLabel: configuration.inputAriaLabel, keyboardSupport: true }); this.styler = styler_1.attachQuickOpenStyler(this.quickOpenWidget, this.themeService, { pickerGroupForeground: colorRegistry_1.foreground }); this.quickOpenWidget.create(); this.codeEditor.addOverlayWidget(this); } QuickOpenEditorWidget.prototype.setInput = function (model, focus) { this.quickOpenWidget.setInput(model, focus); }; QuickOpenEditorWidget.prototype.getId = function () { return QuickOpenEditorWidget.ID; }; QuickOpenEditorWidget.prototype.getDomNode = function () { return this.domNode; }; QuickOpenEditorWidget.prototype.destroy = function () { this.codeEditor.removeOverlayWidget(this); this.quickOpenWidget.dispose(); this.styler.dispose(); }; QuickOpenEditorWidget.prototype.show = function (value) { this.visible = true; var editorLayout = this.codeEditor.getLayoutInfo(); if (editorLayout) { this.quickOpenWidget.layout(new dom_1.Dimension(editorLayout.width, editorLayout.height)); } this.quickOpenWidget.show(value); this.codeEditor.layoutOverlayWidget(this); }; QuickOpenEditorWidget.prototype.getPosition = function () { if (this.visible) { return { preference: 2 /* TOP_CENTER */ }; } return null; }; QuickOpenEditorWidget.ID = 'editor.contrib.quickOpenEditorWidget'; return QuickOpenEditorWidget; }()); exports.QuickOpenEditorWidget = QuickOpenEditorWidget; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[547/*vs/platform/contextview/browser/contextMenuHandler*/], __M([0/*require*/,1/*exports*/,55/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,205/*vs/base/browser/ui/menu/menu*/,6/*vs/base/browser/dom*/,97/*vs/platform/theme/common/styler*/,52/*vs/base/browser/event*/,45/*vs/base/browser/mouseEvent*/,332/*vs/css!vs/platform/contextview/browser/contextMenuHandler*/]), function (require, exports, actions_1, lifecycle_1, menu_1, dom_1, styler_1, event_1, mouseEvent_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ContextMenuHandler = /** @class */ (function () { function ContextMenuHandler(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 }; } ContextMenuHandler.prototype.configure = function (options) { this.options = options; }; ContextMenuHandler.prototype.showContextMenu = function (delegate) { var _this = this; var actions = delegate.getActions(); if (!actions.length) { return; // Don't render an empty context menu } this.focusToReturn = document.activeElement; var menu; this.contextViewService.showContextView({ getAnchor: function () { return delegate.getAnchor(); }, canRelayout: false, anchorAlignment: delegate.anchorAlignment, render: function (container) { var 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(dom_1.$('.context-view-block')); } var menuDisposables = new lifecycle_1.DisposableStore(); var actionRunner = delegate.actionRunner || new actions_1.ActionRunner(); actionRunner.onDidBeforeRun(_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: actionRunner, getKeyBinding: delegate.getKeyBinding ? delegate.getKeyBinding : function (action) { return _this.keybindingService.lookupKeybinding(action.id); } }); menuDisposables.add(styler_1.attachMenuStyler(menu, _this.themeService)); menu.onDidCancel(function () { return _this.contextViewService.hideContextView(true); }, null, menuDisposables); menu.onDidBlur(function () { return _this.contextViewService.hideContextView(true); }, null, menuDisposables); event_1.domEvent(window, dom_1.EventType.BLUR)(function () { _this.contextViewService.hideContextView(true); }, null, menuDisposables); event_1.domEvent(window, dom_1.EventType.MOUSE_DOWN)(function (e) { if (e.defaultPrevented) { return; } var event = new mouseEvent_1.StandardMouseEvent(e); var 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); }, null, menuDisposables); return lifecycle_1.combinedDisposable(menuDisposables, menu); }, focus: function () { if (menu) { menu.focus(!!delegate.autoSelectFirstItem); } }, onHide: function (didCancel) { if (delegate.onHide) { delegate.onHide(!!didCancel); } if (_this.block) { dom_1.removeNode(_this.block); _this.block = null; } if (_this.focusToReturn) { _this.focusToReturn.focus(); } } }); }; ContextMenuHandler.prototype.onActionRun = function (e) { if (this.telemetryService) { this.telemetryService.publicLog2('workbenchActionExecuted', { id: e.action.id, from: 'contextMenu' }); } this.contextViewService.hideContextView(false); // Restore focus here if (this.focusToReturn) { this.focusToReturn.focus(); } }; ContextMenuHandler.prototype.onDidActionRun = function (e) { if (e.error && this.notificationService) { this.notificationService.error(e.error); } }; return ContextMenuHandler; }()); 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[14/*vs/platform/theme/common/themeService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/,2/*vs/base/common/lifecycle*/,42/*vs/platform/registry/common/platform*/,4/*vs/base/common/event*/]), function (require, exports, instantiation_1, lifecycle_1, platform, event_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IThemeService = instantiation_1.createDecorator('themeService'); function themeColorFromId(id) { return { id: id }; } exports.themeColorFromId = themeColorFromId; // base themes exports.DARK = 'dark'; exports.HIGH_CONTRAST = 'hc'; function getThemeTypeSelector(type) { switch (type) { case exports.DARK: return 'vs-dark'; case exports.HIGH_CONTRAST: return 'hc-black'; default: return 'vs'; } } exports.getThemeTypeSelector = getThemeTypeSelector; // static theming participant exports.Extensions = { ThemingContribution: 'base.contributions.theming' }; var ThemingRegistry = /** @class */ (function () { function ThemingRegistry() { this.themingParticipants = []; this.themingParticipants = []; this.onThemingParticipantAddedEmitter = new event_1.Emitter(); } ThemingRegistry.prototype.onThemeChange = function (participant) { var _this = this; this.themingParticipants.push(participant); this.onThemingParticipantAddedEmitter.fire(participant); return lifecycle_1.toDisposable(function () { var idx = _this.themingParticipants.indexOf(participant); _this.themingParticipants.splice(idx, 1); }); }; ThemingRegistry.prototype.getThemingParticipants = function () { return this.themingParticipants; }; return ThemingRegistry; }()); var themingRegistry = new ThemingRegistry(); platform.Registry.add(exports.Extensions.ThemingContribution, themingRegistry); function registerThemingParticipant(participant) { return themingRegistry.onThemeChange(participant); } exports.registerThemingParticipant = registerThemingParticipant; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[548/*vs/editor/browser/services/codeEditorServiceImpl*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,25/*vs/base/common/uri*/,334/*vs/editor/browser/services/abstractCodeEditorService*/,68/*vs/editor/common/editorCommon*/,48/*vs/editor/common/model*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, dom, lifecycle_1, strings, uri_1, abstractCodeEditorService_1, editorCommon_1, model_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var RefCountedStyleSheet = /** @class */ (function () { function RefCountedStyleSheet(parent, editorId, styleSheet) { this._parent = parent; this._editorId = editorId; this.styleSheet = styleSheet; this._refCount = 0; } RefCountedStyleSheet.prototype.ref = function () { this._refCount++; }; RefCountedStyleSheet.prototype.unref = function () { var _a; this._refCount--; if (this._refCount === 0) { (_a = this.styleSheet.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this.styleSheet); this._parent._removeEditorStyleSheets(this._editorId); } }; return RefCountedStyleSheet; }()); var GlobalStyleSheet = /** @class */ (function () { function GlobalStyleSheet(styleSheet) { this.styleSheet = styleSheet; } GlobalStyleSheet.prototype.ref = function () { }; GlobalStyleSheet.prototype.unref = function () { }; return GlobalStyleSheet; }()); var CodeEditorServiceImpl = /** @class */ (function (_super) { __extends(CodeEditorServiceImpl, _super); function CodeEditorServiceImpl(themeService, styleSheet) { if (styleSheet === void 0) { styleSheet = null; } var _this = _super.call(this) || this; _this._decorationOptionProviders = new Map(); _this._editorStyleSheets = new Map(); _this._globalStyleSheet = styleSheet ? new GlobalStyleSheet(styleSheet) : null; _this._themeService = themeService; return _this; } CodeEditorServiceImpl.prototype._getOrCreateGlobalStyleSheet = function () { if (!this._globalStyleSheet) { this._globalStyleSheet = new GlobalStyleSheet(dom.createStyleSheet()); } return this._globalStyleSheet; }; CodeEditorServiceImpl.prototype._getOrCreateStyleSheet = function (editor) { if (!editor) { return this._getOrCreateGlobalStyleSheet(); } var domNode = editor.getContainerDomNode(); if (!dom.isInShadowDOM(domNode)) { return this._getOrCreateGlobalStyleSheet(); } var editorId = editor.getId(); if (!this._editorStyleSheets.has(editorId)) { var refCountedStyleSheet = new RefCountedStyleSheet(this, editorId, dom.createStyleSheet(domNode)); this._editorStyleSheets.set(editorId, refCountedStyleSheet); } return this._editorStyleSheets.get(editorId); }; CodeEditorServiceImpl.prototype._removeEditorStyleSheets = function (editorId) { this._editorStyleSheets.delete(editorId); }; CodeEditorServiceImpl.prototype.registerDecorationType = function (key, options, parentTypeKey, editor) { var provider = this._decorationOptionProviders.get(key); if (!provider) { var styleSheet = this._getOrCreateStyleSheet(editor); var providerArgs = { styleSheet: styleSheet.styleSheet, key: key, parentTypeKey: parentTypeKey, options: options || Object.create(null) }; if (!parentTypeKey) { provider = new DecorationTypeOptionsProvider(this._themeService, styleSheet, providerArgs); } else { provider = new DecorationSubTypeOptionsProvider(this._themeService, styleSheet, providerArgs); } this._decorationOptionProviders.set(key, provider); } provider.refCount++; }; CodeEditorServiceImpl.prototype.removeDecorationType = function (key) { var provider = this._decorationOptionProviders.get(key); if (provider) { provider.refCount--; if (provider.refCount <= 0) { this._decorationOptionProviders.delete(key); provider.dispose(); this.listCodeEditors().forEach(function (ed) { return ed.removeDecorations(key); }); } } }; CodeEditorServiceImpl.prototype.resolveDecorationOptions = function (decorationTypeKey, writable) { var provider = this._decorationOptionProviders.get(decorationTypeKey); if (!provider) { throw new Error('Unknown decoration type key: ' + decorationTypeKey); } return provider.getOptions(this, writable); }; CodeEditorServiceImpl = __decorate([ __param(0, themeService_1.IThemeService) ], CodeEditorServiceImpl); return CodeEditorServiceImpl; }(abstractCodeEditorService_1.AbstractCodeEditorService)); exports.CodeEditorServiceImpl = CodeEditorServiceImpl; var DecorationSubTypeOptionsProvider = /** @class */ (function () { function DecorationSubTypeOptionsProvider(themeService, styleSheet, providerArgs) { this._styleSheet = styleSheet; this._styleSheet.ref(); this._parentTypeKey = providerArgs.parentTypeKey; this.refCount = 0; this._beforeContentRules = new DecorationCSSRules(3 /* BeforeContentClassName */, providerArgs, themeService); this._afterContentRules = new DecorationCSSRules(4 /* AfterContentClassName */, providerArgs, themeService); } DecorationSubTypeOptionsProvider.prototype.getOptions = function (codeEditorService, writable) { var options = codeEditorService.resolveDecorationOptions(this._parentTypeKey, true); if (this._beforeContentRules) { options.beforeContentClassName = this._beforeContentRules.className; } if (this._afterContentRules) { options.afterContentClassName = this._afterContentRules.className; } return options; }; DecorationSubTypeOptionsProvider.prototype.dispose = function () { if (this._beforeContentRules) { this._beforeContentRules.dispose(); this._beforeContentRules = null; } if (this._afterContentRules) { this._afterContentRules.dispose(); this._afterContentRules = null; } this._styleSheet.unref(); }; return DecorationSubTypeOptionsProvider; }()); var DecorationTypeOptionsProvider = /** @class */ (function () { function DecorationTypeOptionsProvider(themeService, styleSheet, providerArgs) { var _this = this; this._disposables = new lifecycle_1.DisposableStore(); this._styleSheet = styleSheet; this._styleSheet.ref(); this.refCount = 0; var createCSSRules = function (type) { var rules = new DecorationCSSRules(type, providerArgs, themeService); _this._disposables.add(rules); if (rules.hasContent) { return rules.className; } return undefined; }; var createInlineCSSRules = function (type) { var rules = new DecorationCSSRules(type, providerArgs, themeService); _this._disposables.add(rules); if (rules.hasContent) { return { className: rules.className, hasLetterSpacing: rules.hasLetterSpacing }; } return null; }; this.className = createCSSRules(0 /* ClassName */); var inlineData = createInlineCSSRules(1 /* InlineClassName */); if (inlineData) { this.inlineClassName = inlineData.className; this.inlineClassNameAffectsLetterSpacing = inlineData.hasLetterSpacing; } this.beforeContentClassName = createCSSRules(3 /* BeforeContentClassName */); this.afterContentClassName = createCSSRules(4 /* AfterContentClassName */); this.glyphMarginClassName = createCSSRules(2 /* GlyphMarginClassName */); var options = providerArgs.options; this.isWholeLine = Boolean(options.isWholeLine); this.stickiness = options.rangeBehavior; var lightOverviewRulerColor = options.light && options.light.overviewRulerColor || options.overviewRulerColor; var darkOverviewRulerColor = options.dark && options.dark.overviewRulerColor || options.overviewRulerColor; if (typeof lightOverviewRulerColor !== 'undefined' || typeof darkOverviewRulerColor !== 'undefined') { this.overviewRuler = { color: lightOverviewRulerColor || darkOverviewRulerColor, darkColor: darkOverviewRulerColor || lightOverviewRulerColor, position: options.overviewRulerLane || model_1.OverviewRulerLane.Center }; } } DecorationTypeOptionsProvider.prototype.getOptions = function (codeEditorService, writable) { if (!writable) { return this; } return { inlineClassName: this.inlineClassName, beforeContentClassName: this.beforeContentClassName, afterContentClassName: this.afterContentClassName, className: this.className, glyphMarginClassName: this.glyphMarginClassName, isWholeLine: this.isWholeLine, overviewRuler: this.overviewRuler, stickiness: this.stickiness }; }; DecorationTypeOptionsProvider.prototype.dispose = function () { this._disposables.dispose(); this._styleSheet.unref(); }; return DecorationTypeOptionsProvider; }()); var _CSS_MAP = { color: 'color:{0} !important;', opacity: 'opacity:{0};', backgroundColor: 'background-color:{0};', outline: 'outline:{0};', outlineColor: 'outline-color:{0};', outlineStyle: 'outline-style:{0};', outlineWidth: 'outline-width:{0};', border: 'border:{0};', borderColor: 'border-color:{0};', borderRadius: 'border-radius:{0};', borderSpacing: 'border-spacing:{0};', borderStyle: 'border-style:{0};', borderWidth: 'border-width:{0};', fontStyle: 'font-style:{0};', fontWeight: 'font-weight:{0};', textDecoration: 'text-decoration:{0};', cursor: 'cursor:{0};', letterSpacing: 'letter-spacing:{0};', gutterIconPath: 'background:{0} center center no-repeat;', gutterIconSize: 'background-size:{0};', contentText: 'content:\'{0}\';', contentIconPath: 'content:{0};', margin: 'margin:{0};', width: 'width:{0};', height: 'height:{0};' }; var DecorationCSSRules = /** @class */ (function () { function DecorationCSSRules(ruleType, providerArgs, themeService) { var _this = this; this._theme = themeService.getTheme(); this._ruleType = ruleType; this._providerArgs = providerArgs; this._usesThemeColors = false; this._hasContent = false; this._hasLetterSpacing = false; var className = CSSNameHelper.getClassName(this._providerArgs.key, ruleType); if (this._providerArgs.parentTypeKey) { className = className + ' ' + CSSNameHelper.getClassName(this._providerArgs.parentTypeKey, ruleType); } this._className = className; this._unThemedSelector = CSSNameHelper.getSelector(this._providerArgs.key, this._providerArgs.parentTypeKey, ruleType); this._buildCSS(); if (this._usesThemeColors) { this._themeListener = themeService.onThemeChange(function (theme) { _this._theme = themeService.getTheme(); _this._removeCSS(); _this._buildCSS(); }); } else { this._themeListener = null; } } DecorationCSSRules.prototype.dispose = function () { if (this._hasContent) { this._removeCSS(); this._hasContent = false; } if (this._themeListener) { this._themeListener.dispose(); this._themeListener = null; } }; Object.defineProperty(DecorationCSSRules.prototype, "hasContent", { get: function () { return this._hasContent; }, enumerable: true, configurable: true }); Object.defineProperty(DecorationCSSRules.prototype, "hasLetterSpacing", { get: function () { return this._hasLetterSpacing; }, enumerable: true, configurable: true }); Object.defineProperty(DecorationCSSRules.prototype, "className", { get: function () { return this._className; }, enumerable: true, configurable: true }); DecorationCSSRules.prototype._buildCSS = function () { var options = this._providerArgs.options; var unthemedCSS, lightCSS, darkCSS; switch (this._ruleType) { case 0 /* ClassName */: unthemedCSS = this.getCSSTextForModelDecorationClassName(options); lightCSS = this.getCSSTextForModelDecorationClassName(options.light); darkCSS = this.getCSSTextForModelDecorationClassName(options.dark); break; case 1 /* InlineClassName */: unthemedCSS = this.getCSSTextForModelDecorationInlineClassName(options); lightCSS = this.getCSSTextForModelDecorationInlineClassName(options.light); darkCSS = this.getCSSTextForModelDecorationInlineClassName(options.dark); break; case 2 /* GlyphMarginClassName */: unthemedCSS = this.getCSSTextForModelDecorationGlyphMarginClassName(options); lightCSS = this.getCSSTextForModelDecorationGlyphMarginClassName(options.light); darkCSS = this.getCSSTextForModelDecorationGlyphMarginClassName(options.dark); break; case 3 /* BeforeContentClassName */: unthemedCSS = this.getCSSTextForModelDecorationContentClassName(options.before); lightCSS = this.getCSSTextForModelDecorationContentClassName(options.light && options.light.before); darkCSS = this.getCSSTextForModelDecorationContentClassName(options.dark && options.dark.before); break; case 4 /* AfterContentClassName */: unthemedCSS = this.getCSSTextForModelDecorationContentClassName(options.after); lightCSS = this.getCSSTextForModelDecorationContentClassName(options.light && options.light.after); darkCSS = this.getCSSTextForModelDecorationContentClassName(options.dark && options.dark.after); break; default: throw new Error('Unknown rule type: ' + this._ruleType); } var sheet = this._providerArgs.styleSheet.sheet; var hasContent = false; if (unthemedCSS.length > 0) { sheet.insertRule(this._unThemedSelector + " {" + unthemedCSS + "}", 0); hasContent = true; } if (lightCSS.length > 0) { sheet.insertRule(".vs" + this._unThemedSelector + " {" + lightCSS + "}", 0); hasContent = true; } if (darkCSS.length > 0) { sheet.insertRule(".vs-dark" + this._unThemedSelector + ", .hc-black" + this._unThemedSelector + " {" + darkCSS + "}", 0); hasContent = true; } this._hasContent = hasContent; }; DecorationCSSRules.prototype._removeCSS = function () { dom.removeCSSRulesContainingSelector(this._unThemedSelector, this._providerArgs.styleSheet); }; /** * Build the CSS for decorations styled via `className`. */ DecorationCSSRules.prototype.getCSSTextForModelDecorationClassName = function (opts) { if (!opts) { return ''; } var cssTextArr = []; this.collectCSSText(opts, ['backgroundColor'], cssTextArr); this.collectCSSText(opts, ['outline', 'outlineColor', 'outlineStyle', 'outlineWidth'], cssTextArr); this.collectBorderSettingsCSSText(opts, cssTextArr); return cssTextArr.join(''); }; /** * Build the CSS for decorations styled via `inlineClassName`. */ DecorationCSSRules.prototype.getCSSTextForModelDecorationInlineClassName = function (opts) { if (!opts) { return ''; } var cssTextArr = []; this.collectCSSText(opts, ['fontStyle', 'fontWeight', 'textDecoration', 'cursor', 'color', 'opacity', 'letterSpacing'], cssTextArr); if (opts.letterSpacing) { this._hasLetterSpacing = true; } return cssTextArr.join(''); }; /** * Build the CSS for decorations styled before or after content. */ DecorationCSSRules.prototype.getCSSTextForModelDecorationContentClassName = function (opts) { if (!opts) { return ''; } var cssTextArr = []; if (typeof opts !== 'undefined') { this.collectBorderSettingsCSSText(opts, cssTextArr); if (typeof opts.contentIconPath !== 'undefined') { cssTextArr.push(strings.format(_CSS_MAP.contentIconPath, dom.asCSSUrl(uri_1.URI.revive(opts.contentIconPath)))); } if (typeof opts.contentText === 'string') { var truncated = opts.contentText.match(/^.*$/m)[0]; // only take first line var escaped = truncated.replace(/['\\]/g, '\\$&'); cssTextArr.push(strings.format(_CSS_MAP.contentText, escaped)); } this.collectCSSText(opts, ['fontStyle', 'fontWeight', 'textDecoration', 'color', 'opacity', 'backgroundColor', 'margin'], cssTextArr); if (this.collectCSSText(opts, ['width', 'height'], cssTextArr)) { cssTextArr.push('display:inline-block;'); } } return cssTextArr.join(''); }; /** * Build the CSS for decorations styled via `glpyhMarginClassName`. */ DecorationCSSRules.prototype.getCSSTextForModelDecorationGlyphMarginClassName = function (opts) { if (!opts) { return ''; } var cssTextArr = []; if (typeof opts.gutterIconPath !== 'undefined') { cssTextArr.push(strings.format(_CSS_MAP.gutterIconPath, dom.asCSSUrl(uri_1.URI.revive(opts.gutterIconPath)))); if (typeof opts.gutterIconSize !== 'undefined') { cssTextArr.push(strings.format(_CSS_MAP.gutterIconSize, opts.gutterIconSize)); } } return cssTextArr.join(''); }; DecorationCSSRules.prototype.collectBorderSettingsCSSText = function (opts, cssTextArr) { if (this.collectCSSText(opts, ['border', 'borderColor', 'borderRadius', 'borderSpacing', 'borderStyle', 'borderWidth'], cssTextArr)) { cssTextArr.push(strings.format('box-sizing: border-box;')); return true; } return false; }; DecorationCSSRules.prototype.collectCSSText = function (opts, properties, cssTextArr) { var lenBefore = cssTextArr.length; for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { var property = properties_1[_i]; var value = this.resolveValue(opts[property]); if (typeof value === 'string') { cssTextArr.push(strings.format(_CSS_MAP[property], value)); } } return cssTextArr.length !== lenBefore; }; DecorationCSSRules.prototype.resolveValue = function (value) { if (editorCommon_1.isThemeColor(value)) { this._usesThemeColors = true; var color = this._theme.getColor(value.id); if (color) { return color.toString(); } return 'transparent'; } return value; }; return DecorationCSSRules; }()); var CSSNameHelper = /** @class */ (function () { function CSSNameHelper() { } CSSNameHelper.getClassName = function (key, type) { return 'ced-' + key + '-' + type; }; CSSNameHelper.getSelector = function (key, parentKey, ruleType) { var selector = '.monaco-editor .' + this.getClassName(key, ruleType); if (parentKey) { selector = selector + '.' + this.getClassName(parentKey, ruleType); } if (ruleType === 3 /* BeforeContentClassName */) { selector += '::before'; } else if (ruleType === 4 /* AfterContentClassName */) { selector += '::after'; } return selector; }; return CSSNameHelper; }()); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[549/*vs/editor/browser/viewParts/editorScrollbar/editorScrollbar*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,28/*vs/base/browser/fastDomNode*/,53/*vs/base/browser/ui/scrollbar/scrollableElement*/,37/*vs/editor/browser/view/viewPart*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, dom, fastDomNode_1, scrollableElement_1, viewPart_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var EditorScrollbar = /** @class */ (function (_super) { __extends(EditorScrollbar, _super); function EditorScrollbar(context, linesContent, viewDomNode, overflowGuardDomNode) { var _this = _super.call(this, context) || this; var options = _this._context.configuration.options; var scrollbar = options.get(78 /* scrollbar */); var mouseWheelScrollSensitivity = options.get(56 /* mouseWheelScrollSensitivity */); var fastScrollSensitivity = options.get(27 /* fastScrollSensitivity */); var scrollbarOptions = { listenOnDomNode: viewDomNode.domNode, className: 'editor-scrollable' + ' ' + themeService_1.getThemeTypeSelector(context.theme.type), useShadows: false, lazyRender: true, vertical: scrollbar.vertical, horizontal: scrollbar.horizontal, verticalHasArrows: scrollbar.verticalHasArrows, horizontalHasArrows: scrollbar.horizontalHasArrows, verticalScrollbarSize: scrollbar.verticalScrollbarSize, verticalSliderSize: scrollbar.verticalSliderSize, horizontalScrollbarSize: scrollbar.horizontalScrollbarSize, horizontalSliderSize: scrollbar.horizontalSliderSize, handleMouseWheel: scrollbar.handleMouseWheel, alwaysConsumeMouseWheel: scrollbar.alwaysConsumeMouseWheel, arrowSize: scrollbar.arrowSize, mouseWheelScrollSensitivity: mouseWheelScrollSensitivity, fastScrollSensitivity: fastScrollSensitivity, }; _this.scrollbar = _this._register(new scrollableElement_1.SmoothScrollableElement(linesContent.domNode, scrollbarOptions, _this._context.viewLayout.getScrollable())); viewPart_1.PartFingerprints.write(_this.scrollbar.getDomNode(), 5 /* ScrollableElement */); _this.scrollbarDomNode = fastDomNode_1.createFastDomNode(_this.scrollbar.getDomNode()); _this.scrollbarDomNode.setPosition('absolute'); _this._setLayout(); // When having a zone widget that calls .focus() on one of its dom elements, // the browser will try desperately to reveal that dom node, unexpectedly // changing the .scrollTop of this.linesContent var onBrowserDesperateReveal = function (domNode, lookAtScrollTop, lookAtScrollLeft) { var newScrollPosition = {}; if (lookAtScrollTop) { var deltaTop = domNode.scrollTop; if (deltaTop) { newScrollPosition.scrollTop = _this._context.viewLayout.getCurrentScrollTop() + deltaTop; domNode.scrollTop = 0; } } if (lookAtScrollLeft) { var deltaLeft = domNode.scrollLeft; if (deltaLeft) { newScrollPosition.scrollLeft = _this._context.viewLayout.getCurrentScrollLeft() + deltaLeft; domNode.scrollLeft = 0; } } _this._context.viewLayout.setScrollPositionNow(newScrollPosition); }; // I've seen this happen both on the view dom node & on the lines content dom node. _this._register(dom.addDisposableListener(viewDomNode.domNode, 'scroll', function (e) { return onBrowserDesperateReveal(viewDomNode.domNode, true, true); })); _this._register(dom.addDisposableListener(linesContent.domNode, 'scroll', function (e) { return onBrowserDesperateReveal(linesContent.domNode, true, false); })); _this._register(dom.addDisposableListener(overflowGuardDomNode.domNode, 'scroll', function (e) { return onBrowserDesperateReveal(overflowGuardDomNode.domNode, true, false); })); _this._register(dom.addDisposableListener(_this.scrollbarDomNode.domNode, 'scroll', function (e) { return onBrowserDesperateReveal(_this.scrollbarDomNode.domNode, true, false); })); return _this; } EditorScrollbar.prototype.dispose = function () { _super.prototype.dispose.call(this); }; EditorScrollbar.prototype._setLayout = function () { var options = this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); this.scrollbarDomNode.setLeft(layoutInfo.contentLeft); var minimap = options.get(54 /* minimap */); var side = minimap.side; if (side === 'right') { this.scrollbarDomNode.setWidth(layoutInfo.contentWidth + layoutInfo.minimapWidth); } else { this.scrollbarDomNode.setWidth(layoutInfo.contentWidth); } this.scrollbarDomNode.setHeight(layoutInfo.height); }; EditorScrollbar.prototype.getOverviewRulerLayoutInfo = function () { return this.scrollbar.getOverviewRulerLayoutInfo(); }; EditorScrollbar.prototype.getDomNode = function () { return this.scrollbarDomNode; }; EditorScrollbar.prototype.delegateVerticalScrollbarMouseDown = function (browserEvent) { this.scrollbar.delegateVerticalScrollbarMouseDown(browserEvent); }; // --- begin event handlers EditorScrollbar.prototype.onConfigurationChanged = function (e) { if (e.hasChanged(78 /* scrollbar */) || e.hasChanged(56 /* mouseWheelScrollSensitivity */) || e.hasChanged(27 /* fastScrollSensitivity */)) { var options = this._context.configuration.options; var scrollbar = options.get(78 /* scrollbar */); var mouseWheelScrollSensitivity = options.get(56 /* mouseWheelScrollSensitivity */); var fastScrollSensitivity = options.get(27 /* fastScrollSensitivity */); var newOpts = { handleMouseWheel: scrollbar.handleMouseWheel, mouseWheelScrollSensitivity: mouseWheelScrollSensitivity, fastScrollSensitivity: fastScrollSensitivity }; this.scrollbar.updateOptions(newOpts); } if (e.hasChanged(107 /* layoutInfo */)) { this._setLayout(); } return true; }; EditorScrollbar.prototype.onScrollChanged = function (e) { return true; }; EditorScrollbar.prototype.onThemeChanged = function (e) { this.scrollbar.updateClassName('editor-scrollable' + ' ' + themeService_1.getThemeTypeSelector(this._context.theme.type)); return true; }; // --- end event handlers EditorScrollbar.prototype.prepareRender = function (ctx) { // Nothing to do }; EditorScrollbar.prototype.render = function (ctx) { this.scrollbar.renderNow(); }; return EditorScrollbar; }(viewPart_1.ViewPart)); exports.EditorScrollbar = EditorScrollbar; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[227/*vs/editor/browser/viewParts/lines/viewLine*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,28/*vs/base/browser/fastDomNode*/,16/*vs/base/common/platform*/,359/*vs/editor/browser/viewParts/lines/rangeUtil*/,91/*vs/editor/common/view/renderingContext*/,148/*vs/editor/common/viewLayout/lineDecorations*/,110/*vs/editor/common/viewLayout/viewLineRenderer*/,14/*vs/platform/theme/common/themeService*/,33/*vs/editor/common/config/editorOptions*/]), function (require, exports, browser, fastDomNode_1, platform, rangeUtil_1, renderingContext_1, lineDecorations_1, viewLineRenderer_1, themeService_1, editorOptions_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var 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; })(); var alwaysRenderInlineSelection = (browser.isEdgeOrIE); var DomReadingContext = /** @class */ (function () { function DomReadingContext(domNode, endNode) { this._domNode = domNode; this._clientRectDeltaLeft = 0; this._clientRectDeltaLeftRead = false; this.endNode = endNode; } Object.defineProperty(DomReadingContext.prototype, "clientRectDeltaLeft", { get: function () { if (!this._clientRectDeltaLeftRead) { this._clientRectDeltaLeftRead = true; this._clientRectDeltaLeft = this._domNode.getBoundingClientRect().left; } return this._clientRectDeltaLeft; }, enumerable: true, configurable: true }); return DomReadingContext; }()); exports.DomReadingContext = DomReadingContext; var ViewLineOptions = /** @class */ (function () { function ViewLineOptions(config, themeType) { this.themeType = themeType; var options = config.options; var fontInfo = options.get(34 /* fontInfo */); this.renderWhitespace = options.get(74 /* renderWhitespace */); this.renderControlCharacters = options.get(69 /* renderControlCharacters */); this.spaceWidth = fontInfo.spaceWidth; this.middotWidth = fontInfo.middotWidth; this.useMonospaceOptimizations = (fontInfo.isMonospace && !options.get(23 /* disableMonospaceOptimizations */)); this.canUseHalfwidthRightwardsArrow = fontInfo.canUseHalfwidthRightwardsArrow; this.lineHeight = options.get(49 /* lineHeight */); this.stopRenderingLineAfter = options.get(88 /* stopRenderingLineAfter */); this.fontLigatures = options.get(35 /* fontLigatures */); } ViewLineOptions.prototype.equals = function (other) { return (this.themeType === other.themeType && this.renderWhitespace === other.renderWhitespace && this.renderControlCharacters === other.renderControlCharacters && this.spaceWidth === other.spaceWidth && this.middotWidth === other.middotWidth && this.useMonospaceOptimizations === other.useMonospaceOptimizations && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.lineHeight === other.lineHeight && this.stopRenderingLineAfter === other.stopRenderingLineAfter && this.fontLigatures === other.fontLigatures); }; return ViewLineOptions; }()); exports.ViewLineOptions = ViewLineOptions; var ViewLine = /** @class */ (function () { function ViewLine(options) { this._options = options; this._isMaybeInvalid = true; this._renderedViewLine = null; } // --- begin IVisibleLineData ViewLine.prototype.getDomNode = function () { if (this._renderedViewLine && this._renderedViewLine.domNode) { return this._renderedViewLine.domNode.domNode; } return null; }; ViewLine.prototype.setDomNode = function (domNode) { if (this._renderedViewLine) { this._renderedViewLine.domNode = fastDomNode_1.createFastDomNode(domNode); } else { throw new Error('I have no rendered view line to set the dom node to...'); } }; ViewLine.prototype.onContentChanged = function () { this._isMaybeInvalid = true; }; ViewLine.prototype.onTokensChanged = function () { this._isMaybeInvalid = true; }; ViewLine.prototype.onDecorationsChanged = function () { this._isMaybeInvalid = true; }; ViewLine.prototype.onOptionsChanged = function (newOptions) { this._isMaybeInvalid = true; this._options = newOptions; }; ViewLine.prototype.onSelectionChanged = function () { if (alwaysRenderInlineSelection || this._options.themeType === themeService_1.HIGH_CONTRAST || this._options.renderWhitespace === 'selection') { this._isMaybeInvalid = true; return true; } return false; }; ViewLine.prototype.renderLine = function (lineNumber, deltaTop, viewportData, sb) { if (this._isMaybeInvalid === false) { // it appears that nothing relevant has changed return false; } this._isMaybeInvalid = false; var lineData = viewportData.getViewLineRenderingData(lineNumber); var options = this._options; var actualInlineDecorations = lineDecorations_1.LineDecoration.filter(lineData.inlineDecorations, lineNumber, lineData.minColumn, lineData.maxColumn); // Only send selection information when needed for rendering whitespace var selectionsOnLine = null; if (alwaysRenderInlineSelection || options.themeType === themeService_1.HIGH_CONTRAST || this._options.renderWhitespace === 'selection') { var selections = viewportData.selections; for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) { var selection = selections_1[_i]; if (selection.endLineNumber < lineNumber || selection.startLineNumber > lineNumber) { // Selection does not intersect line continue; } var startColumn = (selection.startLineNumber === lineNumber ? selection.startColumn : lineData.minColumn); var endColumn = (selection.endLineNumber === lineNumber ? selection.endColumn : lineData.maxColumn); if (startColumn < endColumn) { if (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)); } } } } var 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.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('
    '); var output = viewLineRenderer_1.renderViewLine(renderLineInput, sb); sb.appendASCIIString('
    '); var renderedViewLine = null; if (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; }; ViewLine.prototype.layoutLine = function (lineNumber, deltaTop) { if (this._renderedViewLine && this._renderedViewLine.domNode) { this._renderedViewLine.domNode.setTop(deltaTop); this._renderedViewLine.domNode.setHeight(this._options.lineHeight); } }; // --- end IVisibleLineData ViewLine.prototype.getWidth = function () { if (!this._renderedViewLine) { return 0; } return this._renderedViewLine.getWidth(); }; ViewLine.prototype.getWidthIsFast = function () { if (!this._renderedViewLine) { return true; } return this._renderedViewLine.getWidthIsFast(); }; ViewLine.prototype.getVisibleRangesForRange = function (startColumn, endColumn, context) { if (!this._renderedViewLine) { return null; } startColumn = startColumn | 0; // @perf endColumn = endColumn | 0; // @perf startColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, startColumn)); endColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, endColumn)); var stopRenderingLineAfter = this._renderedViewLine.input.stopRenderingLineAfter | 0; // @perf var 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; } var horizontalRanges = this._renderedViewLine.getVisibleRangesForRange(startColumn, endColumn, context); if (horizontalRanges && horizontalRanges.length > 0) { return new renderingContext_1.VisibleRanges(outsideRenderedLine, horizontalRanges); } return null; }; ViewLine.prototype.getColumnOfNodeOffset = function (lineNumber, spanNode, offset) { if (!this._renderedViewLine) { return 1; } return this._renderedViewLine.getColumnOfNodeOffset(lineNumber, spanNode, offset); }; ViewLine.CLASS_NAME = 'view-line'; return ViewLine; }()); exports.ViewLine = ViewLine; /** * A rendered line which is guaranteed to contain only regular ASCII and is rendered with a monospace font. */ var FastRenderedViewLine = /** @class */ (function () { function FastRenderedViewLine(domNode, renderLineInput, characterMapping) { this.domNode = domNode; this.input = renderLineInput; this._characterMapping = characterMapping; this._charWidth = renderLineInput.spaceWidth; } FastRenderedViewLine.prototype.getWidth = function () { return this._getCharPosition(this._characterMapping.length); }; FastRenderedViewLine.prototype.getWidthIsFast = function () { return true; }; FastRenderedViewLine.prototype.getVisibleRangesForRange = function (startColumn, endColumn, context) { var startPosition = this._getCharPosition(startColumn); var endPosition = this._getCharPosition(endColumn); return [new renderingContext_1.HorizontalRange(startPosition, endPosition - startPosition)]; }; FastRenderedViewLine.prototype._getCharPosition = function (column) { var charOffset = this._characterMapping.getAbsoluteOffsets(); if (charOffset.length === 0) { // No characters on this line return 0; } return Math.round(this._charWidth * charOffset[column - 1]); }; FastRenderedViewLine.prototype.getColumnOfNodeOffset = function (lineNumber, spanNode, offset) { var spanNodeTextContentLength = spanNode.textContent.length; var spanIndex = -1; while (spanNode) { spanNode = spanNode.previousSibling; spanIndex++; } var charOffset = this._characterMapping.partDataToCharOffset(spanIndex, spanNodeTextContentLength, offset); return charOffset + 1; }; return FastRenderedViewLine; }()); /** * Every time we render a line, we save what we have rendered in an instance of this class. */ var RenderedViewLine = /** @class */ (function () { function RenderedViewLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements) { this.domNode = domNode; this.input = renderLineInput; this._characterMapping = characterMapping; this._isWhitespaceOnly = /^\s*$/.test(renderLineInput.lineContent); this._containsForeignElements = containsForeignElements; this._cachedWidth = -1; this._pixelOffsetCache = null; if (!containsRTL || this._characterMapping.length === 0 /* the line is empty */) { this._pixelOffsetCache = new Int32Array(Math.max(2, this._characterMapping.length + 1)); for (var column = 0, len = this._characterMapping.length; column <= len; column++) { this._pixelOffsetCache[column] = -1; } } } // --- Reading from the DOM methods RenderedViewLine.prototype._getReadingTarget = function (myDomNode) { return myDomNode.domNode.firstChild; }; /** * Width of the line in pixels */ RenderedViewLine.prototype.getWidth = function () { if (!this.domNode) { return 0; } if (this._cachedWidth === -1) { this._cachedWidth = this._getReadingTarget(this.domNode).offsetWidth; } return this._cachedWidth; }; RenderedViewLine.prototype.getWidthIsFast = function () { if (this._cachedWidth === -1) { return false; } return true; }; /** * Visible ranges for a model range */ RenderedViewLine.prototype.getVisibleRangesForRange = function (startColumn, endColumn, context) { if (!this.domNode) { return null; } if (this._pixelOffsetCache !== null) { // the text is LTR var startOffset = this._readPixelOffset(this.domNode, startColumn, context); if (startOffset === -1) { return null; } var endOffset = this._readPixelOffset(this.domNode, endColumn, context); if (endOffset === -1) { return null; } return [new renderingContext_1.HorizontalRange(startOffset, endOffset - startOffset)]; } return this._readVisibleRangesForRange(this.domNode, startColumn, endColumn, context); }; RenderedViewLine.prototype._readVisibleRangesForRange = function (domNode, startColumn, endColumn, context) { if (startColumn === endColumn) { var pixelOffset = this._readPixelOffset(domNode, startColumn, context); if (pixelOffset === -1) { return null; } else { return [new renderingContext_1.HorizontalRange(pixelOffset, 0)]; } } else { return this._readRawVisibleRangesForRange(domNode, startColumn, endColumn, context); } }; RenderedViewLine.prototype._readPixelOffset = function (domNode, column, context) { if (this._characterMapping.length === 0) { // This line has no content if (this._containsForeignElements === 0 /* None */) { // We can assume the line is really empty return 0; } if (this._containsForeignElements === 2 /* After */) { // We have foreign elements after the (empty) line return 0; } if (this._containsForeignElements === 1 /* Before */) { // We have foreign elements before the (empty) line return this.getWidth(); } // We have foreign elements before & after the (empty) line var readingTarget = this._getReadingTarget(domNode); if (readingTarget.firstChild) { return readingTarget.firstChild.offsetWidth; } else { return 0; } } if (this._pixelOffsetCache !== null) { // the text is LTR var cachedPixelOffset = this._pixelOffsetCache[column]; if (cachedPixelOffset !== -1) { return cachedPixelOffset; } var result = this._actualReadPixelOffset(domNode, column, context); this._pixelOffsetCache[column] = result; return result; } return this._actualReadPixelOffset(domNode, column, context); }; RenderedViewLine.prototype._actualReadPixelOffset = function (domNode, column, context) { if (this._characterMapping.length === 0) { // This line has no content var r_1 = rangeUtil_1.RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), 0, 0, 0, 0, context.clientRectDeltaLeft, context.endNode); if (!r_1 || r_1.length === 0) { return -1; } return r_1[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(); } var partData = this._characterMapping.charOffsetToPartData(column - 1); var partIndex = viewLineRenderer_1.CharacterMapping.getPartIndex(partData); var charOffsetInPart = viewLineRenderer_1.CharacterMapping.getCharIndex(partData); var r = rangeUtil_1.RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), partIndex, charOffsetInPart, partIndex, charOffsetInPart, context.clientRectDeltaLeft, context.endNode); if (!r || r.length === 0) { return -1; } return r[0].left; }; RenderedViewLine.prototype._readRawVisibleRangesForRange = function (domNode, startColumn, endColumn, context) { if (startColumn === 1 && endColumn === this._characterMapping.length) { // This branch helps IE with bidi text & gives a performance boost to other browsers when reading visible ranges for an entire line return [new renderingContext_1.HorizontalRange(0, this.getWidth())]; } var startPartData = this._characterMapping.charOffsetToPartData(startColumn - 1); var startPartIndex = viewLineRenderer_1.CharacterMapping.getPartIndex(startPartData); var startCharOffsetInPart = viewLineRenderer_1.CharacterMapping.getCharIndex(startPartData); var endPartData = this._characterMapping.charOffsetToPartData(endColumn - 1); var endPartIndex = viewLineRenderer_1.CharacterMapping.getPartIndex(endPartData); var endCharOffsetInPart = viewLineRenderer_1.CharacterMapping.getCharIndex(endPartData); return rangeUtil_1.RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), startPartIndex, startCharOffsetInPart, endPartIndex, endCharOffsetInPart, context.clientRectDeltaLeft, context.endNode); }; /** * Returns the column for the text found at a specific offset inside a rendered dom node */ RenderedViewLine.prototype.getColumnOfNodeOffset = function (lineNumber, spanNode, offset) { var spanNodeTextContentLength = spanNode.textContent.length; var spanIndex = -1; while (spanNode) { spanNode = spanNode.previousSibling; spanIndex++; } var charOffset = this._characterMapping.partDataToCharOffset(spanIndex, spanNodeTextContentLength, offset); return charOffset + 1; }; return RenderedViewLine; }()); var WebKitRenderedViewLine = /** @class */ (function (_super) { __extends(WebKitRenderedViewLine, _super); function WebKitRenderedViewLine() { return _super !== null && _super.apply(this, arguments) || this; } WebKitRenderedViewLine.prototype._readVisibleRangesForRange = function (domNode, startColumn, endColumn, context) { var output = _super.prototype._readVisibleRangesForRange.call(this, domNode, startColumn, endColumn, context); if (!output || output.length === 0 || startColumn === endColumn || (startColumn === 1 && endColumn === this._characterMapping.length)) { return output; } // WebKit is buggy and returns an expanded range (to contain words in some cases) // The last client rect is enlarged (I think) if (!this.input.containsRTL) { // This is an attempt to patch things up // Find position of last column var endPixelOffset = this._readPixelOffset(domNode, endColumn, context); if (endPixelOffset !== -1) { var 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; }; return WebKitRenderedViewLine; }(RenderedViewLine)); var 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[166/*vs/editor/browser/controller/mouseTarget*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,141/*vs/editor/browser/editorDom*/,37/*vs/editor/browser/view/viewPart*/,227/*vs/editor/browser/viewParts/lines/viewLine*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,40/*vs/editor/common/controller/cursorCommon*/,6/*vs/base/browser/dom*/]), function (require, exports, browser, editorDom_1, viewPart_1, viewLine_1, position_1, range_1, cursorCommon_1, dom) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var PointerHandlerLastRenderData = /** @class */ (function () { function PointerHandlerLastRenderData(lastViewCursorsRenderData, lastTextareaPosition) { this.lastViewCursorsRenderData = lastViewCursorsRenderData; this.lastTextareaPosition = lastTextareaPosition; } return PointerHandlerLastRenderData; }()); exports.PointerHandlerLastRenderData = PointerHandlerLastRenderData; var MouseTarget = /** @class */ (function () { function MouseTarget(element, type, mouseColumn, position, range, detail) { if (mouseColumn === void 0) { mouseColumn = 0; } if (position === void 0) { position = null; } if (range === void 0) { range = null; } if (detail === void 0) { detail = null; } this.element = element; this.type = type; this.mouseColumn = mouseColumn; this.position = position; if (!range && position) { range = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column); } this.range = range; this.detail = detail; } MouseTarget._typeToString = function (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'; }; MouseTarget.toString = function (target) { return this._typeToString(target.type) + ': ' + target.position + ' - ' + target.range + ' - ' + target.detail; }; MouseTarget.prototype.toString = function () { return MouseTarget.toString(this); }; return MouseTarget; }()); exports.MouseTarget = MouseTarget; var ElementPath = /** @class */ (function () { function ElementPath() { } ElementPath.isTextArea = function (path) { return (path.length === 2 && path[0] === 3 /* OverflowGuard */ && path[1] === 6 /* TextArea */); }; ElementPath.isChildOfViewLines = function (path) { return (path.length >= 4 && path[0] === 3 /* OverflowGuard */ && path[3] === 7 /* ViewLines */); }; ElementPath.isStrictChildOfViewLines = function (path) { return (path.length > 4 && path[0] === 3 /* OverflowGuard */ && path[3] === 7 /* ViewLines */); }; ElementPath.isChildOfScrollableElement = function (path) { return (path.length >= 2 && path[0] === 3 /* OverflowGuard */ && path[1] === 5 /* ScrollableElement */); }; ElementPath.isChildOfMinimap = function (path) { return (path.length >= 2 && path[0] === 3 /* OverflowGuard */ && path[1] === 8 /* Minimap */); }; ElementPath.isChildOfContentWidgets = function (path) { return (path.length >= 4 && path[0] === 3 /* OverflowGuard */ && path[3] === 1 /* ContentWidgets */); }; ElementPath.isChildOfOverflowingContentWidgets = function (path) { return (path.length >= 1 && path[0] === 2 /* OverflowingContentWidgets */); }; ElementPath.isChildOfOverlayWidgets = function (path) { return (path.length >= 2 && path[0] === 3 /* OverflowGuard */ && path[1] === 4 /* OverlayWidgets */); }; return ElementPath; }()); var HitTestContext = /** @class */ (function () { function HitTestContext(context, viewHelper, lastRenderData) { this.model = context.model; var options = context.configuration.options; this.layoutInfo = options.get(107 /* layoutInfo */); this.viewDomNode = viewHelper.viewDomNode; this.lineHeight = options.get(49 /* lineHeight */); this.typicalHalfwidthCharacterWidth = options.get(34 /* fontInfo */).typicalHalfwidthCharacterWidth; this.lastRenderData = lastRenderData; this._context = context; this._viewHelper = viewHelper; } HitTestContext.prototype.getZoneAtCoord = function (mouseVerticalOffset) { return HitTestContext.getZoneAtCoord(this._context, mouseVerticalOffset); }; HitTestContext.getZoneAtCoord = function (context, mouseVerticalOffset) { // The target is either a view zone or the empty space after the last view-line var viewZoneWhitespace = context.viewLayout.getWhitespaceAtVerticalOffset(mouseVerticalOffset); if (viewZoneWhitespace) { var viewZoneMiddle = viewZoneWhitespace.verticalOffset + viewZoneWhitespace.height / 2, lineCount = context.model.getLineCount(), positionBefore = null, position = void 0, 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; }; HitTestContext.prototype.getFullLineRangeAtCoord = function (mouseVerticalOffset) { if (this._context.viewLayout.isAfterLines(mouseVerticalOffset)) { // Below the last line var lineNumber_1 = this._context.model.getLineCount(); var maxLineColumn_1 = this._context.model.getLineMaxColumn(lineNumber_1); return { range: new range_1.Range(lineNumber_1, maxLineColumn_1, lineNumber_1, maxLineColumn_1), isAfterLines: true }; } var lineNumber = this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset); var maxLineColumn = this._context.model.getLineMaxColumn(lineNumber); return { range: new range_1.Range(lineNumber, 1, lineNumber, maxLineColumn), isAfterLines: false }; }; HitTestContext.prototype.getLineNumberAtVerticalOffset = function (mouseVerticalOffset) { return this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset); }; HitTestContext.prototype.isAfterLines = function (mouseVerticalOffset) { return this._context.viewLayout.isAfterLines(mouseVerticalOffset); }; HitTestContext.prototype.getVerticalOffsetForLineNumber = function (lineNumber) { return this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber); }; HitTestContext.prototype.findAttribute = function (element, attr) { return HitTestContext._findAttribute(element, attr, this._viewHelper.viewDomNode); }; HitTestContext._findAttribute = function (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; }; HitTestContext.prototype.getLineWidth = function (lineNumber) { return this._viewHelper.getLineWidth(lineNumber); }; HitTestContext.prototype.visibleRangeForPosition = function (lineNumber, column) { return this._viewHelper.visibleRangeForPosition(lineNumber, column); }; HitTestContext.prototype.getPositionFromDOMInfo = function (spanNode, offset) { return this._viewHelper.getPositionFromDOMInfo(spanNode, offset); }; HitTestContext.prototype.getCurrentScrollTop = function () { return this._context.viewLayout.getCurrentScrollTop(); }; HitTestContext.prototype.getCurrentScrollLeft = function () { return this._context.viewLayout.getCurrentScrollLeft(); }; return HitTestContext; }()); exports.HitTestContext = HitTestContext; var BareHitTestRequest = /** @class */ (function () { function BareHitTestRequest(ctx, editorPos, pos) { this.editorPos = editorPos; this.pos = pos; this.mouseVerticalOffset = Math.max(0, ctx.getCurrentScrollTop() + pos.y - editorPos.y); this.mouseContentHorizontalOffset = ctx.getCurrentScrollLeft() + pos.x - editorPos.x - ctx.layoutInfo.contentLeft; this.isInMarginArea = (pos.x - editorPos.x < ctx.layoutInfo.contentLeft && pos.x - editorPos.x >= ctx.layoutInfo.glyphMarginLeft); this.isInContentArea = !this.isInMarginArea; this.mouseColumn = Math.max(0, MouseTargetFactory._getMouseColumn(this.mouseContentHorizontalOffset, ctx.typicalHalfwidthCharacterWidth)); } return BareHitTestRequest; }()); var HitTestRequest = /** @class */ (function (_super) { __extends(HitTestRequest, _super); function HitTestRequest(ctx, editorPos, pos, target) { var _this = _super.call(this, ctx, editorPos, pos) || this; _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); } return _this; } HitTestRequest.prototype.toString = function () { return "pos(" + this.pos.x + "," + this.pos.y + "), editorPos(" + this.editorPos.x + "," + this.editorPos.y + "), mouseVerticalOffset: " + this.mouseVerticalOffset + ", mouseContentHorizontalOffset: " + this.mouseContentHorizontalOffset + "\n\ttarget: " + (this.target ? this.target.outerHTML : null); }; HitTestRequest.prototype.fulfill = function (type, position, range, detail) { if (position === void 0) { position = null; } if (range === void 0) { range = null; } if (detail === void 0) { detail = null; } var mouseColumn = this.mouseColumn; if (position && position.column < this._ctx.model.getLineMaxColumn(position.lineNumber)) { // Most likely, the line contains foreign decorations... mouseColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(this._ctx.model.getLineContent(position.lineNumber), position.column, this._ctx.model.getOptions().tabSize) + 1; } return new MouseTarget(this.target, type, mouseColumn, position, range, detail); }; HitTestRequest.prototype.withTarget = function (target) { return new HitTestRequest(this._ctx, this.editorPos, this.pos, target); }; return HitTestRequest; }(BareHitTestRequest)); var EMPTY_CONTENT_AFTER_LINES = { isAfterLines: true }; function createEmptyContentDataInLines(horizontalDistanceToText) { return { isAfterLines: false, horizontalDistanceToText: horizontalDistanceToText }; } var MouseTargetFactory = /** @class */ (function () { function MouseTargetFactory(context, viewHelper) { this._context = context; this._viewHelper = viewHelper; } MouseTargetFactory.prototype.mouseTargetIsWidget = function (e) { var t = e.target; var 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; }; MouseTargetFactory.prototype.createMouseTarget = function (lastRenderData, editorPos, pos, target) { var ctx = new HitTestContext(this._context, this._viewHelper, lastRenderData); var request = new HitTestRequest(ctx, editorPos, pos, target); try { var r = MouseTargetFactory._createMouseTarget(ctx, request, false); // console.log(r.toString()); return r; } catch (err) { // console.log(err); return request.fulfill(0 /* UNKNOWN */); } }; MouseTargetFactory._createMouseTarget = function (ctx, request, domHitTestExecuted) { // console.log(`${domHitTestExecuted ? '=>' : ''}CAME IN REQUEST: ${request}`); // First ensure the request has a target if (request.target === null) { if (domHitTestExecuted) { // Still no target... and we have already executed hit test... return request.fulfill(0 /* UNKNOWN */); } var hitTestResult = MouseTargetFactory._doHitTest(ctx, request); if (hitTestResult.position) { return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request, hitTestResult.position.lineNumber, hitTestResult.position.column); } return this._createMouseTarget(ctx, request.withTarget(hitTestResult.hitTarget), true); } // we know for a fact that request.target is not null var resolvedRequest = request; var result = null; result = result || MouseTargetFactory._hitTestContentWidget(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestOverlayWidget(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestMinimap(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestScrollbarSlider(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestViewZone(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestMargin(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestViewCursor(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestTextArea(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestViewLines(ctx, resolvedRequest, domHitTestExecuted); result = result || MouseTargetFactory._hitTestScrollbar(ctx, resolvedRequest); return (result || request.fulfill(0 /* UNKNOWN */)); }; MouseTargetFactory._hitTestContentWidget = function (ctx, request) { // Is it a content widget? if (ElementPath.isChildOfContentWidgets(request.targetPath) || ElementPath.isChildOfOverflowingContentWidgets(request.targetPath)) { var widgetId = ctx.findAttribute(request.target, 'widgetId'); if (widgetId) { return request.fulfill(9 /* CONTENT_WIDGET */, null, null, widgetId); } else { return request.fulfill(0 /* UNKNOWN */); } } return null; }; MouseTargetFactory._hitTestOverlayWidget = function (ctx, request) { // Is it an overlay widget? if (ElementPath.isChildOfOverlayWidgets(request.targetPath)) { var widgetId = ctx.findAttribute(request.target, 'widgetId'); if (widgetId) { return request.fulfill(12 /* OVERLAY_WIDGET */, null, null, widgetId); } else { return request.fulfill(0 /* UNKNOWN */); } } return null; }; MouseTargetFactory._hitTestViewCursor = function (ctx, request) { if (request.target) { // Check if we've hit a painted cursor var lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData; for (var _i = 0, lastViewCursorsRenderData_1 = lastViewCursorsRenderData; _i < lastViewCursorsRenderData_1.length; _i++) { var d = lastViewCursorsRenderData_1[_i]; if (request.target === d.domNode) { return request.fulfill(6 /* CONTENT_TEXT */, d.position); } } } 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 var lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData; var mouseContentHorizontalOffset = request.mouseContentHorizontalOffset; var mouseVerticalOffset = request.mouseVerticalOffset; for (var _a = 0, lastViewCursorsRenderData_2 = lastViewCursorsRenderData; _a < lastViewCursorsRenderData_2.length; _a++) { var d = lastViewCursorsRenderData_2[_a]; 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; } var cursorVerticalOffset = ctx.getVerticalOffsetForLineNumber(d.position.lineNumber); if (cursorVerticalOffset <= mouseVerticalOffset && mouseVerticalOffset <= cursorVerticalOffset + d.height) { return request.fulfill(6 /* CONTENT_TEXT */, d.position); } } } return null; }; MouseTargetFactory._hitTestViewZone = function (ctx, request) { var viewZoneData = ctx.getZoneAtCoord(request.mouseVerticalOffset); if (viewZoneData) { var mouseTargetType = (request.isInContentArea ? 8 /* CONTENT_VIEW_ZONE */ : 5 /* GUTTER_VIEW_ZONE */); return request.fulfill(mouseTargetType, viewZoneData.position, null, viewZoneData); } return null; }; MouseTargetFactory._hitTestTextArea = function (ctx, request) { // Is it the textarea? if (ElementPath.isTextArea(request.targetPath)) { if (ctx.lastRenderData.lastTextareaPosition) { return request.fulfill(6 /* CONTENT_TEXT */, ctx.lastRenderData.lastTextareaPosition); } return request.fulfill(1 /* TEXTAREA */, ctx.lastRenderData.lastTextareaPosition); } return null; }; MouseTargetFactory._hitTestMargin = function (ctx, request) { if (request.isInMarginArea) { var res = ctx.getFullLineRangeAtCoord(request.mouseVerticalOffset); var pos = res.range.getStartPosition(); var offset = Math.abs(request.pos.x - request.editorPos.x); var detail = { isAfterLines: res.isAfterLines, glyphMarginLeft: ctx.layoutInfo.glyphMarginLeft, glyphMarginWidth: ctx.layoutInfo.glyphMarginWidth, lineNumbersWidth: ctx.layoutInfo.lineNumbersWidth, offsetX: offset }; offset -= ctx.layoutInfo.glyphMarginLeft; if (offset <= ctx.layoutInfo.glyphMarginWidth) { // On the glyph margin return request.fulfill(2 /* GUTTER_GLYPH_MARGIN */, pos, res.range, detail); } offset -= ctx.layoutInfo.glyphMarginWidth; if (offset <= ctx.layoutInfo.lineNumbersWidth) { // On the line numbers return request.fulfill(3 /* GUTTER_LINE_NUMBERS */, pos, res.range, detail); } offset -= ctx.layoutInfo.lineNumbersWidth; // On the line decorations return request.fulfill(4 /* GUTTER_LINE_DECORATIONS */, pos, res.range, detail); } return null; }; MouseTargetFactory._hitTestViewLines = function (ctx, request, domHitTestExecuted) { if (!ElementPath.isChildOfViewLines(request.targetPath)) { return null; } // Check if it is below any lines and any view zones if (ctx.isAfterLines(request.mouseVerticalOffset)) { // This most likely indicates it happened after the last view-line var lineCount = ctx.model.getLineCount(); var maxLineColumn = ctx.model.getLineMaxColumn(lineCount); return request.fulfill(7 /* CONTENT_EMPTY */, new position_1.Position(lineCount, maxLineColumn), undefined, 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)) { var lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); if (ctx.model.getLineLength(lineNumber) === 0) { var lineWidth_1 = ctx.getLineWidth(lineNumber); var detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth_1); return request.fulfill(7 /* CONTENT_EMPTY */, new position_1.Position(lineNumber, 1), undefined, detail); } var lineWidth = ctx.getLineWidth(lineNumber); if (request.mouseContentHorizontalOffset >= lineWidth) { var detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth); var pos = new position_1.Position(lineNumber, ctx.model.getLineMaxColumn(lineNumber)); return request.fulfill(7 /* CONTENT_EMPTY */, pos, undefined, detail); } } // We have already executed hit test... return request.fulfill(0 /* UNKNOWN */); } var hitTestResult = MouseTargetFactory._doHitTest(ctx, request); if (hitTestResult.position) { return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request, hitTestResult.position.lineNumber, hitTestResult.position.column); } return this._createMouseTarget(ctx, request.withTarget(hitTestResult.hitTarget), true); }; MouseTargetFactory._hitTestMinimap = function (ctx, request) { if (ElementPath.isChildOfMinimap(request.targetPath)) { var possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); var maxColumn = ctx.model.getLineMaxColumn(possibleLineNumber); return request.fulfill(11 /* SCROLLBAR */, new position_1.Position(possibleLineNumber, maxColumn)); } return null; }; MouseTargetFactory._hitTestScrollbarSlider = function (ctx, request) { if (ElementPath.isChildOfScrollableElement(request.targetPath)) { if (request.target && request.target.nodeType === 1) { var className = request.target.className; if (className && /\b(slider|scrollbar)\b/.test(className)) { var possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); var maxColumn = ctx.model.getLineMaxColumn(possibleLineNumber); return request.fulfill(11 /* SCROLLBAR */, new position_1.Position(possibleLineNumber, maxColumn)); } } } return null; }; MouseTargetFactory._hitTestScrollbar = function (ctx, request) { // Is it the overview ruler? // Is it a child of the scrollable element? if (ElementPath.isChildOfScrollableElement(request.targetPath)) { var possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); var maxColumn = ctx.model.getLineMaxColumn(possibleLineNumber); return request.fulfill(11 /* SCROLLBAR */, new position_1.Position(possibleLineNumber, maxColumn)); } return null; }; MouseTargetFactory.prototype.getMouseColumn = function (editorPos, pos) { var options = this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); var mouseContentHorizontalOffset = this._context.viewLayout.getCurrentScrollLeft() + pos.x - editorPos.x - layoutInfo.contentLeft; return MouseTargetFactory._getMouseColumn(mouseContentHorizontalOffset, options.get(34 /* fontInfo */).typicalHalfwidthCharacterWidth); }; MouseTargetFactory._getMouseColumn = function (mouseContentHorizontalOffset, typicalHalfwidthCharacterWidth) { if (mouseContentHorizontalOffset < 0) { return 1; } var chars = Math.round(mouseContentHorizontalOffset / typicalHalfwidthCharacterWidth); return (chars + 1); }; MouseTargetFactory.createMouseTargetFromHitTestPosition = function (ctx, request, lineNumber, column) { var pos = new position_1.Position(lineNumber, column); var lineWidth = ctx.getLineWidth(lineNumber); if (request.mouseContentHorizontalOffset > lineWidth) { if (browser.isEdge && pos.column === 1) { // See https://github.com/Microsoft/vscode/issues/10875 var detail_1 = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth); return request.fulfill(7 /* CONTENT_EMPTY */, new position_1.Position(lineNumber, ctx.model.getLineMaxColumn(lineNumber)), undefined, detail_1); } var detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth); return request.fulfill(7 /* CONTENT_EMPTY */, pos, undefined, detail); } var visibleRange = ctx.visibleRangeForPosition(lineNumber, column); if (!visibleRange) { return request.fulfill(0 /* UNKNOWN */, pos); } var columnHorizontalOffset = visibleRange.left; if (request.mouseContentHorizontalOffset === columnHorizontalOffset) { return request.fulfill(6 /* CONTENT_TEXT */, pos); } var points = []; points.push({ offset: visibleRange.left, column: column }); if (column > 1) { var visibleRange_1 = ctx.visibleRangeForPosition(lineNumber, column - 1); if (visibleRange_1) { points.push({ offset: visibleRange_1.left, column: column - 1 }); } } var lineMaxColumn = ctx.model.getLineMaxColumn(lineNumber); if (column < lineMaxColumn) { var visibleRange_2 = ctx.visibleRangeForPosition(lineNumber, column + 1); if (visibleRange_2) { points.push({ offset: visibleRange_2.left, column: column + 1 }); } } points.sort(function (a, b) { return a.offset - b.offset; }); for (var i = 1; i < points.length; i++) { var prev = points[i - 1]; var curr = points[i]; if (prev.offset <= request.mouseContentHorizontalOffset && request.mouseContentHorizontalOffset <= curr.offset) { var rng = new range_1.Range(lineNumber, prev.column, lineNumber, curr.column); return request.fulfill(6 /* CONTENT_TEXT */, pos, rng); } } return request.fulfill(6 /* CONTENT_TEXT */, pos); }; /** * Most probably WebKit browsers and Edge */ MouseTargetFactory._doHitTestWithCaretRangeFromPoint = function (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 var lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); var lineVerticalOffset = ctx.getVerticalOffsetForLineNumber(lineNumber); var lineCenteredVerticalOffset = lineVerticalOffset + Math.floor(ctx.lineHeight / 2); var adjustedPageY = request.pos.y + (lineCenteredVerticalOffset - request.mouseVerticalOffset); if (adjustedPageY <= request.editorPos.y) { adjustedPageY = request.editorPos.y + 1; } if (adjustedPageY >= request.editorPos.y + ctx.layoutInfo.height) { adjustedPageY = request.editorPos.y + ctx.layoutInfo.height - 1; } var adjustedPage = new editorDom_1.PageCoordinates(request.pos.x, adjustedPageY); var r = this._actualDoHitTestWithCaretRangeFromPoint(ctx, adjustedPage.toClientCoordinates()); if (r.position) { 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()); }; MouseTargetFactory._actualDoHitTestWithCaretRangeFromPoint = function (ctx, coords) { var shadowRoot = dom.getShadowRoot(ctx.viewDomNode); var 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 { position: null, hitTarget: null }; } // Chrome always hits a TEXT_NODE, while Edge sometimes hits a token span var startContainer = range.startContainer; var hitTarget = null; if (startContainer.nodeType === startContainer.TEXT_NODE) { // startContainer is expected to be the token text var parent1 = startContainer.parentNode; // expected to be the token span var parent2 = parent1 ? parent1.parentNode : null; // expected to be the view line container span var parent3 = parent2 ? parent2.parentNode : null; // expected to be the view line div var parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null; if (parent3ClassName === viewLine_1.ViewLine.CLASS_NAME) { var p = ctx.getPositionFromDOMInfo(parent1, range.startOffset); return { position: p, hitTarget: null }; } else { hitTarget = startContainer.parentNode; } } else if (startContainer.nodeType === startContainer.ELEMENT_NODE) { // startContainer is expected to be the token span var parent1 = startContainer.parentNode; // expected to be the view line container span var parent2 = parent1 ? parent1.parentNode : null; // expected to be the view line div var parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? parent2.className : null; if (parent2ClassName === viewLine_1.ViewLine.CLASS_NAME) { var p = ctx.getPositionFromDOMInfo(startContainer, startContainer.textContent.length); return { position: p, hitTarget: null }; } else { hitTarget = startContainer; } } return { position: null, hitTarget: hitTarget }; }; /** * Most probably Gecko */ MouseTargetFactory._doHitTestWithCaretPositionFromPoint = function (ctx, coords) { var hitResult = document.caretPositionFromPoint(coords.clientX, coords.clientY); if (hitResult.offsetNode.nodeType === hitResult.offsetNode.TEXT_NODE) { // offsetNode is expected to be the token text var parent1 = hitResult.offsetNode.parentNode; // expected to be the token span var parent2 = parent1 ? parent1.parentNode : null; // expected to be the view line container span var parent3 = parent2 ? parent2.parentNode : null; // expected to be the view line div var parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null; if (parent3ClassName === viewLine_1.ViewLine.CLASS_NAME) { var p = ctx.getPositionFromDOMInfo(hitResult.offsetNode.parentNode, hitResult.offset); return { position: p, hitTarget: null }; } else { return { position: null, hitTarget: hitResult.offsetNode.parentNode }; } } return { position: null, hitTarget: hitResult.offsetNode }; }; /** * Most probably IE */ MouseTargetFactory._doHitTestWithMoveToPoint = function (ctx, coords) { var resultPosition = null; var resultHitTarget = null; var textRange = document.body.createTextRange(); try { textRange.moveToPoint(coords.clientX, coords.clientY); } catch (err) { return { position: null, hitTarget: null }; } textRange.collapse(true); // Now, let's do our best to figure out what we hit :) var parentElement = textRange ? textRange.parentElement() : null; var parent1 = parentElement ? parentElement.parentNode : null; var parent2 = parent1 ? parent1.parentNode : null; var parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? parent2.className : ''; if (parent2ClassName === viewLine_1.ViewLine.CLASS_NAME) { var rangeToContainEntireSpan = textRange.duplicate(); rangeToContainEntireSpan.moveToElementText(parentElement); rangeToContainEntireSpan.setEndPoint('EndToStart', textRange); resultPosition = ctx.getPositionFromDOMInfo(parentElement, rangeToContainEntireSpan.text.length); // 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 ('-') rangeToContainEntireSpan.moveToElementText(ctx.viewDomNode); } else { // Looks like we've hit the hover or something foreign resultHitTarget = parentElement; } // 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 ('-') textRange.moveToElementText(ctx.viewDomNode); return { position: resultPosition, hitTarget: resultHitTarget }; }; MouseTargetFactory._doHitTest = function (ctx, request) { // State of the art (18.10.2012): // The spec says browsers should support document.caretPositionFromPoint, but nobody implemented it (http://dev.w3.org/csswg/cssom-view/) // Gecko: // - they tried to implement it once, but failed: https://bugzilla.mozilla.org/show_bug.cgi?id=654352 // - however, they do give out rangeParent/rangeOffset properties on mouse events // Webkit: // - they have implemented a previous version of the spec which was using document.caretRangeFromPoint // IE: // - they have a proprietary method on ranges, moveToPoint: https://msdn.microsoft.com/en-us/library/ie/ms536632(v=vs.85).aspx // 24.08.2016: Edge has added WebKit's document.caretRangeFromPoint, but it is quite buggy // - when hit testing the cursor it returns the first or the last line in the viewport // - it inconsistently hits text nodes or span nodes, while WebKit only hits text nodes // - when toggling render whitespace on, and hit testing in the empty content after a line, it always hits offset 0 of the first span of the line // Thank you browsers for making this so 'easy' :) if (typeof document.caretRangeFromPoint === 'function') { return this._doHitTestWithCaretRangeFromPoint(ctx, request); } else if (document.caretPositionFromPoint) { return this._doHitTestWithCaretPositionFromPoint(ctx, request.pos.toClientCoordinates()); } else if (document.body.createTextRange) { return this._doHitTestWithMoveToPoint(ctx, request.pos.toClientCoordinates()); } return { position: null, hitTarget: null }; }; return MouseTargetFactory; }()); exports.MouseTargetFactory = MouseTargetFactory; function shadowCaretRangeFromPoint(shadowRoot, x, y) { var range = document.createRange(); // Get the element under the point var 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 = el.lastChild; } // Grab its rect var rect = el.getBoundingClientRect(); // And its font var font = window.getComputedStyle(el, null).getPropertyValue('font'); // And also its txt content var text = el.innerText; // Position the pixel cursor at the left of the element var pixelCursor = rect.left; var offset = 0; var step = void 0; // 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 { var charWidthReader = CharWidthReader.getInstance(); // Goes through all the characters of the innerText, and checks if the x of the point // belongs to the character. for (var 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; var CharWidthReader = /** @class */ (function () { function CharWidthReader() { this._cache = {}; this._canvas = document.createElement('canvas'); } CharWidthReader.getInstance = function () { if (!CharWidthReader._INSTANCE) { CharWidthReader._INSTANCE = new CharWidthReader(); } return CharWidthReader._INSTANCE; }; CharWidthReader.prototype.getCharWidth = function (char, font) { var cacheKey = char + font; if (this._cache[cacheKey]) { return this._cache[cacheKey]; } var context = this._canvas.getContext('2d'); context.font = font; var metrics = context.measureText(char); var width = metrics.width; this._cache[cacheKey] = width; return width; }; CharWidthReader._INSTANCE = null; return CharWidthReader; }()); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[550/*vs/editor/browser/controller/mouseHandler*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,6/*vs/base/browser/dom*/,45/*vs/base/browser/mouseEvent*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,166/*vs/editor/browser/controller/mouseTarget*/,141/*vs/editor/browser/editorDom*/,105/*vs/editor/common/config/editorZoom*/,13/*vs/editor/common/core/position*/,22/*vs/editor/common/core/selection*/,92/*vs/editor/common/viewModel/viewEventHandler*/]), function (require, exports, browser, 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 }); /** * Merges mouse events when mouse move events are throttled */ function createMouseMoveEventMerger(mouseTargetFactory) { return function (lastEvent, currentEvent) { var targetIsWidget = false; if (mouseTargetFactory) { targetIsWidget = mouseTargetFactory.mouseTargetIsWidget(currentEvent); } if (!targetIsWidget) { currentEvent.preventDefault(); } return currentEvent; }; } exports.createMouseMoveEventMerger = createMouseMoveEventMerger; var MouseHandler = /** @class */ (function (_super) { __extends(MouseHandler, _super); function MouseHandler(context, viewController, viewHelper) { var _this = _super.call(this) || this; _this._isFocused = false; _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, function (e, testEventTarget) { return _this._createMouseTarget(e, testEventTarget); }, function (e) { return _this._getMouseColumn(e); })); _this._asyncFocus = _this._register(new async_1.RunOnceScheduler(function () { return _this.viewHelper.focusTextArea(); }, 0)); _this.lastMouseLeaveTime = -1; var mouseEvents = new editorDom_1.EditorMouseEventFactory(_this.viewHelper.viewDomNode); _this._register(mouseEvents.onContextMenu(_this.viewHelper.viewDomNode, function (e) { return _this._onContextMenu(e, true); })); _this._register(mouseEvents.onMouseMoveThrottled(_this.viewHelper.viewDomNode, function (e) { return _this._onMouseMove(e); }, createMouseMoveEventMerger(_this.mouseTargetFactory), MouseHandler.MOUSE_MOVE_MINIMUM_TIME)); _this._register(mouseEvents.onMouseUp(_this.viewHelper.viewDomNode, function (e) { return _this._onMouseUp(e); })); _this._register(mouseEvents.onMouseLeave(_this.viewHelper.viewDomNode, function (e) { return _this._onMouseLeave(e); })); _this._register(mouseEvents.onMouseDown(_this.viewHelper.viewDomNode, function (e) { return _this._onMouseDown(e); })); var onMouseWheel = function (browserEvent) { _this.viewController.emitMouseWheel(browserEvent); if (!_this._context.configuration.options.get(57 /* mouseWheelZoom */)) { return; } var e = new mouseEvent_1.StandardWheelEvent(browserEvent); if (e.browserEvent.ctrlKey || e.browserEvent.metaKey) { var zoomLevel = editorZoom_1.EditorZoom.getZoomLevel(); var delta = e.deltaY > 0 ? 1 : -1; editorZoom_1.EditorZoom.setZoomLevel(zoomLevel + delta); e.preventDefault(); e.stopPropagation(); } }; _this._register(dom.addDisposableListener(_this.viewHelper.viewDomNode, browser.isEdgeOrIE ? 'mousewheel' : 'wheel', onMouseWheel, { capture: true, passive: false })); _this._context.addEventHandler(_this); return _this; } MouseHandler.prototype.dispose = function () { this._context.removeEventHandler(this); _super.prototype.dispose.call(this); }; // --- begin event handlers MouseHandler.prototype.onCursorStateChanged = function (e) { this._mouseDownOperation.onCursorStateChanged(e); return false; }; MouseHandler.prototype.onFocusChanged = function (e) { this._isFocused = e.isFocused; return false; }; MouseHandler.prototype.onScrollChanged = function (e) { this._mouseDownOperation.onScrollChanged(); return false; }; // --- end event handlers MouseHandler.prototype.getTargetAtClientPoint = function (clientX, clientY) { var clientPos = new editorDom_1.ClientCoordinates(clientX, clientY); var pos = clientPos.toPageCoordinates(); var editorPos = editorDom_1.createEditorPagePosition(this.viewHelper.viewDomNode); if (pos.y < editorPos.y || pos.y > editorPos.y + editorPos.height || pos.x < editorPos.x || pos.x > editorPos.x + editorPos.width) { return null; } return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), editorPos, pos, null); }; MouseHandler.prototype._createMouseTarget = function (e, testEventTarget) { return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), e.editorPos, e.pos, testEventTarget ? e.target : null); }; MouseHandler.prototype._getMouseColumn = function (e) { return this.mouseTargetFactory.getMouseColumn(e.editorPos, e.pos); }; MouseHandler.prototype._onContextMenu = function (e, testEventTarget) { this.viewController.emitContextMenu({ event: e, target: this._createMouseTarget(e, testEventTarget) }); }; MouseHandler.prototype._onMouseMove = function (e) { if (this._mouseDownOperation.isActive()) { // In selection/drag operation return; } var 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) }); }; MouseHandler.prototype._onMouseLeave = function (e) { this.lastMouseLeaveTime = (new Date()).getTime(); this.viewController.emitMouseLeave({ event: e, target: null }); }; MouseHandler.prototype._onMouseUp = function (e) { this.viewController.emitMouseUp({ event: e, target: this._createMouseTarget(e, true) }); }; MouseHandler.prototype._onMouseDown = function (e) { var _this = this; var t = this._createMouseTarget(e, true); var targetIsContent = (t.type === 6 /* CONTENT_TEXT */ || t.type === 7 /* CONTENT_EMPTY */); var targetIsGutter = (t.type === 2 /* GUTTER_GLYPH_MARGIN */ || t.type === 3 /* GUTTER_LINE_NUMBERS */ || t.type === 4 /* GUTTER_LINE_DECORATIONS */); var targetIsLineNumbers = (t.type === 3 /* GUTTER_LINE_NUMBERS */); var selectOnLineNumbers = this._context.configuration.options.get(83 /* selectOnLineNumbers */); var targetIsViewZone = (t.type === 8 /* CONTENT_VIEW_ZONE */ || t.type === 5 /* GUTTER_VIEW_ZONE */); var targetIsWidget = (t.type === 9 /* CONTENT_WIDGET */); var shouldHandle = e.leftButton || e.middleButton; if (platform.isMacintosh && e.leftButton && e.ctrlKey) { shouldHandle = false; } var focus = function () { // In IE11, if the focus is in the browser's address bar and // then you click in the editor, calling preventDefault() // will not move focus properly (focus remains the address bar) if (browser.isIE && !_this._isFocused) { _this._asyncFocus.schedule(); } else { 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) { var 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 }); }; MouseHandler.MOUSE_MOVE_MINIMUM_TIME = 100; // ms return MouseHandler; }(viewEventHandler_1.ViewEventHandler)); exports.MouseHandler = MouseHandler; var MouseDownOperation = /** @class */ (function (_super) { __extends(MouseDownOperation, _super); function MouseDownOperation(context, viewController, viewHelper, createMouseTarget, getMouseColumn) { var _this = _super.call(this) || this; _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; return _this; } MouseDownOperation.prototype.dispose = function () { _super.prototype.dispose.call(this); }; MouseDownOperation.prototype.isActive = function () { return this._isActive; }; MouseDownOperation.prototype._onMouseDownThenMove = function (e) { this._lastMouseEvent = e; this._mouseState.setModifiers(e); var 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); } }; MouseDownOperation.prototype.start = function (targetType, e) { var _this = this; this._lastMouseEvent = e; this._mouseState.setStartedOnLineNumbers(targetType === 3 /* GUTTER_LINE_NUMBERS */); this._mouseState.setStartButtons(e); this._mouseState.setModifiers(e); var 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; var options = this._context.configuration.options; if (!options.get(68 /* readOnly */) && options.get(24 /* dragAndDrop */) && !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), function (e) { return _this._onMouseDownThenMove(e); }, function () { var position = _this._findMousePosition(_this._lastMouseEvent, true); _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), function (e) { return _this._onMouseDownThenMove(e); }, function () { return _this._stop(); }); } }; MouseDownOperation.prototype._stop = function () { this._isActive = false; this._onScrollTimeout.cancel(); }; MouseDownOperation.prototype.onScrollChanged = function () { var _this = this; if (!this._isActive) { return; } this._onScrollTimeout.setIfNotSet(function () { if (!_this._lastMouseEvent) { return; } var 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); }; MouseDownOperation.prototype.onCursorStateChanged = function (e) { this._currentSelection = e.selections[0]; }; MouseDownOperation.prototype._getPositionOutsideEditor = function (e) { var editorContent = e.editorPos; var model = this._context.model; var viewLayout = this._context.viewLayout; var mouseColumn = this._getMouseColumn(e); if (e.posy < editorContent.y) { var verticalOffset = Math.max(viewLayout.getCurrentScrollTop() - (editorContent.y - e.posy), 0); var viewZoneData = mouseTarget_1.HitTestContext.getZoneAtCoord(this._context, verticalOffset); if (viewZoneData) { var newPosition = this._helpPositionJumpOverViewZone(viewZoneData); if (newPosition) { return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, newPosition); } } var aboveLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset); return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, new position_1.Position(aboveLineNumber, 1)); } if (e.posy > editorContent.y + editorContent.height) { var verticalOffset = viewLayout.getCurrentScrollTop() + (e.posy - editorContent.y); var viewZoneData = mouseTarget_1.HitTestContext.getZoneAtCoord(this._context, verticalOffset); if (viewZoneData) { var newPosition = this._helpPositionJumpOverViewZone(viewZoneData); if (newPosition) { return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, newPosition); } } var belowLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset); return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, new position_1.Position(belowLineNumber, model.getLineMaxColumn(belowLineNumber))); } var possibleLineNumber = viewLayout.getLineNumberAtVerticalOffset(viewLayout.getCurrentScrollTop() + (e.posy - editorContent.y)); if (e.posx < editorContent.x) { return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, new position_1.Position(possibleLineNumber, 1)); } if (e.posx > editorContent.x + editorContent.width) { return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, new position_1.Position(possibleLineNumber, model.getLineMaxColumn(possibleLineNumber))); } return null; }; MouseDownOperation.prototype._findMousePosition = function (e, testEventTarget) { var positionOutsideEditor = this._getPositionOutsideEditor(e); if (positionOutsideEditor) { return positionOutsideEditor; } var t = this._createMouseTarget(e, testEventTarget); var hintedPosition = t.position; if (!hintedPosition) { return null; } if (t.type === 8 /* CONTENT_VIEW_ZONE */ || t.type === 5 /* GUTTER_VIEW_ZONE */) { var newPosition = this._helpPositionJumpOverViewZone(t.detail); if (newPosition) { return new mouseTarget_1.MouseTarget(t.element, t.type, t.mouseColumn, newPosition, null, t.detail); } } return t; }; MouseDownOperation.prototype._helpPositionJumpOverViewZone = function (viewZoneData) { // Force position on view zones to go above or below depending on where selection started from var selectionStart = new position_1.Position(this._currentSelection.selectionStartLineNumber, this._currentSelection.selectionStartColumn); var positionBefore = viewZoneData.positionBefore; var positionAfter = viewZoneData.positionAfter; if (positionBefore && positionAfter) { if (positionBefore.isBefore(selectionStart)) { return positionBefore; } else { return positionAfter; } } return null; }; MouseDownOperation.prototype._dispatchMouse = function (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, }); }; return MouseDownOperation; }(lifecycle_1.Disposable)); var MouseDownState = /** @class */ (function () { function MouseDownState() { 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; } Object.defineProperty(MouseDownState.prototype, "altKey", { get: function () { return this._altKey; }, enumerable: true, configurable: true }); Object.defineProperty(MouseDownState.prototype, "ctrlKey", { get: function () { return this._ctrlKey; }, enumerable: true, configurable: true }); Object.defineProperty(MouseDownState.prototype, "metaKey", { get: function () { return this._metaKey; }, enumerable: true, configurable: true }); Object.defineProperty(MouseDownState.prototype, "shiftKey", { get: function () { return this._shiftKey; }, enumerable: true, configurable: true }); Object.defineProperty(MouseDownState.prototype, "leftButton", { get: function () { return this._leftButton; }, enumerable: true, configurable: true }); Object.defineProperty(MouseDownState.prototype, "middleButton", { get: function () { return this._middleButton; }, enumerable: true, configurable: true }); Object.defineProperty(MouseDownState.prototype, "startedOnLineNumbers", { get: function () { return this._startedOnLineNumbers; }, enumerable: true, configurable: true }); Object.defineProperty(MouseDownState.prototype, "count", { get: function () { return this._lastMouseDownCount; }, enumerable: true, configurable: true }); MouseDownState.prototype.setModifiers = function (source) { this._altKey = source.altKey; this._ctrlKey = source.ctrlKey; this._metaKey = source.metaKey; this._shiftKey = source.shiftKey; }; MouseDownState.prototype.setStartButtons = function (source) { this._leftButton = source.leftButton; this._middleButton = source.middleButton; }; MouseDownState.prototype.setStartedOnLineNumbers = function (startedOnLineNumbers) { this._startedOnLineNumbers = startedOnLineNumbers; }; MouseDownState.prototype.trySetCount = function (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) var 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 return MouseDownState; }()); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[551/*vs/editor/browser/controller/pointerHandler*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,16/*vs/base/common/platform*/,57/*vs/base/browser/touch*/,2/*vs/base/common/lifecycle*/,550/*vs/editor/browser/controller/mouseHandler*/,141/*vs/editor/browser/editorDom*/,88/*vs/base/browser/canIUse*/]), function (require, exports, dom, platform, touch_1, lifecycle_1, mouseHandler_1, editorDom_1, canIUse_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function gestureChangeEventMerger(lastEvent, currentEvent) { var r = { translationY: currentEvent.translationY, translationX: currentEvent.translationX }; if (lastEvent) { r.translationY += lastEvent.translationY; r.translationX += lastEvent.translationX; } return r; } /** * Basically IE10 and IE11 */ var MsPointerHandler = /** @class */ (function (_super) { __extends(MsPointerHandler, _super); function MsPointerHandler(context, viewController, viewHelper) { var _this = _super.call(this, context, viewController, viewHelper) || this; _this.viewHelper.linesContentDomNode.style.msTouchAction = 'none'; _this.viewHelper.linesContentDomNode.style.msContentZooming = 'none'; // TODO@Alex -> this expects that the view is added in 100 ms, might not be the case // This handler should be added when the dom node is in the dom tree _this._installGestureHandlerTimeout = window.setTimeout(function () { _this._installGestureHandlerTimeout = -1; if (window.MSGesture) { var touchGesture_1 = new MSGesture(); var penGesture_1 = new MSGesture(); touchGesture_1.target = _this.viewHelper.linesContentDomNode; penGesture_1.target = _this.viewHelper.linesContentDomNode; _this.viewHelper.linesContentDomNode.addEventListener('MSPointerDown', function (e) { // Circumvent IE11 breaking change in e.pointerType & TypeScript's stale definitions var pointerType = e.pointerType; if (pointerType === (e.MSPOINTER_TYPE_MOUSE || 'mouse')) { _this._lastPointerType = 'mouse'; return; } else if (pointerType === (e.MSPOINTER_TYPE_TOUCH || 'touch')) { _this._lastPointerType = 'touch'; touchGesture_1.addPointer(e.pointerId); } else { _this._lastPointerType = 'pen'; penGesture_1.addPointer(e.pointerId); } }); _this._register(dom.addDisposableThrottledListener(_this.viewHelper.linesContentDomNode, 'MSGestureChange', function (e) { return _this._onGestureChange(e); }, gestureChangeEventMerger)); _this._register(dom.addDisposableListener(_this.viewHelper.linesContentDomNode, 'MSGestureTap', function (e) { return _this._onCaptureGestureTap(e); }, true)); } }, 100); _this._lastPointerType = 'mouse'; return _this; } MsPointerHandler.prototype._onMouseDown = function (e) { if (this._lastPointerType === 'mouse') { _super.prototype._onMouseDown.call(this, e); } }; MsPointerHandler.prototype._onCaptureGestureTap = function (rawEvent) { var _this = this; var e = new editorDom_1.EditorMouseEvent(rawEvent, this.viewHelper.viewDomNode); var t = this._createMouseTarget(e, false); if (t.position) { this.viewController.moveTo(t.position); } // IE does not want to focus when coming in from the browser's address bar if (e.browserEvent.fromElement) { e.preventDefault(); this.viewHelper.focusTextArea(); } else { // TODO@Alex -> cancel this is focus is lost setTimeout(function () { _this.viewHelper.focusTextArea(); }); } }; MsPointerHandler.prototype._onGestureChange = function (e) { this._context.viewLayout.deltaScrollNow(-e.translationX, -e.translationY); }; MsPointerHandler.prototype.dispose = function () { window.clearTimeout(this._installGestureHandlerTimeout); _super.prototype.dispose.call(this); }; return MsPointerHandler; }(mouseHandler_1.MouseHandler)); /** * Basically Edge but should be modified to handle any pointerEnabled, even without support of MSGesture */ var StandardPointerHandler = /** @class */ (function (_super) { __extends(StandardPointerHandler, _super); function StandardPointerHandler(context, viewController, viewHelper) { var _this = _super.call(this, context, viewController, viewHelper) || this; _this.viewHelper.linesContentDomNode.style.touchAction = 'none'; // TODO@Alex -> this expects that the view is added in 100 ms, might not be the case // This handler should be added when the dom node is in the dom tree _this._installGestureHandlerTimeout = window.setTimeout(function () { _this._installGestureHandlerTimeout = -1; // TODO@Alex: replace the usage of MSGesture here with something that works across all browsers if (window.MSGesture) { var touchGesture_2 = new MSGesture(); var penGesture_2 = new MSGesture(); touchGesture_2.target = _this.viewHelper.linesContentDomNode; penGesture_2.target = _this.viewHelper.linesContentDomNode; _this.viewHelper.linesContentDomNode.addEventListener('pointerdown', function (e) { var pointerType = e.pointerType; if (pointerType === 'mouse') { _this._lastPointerType = 'mouse'; return; } else if (pointerType === 'touch') { _this._lastPointerType = 'touch'; touchGesture_2.addPointer(e.pointerId); } else { _this._lastPointerType = 'pen'; penGesture_2.addPointer(e.pointerId); } }); _this._register(dom.addDisposableThrottledListener(_this.viewHelper.linesContentDomNode, 'MSGestureChange', function (e) { return _this._onGestureChange(e); }, gestureChangeEventMerger)); _this._register(dom.addDisposableListener(_this.viewHelper.linesContentDomNode, 'MSGestureTap', function (e) { return _this._onCaptureGestureTap(e); }, true)); } }, 100); _this._lastPointerType = 'mouse'; return _this; } StandardPointerHandler.prototype._onMouseDown = function (e) { if (this._lastPointerType === 'mouse') { _super.prototype._onMouseDown.call(this, e); } }; StandardPointerHandler.prototype._onCaptureGestureTap = function (rawEvent) { var _this = this; var e = new editorDom_1.EditorMouseEvent(rawEvent, this.viewHelper.viewDomNode); var t = this._createMouseTarget(e, false); if (t.position) { this.viewController.moveTo(t.position); } // IE does not want to focus when coming in from the browser's address bar if (e.browserEvent.fromElement) { e.preventDefault(); this.viewHelper.focusTextArea(); } else { // TODO@Alex -> cancel this is focus is lost setTimeout(function () { _this.viewHelper.focusTextArea(); }); } }; StandardPointerHandler.prototype._onGestureChange = function (e) { this._context.viewLayout.deltaScrollNow(-e.translationX, -e.translationY); }; StandardPointerHandler.prototype.dispose = function () { window.clearTimeout(this._installGestureHandlerTimeout); _super.prototype.dispose.call(this); }; return StandardPointerHandler; }(mouseHandler_1.MouseHandler)); /** * Currently only tested on iOS 13/ iPadOS. */ var PointerEventHandler = /** @class */ (function (_super) { __extends(PointerEventHandler, _super); function PointerEventHandler(context, viewController, viewHelper) { var _this = _super.call(this, context, viewController, viewHelper) || this; _this._register(touch_1.Gesture.addTarget(_this.viewHelper.linesContentDomNode)); _this._register(dom.addDisposableListener(_this.viewHelper.linesContentDomNode, touch_1.EventType.Tap, function (e) { return _this.onTap(e); })); _this._register(dom.addDisposableListener(_this.viewHelper.linesContentDomNode, touch_1.EventType.Change, function (e) { return _this.onChange(e); })); _this._register(dom.addDisposableListener(_this.viewHelper.linesContentDomNode, touch_1.EventType.Contextmenu, function (e) { return _this._onContextMenu(new editorDom_1.EditorMouseEvent(e, _this.viewHelper.viewDomNode), false); })); _this._lastPointerType = 'mouse'; _this._register(dom.addDisposableListener(_this.viewHelper.linesContentDomNode, 'pointerdown', function (e) { var pointerType = e.pointerType; if (pointerType === 'mouse') { _this._lastPointerType = 'mouse'; return; } else if (pointerType === 'touch') { _this._lastPointerType = 'touch'; } else { _this._lastPointerType = 'pen'; } })); // PonterEvents var pointerEvents = new editorDom_1.EditorPointerEventFactory(_this.viewHelper.viewDomNode); _this._register(pointerEvents.onPointerMoveThrottled(_this.viewHelper.viewDomNode, function (e) { return _this._onMouseMove(e); }, mouseHandler_1.createMouseMoveEventMerger(_this.mouseTargetFactory), mouseHandler_1.MouseHandler.MOUSE_MOVE_MINIMUM_TIME)); _this._register(pointerEvents.onPointerUp(_this.viewHelper.viewDomNode, function (e) { return _this._onMouseUp(e); })); _this._register(pointerEvents.onPointerLeave(_this.viewHelper.viewDomNode, function (e) { return _this._onMouseLeave(e); })); _this._register(pointerEvents.onPointerDown(_this.viewHelper.viewDomNode, function (e) { return _this._onMouseDown(e); })); return _this; } PointerEventHandler.prototype.onTap = function (event) { if (!event.initialTarget || !this.viewHelper.linesContentDomNode.contains(event.initialTarget)) { return; } event.preventDefault(); this.viewHelper.focusTextArea(); var 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, }); } }; PointerEventHandler.prototype.onChange = function (e) { if (this._lastPointerType === 'touch') { this._context.viewLayout.deltaScrollNow(-e.translationX, -e.translationY); } }; PointerEventHandler.prototype._onMouseDown = function (e) { if (e.target && this.viewHelper.linesContentDomNode.contains(e.target) && this._lastPointerType === 'touch') { return; } _super.prototype._onMouseDown.call(this, e); }; return PointerEventHandler; }(mouseHandler_1.MouseHandler)); exports.PointerEventHandler = PointerEventHandler; var TouchHandler = /** @class */ (function (_super) { __extends(TouchHandler, _super); function TouchHandler(context, viewController, viewHelper) { var _this = _super.call(this, context, viewController, viewHelper) || this; _this._register(touch_1.Gesture.addTarget(_this.viewHelper.linesContentDomNode)); _this._register(dom.addDisposableListener(_this.viewHelper.linesContentDomNode, touch_1.EventType.Tap, function (e) { return _this.onTap(e); })); _this._register(dom.addDisposableListener(_this.viewHelper.linesContentDomNode, touch_1.EventType.Change, function (e) { return _this.onChange(e); })); _this._register(dom.addDisposableListener(_this.viewHelper.linesContentDomNode, touch_1.EventType.Contextmenu, function (e) { return _this._onContextMenu(new editorDom_1.EditorMouseEvent(e, _this.viewHelper.viewDomNode), false); })); return _this; } TouchHandler.prototype.onTap = function (event) { event.preventDefault(); this.viewHelper.focusTextArea(); var target = this._createMouseTarget(new editorDom_1.EditorMouseEvent(event, this.viewHelper.viewDomNode), false); if (target.position) { this.viewController.moveTo(target.position); } }; TouchHandler.prototype.onChange = function (e) { this._context.viewLayout.deltaScrollNow(-e.translationX, -e.translationY); }; return TouchHandler; }(mouseHandler_1.MouseHandler)); var PointerHandler = /** @class */ (function (_super) { __extends(PointerHandler, _super); function PointerHandler(context, viewController, viewHelper) { var _this = _super.call(this) || this; if (window.navigator.msPointerEnabled) { _this.handler = _this._register(new MsPointerHandler(context, viewController, viewHelper)); } else if ((platform.isIOS && canIUse_1.BrowserFeatures.pointerEvents)) { _this.handler = _this._register(new PointerEventHandler(context, viewController, viewHelper)); } else if (window.TouchEvent) { _this.handler = _this._register(new TouchHandler(context, viewController, viewHelper)); } else if (window.navigator.pointerEnabled || window.PointerEvent) { _this.handler = _this._register(new StandardPointerHandler(context, viewController, viewHelper)); } else { _this.handler = _this._register(new mouseHandler_1.MouseHandler(context, viewController, viewHelper)); } return _this; } PointerHandler.prototype.getTargetAtClientPoint = function (clientX, clientY) { return this.handler.getTargetAtClientPoint(clientX, clientY); }; return PointerHandler; }(lifecycle_1.Disposable)); exports.PointerHandler = PointerHandler; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[228/*vs/editor/browser/view/viewOutgoingEvents*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,166/*vs/editor/browser/controller/mouseTarget*/]), function (require, exports, lifecycle_1, mouseTarget_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ViewOutgoingEvents = /** @class */ (function (_super) { __extends(ViewOutgoingEvents, _super); function ViewOutgoingEvents(viewModel) { var _this = _super.call(this) || this; _this.onDidContentSizeChange = null; _this.onDidScroll = null; _this.onDidGainFocus = null; _this.onDidLoseFocus = null; _this.onKeyDown = null; _this.onKeyUp = null; _this.onContextMenu = null; _this.onMouseMove = null; _this.onMouseLeave = null; _this.onMouseUp = null; _this.onMouseDown = null; _this.onMouseDrag = null; _this.onMouseDrop = null; _this.onMouseWheel = null; _this._viewModel = viewModel; return _this; } ViewOutgoingEvents.prototype.emitContentSizeChange = function (e) { if (this.onDidContentSizeChange) { this.onDidContentSizeChange(e); } }; ViewOutgoingEvents.prototype.emitScrollChanged = function (e) { if (this.onDidScroll) { this.onDidScroll(e); } }; ViewOutgoingEvents.prototype.emitViewFocusGained = function () { if (this.onDidGainFocus) { this.onDidGainFocus(undefined); } }; ViewOutgoingEvents.prototype.emitViewFocusLost = function () { if (this.onDidLoseFocus) { this.onDidLoseFocus(undefined); } }; ViewOutgoingEvents.prototype.emitKeyDown = function (e) { if (this.onKeyDown) { this.onKeyDown(e); } }; ViewOutgoingEvents.prototype.emitKeyUp = function (e) { if (this.onKeyUp) { this.onKeyUp(e); } }; ViewOutgoingEvents.prototype.emitContextMenu = function (e) { if (this.onContextMenu) { this.onContextMenu(this._convertViewToModelMouseEvent(e)); } }; ViewOutgoingEvents.prototype.emitMouseMove = function (e) { if (this.onMouseMove) { this.onMouseMove(this._convertViewToModelMouseEvent(e)); } }; ViewOutgoingEvents.prototype.emitMouseLeave = function (e) { if (this.onMouseLeave) { this.onMouseLeave(this._convertViewToModelMouseEvent(e)); } }; ViewOutgoingEvents.prototype.emitMouseUp = function (e) { if (this.onMouseUp) { this.onMouseUp(this._convertViewToModelMouseEvent(e)); } }; ViewOutgoingEvents.prototype.emitMouseDown = function (e) { if (this.onMouseDown) { this.onMouseDown(this._convertViewToModelMouseEvent(e)); } }; ViewOutgoingEvents.prototype.emitMouseDrag = function (e) { if (this.onMouseDrag) { this.onMouseDrag(this._convertViewToModelMouseEvent(e)); } }; ViewOutgoingEvents.prototype.emitMouseDrop = function (e) { if (this.onMouseDrop) { this.onMouseDrop(this._convertViewToModelMouseEvent(e)); } }; ViewOutgoingEvents.prototype.emitMouseWheel = function (e) { if (this.onMouseWheel) { this.onMouseWheel(e); } }; ViewOutgoingEvents.prototype._convertViewToModelMouseEvent = function (e) { if (e.target) { return { event: e.event, target: this._convertViewToModelMouseTarget(e.target) }; } return e; }; ViewOutgoingEvents.prototype._convertViewToModelMouseTarget = function (target) { return ViewOutgoingEvents.convertViewToModelMouseTarget(target, this._viewModel.coordinatesConverter); }; ViewOutgoingEvents.convertViewToModelMouseTarget = function (target, coordinatesConverter) { return new ExternalMouseTarget(target.element, target.type, target.mouseColumn, target.position ? coordinatesConverter.convertViewPositionToModelPosition(target.position) : null, target.range ? coordinatesConverter.convertViewRangeToModelRange(target.range) : null, target.detail); }; return ViewOutgoingEvents; }(lifecycle_1.Disposable)); exports.ViewOutgoingEvents = ViewOutgoingEvents; var ExternalMouseTarget = /** @class */ (function () { function ExternalMouseTarget(element, type, mouseColumn, position, range, detail) { this.element = element; this.type = type; this.mouseColumn = mouseColumn; this.position = position; this.range = range; this.detail = detail; } ExternalMouseTarget.prototype.toString = function () { return mouseTarget_1.MouseTarget.toString(this); }; return ExternalMouseTarget; }()); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[552/*vs/editor/browser/viewParts/lines/viewLines*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,60/*vs/editor/browser/config/configuration*/,143/*vs/editor/browser/view/viewLayer*/,37/*vs/editor/browser/view/viewPart*/,227/*vs/editor/browser/viewParts/lines/viewLine*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,91/*vs/editor/common/view/renderingContext*/,290/*vs/css!vs/editor/browser/viewParts/lines/viewLines*/]), function (require, exports, async_1, configuration_1, viewLayer_1, viewPart_1, viewLine_1, position_1, range_1, renderingContext_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LastRenderedData = /** @class */ (function () { function LastRenderedData() { this._currentVisibleRange = new range_1.Range(1, 1, 1, 1); } LastRenderedData.prototype.getCurrentVisibleRange = function () { return this._currentVisibleRange; }; LastRenderedData.prototype.setCurrentVisibleRange = function (currentVisibleRange) { this._currentVisibleRange = currentVisibleRange; }; return LastRenderedData; }()); var HorizontalRevealRequest = /** @class */ (function () { function HorizontalRevealRequest(lineNumber, startColumn, endColumn, startScrollTop, stopScrollTop, scrollType) { this.lineNumber = lineNumber; this.startColumn = startColumn; this.endColumn = endColumn; this.startScrollTop = startScrollTop; this.stopScrollTop = stopScrollTop; this.scrollType = scrollType; } return HorizontalRevealRequest; }()); var ViewLines = /** @class */ (function (_super) { __extends(ViewLines, _super); function ViewLines(context, linesContent) { var _this = _super.call(this, context) || this; _this._linesContent = linesContent; _this._textRangeRestingSpot = document.createElement('div'); _this._visibleLines = new viewLayer_1.VisibleLinesCollection(_this); _this.domNode = _this._visibleLines.domNode; var conf = _this._context.configuration; var options = _this._context.configuration.options; var fontInfo = options.get(34 /* fontInfo */); var wrappingInfo = options.get(108 /* wrappingInfo */); _this._lineHeight = options.get(49 /* lineHeight */); _this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth; _this._isViewportWrapping = wrappingInfo.isViewportWrapping; _this._revealHorizontalRightPadding = options.get(75 /* revealHorizontalRightPadding */); _this._cursorSurroundingLines = options.get(19 /* cursorSurroundingLines */); _this._cursorSurroundingLinesStyle = options.get(20 /* cursorSurroundingLinesStyle */); _this._canUseLayerHinting = !options.get(22 /* disableLayerHinting */); _this._viewLineOptions = new viewLine_1.ViewLineOptions(conf, _this._context.theme.type); viewPart_1.PartFingerprints.write(_this.domNode, 7 /* ViewLines */); _this.domNode.setClassName('view-lines'); configuration_1.Configuration.applyFontInfo(_this.domNode, fontInfo); // --- width & height _this._maxLineWidth = 0; _this._asyncUpdateLineWidths = new async_1.RunOnceScheduler(function () { _this._updateLineWidthsSlow(); }, 200); _this._lastRenderedData = new LastRenderedData(); _this._horizontalRevealRequest = null; return _this; } ViewLines.prototype.dispose = function () { this._asyncUpdateLineWidths.dispose(); _super.prototype.dispose.call(this); }; ViewLines.prototype.getDomNode = function () { return this.domNode; }; // ---- begin IVisibleLinesHost ViewLines.prototype.createVisibleLine = function () { return new viewLine_1.ViewLine(this._viewLineOptions); }; // ---- end IVisibleLinesHost // ---- begin view event handlers ViewLines.prototype.onConfigurationChanged = function (e) { this._visibleLines.onConfigurationChanged(e); if (e.hasChanged(108 /* wrappingInfo */)) { this._maxLineWidth = 0; } var options = this._context.configuration.options; var fontInfo = options.get(34 /* fontInfo */); var wrappingInfo = options.get(108 /* wrappingInfo */); this._lineHeight = options.get(49 /* lineHeight */); this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth; this._isViewportWrapping = wrappingInfo.isViewportWrapping; this._revealHorizontalRightPadding = options.get(75 /* revealHorizontalRightPadding */); this._cursorSurroundingLines = options.get(19 /* cursorSurroundingLines */); this._cursorSurroundingLinesStyle = options.get(20 /* cursorSurroundingLinesStyle */); this._canUseLayerHinting = !options.get(22 /* disableLayerHinting */); configuration_1.Configuration.applyFontInfo(this.domNode, fontInfo); this._onOptionsMaybeChanged(); if (e.hasChanged(107 /* layoutInfo */)) { this._maxLineWidth = 0; } return true; }; ViewLines.prototype._onOptionsMaybeChanged = function () { var conf = this._context.configuration; var newViewLineOptions = new viewLine_1.ViewLineOptions(conf, this._context.theme.type); if (!this._viewLineOptions.equals(newViewLineOptions)) { this._viewLineOptions = newViewLineOptions; var startLineNumber = this._visibleLines.getStartLineNumber(); var endLineNumber = this._visibleLines.getEndLineNumber(); for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { var line = this._visibleLines.getVisibleLine(lineNumber); line.onOptionsChanged(this._viewLineOptions); } return true; } return false; }; ViewLines.prototype.onCursorStateChanged = function (e) { var rendStartLineNumber = this._visibleLines.getStartLineNumber(); var rendEndLineNumber = this._visibleLines.getEndLineNumber(); var r = false; for (var lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) { r = this._visibleLines.getVisibleLine(lineNumber).onSelectionChanged() || r; } return r; }; ViewLines.prototype.onDecorationsChanged = function (e) { if (true /*e.inlineDecorationsChanged*/) { var rendStartLineNumber = this._visibleLines.getStartLineNumber(); var rendEndLineNumber = this._visibleLines.getEndLineNumber(); for (var lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) { this._visibleLines.getVisibleLine(lineNumber).onDecorationsChanged(); } } return true; }; ViewLines.prototype.onFlushed = function (e) { var shouldRender = this._visibleLines.onFlushed(e); this._maxLineWidth = 0; return shouldRender; }; ViewLines.prototype.onLinesChanged = function (e) { return this._visibleLines.onLinesChanged(e); }; ViewLines.prototype.onLinesDeleted = function (e) { return this._visibleLines.onLinesDeleted(e); }; ViewLines.prototype.onLinesInserted = function (e) { return this._visibleLines.onLinesInserted(e); }; ViewLines.prototype.onRevealRangeRequest = function (e) { // Using the future viewport here in order to handle multiple // incoming reveal range requests that might all desire to be animated var desiredScrollTop = this._computeScrollTopToRevealRange(this._context.viewLayout.getFutureViewport(), e.source, e.range, e.verticalType); // validate the new desired scroll top var newScrollPosition = this._context.viewLayout.validateScrollPosition({ scrollTop: desiredScrollTop }); if (e.revealHorizontal) { if (e.range.startLineNumber !== e.range.endLineNumber) { // Two or more lines? => scroll to base (That's how you see most of the two lines) newScrollPosition = { scrollTop: newScrollPosition.scrollTop, scrollLeft: 0 }; } else { // We don't necessarily know the horizontal offset of this range since the line might not be in the view... this._horizontalRevealRequest = new HorizontalRevealRequest(e.range.startLineNumber, e.range.startColumn, e.range.endColumn, this._context.viewLayout.getCurrentScrollTop(), newScrollPosition.scrollTop, e.scrollType); } } else { this._horizontalRevealRequest = null; } var scrollTopDelta = Math.abs(this._context.viewLayout.getCurrentScrollTop() - newScrollPosition.scrollTop); if (e.scrollType === 0 /* Smooth */ && scrollTopDelta > this._lineHeight) { this._context.viewLayout.setScrollPositionSmooth(newScrollPosition); } else { this._context.viewLayout.setScrollPositionNow(newScrollPosition); } return true; }; ViewLines.prototype.onScrollChanged = function (e) { if (this._horizontalRevealRequest && e.scrollLeftChanged) { // cancel any outstanding horizontal reveal request if someone else scrolls horizontally. this._horizontalRevealRequest = null; } if (this._horizontalRevealRequest && e.scrollTopChanged) { var min = Math.min(this._horizontalRevealRequest.startScrollTop, this._horizontalRevealRequest.stopScrollTop); var max = Math.max(this._horizontalRevealRequest.startScrollTop, this._horizontalRevealRequest.stopScrollTop); if (e.scrollTop < min || e.scrollTop > max) { // cancel any outstanding horizontal reveal request if someone else scrolls vertically. this._horizontalRevealRequest = null; } } this.domNode.setWidth(e.scrollWidth); return this._visibleLines.onScrollChanged(e) || true; }; ViewLines.prototype.onTokensChanged = function (e) { return this._visibleLines.onTokensChanged(e); }; ViewLines.prototype.onZonesChanged = function (e) { this._context.viewLayout.onMaxLineWidthChanged(this._maxLineWidth); return this._visibleLines.onZonesChanged(e); }; ViewLines.prototype.onThemeChanged = function (e) { return this._onOptionsMaybeChanged(); }; // ---- end view event handlers // ----------- HELPERS FOR OTHERS ViewLines.prototype.getPositionFromDOMInfo = function (spanNode, offset) { var viewLineDomNode = this._getViewLineDomNode(spanNode); if (viewLineDomNode === null) { // Couldn't find view line node return null; } var lineNumber = this._getLineNumberFor(viewLineDomNode); if (lineNumber === -1) { // Couldn't find view line node return null; } if (lineNumber < 1 || lineNumber > this._context.model.getLineCount()) { // lineNumber is outside range return null; } if (this._context.model.getLineMaxColumn(lineNumber) === 1) { // Line is empty return new position_1.Position(lineNumber, 1); } var rendStartLineNumber = this._visibleLines.getStartLineNumber(); var rendEndLineNumber = this._visibleLines.getEndLineNumber(); if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) { // Couldn't find line return null; } var column = this._visibleLines.getVisibleLine(lineNumber).getColumnOfNodeOffset(lineNumber, spanNode, offset); var minColumn = this._context.model.getLineMinColumn(lineNumber); if (column < minColumn) { column = minColumn; } return new position_1.Position(lineNumber, column); }; ViewLines.prototype._getViewLineDomNode = function (node) { while (node && node.nodeType === 1) { if (node.className === viewLine_1.ViewLine.CLASS_NAME) { return node; } node = node.parentElement; } return null; }; /** * @returns the line number of this view line dom node. */ ViewLines.prototype._getLineNumberFor = function (domNode) { var startLineNumber = this._visibleLines.getStartLineNumber(); var endLineNumber = this._visibleLines.getEndLineNumber(); for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { var line = this._visibleLines.getVisibleLine(lineNumber); if (domNode === line.getDomNode()) { return lineNumber; } } return -1; }; ViewLines.prototype.getLineWidth = function (lineNumber) { var rendStartLineNumber = this._visibleLines.getStartLineNumber(); var rendEndLineNumber = this._visibleLines.getEndLineNumber(); if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) { // Couldn't find line return -1; } return this._visibleLines.getVisibleLine(lineNumber).getWidth(); }; ViewLines.prototype.linesVisibleRangesForRange = function (_range, includeNewLines) { if (this.shouldRender()) { // Cannot read from the DOM because it is dirty // i.e. the model & the dom are out of sync, so I'd be reading something stale return null; } var originalEndLineNumber = _range.endLineNumber; var range = range_1.Range.intersectRanges(_range, this._lastRenderedData.getCurrentVisibleRange()); if (!range) { return null; } var visibleRanges = [], visibleRangesLen = 0; var domReadingContext = new viewLine_1.DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot); var nextLineModelLineNumber = 0; if (includeNewLines) { nextLineModelLineNumber = this._context.model.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(range.startLineNumber, 1)).lineNumber; } var rendStartLineNumber = this._visibleLines.getStartLineNumber(); var rendEndLineNumber = this._visibleLines.getEndLineNumber(); for (var lineNumber = range.startLineNumber; lineNumber <= range.endLineNumber; lineNumber++) { if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) { continue; } var startColumn = lineNumber === range.startLineNumber ? range.startColumn : 1; var endColumn = lineNumber === range.endLineNumber ? range.endColumn : this._context.model.getLineMaxColumn(lineNumber); var visibleRangesForLine = this._visibleLines.getVisibleLine(lineNumber).getVisibleRangesForRange(startColumn, endColumn, domReadingContext); if (!visibleRangesForLine) { continue; } if (includeNewLines && lineNumber < originalEndLineNumber) { var currentLineModelLineNumber = nextLineModelLineNumber; nextLineModelLineNumber = this._context.model.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(lineNumber + 1, 1)).lineNumber; if (currentLineModelLineNumber !== nextLineModelLineNumber) { visibleRangesForLine.ranges[visibleRangesForLine.ranges.length - 1].width += this._typicalHalfwidthCharacterWidth; } } visibleRanges[visibleRangesLen++] = new renderingContext_1.LineVisibleRanges(visibleRangesForLine.outsideRenderedLine, lineNumber, visibleRangesForLine.ranges); } if (visibleRangesLen === 0) { return null; } return visibleRanges; }; ViewLines.prototype._visibleRangesForLineRange = function (lineNumber, startColumn, endColumn) { if (this.shouldRender()) { // Cannot read from the DOM because it is dirty // i.e. the model & the dom are out of sync, so I'd be reading something stale return null; } if (lineNumber < this._visibleLines.getStartLineNumber() || lineNumber > this._visibleLines.getEndLineNumber()) { return null; } return this._visibleLines.getVisibleLine(lineNumber).getVisibleRangesForRange(startColumn, endColumn, new viewLine_1.DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot)); }; ViewLines.prototype.visibleRangeForPosition = function (position) { var visibleRanges = this._visibleRangesForLineRange(position.lineNumber, position.column, position.column); if (!visibleRanges) { return null; } return new renderingContext_1.HorizontalPosition(visibleRanges.outsideRenderedLine, visibleRanges.ranges[0].left); }; // --- implementation ViewLines.prototype.updateLineWidths = function () { this._updateLineWidths(false); }; /** * Updates the max line width if it is fast to compute. * Returns true if all lines were taken into account. * Returns false if some lines need to be reevaluated (in a slow fashion). */ ViewLines.prototype._updateLineWidthsFast = function () { return this._updateLineWidths(true); }; ViewLines.prototype._updateLineWidthsSlow = function () { this._updateLineWidths(false); }; ViewLines.prototype._updateLineWidths = function (fast) { var rendStartLineNumber = this._visibleLines.getStartLineNumber(); var rendEndLineNumber = this._visibleLines.getEndLineNumber(); var localMaxLineWidth = 1; var allWidthsComputed = true; for (var lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) { var visibleLine = this._visibleLines.getVisibleLine(lineNumber); if (fast && !visibleLine.getWidthIsFast()) { // Cannot compute width in a fast way for this line allWidthsComputed = false; continue; } localMaxLineWidth = Math.max(localMaxLineWidth, visibleLine.getWidth()); } if (allWidthsComputed && rendStartLineNumber === 1 && rendEndLineNumber === this._context.model.getLineCount()) { // we know the max line width for all the lines this._maxLineWidth = 0; } this._ensureMaxLineWidth(localMaxLineWidth); return allWidthsComputed; }; ViewLines.prototype.prepareRender = function () { throw new Error('Not supported'); }; ViewLines.prototype.render = function () { throw new Error('Not supported'); }; ViewLines.prototype.renderText = function (viewportData) { // (1) render lines - ensures lines are in the DOM this._visibleLines.renderLines(viewportData); this._lastRenderedData.setCurrentVisibleRange(viewportData.visibleRange); this.domNode.setWidth(this._context.viewLayout.getScrollWidth()); this.domNode.setHeight(Math.min(this._context.viewLayout.getScrollHeight(), 1000000)); // (2) compute horizontal scroll position: // - this must happen after the lines are in the DOM since it might need a line that rendered just now // - it might change `scrollWidth` and `scrollLeft` if (this._horizontalRevealRequest) { var revealLineNumber = this._horizontalRevealRequest.lineNumber; var revealStartColumn = this._horizontalRevealRequest.startColumn; var revealEndColumn = this._horizontalRevealRequest.endColumn; var scrollType = this._horizontalRevealRequest.scrollType; // Check that we have the line that contains the horizontal range in the viewport if (viewportData.startLineNumber <= revealLineNumber && revealLineNumber <= viewportData.endLineNumber) { this._horizontalRevealRequest = null; // allow `visibleRangesForRange2` to work this.onDidRender(); // compute new scroll position var newScrollLeft = this._computeScrollLeftToRevealRange(revealLineNumber, revealStartColumn, revealEndColumn); var isViewportWrapping = this._isViewportWrapping; if (!isViewportWrapping) { // ensure `scrollWidth` is large enough this._ensureMaxLineWidth(newScrollLeft.maxHorizontalOffset); } // set `scrollLeft` if (scrollType === 0 /* Smooth */) { this._context.viewLayout.setScrollPositionSmooth({ scrollLeft: newScrollLeft.scrollLeft }); } else { this._context.viewLayout.setScrollPositionNow({ scrollLeft: newScrollLeft.scrollLeft }); } } } // Update max line width (not so important, it is just so the horizontal scrollbar doesn't get too small) if (!this._updateLineWidthsFast()) { // Computing the width of some lines would be slow => delay it this._asyncUpdateLineWidths.schedule(); } // (3) handle scrolling this._linesContent.setLayerHinting(this._canUseLayerHinting); this._linesContent.setContain('strict'); var adjustedScrollTop = this._context.viewLayout.getCurrentScrollTop() - viewportData.bigNumbersDelta; this._linesContent.setTop(-adjustedScrollTop); this._linesContent.setLeft(-this._context.viewLayout.getCurrentScrollLeft()); }; // --- width ViewLines.prototype._ensureMaxLineWidth = function (lineWidth) { var iLineWidth = Math.ceil(lineWidth); if (this._maxLineWidth < iLineWidth) { this._maxLineWidth = iLineWidth; this._context.viewLayout.onMaxLineWidthChanged(this._maxLineWidth); } }; ViewLines.prototype._computeScrollTopToRevealRange = function (viewport, source, range, verticalType) { var viewportStartY = viewport.top; var viewportHeight = viewport.height; var viewportEndY = viewportStartY + viewportHeight; var boxStartY; var boxEndY; // Have a box that includes one extra line height (for the horizontal scrollbar) boxStartY = this._context.viewLayout.getVerticalOffsetForLineNumber(range.startLineNumber); boxEndY = this._context.viewLayout.getVerticalOffsetForLineNumber(range.endLineNumber) + this._lineHeight; var shouldIgnoreScrollOff = source === 'mouse' && this._cursorSurroundingLinesStyle === 'default'; if (!shouldIgnoreScrollOff) { var context = Math.min((viewportHeight / this._lineHeight) / 2, this._cursorSurroundingLines); boxStartY -= context * this._lineHeight; boxEndY += Math.max(0, (context - 1)) * this._lineHeight; } if (verticalType === 0 /* Simple */ || verticalType === 4 /* Bottom */) { // Reveal one line more when the last line would be covered by the scrollbar - arrow down case or revealing a line explicitly at bottom boxEndY += this._lineHeight; } var newScrollTop; if (boxEndY - boxStartY > viewportHeight) { // the box is larger than the viewport ... scroll to its top newScrollTop = boxStartY; } else if (verticalType === 1 /* Center */ || verticalType === 2 /* CenterIfOutsideViewport */) { if (verticalType === 2 /* CenterIfOutsideViewport */ && viewportStartY <= boxStartY && boxEndY <= viewportEndY) { // Box is already in the viewport... do nothing newScrollTop = viewportStartY; } else { // Box is outside the viewport... center it var boxMiddleY = (boxStartY + boxEndY) / 2; newScrollTop = Math.max(0, boxMiddleY - viewportHeight / 2); } } else { newScrollTop = this._computeMinimumScrolling(viewportStartY, viewportEndY, boxStartY, boxEndY, verticalType === 3 /* Top */, verticalType === 4 /* Bottom */); } return newScrollTop; }; ViewLines.prototype._computeScrollLeftToRevealRange = function (lineNumber, startColumn, endColumn) { var maxHorizontalOffset = 0; var viewport = this._context.viewLayout.getCurrentViewport(); var viewportStartX = viewport.left; var viewportEndX = viewportStartX + viewport.width; var visibleRanges = this._visibleRangesForLineRange(lineNumber, startColumn, endColumn); var boxStartX = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; var boxEndX = 0; if (!visibleRanges) { // Unknown return { scrollLeft: viewportStartX, maxHorizontalOffset: maxHorizontalOffset }; } for (var _i = 0, _a = visibleRanges.ranges; _i < _a.length; _i++) { var visibleRange = _a[_i]; if (visibleRange.left < boxStartX) { boxStartX = visibleRange.left; } if (visibleRange.left + visibleRange.width > boxEndX) { boxEndX = visibleRange.left + visibleRange.width; } } maxHorizontalOffset = boxEndX; boxStartX = Math.max(0, boxStartX - ViewLines.HORIZONTAL_EXTRA_PX); boxEndX += this._revealHorizontalRightPadding; var newScrollLeft = this._computeMinimumScrolling(viewportStartX, viewportEndX, boxStartX, boxEndX); return { scrollLeft: newScrollLeft, maxHorizontalOffset: maxHorizontalOffset }; }; ViewLines.prototype._computeMinimumScrolling = function (viewportStart, viewportEnd, boxStart, boxEnd, revealAtStart, revealAtEnd) { viewportStart = viewportStart | 0; viewportEnd = viewportEnd | 0; boxStart = boxStart | 0; boxEnd = boxEnd | 0; revealAtStart = !!revealAtStart; revealAtEnd = !!revealAtEnd; var viewportLength = viewportEnd - viewportStart; var boxLength = boxEnd - boxStart; if (boxLength < viewportLength) { // The box would fit in the viewport if (revealAtStart) { return boxStart; } if (revealAtEnd) { return Math.max(0, boxEnd - viewportLength); } if (boxStart < viewportStart) { // The box is above the viewport return boxStart; } else if (boxEnd > viewportEnd) { // The box is below the viewport return Math.max(0, boxEnd - viewportLength); } } else { // The box would not fit in the viewport // Reveal the beginning of the box return boxStart; } return viewportStart; }; /** * Adds this amount of pixels to the right of lines (no-one wants to type near the edge of the viewport) */ ViewLines.HORIZONTAL_EXTRA_PX = 30; return ViewLines; }(viewPart_1.ViewPart)); exports.ViewLines = ViewLines; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[553/*vs/editor/browser/viewParts/minimap/minimap*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,28/*vs/base/browser/fastDomNode*/,78/*vs/base/browser/globalMouseMoveMonitor*/,16/*vs/base/common/platform*/,5/*vs/base/common/strings*/,143/*vs/editor/browser/view/viewLayer*/,37/*vs/editor/browser/view/viewPart*/,33/*vs/editor/common/config/editorOptions*/,3/*vs/editor/common/core/range*/,215/*vs/editor/common/viewModel/minimapTokensColorTracker*/,81/*vs/editor/common/view/viewEvents*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,57/*vs/base/browser/touch*/,337/*vs/editor/browser/viewParts/minimap/minimapCharRendererFactory*/,48/*vs/editor/common/model*/,102/*vs/base/common/functional*/,293/*vs/css!vs/editor/browser/viewParts/minimap/minimap*/]), function (require, exports, dom, fastDomNode_1, globalMouseMoveMonitor_1, platform, strings, viewLayer_1, viewPart_1, editorOptions_1, range_1, minimapTokensColorTracker_1, viewEvents, colorRegistry_1, themeService_1, touch_1, minimapCharRendererFactory_1, model_1, functional_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function getMinimapLineHeight(renderMinimap, scale) { if (renderMinimap === 1 /* Text */) { return 2 /* BASE_CHAR_HEIGHT */ * scale; } // RenderMinimap.Blocks return (2 /* BASE_CHAR_HEIGHT */ + 1) * scale; } function getMinimapCharWidth(renderMinimap, scale) { if (renderMinimap === 1 /* Text */) { return 1 /* BASE_CHAR_WIDTH */ * scale; } // RenderMinimap.Blocks return 1 /* BASE_CHAR_WIDTH */ * scale; } /** * The orthogonal distance to the slider at which dragging "resets". This implements "snapping" */ var MOUSE_DRAG_RESET_DISTANCE = 140; var GUTTER_DECORATION_WIDTH = 2; var MinimapOptions = /** @class */ (function () { function MinimapOptions(configuration) { var _this = this; var options = configuration.options; var pixelRatio = options.get(105 /* pixelRatio */); var layoutInfo = options.get(107 /* layoutInfo */); var fontInfo = options.get(34 /* fontInfo */); this.renderMinimap = layoutInfo.renderMinimap | 0; this.scrollBeyondLastLine = options.get(80 /* scrollBeyondLastLine */); var minimapOpts = options.get(54 /* minimap */); this.showSlider = minimapOpts.showSlider; this.fontScale = Math.round(minimapOpts.scale * pixelRatio); this.charRenderer = functional_1.once(function () { return minimapCharRendererFactory_1.MinimapCharRendererFactory.create(_this.fontScale, fontInfo.fontFamily); }); this.pixelRatio = pixelRatio; this.typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth; this.lineHeight = options.get(49 /* lineHeight */); this.minimapLeft = layoutInfo.minimapLeft; this.minimapWidth = layoutInfo.minimapWidth; this.minimapHeight = layoutInfo.height; this.canvasInnerWidth = Math.floor(pixelRatio * this.minimapWidth); this.canvasInnerHeight = Math.floor(pixelRatio * this.minimapHeight); this.canvasOuterWidth = this.canvasInnerWidth / pixelRatio; this.canvasOuterHeight = this.canvasInnerHeight / pixelRatio; } MinimapOptions.prototype.equals = function (other) { return (this.renderMinimap === other.renderMinimap && this.scrollBeyondLastLine === other.scrollBeyondLastLine && this.showSlider === other.showSlider && this.pixelRatio === other.pixelRatio && this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth && this.lineHeight === other.lineHeight && this.fontScale === other.fontScale && this.minimapLeft === other.minimapLeft && this.minimapWidth === other.minimapWidth && this.minimapHeight === other.minimapHeight && this.canvasInnerWidth === other.canvasInnerWidth && this.canvasInnerHeight === other.canvasInnerHeight && this.canvasOuterWidth === other.canvasOuterWidth && this.canvasOuterHeight === other.canvasOuterHeight); }; return MinimapOptions; }()); var MinimapLayout = /** @class */ (function () { function MinimapLayout(scrollTop, scrollHeight, computedSliderRatio, sliderTop, sliderHeight, startLineNumber, endLineNumber) { this.scrollTop = scrollTop; this.scrollHeight = scrollHeight; this._computedSliderRatio = computedSliderRatio; this.sliderTop = sliderTop; this.sliderHeight = sliderHeight; this.startLineNumber = startLineNumber; this.endLineNumber = endLineNumber; } /** * Compute a desired `scrollPosition` such that the slider moves by `delta`. */ MinimapLayout.prototype.getDesiredScrollTopFromDelta = function (delta) { var desiredSliderPosition = this.sliderTop + delta; return Math.round(desiredSliderPosition / this._computedSliderRatio); }; MinimapLayout.prototype.getDesiredScrollTopFromTouchLocation = function (pageY) { return Math.round((pageY - this.sliderHeight / 2) / this._computedSliderRatio); }; MinimapLayout.create = function (options, viewportStartLineNumber, viewportEndLineNumber, viewportHeight, viewportContainsWhitespaceGaps, lineCount, scrollTop, scrollHeight, previousLayout) { var pixelRatio = options.pixelRatio; var minimapLineHeight = getMinimapLineHeight(options.renderMinimap, options.fontScale); var minimapLinesFitting = Math.floor(options.canvasInnerHeight / minimapLineHeight); var lineHeight = options.lineHeight; // The visible line count in a viewport can change due to a number of reasons: // a) with the same viewport width, different scroll positions can result in partial lines being visible: // e.g. for a line height of 20, and a viewport height of 600 // * scrollTop = 0 => visible lines are [1, 30] // * scrollTop = 10 => visible lines are [1, 31] (with lines 1 and 31 partially visible) // * scrollTop = 20 => visible lines are [2, 31] // b) whitespace gaps might make their way in the viewport (which results in a decrease in the visible line count) // c) we could be in the scroll beyond last line case (which also results in a decrease in the visible line count, down to possibly only one line being visible) // We must first establish a desirable slider height. var sliderHeight; if (viewportContainsWhitespaceGaps && viewportEndLineNumber !== lineCount) { // case b) from above: there are whitespace gaps in the viewport. // In this case, the height of the slider directly reflects the visible line count. var viewportLineCount = viewportEndLineNumber - viewportStartLineNumber + 1; sliderHeight = Math.floor(viewportLineCount * minimapLineHeight / pixelRatio); } else { // The slider has a stable height var expectedViewportLineCount = viewportHeight / lineHeight; sliderHeight = Math.floor(expectedViewportLineCount * minimapLineHeight / pixelRatio); } var maxMinimapSliderTop; if (options.scrollBeyondLastLine) { // The minimap slider, when dragged all the way down, will contain the last line at its top maxMinimapSliderTop = (lineCount - 1) * minimapLineHeight / pixelRatio; } else { // The minimap slider, when dragged all the way down, will contain the last line at its bottom maxMinimapSliderTop = Math.max(0, lineCount * minimapLineHeight / pixelRatio - sliderHeight); } maxMinimapSliderTop = Math.min(options.minimapHeight - sliderHeight, maxMinimapSliderTop); // The slider can move from 0 to `maxMinimapSliderTop` // in the same way `scrollTop` can move from 0 to `scrollHeight` - `viewportHeight`. var computedSliderRatio = (maxMinimapSliderTop) / (scrollHeight - viewportHeight); var sliderTop = (scrollTop * computedSliderRatio); var extraLinesAtTheBottom = 0; if (options.scrollBeyondLastLine) { var expectedViewportLineCount = viewportHeight / lineHeight; extraLinesAtTheBottom = expectedViewportLineCount; } if (minimapLinesFitting >= lineCount + extraLinesAtTheBottom) { // All lines fit in the minimap var startLineNumber = 1; var endLineNumber = lineCount; return new MinimapLayout(scrollTop, scrollHeight, computedSliderRatio, sliderTop, sliderHeight, startLineNumber, endLineNumber); } else { var startLineNumber = Math.max(1, Math.floor(viewportStartLineNumber - sliderTop * pixelRatio / minimapLineHeight)); // Avoid flickering caused by a partial viewport start line // by being consistent w.r.t. the previous layout decision if (previousLayout && previousLayout.scrollHeight === scrollHeight) { if (previousLayout.scrollTop > scrollTop) { // Scrolling up => never increase `startLineNumber` startLineNumber = Math.min(startLineNumber, previousLayout.startLineNumber); } if (previousLayout.scrollTop < scrollTop) { // Scrolling down => never decrease `startLineNumber` startLineNumber = Math.max(startLineNumber, previousLayout.startLineNumber); } } var endLineNumber = Math.min(lineCount, startLineNumber + minimapLinesFitting - 1); return new MinimapLayout(scrollTop, scrollHeight, computedSliderRatio, sliderTop, sliderHeight, startLineNumber, endLineNumber); } }; return MinimapLayout; }()); var MinimapLine = /** @class */ (function () { function MinimapLine(dy) { this.dy = dy; } MinimapLine.prototype.onContentChanged = function () { this.dy = -1; }; MinimapLine.prototype.onTokensChanged = function () { this.dy = -1; }; MinimapLine.INVALID = new MinimapLine(-1); return MinimapLine; }()); var RenderData = /** @class */ (function () { function RenderData(renderedLayout, imageData, lines) { this.renderedLayout = renderedLayout; this._imageData = imageData; this._renderedLines = new viewLayer_1.RenderedLinesCollection(function () { return MinimapLine.INVALID; }); this._renderedLines._set(renderedLayout.startLineNumber, lines); } /** * Check if the current RenderData matches accurately the new desired layout and no painting is needed. */ RenderData.prototype.linesEquals = function (layout) { if (!this.scrollEquals(layout)) { return false; } var tmp = this._renderedLines._get(); var lines = tmp.lines; for (var i = 0, len = lines.length; i < len; i++) { if (lines[i].dy === -1) { // This line is invalid return false; } } return true; }; /** * Check if the current RenderData matches the new layout's scroll position */ RenderData.prototype.scrollEquals = function (layout) { return this.renderedLayout.startLineNumber === layout.startLineNumber && this.renderedLayout.endLineNumber === layout.endLineNumber; }; RenderData.prototype._get = function () { var tmp = this._renderedLines._get(); return { imageData: this._imageData, rendLineNumberStart: tmp.rendLineNumberStart, lines: tmp.lines }; }; RenderData.prototype.onLinesChanged = function (e) { return this._renderedLines.onLinesChanged(e.fromLineNumber, e.toLineNumber); }; RenderData.prototype.onLinesDeleted = function (e) { this._renderedLines.onLinesDeleted(e.fromLineNumber, e.toLineNumber); }; RenderData.prototype.onLinesInserted = function (e) { this._renderedLines.onLinesInserted(e.fromLineNumber, e.toLineNumber); }; RenderData.prototype.onTokensChanged = function (e) { return this._renderedLines.onTokensChanged(e.ranges); }; return RenderData; }()); /** * Some sort of double buffering. * * Keeps two buffers around that will be rotated for painting. * Always gives a buffer that is filled with the background color. */ var MinimapBuffers = /** @class */ (function () { function MinimapBuffers(ctx, WIDTH, HEIGHT, background) { this._backgroundFillData = MinimapBuffers._createBackgroundFillData(WIDTH, HEIGHT, background); this._buffers = [ ctx.createImageData(WIDTH, HEIGHT), ctx.createImageData(WIDTH, HEIGHT) ]; this._lastUsedBuffer = 0; } MinimapBuffers.prototype.getBuffer = function () { // rotate buffers this._lastUsedBuffer = 1 - this._lastUsedBuffer; var result = this._buffers[this._lastUsedBuffer]; // fill with background color result.data.set(this._backgroundFillData); return result; }; MinimapBuffers._createBackgroundFillData = function (WIDTH, HEIGHT, background) { var backgroundR = background.r; var backgroundG = background.g; var backgroundB = background.b; var result = new Uint8ClampedArray(WIDTH * HEIGHT * 4); var offset = 0; for (var i = 0; i < HEIGHT; i++) { for (var j = 0; j < WIDTH; j++) { result[offset] = backgroundR; result[offset + 1] = backgroundG; result[offset + 2] = backgroundB; result[offset + 3] = 255; offset += 4; } } return result; }; return MinimapBuffers; }()); var Minimap = /** @class */ (function (_super) { __extends(Minimap, _super); function Minimap(context) { var _this = _super.call(this, context) || this; _this._selections = []; _this._renderDecorations = false; _this._gestureInProgress = false; _this._options = new MinimapOptions(_this._context.configuration); _this._lastRenderData = null; _this._buffers = null; _this._selectionColor = _this._context.theme.getColor(colorRegistry_1.minimapSelection); _this._domNode = fastDomNode_1.createFastDomNode(document.createElement('div')); viewPart_1.PartFingerprints.write(_this._domNode, 8 /* Minimap */); _this._domNode.setClassName(_this._getMinimapDomNodeClassName()); _this._domNode.setPosition('absolute'); _this._domNode.setAttribute('role', 'presentation'); _this._domNode.setAttribute('aria-hidden', 'true'); _this._shadow = fastDomNode_1.createFastDomNode(document.createElement('div')); _this._shadow.setClassName('minimap-shadow-hidden'); _this._domNode.appendChild(_this._shadow); _this._canvas = fastDomNode_1.createFastDomNode(document.createElement('canvas')); _this._canvas.setPosition('absolute'); _this._canvas.setLeft(0); _this._domNode.appendChild(_this._canvas); _this._decorationsCanvas = fastDomNode_1.createFastDomNode(document.createElement('canvas')); _this._decorationsCanvas.setPosition('absolute'); _this._decorationsCanvas.setClassName('minimap-decorations-layer'); _this._decorationsCanvas.setLeft(0); _this._domNode.appendChild(_this._decorationsCanvas); _this._slider = fastDomNode_1.createFastDomNode(document.createElement('div')); _this._slider.setPosition('absolute'); _this._slider.setClassName('minimap-slider'); _this._slider.setLayerHinting(true); _this._slider.setContain('strict'); _this._domNode.appendChild(_this._slider); _this._sliderHorizontal = fastDomNode_1.createFastDomNode(document.createElement('div')); _this._sliderHorizontal.setPosition('absolute'); _this._sliderHorizontal.setClassName('minimap-slider-horizontal'); _this._slider.appendChild(_this._sliderHorizontal); _this._tokensColorTracker = minimapTokensColorTracker_1.MinimapTokensColorTracker.getInstance(); _this._applyLayout(); _this._mouseDownListener = dom.addStandardDisposableListener(_this._domNode.domNode, 'mousedown', function (e) { e.preventDefault(); var renderMinimap = _this._options.renderMinimap; if (renderMinimap === 0 /* None */) { return; } if (!_this._lastRenderData) { return; } var minimapLineHeight = getMinimapLineHeight(renderMinimap, _this._options.fontScale); var internalOffsetY = _this._options.pixelRatio * e.browserEvent.offsetY; var lineIndex = Math.floor(internalOffsetY / minimapLineHeight); var lineNumber = lineIndex + _this._lastRenderData.renderedLayout.startLineNumber; lineNumber = Math.min(lineNumber, _this._context.model.getLineCount()); _this._context.privateViewEventBus.emit(new viewEvents.ViewRevealRangeRequestEvent('mouse', new range_1.Range(lineNumber, 1, lineNumber, 1), 1 /* Center */, false, 0 /* Smooth */)); }); _this._sliderMouseMoveMonitor = new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor(); _this._sliderMouseDownListener = dom.addStandardDisposableListener(_this._slider.domNode, 'mousedown', function (e) { e.preventDefault(); e.stopPropagation(); if (e.leftButton && _this._lastRenderData) { var initialMousePosition_1 = e.posy; var initialMouseOrthogonalPosition_1 = e.posx; var initialSliderState_1 = _this._lastRenderData.renderedLayout; _this._slider.toggleClassName('active', true); _this._sliderMouseMoveMonitor.startMonitoring(e.target, e.buttons, globalMouseMoveMonitor_1.standardMouseMoveMerger, function (mouseMoveData) { var mouseOrthogonalDelta = Math.abs(mouseMoveData.posx - initialMouseOrthogonalPosition_1); if (platform.isWindows && mouseOrthogonalDelta > MOUSE_DRAG_RESET_DISTANCE) { // The mouse has wondered away from the scrollbar => reset dragging _this._context.viewLayout.setScrollPositionNow({ scrollTop: initialSliderState_1.scrollTop }); return; } var mouseDelta = mouseMoveData.posy - initialMousePosition_1; _this._context.viewLayout.setScrollPositionNow({ scrollTop: initialSliderState_1.getDesiredScrollTopFromDelta(mouseDelta) }); }, function () { _this._slider.toggleClassName('active', false); }); } }); _this._gestureDisposable = touch_1.Gesture.addTarget(_this._domNode.domNode); _this._sliderTouchStartListener = dom.addDisposableListener(_this._domNode.domNode, touch_1.EventType.Start, function (e) { e.preventDefault(); e.stopPropagation(); if (_this._lastRenderData) { _this._slider.toggleClassName('active', true); _this._gestureInProgress = true; _this.scrollDueToTouchEvent(e); } }); _this._sliderTouchMoveListener = dom.addStandardDisposableListener(_this._domNode.domNode, touch_1.EventType.Change, function (e) { e.preventDefault(); e.stopPropagation(); if (_this._lastRenderData && _this._gestureInProgress) { _this.scrollDueToTouchEvent(e); } }); _this._sliderTouchEndListener = dom.addStandardDisposableListener(_this._domNode.domNode, touch_1.EventType.End, function (e) { e.preventDefault(); e.stopPropagation(); _this._gestureInProgress = false; _this._slider.toggleClassName('active', false); }); return _this; } Minimap.prototype.scrollDueToTouchEvent = function (touch) { var startY = this._domNode.domNode.getBoundingClientRect().top; var scrollTop = this._lastRenderData.renderedLayout.getDesiredScrollTopFromTouchLocation(touch.pageY - startY); this._context.viewLayout.setScrollPositionNow({ scrollTop: scrollTop }); }; Minimap.prototype.dispose = function () { this._mouseDownListener.dispose(); this._sliderMouseMoveMonitor.dispose(); this._sliderMouseDownListener.dispose(); this._gestureDisposable.dispose(); this._sliderTouchStartListener.dispose(); this._sliderTouchMoveListener.dispose(); this._sliderTouchEndListener.dispose(); _super.prototype.dispose.call(this); }; Minimap.prototype._getMinimapDomNodeClassName = function () { if (this._options.showSlider === 'always') { return 'minimap slider-always'; } return 'minimap slider-mouseover'; }; Minimap.prototype.getDomNode = function () { return this._domNode; }; Minimap.prototype._applyLayout = function () { this._domNode.setLeft(this._options.minimapLeft); this._domNode.setWidth(this._options.minimapWidth); this._domNode.setHeight(this._options.minimapHeight); this._shadow.setHeight(this._options.minimapHeight); this._canvas.setWidth(this._options.canvasOuterWidth); this._canvas.setHeight(this._options.canvasOuterHeight); this._canvas.domNode.width = this._options.canvasInnerWidth; this._canvas.domNode.height = this._options.canvasInnerHeight; this._decorationsCanvas.setWidth(this._options.canvasOuterWidth); this._decorationsCanvas.setHeight(this._options.canvasOuterHeight); this._decorationsCanvas.domNode.width = this._options.canvasInnerWidth; this._decorationsCanvas.domNode.height = this._options.canvasInnerHeight; this._slider.setWidth(this._options.minimapWidth); }; Minimap.prototype._getBuffer = function () { if (!this._buffers) { if (this._options.canvasInnerWidth > 0 && this._options.canvasInnerHeight > 0) { this._buffers = new MinimapBuffers(this._canvas.domNode.getContext('2d'), this._options.canvasInnerWidth, this._options.canvasInnerHeight, this._tokensColorTracker.getColor(2 /* DefaultBackground */)); } } return this._buffers ? this._buffers.getBuffer() : null; }; Minimap.prototype._onOptionsMaybeChanged = function () { var opts = new MinimapOptions(this._context.configuration); if (this._options.equals(opts)) { return false; } this._options = opts; this._lastRenderData = null; this._buffers = null; this._applyLayout(); this._domNode.setClassName(this._getMinimapDomNodeClassName()); return true; }; // ---- begin view event handlers Minimap.prototype.onConfigurationChanged = function (e) { return this._onOptionsMaybeChanged(); }; Minimap.prototype.onCursorStateChanged = function (e) { this._selections = e.selections; this._renderDecorations = true; return true; }; Minimap.prototype.onFlushed = function (e) { this._lastRenderData = null; return true; }; Minimap.prototype.onLinesChanged = function (e) { if (this._lastRenderData) { return this._lastRenderData.onLinesChanged(e); } return false; }; Minimap.prototype.onLinesDeleted = function (e) { if (this._lastRenderData) { this._lastRenderData.onLinesDeleted(e); } return true; }; Minimap.prototype.onLinesInserted = function (e) { if (this._lastRenderData) { this._lastRenderData.onLinesInserted(e); } return true; }; Minimap.prototype.onScrollChanged = function (e) { this._renderDecorations = true; return true; }; Minimap.prototype.onTokensChanged = function (e) { if (this._lastRenderData) { return this._lastRenderData.onTokensChanged(e); } return false; }; Minimap.prototype.onTokensColorsChanged = function (e) { this._lastRenderData = null; this._buffers = null; return true; }; Minimap.prototype.onZonesChanged = function (e) { this._lastRenderData = null; return true; }; Minimap.prototype.onDecorationsChanged = function (e) { this._renderDecorations = true; return true; }; Minimap.prototype.onThemeChanged = function (e) { this._context.model.invalidateMinimapColorCache(); this._selectionColor = this._context.theme.getColor(colorRegistry_1.minimapSelection); this._renderDecorations = true; return true; }; // --- end event handlers Minimap.prototype.prepareRender = function (ctx) { // Nothing to read }; Minimap.prototype.render = function (renderingCtx) { var renderMinimap = this._options.renderMinimap; if (renderMinimap === 0 /* None */) { this._shadow.setClassName('minimap-shadow-hidden'); this._sliderHorizontal.setWidth(0); this._sliderHorizontal.setHeight(0); return; } if (renderingCtx.scrollLeft + renderingCtx.viewportWidth >= renderingCtx.scrollWidth) { this._shadow.setClassName('minimap-shadow-hidden'); } else { this._shadow.setClassName('minimap-shadow-visible'); } var layout = MinimapLayout.create(this._options, renderingCtx.visibleRange.startLineNumber, renderingCtx.visibleRange.endLineNumber, renderingCtx.viewportHeight, (renderingCtx.viewportData.whitespaceViewportData.length > 0), this._context.model.getLineCount(), renderingCtx.scrollTop, renderingCtx.scrollHeight, this._lastRenderData ? this._lastRenderData.renderedLayout : null); this._slider.setTop(layout.sliderTop); this._slider.setHeight(layout.sliderHeight); // Compute horizontal slider coordinates var scrollLeftChars = renderingCtx.scrollLeft / this._options.typicalHalfwidthCharacterWidth; var horizontalSliderLeft = Math.min(this._options.minimapWidth, Math.round(scrollLeftChars * getMinimapCharWidth(this._options.renderMinimap, this._options.fontScale) / this._options.pixelRatio)); this._sliderHorizontal.setLeft(horizontalSliderLeft); this._sliderHorizontal.setWidth(this._options.minimapWidth - horizontalSliderLeft); this._sliderHorizontal.setTop(0); this._sliderHorizontal.setHeight(layout.sliderHeight); this.renderDecorations(layout); this._lastRenderData = this.renderLines(layout); }; Minimap.prototype.renderDecorations = function (layout) { if (this._renderDecorations) { this._renderDecorations = false; var decorations = this._context.model.getDecorationsInViewport(new range_1.Range(layout.startLineNumber, 1, layout.endLineNumber, this._context.model.getLineMaxColumn(layout.endLineNumber))); var _a = this._options, renderMinimap = _a.renderMinimap, canvasInnerWidth = _a.canvasInnerWidth, canvasInnerHeight = _a.canvasInnerHeight; var lineHeight = getMinimapLineHeight(renderMinimap, this._options.fontScale); var characterWidth = getMinimapCharWidth(renderMinimap, this._options.fontScale); var tabSize = this._context.model.getOptions().tabSize; var canvasContext = this._decorationsCanvas.domNode.getContext('2d'); canvasContext.clearRect(0, 0, canvasInnerWidth, canvasInnerHeight); var lineOffsetMap = new Map(); for (var i = 0; i < this._selections.length; i++) { var selection = this._selections[i]; for (var line = selection.startLineNumber; line <= selection.endLineNumber; line++) { this.renderDecorationOnLine(canvasContext, lineOffsetMap, selection, this._selectionColor, layout, line, lineHeight, lineHeight, tabSize, characterWidth); } } // Loop over decorations, ignoring those that don't have the minimap property set and rendering rectangles for each line the decoration spans for (var i = 0; i < decorations.length; i++) { var decoration = decorations[i]; if (!decoration.options.minimap) { continue; } var decorationColor = decoration.options.minimap.getColor(this._context.theme); for (var line = decoration.range.startLineNumber; line <= decoration.range.endLineNumber; line++) { switch (decoration.options.minimap.position) { case model_1.MinimapPosition.Inline: this.renderDecorationOnLine(canvasContext, lineOffsetMap, decoration.range, decorationColor, layout, line, lineHeight, lineHeight, tabSize, characterWidth); continue; case model_1.MinimapPosition.Gutter: var y = (line - layout.startLineNumber) * lineHeight; var x = 2; this.renderDecoration(canvasContext, decorationColor, x, y, GUTTER_DECORATION_WIDTH, lineHeight); continue; } } } } }; Minimap.prototype.renderDecorationOnLine = function (canvasContext, lineOffsetMap, decorationRange, decorationColor, layout, lineNumber, height, lineHeight, tabSize, charWidth) { var y = (lineNumber - layout.startLineNumber) * lineHeight; // Skip rendering the line if it's vertically outside our viewport if (y + height < 0 || y > this._options.canvasInnerHeight) { return; } // Cache line offset data so that it is only read once per line var lineIndexToXOffset = lineOffsetMap.get(lineNumber); var isFirstDecorationForLine = !lineIndexToXOffset; if (!lineIndexToXOffset) { var lineData = this._context.model.getLineContent(lineNumber); lineIndexToXOffset = [editorOptions_1.MINIMAP_GUTTER_WIDTH]; for (var i = 1; i < lineData.length + 1; i++) { var charCode = lineData.charCodeAt(i - 1); var dx = charCode === 9 /* Tab */ ? tabSize * charWidth : strings.isFullWidthCharacter(charCode) ? 2 * charWidth : charWidth; lineIndexToXOffset[i] = lineIndexToXOffset[i - 1] + dx; } lineOffsetMap.set(lineNumber, lineIndexToXOffset); } var startColumn = decorationRange.startColumn, endColumn = decorationRange.endColumn, startLineNumber = decorationRange.startLineNumber, endLineNumber = decorationRange.endLineNumber; var x = startLineNumber === lineNumber ? lineIndexToXOffset[startColumn - 1] : editorOptions_1.MINIMAP_GUTTER_WIDTH; var endColumnForLine = endLineNumber > lineNumber ? lineIndexToXOffset.length - 1 : endColumn - 1; if (endColumnForLine > 0) { // If the decoration starts at the last character of the column and spans over it, ensure it has a width var width = lineIndexToXOffset[endColumnForLine] - x || 2; this.renderDecoration(canvasContext, decorationColor, x, y, width, height); } if (isFirstDecorationForLine) { this.renderLineHighlight(canvasContext, decorationColor, y, height); } }; Minimap.prototype.renderLineHighlight = function (canvasContext, decorationColor, y, height) { canvasContext.fillStyle = decorationColor && decorationColor.transparent(0.5).toString() || ''; canvasContext.fillRect(editorOptions_1.MINIMAP_GUTTER_WIDTH, y, canvasContext.canvas.width, height); }; Minimap.prototype.renderDecoration = function (canvasContext, decorationColor, x, y, width, height) { canvasContext.fillStyle = decorationColor && decorationColor.toString() || ''; canvasContext.fillRect(x, y, width, height); }; Minimap.prototype.renderLines = function (layout) { var renderMinimap = this._options.renderMinimap; var charRenderer = this._options.charRenderer(); var startLineNumber = layout.startLineNumber; var endLineNumber = layout.endLineNumber; var minimapLineHeight = getMinimapLineHeight(renderMinimap, this._options.fontScale); // Check if nothing changed w.r.t. lines from last frame if (this._lastRenderData && this._lastRenderData.linesEquals(layout)) { var _lastData = this._lastRenderData._get(); // Nice!! Nothing changed from last frame return new RenderData(layout, _lastData.imageData, _lastData.lines); } // Oh well!! We need to repaint some lines... var imageData = this._getBuffer(); if (!imageData) { // 0 width or 0 height canvas, nothing to do return null; } // Render untouched lines by using last rendered data. var _a = Minimap._renderUntouchedLines(imageData, startLineNumber, endLineNumber, minimapLineHeight, this._lastRenderData), _dirtyY1 = _a[0], _dirtyY2 = _a[1], needed = _a[2]; // Fetch rendering info from view model for rest of lines that need rendering. var lineInfo = this._context.model.getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed); var tabSize = lineInfo.tabSize; var background = this._tokensColorTracker.getColor(2 /* DefaultBackground */); var useLighterFont = this._tokensColorTracker.backgroundIsLight(); // Render the rest of lines var dy = 0; var renderedLines = []; for (var lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) { if (needed[lineIndex]) { Minimap._renderLine(imageData, background, useLighterFont, renderMinimap, this._tokensColorTracker, charRenderer, dy, tabSize, lineInfo.data[lineIndex], this._options.fontScale); } renderedLines[lineIndex] = new MinimapLine(dy); dy += minimapLineHeight; } var dirtyY1 = (_dirtyY1 === -1 ? 0 : _dirtyY1); var dirtyY2 = (_dirtyY2 === -1 ? imageData.height : _dirtyY2); var dirtyHeight = dirtyY2 - dirtyY1; // Finally, paint to the canvas var ctx = this._canvas.domNode.getContext('2d'); ctx.putImageData(imageData, 0, 0, 0, dirtyY1, imageData.width, dirtyHeight); // Save rendered data for reuse on next frame if possible return new RenderData(layout, imageData, renderedLines); }; Minimap._renderUntouchedLines = function (target, startLineNumber, endLineNumber, minimapLineHeight, lastRenderData) { var needed = []; if (!lastRenderData) { for (var i = 0, len = endLineNumber - startLineNumber + 1; i < len; i++) { needed[i] = true; } return [-1, -1, needed]; } var _lastData = lastRenderData._get(); var lastTargetData = _lastData.imageData.data; var lastStartLineNumber = _lastData.rendLineNumberStart; var lastLines = _lastData.lines; var lastLinesLength = lastLines.length; var WIDTH = target.width; var targetData = target.data; var maxDestPixel = (endLineNumber - startLineNumber + 1) * minimapLineHeight * WIDTH * 4; var dirtyPixel1 = -1; // the pixel offset up to which all the data is equal to the prev frame var dirtyPixel2 = -1; // the pixel offset after which all the data is equal to the prev frame var copySourceStart = -1; var copySourceEnd = -1; var copyDestStart = -1; var copyDestEnd = -1; var dest_dy = 0; for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { var lineIndex = lineNumber - startLineNumber; var lastLineIndex = lineNumber - lastStartLineNumber; var source_dy = (lastLineIndex >= 0 && lastLineIndex < lastLinesLength ? lastLines[lastLineIndex].dy : -1); if (source_dy === -1) { needed[lineIndex] = true; dest_dy += minimapLineHeight; continue; } var sourceStart = source_dy * WIDTH * 4; var sourceEnd = (source_dy + minimapLineHeight) * WIDTH * 4; var destStart = dest_dy * WIDTH * 4; var destEnd = (dest_dy + minimapLineHeight) * WIDTH * 4; if (copySourceEnd === sourceStart && copyDestEnd === destStart) { // contiguous zone => extend copy request copySourceEnd = sourceEnd; copyDestEnd = destEnd; } else { if (copySourceStart !== -1) { // flush existing copy request targetData.set(lastTargetData.subarray(copySourceStart, copySourceEnd), copyDestStart); if (dirtyPixel1 === -1 && copySourceStart === 0 && copySourceStart === copyDestStart) { dirtyPixel1 = copySourceEnd; } if (dirtyPixel2 === -1 && copySourceEnd === maxDestPixel && copySourceStart === copyDestStart) { dirtyPixel2 = copySourceStart; } } copySourceStart = sourceStart; copySourceEnd = sourceEnd; copyDestStart = destStart; copyDestEnd = destEnd; } needed[lineIndex] = false; dest_dy += minimapLineHeight; } if (copySourceStart !== -1) { // flush existing copy request targetData.set(lastTargetData.subarray(copySourceStart, copySourceEnd), copyDestStart); if (dirtyPixel1 === -1 && copySourceStart === 0 && copySourceStart === copyDestStart) { dirtyPixel1 = copySourceEnd; } if (dirtyPixel2 === -1 && copySourceEnd === maxDestPixel && copySourceStart === copyDestStart) { dirtyPixel2 = copySourceStart; } } var dirtyY1 = (dirtyPixel1 === -1 ? -1 : dirtyPixel1 / (WIDTH * 4)); var dirtyY2 = (dirtyPixel2 === -1 ? -1 : dirtyPixel2 / (WIDTH * 4)); return [dirtyY1, dirtyY2, needed]; }; Minimap._renderLine = function (target, backgroundColor, useLighterFont, renderMinimap, colorTracker, minimapCharRenderer, dy, tabSize, lineData, fontScale) { var content = lineData.content; var tokens = lineData.tokens; var charWidth = getMinimapCharWidth(renderMinimap, fontScale); var maxDx = target.width - charWidth; var dx = editorOptions_1.MINIMAP_GUTTER_WIDTH; var charIndex = 0; var tabsCharDelta = 0; for (var tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) { var tokenEndIndex = tokens.getEndOffset(tokenIndex); var tokenColorId = tokens.getForeground(tokenIndex); var tokenColor = colorTracker.getColor(tokenColorId); for (; charIndex < tokenEndIndex; charIndex++) { if (dx > maxDx) { // hit edge of minimap return; } var charCode = content.charCodeAt(charIndex); if (charCode === 9 /* Tab */) { var insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize; tabsCharDelta += insertSpacesCount - 1; // No need to render anything since tab is invisible dx += insertSpacesCount * charWidth; } else if (charCode === 32 /* Space */) { // No need to render anything since space is invisible dx += charWidth; } else { // Render twice for a full width character var count = strings.isFullWidthCharacter(charCode) ? 2 : 1; for (var i = 0; i < count; i++) { if (renderMinimap === 2 /* Blocks */) { minimapCharRenderer.blockRenderChar(target, dx, dy, tokenColor, backgroundColor, useLighterFont); } else { // RenderMinimap.Text minimapCharRenderer.renderChar(target, dx, dy, charCode, tokenColor, backgroundColor, fontScale, useLighterFont); } dx += charWidth; if (dx > maxDx) { // hit edge of minimap return; } } } } } }; return Minimap; }(viewPart_1.ViewPart)); exports.Minimap = Minimap; themeService_1.registerThemingParticipant(function (theme, collector) { var sliderBackground = theme.getColor(colorRegistry_1.scrollbarSliderBackground); if (sliderBackground) { var halfSliderBackground = sliderBackground.transparent(0.5); collector.addRule(".monaco-editor .minimap-slider, .monaco-editor .minimap-slider .minimap-slider-horizontal { background: " + halfSliderBackground + "; }"); } var sliderHoverBackground = theme.getColor(colorRegistry_1.scrollbarSliderHoverBackground); if (sliderHoverBackground) { var halfSliderHoverBackground = sliderHoverBackground.transparent(0.5); collector.addRule(".monaco-editor .minimap-slider:hover, .monaco-editor .minimap-slider:hover .minimap-slider-horizontal { background: " + halfSliderHoverBackground + "; }"); } var sliderActiveBackground = theme.getColor(colorRegistry_1.scrollbarSliderActiveBackground); if (sliderActiveBackground) { var halfSliderActiveBackground = sliderActiveBackground.transparent(0.5); collector.addRule(".monaco-editor .minimap-slider.active, .monaco-editor .minimap-slider.active .minimap-slider-horizontal { background: " + halfSliderActiveBackground + "; }"); } var shadow = theme.getColor(colorRegistry_1.scrollbarShadow); if (shadow) { collector.addRule(".monaco-editor .minimap-shadow-visible { box-shadow: " + shadow + " -6px 0 6px -6px inset; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[554/*vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,37/*vs/editor/browser/view/viewPart*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,296/*vs/css!vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/]), function (require, exports, fastDomNode_1, viewPart_1, colorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ScrollDecorationViewPart = /** @class */ (function (_super) { __extends(ScrollDecorationViewPart, _super); function ScrollDecorationViewPart(context) { var _this = _super.call(this, context) || this; _this._scrollTop = 0; _this._width = 0; _this._updateWidth(); _this._shouldShow = false; var options = _this._context.configuration.options; var scrollbar = options.get(78 /* scrollbar */); _this._useShadows = scrollbar.useShadows; _this._domNode = fastDomNode_1.createFastDomNode(document.createElement('div')); _this._domNode.setAttribute('role', 'presentation'); _this._domNode.setAttribute('aria-hidden', 'true'); return _this; } ScrollDecorationViewPart.prototype.dispose = function () { _super.prototype.dispose.call(this); }; ScrollDecorationViewPart.prototype._updateShouldShow = function () { var newShouldShow = (this._useShadows && this._scrollTop > 0); if (this._shouldShow !== newShouldShow) { this._shouldShow = newShouldShow; return true; } return false; }; ScrollDecorationViewPart.prototype.getDomNode = function () { return this._domNode; }; ScrollDecorationViewPart.prototype._updateWidth = function () { var options = this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); if (layoutInfo.renderMinimap === 0 || (layoutInfo.minimapWidth > 0 && layoutInfo.minimapLeft === 0)) { this._width = layoutInfo.width; } else { this._width = layoutInfo.width - layoutInfo.minimapWidth - layoutInfo.verticalScrollbarWidth; } }; // --- begin event handlers ScrollDecorationViewPart.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; var scrollbar = options.get(78 /* scrollbar */); this._useShadows = scrollbar.useShadows; this._updateWidth(); this._updateShouldShow(); return true; }; ScrollDecorationViewPart.prototype.onScrollChanged = function (e) { this._scrollTop = e.scrollTop; return this._updateShouldShow(); }; // --- end event handlers ScrollDecorationViewPart.prototype.prepareRender = function (ctx) { // Nothing to read }; ScrollDecorationViewPart.prototype.render = function (ctx) { this._domNode.setWidth(this._width); this._domNode.setClassName(this._shouldShow ? 'scroll-decoration' : ''); }; return ScrollDecorationViewPart; }(viewPart_1.ViewPart)); exports.ScrollDecorationViewPart = ScrollDecorationViewPart; themeService_1.registerThemingParticipant(function (theme, collector) { var shadow = theme.getColor(colorRegistry_1.scrollbarShadow); if (shadow) { collector.addRule(".monaco-editor .scroll-decoration { box-shadow: " + shadow + " 0 6px 6px -6px inset; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[555/*vs/editor/browser/viewParts/selections/selections*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,82/*vs/editor/browser/view/dynamicViewOverlay*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,297/*vs/css!vs/editor/browser/viewParts/selections/selections*/]), function (require, exports, browser, dynamicViewOverlay_1, colorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var HorizontalRangeWithStyle = /** @class */ (function () { function HorizontalRangeWithStyle(other) { this.left = other.left; this.width = other.width; this.startStyle = null; this.endStyle = null; } return HorizontalRangeWithStyle; }()); var LineVisibleRangesWithStyle = /** @class */ (function () { function LineVisibleRangesWithStyle(lineNumber, ranges) { this.lineNumber = lineNumber; this.ranges = ranges; } return LineVisibleRangesWithStyle; }()); function toStyledRange(item) { return new HorizontalRangeWithStyle(item); } function toStyled(item) { return new LineVisibleRangesWithStyle(item.lineNumber, item.ranges.map(toStyledRange)); } // TODO@Alex: Remove this once IE11 fixes Bug #524217 // The problem in IE11 is that it does some sort of auto-zooming to accomodate for displays with different pixel density. // Unfortunately, this auto-zooming is buggy around dealing with rounded borders var isIEWithZoomingIssuesNearRoundedBorders = browser.isEdgeOrIE; var SelectionsOverlay = /** @class */ (function (_super) { __extends(SelectionsOverlay, _super); function SelectionsOverlay(context) { var _this = _super.call(this) || this; _this._previousFrameVisibleRangesWithStyle = []; _this._context = context; var options = _this._context.configuration.options; _this._lineHeight = options.get(49 /* lineHeight */); _this._roundedSelection = options.get(76 /* roundedSelection */); _this._typicalHalfwidthCharacterWidth = options.get(34 /* fontInfo */).typicalHalfwidthCharacterWidth; _this._selections = []; _this._renderResult = null; _this._context.addEventHandler(_this); return _this; } SelectionsOverlay.prototype.dispose = function () { this._context.removeEventHandler(this); this._renderResult = null; _super.prototype.dispose.call(this); }; // --- begin event handlers SelectionsOverlay.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; this._lineHeight = options.get(49 /* lineHeight */); this._roundedSelection = options.get(76 /* roundedSelection */); this._typicalHalfwidthCharacterWidth = options.get(34 /* fontInfo */).typicalHalfwidthCharacterWidth; return true; }; SelectionsOverlay.prototype.onCursorStateChanged = function (e) { this._selections = e.selections.slice(0); return true; }; SelectionsOverlay.prototype.onDecorationsChanged = function (e) { // true for inline decorations that can end up relayouting text return true; //e.inlineDecorationsChanged; }; SelectionsOverlay.prototype.onFlushed = function (e) { return true; }; SelectionsOverlay.prototype.onLinesChanged = function (e) { return true; }; SelectionsOverlay.prototype.onLinesDeleted = function (e) { return true; }; SelectionsOverlay.prototype.onLinesInserted = function (e) { return true; }; SelectionsOverlay.prototype.onScrollChanged = function (e) { return e.scrollTopChanged; }; SelectionsOverlay.prototype.onZonesChanged = function (e) { return true; }; // --- end event handlers SelectionsOverlay.prototype._visibleRangesHaveGaps = function (linesVisibleRanges) { for (var i = 0, len = linesVisibleRanges.length; i < len; i++) { var lineVisibleRanges = linesVisibleRanges[i]; if (lineVisibleRanges.ranges.length > 1) { // There are two ranges on the same line return true; } } return false; }; SelectionsOverlay.prototype._enrichVisibleRangesWithStyle = function (viewport, linesVisibleRanges, previousFrame) { var epsilon = this._typicalHalfwidthCharacterWidth / 4; var previousFrameTop = null; var previousFrameBottom = null; if (previousFrame && previousFrame.length > 0 && linesVisibleRanges.length > 0) { var topLineNumber = linesVisibleRanges[0].lineNumber; if (topLineNumber === viewport.startLineNumber) { for (var i = 0; !previousFrameTop && i < previousFrame.length; i++) { if (previousFrame[i].lineNumber === topLineNumber) { previousFrameTop = previousFrame[i].ranges[0]; } } } var bottomLineNumber = linesVisibleRanges[linesVisibleRanges.length - 1].lineNumber; if (bottomLineNumber === viewport.endLineNumber) { for (var i = previousFrame.length - 1; !previousFrameBottom && i >= 0; i--) { if (previousFrame[i].lineNumber === bottomLineNumber) { previousFrameBottom = previousFrame[i].ranges[0]; } } } if (previousFrameTop && !previousFrameTop.startStyle) { previousFrameTop = null; } if (previousFrameBottom && !previousFrameBottom.startStyle) { previousFrameBottom = null; } } for (var i = 0, len = linesVisibleRanges.length; i < len; i++) { // We know for a fact that there is precisely one range on each line var curLineRange = linesVisibleRanges[i].ranges[0]; var curLeft = curLineRange.left; var curRight = curLineRange.left + curLineRange.width; var startStyle = { top: 0 /* EXTERN */, bottom: 0 /* EXTERN */ }; var endStyle = { top: 0 /* EXTERN */, bottom: 0 /* EXTERN */ }; if (i > 0) { // Look above var prevLeft = linesVisibleRanges[i - 1].ranges[0].left; var prevRight = linesVisibleRanges[i - 1].ranges[0].left + linesVisibleRanges[i - 1].ranges[0].width; if (abs(curLeft - prevLeft) < epsilon) { startStyle.top = 2 /* FLAT */; } else if (curLeft > prevLeft) { startStyle.top = 1 /* INTERN */; } if (abs(curRight - prevRight) < epsilon) { endStyle.top = 2 /* FLAT */; } else if (prevLeft < curRight && curRight < prevRight) { endStyle.top = 1 /* INTERN */; } } else if (previousFrameTop) { // Accept some hick-ups near the viewport edges to save on repaints startStyle.top = previousFrameTop.startStyle.top; endStyle.top = previousFrameTop.endStyle.top; } if (i + 1 < len) { // Look below var nextLeft = linesVisibleRanges[i + 1].ranges[0].left; var nextRight = linesVisibleRanges[i + 1].ranges[0].left + linesVisibleRanges[i + 1].ranges[0].width; if (abs(curLeft - nextLeft) < epsilon) { startStyle.bottom = 2 /* FLAT */; } else if (nextLeft < curLeft && curLeft < nextRight) { startStyle.bottom = 1 /* INTERN */; } if (abs(curRight - nextRight) < epsilon) { endStyle.bottom = 2 /* FLAT */; } else if (curRight < nextRight) { endStyle.bottom = 1 /* INTERN */; } } else if (previousFrameBottom) { // Accept some hick-ups near the viewport edges to save on repaints startStyle.bottom = previousFrameBottom.startStyle.bottom; endStyle.bottom = previousFrameBottom.endStyle.bottom; } curLineRange.startStyle = startStyle; curLineRange.endStyle = endStyle; } }; SelectionsOverlay.prototype._getVisibleRangesWithStyle = function (selection, ctx, previousFrame) { var _linesVisibleRanges = ctx.linesVisibleRangesForRange(selection, true) || []; var linesVisibleRanges = _linesVisibleRanges.map(toStyled); var visibleRangesHaveGaps = this._visibleRangesHaveGaps(linesVisibleRanges); if (!isIEWithZoomingIssuesNearRoundedBorders && !visibleRangesHaveGaps && this._roundedSelection) { this._enrichVisibleRangesWithStyle(ctx.visibleRange, linesVisibleRanges, previousFrame); } // The visible ranges are sorted TOP-BOTTOM and LEFT-RIGHT return linesVisibleRanges; }; SelectionsOverlay.prototype._createSelectionPiece = function (top, height, className, left, width) { return ('
    '); }; SelectionsOverlay.prototype._actualRenderOneSelection = function (output2, visibleStartLineNumber, hasMultipleSelections, visibleRanges) { if (visibleRanges.length === 0) { return; } var visibleRangesHaveStyle = !!visibleRanges[0].ranges[0].startStyle; var fullLineHeight = (this._lineHeight).toString(); var reducedLineHeight = (this._lineHeight - 1).toString(); var firstLineNumber = visibleRanges[0].lineNumber; var lastLineNumber = visibleRanges[visibleRanges.length - 1].lineNumber; for (var i = 0, len = visibleRanges.length; i < len; i++) { var lineVisibleRanges = visibleRanges[i]; var lineNumber = lineVisibleRanges.lineNumber; var lineIndex = lineNumber - visibleStartLineNumber; var lineHeight = hasMultipleSelections ? (lineNumber === lastLineNumber || lineNumber === firstLineNumber ? reducedLineHeight : fullLineHeight) : fullLineHeight; var top_1 = hasMultipleSelections ? (lineNumber === firstLineNumber ? 1 : 0) : 0; var innerCornerOutput = ''; var restOfSelectionOutput = ''; for (var j = 0, lenJ = lineVisibleRanges.ranges.length; j < lenJ; j++) { var visibleRange = lineVisibleRanges.ranges[j]; if (visibleRangesHaveStyle) { var startStyle = visibleRange.startStyle; var endStyle = visibleRange.endStyle; if (startStyle.top === 1 /* INTERN */ || startStyle.bottom === 1 /* INTERN */) { // Reverse rounded corner to the left // First comes the selection (blue layer) innerCornerOutput += this._createSelectionPiece(top_1, lineHeight, SelectionsOverlay.SELECTION_CLASS_NAME, visibleRange.left - SelectionsOverlay.ROUNDED_PIECE_WIDTH, SelectionsOverlay.ROUNDED_PIECE_WIDTH); // Second comes the background (white layer) with inverse border radius var className_1 = SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME; if (startStyle.top === 1 /* INTERN */) { className_1 += ' ' + SelectionsOverlay.SELECTION_TOP_RIGHT; } if (startStyle.bottom === 1 /* INTERN */) { className_1 += ' ' + SelectionsOverlay.SELECTION_BOTTOM_RIGHT; } innerCornerOutput += this._createSelectionPiece(top_1, lineHeight, className_1, visibleRange.left - SelectionsOverlay.ROUNDED_PIECE_WIDTH, SelectionsOverlay.ROUNDED_PIECE_WIDTH); } if (endStyle.top === 1 /* INTERN */ || endStyle.bottom === 1 /* INTERN */) { // Reverse rounded corner to the right // First comes the selection (blue layer) innerCornerOutput += this._createSelectionPiece(top_1, lineHeight, SelectionsOverlay.SELECTION_CLASS_NAME, visibleRange.left + visibleRange.width, SelectionsOverlay.ROUNDED_PIECE_WIDTH); // Second comes the background (white layer) with inverse border radius var className_2 = SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME; if (endStyle.top === 1 /* INTERN */) { className_2 += ' ' + SelectionsOverlay.SELECTION_TOP_LEFT; } if (endStyle.bottom === 1 /* INTERN */) { className_2 += ' ' + SelectionsOverlay.SELECTION_BOTTOM_LEFT; } innerCornerOutput += this._createSelectionPiece(top_1, lineHeight, className_2, visibleRange.left + visibleRange.width, SelectionsOverlay.ROUNDED_PIECE_WIDTH); } } var className = SelectionsOverlay.SELECTION_CLASS_NAME; if (visibleRangesHaveStyle) { var startStyle = visibleRange.startStyle; var endStyle = visibleRange.endStyle; if (startStyle.top === 0 /* EXTERN */) { className += ' ' + SelectionsOverlay.SELECTION_TOP_LEFT; } if (startStyle.bottom === 0 /* EXTERN */) { className += ' ' + SelectionsOverlay.SELECTION_BOTTOM_LEFT; } if (endStyle.top === 0 /* EXTERN */) { className += ' ' + SelectionsOverlay.SELECTION_TOP_RIGHT; } if (endStyle.bottom === 0 /* EXTERN */) { className += ' ' + SelectionsOverlay.SELECTION_BOTTOM_RIGHT; } } restOfSelectionOutput += this._createSelectionPiece(top_1, lineHeight, className, visibleRange.left, visibleRange.width); } output2[lineIndex][0] += innerCornerOutput; output2[lineIndex][1] += restOfSelectionOutput; } }; SelectionsOverlay.prototype.prepareRender = function (ctx) { // Build HTML for inner corners separate from HTML for the rest of selections, // as the inner corner HTML can interfere with that of other selections. // In final render, make sure to place the inner corner HTML before the rest of selection HTML. See issue #77777. var output = []; var visibleStartLineNumber = ctx.visibleRange.startLineNumber; var visibleEndLineNumber = ctx.visibleRange.endLineNumber; for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) { var lineIndex = lineNumber - visibleStartLineNumber; output[lineIndex] = ['', '']; } var thisFrameVisibleRangesWithStyle = []; for (var i = 0, len = this._selections.length; i < len; i++) { var selection = this._selections[i]; if (selection.isEmpty()) { thisFrameVisibleRangesWithStyle[i] = null; continue; } var visibleRangesWithStyle = this._getVisibleRangesWithStyle(selection, ctx, this._previousFrameVisibleRangesWithStyle[i]); thisFrameVisibleRangesWithStyle[i] = visibleRangesWithStyle; this._actualRenderOneSelection(output, visibleStartLineNumber, this._selections.length > 1, visibleRangesWithStyle); } this._previousFrameVisibleRangesWithStyle = thisFrameVisibleRangesWithStyle; this._renderResult = output.map(function (_a) { var internalCorners = _a[0], restOfSelection = _a[1]; return internalCorners + restOfSelection; }); }; SelectionsOverlay.prototype.render = function (startLineNumber, lineNumber) { if (!this._renderResult) { return ''; } var lineIndex = lineNumber - startLineNumber; if (lineIndex < 0 || lineIndex >= this._renderResult.length) { return ''; } return this._renderResult[lineIndex]; }; SelectionsOverlay.SELECTION_CLASS_NAME = 'selected-text'; SelectionsOverlay.SELECTION_TOP_LEFT = 'top-left-radius'; SelectionsOverlay.SELECTION_BOTTOM_LEFT = 'bottom-left-radius'; SelectionsOverlay.SELECTION_TOP_RIGHT = 'top-right-radius'; SelectionsOverlay.SELECTION_BOTTOM_RIGHT = 'bottom-right-radius'; SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME = 'monaco-editor-background'; SelectionsOverlay.ROUNDED_PIECE_WIDTH = 10; return SelectionsOverlay; }(dynamicViewOverlay_1.DynamicViewOverlay)); exports.SelectionsOverlay = SelectionsOverlay; themeService_1.registerThemingParticipant(function (theme, collector) { var editorSelectionColor = theme.getColor(colorRegistry_1.editorSelectionBackground); if (editorSelectionColor) { collector.addRule(".monaco-editor .focused .selected-text { background-color: " + editorSelectionColor + "; }"); } var editorInactiveSelectionColor = theme.getColor(colorRegistry_1.editorInactiveSelection); if (editorInactiveSelectionColor) { collector.addRule(".monaco-editor .selected-text { background-color: " + editorInactiveSelectionColor + "; }"); } var editorSelectionForegroundColor = theme.getColor(colorRegistry_1.editorSelectionForeground); if (editorSelectionForegroundColor) { collector.addRule(".monaco-editor .view-line span.inline-selected-text { color: " + editorSelectionForegroundColor + "; }"); } }); function abs(n) { return n < 0 ? -n : n; } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[556/*vs/editor/common/services/modelServiceImpl*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,10/*vs/base/common/errors*/,33/*vs/editor/common/config/editorOptions*/,30/*vs/editor/common/model/textModel*/,17/*vs/editor/common/modes*/,118/*vs/editor/common/modes/modesRegistry*/,114/*vs/editor/common/services/textResourceConfigurationService*/,43/*vs/platform/configuration/common/configuration*/,15/*vs/base/common/async*/,26/*vs/base/common/cancellation*/,157/*vs/editor/common/model/tokensStore*/,14/*vs/platform/theme/common/themeService*/,95/*vs/platform/log/common/log*/]), function (require, exports, event_1, lifecycle_1, platform, errors, editorOptions_1, textModel_1, modes_1, modesRegistry_1, textResourceConfigurationService_1, configuration_1, async_1, cancellation_1, tokensStore_1, themeService_1, log_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function MODEL_ID(resource) { return resource.toString(); } var ModelData = /** @class */ (function () { function ModelData(model, onWillDispose, onDidChangeLanguage) { this._modelEventListeners = new lifecycle_1.DisposableStore(); this.model = model; this._languageSelection = null; this._languageSelectionListener = null; this._modelEventListeners.add(model.onWillDispose(function () { return onWillDispose(model); })); this._modelEventListeners.add(model.onDidChangeLanguage(function (e) { return onDidChangeLanguage(model, e); })); } ModelData.prototype._disposeLanguageSelection = function () { if (this._languageSelectionListener) { this._languageSelectionListener.dispose(); this._languageSelectionListener = null; } if (this._languageSelection) { this._languageSelection.dispose(); this._languageSelection = null; } }; ModelData.prototype.dispose = function () { this._modelEventListeners.dispose(); this._disposeLanguageSelection(); }; ModelData.prototype.setLanguage = function (languageSelection) { var _this = this; this._disposeLanguageSelection(); this._languageSelection = languageSelection; this._languageSelectionListener = this._languageSelection.onDidChange(function () { return _this.model.setMode(languageSelection.languageIdentifier); }); this.model.setMode(languageSelection.languageIdentifier); }; return ModelData; }()); var DEFAULT_EOL = (platform.isLinux || platform.isMacintosh) ? 1 /* LF */ : 2 /* CRLF */; var ModelServiceImpl = /** @class */ (function (_super) { __extends(ModelServiceImpl, _super); function ModelServiceImpl(configurationService, resourcePropertiesService, themeService, logService) { var _this = _super.call(this) || this; _this._onModelAdded = _this._register(new event_1.Emitter()); _this.onModelAdded = _this._onModelAdded.event; _this._onModelRemoved = _this._register(new event_1.Emitter()); _this.onModelRemoved = _this._onModelRemoved.event; _this._onModelModeChanged = _this._register(new event_1.Emitter()); _this.onModelModeChanged = _this._onModelModeChanged.event; _this._configurationService = configurationService; _this._resourcePropertiesService = resourcePropertiesService; _this._models = {}; _this._modelCreationOptionsByLanguageAndResource = Object.create(null); _this._configurationServiceSubscription = _this._configurationService.onDidChangeConfiguration(function (e) { return _this._updateModelOptions(); }); _this._updateModelOptions(); _this._register(new SemanticColoringFeature(_this, themeService, configurationService, logService)); return _this; } ModelServiceImpl._readModelOptions = function (config, isForSimpleWidget) { var tabSize = editorOptions_1.EDITOR_MODEL_DEFAULTS.tabSize; if (config.editor && typeof config.editor.tabSize !== 'undefined') { var parsedTabSize = parseInt(config.editor.tabSize, 10); if (!isNaN(parsedTabSize)) { tabSize = parsedTabSize; } if (tabSize < 1) { tabSize = 1; } } var indentSize = tabSize; if (config.editor && typeof config.editor.indentSize !== 'undefined' && config.editor.indentSize !== 'tabSize') { var parsedIndentSize = parseInt(config.editor.indentSize, 10); if (!isNaN(parsedIndentSize)) { indentSize = parsedIndentSize; } if (indentSize < 1) { indentSize = 1; } } var insertSpaces = editorOptions_1.EDITOR_MODEL_DEFAULTS.insertSpaces; if (config.editor && typeof config.editor.insertSpaces !== 'undefined') { insertSpaces = (config.editor.insertSpaces === 'false' ? false : Boolean(config.editor.insertSpaces)); } var newDefaultEOL = DEFAULT_EOL; var eol = config.eol; if (eol === '\r\n') { newDefaultEOL = 2 /* CRLF */; } else if (eol === '\n') { newDefaultEOL = 1 /* LF */; } var trimAutoWhitespace = editorOptions_1.EDITOR_MODEL_DEFAULTS.trimAutoWhitespace; if (config.editor && typeof config.editor.trimAutoWhitespace !== 'undefined') { trimAutoWhitespace = (config.editor.trimAutoWhitespace === 'false' ? false : Boolean(config.editor.trimAutoWhitespace)); } var detectIndentation = editorOptions_1.EDITOR_MODEL_DEFAULTS.detectIndentation; if (config.editor && typeof config.editor.detectIndentation !== 'undefined') { detectIndentation = (config.editor.detectIndentation === 'false' ? false : Boolean(config.editor.detectIndentation)); } var largeFileOptimizations = editorOptions_1.EDITOR_MODEL_DEFAULTS.largeFileOptimizations; if (config.editor && typeof config.editor.largeFileOptimizations !== 'undefined') { largeFileOptimizations = (config.editor.largeFileOptimizations === 'false' ? false : Boolean(config.editor.largeFileOptimizations)); } return { isForSimpleWidget: isForSimpleWidget, tabSize: tabSize, indentSize: indentSize, insertSpaces: insertSpaces, detectIndentation: detectIndentation, defaultEOL: newDefaultEOL, trimAutoWhitespace: trimAutoWhitespace, largeFileOptimizations: largeFileOptimizations }; }; ModelServiceImpl.prototype.getCreationOptions = function (language, resource, isForSimpleWidget) { var creationOptions = this._modelCreationOptionsByLanguageAndResource[language + resource]; if (!creationOptions) { var editor = this._configurationService.getValue('editor', { overrideIdentifier: language, resource: resource }); var eol = this._resourcePropertiesService.getEOL(resource, language); creationOptions = ModelServiceImpl._readModelOptions({ editor: editor, eol: eol }, isForSimpleWidget); this._modelCreationOptionsByLanguageAndResource[language + resource] = creationOptions; } return creationOptions; }; ModelServiceImpl.prototype._updateModelOptions = function () { var oldOptionsByLanguageAndResource = this._modelCreationOptionsByLanguageAndResource; this._modelCreationOptionsByLanguageAndResource = Object.create(null); // Update options on all models var keys = Object.keys(this._models); for (var i = 0, len = keys.length; i < len; i++) { var modelId = keys[i]; var modelData = this._models[modelId]; var language = modelData.model.getLanguageIdentifier().language; var uri = modelData.model.uri; var oldOptions = oldOptionsByLanguageAndResource[language + uri]; var newOptions = this.getCreationOptions(language, uri, modelData.model.isForSimpleWidget); ModelServiceImpl._setModelOptionsForModel(modelData.model, newOptions, oldOptions); } }; ModelServiceImpl._setModelOptionsForModel = function (model, newOptions, currentOptions) { if (currentOptions && currentOptions.defaultEOL !== newOptions.defaultEOL && model.getLineCount() === 1) { model.setEOL(newOptions.defaultEOL === 1 /* LF */ ? 0 /* LF */ : 1 /* CRLF */); } if (currentOptions && (currentOptions.detectIndentation === newOptions.detectIndentation) && (currentOptions.insertSpaces === newOptions.insertSpaces) && (currentOptions.tabSize === newOptions.tabSize) && (currentOptions.indentSize === newOptions.indentSize) && (currentOptions.trimAutoWhitespace === newOptions.trimAutoWhitespace)) { // Same indent opts, no need to touch the model return; } if (newOptions.detectIndentation) { model.detectIndentation(newOptions.insertSpaces, newOptions.tabSize); model.updateOptions({ trimAutoWhitespace: newOptions.trimAutoWhitespace }); } else { model.updateOptions({ insertSpaces: newOptions.insertSpaces, tabSize: newOptions.tabSize, indentSize: newOptions.indentSize, trimAutoWhitespace: newOptions.trimAutoWhitespace }); } }; ModelServiceImpl.prototype.dispose = function () { this._configurationServiceSubscription.dispose(); _super.prototype.dispose.call(this); }; // --- begin IModelService ModelServiceImpl.prototype._createModelData = function (value, languageIdentifier, resource, isForSimpleWidget) { var _this = this; // create & save the model var options = this.getCreationOptions(languageIdentifier.language, resource, isForSimpleWidget); var model = new textModel_1.TextModel(value, options, languageIdentifier, resource); var modelId = MODEL_ID(model.uri); if (this._models[modelId]) { // There already exists a model with this id => this is a programmer error throw new Error('ModelService: Cannot add model because it already exists!'); } var modelData = new ModelData(model, function (model) { return _this._onWillDispose(model); }, function (model, e) { return _this._onDidChangeLanguage(model, e); }); this._models[modelId] = modelData; return modelData; }; ModelServiceImpl.prototype.createModel = function (value, languageSelection, resource, isForSimpleWidget) { if (isForSimpleWidget === void 0) { isForSimpleWidget = false; } var modelData; if (languageSelection) { modelData = this._createModelData(value, languageSelection.languageIdentifier, resource, isForSimpleWidget); this.setMode(modelData.model, languageSelection); } else { modelData = this._createModelData(value, modesRegistry_1.PLAINTEXT_LANGUAGE_IDENTIFIER, resource, isForSimpleWidget); } this._onModelAdded.fire(modelData.model); return modelData.model; }; ModelServiceImpl.prototype.setMode = function (model, languageSelection) { if (!languageSelection) { return; } var modelData = this._models[MODEL_ID(model.uri)]; if (!modelData) { return; } modelData.setLanguage(languageSelection); }; ModelServiceImpl.prototype.getModels = function () { var ret = []; var keys = Object.keys(this._models); for (var i = 0, len = keys.length; i < len; i++) { var modelId = keys[i]; ret.push(this._models[modelId].model); } return ret; }; ModelServiceImpl.prototype.getModel = function (resource) { var modelId = MODEL_ID(resource); var modelData = this._models[modelId]; if (!modelData) { return null; } return modelData.model; }; // --- end IModelService ModelServiceImpl.prototype._onWillDispose = function (model) { var modelId = MODEL_ID(model.uri); var modelData = this._models[modelId]; delete this._models[modelId]; modelData.dispose(); // clean up cache delete this._modelCreationOptionsByLanguageAndResource[model.getLanguageIdentifier().language + model.uri]; this._onModelRemoved.fire(model); }; ModelServiceImpl.prototype._onDidChangeLanguage = function (model, e) { var oldModeId = e.oldLanguage; var newModeId = model.getLanguageIdentifier().language; var oldOptions = this.getCreationOptions(oldModeId, model.uri, model.isForSimpleWidget); var newOptions = this.getCreationOptions(newModeId, model.uri, model.isForSimpleWidget); ModelServiceImpl._setModelOptionsForModel(model, newOptions, oldOptions); this._onModelModeChanged.fire({ model: model, oldModeId: oldModeId }); }; ModelServiceImpl = __decorate([ __param(0, configuration_1.IConfigurationService), __param(1, textResourceConfigurationService_1.ITextResourcePropertiesService), __param(2, themeService_1.IThemeService), __param(3, log_1.ILogService) ], ModelServiceImpl); return ModelServiceImpl; }(lifecycle_1.Disposable)); exports.ModelServiceImpl = ModelServiceImpl; var SemanticColoringFeature = /** @class */ (function (_super) { __extends(SemanticColoringFeature, _super); function SemanticColoringFeature(modelService, themeService, configurationService, logService) { var _this = _super.call(this) || this; _this._configurationService = configurationService; _this._watchers = Object.create(null); _this._semanticStyling = _this._register(new SemanticStyling(themeService, logService)); var isSemanticColoringEnabled = function (model) { var options = configurationService.getValue(SemanticColoringFeature.SETTING_ID, { overrideIdentifier: model.getLanguageIdentifier().language, resource: model.uri }); return options && options.enabled; }; var register = function (model) { _this._watchers[model.uri.toString()] = new ModelSemanticColoring(model, themeService, _this._semanticStyling); }; var deregister = function (model, modelSemanticColoring) { modelSemanticColoring.dispose(); delete _this._watchers[model.uri.toString()]; }; _this._register(modelService.onModelAdded(function (model) { if (isSemanticColoringEnabled(model)) { register(model); } })); _this._register(modelService.onModelRemoved(function (model) { var curr = _this._watchers[model.uri.toString()]; if (curr) { deregister(model, curr); } })); _this._configurationService.onDidChangeConfiguration(function (e) { if (e.affectsConfiguration(SemanticColoringFeature.SETTING_ID)) { for (var _i = 0, _a = modelService.getModels(); _i < _a.length; _i++) { var model = _a[_i]; var curr = _this._watchers[model.uri.toString()]; if (isSemanticColoringEnabled(model)) { if (!curr) { register(model); } } else { if (curr) { deregister(model, curr); } } } } }); return _this; } SemanticColoringFeature.SETTING_ID = 'editor.semanticHighlighting'; return SemanticColoringFeature; }(lifecycle_1.Disposable)); var SemanticStyling = /** @class */ (function (_super) { __extends(SemanticStyling, _super); function SemanticStyling(_themeService, _logService) { var _this = _super.call(this) || this; _this._themeService = _themeService; _this._logService = _logService; _this._caches = new WeakMap(); if (_this._themeService) { // workaround for tests which use undefined... :/ _this._register(_this._themeService.onThemeChange(function () { _this._caches = new WeakMap(); })); } return _this; } SemanticStyling.prototype.get = function (provider) { if (!this._caches.has(provider)) { this._caches.set(provider, new SemanticColoringProviderStyling(provider.getLegend(), this._themeService, this._logService)); } return this._caches.get(provider); }; return SemanticStyling; }(lifecycle_1.Disposable)); var HashTableEntry = /** @class */ (function () { function HashTableEntry(tokenTypeIndex, tokenModifierSet, metadata) { this.tokenTypeIndex = tokenTypeIndex; this.tokenModifierSet = tokenModifierSet; this.metadata = metadata; this.next = null; } return HashTableEntry; }()); var HashTable = /** @class */ (function () { function HashTable() { this._elementsCount = 0; this._currentLengthIndex = 0; this._currentLength = HashTable._SIZES[this._currentLengthIndex]; this._growCount = Math.round(this._currentLengthIndex + 1 < HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0); this._elements = []; HashTable._nullOutEntries(this._elements, this._currentLength); } HashTable._nullOutEntries = function (entries, length) { for (var i = 0; i < length; i++) { entries[i] = null; } }; HashTable.prototype._hashFunc = function (tokenTypeIndex, tokenModifierSet) { return ((((tokenTypeIndex << 5) - tokenTypeIndex) + tokenModifierSet) | 0) % this._currentLength; // tokenTypeIndex * 31 + tokenModifierSet, keep as int32 }; HashTable.prototype.get = function (tokenTypeIndex, tokenModifierSet) { var hash = this._hashFunc(tokenTypeIndex, tokenModifierSet); var p = this._elements[hash]; while (p) { if (p.tokenTypeIndex === tokenTypeIndex && p.tokenModifierSet === tokenModifierSet) { return p; } p = p.next; } return null; }; HashTable.prototype.add = function (tokenTypeIndex, tokenModifierSet, metadata) { this._elementsCount++; if (this._growCount !== 0 && this._elementsCount >= this._growCount) { // expand! var oldElements = this._elements; this._currentLengthIndex++; this._currentLength = HashTable._SIZES[this._currentLengthIndex]; this._growCount = Math.round(this._currentLengthIndex + 1 < HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0); this._elements = []; HashTable._nullOutEntries(this._elements, this._currentLength); for (var _i = 0, oldElements_1 = oldElements; _i < oldElements_1.length; _i++) { var first = oldElements_1[_i]; var p = first; while (p) { var oldNext = p.next; p.next = null; this._add(p); p = oldNext; } } } this._add(new HashTableEntry(tokenTypeIndex, tokenModifierSet, metadata)); }; HashTable.prototype._add = function (element) { var hash = this._hashFunc(element.tokenTypeIndex, element.tokenModifierSet); element.next = this._elements[hash]; this._elements[hash] = element; }; HashTable._SIZES = [3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143]; return HashTable; }()); var SemanticColoringProviderStyling = /** @class */ (function () { function SemanticColoringProviderStyling(_legend, _themeService, _logService) { this._legend = _legend; this._themeService = _themeService; this._logService = _logService; this._hashTable = new HashTable(); } SemanticColoringProviderStyling.prototype.getMetadata = function (tokenTypeIndex, tokenModifierSet) { var entry = this._hashTable.get(tokenTypeIndex, tokenModifierSet); var metadata; if (entry) { metadata = entry.metadata; } else { var tokenType = this._legend.tokenTypes[tokenTypeIndex]; var tokenModifiers = []; var modifierSet = tokenModifierSet; for (var modifierIndex = 0; modifierSet > 0 && modifierIndex < this._legend.tokenModifiers.length; modifierIndex++) { if (modifierSet & 1) { tokenModifiers.push(this._legend.tokenModifiers[modifierIndex]); } modifierSet = modifierSet >> 1; } var tokenStyle = this._themeService.getTheme().getTokenStyleMetadata(tokenType, tokenModifiers); if (typeof tokenStyle === 'undefined') { metadata = 2147483647 /* NO_STYLING */; } else { metadata = 0; if (typeof tokenStyle.italic !== 'undefined') { var italicBit = (tokenStyle.italic ? 1 /* Italic */ : 0) << 11 /* FONT_STYLE_OFFSET */; metadata |= italicBit | 1 /* SEMANTIC_USE_ITALIC */; } if (typeof tokenStyle.bold !== 'undefined') { var boldBit = (tokenStyle.bold ? 2 /* Bold */ : 0) << 11 /* FONT_STYLE_OFFSET */; metadata |= boldBit | 2 /* SEMANTIC_USE_BOLD */; } if (typeof tokenStyle.underline !== 'undefined') { var underlineBit = (tokenStyle.underline ? 4 /* Underline */ : 0) << 11 /* FONT_STYLE_OFFSET */; metadata |= underlineBit | 4 /* SEMANTIC_USE_UNDERLINE */; } if (tokenStyle.foreground) { var foregroundBits = (tokenStyle.foreground) << 14 /* FOREGROUND_OFFSET */; metadata |= foregroundBits | 8 /* SEMANTIC_USE_FOREGROUND */; } if (metadata === 0) { // Nothing! metadata = 2147483647 /* NO_STYLING */; } } this._hashTable.add(tokenTypeIndex, tokenModifierSet, metadata); } if (this._logService.getLevel() === log_1.LogLevel.Trace) { var type = this._legend.tokenTypes[tokenTypeIndex]; var modifiers = tokenModifierSet ? ' ' + this._legend.tokenModifiers.filter(function (_, i) { return tokenModifierSet & (1 << i); }).join(' ') : ''; this._logService.trace("tokenStyleMetadata " + (entry ? '[CACHED] ' : '') + type + modifiers + ": foreground " + modes_1.TokenMetadata.getForeground(metadata) + ", fontStyle " + modes_1.TokenMetadata.getFontStyle(metadata).toString(2)); } return metadata; }; return SemanticColoringProviderStyling; }()); var SemanticTokensResponse = /** @class */ (function () { function SemanticTokensResponse(_provider, resultId, data) { this._provider = _provider; this.resultId = resultId; this.data = data; } SemanticTokensResponse.prototype.dispose = function () { this._provider.releaseDocumentSemanticTokens(this.resultId); }; return SemanticTokensResponse; }()); var ModelSemanticColoring = /** @class */ (function (_super) { __extends(ModelSemanticColoring, _super); function ModelSemanticColoring(model, themeService, stylingProvider) { var _this = _super.call(this) || this; _this._isDisposed = false; _this._model = model; _this._semanticStyling = stylingProvider; _this._fetchSemanticTokens = _this._register(new async_1.RunOnceScheduler(function () { return _this._fetchSemanticTokensNow(); }, 300)); _this._currentResponse = null; _this._currentRequestCancellationTokenSource = null; _this._register(_this._model.onDidChangeContent(function (e) { if (!_this._fetchSemanticTokens.isScheduled()) { _this._fetchSemanticTokens.schedule(); } })); _this._register(modes_1.DocumentSemanticTokensProviderRegistry.onDidChange(function (e) { return _this._fetchSemanticTokens.schedule(); })); if (themeService) { // workaround for tests which use undefined... :/ _this._register(themeService.onThemeChange(function (_) { // clear out existing tokens _this._setSemanticTokens(null, null, null, []); _this._fetchSemanticTokens.schedule(); })); } _this._fetchSemanticTokens.schedule(0); return _this; } ModelSemanticColoring.prototype.dispose = function () { if (this._currentResponse) { this._currentResponse.dispose(); this._currentResponse = null; } if (this._currentRequestCancellationTokenSource) { this._currentRequestCancellationTokenSource.cancel(); this._currentRequestCancellationTokenSource = null; } this._setSemanticTokens(null, null, null, []); this._isDisposed = true; _super.prototype.dispose.call(this); }; ModelSemanticColoring.prototype._fetchSemanticTokensNow = function () { var _this = this; if (this._currentRequestCancellationTokenSource) { // there is already a request running, let it finish... return; } var provider = this._getSemanticColoringProvider(); if (!provider) { return; } this._currentRequestCancellationTokenSource = new cancellation_1.CancellationTokenSource(); var pendingChanges = []; var contentChangeListener = this._model.onDidChangeContent(function (e) { pendingChanges.push(e); }); var styling = this._semanticStyling.get(provider); var lastResultId = this._currentResponse ? this._currentResponse.resultId || null : null; var request = Promise.resolve(provider.provideDocumentSemanticTokens(this._model, lastResultId, this._currentRequestCancellationTokenSource.token)); request.then(function (res) { _this._currentRequestCancellationTokenSource = null; contentChangeListener.dispose(); _this._setSemanticTokens(provider, res || null, styling, pendingChanges); }, function (err) { if (!err || typeof err.message !== 'string' || err.message.indexOf('busy') === -1) { errors.onUnexpectedError(err); } // Semantic tokens eats up all errors and considers errors to mean that the result is temporarily not available // The API does not have a special error kind to express this... _this._currentRequestCancellationTokenSource = null; contentChangeListener.dispose(); if (pendingChanges.length > 0) { // More changes occurred while the request was running if (!_this._fetchSemanticTokens.isScheduled()) { _this._fetchSemanticTokens.schedule(); } } }); }; ModelSemanticColoring._isSemanticTokens = function (v) { return v && !!(v.data); }; ModelSemanticColoring._isSemanticTokensEdits = function (v) { return v && Array.isArray(v.edits); }; ModelSemanticColoring._copy = function (src, srcOffset, dest, destOffset, length) { for (var i = 0; i < length; i++) { dest[destOffset + i] = src[srcOffset + i]; } }; ModelSemanticColoring.prototype._setSemanticTokens = function (provider, tokens, styling, pendingChanges) { var currentResponse = this._currentResponse; if (this._currentResponse) { this._currentResponse.dispose(); this._currentResponse = null; } if (this._isDisposed) { // disposed! if (provider && tokens) { provider.releaseDocumentSemanticTokens(tokens.resultId); } return; } if (!provider || !tokens || !styling) { this._model.setSemanticTokens(null); return; } if (ModelSemanticColoring._isSemanticTokensEdits(tokens)) { if (!currentResponse) { // not possible! this._model.setSemanticTokens(null); return; } if (tokens.edits.length === 0) { // nothing to do! tokens = { resultId: tokens.resultId, data: currentResponse.data }; } else { var deltaLength = 0; for (var _i = 0, _a = tokens.edits; _i < _a.length; _i++) { var edit = _a[_i]; deltaLength += (edit.data ? edit.data.length : 0) - edit.deleteCount; } var srcData = currentResponse.data; var destData = new Uint32Array(srcData.length + deltaLength); var srcLastStart = srcData.length; var destLastStart = destData.length; for (var i = tokens.edits.length - 1; i >= 0; i--) { var edit = tokens.edits[i]; var copyCount = srcLastStart - (edit.start + edit.deleteCount); if (copyCount > 0) { ModelSemanticColoring._copy(srcData, srcLastStart - copyCount, destData, destLastStart - copyCount, copyCount); destLastStart -= copyCount; } if (edit.data) { ModelSemanticColoring._copy(edit.data, 0, destData, destLastStart - edit.data.length, edit.data.length); destLastStart -= edit.data.length; } srcLastStart = edit.start; } if (srcLastStart > 0) { ModelSemanticColoring._copy(srcData, 0, destData, 0, srcLastStart); } tokens = { resultId: tokens.resultId, data: destData }; } } if (ModelSemanticColoring._isSemanticTokens(tokens)) { this._currentResponse = new SemanticTokensResponse(provider, tokens.resultId, tokens.data); var srcData = tokens.data; var tokenCount = (tokens.data.length / 5) | 0; var tokensPerArea = Math.max(Math.ceil(tokenCount / 1024 /* DesiredMaxAreas */), 400 /* DesiredTokensPerArea */); var result = []; var tokenIndex = 0; var lastLineNumber = 1; var lastStartCharacter = 0; while (tokenIndex < tokenCount) { var tokenStartIndex = tokenIndex; var tokenEndIndex = Math.min(tokenStartIndex + tokensPerArea, tokenCount); // Keep tokens on the same line in the same area... if (tokenEndIndex < tokenCount) { var smallTokenEndIndex = tokenEndIndex; while (smallTokenEndIndex - 1 > tokenStartIndex && srcData[5 * smallTokenEndIndex] === 0) { smallTokenEndIndex--; } if (smallTokenEndIndex - 1 === tokenStartIndex) { // there are so many tokens on this line that our area would be empty, we must now go right var bigTokenEndIndex = tokenEndIndex; while (bigTokenEndIndex + 1 < tokenCount && srcData[5 * bigTokenEndIndex] === 0) { bigTokenEndIndex++; } tokenEndIndex = bigTokenEndIndex; } else { tokenEndIndex = smallTokenEndIndex; } } var destData = new Uint32Array((tokenEndIndex - tokenStartIndex) * 4); var destOffset = 0; var areaLine = 0; while (tokenIndex < tokenEndIndex) { var srcOffset = 5 * tokenIndex; var deltaLine = srcData[srcOffset]; var deltaCharacter = srcData[srcOffset + 1]; var lineNumber = lastLineNumber + deltaLine; var startCharacter = (deltaLine === 0 ? lastStartCharacter + deltaCharacter : deltaCharacter); var length_1 = srcData[srcOffset + 2]; var tokenTypeIndex = srcData[srcOffset + 3]; var tokenModifierSet = srcData[srcOffset + 4]; var metadata = styling.getMetadata(tokenTypeIndex, tokenModifierSet); if (metadata !== 2147483647 /* NO_STYLING */) { if (areaLine === 0) { areaLine = lineNumber; } destData[destOffset] = lineNumber - areaLine; destData[destOffset + 1] = startCharacter; destData[destOffset + 2] = startCharacter + length_1; destData[destOffset + 3] = metadata; destOffset += 4; } lastLineNumber = lineNumber; lastStartCharacter = startCharacter; tokenIndex++; } if (destOffset !== destData.length) { destData = destData.subarray(0, destOffset); } var tokens_1 = new tokensStore_1.MultilineTokens2(areaLine, new tokensStore_1.SparseEncodedTokens(destData)); result.push(tokens_1); } // Adjust incoming semantic tokens if (pendingChanges.length > 0) { // More changes occurred while the request was running // We need to: // 1. Adjust incoming semantic tokens // 2. Request them again for (var _b = 0, pendingChanges_1 = pendingChanges; _b < pendingChanges_1.length; _b++) { var change = pendingChanges_1[_b]; for (var _c = 0, result_1 = result; _c < result_1.length; _c++) { var area = result_1[_c]; for (var _d = 0, _e = change.changes; _d < _e.length; _d++) { var singleChange = _e[_d]; area.applyEdit(singleChange.range, singleChange.text); } } } if (!this._fetchSemanticTokens.isScheduled()) { this._fetchSemanticTokens.schedule(); } } this._model.setSemanticTokens(result); return; } this._model.setSemanticTokens(null); }; ModelSemanticColoring.prototype._getSemanticColoringProvider = function () { var result = modes_1.DocumentSemanticTokensProviderRegistry.ordered(this._model); return (result.length > 0 ? result[0] : null); }; return ModelSemanticColoring; }(lifecycle_1.Disposable)); }); /*--------------------------------------------------------------------------------------------- * 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/editor/common/view/editorColorRegistry*/], __M([0/*require*/,1/*exports*/,427/*vs/nls!vs/editor/common/view/editorColorRegistry*/,27/*vs/base/common/color*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, nls, color_1, colorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Definition of the editor colors */ exports.editorLineHighlight = colorRegistry_1.registerColor('editor.lineHighlightBackground', { dark: null, light: null, hc: null }, nls.localize(0, null)); exports.editorLineHighlightBorder = colorRegistry_1.registerColor('editor.lineHighlightBorder', { dark: '#282828', light: '#eeeeee', hc: '#f38518' }, nls.localize(1, null)); exports.editorRangeHighlight = colorRegistry_1.registerColor('editor.rangeHighlightBackground', { dark: '#ffffff0b', light: '#fdff0033', hc: null }, nls.localize(2, null), true); exports.editorRangeHighlightBorder = colorRegistry_1.registerColor('editor.rangeHighlightBorder', { dark: null, light: null, hc: colorRegistry_1.activeContrastBorder }, nls.localize(3, null), true); exports.editorSymbolHighlight = colorRegistry_1.registerColor('editor.symbolHighlightBackground', { dark: colorRegistry_1.editorFindMatchHighlight, light: colorRegistry_1.editorFindMatchHighlight, hc: null }, nls.localize(4, null), true); exports.editorSymbolHighlightBorder = colorRegistry_1.registerColor('editor.symbolHighlightBorder', { dark: null, light: null, hc: colorRegistry_1.activeContrastBorder }, nls.localize(5, null), true); exports.editorCursorForeground = colorRegistry_1.registerColor('editorCursor.foreground', { dark: '#AEAFAD', light: color_1.Color.black, hc: color_1.Color.white }, nls.localize(6, null)); exports.editorCursorBackground = colorRegistry_1.registerColor('editorCursor.background', null, nls.localize(7, null)); exports.editorWhitespaces = colorRegistry_1.registerColor('editorWhitespace.foreground', { dark: '#e3e4e229', light: '#33333333', hc: '#e3e4e229' }, nls.localize(8, null)); exports.editorIndentGuides = colorRegistry_1.registerColor('editorIndentGuide.background', { dark: exports.editorWhitespaces, light: exports.editorWhitespaces, hc: exports.editorWhitespaces }, nls.localize(9, null)); exports.editorActiveIndentGuides = colorRegistry_1.registerColor('editorIndentGuide.activeBackground', { dark: exports.editorWhitespaces, light: exports.editorWhitespaces, hc: exports.editorWhitespaces }, nls.localize(10, null)); exports.editorLineNumbers = colorRegistry_1.registerColor('editorLineNumber.foreground', { dark: '#858585', light: '#237893', hc: color_1.Color.white }, nls.localize(11, null)); var deprecatedEditorActiveLineNumber = colorRegistry_1.registerColor('editorActiveLineNumber.foreground', { dark: '#c6c6c6', light: '#0B216F', hc: colorRegistry_1.activeContrastBorder }, nls.localize(12, null), false, nls.localize(13, null)); exports.editorActiveLineNumber = colorRegistry_1.registerColor('editorLineNumber.activeForeground', { dark: deprecatedEditorActiveLineNumber, light: deprecatedEditorActiveLineNumber, hc: deprecatedEditorActiveLineNumber }, nls.localize(14, null)); exports.editorRuler = colorRegistry_1.registerColor('editorRuler.foreground', { dark: '#5A5A5A', light: color_1.Color.lightgrey, hc: color_1.Color.white }, nls.localize(15, null)); exports.editorCodeLensForeground = colorRegistry_1.registerColor('editorCodeLens.foreground', { dark: '#999999', light: '#999999', hc: '#999999' }, nls.localize(16, null)); exports.editorBracketMatchBackground = colorRegistry_1.registerColor('editorBracketMatch.background', { dark: '#0064001a', light: '#0064001a', hc: '#0064001a' }, nls.localize(17, null)); exports.editorBracketMatchBorder = colorRegistry_1.registerColor('editorBracketMatch.border', { dark: '#888', light: '#B9B9B9', hc: colorRegistry_1.contrastBorder }, nls.localize(18, null)); exports.editorOverviewRulerBorder = colorRegistry_1.registerColor('editorOverviewRuler.border', { dark: '#7f7f7f4d', light: '#7f7f7f4d', hc: '#7f7f7f4d' }, nls.localize(19, null)); exports.editorGutter = colorRegistry_1.registerColor('editorGutter.background', { dark: colorRegistry_1.editorBackground, light: colorRegistry_1.editorBackground, hc: colorRegistry_1.editorBackground }, nls.localize(20, null)); exports.editorUnnecessaryCodeBorder = colorRegistry_1.registerColor('editorUnnecessaryCode.border', { dark: null, light: null, hc: color_1.Color.fromHex('#fff').transparent(0.8) }, nls.localize(21, null)); exports.editorUnnecessaryCodeOpacity = colorRegistry_1.registerColor('editorUnnecessaryCode.opacity', { dark: color_1.Color.fromHex('#000a'), light: color_1.Color.fromHex('#0007'), hc: null }, nls.localize(22, null)); exports.overviewRulerError = colorRegistry_1.registerColor('editorOverviewRuler.errorForeground', { dark: new color_1.Color(new color_1.RGBA(255, 18, 18, 0.7)), light: new color_1.Color(new color_1.RGBA(255, 18, 18, 0.7)), hc: new color_1.Color(new color_1.RGBA(255, 50, 50, 1)) }, nls.localize(23, null)); exports.overviewRulerWarning = colorRegistry_1.registerColor('editorOverviewRuler.warningForeground', { dark: colorRegistry_1.editorWarningForeground, light: colorRegistry_1.editorWarningForeground, hc: colorRegistry_1.editorWarningBorder }, nls.localize(24, null)); exports.overviewRulerInfo = colorRegistry_1.registerColor('editorOverviewRuler.infoForeground', { dark: colorRegistry_1.editorInfoForeground, light: colorRegistry_1.editorInfoForeground, hc: colorRegistry_1.editorInfoBorder }, nls.localize(25, null)); // contains all color rules that used to defined in editor/browser/widget/editor.css themeService_1.registerThemingParticipant(function (theme, collector) { var background = theme.getColor(colorRegistry_1.editorBackground); if (background) { collector.addRule(".monaco-editor, .monaco-editor-background, .monaco-editor .inputarea.ime-input { background-color: " + background + "; }"); } var foreground = theme.getColor(colorRegistry_1.editorForeground); if (foreground) { collector.addRule(".monaco-editor, .monaco-editor .inputarea.ime-input { color: " + foreground + "; }"); } var gutter = theme.getColor(exports.editorGutter); if (gutter) { collector.addRule(".monaco-editor .margin { background-color: " + gutter + "; }"); } var rangeHighlight = theme.getColor(exports.editorRangeHighlight); if (rangeHighlight) { collector.addRule(".monaco-editor .rangeHighlight { background-color: " + rangeHighlight + "; }"); } var rangeHighlightBorder = theme.getColor(exports.editorRangeHighlightBorder); if (rangeHighlightBorder) { collector.addRule(".monaco-editor .rangeHighlight { border: 1px " + (theme.type === 'hc' ? 'dotted' : 'solid') + " " + rangeHighlightBorder + "; }"); } var symbolHighlight = theme.getColor(exports.editorSymbolHighlight); if (symbolHighlight) { collector.addRule(".monaco-editor .symbolHighlight { background-color: " + symbolHighlight + "; }"); } var symbolHighlightBorder = theme.getColor(exports.editorSymbolHighlightBorder); if (symbolHighlightBorder) { collector.addRule(".monaco-editor .symbolHighlight { border: 1px " + (theme.type === 'hc' ? 'dotted' : 'solid') + " " + symbolHighlightBorder + "; }"); } var invisibles = theme.getColor(exports.editorWhitespaces); if (invisibles) { collector.addRule(".vs-whitespace { color: " + invisibles + " !important; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[557/*vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/], __M([0/*require*/,1/*exports*/,82/*vs/editor/browser/view/dynamicViewOverlay*/,44/*vs/editor/common/view/editorColorRegistry*/,19/*vs/base/common/arrays*/,14/*vs/platform/theme/common/themeService*/,285/*vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/]), function (require, exports, dynamicViewOverlay_1, editorColorRegistry_1, arrays, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var isRenderedUsingBorder = true; var AbstractLineHighlightOverlay = /** @class */ (function (_super) { __extends(AbstractLineHighlightOverlay, _super); function AbstractLineHighlightOverlay(context) { var _this = _super.call(this) || this; _this._context = context; var options = _this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); _this._lineHeight = options.get(49 /* lineHeight */); _this._renderLineHighlight = options.get(72 /* renderLineHighlight */); _this._contentLeft = layoutInfo.contentLeft; _this._contentWidth = layoutInfo.contentWidth; _this._selectionIsEmpty = true; _this._cursorLineNumbers = []; _this._selections = []; _this._renderData = null; _this._context.addEventHandler(_this); return _this; } AbstractLineHighlightOverlay.prototype.dispose = function () { this._context.removeEventHandler(this); _super.prototype.dispose.call(this); }; AbstractLineHighlightOverlay.prototype._readFromSelections = function () { var hasChanged = false; // Only render the first selection when using border var renderSelections = isRenderedUsingBorder ? this._selections.slice(0, 1) : this._selections; var cursorsLineNumbers = renderSelections.map(function (s) { return s.positionLineNumber; }); cursorsLineNumbers.sort(function (a, b) { return a - b; }); if (!arrays.equals(this._cursorLineNumbers, cursorsLineNumbers)) { this._cursorLineNumbers = cursorsLineNumbers; hasChanged = true; } var selectionIsEmpty = renderSelections.every(function (s) { return s.isEmpty(); }); if (this._selectionIsEmpty !== selectionIsEmpty) { this._selectionIsEmpty = selectionIsEmpty; hasChanged = true; } return hasChanged; }; // --- begin event handlers AbstractLineHighlightOverlay.prototype.onThemeChanged = function (e) { return this._readFromSelections(); }; AbstractLineHighlightOverlay.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); this._lineHeight = options.get(49 /* lineHeight */); this._renderLineHighlight = options.get(72 /* renderLineHighlight */); this._contentLeft = layoutInfo.contentLeft; this._contentWidth = layoutInfo.contentWidth; return true; }; AbstractLineHighlightOverlay.prototype.onCursorStateChanged = function (e) { this._selections = e.selections; return this._readFromSelections(); }; AbstractLineHighlightOverlay.prototype.onFlushed = function (e) { return true; }; AbstractLineHighlightOverlay.prototype.onLinesDeleted = function (e) { return true; }; AbstractLineHighlightOverlay.prototype.onLinesInserted = function (e) { return true; }; AbstractLineHighlightOverlay.prototype.onScrollChanged = function (e) { return e.scrollWidthChanged || e.scrollTopChanged; }; AbstractLineHighlightOverlay.prototype.onZonesChanged = function (e) { return true; }; // --- end event handlers AbstractLineHighlightOverlay.prototype.prepareRender = function (ctx) { if (!this._shouldRenderThis()) { this._renderData = null; return; } var renderedLine = this._renderOne(ctx); var visibleStartLineNumber = ctx.visibleRange.startLineNumber; var visibleEndLineNumber = ctx.visibleRange.endLineNumber; var len = this._cursorLineNumbers.length; var index = 0; var renderData = []; for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) { var lineIndex = lineNumber - visibleStartLineNumber; while (index < len && this._cursorLineNumbers[index] < lineNumber) { index++; } if (index < len && this._cursorLineNumbers[index] === lineNumber) { renderData[lineIndex] = renderedLine; } else { renderData[lineIndex] = ''; } } this._renderData = renderData; }; AbstractLineHighlightOverlay.prototype.render = function (startLineNumber, lineNumber) { if (!this._renderData) { return ''; } var lineIndex = lineNumber - startLineNumber; if (lineIndex >= this._renderData.length) { return ''; } return this._renderData[lineIndex]; }; return AbstractLineHighlightOverlay; }(dynamicViewOverlay_1.DynamicViewOverlay)); exports.AbstractLineHighlightOverlay = AbstractLineHighlightOverlay; var CurrentLineHighlightOverlay = /** @class */ (function (_super) { __extends(CurrentLineHighlightOverlay, _super); function CurrentLineHighlightOverlay() { return _super !== null && _super.apply(this, arguments) || this; } CurrentLineHighlightOverlay.prototype._renderOne = function (ctx) { var className = 'current-line' + (this._shouldRenderOther() ? ' current-line-both' : ''); return "
    "; }; CurrentLineHighlightOverlay.prototype._shouldRenderThis = function () { return ((this._renderLineHighlight === 'line' || this._renderLineHighlight === 'all') && this._selectionIsEmpty); }; CurrentLineHighlightOverlay.prototype._shouldRenderOther = function () { return ((this._renderLineHighlight === 'gutter' || this._renderLineHighlight === 'all')); }; return CurrentLineHighlightOverlay; }(AbstractLineHighlightOverlay)); exports.CurrentLineHighlightOverlay = CurrentLineHighlightOverlay; var CurrentLineMarginHighlightOverlay = /** @class */ (function (_super) { __extends(CurrentLineMarginHighlightOverlay, _super); function CurrentLineMarginHighlightOverlay() { return _super !== null && _super.apply(this, arguments) || this; } CurrentLineMarginHighlightOverlay.prototype._renderOne = function (ctx) { var className = 'current-line current-line-margin' + (this._shouldRenderOther() ? ' current-line-margin-both' : ''); return "
    "; }; CurrentLineMarginHighlightOverlay.prototype._shouldRenderThis = function () { return ((this._renderLineHighlight === 'gutter' || this._renderLineHighlight === 'all')); }; CurrentLineMarginHighlightOverlay.prototype._shouldRenderOther = function () { return ((this._renderLineHighlight === 'line' || this._renderLineHighlight === 'all') && this._selectionIsEmpty); }; return CurrentLineMarginHighlightOverlay; }(AbstractLineHighlightOverlay)); exports.CurrentLineMarginHighlightOverlay = CurrentLineMarginHighlightOverlay; themeService_1.registerThemingParticipant(function (theme, collector) { isRenderedUsingBorder = false; var lineHighlight = theme.getColor(editorColorRegistry_1.editorLineHighlight); if (lineHighlight) { collector.addRule(".monaco-editor .view-overlays .current-line { background-color: " + lineHighlight + "; }"); collector.addRule(".monaco-editor .margin-view-overlays .current-line-margin { background-color: " + lineHighlight + "; border: none; }"); } if (!lineHighlight || lineHighlight.isTransparent() || theme.defines(editorColorRegistry_1.editorLineHighlightBorder)) { var lineHighlightBorder = theme.getColor(editorColorRegistry_1.editorLineHighlightBorder); if (lineHighlightBorder) { isRenderedUsingBorder = true; collector.addRule(".monaco-editor .view-overlays .current-line { border: 2px solid " + lineHighlightBorder + "; }"); collector.addRule(".monaco-editor .margin-view-overlays .current-line-margin { border: 2px solid " + lineHighlightBorder + "; }"); if (theme.type === 'hc') { collector.addRule(".monaco-editor .view-overlays .current-line { border-width: 1px; }"); collector.addRule(".monaco-editor .margin-view-overlays .current-line-margin { border-width: 1px; }"); } } } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[558/*vs/editor/browser/viewParts/indentGuides/indentGuides*/], __M([0/*require*/,1/*exports*/,82/*vs/editor/browser/view/dynamicViewOverlay*/,13/*vs/editor/common/core/position*/,44/*vs/editor/common/view/editorColorRegistry*/,14/*vs/platform/theme/common/themeService*/,288/*vs/css!vs/editor/browser/viewParts/indentGuides/indentGuides*/]), function (require, exports, dynamicViewOverlay_1, position_1, editorColorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var IndentGuidesOverlay = /** @class */ (function (_super) { __extends(IndentGuidesOverlay, _super); function IndentGuidesOverlay(context) { var _this = _super.call(this) || this; _this._context = context; _this._primaryLineNumber = 0; var options = _this._context.configuration.options; var wrappingInfo = options.get(108 /* wrappingInfo */); var fontInfo = options.get(34 /* fontInfo */); _this._lineHeight = options.get(49 /* lineHeight */); _this._spaceWidth = fontInfo.spaceWidth; _this._enabled = options.get(70 /* renderIndentGuides */); _this._activeIndentEnabled = options.get(43 /* highlightActiveIndentGuide */); _this._maxIndentLeft = wrappingInfo.wrappingColumn === -1 ? -1 : (wrappingInfo.wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth); _this._renderResult = null; _this._context.addEventHandler(_this); return _this; } IndentGuidesOverlay.prototype.dispose = function () { this._context.removeEventHandler(this); this._renderResult = null; _super.prototype.dispose.call(this); }; // --- begin event handlers IndentGuidesOverlay.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; var wrappingInfo = options.get(108 /* wrappingInfo */); var fontInfo = options.get(34 /* fontInfo */); this._lineHeight = options.get(49 /* lineHeight */); this._spaceWidth = fontInfo.spaceWidth; this._enabled = options.get(70 /* renderIndentGuides */); this._activeIndentEnabled = options.get(43 /* highlightActiveIndentGuide */); this._maxIndentLeft = wrappingInfo.wrappingColumn === -1 ? -1 : (wrappingInfo.wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth); return true; }; IndentGuidesOverlay.prototype.onCursorStateChanged = function (e) { var selection = e.selections[0]; var newPrimaryLineNumber = selection.isEmpty() ? selection.positionLineNumber : 0; if (this._primaryLineNumber !== newPrimaryLineNumber) { this._primaryLineNumber = newPrimaryLineNumber; return true; } return false; }; IndentGuidesOverlay.prototype.onDecorationsChanged = function (e) { // true for inline decorations return true; }; IndentGuidesOverlay.prototype.onFlushed = function (e) { return true; }; IndentGuidesOverlay.prototype.onLinesChanged = function (e) { return true; }; IndentGuidesOverlay.prototype.onLinesDeleted = function (e) { return true; }; IndentGuidesOverlay.prototype.onLinesInserted = function (e) { return true; }; IndentGuidesOverlay.prototype.onScrollChanged = function (e) { return e.scrollTopChanged; // || e.scrollWidthChanged; }; IndentGuidesOverlay.prototype.onZonesChanged = function (e) { return true; }; IndentGuidesOverlay.prototype.onLanguageConfigurationChanged = function (e) { return true; }; // --- end event handlers IndentGuidesOverlay.prototype.prepareRender = function (ctx) { if (!this._enabled) { this._renderResult = null; return; } var visibleStartLineNumber = ctx.visibleRange.startLineNumber; var visibleEndLineNumber = ctx.visibleRange.endLineNumber; var indentSize = this._context.model.getOptions().indentSize; var indentWidth = indentSize * this._spaceWidth; var scrollWidth = ctx.scrollWidth; var lineHeight = this._lineHeight; var indents = this._context.model.getLinesIndentGuides(visibleStartLineNumber, visibleEndLineNumber); var activeIndentStartLineNumber = 0; var activeIndentEndLineNumber = 0; var activeIndentLevel = 0; if (this._activeIndentEnabled && this._primaryLineNumber) { var activeIndentInfo = this._context.model.getActiveIndentGuide(this._primaryLineNumber, visibleStartLineNumber, visibleEndLineNumber); activeIndentStartLineNumber = activeIndentInfo.startLineNumber; activeIndentEndLineNumber = activeIndentInfo.endLineNumber; activeIndentLevel = activeIndentInfo.indent; } var output = []; for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) { var containsActiveIndentGuide = (activeIndentStartLineNumber <= lineNumber && lineNumber <= activeIndentEndLineNumber); var lineIndex = lineNumber - visibleStartLineNumber; var indent = indents[lineIndex]; var result = ''; if (indent >= 1) { var leftMostVisiblePosition = ctx.visibleRangeForPosition(new position_1.Position(lineNumber, 1)); var left = leftMostVisiblePosition ? leftMostVisiblePosition.left : 0; for (var i = 1; i <= indent; i++) { var className = (containsActiveIndentGuide && i === activeIndentLevel ? 'cigra' : 'cigr'); result += "
    "; left += indentWidth; if (left > scrollWidth || (this._maxIndentLeft > 0 && left > this._maxIndentLeft)) { break; } } } output[lineIndex] = result; } this._renderResult = output; }; IndentGuidesOverlay.prototype.render = function (startLineNumber, lineNumber) { if (!this._renderResult) { return ''; } var lineIndex = lineNumber - startLineNumber; if (lineIndex < 0 || lineIndex >= this._renderResult.length) { return ''; } return this._renderResult[lineIndex]; }; return IndentGuidesOverlay; }(dynamicViewOverlay_1.DynamicViewOverlay)); exports.IndentGuidesOverlay = IndentGuidesOverlay; themeService_1.registerThemingParticipant(function (theme, collector) { var editorIndentGuidesColor = theme.getColor(editorColorRegistry_1.editorIndentGuides); if (editorIndentGuidesColor) { collector.addRule(".monaco-editor .lines-content .cigr { box-shadow: 1px 0 0 0 " + editorIndentGuidesColor + " inset; }"); } var editorActiveIndentGuidesColor = theme.getColor(editorColorRegistry_1.editorActiveIndentGuides) || editorIndentGuidesColor; if (editorActiveIndentGuidesColor) { collector.addRule(".monaco-editor .lines-content .cigra { box-shadow: 1px 0 0 0 " + editorActiveIndentGuidesColor + " inset; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[229/*vs/editor/browser/viewParts/lineNumbers/lineNumbers*/], __M([0/*require*/,1/*exports*/,16/*vs/base/common/platform*/,82/*vs/editor/browser/view/dynamicViewOverlay*/,13/*vs/editor/common/core/position*/,44/*vs/editor/common/view/editorColorRegistry*/,14/*vs/platform/theme/common/themeService*/,289/*vs/css!vs/editor/browser/viewParts/lineNumbers/lineNumbers*/]), function (require, exports, platform, dynamicViewOverlay_1, position_1, editorColorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LineNumbersOverlay = /** @class */ (function (_super) { __extends(LineNumbersOverlay, _super); function LineNumbersOverlay(context) { var _this = _super.call(this) || this; _this._context = context; _this._readConfig(); _this._lastCursorModelPosition = new position_1.Position(1, 1); _this._renderResult = null; _this._context.addEventHandler(_this); return _this; } LineNumbersOverlay.prototype._readConfig = function () { var options = this._context.configuration.options; this._lineHeight = options.get(49 /* lineHeight */); var lineNumbers = options.get(50 /* lineNumbers */); this._renderLineNumbers = lineNumbers.renderType; this._renderCustomLineNumbers = lineNumbers.renderFn; this._renderFinalNewline = options.get(71 /* renderFinalNewline */); var layoutInfo = options.get(107 /* layoutInfo */); this._lineNumbersLeft = layoutInfo.lineNumbersLeft; this._lineNumbersWidth = layoutInfo.lineNumbersWidth; }; LineNumbersOverlay.prototype.dispose = function () { this._context.removeEventHandler(this); this._renderResult = null; _super.prototype.dispose.call(this); }; // --- begin event handlers LineNumbersOverlay.prototype.onConfigurationChanged = function (e) { this._readConfig(); return true; }; LineNumbersOverlay.prototype.onCursorStateChanged = function (e) { var primaryViewPosition = e.selections[0].getPosition(); this._lastCursorModelPosition = this._context.model.coordinatesConverter.convertViewPositionToModelPosition(primaryViewPosition); if (this._renderLineNumbers === 2 /* Relative */ || this._renderLineNumbers === 3 /* Interval */) { return true; } return false; }; LineNumbersOverlay.prototype.onFlushed = function (e) { return true; }; LineNumbersOverlay.prototype.onLinesChanged = function (e) { return true; }; LineNumbersOverlay.prototype.onLinesDeleted = function (e) { return true; }; LineNumbersOverlay.prototype.onLinesInserted = function (e) { return true; }; LineNumbersOverlay.prototype.onScrollChanged = function (e) { return e.scrollTopChanged; }; LineNumbersOverlay.prototype.onZonesChanged = function (e) { return true; }; // --- end event handlers LineNumbersOverlay.prototype._getLineRenderLineNumber = function (viewLineNumber) { var modelPosition = this._context.model.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(viewLineNumber, 1)); if (modelPosition.column !== 1) { return ''; } var modelLineNumber = modelPosition.lineNumber; if (this._renderCustomLineNumbers) { return this._renderCustomLineNumbers(modelLineNumber); } if (this._renderLineNumbers === 2 /* Relative */) { var diff = Math.abs(this._lastCursorModelPosition.lineNumber - modelLineNumber); if (diff === 0) { return '' + modelLineNumber + ''; } return String(diff); } if (this._renderLineNumbers === 3 /* Interval */) { if (this._lastCursorModelPosition.lineNumber === modelLineNumber) { return String(modelLineNumber); } if (modelLineNumber % 10 === 0) { return String(modelLineNumber); } return ''; } return String(modelLineNumber); }; LineNumbersOverlay.prototype.prepareRender = function (ctx) { if (this._renderLineNumbers === 0 /* Off */) { this._renderResult = null; return; } var lineHeightClassName = (platform.isLinux ? (this._lineHeight % 2 === 0 ? ' lh-even' : ' lh-odd') : ''); var visibleStartLineNumber = ctx.visibleRange.startLineNumber; var visibleEndLineNumber = ctx.visibleRange.endLineNumber; var common = '
    '; var lineCount = this._context.model.getLineCount(); var output = []; for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) { var lineIndex = lineNumber - visibleStartLineNumber; if (!this._renderFinalNewline) { if (lineNumber === lineCount && this._context.model.getLineLength(lineNumber) === 0) { // Do not render last (empty) line output[lineIndex] = ''; continue; } } var renderLineNumber = this._getLineRenderLineNumber(lineNumber); if (renderLineNumber) { output[lineIndex] = (common + renderLineNumber + '
    '); } else { output[lineIndex] = ''; } } this._renderResult = output; }; LineNumbersOverlay.prototype.render = function (startLineNumber, lineNumber) { if (!this._renderResult) { return ''; } var lineIndex = lineNumber - startLineNumber; if (lineIndex < 0 || lineIndex >= this._renderResult.length) { return ''; } return this._renderResult[lineIndex]; }; LineNumbersOverlay.CLASS_NAME = 'line-numbers'; return LineNumbersOverlay; }(dynamicViewOverlay_1.DynamicViewOverlay)); exports.LineNumbersOverlay = LineNumbersOverlay; // theming themeService_1.registerThemingParticipant(function (theme, collector) { var lineNumbers = theme.getColor(editorColorRegistry_1.editorLineNumbers); if (lineNumbers) { collector.addRule(".monaco-editor .line-numbers { color: " + lineNumbers + "; }"); } var activeLineNumber = theme.getColor(editorColorRegistry_1.editorActiveLineNumber); if (activeLineNumber) { collector.addRule(".monaco-editor .current-line ~ .line-numbers { color: " + activeLineNumber + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[559/*vs/editor/browser/controller/textAreaHandler*/], __M([0/*require*/,1/*exports*/,416/*vs/nls!vs/editor/browser/controller/textAreaHandler*/,24/*vs/base/browser/browser*/,28/*vs/base/browser/fastDomNode*/,16/*vs/base/common/platform*/,5/*vs/base/common/strings*/,60/*vs/editor/browser/config/configuration*/,189/*vs/editor/browser/controller/textAreaInput*/,187/*vs/editor/browser/controller/textAreaState*/,37/*vs/editor/browser/view/viewPart*/,229/*vs/editor/browser/viewParts/lineNumbers/lineNumbers*/,195/*vs/editor/browser/viewParts/margin/margin*/,33/*vs/editor/common/config/editorOptions*/,89/*vs/editor/common/controller/wordCharacterClassifier*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,81/*vs/editor/common/view/viewEvents*/,284/*vs/css!vs/editor/browser/controller/textAreaHandler*/]), function (require, exports, nls, browser, fastDomNode_1, platform, strings, configuration_1, textAreaInput_1, textAreaState_1, viewPart_1, lineNumbers_1, margin_1, editorOptions_1, wordCharacterClassifier_1, position_1, range_1, selection_1, viewEvents) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var VisibleTextAreaData = /** @class */ (function () { function VisibleTextAreaData(top, left, width) { this.top = top; this.left = left; this.width = width; } VisibleTextAreaData.prototype.setWidth = function (width) { return new VisibleTextAreaData(this.top, this.left, width); }; return VisibleTextAreaData; }()); var canUseZeroSizeTextarea = (browser.isEdgeOrIE || browser.isFirefox); var TextAreaHandler = /** @class */ (function (_super) { __extends(TextAreaHandler, _super); function TextAreaHandler(context, viewController, viewHelper) { var _this = _super.call(this, context) || this; // --- end view API _this._primaryCursorPosition = new position_1.Position(1, 1); _this._primaryCursorVisibleRange = null; _this._viewController = viewController; _this._viewHelper = viewHelper; _this._scrollLeft = 0; _this._scrollTop = 0; var options = _this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); _this._setAccessibilityOptions(options); _this._contentLeft = layoutInfo.contentLeft; _this._contentWidth = layoutInfo.contentWidth; _this._contentHeight = layoutInfo.height; _this._fontInfo = options.get(34 /* fontInfo */); _this._lineHeight = options.get(49 /* lineHeight */); _this._emptySelectionClipboard = options.get(25 /* emptySelectionClipboard */); _this._copyWithSyntaxHighlighting = options.get(15 /* copyWithSyntaxHighlighting */); _this._visibleTextArea = null; _this._selections = [new selection_1.Selection(1, 1, 1, 1)]; _this._modelSelections = [new selection_1.Selection(1, 1, 1, 1)]; _this._lastRenderPosition = null; // Text Area (The focus will always be in the textarea when the cursor is blinking) _this.textArea = fastDomNode_1.createFastDomNode(document.createElement('textarea')); viewPart_1.PartFingerprints.write(_this.textArea, 6 /* TextArea */); _this.textArea.setClassName('inputarea'); _this.textArea.setAttribute('wrap', 'off'); _this.textArea.setAttribute('autocorrect', 'off'); _this.textArea.setAttribute('autocapitalize', 'off'); _this.textArea.setAttribute('autocomplete', 'off'); _this.textArea.setAttribute('spellcheck', 'false'); _this.textArea.setAttribute('aria-label', _this._getAriaLabel(options)); _this.textArea.setAttribute('role', 'textbox'); _this.textArea.setAttribute('aria-multiline', 'true'); _this.textArea.setAttribute('aria-haspopup', 'false'); _this.textArea.setAttribute('aria-autocomplete', 'both'); if (platform.isWeb && options.get(68 /* readOnly */)) { _this.textArea.setAttribute('readonly', 'true'); } _this.textAreaCover = fastDomNode_1.createFastDomNode(document.createElement('div')); _this.textAreaCover.setPosition('absolute'); var simpleModel = { getLineCount: function () { return _this._context.model.getLineCount(); }, getLineMaxColumn: function (lineNumber) { return _this._context.model.getLineMaxColumn(lineNumber); }, getValueInRange: function (range, eol) { return _this._context.model.getValueInRange(range, eol); } }; var textAreaInputHost = { getDataToCopy: function (generateHTML) { var rawTextToCopy = _this._context.model.getPlainTextToCopy(_this._modelSelections, _this._emptySelectionClipboard, platform.isWindows); var newLineCharacter = _this._context.model.getEOL(); var isFromEmptySelection = (_this._emptySelectionClipboard && _this._modelSelections.length === 1 && _this._modelSelections[0].isEmpty()); var multicursorText = (Array.isArray(rawTextToCopy) ? rawTextToCopy : null); var text = (Array.isArray(rawTextToCopy) ? rawTextToCopy.join(newLineCharacter) : rawTextToCopy); var html = undefined; var mode = null; if (generateHTML) { if (textAreaInput_1.CopyOptions.forceCopyWithSyntaxHighlighting || (_this._copyWithSyntaxHighlighting && text.length < 65536)) { var richText = _this._context.model.getRichTextToCopy(_this._modelSelections, _this._emptySelectionClipboard); if (richText) { html = richText.html; mode = richText.mode; } } } return { isFromEmptySelection: isFromEmptySelection, multicursorText: multicursorText, text: text, html: html, mode: mode }; }, getScreenReaderContent: function (currentState) { if (browser.isIPad) { // Do not place anything in the textarea for the iPad return textAreaState_1.TextAreaState.EMPTY; } if (_this._accessibilitySupport === 1 /* Disabled */) { // We know for a fact that a screen reader is not attached // On OSX, we write the character before the cursor to allow for "long-press" composition // Also on OSX, we write the word before the cursor to allow for the Accessibility Keyboard to give good hints if (platform.isMacintosh) { var selection = _this._selections[0]; if (selection.isEmpty()) { var position = selection.getStartPosition(); var textBefore = _this._getWordBeforePosition(position); if (textBefore.length === 0) { textBefore = _this._getCharacterBeforePosition(position); } if (textBefore.length > 0) { return new textAreaState_1.TextAreaState(textBefore, textBefore.length, textBefore.length, position, position); } } } return textAreaState_1.TextAreaState.EMPTY; } return textAreaState_1.PagedScreenReaderStrategy.fromEditorSelection(currentState, simpleModel, _this._selections[0], _this._accessibilityPageSize, _this._accessibilitySupport === 0 /* Unknown */); }, deduceModelPosition: function (viewAnchorPosition, deltaOffset, lineFeedCnt) { return _this._context.model.deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt); } }; _this._textAreaInput = _this._register(new textAreaInput_1.TextAreaInput(textAreaInputHost, _this.textArea)); _this._register(_this._textAreaInput.onKeyDown(function (e) { _this._viewController.emitKeyDown(e); })); _this._register(_this._textAreaInput.onKeyUp(function (e) { _this._viewController.emitKeyUp(e); })); _this._register(_this._textAreaInput.onPaste(function (e) { var pasteOnNewLine = false; var multicursorText = null; var mode = null; if (e.metadata) { pasteOnNewLine = (_this._emptySelectionClipboard && !!e.metadata.isFromEmptySelection); multicursorText = (typeof e.metadata.multicursorText !== 'undefined' ? e.metadata.multicursorText : null); mode = e.metadata.mode; } _this._viewController.paste('keyboard', e.text, pasteOnNewLine, multicursorText, mode); })); _this._register(_this._textAreaInput.onCut(function () { _this._viewController.cut('keyboard'); })); _this._register(_this._textAreaInput.onType(function (e) { if (e.replaceCharCnt) { _this._viewController.replacePreviousChar('keyboard', e.text, e.replaceCharCnt); } else { _this._viewController.type('keyboard', e.text); } })); _this._register(_this._textAreaInput.onSelectionChangeRequest(function (modelSelection) { _this._viewController.setSelection('keyboard', modelSelection); })); _this._register(_this._textAreaInput.onCompositionStart(function () { var lineNumber = _this._selections[0].startLineNumber; var column = _this._selections[0].startColumn; _this._context.privateViewEventBus.emit(new viewEvents.ViewRevealRangeRequestEvent('keyboard', new range_1.Range(lineNumber, column, lineNumber, column), 0 /* Simple */, true, 1 /* Immediate */)); // Find range pixel position var visibleRange = _this._viewHelper.visibleRangeForPositionRelativeToEditor(lineNumber, column); if (visibleRange) { _this._visibleTextArea = new VisibleTextAreaData(_this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber), visibleRange.left, canUseZeroSizeTextarea ? 0 : 1); _this._render(); } // Show the textarea _this.textArea.setClassName('inputarea ime-input'); _this._viewController.compositionStart('keyboard'); })); _this._register(_this._textAreaInput.onCompositionUpdate(function (e) { if (browser.isEdgeOrIE) { // Due to isEdgeOrIE (where the textarea was not cleared initially) // we cannot assume the text consists only of the composited text _this._visibleTextArea = _this._visibleTextArea.setWidth(0); } else { // adjust width by its size _this._visibleTextArea = _this._visibleTextArea.setWidth(measureText(e.data, _this._fontInfo)); } _this._render(); })); _this._register(_this._textAreaInput.onCompositionEnd(function () { _this._visibleTextArea = null; _this._render(); _this.textArea.setClassName('inputarea'); _this._viewController.compositionEnd('keyboard'); })); _this._register(_this._textAreaInput.onFocus(function () { _this._context.privateViewEventBus.emit(new viewEvents.ViewFocusChangedEvent(true)); })); _this._register(_this._textAreaInput.onBlur(function () { _this._context.privateViewEventBus.emit(new viewEvents.ViewFocusChangedEvent(false)); })); return _this; } TextAreaHandler.prototype.dispose = function () { _super.prototype.dispose.call(this); }; TextAreaHandler.prototype._getWordBeforePosition = function (position) { var lineContent = this._context.model.getLineContent(position.lineNumber); var wordSeparators = wordCharacterClassifier_1.getMapForWordSeparators(this._context.configuration.options.get(96 /* wordSeparators */)); var column = position.column; var distance = 0; while (column > 1) { var charCode = lineContent.charCodeAt(column - 2); var charClass = wordSeparators.get(charCode); if (charClass !== 0 /* Regular */ || distance > 50) { return lineContent.substring(column - 1, position.column - 1); } distance++; column--; } return lineContent.substring(0, position.column - 1); }; TextAreaHandler.prototype._getCharacterBeforePosition = function (position) { if (position.column > 1) { var lineContent = this._context.model.getLineContent(position.lineNumber); var charBefore = lineContent.charAt(position.column - 2); if (!strings.isHighSurrogate(charBefore.charCodeAt(0))) { return charBefore; } } return ''; }; TextAreaHandler.prototype._getAriaLabel = function (options) { var accessibilitySupport = options.get(2 /* accessibilitySupport */); if (accessibilitySupport === 1 /* Disabled */) { return nls.localize(0, null); } return options.get(4 /* ariaLabel */); }; TextAreaHandler.prototype._setAccessibilityOptions = function (options) { this._accessibilitySupport = options.get(2 /* accessibilitySupport */); var accessibilityPageSize = options.get(3 /* accessibilityPageSize */); if (this._accessibilitySupport === 2 /* Enabled */ && accessibilityPageSize === editorOptions_1.EditorOptions.accessibilityPageSize.defaultValue) { // If a screen reader is attached and the default value is not set we shuold automatically increase the page size to 160 for a better experience // If we put more than 160 lines the nvda can not handle this https://github.com/microsoft/vscode/issues/89717 this._accessibilityPageSize = 160; } else { this._accessibilityPageSize = accessibilityPageSize; } }; // --- begin event handlers TextAreaHandler.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); this._setAccessibilityOptions(options); this._contentLeft = layoutInfo.contentLeft; this._contentWidth = layoutInfo.contentWidth; this._contentHeight = layoutInfo.height; this._fontInfo = options.get(34 /* fontInfo */); this._lineHeight = options.get(49 /* lineHeight */); this._emptySelectionClipboard = options.get(25 /* emptySelectionClipboard */); this._copyWithSyntaxHighlighting = options.get(15 /* copyWithSyntaxHighlighting */); this.textArea.setAttribute('aria-label', this._getAriaLabel(options)); if (platform.isWeb && e.hasChanged(68 /* readOnly */)) { if (options.get(68 /* readOnly */)) { this.textArea.setAttribute('readonly', 'true'); } else { this.textArea.removeAttribute('readonly'); } } if (e.hasChanged(2 /* accessibilitySupport */)) { this._textAreaInput.writeScreenReaderContent('strategy changed'); } return true; }; TextAreaHandler.prototype.onCursorStateChanged = function (e) { this._selections = e.selections.slice(0); this._modelSelections = e.modelSelections.slice(0); this._textAreaInput.writeScreenReaderContent('selection changed'); return true; }; TextAreaHandler.prototype.onDecorationsChanged = function (e) { // true for inline decorations that can end up relayouting text return true; }; TextAreaHandler.prototype.onFlushed = function (e) { return true; }; TextAreaHandler.prototype.onLinesChanged = function (e) { return true; }; TextAreaHandler.prototype.onLinesDeleted = function (e) { return true; }; TextAreaHandler.prototype.onLinesInserted = function (e) { return true; }; TextAreaHandler.prototype.onScrollChanged = function (e) { this._scrollLeft = e.scrollLeft; this._scrollTop = e.scrollTop; return true; }; TextAreaHandler.prototype.onZonesChanged = function (e) { return true; }; // --- end event handlers // --- begin view API TextAreaHandler.prototype.isFocused = function () { return this._textAreaInput.isFocused(); }; TextAreaHandler.prototype.focusTextArea = function () { this._textAreaInput.focusTextArea(); }; TextAreaHandler.prototype.getLastRenderData = function () { return this._lastRenderPosition; }; TextAreaHandler.prototype.setAriaOptions = function (options) { if (options.activeDescendant) { this.textArea.setAttribute('aria-haspopup', 'true'); this.textArea.setAttribute('aria-autocomplete', 'list'); this.textArea.setAttribute('aria-activedescendant', options.activeDescendant); } else { this.textArea.setAttribute('aria-haspopup', 'false'); this.textArea.setAttribute('aria-autocomplete', 'both'); this.textArea.removeAttribute('aria-activedescendant'); } }; TextAreaHandler.prototype.prepareRender = function (ctx) { this._primaryCursorPosition = new position_1.Position(this._selections[0].positionLineNumber, this._selections[0].positionColumn); this._primaryCursorVisibleRange = ctx.visibleRangeForPosition(this._primaryCursorPosition); }; TextAreaHandler.prototype.render = function (ctx) { this._textAreaInput.writeScreenReaderContent('render'); this._render(); }; TextAreaHandler.prototype._render = function () { if (this._visibleTextArea) { // The text area is visible for composition reasons this._renderInsideEditor(null, this._visibleTextArea.top - this._scrollTop, this._contentLeft + this._visibleTextArea.left - this._scrollLeft, this._visibleTextArea.width, this._lineHeight); return; } if (!this._primaryCursorVisibleRange) { // The primary cursor is outside the viewport => place textarea to the top left this._renderAtTopLeft(); return; } var left = this._contentLeft + this._primaryCursorVisibleRange.left - this._scrollLeft; if (left < this._contentLeft || left > this._contentLeft + this._contentWidth) { // cursor is outside the viewport this._renderAtTopLeft(); return; } var top = this._context.viewLayout.getVerticalOffsetForLineNumber(this._selections[0].positionLineNumber) - this._scrollTop; if (top < 0 || top > this._contentHeight) { // cursor is outside the viewport this._renderAtTopLeft(); return; } // The primary cursor is in the viewport (at least vertically) => place textarea on the cursor if (platform.isMacintosh) { // For the popup emoji input, we will make the text area as high as the line height // We will also make the fontSize and lineHeight the correct dimensions to help with the placement of these pickers this._renderInsideEditor(this._primaryCursorPosition, top, left, canUseZeroSizeTextarea ? 0 : 1, this._lineHeight); return; } this._renderInsideEditor(this._primaryCursorPosition, top, left, canUseZeroSizeTextarea ? 0 : 1, canUseZeroSizeTextarea ? 0 : 1); }; TextAreaHandler.prototype._renderInsideEditor = function (renderedPosition, top, left, width, height) { this._lastRenderPosition = renderedPosition; var ta = this.textArea; var tac = this.textAreaCover; configuration_1.Configuration.applyFontInfo(ta, this._fontInfo); ta.setTop(top); ta.setLeft(left); ta.setWidth(width); ta.setHeight(height); tac.setTop(0); tac.setLeft(0); tac.setWidth(0); tac.setHeight(0); }; TextAreaHandler.prototype._renderAtTopLeft = function () { this._lastRenderPosition = null; var ta = this.textArea; var tac = this.textAreaCover; configuration_1.Configuration.applyFontInfo(ta, this._fontInfo); ta.setTop(0); ta.setLeft(0); tac.setTop(0); tac.setLeft(0); if (canUseZeroSizeTextarea) { ta.setWidth(0); ta.setHeight(0); tac.setWidth(0); tac.setHeight(0); return; } // (in WebKit the textarea is 1px by 1px because it cannot handle input to a 0x0 textarea) // specifically, when doing Korean IME, setting the textarea to 0x0 breaks IME badly. ta.setWidth(1); ta.setHeight(1); tac.setWidth(1); tac.setHeight(1); var options = this._context.configuration.options; if (options.get(40 /* glyphMargin */)) { tac.setClassName('monaco-editor-background textAreaCover ' + margin_1.Margin.OUTER_CLASS_NAME); } else { if (options.get(50 /* lineNumbers */).renderType !== 0 /* Off */) { tac.setClassName('monaco-editor-background textAreaCover ' + lineNumbers_1.LineNumbersOverlay.CLASS_NAME); } else { tac.setClassName('monaco-editor-background textAreaCover'); } } }; return TextAreaHandler; }(viewPart_1.ViewPart)); exports.TextAreaHandler = TextAreaHandler; function measureText(text, fontInfo) { // adjust width by its size var canvasElem = document.createElement('canvas'); var context = canvasElem.getContext('2d'); context.font = createFontString(fontInfo); var metrics = context.measureText(text); if (browser.isFirefox) { return metrics.width + 2; // +2 for Japanese... } else { return metrics.width; } } function createFontString(bareFontInfo) { return doCreateFontString('normal', bareFontInfo.fontWeight, bareFontInfo.fontSize, bareFontInfo.lineHeight, bareFontInfo.fontFamily); } function doCreateFontString(fontStyle, fontWeight, fontSize, lineHeight, fontFamily) { // The full font syntax is: // style | variant | weight | stretch | size/line-height | fontFamily // (https://developer.mozilla.org/en-US/docs/Web/CSS/font) // But it appears Edge and IE11 cannot properly parse `stretch`. return fontStyle + " normal " + fontWeight + " " + fontSize + "px / " + lineHeight + "px " + fontFamily; } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[560/*vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,27/*vs/base/common/color*/,37/*vs/editor/browser/view/viewPart*/,13/*vs/editor/common/core/position*/,17/*vs/editor/common/modes*/,44/*vs/editor/common/view/editorColorRegistry*/]), function (require, exports, fastDomNode_1, color_1, viewPart_1, position_1, modes_1, editorColorRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Settings = /** @class */ (function () { function Settings(config, theme) { var options = config.options; this.lineHeight = options.get(49 /* lineHeight */); this.pixelRatio = options.get(105 /* pixelRatio */); this.overviewRulerLanes = options.get(63 /* overviewRulerLanes */); this.renderBorder = options.get(62 /* overviewRulerBorder */); var borderColor = theme.getColor(editorColorRegistry_1.editorOverviewRulerBorder); this.borderColor = borderColor ? borderColor.toString() : null; this.hideCursor = options.get(42 /* hideCursorInOverviewRuler */); var cursorColor = theme.getColor(editorColorRegistry_1.editorCursorForeground); this.cursorColor = cursorColor ? cursorColor.transparent(0.7).toString() : null; this.themeType = theme.type; var minimapOpts = options.get(54 /* minimap */); var minimapEnabled = minimapOpts.enabled; var minimapSide = minimapOpts.side; var backgroundColor = (minimapEnabled ? modes_1.TokenizationRegistry.getDefaultBackground() : null); if (backgroundColor === null || minimapSide === 'left') { this.backgroundColor = null; } else { this.backgroundColor = color_1.Color.Format.CSS.formatHex(backgroundColor); } var layoutInfo = options.get(107 /* layoutInfo */); var position = layoutInfo.overviewRuler; this.top = position.top; this.right = position.right; this.domWidth = position.width; this.domHeight = position.height; if (this.overviewRulerLanes === 0) { // overview ruler is off this.canvasWidth = 0; this.canvasHeight = 0; } else { this.canvasWidth = (this.domWidth * this.pixelRatio) | 0; this.canvasHeight = (this.domHeight * this.pixelRatio) | 0; } var _a = this._initLanes(1, this.canvasWidth, this.overviewRulerLanes), x = _a[0], w = _a[1]; this.x = x; this.w = w; } Settings.prototype._initLanes = function (canvasLeftOffset, canvasWidth, laneCount) { var remainingWidth = canvasWidth - canvasLeftOffset; if (laneCount >= 3) { var leftWidth = Math.floor(remainingWidth / 3); var rightWidth = Math.floor(remainingWidth / 3); var centerWidth = remainingWidth - leftWidth - rightWidth; var leftOffset = canvasLeftOffset; var centerOffset = leftOffset + leftWidth; var rightOffset = leftOffset + leftWidth + centerWidth; return [ [ 0, leftOffset, centerOffset, leftOffset, rightOffset, leftOffset, centerOffset, leftOffset, ], [ 0, leftWidth, centerWidth, leftWidth + centerWidth, rightWidth, leftWidth + centerWidth + rightWidth, centerWidth + rightWidth, leftWidth + centerWidth + rightWidth, ] ]; } else if (laneCount === 2) { var leftWidth = Math.floor(remainingWidth / 2); var rightWidth = remainingWidth - leftWidth; var leftOffset = canvasLeftOffset; var rightOffset = leftOffset + leftWidth; return [ [ 0, leftOffset, leftOffset, leftOffset, rightOffset, leftOffset, leftOffset, leftOffset, ], [ 0, leftWidth, leftWidth, leftWidth, rightWidth, leftWidth + rightWidth, leftWidth + rightWidth, leftWidth + rightWidth, ] ]; } else { var offset = canvasLeftOffset; var width = remainingWidth; return [ [ 0, offset, offset, offset, offset, offset, offset, offset, ], [ 0, width, width, width, width, width, width, width, ] ]; } }; Settings.prototype.equals = function (other) { return (this.lineHeight === other.lineHeight && this.pixelRatio === other.pixelRatio && this.overviewRulerLanes === other.overviewRulerLanes && this.renderBorder === other.renderBorder && this.borderColor === other.borderColor && this.hideCursor === other.hideCursor && this.cursorColor === other.cursorColor && this.themeType === other.themeType && this.backgroundColor === other.backgroundColor && this.top === other.top && this.right === other.right && this.domWidth === other.domWidth && this.domHeight === other.domHeight && this.canvasWidth === other.canvasWidth && this.canvasHeight === other.canvasHeight); }; return Settings; }()); var DecorationsOverviewRuler = /** @class */ (function (_super) { __extends(DecorationsOverviewRuler, _super); function DecorationsOverviewRuler(context) { var _this = _super.call(this, context) || this; _this._domNode = fastDomNode_1.createFastDomNode(document.createElement('canvas')); _this._domNode.setClassName('decorationsOverviewRuler'); _this._domNode.setPosition('absolute'); _this._domNode.setLayerHinting(true); _this._domNode.setContain('strict'); _this._domNode.setAttribute('aria-hidden', 'true'); _this._updateSettings(false); _this._tokensColorTrackerListener = modes_1.TokenizationRegistry.onDidChange(function (e) { if (e.changedColorMap) { _this._updateSettings(true); } }); _this._cursorPositions = []; return _this; } DecorationsOverviewRuler.prototype.dispose = function () { _super.prototype.dispose.call(this); this._tokensColorTrackerListener.dispose(); }; DecorationsOverviewRuler.prototype._updateSettings = function (renderNow) { var newSettings = new Settings(this._context.configuration, this._context.theme); if (this._settings && this._settings.equals(newSettings)) { // nothing to do return false; } this._settings = newSettings; this._domNode.setTop(this._settings.top); this._domNode.setRight(this._settings.right); this._domNode.setWidth(this._settings.domWidth); this._domNode.setHeight(this._settings.domHeight); this._domNode.domNode.width = this._settings.canvasWidth; this._domNode.domNode.height = this._settings.canvasHeight; if (renderNow) { this._render(); } return true; }; // ---- begin view event handlers DecorationsOverviewRuler.prototype.onConfigurationChanged = function (e) { return this._updateSettings(false); }; DecorationsOverviewRuler.prototype.onCursorStateChanged = function (e) { this._cursorPositions = []; for (var i = 0, len = e.selections.length; i < len; i++) { this._cursorPositions[i] = e.selections[i].getPosition(); } this._cursorPositions.sort(position_1.Position.compare); return true; }; DecorationsOverviewRuler.prototype.onDecorationsChanged = function (e) { return true; }; DecorationsOverviewRuler.prototype.onFlushed = function (e) { return true; }; DecorationsOverviewRuler.prototype.onScrollChanged = function (e) { return e.scrollHeightChanged; }; DecorationsOverviewRuler.prototype.onZonesChanged = function (e) { return true; }; DecorationsOverviewRuler.prototype.onThemeChanged = function (e) { // invalidate color cache this._context.model.invalidateOverviewRulerColorCache(); return this._updateSettings(false); }; // ---- end view event handlers DecorationsOverviewRuler.prototype.getDomNode = function () { return this._domNode.domNode; }; DecorationsOverviewRuler.prototype.prepareRender = function (ctx) { // Nothing to read }; DecorationsOverviewRuler.prototype.render = function (editorCtx) { this._render(); }; DecorationsOverviewRuler.prototype._render = function () { if (this._settings.overviewRulerLanes === 0) { // overview ruler is off this._domNode.setBackgroundColor(this._settings.backgroundColor ? this._settings.backgroundColor : ''); return; } var canvasWidth = this._settings.canvasWidth; var canvasHeight = this._settings.canvasHeight; var lineHeight = this._settings.lineHeight; var viewLayout = this._context.viewLayout; var outerHeight = this._context.viewLayout.getScrollHeight(); var heightRatio = canvasHeight / outerHeight; var decorations = this._context.model.getAllOverviewRulerDecorations(this._context.theme); var minDecorationHeight = (6 /* MIN_DECORATION_HEIGHT */ * this._settings.pixelRatio) | 0; var halfMinDecorationHeight = (minDecorationHeight / 2) | 0; var canvasCtx = this._domNode.domNode.getContext('2d'); if (this._settings.backgroundColor === null) { canvasCtx.clearRect(0, 0, canvasWidth, canvasHeight); } else { canvasCtx.fillStyle = this._settings.backgroundColor; canvasCtx.fillRect(0, 0, canvasWidth, canvasHeight); } var x = this._settings.x; var w = this._settings.w; // Avoid flickering by always rendering the colors in the same order // colors that don't use transparency will be sorted last (they start with #) var colors = Object.keys(decorations); colors.sort(); for (var cIndex = 0, cLen = colors.length; cIndex < cLen; cIndex++) { var color = colors[cIndex]; var colorDecorations = decorations[color]; canvasCtx.fillStyle = color; var prevLane = 0; var prevY1 = 0; var prevY2 = 0; for (var i = 0, len = colorDecorations.length; i < len; i++) { var lane = colorDecorations[3 * i]; var startLineNumber = colorDecorations[3 * i + 1]; var endLineNumber = colorDecorations[3 * i + 2]; var y1 = (viewLayout.getVerticalOffsetForLineNumber(startLineNumber) * heightRatio) | 0; var y2 = ((viewLayout.getVerticalOffsetForLineNumber(endLineNumber) + lineHeight) * heightRatio) | 0; var height = y2 - y1; if (height < minDecorationHeight) { var yCenter = ((y1 + y2) / 2) | 0; if (yCenter < halfMinDecorationHeight) { yCenter = halfMinDecorationHeight; } else if (yCenter + halfMinDecorationHeight > canvasHeight) { yCenter = canvasHeight - halfMinDecorationHeight; } y1 = yCenter - halfMinDecorationHeight; y2 = yCenter + halfMinDecorationHeight; } if (y1 > prevY2 + 1 || lane !== prevLane) { // flush prev if (i !== 0) { canvasCtx.fillRect(x[prevLane], prevY1, w[prevLane], prevY2 - prevY1); } prevLane = lane; prevY1 = y1; prevY2 = y2; } else { // merge into prev if (y2 > prevY2) { prevY2 = y2; } } } canvasCtx.fillRect(x[prevLane], prevY1, w[prevLane], prevY2 - prevY1); } // Draw cursors if (!this._settings.hideCursor && this._settings.cursorColor) { var cursorHeight = (2 * this._settings.pixelRatio) | 0; var halfCursorHeight = (cursorHeight / 2) | 0; var cursorX = this._settings.x[7 /* Full */]; var cursorW = this._settings.w[7 /* Full */]; canvasCtx.fillStyle = this._settings.cursorColor; var prevY1 = -100; var prevY2 = -100; for (var i = 0, len = this._cursorPositions.length; i < len; i++) { var cursor = this._cursorPositions[i]; var yCenter = (viewLayout.getVerticalOffsetForLineNumber(cursor.lineNumber) * heightRatio) | 0; if (yCenter < halfCursorHeight) { yCenter = halfCursorHeight; } else if (yCenter + halfCursorHeight > canvasHeight) { yCenter = canvasHeight - halfCursorHeight; } var y1 = yCenter - halfCursorHeight; var y2 = y1 + cursorHeight; if (y1 > prevY2 + 1) { // flush prev if (i !== 0) { canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1); } prevY1 = y1; prevY2 = y2; } else { // merge into prev if (y2 > prevY2) { prevY2 = y2; } } } canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1); } if (this._settings.renderBorder && this._settings.borderColor && this._settings.overviewRulerLanes > 0) { canvasCtx.beginPath(); canvasCtx.lineWidth = 1; canvasCtx.strokeStyle = this._settings.borderColor; canvasCtx.moveTo(0, 0); canvasCtx.lineTo(0, canvasHeight); canvasCtx.stroke(); canvasCtx.moveTo(0, 0); canvasCtx.lineTo(canvasWidth, 0); canvasCtx.stroke(); } }; return DecorationsOverviewRuler; }(viewPart_1.ViewPart)); exports.DecorationsOverviewRuler = DecorationsOverviewRuler; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[561/*vs/editor/browser/viewParts/rulers/rulers*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,37/*vs/editor/browser/view/viewPart*/,44/*vs/editor/common/view/editorColorRegistry*/,14/*vs/platform/theme/common/themeService*/,295/*vs/css!vs/editor/browser/viewParts/rulers/rulers*/]), function (require, exports, fastDomNode_1, viewPart_1, editorColorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Rulers = /** @class */ (function (_super) { __extends(Rulers, _super); function Rulers(context) { var _this = _super.call(this, context) || this; _this.domNode = fastDomNode_1.createFastDomNode(document.createElement('div')); _this.domNode.setAttribute('role', 'presentation'); _this.domNode.setAttribute('aria-hidden', 'true'); _this.domNode.setClassName('view-rulers'); _this._renderedRulers = []; var options = _this._context.configuration.options; _this._rulers = options.get(77 /* rulers */); _this._typicalHalfwidthCharacterWidth = options.get(34 /* fontInfo */).typicalHalfwidthCharacterWidth; return _this; } Rulers.prototype.dispose = function () { _super.prototype.dispose.call(this); }; // --- begin event handlers Rulers.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; this._rulers = options.get(77 /* rulers */); this._typicalHalfwidthCharacterWidth = options.get(34 /* fontInfo */).typicalHalfwidthCharacterWidth; return true; }; Rulers.prototype.onScrollChanged = function (e) { return e.scrollHeightChanged; }; // --- end event handlers Rulers.prototype.prepareRender = function (ctx) { // Nothing to read }; Rulers.prototype._ensureRulersCount = function () { var currentCount = this._renderedRulers.length; var desiredCount = this._rulers.length; if (currentCount === desiredCount) { // Nothing to do return; } if (currentCount < desiredCount) { var tabSize = this._context.model.getOptions().tabSize; var rulerWidth = tabSize; var addCount = desiredCount - currentCount; while (addCount > 0) { var node = fastDomNode_1.createFastDomNode(document.createElement('div')); node.setClassName('view-ruler'); node.setWidth(rulerWidth); this.domNode.appendChild(node); this._renderedRulers.push(node); addCount--; } return; } var removeCount = currentCount - desiredCount; while (removeCount > 0) { var node = this._renderedRulers.pop(); this.domNode.removeChild(node); removeCount--; } }; Rulers.prototype.render = function (ctx) { this._ensureRulersCount(); for (var i = 0, len = this._rulers.length; i < len; i++) { var node = this._renderedRulers[i]; node.setHeight(Math.min(ctx.scrollHeight, 1000000)); node.setLeft(this._rulers[i] * this._typicalHalfwidthCharacterWidth); } }; return Rulers; }(viewPart_1.ViewPart)); exports.Rulers = Rulers; themeService_1.registerThemingParticipant(function (theme, collector) { var rulerColor = theme.getColor(editorColorRegistry_1.editorRuler); if (rulerColor) { collector.addRule(".monaco-editor .view-ruler { box-shadow: 1px 0 0 0 " + rulerColor + " inset; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[562/*vs/editor/browser/viewParts/viewCursors/viewCursors*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,15/*vs/base/common/async*/,37/*vs/editor/browser/view/viewPart*/,514/*vs/editor/browser/viewParts/viewCursors/viewCursor*/,33/*vs/editor/common/config/editorOptions*/,44/*vs/editor/common/view/editorColorRegistry*/,14/*vs/platform/theme/common/themeService*/,298/*vs/css!vs/editor/browser/viewParts/viewCursors/viewCursors*/]), function (require, exports, fastDomNode_1, async_1, viewPart_1, viewCursor_1, editorOptions_1, editorColorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ViewCursors = /** @class */ (function (_super) { __extends(ViewCursors, _super); function ViewCursors(context) { var _this = _super.call(this, context) || this; var options = _this._context.configuration.options; _this._readOnly = options.get(68 /* readOnly */); _this._cursorBlinking = options.get(16 /* cursorBlinking */); _this._cursorStyle = options.get(18 /* cursorStyle */); _this._cursorSmoothCaretAnimation = options.get(17 /* cursorSmoothCaretAnimation */); _this._selectionIsEmpty = true; _this._isVisible = false; _this._primaryCursor = new viewCursor_1.ViewCursor(_this._context); _this._secondaryCursors = []; _this._renderData = []; _this._domNode = fastDomNode_1.createFastDomNode(document.createElement('div')); _this._domNode.setAttribute('role', 'presentation'); _this._domNode.setAttribute('aria-hidden', 'true'); _this._updateDomClassName(); _this._domNode.appendChild(_this._primaryCursor.getDomNode()); _this._startCursorBlinkAnimation = new async_1.TimeoutTimer(); _this._cursorFlatBlinkInterval = new async_1.IntervalTimer(); _this._blinkingEnabled = false; _this._editorHasFocus = false; _this._updateBlinking(); return _this; } ViewCursors.prototype.dispose = function () { _super.prototype.dispose.call(this); this._startCursorBlinkAnimation.dispose(); this._cursorFlatBlinkInterval.dispose(); }; ViewCursors.prototype.getDomNode = function () { return this._domNode; }; // --- begin event handlers ViewCursors.prototype.onConfigurationChanged = function (e) { var options = this._context.configuration.options; this._readOnly = options.get(68 /* readOnly */); this._cursorBlinking = options.get(16 /* cursorBlinking */); this._cursorStyle = options.get(18 /* cursorStyle */); this._cursorSmoothCaretAnimation = options.get(17 /* cursorSmoothCaretAnimation */); this._updateBlinking(); this._updateDomClassName(); this._primaryCursor.onConfigurationChanged(e); for (var i = 0, len = this._secondaryCursors.length; i < len; i++) { this._secondaryCursors[i].onConfigurationChanged(e); } return true; }; ViewCursors.prototype._onCursorPositionChanged = function (position, secondaryPositions) { this._primaryCursor.onCursorPositionChanged(position); this._updateBlinking(); if (this._secondaryCursors.length < secondaryPositions.length) { // Create new cursors var addCnt = secondaryPositions.length - this._secondaryCursors.length; for (var i = 0; i < addCnt; i++) { var newCursor = new viewCursor_1.ViewCursor(this._context); this._domNode.domNode.insertBefore(newCursor.getDomNode().domNode, this._primaryCursor.getDomNode().domNode.nextSibling); this._secondaryCursors.push(newCursor); } } else if (this._secondaryCursors.length > secondaryPositions.length) { // Remove some cursors var removeCnt = this._secondaryCursors.length - secondaryPositions.length; for (var i = 0; i < removeCnt; i++) { this._domNode.removeChild(this._secondaryCursors[0].getDomNode()); this._secondaryCursors.splice(0, 1); } } for (var i = 0; i < secondaryPositions.length; i++) { this._secondaryCursors[i].onCursorPositionChanged(secondaryPositions[i]); } }; ViewCursors.prototype.onCursorStateChanged = function (e) { var positions = []; for (var i = 0, len = e.selections.length; i < len; i++) { positions[i] = e.selections[i].getPosition(); } this._onCursorPositionChanged(positions[0], positions.slice(1)); var selectionIsEmpty = e.selections[0].isEmpty(); if (this._selectionIsEmpty !== selectionIsEmpty) { this._selectionIsEmpty = selectionIsEmpty; this._updateDomClassName(); } return true; }; ViewCursors.prototype.onDecorationsChanged = function (e) { // true for inline decorations that can end up relayouting text return true; }; ViewCursors.prototype.onFlushed = function (e) { return true; }; ViewCursors.prototype.onFocusChanged = function (e) { this._editorHasFocus = e.isFocused; this._updateBlinking(); return false; }; ViewCursors.prototype.onLinesChanged = function (e) { return true; }; ViewCursors.prototype.onLinesDeleted = function (e) { return true; }; ViewCursors.prototype.onLinesInserted = function (e) { return true; }; ViewCursors.prototype.onScrollChanged = function (e) { return true; }; ViewCursors.prototype.onTokensChanged = function (e) { var shouldRender = function (position) { for (var i = 0, len = e.ranges.length; i < len; i++) { if (e.ranges[i].fromLineNumber <= position.lineNumber && position.lineNumber <= e.ranges[i].toLineNumber) { return true; } } return false; }; if (shouldRender(this._primaryCursor.getPosition())) { return true; } for (var _i = 0, _a = this._secondaryCursors; _i < _a.length; _i++) { var secondaryCursor = _a[_i]; if (shouldRender(secondaryCursor.getPosition())) { return true; } } return false; }; ViewCursors.prototype.onZonesChanged = function (e) { return true; }; // --- end event handlers // ---- blinking logic ViewCursors.prototype._getCursorBlinking = function () { if (!this._editorHasFocus) { return 0 /* Hidden */; } if (this._readOnly) { return 5 /* Solid */; } return this._cursorBlinking; }; ViewCursors.prototype._updateBlinking = function () { var _this = this; this._startCursorBlinkAnimation.cancel(); this._cursorFlatBlinkInterval.cancel(); var blinkingStyle = this._getCursorBlinking(); // hidden and solid are special as they involve no animations var isHidden = (blinkingStyle === 0 /* Hidden */); var isSolid = (blinkingStyle === 5 /* Solid */); if (isHidden) { this._hide(); } else { this._show(); } this._blinkingEnabled = false; this._updateDomClassName(); if (!isHidden && !isSolid) { if (blinkingStyle === 1 /* Blink */) { // flat blinking is handled by JavaScript to save battery life due to Chromium step timing issue https://bugs.chromium.org/p/chromium/issues/detail?id=361587 this._cursorFlatBlinkInterval.cancelAndSet(function () { if (_this._isVisible) { _this._hide(); } else { _this._show(); } }, ViewCursors.BLINK_INTERVAL); } else { this._startCursorBlinkAnimation.setIfNotSet(function () { _this._blinkingEnabled = true; _this._updateDomClassName(); }, ViewCursors.BLINK_INTERVAL); } } }; // --- end blinking logic ViewCursors.prototype._updateDomClassName = function () { this._domNode.setClassName(this._getClassName()); }; ViewCursors.prototype._getClassName = function () { var result = 'cursors-layer'; if (!this._selectionIsEmpty) { result += ' has-selection'; } switch (this._cursorStyle) { case editorOptions_1.TextEditorCursorStyle.Line: result += ' cursor-line-style'; break; case editorOptions_1.TextEditorCursorStyle.Block: result += ' cursor-block-style'; break; case editorOptions_1.TextEditorCursorStyle.Underline: result += ' cursor-underline-style'; break; case editorOptions_1.TextEditorCursorStyle.LineThin: result += ' cursor-line-thin-style'; break; case editorOptions_1.TextEditorCursorStyle.BlockOutline: result += ' cursor-block-outline-style'; break; case editorOptions_1.TextEditorCursorStyle.UnderlineThin: result += ' cursor-underline-thin-style'; break; default: result += ' cursor-line-style'; } if (this._blinkingEnabled) { switch (this._getCursorBlinking()) { case 1 /* Blink */: result += ' cursor-blink'; break; case 2 /* Smooth */: result += ' cursor-smooth'; break; case 3 /* Phase */: result += ' cursor-phase'; break; case 4 /* Expand */: result += ' cursor-expand'; break; case 5 /* Solid */: result += ' cursor-solid'; break; default: result += ' cursor-solid'; } } else { result += ' cursor-solid'; } if (this._cursorSmoothCaretAnimation) { result += ' cursor-smooth-caret-animation'; } return result; }; ViewCursors.prototype._show = function () { this._primaryCursor.show(); for (var i = 0, len = this._secondaryCursors.length; i < len; i++) { this._secondaryCursors[i].show(); } this._isVisible = true; }; ViewCursors.prototype._hide = function () { this._primaryCursor.hide(); for (var i = 0, len = this._secondaryCursors.length; i < len; i++) { this._secondaryCursors[i].hide(); } this._isVisible = false; }; // ---- IViewPart implementation ViewCursors.prototype.prepareRender = function (ctx) { this._primaryCursor.prepareRender(ctx); for (var i = 0, len = this._secondaryCursors.length; i < len; i++) { this._secondaryCursors[i].prepareRender(ctx); } }; ViewCursors.prototype.render = function (ctx) { var renderData = [], renderDataLen = 0; var primaryRenderData = this._primaryCursor.render(ctx); if (primaryRenderData) { renderData[renderDataLen++] = primaryRenderData; } for (var i = 0, len = this._secondaryCursors.length; i < len; i++) { var secondaryRenderData = this._secondaryCursors[i].render(ctx); if (secondaryRenderData) { renderData[renderDataLen++] = secondaryRenderData; } } this._renderData = renderData; }; ViewCursors.prototype.getLastRenderData = function () { return this._renderData; }; ViewCursors.BLINK_INTERVAL = 500; return ViewCursors; }(viewPart_1.ViewPart)); exports.ViewCursors = ViewCursors; themeService_1.registerThemingParticipant(function (theme, collector) { var caret = theme.getColor(editorColorRegistry_1.editorCursorForeground); if (caret) { var caretBackground = theme.getColor(editorColorRegistry_1.editorCursorBackground); if (!caretBackground) { caretBackground = caret.opposite(); } collector.addRule(".monaco-editor .cursor { background-color: " + caret + "; border-color: " + caret + "; color: " + caretBackground + "; }"); if (theme.type === 'hc') { collector.addRule(".monaco-editor .cursors-layer.has-selection .cursor { border-left: 1px solid " + caretBackground + "; border-right: 1px solid " + caretBackground + "; }"); } } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[563/*vs/editor/browser/view/viewImpl*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,28/*vs/base/browser/fastDomNode*/,10/*vs/base/common/errors*/,551/*vs/editor/browser/controller/pointerHandler*/,559/*vs/editor/browser/controller/textAreaHandler*/,523/*vs/editor/browser/view/viewController*/,228/*vs/editor/browser/view/viewOutgoingEvents*/,513/*vs/editor/browser/view/viewOverlays*/,37/*vs/editor/browser/view/viewPart*/,366/*vs/editor/browser/viewParts/contentWidgets/contentWidgets*/,557/*vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/,367/*vs/editor/browser/viewParts/decorations/decorations*/,549/*vs/editor/browser/viewParts/editorScrollbar/editorScrollbar*/,149/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/,558/*vs/editor/browser/viewParts/indentGuides/indentGuides*/,229/*vs/editor/browser/viewParts/lineNumbers/lineNumbers*/,552/*vs/editor/browser/viewParts/lines/viewLines*/,368/*vs/editor/browser/viewParts/linesDecorations/linesDecorations*/,195/*vs/editor/browser/viewParts/margin/margin*/,369/*vs/editor/browser/viewParts/marginDecorations/marginDecorations*/,553/*vs/editor/browser/viewParts/minimap/minimap*/,370/*vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/,560/*vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler*/,371/*vs/editor/browser/viewParts/overviewRuler/overviewRuler*/,561/*vs/editor/browser/viewParts/rulers/rulers*/,554/*vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/,555/*vs/editor/browser/viewParts/selections/selections*/,562/*vs/editor/browser/viewParts/viewCursors/viewCursors*/,372/*vs/editor/browser/viewParts/viewZones/viewZones*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,91/*vs/editor/common/view/renderingContext*/,360/*vs/editor/common/view/viewContext*/,361/*vs/editor/common/view/viewEventDispatcher*/,81/*vs/editor/common/view/viewEvents*/,363/*vs/editor/common/viewLayout/viewLinesViewportData*/,92/*vs/editor/common/viewModel/viewEventHandler*/,14/*vs/platform/theme/common/themeService*/,166/*vs/editor/browser/controller/mouseTarget*/]), function (require, exports, dom, fastDomNode_1, errors_1, pointerHandler_1, textAreaHandler_1, viewController_1, viewOutgoingEvents_1, viewOverlays_1, viewPart_1, contentWidgets_1, currentLineHighlight_1, decorations_1, editorScrollbar_1, glyphMargin_1, indentGuides_1, lineNumbers_1, viewLines_1, linesDecorations_1, margin_1, marginDecorations_1, minimap_1, overlayWidgets_1, decorationsOverviewRuler_1, overviewRuler_1, rulers_1, scrollDecoration_1, selections_1, viewCursors_1, viewZones_1, position_1, range_1, renderingContext_1, viewContext_1, viewEventDispatcher_1, viewEvents, viewLinesViewportData_1, viewEventHandler_1, themeService_1, mouseTarget_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var View = /** @class */ (function (_super) { __extends(View, _super); function View(commandDelegate, configuration, themeService, model, cursor, outgoingEvents) { var _this = _super.call(this) || this; _this._cursor = cursor; _this._renderAnimationFrame = null; _this.outgoingEvents = outgoingEvents; var viewController = new viewController_1.ViewController(configuration, model, _this.outgoingEvents, commandDelegate); // The event dispatcher will always go through _renderOnce before dispatching any events _this.eventDispatcher = new viewEventDispatcher_1.ViewEventDispatcher(function (callback) { return _this._renderOnce(callback); }); // Ensure the view is the first event handler in order to update the layout _this.eventDispatcher.addEventHandler(_this); // The view context is passed on to most classes (basically to reduce param. counts in ctors) _this._context = new viewContext_1.ViewContext(configuration, themeService.getTheme(), model, _this.eventDispatcher); _this._register(themeService.onThemeChange(function (theme) { _this._context.theme = theme; _this.eventDispatcher.emit(new viewEvents.ViewThemeChangedEvent()); _this.render(true, false); })); _this.viewParts = []; // Keyboard handler _this._textAreaHandler = new textAreaHandler_1.TextAreaHandler(_this._context, viewController, _this.createTextAreaHandlerHelper()); _this.viewParts.push(_this._textAreaHandler); // These two dom nodes must be constructed up front, since references are needed in the layout provider (scrolling & co.) _this.linesContent = fastDomNode_1.createFastDomNode(document.createElement('div')); _this.linesContent.setClassName('lines-content' + ' monaco-editor-background'); _this.linesContent.setPosition('absolute'); _this.domNode = fastDomNode_1.createFastDomNode(document.createElement('div')); _this.domNode.setClassName(_this.getEditorClassName()); _this.overflowGuardContainer = fastDomNode_1.createFastDomNode(document.createElement('div')); viewPart_1.PartFingerprints.write(_this.overflowGuardContainer, 3 /* OverflowGuard */); _this.overflowGuardContainer.setClassName('overflow-guard'); _this._scrollbar = new editorScrollbar_1.EditorScrollbar(_this._context, _this.linesContent, _this.domNode, _this.overflowGuardContainer); _this.viewParts.push(_this._scrollbar); // View Lines _this.viewLines = new viewLines_1.ViewLines(_this._context, _this.linesContent); // View Zones _this.viewZones = new viewZones_1.ViewZones(_this._context); _this.viewParts.push(_this.viewZones); // Decorations overview ruler var decorationsOverviewRuler = new decorationsOverviewRuler_1.DecorationsOverviewRuler(_this._context); _this.viewParts.push(decorationsOverviewRuler); var scrollDecoration = new scrollDecoration_1.ScrollDecorationViewPart(_this._context); _this.viewParts.push(scrollDecoration); var contentViewOverlays = new viewOverlays_1.ContentViewOverlays(_this._context); _this.viewParts.push(contentViewOverlays); contentViewOverlays.addDynamicOverlay(new currentLineHighlight_1.CurrentLineHighlightOverlay(_this._context)); contentViewOverlays.addDynamicOverlay(new selections_1.SelectionsOverlay(_this._context)); contentViewOverlays.addDynamicOverlay(new indentGuides_1.IndentGuidesOverlay(_this._context)); contentViewOverlays.addDynamicOverlay(new decorations_1.DecorationsOverlay(_this._context)); var marginViewOverlays = new viewOverlays_1.MarginViewOverlays(_this._context); _this.viewParts.push(marginViewOverlays); marginViewOverlays.addDynamicOverlay(new currentLineHighlight_1.CurrentLineMarginHighlightOverlay(_this._context)); marginViewOverlays.addDynamicOverlay(new glyphMargin_1.GlyphMarginOverlay(_this._context)); marginViewOverlays.addDynamicOverlay(new marginDecorations_1.MarginViewLineDecorationsOverlay(_this._context)); marginViewOverlays.addDynamicOverlay(new linesDecorations_1.LinesDecorationsOverlay(_this._context)); marginViewOverlays.addDynamicOverlay(new lineNumbers_1.LineNumbersOverlay(_this._context)); var margin = new margin_1.Margin(_this._context); margin.getDomNode().appendChild(_this.viewZones.marginDomNode); margin.getDomNode().appendChild(marginViewOverlays.getDomNode()); _this.viewParts.push(margin); // Content widgets _this.contentWidgets = new contentWidgets_1.ViewContentWidgets(_this._context, _this.domNode); _this.viewParts.push(_this.contentWidgets); _this.viewCursors = new viewCursors_1.ViewCursors(_this._context); _this.viewParts.push(_this.viewCursors); // Overlay widgets _this.overlayWidgets = new overlayWidgets_1.ViewOverlayWidgets(_this._context); _this.viewParts.push(_this.overlayWidgets); var rulers = new rulers_1.Rulers(_this._context); _this.viewParts.push(rulers); var minimap = new minimap_1.Minimap(_this._context); _this.viewParts.push(minimap); // -------------- Wire dom nodes up if (decorationsOverviewRuler) { var overviewRulerData = _this._scrollbar.getOverviewRulerLayoutInfo(); overviewRulerData.parent.insertBefore(decorationsOverviewRuler.getDomNode(), overviewRulerData.insertBefore); } _this.linesContent.appendChild(contentViewOverlays.getDomNode()); _this.linesContent.appendChild(rulers.domNode); _this.linesContent.appendChild(_this.viewZones.domNode); _this.linesContent.appendChild(_this.viewLines.getDomNode()); _this.linesContent.appendChild(_this.contentWidgets.domNode); _this.linesContent.appendChild(_this.viewCursors.getDomNode()); _this.overflowGuardContainer.appendChild(margin.getDomNode()); _this.overflowGuardContainer.appendChild(_this._scrollbar.getDomNode()); _this.overflowGuardContainer.appendChild(scrollDecoration.getDomNode()); _this.overflowGuardContainer.appendChild(_this._textAreaHandler.textArea); _this.overflowGuardContainer.appendChild(_this._textAreaHandler.textAreaCover); _this.overflowGuardContainer.appendChild(_this.overlayWidgets.getDomNode()); _this.overflowGuardContainer.appendChild(minimap.getDomNode()); _this.domNode.appendChild(_this.overflowGuardContainer); _this.domNode.appendChild(_this.contentWidgets.overflowingContentWidgetsDomNode); _this._applyLayout(); // Pointer handler _this.pointerHandler = _this._register(new pointerHandler_1.PointerHandler(_this._context, viewController, _this.createPointerHandlerHelper())); _this._register(model.addEventListener(function (events) { _this.eventDispatcher.emitMany(events); })); _this._register(_this._cursor.addEventListener(function (events) { _this.eventDispatcher.emitMany(events); })); return _this; } View.prototype._flushAccumulatedAndRenderNow = function () { this._renderNow(); }; View.prototype.createPointerHandlerHelper = function () { var _this = this; return { viewDomNode: this.domNode.domNode, linesContentDomNode: this.linesContent.domNode, focusTextArea: function () { _this.focus(); }, getLastRenderData: function () { var lastViewCursorsRenderData = _this.viewCursors.getLastRenderData() || []; var lastTextareaPosition = _this._textAreaHandler.getLastRenderData(); return new mouseTarget_1.PointerHandlerLastRenderData(lastViewCursorsRenderData, lastTextareaPosition); }, shouldSuppressMouseDownOnViewZone: function (viewZoneId) { return _this.viewZones.shouldSuppressMouseDownOnViewZone(viewZoneId); }, shouldSuppressMouseDownOnWidget: function (widgetId) { return _this.contentWidgets.shouldSuppressMouseDownOnWidget(widgetId); }, getPositionFromDOMInfo: function (spanNode, offset) { _this._flushAccumulatedAndRenderNow(); return _this.viewLines.getPositionFromDOMInfo(spanNode, offset); }, visibleRangeForPosition: function (lineNumber, column) { _this._flushAccumulatedAndRenderNow(); return _this.viewLines.visibleRangeForPosition(new position_1.Position(lineNumber, column)); }, getLineWidth: function (lineNumber) { _this._flushAccumulatedAndRenderNow(); return _this.viewLines.getLineWidth(lineNumber); } }; }; View.prototype.createTextAreaHandlerHelper = function () { var _this = this; return { visibleRangeForPositionRelativeToEditor: function (lineNumber, column) { _this._flushAccumulatedAndRenderNow(); return _this.viewLines.visibleRangeForPosition(new position_1.Position(lineNumber, column)); } }; }; View.prototype._applyLayout = function () { var options = this._context.configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); this.domNode.setWidth(layoutInfo.width); this.domNode.setHeight(layoutInfo.height); this.overflowGuardContainer.setWidth(layoutInfo.width); this.overflowGuardContainer.setHeight(layoutInfo.height); this.linesContent.setWidth(1000000); this.linesContent.setHeight(1000000); }; View.prototype.getEditorClassName = function () { var focused = this._textAreaHandler.isFocused() ? ' focused' : ''; return this._context.configuration.options.get(104 /* editorClassName */) + ' ' + themeService_1.getThemeTypeSelector(this._context.theme.type) + focused; }; // --- begin event handlers View.prototype.onConfigurationChanged = function (e) { this.domNode.setClassName(this.getEditorClassName()); this._applyLayout(); return false; }; View.prototype.onContentSizeChanged = function (e) { this.outgoingEvents.emitContentSizeChange(e); return false; }; View.prototype.onFocusChanged = function (e) { this.domNode.setClassName(this.getEditorClassName()); this._context.model.setHasFocus(e.isFocused); if (e.isFocused) { this.outgoingEvents.emitViewFocusGained(); } else { this.outgoingEvents.emitViewFocusLost(); } return false; }; View.prototype.onScrollChanged = function (e) { this.outgoingEvents.emitScrollChanged(e); return false; }; View.prototype.onThemeChanged = function (e) { this.domNode.setClassName(this.getEditorClassName()); return false; }; // --- end event handlers View.prototype.dispose = function () { if (this._renderAnimationFrame !== null) { this._renderAnimationFrame.dispose(); this._renderAnimationFrame = null; } this.eventDispatcher.removeEventHandler(this); this.outgoingEvents.dispose(); this.viewLines.dispose(); // Destroy view parts for (var i = 0, len = this.viewParts.length; i < len; i++) { this.viewParts[i].dispose(); } this.viewParts = []; _super.prototype.dispose.call(this); }; View.prototype._renderOnce = function (callback) { var r = safeInvokeNoArg(callback); this._scheduleRender(); return r; }; View.prototype._scheduleRender = function () { if (this._renderAnimationFrame === null) { this._renderAnimationFrame = dom.runAtThisOrScheduleAtNextAnimationFrame(this._onRenderScheduled.bind(this), 100); } }; View.prototype._onRenderScheduled = function () { this._renderAnimationFrame = null; this._flushAccumulatedAndRenderNow(); }; View.prototype._renderNow = function () { var _this = this; safeInvokeNoArg(function () { return _this._actualRender(); }); }; View.prototype._getViewPartsToRender = function () { var result = [], resultLen = 0; for (var i = 0, len = this.viewParts.length; i < len; i++) { var viewPart = this.viewParts[i]; if (viewPart.shouldRender()) { result[resultLen++] = viewPart; } } return result; }; View.prototype._actualRender = function () { if (!dom.isInDOM(this.domNode.domNode)) { return; } var viewPartsToRender = this._getViewPartsToRender(); if (!this.viewLines.shouldRender() && viewPartsToRender.length === 0) { // Nothing to render return; } var partialViewportData = this._context.viewLayout.getLinesViewportData(); this._context.model.setViewport(partialViewportData.startLineNumber, partialViewportData.endLineNumber, partialViewportData.centeredLineNumber); var viewportData = new viewLinesViewportData_1.ViewportData(this._cursor.getViewSelections(), partialViewportData, this._context.viewLayout.getWhitespaceViewportData(), this._context.model); if (this.contentWidgets.shouldRender()) { // Give the content widgets a chance to set their max width before a possible synchronous layout this.contentWidgets.onBeforeRender(viewportData); } if (this.viewLines.shouldRender()) { this.viewLines.renderText(viewportData); this.viewLines.onDidRender(); // Rendering of viewLines might cause scroll events to occur, so collect view parts to render again viewPartsToRender = this._getViewPartsToRender(); } var renderingContext = new renderingContext_1.RenderingContext(this._context.viewLayout, viewportData, this.viewLines); // Render the rest of the parts for (var i = 0, len = viewPartsToRender.length; i < len; i++) { var viewPart = viewPartsToRender[i]; viewPart.prepareRender(renderingContext); } for (var i = 0, len = viewPartsToRender.length; i < len; i++) { var viewPart = viewPartsToRender[i]; viewPart.render(renderingContext); viewPart.onDidRender(); } }; // --- BEGIN CodeEditor helpers View.prototype.delegateVerticalScrollbarMouseDown = function (browserEvent) { this._scrollbar.delegateVerticalScrollbarMouseDown(browserEvent); }; View.prototype.restoreState = function (scrollPosition) { this._context.viewLayout.setScrollPositionNow({ scrollTop: scrollPosition.scrollTop }); this._context.model.tokenizeViewport(); this._renderNow(); this.viewLines.updateLineWidths(); this._context.viewLayout.setScrollPositionNow({ scrollLeft: scrollPosition.scrollLeft }); }; View.prototype.getOffsetForColumn = function (modelLineNumber, modelColumn) { var modelPosition = this._context.model.validateModelPosition({ lineNumber: modelLineNumber, column: modelColumn }); var viewPosition = this._context.model.coordinatesConverter.convertModelPositionToViewPosition(modelPosition); this._flushAccumulatedAndRenderNow(); var visibleRange = this.viewLines.visibleRangeForPosition(new position_1.Position(viewPosition.lineNumber, viewPosition.column)); if (!visibleRange) { return -1; } return visibleRange.left; }; View.prototype.getTargetAtClientPoint = function (clientX, clientY) { var mouseTarget = this.pointerHandler.getTargetAtClientPoint(clientX, clientY); if (!mouseTarget) { return null; } return viewOutgoingEvents_1.ViewOutgoingEvents.convertViewToModelMouseTarget(mouseTarget, this._context.model.coordinatesConverter); }; View.prototype.createOverviewRuler = function (cssClassName) { return new overviewRuler_1.OverviewRuler(this._context, cssClassName); }; View.prototype.change = function (callback) { var _this = this; return this._renderOnce(function () { var zonesHaveChanged = _this.viewZones.changeViewZones(callback); if (zonesHaveChanged) { _this._context.viewLayout.onHeightMaybeChanged(); _this._context.privateViewEventBus.emit(new viewEvents.ViewZonesChangedEvent()); } return zonesHaveChanged; }); }; View.prototype.render = function (now, everything) { if (everything) { // Force everything to render... this.viewLines.forceShouldRender(); for (var i = 0, len = this.viewParts.length; i < len; i++) { var viewPart = this.viewParts[i]; viewPart.forceShouldRender(); } } if (now) { this._flushAccumulatedAndRenderNow(); } else { this._scheduleRender(); } }; View.prototype.focus = function () { this._textAreaHandler.focusTextArea(); }; View.prototype.isFocused = function () { return this._textAreaHandler.isFocused(); }; View.prototype.setAriaOptions = function (options) { this._textAreaHandler.setAriaOptions(options); }; View.prototype.addContentWidget = function (widgetData) { this.contentWidgets.addWidget(widgetData.widget); this.layoutContentWidget(widgetData); this._scheduleRender(); }; View.prototype.layoutContentWidget = function (widgetData) { var newRange = widgetData.position ? widgetData.position.range || null : null; if (newRange === null) { var newPosition = widgetData.position ? widgetData.position.position : null; if (newPosition !== null) { newRange = new range_1.Range(newPosition.lineNumber, newPosition.column, newPosition.lineNumber, newPosition.column); } } var newPreference = widgetData.position ? widgetData.position.preference : null; this.contentWidgets.setWidgetPosition(widgetData.widget, newRange, newPreference); this._scheduleRender(); }; View.prototype.removeContentWidget = function (widgetData) { this.contentWidgets.removeWidget(widgetData.widget); this._scheduleRender(); }; View.prototype.addOverlayWidget = function (widgetData) { this.overlayWidgets.addWidget(widgetData.widget); this.layoutOverlayWidget(widgetData); this._scheduleRender(); }; View.prototype.layoutOverlayWidget = function (widgetData) { var newPreference = widgetData.position ? widgetData.position.preference : null; var shouldRender = this.overlayWidgets.setWidgetPosition(widgetData.widget, newPreference); if (shouldRender) { this._scheduleRender(); } }; View.prototype.removeOverlayWidget = function (widgetData) { this.overlayWidgets.removeWidget(widgetData.widget); this._scheduleRender(); }; return View; }(viewEventHandler_1.ViewEventHandler)); exports.View = View; function safeInvokeNoArg(func) { try { return func(); } catch (e) { 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[121/*vs/editor/browser/widget/codeEditorWidget*/], __M([0/*require*/,1/*exports*/,417/*vs/nls!vs/editor/browser/widget/codeEditorWidget*/,6/*vs/base/browser/dom*/,10/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,46/*vs/base/common/network*/,60/*vs/editor/browser/config/configuration*/,12/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,563/*vs/editor/browser/view/viewImpl*/,228/*vs/editor/browser/view/viewOutgoingEvents*/,33/*vs/editor/common/config/editorOptions*/,486/*vs/editor/common/controller/cursor*/,40/*vs/editor/common/controller/cursorCommon*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,190/*vs/editor/common/editorAction*/,68/*vs/editor/common/editorCommon*/,23/*vs/editor/common/editorContextKeys*/,17/*vs/editor/common/modes*/,44/*vs/editor/common/view/editorColorRegistry*/,20/*vs/platform/theme/common/colorRegistry*/,488/*vs/editor/common/viewModel/viewModelImpl*/,29/*vs/platform/commands/common/commands*/,18/*vs/platform/contextkey/common/contextkey*/,11/*vs/platform/instantiation/common/instantiation*/,115/*vs/platform/instantiation/common/serviceCollection*/,35/*vs/platform/notification/common/notification*/,14/*vs/platform/theme/common/themeService*/,64/*vs/platform/accessibility/common/accessibility*/,21/*vs/base/common/types*/,487/*vs/editor/common/viewModel/monospaceLineBreaksComputer*/,512/*vs/editor/browser/view/domLineBreaksComputer*/,301/*vs/css!vs/editor/browser/widget/media/editor*/]), function (require, exports, nls, dom, errors_1, event_1, lifecycle_1, network_1, configuration_1, editorExtensions_1, codeEditorService_1, viewImpl_1, viewOutgoingEvents_1, editorOptions_1, cursor_1, cursorCommon_1, position_1, range_1, selection_1, editorAction_1, editorCommon, editorContextKeys_1, modes, editorColorRegistry_1, colorRegistry_1, viewModelImpl_1, commands_1, contextkey_1, instantiation_1, serviceCollection_1, notification_1, themeService_1, accessibility_1, types_1, monospaceLineBreaksComputer_1, domLineBreaksComputer_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var EDITOR_ID = 0; var ModelData = /** @class */ (function () { function ModelData(model, viewModel, cursor, view, hasRealView, listenersToRemove) { this.model = model; this.viewModel = viewModel; this.cursor = cursor; this.view = view; this.hasRealView = hasRealView; this.listenersToRemove = listenersToRemove; } ModelData.prototype.dispose = function () { lifecycle_1.dispose(this.listenersToRemove); this.model.onBeforeDetached(); if (this.hasRealView) { this.view.dispose(); } this.cursor.dispose(); this.viewModel.dispose(); }; return ModelData; }()); var CodeEditorWidget = /** @class */ (function (_super) { __extends(CodeEditorWidget, _super); function CodeEditorWidget(domElement, options, codeEditorWidgetOptions, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService) { var _this = _super.call(this) || this; //#region Eventing _this._onDidDispose = _this._register(new event_1.Emitter()); _this.onDidDispose = _this._onDidDispose.event; _this._onDidChangeModelContent = _this._register(new event_1.Emitter()); _this.onDidChangeModelContent = _this._onDidChangeModelContent.event; _this._onDidChangeModelLanguage = _this._register(new event_1.Emitter()); _this.onDidChangeModelLanguage = _this._onDidChangeModelLanguage.event; _this._onDidChangeModelLanguageConfiguration = _this._register(new event_1.Emitter()); _this.onDidChangeModelLanguageConfiguration = _this._onDidChangeModelLanguageConfiguration.event; _this._onDidChangeModelOptions = _this._register(new event_1.Emitter()); _this.onDidChangeModelOptions = _this._onDidChangeModelOptions.event; _this._onDidChangeModelDecorations = _this._register(new event_1.Emitter()); _this.onDidChangeModelDecorations = _this._onDidChangeModelDecorations.event; _this._onDidChangeConfiguration = _this._register(new event_1.Emitter()); _this.onDidChangeConfiguration = _this._onDidChangeConfiguration.event; _this._onDidChangeModel = _this._register(new event_1.Emitter()); _this.onDidChangeModel = _this._onDidChangeModel.event; _this._onDidChangeCursorPosition = _this._register(new event_1.Emitter()); _this.onDidChangeCursorPosition = _this._onDidChangeCursorPosition.event; _this._onDidChangeCursorSelection = _this._register(new event_1.Emitter()); _this.onDidChangeCursorSelection = _this._onDidChangeCursorSelection.event; _this._onDidAttemptReadOnlyEdit = _this._register(new event_1.Emitter()); _this.onDidAttemptReadOnlyEdit = _this._onDidAttemptReadOnlyEdit.event; _this._onDidLayoutChange = _this._register(new event_1.Emitter()); _this.onDidLayoutChange = _this._onDidLayoutChange.event; _this._editorTextFocus = _this._register(new BooleanEventEmitter()); _this.onDidFocusEditorText = _this._editorTextFocus.onDidChangeToTrue; _this.onDidBlurEditorText = _this._editorTextFocus.onDidChangeToFalse; _this._editorWidgetFocus = _this._register(new BooleanEventEmitter()); _this.onDidFocusEditorWidget = _this._editorWidgetFocus.onDidChangeToTrue; _this.onDidBlurEditorWidget = _this._editorWidgetFocus.onDidChangeToFalse; _this._onWillType = _this._register(new event_1.Emitter()); _this.onWillType = _this._onWillType.event; _this._onDidType = _this._register(new event_1.Emitter()); _this.onDidType = _this._onDidType.event; _this._onDidCompositionStart = _this._register(new event_1.Emitter()); _this.onDidCompositionStart = _this._onDidCompositionStart.event; _this._onDidCompositionEnd = _this._register(new event_1.Emitter()); _this.onDidCompositionEnd = _this._onDidCompositionEnd.event; _this._onDidPaste = _this._register(new event_1.Emitter()); _this.onDidPaste = _this._onDidPaste.event; _this._onMouseUp = _this._register(new event_1.Emitter()); _this.onMouseUp = _this._onMouseUp.event; _this._onMouseDown = _this._register(new event_1.Emitter()); _this.onMouseDown = _this._onMouseDown.event; _this._onMouseDrag = _this._register(new event_1.Emitter()); _this.onMouseDrag = _this._onMouseDrag.event; _this._onMouseDrop = _this._register(new event_1.Emitter()); _this.onMouseDrop = _this._onMouseDrop.event; _this._onContextMenu = _this._register(new event_1.Emitter()); _this.onContextMenu = _this._onContextMenu.event; _this._onMouseMove = _this._register(new event_1.Emitter()); _this.onMouseMove = _this._onMouseMove.event; _this._onMouseLeave = _this._register(new event_1.Emitter()); _this.onMouseLeave = _this._onMouseLeave.event; _this._onMouseWheel = _this._register(new event_1.Emitter()); _this.onMouseWheel = _this._onMouseWheel.event; _this._onKeyUp = _this._register(new event_1.Emitter()); _this.onKeyUp = _this._onKeyUp.event; _this._onKeyDown = _this._register(new event_1.Emitter()); _this.onKeyDown = _this._onKeyDown.event; _this._onDidContentSizeChange = _this._register(new event_1.Emitter()); _this.onDidContentSizeChange = _this._onDidContentSizeChange.event; _this._onDidScrollChange = _this._register(new event_1.Emitter()); _this.onDidScrollChange = _this._onDidScrollChange.event; _this._onDidChangeViewZones = _this._register(new event_1.Emitter()); _this.onDidChangeViewZones = _this._onDidChangeViewZones.event; _this._domElement = domElement; _this._id = (++EDITOR_ID); _this._decorationTypeKeysToIds = {}; _this._decorationTypeSubtypes = {}; _this.isSimpleWidget = codeEditorWidgetOptions.isSimpleWidget || false; _this._telemetryData = codeEditorWidgetOptions.telemetryData; options = options || {}; _this._configuration = _this._register(_this._createConfiguration(options, accessibilityService)); _this._register(_this._configuration.onDidChange(function (e) { _this._onDidChangeConfiguration.fire(e); var options = _this._configuration.options; if (e.hasChanged(107 /* layoutInfo */)) { var layoutInfo = options.get(107 /* layoutInfo */); _this._onDidLayoutChange.fire(layoutInfo); } })); _this._contextKeyService = _this._register(contextKeyService.createScoped(_this._domElement)); _this._notificationService = notificationService; _this._codeEditorService = codeEditorService; _this._commandService = commandService; _this._themeService = themeService; _this._register(new EditorContextKeysManager(_this, _this._contextKeyService)); _this._register(new EditorModeContext(_this, _this._contextKeyService)); _this._instantiationService = instantiationService.createChild(new serviceCollection_1.ServiceCollection([contextkey_1.IContextKeyService, _this._contextKeyService])); _this._modelData = null; _this._contributions = {}; _this._actions = {}; _this._focusTracker = new CodeEditorWidgetFocusTracker(domElement); _this._focusTracker.onChange(function () { _this._editorWidgetFocus.setValue(_this._focusTracker.hasFocus()); }); _this._contentWidgets = {}; _this._overlayWidgets = {}; var contributions; if (Array.isArray(codeEditorWidgetOptions.contributions)) { contributions = codeEditorWidgetOptions.contributions; } else { contributions = editorExtensions_1.EditorExtensionsRegistry.getEditorContributions(); } for (var _i = 0, contributions_1 = contributions; _i < contributions_1.length; _i++) { var desc = contributions_1[_i]; try { var contribution = _this._instantiationService.createInstance(desc.ctor, _this); _this._contributions[desc.id] = contribution; } catch (err) { errors_1.onUnexpectedError(err); } } editorExtensions_1.EditorExtensionsRegistry.getEditorActions().forEach(function (action) { var internalAction = new editorAction_1.InternalEditorAction(action.id, action.label, action.alias, types_1.withNullAsUndefined(action.precondition), function () { return _this._instantiationService.invokeFunction(function (accessor) { return Promise.resolve(action.runEditorCommand(accessor, _this, null)); }); }, _this._contextKeyService); _this._actions[internalAction.id] = internalAction; }); _this._codeEditorService.addCodeEditor(_this); return _this; } CodeEditorWidget.prototype._createConfiguration = function (options, accessibilityService) { return new configuration_1.Configuration(this.isSimpleWidget, options, this._domElement, accessibilityService); }; CodeEditorWidget.prototype.getId = function () { return this.getEditorType() + ':' + this._id; }; CodeEditorWidget.prototype.getEditorType = function () { return editorCommon.EditorType.ICodeEditor; }; CodeEditorWidget.prototype.dispose = function () { this._codeEditorService.removeCodeEditor(this); this._focusTracker.dispose(); var keys = Object.keys(this._contributions); for (var i = 0, len = keys.length; i < len; i++) { var contributionId = keys[i]; this._contributions[contributionId].dispose(); } this._removeDecorationTypes(); this._postDetachModelCleanup(this._detachModel()); this._onDidDispose.fire(); _super.prototype.dispose.call(this); }; CodeEditorWidget.prototype.invokeWithinContext = function (fn) { return this._instantiationService.invokeFunction(fn); }; CodeEditorWidget.prototype.updateOptions = function (newOptions) { this._configuration.updateOptions(newOptions); }; CodeEditorWidget.prototype.getOptions = function () { return this._configuration.options; }; CodeEditorWidget.prototype.getOption = function (id) { return this._configuration.options.get(id); }; CodeEditorWidget.prototype.getRawOptions = function () { return this._configuration.getRawOptions(); }; CodeEditorWidget.prototype.getValue = function (options) { if (options === void 0) { options = null; } if (!this._modelData) { return ''; } var preserveBOM = (options && options.preserveBOM) ? true : false; var eolPreference = 0 /* TextDefined */; if (options && options.lineEnding && options.lineEnding === '\n') { eolPreference = 1 /* LF */; } else if (options && options.lineEnding && options.lineEnding === '\r\n') { eolPreference = 2 /* CRLF */; } return this._modelData.model.getValue(eolPreference, preserveBOM); }; CodeEditorWidget.prototype.setValue = function (newValue) { if (!this._modelData) { return; } this._modelData.model.setValue(newValue); }; CodeEditorWidget.prototype.getModel = function () { if (!this._modelData) { return null; } return this._modelData.model; }; CodeEditorWidget.prototype.setModel = function (_model) { if (_model === void 0) { _model = null; } var model = _model; if (this._modelData === null && model === null) { // Current model is the new model return; } if (this._modelData && this._modelData.model === model) { // Current model is the new model return; } var hasTextFocus = this.hasTextFocus(); var detachedModel = this._detachModel(); this._attachModel(model); if (hasTextFocus && this.hasModel()) { this.focus(); } var e = { oldModelUrl: detachedModel ? detachedModel.uri : null, newModelUrl: model ? model.uri : null }; this._removeDecorationTypes(); this._onDidChangeModel.fire(e); this._postDetachModelCleanup(detachedModel); }; CodeEditorWidget.prototype._removeDecorationTypes = function () { this._decorationTypeKeysToIds = {}; if (this._decorationTypeSubtypes) { for (var decorationType in this._decorationTypeSubtypes) { var subTypes = this._decorationTypeSubtypes[decorationType]; for (var subType in subTypes) { this._removeDecorationType(decorationType + '-' + subType); } } this._decorationTypeSubtypes = {}; } }; CodeEditorWidget.prototype.getVisibleRanges = function () { if (!this._modelData) { return []; } return this._modelData.viewModel.getVisibleRanges(); }; CodeEditorWidget.prototype.getWhitespaces = function () { if (!this._modelData) { return []; } return this._modelData.viewModel.viewLayout.getWhitespaces(); }; CodeEditorWidget._getVerticalOffsetForPosition = function (modelData, modelLineNumber, modelColumn) { var modelPosition = modelData.model.validatePosition({ lineNumber: modelLineNumber, column: modelColumn }); var viewPosition = modelData.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition); return modelData.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber); }; CodeEditorWidget.prototype.getTopForLineNumber = function (lineNumber) { if (!this._modelData) { return -1; } return CodeEditorWidget._getVerticalOffsetForPosition(this._modelData, lineNumber, 1); }; CodeEditorWidget.prototype.getTopForPosition = function (lineNumber, column) { if (!this._modelData) { return -1; } return CodeEditorWidget._getVerticalOffsetForPosition(this._modelData, lineNumber, column); }; CodeEditorWidget.prototype.setHiddenAreas = function (ranges) { if (this._modelData) { this._modelData.viewModel.setHiddenAreas(ranges.map(function (r) { return range_1.Range.lift(r); })); } }; CodeEditorWidget.prototype.getVisibleColumnFromPosition = function (rawPosition) { if (!this._modelData) { return rawPosition.column; } var position = this._modelData.model.validatePosition(rawPosition); var tabSize = this._modelData.model.getOptions().tabSize; return cursorCommon_1.CursorColumns.visibleColumnFromColumn(this._modelData.model.getLineContent(position.lineNumber), position.column, tabSize) + 1; }; CodeEditorWidget.prototype.getPosition = function () { if (!this._modelData) { return null; } return this._modelData.cursor.getPosition(); }; CodeEditorWidget.prototype.setPosition = function (position) { if (!this._modelData) { return; } if (!position_1.Position.isIPosition(position)) { throw new Error('Invalid arguments'); } this._modelData.cursor.setSelections('api', [{ selectionStartLineNumber: position.lineNumber, selectionStartColumn: position.column, positionLineNumber: position.lineNumber, positionColumn: position.column }]); }; CodeEditorWidget.prototype._sendRevealRange = function (modelRange, verticalType, revealHorizontal, scrollType) { if (!this._modelData) { return; } if (!range_1.Range.isIRange(modelRange)) { throw new Error('Invalid arguments'); } var validatedModelRange = this._modelData.model.validateRange(modelRange); var viewRange = this._modelData.viewModel.coordinatesConverter.convertModelRangeToViewRange(validatedModelRange); this._modelData.cursor.emitCursorRevealRange('api', viewRange, verticalType, revealHorizontal, scrollType); }; CodeEditorWidget.prototype.revealLine = function (lineNumber, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this._revealLine(lineNumber, 0 /* Simple */, scrollType); }; CodeEditorWidget.prototype.revealLineInCenter = function (lineNumber, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this._revealLine(lineNumber, 1 /* Center */, scrollType); }; CodeEditorWidget.prototype.revealLineInCenterIfOutsideViewport = function (lineNumber, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this._revealLine(lineNumber, 2 /* CenterIfOutsideViewport */, scrollType); }; CodeEditorWidget.prototype._revealLine = function (lineNumber, revealType, scrollType) { if (typeof lineNumber !== 'number') { throw new Error('Invalid arguments'); } this._sendRevealRange(new range_1.Range(lineNumber, 1, lineNumber, 1), revealType, false, scrollType); }; CodeEditorWidget.prototype.revealPosition = function (position, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this._revealPosition(position, 0 /* Simple */, true, scrollType); }; CodeEditorWidget.prototype.revealPositionInCenter = function (position, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this._revealPosition(position, 1 /* Center */, true, scrollType); }; CodeEditorWidget.prototype.revealPositionInCenterIfOutsideViewport = function (position, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this._revealPosition(position, 2 /* CenterIfOutsideViewport */, true, scrollType); }; CodeEditorWidget.prototype._revealPosition = function (position, verticalType, revealHorizontal, scrollType) { if (!position_1.Position.isIPosition(position)) { throw new Error('Invalid arguments'); } this._sendRevealRange(new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column), verticalType, revealHorizontal, scrollType); }; CodeEditorWidget.prototype.getSelection = function () { if (!this._modelData) { return null; } return this._modelData.cursor.getSelection(); }; CodeEditorWidget.prototype.getSelections = function () { if (!this._modelData) { return null; } return this._modelData.cursor.getSelections(); }; CodeEditorWidget.prototype.setSelection = function (something) { var isSelection = selection_1.Selection.isISelection(something); var isRange = range_1.Range.isIRange(something); if (!isSelection && !isRange) { throw new Error('Invalid arguments'); } if (isSelection) { this._setSelectionImpl(something); } else if (isRange) { // act as if it was an IRange var selection = { selectionStartLineNumber: something.startLineNumber, selectionStartColumn: something.startColumn, positionLineNumber: something.endLineNumber, positionColumn: something.endColumn }; this._setSelectionImpl(selection); } }; CodeEditorWidget.prototype._setSelectionImpl = function (sel) { if (!this._modelData) { return; } var selection = new selection_1.Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn); this._modelData.cursor.setSelections('api', [selection]); }; CodeEditorWidget.prototype.revealLines = function (startLineNumber, endLineNumber, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this._revealLines(startLineNumber, endLineNumber, 0 /* Simple */, scrollType); }; CodeEditorWidget.prototype.revealLinesInCenter = function (startLineNumber, endLineNumber, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this._revealLines(startLineNumber, endLineNumber, 1 /* Center */, scrollType); }; CodeEditorWidget.prototype.revealLinesInCenterIfOutsideViewport = function (startLineNumber, endLineNumber, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this._revealLines(startLineNumber, endLineNumber, 2 /* CenterIfOutsideViewport */, scrollType); }; CodeEditorWidget.prototype._revealLines = function (startLineNumber, endLineNumber, verticalType, scrollType) { if (typeof startLineNumber !== 'number' || typeof endLineNumber !== 'number') { throw new Error('Invalid arguments'); } this._sendRevealRange(new range_1.Range(startLineNumber, 1, endLineNumber, 1), verticalType, false, scrollType); }; CodeEditorWidget.prototype.revealRange = function (range, scrollType, revealVerticalInCenter, revealHorizontal) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } if (revealVerticalInCenter === void 0) { revealVerticalInCenter = false; } if (revealHorizontal === void 0) { revealHorizontal = true; } this._revealRange(range, revealVerticalInCenter ? 1 /* Center */ : 0 /* Simple */, revealHorizontal, scrollType); }; CodeEditorWidget.prototype.revealRangeInCenter = function (range, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this._revealRange(range, 1 /* Center */, true, scrollType); }; CodeEditorWidget.prototype.revealRangeInCenterIfOutsideViewport = function (range, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this._revealRange(range, 2 /* CenterIfOutsideViewport */, true, scrollType); }; CodeEditorWidget.prototype.revealRangeAtTop = function (range, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this._revealRange(range, 3 /* Top */, true, scrollType); }; CodeEditorWidget.prototype._revealRange = function (range, verticalType, revealHorizontal, scrollType) { if (!range_1.Range.isIRange(range)) { throw new Error('Invalid arguments'); } this._sendRevealRange(range_1.Range.lift(range), verticalType, revealHorizontal, scrollType); }; CodeEditorWidget.prototype.setSelections = function (ranges, source) { if (source === void 0) { source = 'api'; } if (!this._modelData) { return; } if (!ranges || ranges.length === 0) { throw new Error('Invalid arguments'); } for (var i = 0, len = ranges.length; i < len; i++) { if (!selection_1.Selection.isISelection(ranges[i])) { throw new Error('Invalid arguments'); } } this._modelData.cursor.setSelections(source, ranges); }; CodeEditorWidget.prototype.getContentWidth = function () { if (!this._modelData) { return -1; } return this._modelData.viewModel.viewLayout.getContentWidth(); }; CodeEditorWidget.prototype.getScrollWidth = function () { if (!this._modelData) { return -1; } return this._modelData.viewModel.viewLayout.getScrollWidth(); }; CodeEditorWidget.prototype.getScrollLeft = function () { if (!this._modelData) { return -1; } return this._modelData.viewModel.viewLayout.getCurrentScrollLeft(); }; CodeEditorWidget.prototype.getContentHeight = function () { if (!this._modelData) { return -1; } return this._modelData.viewModel.viewLayout.getContentHeight(); }; CodeEditorWidget.prototype.getScrollHeight = function () { if (!this._modelData) { return -1; } return this._modelData.viewModel.viewLayout.getScrollHeight(); }; CodeEditorWidget.prototype.getScrollTop = function () { if (!this._modelData) { return -1; } return this._modelData.viewModel.viewLayout.getCurrentScrollTop(); }; CodeEditorWidget.prototype.setScrollLeft = function (newScrollLeft) { if (!this._modelData) { return; } if (typeof newScrollLeft !== 'number') { throw new Error('Invalid arguments'); } this._modelData.viewModel.viewLayout.setScrollPositionNow({ scrollLeft: newScrollLeft }); }; CodeEditorWidget.prototype.setScrollTop = function (newScrollTop) { if (!this._modelData) { return; } if (typeof newScrollTop !== 'number') { throw new Error('Invalid arguments'); } this._modelData.viewModel.viewLayout.setScrollPositionNow({ scrollTop: newScrollTop }); }; CodeEditorWidget.prototype.setScrollPosition = function (position) { if (!this._modelData) { return; } this._modelData.viewModel.viewLayout.setScrollPositionNow(position); }; CodeEditorWidget.prototype.saveViewState = function () { if (!this._modelData) { return null; } var contributionsState = {}; var keys = Object.keys(this._contributions); for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { var id = keys_1[_i]; var contribution = this._contributions[id]; if (typeof contribution.saveViewState === 'function') { contributionsState[id] = contribution.saveViewState(); } } var cursorState = this._modelData.cursor.saveState(); var viewState = this._modelData.viewModel.saveState(); return { cursorState: cursorState, viewState: viewState, contributionsState: contributionsState }; }; CodeEditorWidget.prototype.restoreViewState = function (s) { if (!this._modelData || !this._modelData.hasRealView) { return; } var codeEditorState = s; if (codeEditorState && codeEditorState.cursorState && codeEditorState.viewState) { var cursorState = codeEditorState.cursorState; if (Array.isArray(cursorState)) { this._modelData.cursor.restoreState(cursorState); } else { // Backwards compatibility this._modelData.cursor.restoreState([cursorState]); } var contributionsState = codeEditorState.contributionsState || {}; var keys = Object.keys(this._contributions); for (var i = 0, len = keys.length; i < len; i++) { var id = keys[i]; var contribution = this._contributions[id]; if (typeof contribution.restoreViewState === 'function') { contribution.restoreViewState(contributionsState[id]); } } var reducedState = this._modelData.viewModel.reduceRestoreState(codeEditorState.viewState); this._modelData.view.restoreState(reducedState); } }; CodeEditorWidget.prototype.getContribution = function (id) { return (this._contributions[id] || null); }; CodeEditorWidget.prototype.getActions = function () { var result = []; var keys = Object.keys(this._actions); for (var i = 0, len = keys.length; i < len; i++) { var id = keys[i]; result.push(this._actions[id]); } return result; }; CodeEditorWidget.prototype.getSupportedActions = function () { var result = this.getActions(); result = result.filter(function (action) { return action.isSupported(); }); return result; }; CodeEditorWidget.prototype.getAction = function (id) { return this._actions[id] || null; }; CodeEditorWidget.prototype.trigger = function (source, handlerId, payload) { payload = payload || {}; // Special case for typing if (handlerId === editorCommon.Handler.Type) { if (!this._modelData || typeof payload.text !== 'string' || payload.text.length === 0) { // nothing to do return; } if (source === 'keyboard') { this._onWillType.fire(payload.text); } this._modelData.cursor.trigger(source, handlerId, payload); if (source === 'keyboard') { this._onDidType.fire(payload.text); } return; } // Special case for pasting if (handlerId === editorCommon.Handler.Paste) { if (!this._modelData || typeof payload.text !== 'string' || payload.text.length === 0) { // nothing to do return; } var startPosition = this._modelData.cursor.getSelection().getStartPosition(); this._modelData.cursor.trigger(source, handlerId, payload); var endPosition = this._modelData.cursor.getSelection().getStartPosition(); if (source === 'keyboard') { this._onDidPaste.fire({ range: new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column), mode: payload.mode }); } return; } var action = this.getAction(handlerId); if (action) { Promise.resolve(action.run()).then(undefined, errors_1.onUnexpectedError); return; } if (!this._modelData) { return; } if (this._triggerEditorCommand(source, handlerId, payload)) { return; } this._modelData.cursor.trigger(source, handlerId, payload); if (handlerId === editorCommon.Handler.CompositionStart) { this._onDidCompositionStart.fire(); } if (handlerId === editorCommon.Handler.CompositionEnd) { this._onDidCompositionEnd.fire(); } }; CodeEditorWidget.prototype._triggerEditorCommand = function (source, handlerId, payload) { var _this = this; var command = editorExtensions_1.EditorExtensionsRegistry.getEditorCommand(handlerId); if (command) { payload = payload || {}; payload.source = source; this._instantiationService.invokeFunction(function (accessor) { Promise.resolve(command.runEditorCommand(accessor, _this, payload)).then(undefined, errors_1.onUnexpectedError); }); return true; } return false; }; CodeEditorWidget.prototype._getCursors = function () { if (!this._modelData) { return null; } return this._modelData.cursor; }; CodeEditorWidget.prototype.pushUndoStop = function () { if (!this._modelData) { return false; } if (this._configuration.options.get(68 /* readOnly */)) { // read only editor => sorry! return false; } this._modelData.model.pushStackElement(); return true; }; CodeEditorWidget.prototype.executeEdits = function (source, edits, endCursorState) { if (!this._modelData) { return false; } if (this._configuration.options.get(68 /* readOnly */)) { // read only editor => sorry! return false; } var cursorStateComputer; if (!endCursorState) { cursorStateComputer = function () { return null; }; } else if (Array.isArray(endCursorState)) { cursorStateComputer = function () { return endCursorState; }; } else { cursorStateComputer = endCursorState; } this._modelData.cursor.executeEdits(source, edits, cursorStateComputer); return true; }; CodeEditorWidget.prototype.executeCommand = function (source, command) { if (!this._modelData) { return; } this._modelData.cursor.trigger(source, editorCommon.Handler.ExecuteCommand, command); }; CodeEditorWidget.prototype.executeCommands = function (source, commands) { if (!this._modelData) { return; } this._modelData.cursor.trigger(source, editorCommon.Handler.ExecuteCommands, commands); }; CodeEditorWidget.prototype.changeDecorations = function (callback) { if (!this._modelData) { // callback will not be called return null; } return this._modelData.model.changeDecorations(callback, this._id); }; CodeEditorWidget.prototype.getLineDecorations = function (lineNumber) { if (!this._modelData) { return null; } return this._modelData.model.getLineDecorations(lineNumber, this._id, editorOptions_1.filterValidationDecorations(this._configuration.options)); }; CodeEditorWidget.prototype.deltaDecorations = function (oldDecorations, newDecorations) { if (!this._modelData) { return []; } if (oldDecorations.length === 0 && newDecorations.length === 0) { return oldDecorations; } return this._modelData.model.deltaDecorations(oldDecorations, newDecorations, this._id); }; CodeEditorWidget.prototype.removeDecorations = function (decorationTypeKey) { // remove decorations for type and sub type var oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey]; if (oldDecorationsIds) { this.deltaDecorations(oldDecorationsIds, []); } if (this._decorationTypeKeysToIds.hasOwnProperty(decorationTypeKey)) { delete this._decorationTypeKeysToIds[decorationTypeKey]; } if (this._decorationTypeSubtypes.hasOwnProperty(decorationTypeKey)) { delete this._decorationTypeSubtypes[decorationTypeKey]; } }; CodeEditorWidget.prototype.getLayoutInfo = function () { var options = this._configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); return layoutInfo; }; CodeEditorWidget.prototype.createOverviewRuler = function (cssClassName) { if (!this._modelData || !this._modelData.hasRealView) { return null; } return this._modelData.view.createOverviewRuler(cssClassName); }; CodeEditorWidget.prototype.getContainerDomNode = function () { return this._domElement; }; CodeEditorWidget.prototype.getDomNode = function () { if (!this._modelData || !this._modelData.hasRealView) { return null; } return this._modelData.view.domNode.domNode; }; CodeEditorWidget.prototype.delegateVerticalScrollbarMouseDown = function (browserEvent) { if (!this._modelData || !this._modelData.hasRealView) { return; } this._modelData.view.delegateVerticalScrollbarMouseDown(browserEvent); }; CodeEditorWidget.prototype.layout = function (dimension) { this._configuration.observeReferenceElement(dimension); this.render(); }; CodeEditorWidget.prototype.focus = function () { if (!this._modelData || !this._modelData.hasRealView) { return; } this._modelData.view.focus(); }; CodeEditorWidget.prototype.hasTextFocus = function () { if (!this._modelData || !this._modelData.hasRealView) { return false; } return this._modelData.view.isFocused(); }; CodeEditorWidget.prototype.hasWidgetFocus = function () { return this._focusTracker && this._focusTracker.hasFocus(); }; CodeEditorWidget.prototype.addContentWidget = function (widget) { var widgetData = { widget: widget, position: widget.getPosition() }; if (this._contentWidgets.hasOwnProperty(widget.getId())) { console.warn('Overwriting a content widget with the same id.'); } this._contentWidgets[widget.getId()] = widgetData; if (this._modelData && this._modelData.hasRealView) { this._modelData.view.addContentWidget(widgetData); } }; CodeEditorWidget.prototype.layoutContentWidget = function (widget) { var widgetId = widget.getId(); if (this._contentWidgets.hasOwnProperty(widgetId)) { var widgetData = this._contentWidgets[widgetId]; widgetData.position = widget.getPosition(); if (this._modelData && this._modelData.hasRealView) { this._modelData.view.layoutContentWidget(widgetData); } } }; CodeEditorWidget.prototype.removeContentWidget = function (widget) { var widgetId = widget.getId(); if (this._contentWidgets.hasOwnProperty(widgetId)) { var widgetData = this._contentWidgets[widgetId]; delete this._contentWidgets[widgetId]; if (this._modelData && this._modelData.hasRealView) { this._modelData.view.removeContentWidget(widgetData); } } }; CodeEditorWidget.prototype.addOverlayWidget = function (widget) { var widgetData = { widget: widget, position: widget.getPosition() }; if (this._overlayWidgets.hasOwnProperty(widget.getId())) { console.warn('Overwriting an overlay widget with the same id.'); } this._overlayWidgets[widget.getId()] = widgetData; if (this._modelData && this._modelData.hasRealView) { this._modelData.view.addOverlayWidget(widgetData); } }; CodeEditorWidget.prototype.layoutOverlayWidget = function (widget) { var widgetId = widget.getId(); if (this._overlayWidgets.hasOwnProperty(widgetId)) { var widgetData = this._overlayWidgets[widgetId]; widgetData.position = widget.getPosition(); if (this._modelData && this._modelData.hasRealView) { this._modelData.view.layoutOverlayWidget(widgetData); } } }; CodeEditorWidget.prototype.removeOverlayWidget = function (widget) { var widgetId = widget.getId(); if (this._overlayWidgets.hasOwnProperty(widgetId)) { var widgetData = this._overlayWidgets[widgetId]; delete this._overlayWidgets[widgetId]; if (this._modelData && this._modelData.hasRealView) { this._modelData.view.removeOverlayWidget(widgetData); } } }; CodeEditorWidget.prototype.changeViewZones = function (callback) { if (!this._modelData || !this._modelData.hasRealView) { return; } var hasChanges = this._modelData.view.change(callback); if (hasChanges) { this._onDidChangeViewZones.fire(); } }; CodeEditorWidget.prototype.getTargetAtClientPoint = function (clientX, clientY) { if (!this._modelData || !this._modelData.hasRealView) { return null; } return this._modelData.view.getTargetAtClientPoint(clientX, clientY); }; CodeEditorWidget.prototype.getScrolledVisiblePosition = function (rawPosition) { if (!this._modelData || !this._modelData.hasRealView) { return null; } var position = this._modelData.model.validatePosition(rawPosition); var options = this._configuration.options; var layoutInfo = options.get(107 /* layoutInfo */); var top = CodeEditorWidget._getVerticalOffsetForPosition(this._modelData, position.lineNumber, position.column) - this.getScrollTop(); var left = this._modelData.view.getOffsetForColumn(position.lineNumber, position.column) + layoutInfo.glyphMarginWidth + layoutInfo.lineNumbersWidth + layoutInfo.decorationsWidth - this.getScrollLeft(); return { top: top, left: left, height: options.get(49 /* lineHeight */) }; }; CodeEditorWidget.prototype.getOffsetForColumn = function (lineNumber, column) { if (!this._modelData || !this._modelData.hasRealView) { return -1; } return this._modelData.view.getOffsetForColumn(lineNumber, column); }; CodeEditorWidget.prototype.render = function (forceRedraw) { if (forceRedraw === void 0) { forceRedraw = false; } if (!this._modelData || !this._modelData.hasRealView) { return; } this._modelData.view.render(true, forceRedraw); }; CodeEditorWidget.prototype.setAriaOptions = function (options) { if (!this._modelData || !this._modelData.hasRealView) { return; } this._modelData.view.setAriaOptions(options); }; CodeEditorWidget.prototype.applyFontInfo = function (target) { configuration_1.Configuration.applyFontInfoSlow(target, this._configuration.options.get(34 /* fontInfo */)); }; CodeEditorWidget.prototype._attachModel = function (model) { var _this = this; if (!model) { this._modelData = null; return; } var listenersToRemove = []; this._domElement.setAttribute('data-mode-id', model.getLanguageIdentifier().language); this._configuration.setIsDominatedByLongLines(model.isDominatedByLongLines()); this._configuration.setMaxLineNumber(model.getLineCount()); model.onBeforeAttached(); var viewModel = new viewModelImpl_1.ViewModel(this._id, this._configuration, model, domLineBreaksComputer_1.DOMLineBreaksComputerFactory.create(), monospaceLineBreaksComputer_1.MonospaceLineBreaksComputerFactory.create(this._configuration.options), function (callback) { return dom.scheduleAtNextAnimationFrame(callback); }); listenersToRemove.push(model.onDidChangeDecorations(function (e) { return _this._onDidChangeModelDecorations.fire(e); })); listenersToRemove.push(model.onDidChangeLanguage(function (e) { _this._domElement.setAttribute('data-mode-id', model.getLanguageIdentifier().language); _this._onDidChangeModelLanguage.fire(e); })); listenersToRemove.push(model.onDidChangeLanguageConfiguration(function (e) { return _this._onDidChangeModelLanguageConfiguration.fire(e); })); listenersToRemove.push(model.onDidChangeContent(function (e) { return _this._onDidChangeModelContent.fire(e); })); listenersToRemove.push(model.onDidChangeOptions(function (e) { return _this._onDidChangeModelOptions.fire(e); })); // Someone might destroy the model from under the editor, so prevent any exceptions by setting a null model listenersToRemove.push(model.onWillDispose(function () { return _this.setModel(null); })); var cursor = new cursor_1.Cursor(this._configuration, model, viewModel); listenersToRemove.push(cursor.onDidReachMaxCursorCount(function () { _this._notificationService.warn(nls.localize(0, null, cursor_1.Cursor.MAX_CURSOR_COUNT)); })); listenersToRemove.push(cursor.onDidAttemptReadOnlyEdit(function () { _this._onDidAttemptReadOnlyEdit.fire(undefined); })); listenersToRemove.push(cursor.onDidChange(function (e) { var positions = []; for (var i = 0, len = e.selections.length; i < len; i++) { positions[i] = e.selections[i].getPosition(); } var e1 = { position: positions[0], secondaryPositions: positions.slice(1), reason: e.reason, source: e.source }; _this._onDidChangeCursorPosition.fire(e1); var e2 = { selection: e.selections[0], secondarySelections: e.selections.slice(1), modelVersionId: e.modelVersionId, oldSelections: e.oldSelections, oldModelVersionId: e.oldModelVersionId, source: e.source, reason: e.reason }; _this._onDidChangeCursorSelection.fire(e2); })); var _a = this._createView(viewModel, cursor), view = _a[0], hasRealView = _a[1]; if (hasRealView) { this._domElement.appendChild(view.domNode.domNode); var keys = Object.keys(this._contentWidgets); for (var i = 0, len = keys.length; i < len; i++) { var widgetId = keys[i]; view.addContentWidget(this._contentWidgets[widgetId]); } keys = Object.keys(this._overlayWidgets); for (var i = 0, len = keys.length; i < len; i++) { var widgetId = keys[i]; view.addOverlayWidget(this._overlayWidgets[widgetId]); } view.render(false, true); view.domNode.domNode.setAttribute('data-uri', model.uri.toString()); } this._modelData = new ModelData(model, viewModel, cursor, view, hasRealView, listenersToRemove); }; CodeEditorWidget.prototype._createView = function (viewModel, cursor) { var _this = this; var commandDelegate; if (this.isSimpleWidget) { commandDelegate = { executeEditorCommand: function (editorCommand, args) { editorCommand.runCoreEditorCommand(cursor, args); }, paste: function (source, text, pasteOnNewLine, multicursorText, mode) { _this.trigger(source, editorCommon.Handler.Paste, { text: text, pasteOnNewLine: pasteOnNewLine, multicursorText: multicursorText, mode: mode }); }, type: function (source, text) { _this.trigger(source, editorCommon.Handler.Type, { text: text }); }, replacePreviousChar: function (source, text, replaceCharCnt) { _this.trigger(source, editorCommon.Handler.ReplacePreviousChar, { text: text, replaceCharCnt: replaceCharCnt }); }, compositionStart: function (source) { _this.trigger(source, editorCommon.Handler.CompositionStart, undefined); }, compositionEnd: function (source) { _this.trigger(source, editorCommon.Handler.CompositionEnd, undefined); }, cut: function (source) { _this.trigger(source, editorCommon.Handler.Cut, undefined); } }; } else { commandDelegate = { executeEditorCommand: function (editorCommand, args) { editorCommand.runCoreEditorCommand(cursor, args); }, paste: function (source, text, pasteOnNewLine, multicursorText, mode) { _this._commandService.executeCommand(editorCommon.Handler.Paste, { text: text, pasteOnNewLine: pasteOnNewLine, multicursorText: multicursorText, mode: mode }); }, type: function (source, text) { _this._commandService.executeCommand(editorCommon.Handler.Type, { text: text }); }, replacePreviousChar: function (source, text, replaceCharCnt) { _this._commandService.executeCommand(editorCommon.Handler.ReplacePreviousChar, { text: text, replaceCharCnt: replaceCharCnt }); }, compositionStart: function (source) { _this._commandService.executeCommand(editorCommon.Handler.CompositionStart, {}); }, compositionEnd: function (source) { _this._commandService.executeCommand(editorCommon.Handler.CompositionEnd, {}); }, cut: function (source) { _this._commandService.executeCommand(editorCommon.Handler.Cut, {}); } }; } var viewOutgoingEvents = new viewOutgoingEvents_1.ViewOutgoingEvents(viewModel); viewOutgoingEvents.onDidContentSizeChange = function (e) { return _this._onDidContentSizeChange.fire(e); }; viewOutgoingEvents.onDidScroll = function (e) { return _this._onDidScrollChange.fire(e); }; viewOutgoingEvents.onDidGainFocus = function () { return _this._editorTextFocus.setValue(true); }; viewOutgoingEvents.onDidLoseFocus = function () { return _this._editorTextFocus.setValue(false); }; viewOutgoingEvents.onContextMenu = function (e) { return _this._onContextMenu.fire(e); }; viewOutgoingEvents.onMouseDown = function (e) { return _this._onMouseDown.fire(e); }; viewOutgoingEvents.onMouseUp = function (e) { return _this._onMouseUp.fire(e); }; viewOutgoingEvents.onMouseDrag = function (e) { return _this._onMouseDrag.fire(e); }; viewOutgoingEvents.onMouseDrop = function (e) { return _this._onMouseDrop.fire(e); }; viewOutgoingEvents.onKeyUp = function (e) { return _this._onKeyUp.fire(e); }; viewOutgoingEvents.onMouseMove = function (e) { return _this._onMouseMove.fire(e); }; viewOutgoingEvents.onMouseLeave = function (e) { return _this._onMouseLeave.fire(e); }; viewOutgoingEvents.onMouseWheel = function (e) { return _this._onMouseWheel.fire(e); }; viewOutgoingEvents.onKeyDown = function (e) { return _this._onKeyDown.fire(e); }; var view = new viewImpl_1.View(commandDelegate, this._configuration, this._themeService, viewModel, cursor, viewOutgoingEvents); return [view, true]; }; CodeEditorWidget.prototype._postDetachModelCleanup = function (detachedModel) { if (detachedModel) { detachedModel.removeAllDecorationsWithOwnerId(this._id); } }; CodeEditorWidget.prototype._detachModel = function () { if (!this._modelData) { return null; } var model = this._modelData.model; var removeDomNode = this._modelData.hasRealView ? this._modelData.view.domNode.domNode : null; this._modelData.dispose(); this._modelData = null; this._domElement.removeAttribute('data-mode-id'); if (removeDomNode) { this._domElement.removeChild(removeDomNode); } return model; }; CodeEditorWidget.prototype._removeDecorationType = function (key) { this._codeEditorService.removeDecorationType(key); }; CodeEditorWidget.prototype.hasModel = function () { return (this._modelData !== null); }; CodeEditorWidget = __decorate([ __param(3, instantiation_1.IInstantiationService), __param(4, codeEditorService_1.ICodeEditorService), __param(5, commands_1.ICommandService), __param(6, contextkey_1.IContextKeyService), __param(7, themeService_1.IThemeService), __param(8, notification_1.INotificationService), __param(9, accessibility_1.IAccessibilityService) ], CodeEditorWidget); return CodeEditorWidget; }(lifecycle_1.Disposable)); exports.CodeEditorWidget = CodeEditorWidget; var BooleanEventEmitter = /** @class */ (function (_super) { __extends(BooleanEventEmitter, _super); function BooleanEventEmitter() { var _this = _super.call(this) || this; _this._onDidChangeToTrue = _this._register(new event_1.Emitter()); _this.onDidChangeToTrue = _this._onDidChangeToTrue.event; _this._onDidChangeToFalse = _this._register(new event_1.Emitter()); _this.onDidChangeToFalse = _this._onDidChangeToFalse.event; _this._value = 0 /* NotSet */; return _this; } BooleanEventEmitter.prototype.setValue = function (_value) { var value = (_value ? 2 /* True */ : 1 /* False */); if (this._value === value) { return; } this._value = value; if (this._value === 2 /* True */) { this._onDidChangeToTrue.fire(); } else if (this._value === 1 /* False */) { this._onDidChangeToFalse.fire(); } }; return BooleanEventEmitter; }(lifecycle_1.Disposable)); exports.BooleanEventEmitter = BooleanEventEmitter; var EditorContextKeysManager = /** @class */ (function (_super) { __extends(EditorContextKeysManager, _super); function EditorContextKeysManager(editor, contextKeyService) { var _this = _super.call(this) || this; _this._editor = editor; contextKeyService.createKey('editorId', editor.getId()); _this._editorSimpleInput = editorContextKeys_1.EditorContextKeys.editorSimpleInput.bindTo(contextKeyService); _this._editorFocus = editorContextKeys_1.EditorContextKeys.focus.bindTo(contextKeyService); _this._textInputFocus = editorContextKeys_1.EditorContextKeys.textInputFocus.bindTo(contextKeyService); _this._editorTextFocus = editorContextKeys_1.EditorContextKeys.editorTextFocus.bindTo(contextKeyService); _this._editorTabMovesFocus = editorContextKeys_1.EditorContextKeys.tabMovesFocus.bindTo(contextKeyService); _this._editorReadonly = editorContextKeys_1.EditorContextKeys.readOnly.bindTo(contextKeyService); _this._hasMultipleSelections = editorContextKeys_1.EditorContextKeys.hasMultipleSelections.bindTo(contextKeyService); _this._hasNonEmptySelection = editorContextKeys_1.EditorContextKeys.hasNonEmptySelection.bindTo(contextKeyService); _this._canUndo = editorContextKeys_1.EditorContextKeys.canUndo.bindTo(contextKeyService); _this._canRedo = editorContextKeys_1.EditorContextKeys.canRedo.bindTo(contextKeyService); _this._register(_this._editor.onDidChangeConfiguration(function () { return _this._updateFromConfig(); })); _this._register(_this._editor.onDidChangeCursorSelection(function () { return _this._updateFromSelection(); })); _this._register(_this._editor.onDidFocusEditorWidget(function () { return _this._updateFromFocus(); })); _this._register(_this._editor.onDidBlurEditorWidget(function () { return _this._updateFromFocus(); })); _this._register(_this._editor.onDidFocusEditorText(function () { return _this._updateFromFocus(); })); _this._register(_this._editor.onDidBlurEditorText(function () { return _this._updateFromFocus(); })); _this._register(_this._editor.onDidChangeModel(function () { return _this._updateFromModel(); })); _this._register(_this._editor.onDidChangeConfiguration(function () { return _this._updateFromModel(); })); _this._updateFromConfig(); _this._updateFromSelection(); _this._updateFromFocus(); _this._updateFromModel(); _this._editorSimpleInput.set(_this._editor.isSimpleWidget); return _this; } EditorContextKeysManager.prototype._updateFromConfig = function () { var options = this._editor.getOptions(); this._editorTabMovesFocus.set(options.get(106 /* tabFocusMode */)); this._editorReadonly.set(options.get(68 /* readOnly */)); }; EditorContextKeysManager.prototype._updateFromSelection = function () { var selections = this._editor.getSelections(); if (!selections) { this._hasMultipleSelections.reset(); this._hasNonEmptySelection.reset(); } else { this._hasMultipleSelections.set(selections.length > 1); this._hasNonEmptySelection.set(selections.some(function (s) { return !s.isEmpty(); })); } }; EditorContextKeysManager.prototype._updateFromFocus = function () { this._editorFocus.set(this._editor.hasWidgetFocus() && !this._editor.isSimpleWidget); this._editorTextFocus.set(this._editor.hasTextFocus() && !this._editor.isSimpleWidget); this._textInputFocus.set(this._editor.hasTextFocus()); }; EditorContextKeysManager.prototype._updateFromModel = function () { var model = this._editor.getModel(); this._canUndo.set(Boolean(model && model.canUndo())); this._canRedo.set(Boolean(model && model.canRedo())); }; return EditorContextKeysManager; }(lifecycle_1.Disposable)); var EditorModeContext = /** @class */ (function (_super) { __extends(EditorModeContext, _super); function EditorModeContext(_editor, _contextKeyService) { var _this = _super.call(this) || this; _this._editor = _editor; _this._contextKeyService = _contextKeyService; _this._langId = editorContextKeys_1.EditorContextKeys.languageId.bindTo(_contextKeyService); _this._hasCompletionItemProvider = editorContextKeys_1.EditorContextKeys.hasCompletionItemProvider.bindTo(_contextKeyService); _this._hasCodeActionsProvider = editorContextKeys_1.EditorContextKeys.hasCodeActionsProvider.bindTo(_contextKeyService); _this._hasCodeLensProvider = editorContextKeys_1.EditorContextKeys.hasCodeLensProvider.bindTo(_contextKeyService); _this._hasDefinitionProvider = editorContextKeys_1.EditorContextKeys.hasDefinitionProvider.bindTo(_contextKeyService); _this._hasDeclarationProvider = editorContextKeys_1.EditorContextKeys.hasDeclarationProvider.bindTo(_contextKeyService); _this._hasImplementationProvider = editorContextKeys_1.EditorContextKeys.hasImplementationProvider.bindTo(_contextKeyService); _this._hasTypeDefinitionProvider = editorContextKeys_1.EditorContextKeys.hasTypeDefinitionProvider.bindTo(_contextKeyService); _this._hasHoverProvider = editorContextKeys_1.EditorContextKeys.hasHoverProvider.bindTo(_contextKeyService); _this._hasDocumentHighlightProvider = editorContextKeys_1.EditorContextKeys.hasDocumentHighlightProvider.bindTo(_contextKeyService); _this._hasDocumentSymbolProvider = editorContextKeys_1.EditorContextKeys.hasDocumentSymbolProvider.bindTo(_contextKeyService); _this._hasReferenceProvider = editorContextKeys_1.EditorContextKeys.hasReferenceProvider.bindTo(_contextKeyService); _this._hasRenameProvider = editorContextKeys_1.EditorContextKeys.hasRenameProvider.bindTo(_contextKeyService); _this._hasSignatureHelpProvider = editorContextKeys_1.EditorContextKeys.hasSignatureHelpProvider.bindTo(_contextKeyService); _this._hasDocumentFormattingProvider = editorContextKeys_1.EditorContextKeys.hasDocumentFormattingProvider.bindTo(_contextKeyService); _this._hasDocumentSelectionFormattingProvider = editorContextKeys_1.EditorContextKeys.hasDocumentSelectionFormattingProvider.bindTo(_contextKeyService); _this._hasMultipleDocumentFormattingProvider = editorContextKeys_1.EditorContextKeys.hasMultipleDocumentFormattingProvider.bindTo(_contextKeyService); _this._hasMultipleDocumentSelectionFormattingProvider = editorContextKeys_1.EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider.bindTo(_contextKeyService); _this._isInWalkThrough = editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.bindTo(_contextKeyService); var update = function () { return _this._update(); }; // update when model/mode changes _this._register(_editor.onDidChangeModel(update)); _this._register(_editor.onDidChangeModelLanguage(update)); // update when registries change _this._register(modes.CompletionProviderRegistry.onDidChange(update)); _this._register(modes.CodeActionProviderRegistry.onDidChange(update)); _this._register(modes.CodeLensProviderRegistry.onDidChange(update)); _this._register(modes.DefinitionProviderRegistry.onDidChange(update)); _this._register(modes.DeclarationProviderRegistry.onDidChange(update)); _this._register(modes.ImplementationProviderRegistry.onDidChange(update)); _this._register(modes.TypeDefinitionProviderRegistry.onDidChange(update)); _this._register(modes.HoverProviderRegistry.onDidChange(update)); _this._register(modes.DocumentHighlightProviderRegistry.onDidChange(update)); _this._register(modes.DocumentSymbolProviderRegistry.onDidChange(update)); _this._register(modes.ReferenceProviderRegistry.onDidChange(update)); _this._register(modes.RenameProviderRegistry.onDidChange(update)); _this._register(modes.DocumentFormattingEditProviderRegistry.onDidChange(update)); _this._register(modes.DocumentRangeFormattingEditProviderRegistry.onDidChange(update)); _this._register(modes.SignatureHelpProviderRegistry.onDidChange(update)); update(); return _this; } EditorModeContext.prototype.dispose = function () { _super.prototype.dispose.call(this); }; EditorModeContext.prototype.reset = function () { var _this = this; this._contextKeyService.bufferChangeEvents(function () { _this._langId.reset(); _this._hasCompletionItemProvider.reset(); _this._hasCodeActionsProvider.reset(); _this._hasCodeLensProvider.reset(); _this._hasDefinitionProvider.reset(); _this._hasDeclarationProvider.reset(); _this._hasImplementationProvider.reset(); _this._hasTypeDefinitionProvider.reset(); _this._hasHoverProvider.reset(); _this._hasDocumentHighlightProvider.reset(); _this._hasDocumentSymbolProvider.reset(); _this._hasReferenceProvider.reset(); _this._hasRenameProvider.reset(); _this._hasDocumentFormattingProvider.reset(); _this._hasDocumentSelectionFormattingProvider.reset(); _this._hasSignatureHelpProvider.reset(); _this._isInWalkThrough.reset(); }); }; EditorModeContext.prototype._update = function () { var _this = this; var model = this._editor.getModel(); if (!model) { this.reset(); return; } this._contextKeyService.bufferChangeEvents(function () { _this._langId.set(model.getLanguageIdentifier().language); _this._hasCompletionItemProvider.set(modes.CompletionProviderRegistry.has(model)); _this._hasCodeActionsProvider.set(modes.CodeActionProviderRegistry.has(model)); _this._hasCodeLensProvider.set(modes.CodeLensProviderRegistry.has(model)); _this._hasDefinitionProvider.set(modes.DefinitionProviderRegistry.has(model)); _this._hasDeclarationProvider.set(modes.DeclarationProviderRegistry.has(model)); _this._hasImplementationProvider.set(modes.ImplementationProviderRegistry.has(model)); _this._hasTypeDefinitionProvider.set(modes.TypeDefinitionProviderRegistry.has(model)); _this._hasHoverProvider.set(modes.HoverProviderRegistry.has(model)); _this._hasDocumentHighlightProvider.set(modes.DocumentHighlightProviderRegistry.has(model)); _this._hasDocumentSymbolProvider.set(modes.DocumentSymbolProviderRegistry.has(model)); _this._hasReferenceProvider.set(modes.ReferenceProviderRegistry.has(model)); _this._hasRenameProvider.set(modes.RenameProviderRegistry.has(model)); _this._hasSignatureHelpProvider.set(modes.SignatureHelpProviderRegistry.has(model)); _this._hasDocumentFormattingProvider.set(modes.DocumentFormattingEditProviderRegistry.has(model) || modes.DocumentRangeFormattingEditProviderRegistry.has(model)); _this._hasDocumentSelectionFormattingProvider.set(modes.DocumentRangeFormattingEditProviderRegistry.has(model)); _this._hasMultipleDocumentFormattingProvider.set(modes.DocumentFormattingEditProviderRegistry.all(model).length + modes.DocumentRangeFormattingEditProviderRegistry.all(model).length > 1); _this._hasMultipleDocumentSelectionFormattingProvider.set(modes.DocumentRangeFormattingEditProviderRegistry.all(model).length > 1); _this._isInWalkThrough.set(model.uri.scheme === network_1.Schemas.walkThroughSnippet); }); }; return EditorModeContext; }(lifecycle_1.Disposable)); exports.EditorModeContext = EditorModeContext; var CodeEditorWidgetFocusTracker = /** @class */ (function (_super) { __extends(CodeEditorWidgetFocusTracker, _super); function CodeEditorWidgetFocusTracker(domElement) { var _this = _super.call(this) || this; _this._onChange = _this._register(new event_1.Emitter()); _this.onChange = _this._onChange.event; _this._hasFocus = false; _this._domFocusTracker = _this._register(dom.trackFocus(domElement)); _this._register(_this._domFocusTracker.onDidFocus(function () { _this._hasFocus = true; _this._onChange.fire(undefined); })); _this._register(_this._domFocusTracker.onDidBlur(function () { _this._hasFocus = false; _this._onChange.fire(undefined); })); return _this; } CodeEditorWidgetFocusTracker.prototype.hasFocus = function () { return this._hasFocus; }; return CodeEditorWidgetFocusTracker; }(lifecycle_1.Disposable)); var squigglyStart = encodeURIComponent(""); function getSquigglySVGData(color) { return squigglyStart + encodeURIComponent(color.toString()) + squigglyEnd; } var dotdotdotStart = encodeURIComponent(""); function getDotDotDotSVGData(color) { return dotdotdotStart + encodeURIComponent(color.toString()) + dotdotdotEnd; } themeService_1.registerThemingParticipant(function (theme, collector) { var errorBorderColor = theme.getColor(colorRegistry_1.editorErrorBorder); if (errorBorderColor) { collector.addRule(".monaco-editor ." + "squiggly-error" /* EditorErrorDecoration */ + " { border-bottom: 4px double " + errorBorderColor + "; }"); } var errorForeground = theme.getColor(colorRegistry_1.editorErrorForeground); if (errorForeground) { collector.addRule(".monaco-editor ." + "squiggly-error" /* EditorErrorDecoration */ + " { background: url(\"data:image/svg+xml," + getSquigglySVGData(errorForeground) + "\") repeat-x bottom left; }"); } var warningBorderColor = theme.getColor(colorRegistry_1.editorWarningBorder); if (warningBorderColor) { collector.addRule(".monaco-editor ." + "squiggly-warning" /* EditorWarningDecoration */ + " { border-bottom: 4px double " + warningBorderColor + "; }"); } var warningForeground = theme.getColor(colorRegistry_1.editorWarningForeground); if (warningForeground) { collector.addRule(".monaco-editor ." + "squiggly-warning" /* EditorWarningDecoration */ + " { background: url(\"data:image/svg+xml," + getSquigglySVGData(warningForeground) + "\") repeat-x bottom left; }"); } var infoBorderColor = theme.getColor(colorRegistry_1.editorInfoBorder); if (infoBorderColor) { collector.addRule(".monaco-editor ." + "squiggly-info" /* EditorInfoDecoration */ + " { border-bottom: 4px double " + infoBorderColor + "; }"); } var infoForeground = theme.getColor(colorRegistry_1.editorInfoForeground); if (infoForeground) { collector.addRule(".monaco-editor ." + "squiggly-info" /* EditorInfoDecoration */ + " { background: url(\"data:image/svg+xml," + getSquigglySVGData(infoForeground) + "\") repeat-x bottom left; }"); } var hintBorderColor = theme.getColor(colorRegistry_1.editorHintBorder); if (hintBorderColor) { collector.addRule(".monaco-editor ." + "squiggly-hint" /* EditorHintDecoration */ + " { border-bottom: 2px dotted " + hintBorderColor + "; }"); } var hintForeground = theme.getColor(colorRegistry_1.editorHintForeground); if (hintForeground) { collector.addRule(".monaco-editor ." + "squiggly-hint" /* EditorHintDecoration */ + " { background: url(\"data:image/svg+xml," + getDotDotDotSVGData(hintForeground) + "\") no-repeat bottom left; }"); } var unnecessaryForeground = theme.getColor(editorColorRegistry_1.editorUnnecessaryCodeOpacity); if (unnecessaryForeground) { collector.addRule(".monaco-editor.showUnused ." + "squiggly-inline-unnecessary" /* EditorUnnecessaryInlineDecoration */ + " { opacity: " + unnecessaryForeground.rgba.a + "; }"); } var unnecessaryBorder = theme.getColor(editorColorRegistry_1.editorUnnecessaryCodeBorder); if (unnecessaryBorder) { collector.addRule(".monaco-editor.showUnused ." + "squiggly-unnecessary" /* EditorUnnecessaryDecoration */ + " { border-bottom: 2px dashed " + unnecessaryBorder + "; }"); } var deprecatedForeground = theme.getColor(colorRegistry_1.editorForeground) || 'inherit'; collector.addRule(".monaco-editor ." + "squiggly-inline-deprecated" /* EditorDeprecatedInlineDecoration */ + " { text-decoration: line-through; text-decoration-color: " + deprecatedForeground + "}"); }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[564/*vs/editor/browser/widget/diffReview*/], __M([0/*require*/,1/*exports*/,419/*vs/nls!vs/editor/browser/widget/diffReview*/,6/*vs/base/browser/dom*/,28/*vs/base/browser/fastDomNode*/,70/*vs/base/browser/ui/actionbar/actionbar*/,53/*vs/base/browser/ui/scrollbar/scrollableElement*/,55/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,60/*vs/editor/browser/config/configuration*/,12/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,33/*vs/editor/common/config/editorOptions*/,93/*vs/editor/common/core/lineTokens*/,13/*vs/editor/common/core/position*/,44/*vs/editor/common/view/editorColorRegistry*/,110/*vs/editor/common/viewLayout/viewLineRenderer*/,69/*vs/editor/common/viewModel/viewModel*/,18/*vs/platform/contextkey/common/contextkey*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,300/*vs/css!vs/editor/browser/widget/media/diffReview*/]), function (require, exports, nls, dom, fastDomNode_1, actionbar_1, scrollableElement_1, actions_1, lifecycle_1, configuration_1, editorExtensions_1, codeEditorService_1, editorOptions_1, lineTokens_1, position_1, editorColorRegistry_1, viewLineRenderer_1, viewModel_1, contextkey_1, colorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DIFF_LINES_PADDING = 3; var DiffEntry = /** @class */ (function () { function DiffEntry(originalLineStart, originalLineEnd, modifiedLineStart, modifiedLineEnd) { this.originalLineStart = originalLineStart; this.originalLineEnd = originalLineEnd; this.modifiedLineStart = modifiedLineStart; this.modifiedLineEnd = modifiedLineEnd; } DiffEntry.prototype.getType = function () { if (this.originalLineStart === 0) { return 1 /* Insert */; } if (this.modifiedLineStart === 0) { return 2 /* Delete */; } return 0 /* Equal */; }; return DiffEntry; }()); var Diff = /** @class */ (function () { function Diff(entries) { this.entries = entries; } return Diff; }()); var DiffReview = /** @class */ (function (_super) { __extends(DiffReview, _super); function DiffReview(diffEditor) { var _this = _super.call(this) || this; _this._width = 0; _this._diffEditor = diffEditor; _this._isVisible = false; _this.shadow = fastDomNode_1.createFastDomNode(document.createElement('div')); _this.shadow.setClassName('diff-review-shadow'); _this.actionBarContainer = fastDomNode_1.createFastDomNode(document.createElement('div')); _this.actionBarContainer.setClassName('diff-review-actions'); _this._actionBar = _this._register(new actionbar_1.ActionBar(_this.actionBarContainer.domNode)); _this._actionBar.push(new actions_1.Action('diffreview.close', nls.localize(0, null), 'close-diff-review', true, function () { _this.hide(); return Promise.resolve(null); }), { label: false, icon: true }); _this.domNode = fastDomNode_1.createFastDomNode(document.createElement('div')); _this.domNode.setClassName('diff-review monaco-editor-background'); _this._content = fastDomNode_1.createFastDomNode(document.createElement('div')); _this._content.setClassName('diff-review-content'); _this.scrollbar = _this._register(new scrollableElement_1.DomScrollableElement(_this._content.domNode, {})); _this.domNode.domNode.appendChild(_this.scrollbar.getDomNode()); _this._register(diffEditor.onDidUpdateDiff(function () { if (!_this._isVisible) { return; } _this._diffs = _this._compute(); _this._render(); })); _this._register(diffEditor.getModifiedEditor().onDidChangeCursorPosition(function () { if (!_this._isVisible) { return; } _this._render(); })); _this._register(diffEditor.getOriginalEditor().onDidFocusEditorWidget(function () { if (_this._isVisible) { _this.hide(); } })); _this._register(diffEditor.getModifiedEditor().onDidFocusEditorWidget(function () { if (_this._isVisible) { _this.hide(); } })); _this._register(dom.addStandardDisposableListener(_this.domNode.domNode, 'click', function (e) { e.preventDefault(); var row = dom.findParentWithClass(e.target, 'diff-review-row'); if (row) { _this._goToRow(row); } })); _this._register(dom.addStandardDisposableListener(_this.domNode.domNode, 'keydown', function (e) { if (e.equals(18 /* DownArrow */) || e.equals(2048 /* CtrlCmd */ | 18 /* DownArrow */) || e.equals(512 /* Alt */ | 18 /* DownArrow */)) { e.preventDefault(); _this._goToRow(_this._getNextRow()); } if (e.equals(16 /* UpArrow */) || e.equals(2048 /* CtrlCmd */ | 16 /* UpArrow */) || e.equals(512 /* Alt */ | 16 /* UpArrow */)) { e.preventDefault(); _this._goToRow(_this._getPrevRow()); } if (e.equals(9 /* Escape */) || e.equals(2048 /* CtrlCmd */ | 9 /* Escape */) || e.equals(512 /* Alt */ | 9 /* Escape */) || e.equals(1024 /* Shift */ | 9 /* Escape */)) { e.preventDefault(); _this.hide(); } if (e.equals(10 /* Space */) || e.equals(3 /* Enter */)) { e.preventDefault(); _this.accept(); } })); _this._diffs = []; _this._currentDiff = null; return _this; } DiffReview.prototype.prev = function () { var index = 0; if (!this._isVisible) { this._diffs = this._compute(); } if (this._isVisible) { var currentIndex = -1; for (var i = 0, len = this._diffs.length; i < len; i++) { if (this._diffs[i] === this._currentDiff) { currentIndex = i; break; } } index = (this._diffs.length + currentIndex - 1); } else { index = this._findDiffIndex(this._diffEditor.getPosition()); } if (this._diffs.length === 0) { // Nothing to do return; } index = index % this._diffs.length; this._diffEditor.setPosition(new position_1.Position(this._diffs[index].entries[0].modifiedLineStart, 1)); this._isVisible = true; this._diffEditor.doLayout(); this._render(); this._goToRow(this._getNextRow()); }; DiffReview.prototype.next = function () { var index = 0; if (!this._isVisible) { this._diffs = this._compute(); } if (this._isVisible) { var currentIndex = -1; for (var i = 0, len = this._diffs.length; i < len; i++) { if (this._diffs[i] === this._currentDiff) { currentIndex = i; break; } } index = (currentIndex + 1); } else { index = this._findDiffIndex(this._diffEditor.getPosition()); } if (this._diffs.length === 0) { // Nothing to do return; } index = index % this._diffs.length; this._diffEditor.setPosition(new position_1.Position(this._diffs[index].entries[0].modifiedLineStart, 1)); this._isVisible = true; this._diffEditor.doLayout(); this._render(); this._goToRow(this._getNextRow()); }; DiffReview.prototype.accept = function () { var jumpToLineNumber = -1; var current = this._getCurrentFocusedRow(); if (current) { var lineNumber = parseInt(current.getAttribute('data-line'), 10); if (!isNaN(lineNumber)) { jumpToLineNumber = lineNumber; } } this.hide(); if (jumpToLineNumber !== -1) { this._diffEditor.setPosition(new position_1.Position(jumpToLineNumber, 1)); this._diffEditor.revealPosition(new position_1.Position(jumpToLineNumber, 1), 1 /* Immediate */); } }; DiffReview.prototype.hide = function () { this._isVisible = false; this._diffEditor.focus(); this._diffEditor.doLayout(); this._render(); }; DiffReview.prototype._getPrevRow = function () { var current = this._getCurrentFocusedRow(); if (!current) { return this._getFirstRow(); } if (current.previousElementSibling) { return current.previousElementSibling; } return current; }; DiffReview.prototype._getNextRow = function () { var current = this._getCurrentFocusedRow(); if (!current) { return this._getFirstRow(); } if (current.nextElementSibling) { return current.nextElementSibling; } return current; }; DiffReview.prototype._getFirstRow = function () { return this.domNode.domNode.querySelector('.diff-review-row'); }; DiffReview.prototype._getCurrentFocusedRow = function () { var result = document.activeElement; if (result && /diff-review-row/.test(result.className)) { return result; } return null; }; DiffReview.prototype._goToRow = function (row) { var prev = this._getCurrentFocusedRow(); row.tabIndex = 0; row.focus(); if (prev && prev !== row) { prev.tabIndex = -1; } this.scrollbar.scanDomNode(); }; DiffReview.prototype.isVisible = function () { return this._isVisible; }; DiffReview.prototype.layout = function (top, width, height) { this._width = width; this.shadow.setTop(top - 6); this.shadow.setWidth(width); this.shadow.setHeight(this._isVisible ? 6 : 0); this.domNode.setTop(top); this.domNode.setWidth(width); this.domNode.setHeight(height); this._content.setHeight(height); this._content.setWidth(width); if (this._isVisible) { this.actionBarContainer.setAttribute('aria-hidden', 'false'); this.actionBarContainer.setDisplay('block'); } else { this.actionBarContainer.setAttribute('aria-hidden', 'true'); this.actionBarContainer.setDisplay('none'); } }; DiffReview.prototype._compute = function () { var lineChanges = this._diffEditor.getLineChanges(); if (!lineChanges || lineChanges.length === 0) { return []; } var originalModel = this._diffEditor.getOriginalEditor().getModel(); var modifiedModel = this._diffEditor.getModifiedEditor().getModel(); if (!originalModel || !modifiedModel) { return []; } return DiffReview._mergeAdjacent(lineChanges, originalModel.getLineCount(), modifiedModel.getLineCount()); }; DiffReview._mergeAdjacent = function (lineChanges, originalLineCount, modifiedLineCount) { if (!lineChanges || lineChanges.length === 0) { return []; } var diffs = [], diffsLength = 0; for (var i = 0, len = lineChanges.length; i < len; i++) { var lineChange = lineChanges[i]; var originalStart = lineChange.originalStartLineNumber; var originalEnd = lineChange.originalEndLineNumber; var modifiedStart = lineChange.modifiedStartLineNumber; var modifiedEnd = lineChange.modifiedEndLineNumber; var r_1 = [], rLength_1 = 0; // Emit before anchors { var originalEqualAbove = (originalEnd === 0 ? originalStart : originalStart - 1); var modifiedEqualAbove = (modifiedEnd === 0 ? modifiedStart : modifiedStart - 1); // Make sure we don't step into the previous diff var minOriginal = 1; var minModified = 1; if (i > 0) { var prevLineChange = lineChanges[i - 1]; if (prevLineChange.originalEndLineNumber === 0) { minOriginal = prevLineChange.originalStartLineNumber + 1; } else { minOriginal = prevLineChange.originalEndLineNumber + 1; } if (prevLineChange.modifiedEndLineNumber === 0) { minModified = prevLineChange.modifiedStartLineNumber + 1; } else { minModified = prevLineChange.modifiedEndLineNumber + 1; } } var fromOriginal = originalEqualAbove - DIFF_LINES_PADDING + 1; var fromModified = modifiedEqualAbove - DIFF_LINES_PADDING + 1; if (fromOriginal < minOriginal) { var delta = minOriginal - fromOriginal; fromOriginal = fromOriginal + delta; fromModified = fromModified + delta; } if (fromModified < minModified) { var delta = minModified - fromModified; fromOriginal = fromOriginal + delta; fromModified = fromModified + delta; } r_1[rLength_1++] = new DiffEntry(fromOriginal, originalEqualAbove, fromModified, modifiedEqualAbove); } // Emit deleted lines { if (originalEnd !== 0) { r_1[rLength_1++] = new DiffEntry(originalStart, originalEnd, 0, 0); } } // Emit inserted lines { if (modifiedEnd !== 0) { r_1[rLength_1++] = new DiffEntry(0, 0, modifiedStart, modifiedEnd); } } // Emit after anchors { var originalEqualBelow = (originalEnd === 0 ? originalStart + 1 : originalEnd + 1); var modifiedEqualBelow = (modifiedEnd === 0 ? modifiedStart + 1 : modifiedEnd + 1); // Make sure we don't step into the next diff var maxOriginal = originalLineCount; var maxModified = modifiedLineCount; if (i + 1 < len) { var nextLineChange = lineChanges[i + 1]; if (nextLineChange.originalEndLineNumber === 0) { maxOriginal = nextLineChange.originalStartLineNumber; } else { maxOriginal = nextLineChange.originalStartLineNumber - 1; } if (nextLineChange.modifiedEndLineNumber === 0) { maxModified = nextLineChange.modifiedStartLineNumber; } else { maxModified = nextLineChange.modifiedStartLineNumber - 1; } } var toOriginal = originalEqualBelow + DIFF_LINES_PADDING - 1; var toModified = modifiedEqualBelow + DIFF_LINES_PADDING - 1; if (toOriginal > maxOriginal) { var delta = maxOriginal - toOriginal; toOriginal = toOriginal + delta; toModified = toModified + delta; } if (toModified > maxModified) { var delta = maxModified - toModified; toOriginal = toOriginal + delta; toModified = toModified + delta; } r_1[rLength_1++] = new DiffEntry(originalEqualBelow, toOriginal, modifiedEqualBelow, toModified); } diffs[diffsLength++] = new Diff(r_1); } // Merge adjacent diffs var curr = diffs[0].entries; var r = [], rLength = 0; for (var i = 1, len = diffs.length; i < len; i++) { var thisDiff = diffs[i].entries; var currLast = curr[curr.length - 1]; var thisFirst = thisDiff[0]; if (currLast.getType() === 0 /* Equal */ && thisFirst.getType() === 0 /* Equal */ && thisFirst.originalLineStart <= currLast.originalLineEnd) { // We are dealing with equal lines that overlap curr[curr.length - 1] = new DiffEntry(currLast.originalLineStart, thisFirst.originalLineEnd, currLast.modifiedLineStart, thisFirst.modifiedLineEnd); curr = curr.concat(thisDiff.slice(1)); continue; } r[rLength++] = new Diff(curr); curr = thisDiff; } r[rLength++] = new Diff(curr); return r; }; DiffReview.prototype._findDiffIndex = function (pos) { var lineNumber = pos.lineNumber; for (var i = 0, len = this._diffs.length; i < len; i++) { var diff = this._diffs[i].entries; var lastModifiedLine = diff[diff.length - 1].modifiedLineEnd; if (lineNumber <= lastModifiedLine) { return i; } } return 0; }; DiffReview.prototype._render = function () { var originalOptions = this._diffEditor.getOriginalEditor().getOptions(); var modifiedOptions = this._diffEditor.getModifiedEditor().getOptions(); var originalModel = this._diffEditor.getOriginalEditor().getModel(); var modifiedModel = this._diffEditor.getModifiedEditor().getModel(); var originalModelOpts = originalModel.getOptions(); var modifiedModelOpts = modifiedModel.getOptions(); if (!this._isVisible || !originalModel || !modifiedModel) { dom.clearNode(this._content.domNode); this._currentDiff = null; this.scrollbar.scanDomNode(); return; } var diffIndex = this._findDiffIndex(this._diffEditor.getPosition()); if (this._diffs[diffIndex] === this._currentDiff) { return; } this._currentDiff = this._diffs[diffIndex]; var diffs = this._diffs[diffIndex].entries; var container = document.createElement('div'); container.className = 'diff-review-table'; container.setAttribute('role', 'list'); configuration_1.Configuration.applyFontInfoSlow(container, modifiedOptions.get(34 /* fontInfo */)); var minOriginalLine = 0; var maxOriginalLine = 0; var minModifiedLine = 0; var maxModifiedLine = 0; for (var i = 0, len = diffs.length; i < len; i++) { var diffEntry = diffs[i]; var originalLineStart = diffEntry.originalLineStart; var originalLineEnd = diffEntry.originalLineEnd; var modifiedLineStart = diffEntry.modifiedLineStart; var modifiedLineEnd = diffEntry.modifiedLineEnd; if (originalLineStart !== 0 && ((minOriginalLine === 0 || originalLineStart < minOriginalLine))) { minOriginalLine = originalLineStart; } if (originalLineEnd !== 0 && ((maxOriginalLine === 0 || originalLineEnd > maxOriginalLine))) { maxOriginalLine = originalLineEnd; } if (modifiedLineStart !== 0 && ((minModifiedLine === 0 || modifiedLineStart < minModifiedLine))) { minModifiedLine = modifiedLineStart; } if (modifiedLineEnd !== 0 && ((maxModifiedLine === 0 || modifiedLineEnd > maxModifiedLine))) { maxModifiedLine = modifiedLineEnd; } } var header = document.createElement('div'); header.className = 'diff-review-row'; var cell = document.createElement('div'); cell.className = 'diff-review-cell diff-review-summary'; var originalChangedLinesCnt = maxOriginalLine - minOriginalLine + 1; var modifiedChangedLinesCnt = maxModifiedLine - minModifiedLine + 1; cell.appendChild(document.createTextNode(diffIndex + 1 + "/" + this._diffs.length + ": @@ -" + minOriginalLine + "," + originalChangedLinesCnt + " +" + minModifiedLine + "," + modifiedChangedLinesCnt + " @@")); header.setAttribute('data-line', String(minModifiedLine)); var getAriaLines = function (lines) { if (lines === 0) { return nls.localize(1, null); } else if (lines === 1) { return nls.localize(2, null); } else { return nls.localize(3, null, lines); } }; var originalChangedLinesCntAria = getAriaLines(originalChangedLinesCnt); var modifiedChangedLinesCntAria = getAriaLines(modifiedChangedLinesCnt); header.setAttribute('aria-label', nls.localize(4, null, (diffIndex + 1), this._diffs.length, minOriginalLine, originalChangedLinesCntAria, minModifiedLine, modifiedChangedLinesCntAria)); header.appendChild(cell); // @@ -504,7 +517,7 @@ header.setAttribute('role', 'listitem'); container.appendChild(header); var modLine = minModifiedLine; for (var i = 0, len = diffs.length; i < len; i++) { var diffEntry = diffs[i]; DiffReview._renderSection(container, diffEntry, modLine, this._width, originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts); if (diffEntry.modifiedLineStart !== 0) { modLine = diffEntry.modifiedLineEnd; } } dom.clearNode(this._content.domNode); this._content.domNode.appendChild(container); this.scrollbar.scanDomNode(); }; DiffReview._renderSection = function (dest, diffEntry, modLine, width, originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts) { var type = diffEntry.getType(); var rowClassName = 'diff-review-row'; var lineNumbersExtraClassName = ''; var spacerClassName = 'diff-review-spacer'; switch (type) { case 1 /* Insert */: rowClassName = 'diff-review-row line-insert'; lineNumbersExtraClassName = ' char-insert'; spacerClassName = 'diff-review-spacer insert-sign'; break; case 2 /* Delete */: rowClassName = 'diff-review-row line-delete'; lineNumbersExtraClassName = ' char-delete'; spacerClassName = 'diff-review-spacer delete-sign'; break; } var originalLineStart = diffEntry.originalLineStart; var originalLineEnd = diffEntry.originalLineEnd; var modifiedLineStart = diffEntry.modifiedLineStart; var modifiedLineEnd = diffEntry.modifiedLineEnd; var cnt = Math.max(modifiedLineEnd - modifiedLineStart, originalLineEnd - originalLineStart); var originalLayoutInfo = originalOptions.get(107 /* layoutInfo */); var originalLineNumbersWidth = originalLayoutInfo.glyphMarginWidth + originalLayoutInfo.lineNumbersWidth; var modifiedLayoutInfo = modifiedOptions.get(107 /* layoutInfo */); var modifiedLineNumbersWidth = 10 + modifiedLayoutInfo.glyphMarginWidth + modifiedLayoutInfo.lineNumbersWidth; for (var i = 0; i <= cnt; i++) { var originalLine = (originalLineStart === 0 ? 0 : originalLineStart + i); var modifiedLine = (modifiedLineStart === 0 ? 0 : modifiedLineStart + i); var row = document.createElement('div'); row.style.minWidth = width + 'px'; row.className = rowClassName; row.setAttribute('role', 'listitem'); if (modifiedLine !== 0) { modLine = modifiedLine; } row.setAttribute('data-line', String(modLine)); var cell = document.createElement('div'); cell.className = 'diff-review-cell'; row.appendChild(cell); var originalLineNumber = document.createElement('span'); originalLineNumber.style.width = (originalLineNumbersWidth + 'px'); originalLineNumber.style.minWidth = (originalLineNumbersWidth + 'px'); originalLineNumber.className = 'diff-review-line-number' + lineNumbersExtraClassName; if (originalLine !== 0) { originalLineNumber.appendChild(document.createTextNode(String(originalLine))); } else { originalLineNumber.innerHTML = ' '; } cell.appendChild(originalLineNumber); var modifiedLineNumber = document.createElement('span'); modifiedLineNumber.style.width = (modifiedLineNumbersWidth + 'px'); modifiedLineNumber.style.minWidth = (modifiedLineNumbersWidth + 'px'); modifiedLineNumber.style.paddingRight = '10px'; modifiedLineNumber.className = 'diff-review-line-number' + lineNumbersExtraClassName; if (modifiedLine !== 0) { modifiedLineNumber.appendChild(document.createTextNode(String(modifiedLine))); } else { modifiedLineNumber.innerHTML = ' '; } cell.appendChild(modifiedLineNumber); var spacer = document.createElement('span'); spacer.className = spacerClassName; spacer.innerHTML = '  '; cell.appendChild(spacer); var lineContent = void 0; if (modifiedLine !== 0) { cell.insertAdjacentHTML('beforeend', this._renderLine(modifiedModel, modifiedOptions, modifiedModelOpts.tabSize, modifiedLine)); lineContent = modifiedModel.getLineContent(modifiedLine); } else { cell.insertAdjacentHTML('beforeend', this._renderLine(originalModel, originalOptions, originalModelOpts.tabSize, originalLine)); lineContent = originalModel.getLineContent(originalLine); } if (lineContent.length === 0) { lineContent = nls.localize(5, null); } var ariaLabel = ''; switch (type) { case 0 /* Equal */: ariaLabel = nls.localize(6, null, originalLine, modifiedLine, lineContent); break; case 1 /* Insert */: ariaLabel = nls.localize(7, null, modifiedLine, lineContent); break; case 2 /* Delete */: ariaLabel = nls.localize(8, null, originalLine, lineContent); break; } row.setAttribute('aria-label', ariaLabel); dest.appendChild(row); } }; DiffReview._renderLine = function (model, options, tabSize, lineNumber) { var lineContent = model.getLineContent(lineNumber); var fontInfo = options.get(34 /* fontInfo */); var defaultMetadata = ((0 /* None */ << 11 /* FONT_STYLE_OFFSET */) | (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */) | (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0; var tokens = new Uint32Array(2); tokens[0] = lineContent.length; tokens[1] = defaultMetadata; var lineTokens = new lineTokens_1.LineTokens(tokens, lineContent); var isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(lineContent, model.mightContainNonBasicASCII()); var containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(lineContent, isBasicASCII, model.mightContainRTL()); var r = viewLineRenderer_1.renderViewLine2(new viewLineRenderer_1.RenderLineInput((fontInfo.isMonospace && !options.get(23 /* disableMonospaceOptimizations */)), fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII, containsRTL, 0, lineTokens, [], tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, options.get(88 /* stopRenderingLineAfter */), options.get(74 /* renderWhitespace */), options.get(69 /* renderControlCharacters */), options.get(35 /* fontLigatures */) !== editorOptions_1.EditorFontLigatures.OFF, null)); return r.html; }; return DiffReview; }(lifecycle_1.Disposable)); exports.DiffReview = DiffReview; // theming themeService_1.registerThemingParticipant(function (theme, collector) { var lineNumbers = theme.getColor(editorColorRegistry_1.editorLineNumbers); if (lineNumbers) { collector.addRule(".monaco-diff-editor .diff-review-line-number { color: " + lineNumbers + "; }"); } var shadow = theme.getColor(colorRegistry_1.scrollbarShadow); if (shadow) { collector.addRule(".monaco-diff-editor .diff-review-shadow { box-shadow: " + shadow + " 0 -6px 6px -6px inset; }"); } }); var DiffReviewNext = /** @class */ (function (_super) { __extends(DiffReviewNext, _super); function DiffReviewNext() { return _super.call(this, { id: 'editor.action.diffReview.next', label: nls.localize(9, null), alias: 'Go to Next Difference', precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'), kbOpts: { kbExpr: null, primary: 65 /* F7 */, weight: 100 /* EditorContrib */ } }) || this; } DiffReviewNext.prototype.run = function (accessor, editor) { var diffEditor = findFocusedDiffEditor(accessor); if (diffEditor) { diffEditor.diffReviewNext(); } }; return DiffReviewNext; }(editorExtensions_1.EditorAction)); var DiffReviewPrev = /** @class */ (function (_super) { __extends(DiffReviewPrev, _super); function DiffReviewPrev() { return _super.call(this, { id: 'editor.action.diffReview.prev', label: nls.localize(10, null), alias: 'Go to Previous Difference', precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'), kbOpts: { kbExpr: null, primary: 1024 /* Shift */ | 65 /* F7 */, weight: 100 /* EditorContrib */ } }) || this; } DiffReviewPrev.prototype.run = function (accessor, editor) { var diffEditor = findFocusedDiffEditor(accessor); if (diffEditor) { diffEditor.diffReviewPrev(); } }; return DiffReviewPrev; }(editorExtensions_1.EditorAction)); function findFocusedDiffEditor(accessor) { var codeEditorService = accessor.get(codeEditorService_1.ICodeEditorService); var diffEditors = codeEditorService.listDiffEditors(); for (var i = 0, len = diffEditors.length; i < len; i++) { var diffEditor = diffEditors[i]; if (diffEditor.hasWidgetFocus()) { return diffEditor; } } return null; } editorExtensions_1.registerEditorAction(DiffReviewNext); editorExtensions_1.registerEditorAction(DiffReviewPrev); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[230/*vs/editor/browser/widget/diffEditorWidget*/], __M([0/*require*/,1/*exports*/,418/*vs/nls!vs/editor/browser/widget/diffEditorWidget*/,6/*vs/base/browser/dom*/,28/*vs/base/browser/fastDomNode*/,104/*vs/base/browser/ui/sash/sash*/,15/*vs/base/common/async*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,31/*vs/base/common/objects*/,60/*vs/editor/browser/config/configuration*/,67/*vs/editor/browser/core/editorState*/,32/*vs/editor/browser/services/codeEditorService*/,121/*vs/editor/browser/widget/codeEditorWidget*/,564/*vs/editor/browser/widget/diffReview*/,33/*vs/editor/common/config/editorOptions*/,3/*vs/editor/common/core/range*/,106/*vs/editor/common/core/stringBuilder*/,68/*vs/editor/common/editorCommon*/,30/*vs/editor/common/model/textModel*/,62/*vs/editor/common/services/editorWorkerService*/,193/*vs/editor/common/view/overviewZoneManager*/,148/*vs/editor/common/viewLayout/lineDecorations*/,110/*vs/editor/common/viewLayout/viewLineRenderer*/,69/*vs/editor/common/viewModel/viewModel*/,18/*vs/platform/contextkey/common/contextkey*/,11/*vs/platform/instantiation/common/instantiation*/,115/*vs/platform/instantiation/common/serviceCollection*/,35/*vs/platform/notification/common/notification*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,66/*vs/platform/contextview/browser/contextView*/,421/*vs/editor/browser/widget/inlineDiffMargin*/,12/*vs/editor/browser/editorExtensions*/,10/*vs/base/common/errors*/,73/*vs/platform/progress/common/progress*/,185/*vs/editor/browser/config/elementSizeObserver*/,299/*vs/css!vs/editor/browser/widget/media/diffEditor*/]), function (require, exports, nls, dom, fastDomNode_1, sash_1, async_1, event_1, lifecycle_1, objects, configuration_1, editorState_1, codeEditorService_1, codeEditorWidget_1, diffReview_1, editorOptions_1, range_1, stringBuilder_1, editorCommon, textModel_1, editorWorkerService_1, overviewZoneManager_1, lineDecorations_1, viewLineRenderer_1, viewModel_1, contextkey_1, instantiation_1, serviceCollection_1, notification_1, colorRegistry_1, themeService_1, contextView_1, inlineDiffMargin_1, editorExtensions_1, errors_1, progress_1, elementSizeObserver_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var VisualEditorState = /** @class */ (function () { function VisualEditorState(_contextMenuService, _clipboardService) { this._contextMenuService = _contextMenuService; this._clipboardService = _clipboardService; this._zones = []; this.inlineDiffMargins = []; this._zonesMap = {}; this._decorations = []; } VisualEditorState.prototype.getForeignViewZones = function (allViewZones) { var _this = this; return allViewZones.filter(function (z) { return !_this._zonesMap[String(z.id)]; }); }; VisualEditorState.prototype.clean = function (editor) { var _this = this; // (1) View zones if (this._zones.length > 0) { editor.changeViewZones(function (viewChangeAccessor) { for (var i = 0, length_1 = _this._zones.length; i < length_1; i++) { viewChangeAccessor.removeZone(_this._zones[i]); } }); } this._zones = []; this._zonesMap = {}; // (2) Model decorations this._decorations = editor.deltaDecorations(this._decorations, []); }; VisualEditorState.prototype.apply = function (editor, overviewRuler, newDecorations, restoreScrollState) { var _this = this; var scrollState = restoreScrollState ? editorState_1.StableEditorScrollState.capture(editor) : null; // view zones editor.changeViewZones(function (viewChangeAccessor) { for (var i = 0, length_2 = _this._zones.length; i < length_2; i++) { viewChangeAccessor.removeZone(_this._zones[i]); } for (var i = 0, length_3 = _this.inlineDiffMargins.length; i < length_3; i++) { _this.inlineDiffMargins[i].dispose(); } _this._zones = []; _this._zonesMap = {}; _this.inlineDiffMargins = []; for (var i = 0, length_4 = newDecorations.zones.length; i < length_4; i++) { var viewZone = newDecorations.zones[i]; viewZone.suppressMouseDown = true; var zoneId = viewChangeAccessor.addZone(viewZone); _this._zones.push(zoneId); _this._zonesMap[String(zoneId)] = true; if (newDecorations.zones[i].diff && viewZone.marginDomNode && _this._clipboardService) { viewZone.suppressMouseDown = false; _this.inlineDiffMargins.push(new inlineDiffMargin_1.InlineDiffMargin(zoneId, viewZone.marginDomNode, editor, newDecorations.zones[i].diff, _this._contextMenuService, _this._clipboardService)); } } }); if (scrollState) { scrollState.restore(editor); } // decorations this._decorations = editor.deltaDecorations(this._decorations, newDecorations.decorations); // overview ruler if (overviewRuler) { overviewRuler.setZones(newDecorations.overviewZones); } }; return VisualEditorState; }()); var DIFF_EDITOR_ID = 0; var DiffEditorWidget = /** @class */ (function (_super) { __extends(DiffEditorWidget, _super); function DiffEditorWidget(domElement, options, clipboardService, editorWorkerService, contextKeyService, instantiationService, codeEditorService, themeService, notificationService, contextMenuService, _editorProgressService) { var _this = _super.call(this) || this; _this._editorProgressService = _editorProgressService; _this._onDidDispose = _this._register(new event_1.Emitter()); _this.onDidDispose = _this._onDidDispose.event; _this._onDidUpdateDiff = _this._register(new event_1.Emitter()); _this.onDidUpdateDiff = _this._onDidUpdateDiff.event; _this._lastOriginalWarning = null; _this._lastModifiedWarning = null; _this._editorWorkerService = editorWorkerService; _this._codeEditorService = codeEditorService; _this._contextKeyService = _this._register(contextKeyService.createScoped(domElement)); _this._contextKeyService.createKey('isInDiffEditor', true); _this._themeService = themeService; _this._notificationService = notificationService; _this.id = (++DIFF_EDITOR_ID); _this._state = 0 /* Idle */; _this._updatingDiffProgress = null; _this._domElement = domElement; options = options || {}; // renderSideBySide _this._renderSideBySide = true; if (typeof options.renderSideBySide !== 'undefined') { _this._renderSideBySide = options.renderSideBySide; } // maxComputationTime _this._maxComputationTime = 5000; if (typeof options.maxComputationTime !== 'undefined') { _this._maxComputationTime = options.maxComputationTime; } // ignoreTrimWhitespace _this._ignoreTrimWhitespace = true; if (typeof options.ignoreTrimWhitespace !== 'undefined') { _this._ignoreTrimWhitespace = options.ignoreTrimWhitespace; } // renderIndicators _this._renderIndicators = true; if (typeof options.renderIndicators !== 'undefined') { _this._renderIndicators = options.renderIndicators; } _this._originalIsEditable = false; if (typeof options.originalEditable !== 'undefined') { _this._originalIsEditable = Boolean(options.originalEditable); } _this._updateDecorationsRunner = _this._register(new async_1.RunOnceScheduler(function () { return _this._updateDecorations(); }, 0)); _this._containerDomElement = document.createElement('div'); _this._containerDomElement.className = DiffEditorWidget._getClassName(_this._themeService.getTheme(), _this._renderSideBySide); _this._containerDomElement.style.position = 'relative'; _this._containerDomElement.style.height = '100%'; _this._domElement.appendChild(_this._containerDomElement); _this._overviewViewportDomElement = fastDomNode_1.createFastDomNode(document.createElement('div')); _this._overviewViewportDomElement.setClassName('diffViewport'); _this._overviewViewportDomElement.setPosition('absolute'); _this._overviewDomElement = document.createElement('div'); _this._overviewDomElement.className = 'diffOverview'; _this._overviewDomElement.style.position = 'absolute'; _this._overviewDomElement.appendChild(_this._overviewViewportDomElement.domNode); _this._register(dom.addStandardDisposableListener(_this._overviewDomElement, 'mousedown', function (e) { _this.modifiedEditor.delegateVerticalScrollbarMouseDown(e); })); _this._containerDomElement.appendChild(_this._overviewDomElement); // Create left side _this._originalDomNode = document.createElement('div'); _this._originalDomNode.className = 'editor original'; _this._originalDomNode.style.position = 'absolute'; _this._originalDomNode.style.height = '100%'; _this._containerDomElement.appendChild(_this._originalDomNode); // Create right side _this._modifiedDomNode = document.createElement('div'); _this._modifiedDomNode.className = 'editor modified'; _this._modifiedDomNode.style.position = 'absolute'; _this._modifiedDomNode.style.height = '100%'; _this._containerDomElement.appendChild(_this._modifiedDomNode); _this._beginUpdateDecorationsTimeout = -1; _this._currentlyChangingViewZones = false; _this._diffComputationToken = 0; _this._originalEditorState = new VisualEditorState(contextMenuService, clipboardService); _this._modifiedEditorState = new VisualEditorState(contextMenuService, clipboardService); _this._isVisible = true; _this._isHandlingScrollEvent = false; _this._elementSizeObserver = _this._register(new elementSizeObserver_1.ElementSizeObserver(_this._containerDomElement, undefined, function () { return _this._onDidContainerSizeChanged(); })); if (options.automaticLayout) { _this._elementSizeObserver.startObserving(); } _this._diffComputationResult = null; var leftContextKeyService = _this._contextKeyService.createScoped(); leftContextKeyService.createKey('isInDiffLeftEditor', true); var leftServices = new serviceCollection_1.ServiceCollection(); leftServices.set(contextkey_1.IContextKeyService, leftContextKeyService); var leftScopedInstantiationService = instantiationService.createChild(leftServices); var rightContextKeyService = _this._contextKeyService.createScoped(); rightContextKeyService.createKey('isInDiffRightEditor', true); var rightServices = new serviceCollection_1.ServiceCollection(); rightServices.set(contextkey_1.IContextKeyService, rightContextKeyService); var rightScopedInstantiationService = instantiationService.createChild(rightServices); _this.originalEditor = _this._createLeftHandSideEditor(options, leftScopedInstantiationService); _this.modifiedEditor = _this._createRightHandSideEditor(options, rightScopedInstantiationService); _this._originalOverviewRuler = null; _this._modifiedOverviewRuler = null; _this._reviewPane = new diffReview_1.DiffReview(_this); _this._containerDomElement.appendChild(_this._reviewPane.domNode.domNode); _this._containerDomElement.appendChild(_this._reviewPane.shadow.domNode); _this._containerDomElement.appendChild(_this._reviewPane.actionBarContainer.domNode); // enableSplitViewResizing _this._enableSplitViewResizing = true; if (typeof options.enableSplitViewResizing !== 'undefined') { _this._enableSplitViewResizing = options.enableSplitViewResizing; } if (_this._renderSideBySide) { _this._setStrategy(new DiffEditorWidgetSideBySide(_this._createDataSource(), _this._enableSplitViewResizing)); } else { _this._setStrategy(new DiffEditorWidgetInline(_this._createDataSource(), _this._enableSplitViewResizing)); } _this._register(themeService.onThemeChange(function (t) { if (_this._strategy && _this._strategy.applyColors(t)) { _this._updateDecorationsRunner.schedule(); } _this._containerDomElement.className = DiffEditorWidget._getClassName(_this._themeService.getTheme(), _this._renderSideBySide); })); var contributions = editorExtensions_1.EditorExtensionsRegistry.getDiffEditorContributions(); for (var _i = 0, contributions_1 = contributions; _i < contributions_1.length; _i++) { var desc = contributions_1[_i]; try { _this._register(instantiationService.createInstance(desc.ctor, _this)); } catch (err) { errors_1.onUnexpectedError(err); } } _this._codeEditorService.addDiffEditor(_this); return _this; } DiffEditorWidget.prototype._setState = function (newState) { if (this._state === newState) { return; } this._state = newState; if (this._updatingDiffProgress) { this._updatingDiffProgress.done(); this._updatingDiffProgress = null; } if (this._state === 1 /* ComputingDiff */) { this._updatingDiffProgress = this._editorProgressService.show(true, 1000); } }; DiffEditorWidget.prototype.hasWidgetFocus = function () { return dom.isAncestor(document.activeElement, this._domElement); }; DiffEditorWidget.prototype.diffReviewNext = function () { this._reviewPane.next(); }; DiffEditorWidget.prototype.diffReviewPrev = function () { this._reviewPane.prev(); }; DiffEditorWidget._getClassName = function (theme, renderSideBySide) { var result = 'monaco-diff-editor monaco-editor-background '; if (renderSideBySide) { result += 'side-by-side '; } result += themeService_1.getThemeTypeSelector(theme.type); return result; }; DiffEditorWidget.prototype._recreateOverviewRulers = function () { if (this._originalOverviewRuler) { this._overviewDomElement.removeChild(this._originalOverviewRuler.getDomNode()); this._originalOverviewRuler.dispose(); } if (this.originalEditor.hasModel()) { this._originalOverviewRuler = this.originalEditor.createOverviewRuler('original diffOverviewRuler'); this._overviewDomElement.appendChild(this._originalOverviewRuler.getDomNode()); } if (this._modifiedOverviewRuler) { this._overviewDomElement.removeChild(this._modifiedOverviewRuler.getDomNode()); this._modifiedOverviewRuler.dispose(); } if (this.modifiedEditor.hasModel()) { this._modifiedOverviewRuler = this.modifiedEditor.createOverviewRuler('modified diffOverviewRuler'); this._overviewDomElement.appendChild(this._modifiedOverviewRuler.getDomNode()); } this._layoutOverviewRulers(); }; DiffEditorWidget.prototype._createLeftHandSideEditor = function (options, instantiationService) { var _this = this; var editor = this._createInnerEditor(instantiationService, this._originalDomNode, this._adjustOptionsForLeftHandSide(options, this._originalIsEditable)); this._register(editor.onDidScrollChange(function (e) { if (_this._isHandlingScrollEvent) { return; } if (!e.scrollTopChanged && !e.scrollLeftChanged && !e.scrollHeightChanged) { return; } _this._isHandlingScrollEvent = true; _this.modifiedEditor.setScrollPosition({ scrollLeft: e.scrollLeft, scrollTop: e.scrollTop }); _this._isHandlingScrollEvent = false; _this._layoutOverviewViewport(); })); this._register(editor.onDidChangeViewZones(function () { _this._onViewZonesChanged(); })); this._register(editor.onDidChangeModelContent(function () { if (_this._isVisible) { _this._beginUpdateDecorationsSoon(); } })); return editor; }; DiffEditorWidget.prototype._createRightHandSideEditor = function (options, instantiationService) { var _this = this; var editor = this._createInnerEditor(instantiationService, this._modifiedDomNode, this._adjustOptionsForRightHandSide(options)); this._register(editor.onDidScrollChange(function (e) { if (_this._isHandlingScrollEvent) { return; } if (!e.scrollTopChanged && !e.scrollLeftChanged && !e.scrollHeightChanged) { return; } _this._isHandlingScrollEvent = true; _this.originalEditor.setScrollPosition({ scrollLeft: e.scrollLeft, scrollTop: e.scrollTop }); _this._isHandlingScrollEvent = false; _this._layoutOverviewViewport(); })); this._register(editor.onDidChangeViewZones(function () { _this._onViewZonesChanged(); })); this._register(editor.onDidChangeConfiguration(function (e) { if (e.hasChanged(34 /* fontInfo */) && editor.getModel()) { _this._onViewZonesChanged(); } })); this._register(editor.onDidChangeModelContent(function () { if (_this._isVisible) { _this._beginUpdateDecorationsSoon(); } })); this._register(editor.onDidChangeModelOptions(function (e) { if (e.tabSize) { _this._updateDecorationsRunner.schedule(); } })); return editor; }; DiffEditorWidget.prototype._createInnerEditor = function (instantiationService, container, options) { return instantiationService.createInstance(codeEditorWidget_1.CodeEditorWidget, container, options, {}); }; DiffEditorWidget.prototype.dispose = function () { this._codeEditorService.removeDiffEditor(this); if (this._beginUpdateDecorationsTimeout !== -1) { window.clearTimeout(this._beginUpdateDecorationsTimeout); this._beginUpdateDecorationsTimeout = -1; } this._cleanViewZonesAndDecorations(); if (this._originalOverviewRuler) { this._overviewDomElement.removeChild(this._originalOverviewRuler.getDomNode()); this._originalOverviewRuler.dispose(); } if (this._modifiedOverviewRuler) { this._overviewDomElement.removeChild(this._modifiedOverviewRuler.getDomNode()); this._modifiedOverviewRuler.dispose(); } this._overviewDomElement.removeChild(this._overviewViewportDomElement.domNode); this._containerDomElement.removeChild(this._overviewDomElement); this._containerDomElement.removeChild(this._originalDomNode); this.originalEditor.dispose(); this._containerDomElement.removeChild(this._modifiedDomNode); this.modifiedEditor.dispose(); this._strategy.dispose(); this._containerDomElement.removeChild(this._reviewPane.domNode.domNode); this._containerDomElement.removeChild(this._reviewPane.shadow.domNode); this._containerDomElement.removeChild(this._reviewPane.actionBarContainer.domNode); this._reviewPane.dispose(); this._domElement.removeChild(this._containerDomElement); this._onDidDispose.fire(); _super.prototype.dispose.call(this); }; //------------ begin IDiffEditor methods DiffEditorWidget.prototype.getId = function () { return this.getEditorType() + ':' + this.id; }; DiffEditorWidget.prototype.getEditorType = function () { return editorCommon.EditorType.IDiffEditor; }; DiffEditorWidget.prototype.getLineChanges = function () { if (!this._diffComputationResult) { return null; } return this._diffComputationResult.changes; }; DiffEditorWidget.prototype.getOriginalEditor = function () { return this.originalEditor; }; DiffEditorWidget.prototype.getModifiedEditor = function () { return this.modifiedEditor; }; DiffEditorWidget.prototype.updateOptions = function (newOptions) { // Handle side by side var renderSideBySideChanged = false; if (typeof newOptions.renderSideBySide !== 'undefined') { if (this._renderSideBySide !== newOptions.renderSideBySide) { this._renderSideBySide = newOptions.renderSideBySide; renderSideBySideChanged = true; } } if (typeof newOptions.maxComputationTime !== 'undefined') { this._maxComputationTime = newOptions.maxComputationTime; if (this._isVisible) { this._beginUpdateDecorationsSoon(); } } var beginUpdateDecorations = false; if (typeof newOptions.ignoreTrimWhitespace !== 'undefined') { if (this._ignoreTrimWhitespace !== newOptions.ignoreTrimWhitespace) { this._ignoreTrimWhitespace = newOptions.ignoreTrimWhitespace; // Begin comparing beginUpdateDecorations = true; } } if (typeof newOptions.renderIndicators !== 'undefined') { if (this._renderIndicators !== newOptions.renderIndicators) { this._renderIndicators = newOptions.renderIndicators; beginUpdateDecorations = true; } } if (beginUpdateDecorations) { this._beginUpdateDecorations(); } if (typeof newOptions.originalEditable !== 'undefined') { this._originalIsEditable = Boolean(newOptions.originalEditable); } this.modifiedEditor.updateOptions(this._adjustOptionsForRightHandSide(newOptions)); this.originalEditor.updateOptions(this._adjustOptionsForLeftHandSide(newOptions, this._originalIsEditable)); // enableSplitViewResizing if (typeof newOptions.enableSplitViewResizing !== 'undefined') { this._enableSplitViewResizing = newOptions.enableSplitViewResizing; } this._strategy.setEnableSplitViewResizing(this._enableSplitViewResizing); // renderSideBySide if (renderSideBySideChanged) { if (this._renderSideBySide) { this._setStrategy(new DiffEditorWidgetSideBySide(this._createDataSource(), this._enableSplitViewResizing)); } else { this._setStrategy(new DiffEditorWidgetInline(this._createDataSource(), this._enableSplitViewResizing)); } // Update class name this._containerDomElement.className = DiffEditorWidget._getClassName(this._themeService.getTheme(), this._renderSideBySide); } }; DiffEditorWidget.prototype.getModel = function () { return { original: this.originalEditor.getModel(), modified: this.modifiedEditor.getModel() }; }; DiffEditorWidget.prototype.setModel = function (model) { // Guard us against partial null model if (model && (!model.original || !model.modified)) { throw new Error(!model.original ? 'DiffEditorWidget.setModel: Original model is null' : 'DiffEditorWidget.setModel: Modified model is null'); } // Remove all view zones & decorations this._cleanViewZonesAndDecorations(); // Update code editor models this.originalEditor.setModel(model ? model.original : null); this.modifiedEditor.setModel(model ? model.modified : null); this._updateDecorationsRunner.cancel(); // this.originalEditor.onDidChangeModelOptions if (model) { this.originalEditor.setScrollTop(0); this.modifiedEditor.setScrollTop(0); } // Disable any diff computations that will come in this._diffComputationResult = null; this._diffComputationToken++; this._setState(0 /* Idle */); if (model) { this._recreateOverviewRulers(); // Begin comparing this._beginUpdateDecorations(); } this._layoutOverviewViewport(); }; DiffEditorWidget.prototype.getDomNode = function () { return this._domElement; }; DiffEditorWidget.prototype.getVisibleColumnFromPosition = function (position) { return this.modifiedEditor.getVisibleColumnFromPosition(position); }; DiffEditorWidget.prototype.getPosition = function () { return this.modifiedEditor.getPosition(); }; DiffEditorWidget.prototype.setPosition = function (position) { this.modifiedEditor.setPosition(position); }; DiffEditorWidget.prototype.revealLine = function (lineNumber, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this.modifiedEditor.revealLine(lineNumber, scrollType); }; DiffEditorWidget.prototype.revealLineInCenter = function (lineNumber, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this.modifiedEditor.revealLineInCenter(lineNumber, scrollType); }; DiffEditorWidget.prototype.revealLineInCenterIfOutsideViewport = function (lineNumber, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this.modifiedEditor.revealLineInCenterIfOutsideViewport(lineNumber, scrollType); }; DiffEditorWidget.prototype.revealPosition = function (position, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this.modifiedEditor.revealPosition(position, scrollType); }; DiffEditorWidget.prototype.revealPositionInCenter = function (position, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this.modifiedEditor.revealPositionInCenter(position, scrollType); }; DiffEditorWidget.prototype.revealPositionInCenterIfOutsideViewport = function (position, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this.modifiedEditor.revealPositionInCenterIfOutsideViewport(position, scrollType); }; DiffEditorWidget.prototype.getSelection = function () { return this.modifiedEditor.getSelection(); }; DiffEditorWidget.prototype.getSelections = function () { return this.modifiedEditor.getSelections(); }; DiffEditorWidget.prototype.setSelection = function (something) { this.modifiedEditor.setSelection(something); }; DiffEditorWidget.prototype.setSelections = function (ranges) { this.modifiedEditor.setSelections(ranges); }; DiffEditorWidget.prototype.revealLines = function (startLineNumber, endLineNumber, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this.modifiedEditor.revealLines(startLineNumber, endLineNumber, scrollType); }; DiffEditorWidget.prototype.revealLinesInCenter = function (startLineNumber, endLineNumber, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this.modifiedEditor.revealLinesInCenter(startLineNumber, endLineNumber, scrollType); }; DiffEditorWidget.prototype.revealLinesInCenterIfOutsideViewport = function (startLineNumber, endLineNumber, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this.modifiedEditor.revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType); }; DiffEditorWidget.prototype.revealRange = function (range, scrollType, revealVerticalInCenter, revealHorizontal) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } if (revealVerticalInCenter === void 0) { revealVerticalInCenter = false; } if (revealHorizontal === void 0) { revealHorizontal = true; } this.modifiedEditor.revealRange(range, scrollType, revealVerticalInCenter, revealHorizontal); }; DiffEditorWidget.prototype.revealRangeInCenter = function (range, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this.modifiedEditor.revealRangeInCenter(range, scrollType); }; DiffEditorWidget.prototype.revealRangeInCenterIfOutsideViewport = function (range, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this.modifiedEditor.revealRangeInCenterIfOutsideViewport(range, scrollType); }; DiffEditorWidget.prototype.revealRangeAtTop = function (range, scrollType) { if (scrollType === void 0) { scrollType = 0 /* Smooth */; } this.modifiedEditor.revealRangeAtTop(range, scrollType); }; DiffEditorWidget.prototype.getSupportedActions = function () { return this.modifiedEditor.getSupportedActions(); }; DiffEditorWidget.prototype.saveViewState = function () { var originalViewState = this.originalEditor.saveViewState(); var modifiedViewState = this.modifiedEditor.saveViewState(); return { original: originalViewState, modified: modifiedViewState }; }; DiffEditorWidget.prototype.restoreViewState = function (s) { if (s.original && s.modified) { var diffEditorState = s; this.originalEditor.restoreViewState(diffEditorState.original); this.modifiedEditor.restoreViewState(diffEditorState.modified); } }; DiffEditorWidget.prototype.layout = function (dimension) { this._elementSizeObserver.observe(dimension); }; DiffEditorWidget.prototype.focus = function () { this.modifiedEditor.focus(); }; DiffEditorWidget.prototype.hasTextFocus = function () { return this.originalEditor.hasTextFocus() || this.modifiedEditor.hasTextFocus(); }; DiffEditorWidget.prototype.trigger = function (source, handlerId, payload) { this.modifiedEditor.trigger(source, handlerId, payload); }; DiffEditorWidget.prototype.changeDecorations = function (callback) { return this.modifiedEditor.changeDecorations(callback); }; //------------ end IDiffEditor methods //------------ begin layouting methods DiffEditorWidget.prototype._onDidContainerSizeChanged = function () { this._doLayout(); }; DiffEditorWidget.prototype._getReviewHeight = function () { return this._reviewPane.isVisible() ? this._elementSizeObserver.getHeight() : 0; }; DiffEditorWidget.prototype._layoutOverviewRulers = function () { if (!this._originalOverviewRuler || !this._modifiedOverviewRuler) { return; } var height = this._elementSizeObserver.getHeight(); var reviewHeight = this._getReviewHeight(); var freeSpace = DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH - 2 * DiffEditorWidget.ONE_OVERVIEW_WIDTH; var layoutInfo = this.modifiedEditor.getLayoutInfo(); if (layoutInfo) { this._originalOverviewRuler.setLayout({ top: 0, width: DiffEditorWidget.ONE_OVERVIEW_WIDTH, right: freeSpace + DiffEditorWidget.ONE_OVERVIEW_WIDTH, height: (height - reviewHeight) }); this._modifiedOverviewRuler.setLayout({ top: 0, right: 0, width: DiffEditorWidget.ONE_OVERVIEW_WIDTH, height: (height - reviewHeight) }); } }; //------------ end layouting methods DiffEditorWidget.prototype._onViewZonesChanged = function () { if (this._currentlyChangingViewZones) { return; } this._updateDecorationsRunner.schedule(); }; DiffEditorWidget.prototype._beginUpdateDecorationsSoon = function () { var _this = this; // Clear previous timeout if necessary if (this._beginUpdateDecorationsTimeout !== -1) { window.clearTimeout(this._beginUpdateDecorationsTimeout); this._beginUpdateDecorationsTimeout = -1; } this._beginUpdateDecorationsTimeout = window.setTimeout(function () { return _this._beginUpdateDecorations(); }, DiffEditorWidget.UPDATE_DIFF_DECORATIONS_DELAY); }; DiffEditorWidget._equals = function (a, b) { if (!a && !b) { return true; } if (!a || !b) { return false; } return (a.toString() === b.toString()); }; DiffEditorWidget.prototype._beginUpdateDecorations = function () { var _this = this; this._beginUpdateDecorationsTimeout = -1; var currentOriginalModel = this.originalEditor.getModel(); var currentModifiedModel = this.modifiedEditor.getModel(); if (!currentOriginalModel || !currentModifiedModel) { return; } // Prevent old diff requests to come if a new request has been initiated // The best method would be to call cancel on the Promise, but this is not // yet supported, so using tokens for now. this._diffComputationToken++; var currentToken = this._diffComputationToken; this._setState(1 /* ComputingDiff */); if (!this._editorWorkerService.canComputeDiff(currentOriginalModel.uri, currentModifiedModel.uri)) { if (!DiffEditorWidget._equals(currentOriginalModel.uri, this._lastOriginalWarning) || !DiffEditorWidget._equals(currentModifiedModel.uri, this._lastModifiedWarning)) { this._lastOriginalWarning = currentOriginalModel.uri; this._lastModifiedWarning = currentModifiedModel.uri; this._notificationService.warn(nls.localize(0, null)); } return; } this._editorWorkerService.computeDiff(currentOriginalModel.uri, currentModifiedModel.uri, this._ignoreTrimWhitespace, this._maxComputationTime).then(function (result) { if (currentToken === _this._diffComputationToken && currentOriginalModel === _this.originalEditor.getModel() && currentModifiedModel === _this.modifiedEditor.getModel()) { _this._setState(2 /* DiffComputed */); _this._diffComputationResult = result; _this._updateDecorationsRunner.schedule(); _this._onDidUpdateDiff.fire(); } }, function (error) { if (currentToken === _this._diffComputationToken && currentOriginalModel === _this.originalEditor.getModel() && currentModifiedModel === _this.modifiedEditor.getModel()) { _this._setState(2 /* DiffComputed */); _this._diffComputationResult = null; _this._updateDecorationsRunner.schedule(); } }); }; DiffEditorWidget.prototype._cleanViewZonesAndDecorations = function () { this._originalEditorState.clean(this.originalEditor); this._modifiedEditorState.clean(this.modifiedEditor); }; DiffEditorWidget.prototype._updateDecorations = function () { if (!this.originalEditor.getModel() || !this.modifiedEditor.getModel() || !this._originalOverviewRuler || !this._modifiedOverviewRuler) { return; } var lineChanges = (this._diffComputationResult ? this._diffComputationResult.changes : []); var foreignOriginal = this._originalEditorState.getForeignViewZones(this.originalEditor.getWhitespaces()); var foreignModified = this._modifiedEditorState.getForeignViewZones(this.modifiedEditor.getWhitespaces()); var diffDecorations = this._strategy.getEditorsDiffDecorations(lineChanges, this._ignoreTrimWhitespace, this._renderIndicators, foreignOriginal, foreignModified, this.originalEditor, this.modifiedEditor); try { this._currentlyChangingViewZones = true; this._originalEditorState.apply(this.originalEditor, this._originalOverviewRuler, diffDecorations.original, false); this._modifiedEditorState.apply(this.modifiedEditor, this._modifiedOverviewRuler, diffDecorations.modified, true); } finally { this._currentlyChangingViewZones = false; } }; DiffEditorWidget.prototype._adjustOptionsForSubEditor = function (options) { var clonedOptions = objects.deepClone(options || {}); clonedOptions.inDiffEditor = true; clonedOptions.wordWrap = 'off'; clonedOptions.wordWrapMinified = false; clonedOptions.automaticLayout = false; clonedOptions.scrollbar = clonedOptions.scrollbar || {}; clonedOptions.scrollbar.vertical = 'visible'; clonedOptions.folding = false; clonedOptions.codeLens = false; clonedOptions.fixedOverflowWidgets = true; // clonedOptions.lineDecorationsWidth = '2ch'; if (!clonedOptions.minimap) { clonedOptions.minimap = {}; } clonedOptions.minimap.enabled = false; return clonedOptions; }; DiffEditorWidget.prototype._adjustOptionsForLeftHandSide = function (options, isEditable) { var result = this._adjustOptionsForSubEditor(options); result.readOnly = !isEditable; result.extraEditorClassName = 'original-in-monaco-diff-editor'; return result; }; DiffEditorWidget.prototype._adjustOptionsForRightHandSide = function (options) { var result = this._adjustOptionsForSubEditor(options); result.revealHorizontalRightPadding = editorOptions_1.EditorOptions.revealHorizontalRightPadding.defaultValue + DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH; result.scrollbar.verticalHasArrows = false; result.extraEditorClassName = 'modified-in-monaco-diff-editor'; return result; }; DiffEditorWidget.prototype.doLayout = function () { this._elementSizeObserver.observe(); this._doLayout(); }; DiffEditorWidget.prototype._doLayout = function () { var width = this._elementSizeObserver.getWidth(); var height = this._elementSizeObserver.getHeight(); var reviewHeight = this._getReviewHeight(); var splitPoint = this._strategy.layout(); this._originalDomNode.style.width = splitPoint + 'px'; this._originalDomNode.style.left = '0px'; this._modifiedDomNode.style.width = (width - splitPoint) + 'px'; this._modifiedDomNode.style.left = splitPoint + 'px'; this._overviewDomElement.style.top = '0px'; this._overviewDomElement.style.height = (height - reviewHeight) + 'px'; this._overviewDomElement.style.width = DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH + 'px'; this._overviewDomElement.style.left = (width - DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH) + 'px'; this._overviewViewportDomElement.setWidth(DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH); this._overviewViewportDomElement.setHeight(30); this.originalEditor.layout({ width: splitPoint, height: (height - reviewHeight) }); this.modifiedEditor.layout({ width: width - splitPoint - DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH, height: (height - reviewHeight) }); if (this._originalOverviewRuler || this._modifiedOverviewRuler) { this._layoutOverviewRulers(); } this._reviewPane.layout(height - reviewHeight, width, reviewHeight); this._layoutOverviewViewport(); }; DiffEditorWidget.prototype._layoutOverviewViewport = function () { var layout = this._computeOverviewViewport(); if (!layout) { this._overviewViewportDomElement.setTop(0); this._overviewViewportDomElement.setHeight(0); } else { this._overviewViewportDomElement.setTop(layout.top); this._overviewViewportDomElement.setHeight(layout.height); } }; DiffEditorWidget.prototype._computeOverviewViewport = function () { var layoutInfo = this.modifiedEditor.getLayoutInfo(); if (!layoutInfo) { return null; } var scrollTop = this.modifiedEditor.getScrollTop(); var scrollHeight = this.modifiedEditor.getScrollHeight(); var computedAvailableSize = Math.max(0, layoutInfo.height); var computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * 0); var computedRatio = scrollHeight > 0 ? (computedRepresentableSize / scrollHeight) : 0; var computedSliderSize = Math.max(0, Math.floor(layoutInfo.height * computedRatio)); var computedSliderPosition = Math.floor(scrollTop * computedRatio); return { height: computedSliderSize, top: computedSliderPosition }; }; DiffEditorWidget.prototype._createDataSource = function () { var _this = this; return { getWidth: function () { return _this._elementSizeObserver.getWidth(); }, getHeight: function () { return (_this._elementSizeObserver.getHeight() - _this._getReviewHeight()); }, getContainerDomNode: function () { return _this._containerDomElement; }, relayoutEditors: function () { _this._doLayout(); }, getOriginalEditor: function () { return _this.originalEditor; }, getModifiedEditor: function () { return _this.modifiedEditor; } }; }; DiffEditorWidget.prototype._setStrategy = function (newStrategy) { if (this._strategy) { this._strategy.dispose(); } this._strategy = newStrategy; newStrategy.applyColors(this._themeService.getTheme()); if (this._diffComputationResult) { this._updateDecorations(); } // Just do a layout, the strategy might need it this._doLayout(); }; DiffEditorWidget.prototype._getLineChangeAtOrBeforeLineNumber = function (lineNumber, startLineNumberExtractor) { var lineChanges = (this._diffComputationResult ? this._diffComputationResult.changes : []); if (lineChanges.length === 0 || lineNumber < startLineNumberExtractor(lineChanges[0])) { // There are no changes or `lineNumber` is before the first change return null; } var min = 0, max = lineChanges.length - 1; while (min < max) { var mid = Math.floor((min + max) / 2); var midStart = startLineNumberExtractor(lineChanges[mid]); var midEnd = (mid + 1 <= max ? startLineNumberExtractor(lineChanges[mid + 1]) : 1073741824 /* MAX_SAFE_SMALL_INTEGER */); if (lineNumber < midStart) { max = mid - 1; } else if (lineNumber >= midEnd) { min = mid + 1; } else { // HIT! min = mid; max = mid; } } return lineChanges[min]; }; DiffEditorWidget.prototype._getEquivalentLineForOriginalLineNumber = function (lineNumber) { var lineChange = this._getLineChangeAtOrBeforeLineNumber(lineNumber, function (lineChange) { return lineChange.originalStartLineNumber; }); if (!lineChange) { return lineNumber; } var originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0); var modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0); var lineChangeOriginalLength = (lineChange.originalEndLineNumber > 0 ? (lineChange.originalEndLineNumber - lineChange.originalStartLineNumber + 1) : 0); var lineChangeModifiedLength = (lineChange.modifiedEndLineNumber > 0 ? (lineChange.modifiedEndLineNumber - lineChange.modifiedStartLineNumber + 1) : 0); var delta = lineNumber - originalEquivalentLineNumber; if (delta <= lineChangeOriginalLength) { return modifiedEquivalentLineNumber + Math.min(delta, lineChangeModifiedLength); } return modifiedEquivalentLineNumber + lineChangeModifiedLength - lineChangeOriginalLength + delta; }; DiffEditorWidget.prototype._getEquivalentLineForModifiedLineNumber = function (lineNumber) { var lineChange = this._getLineChangeAtOrBeforeLineNumber(lineNumber, function (lineChange) { return lineChange.modifiedStartLineNumber; }); if (!lineChange) { return lineNumber; } var originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0); var modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0); var lineChangeOriginalLength = (lineChange.originalEndLineNumber > 0 ? (lineChange.originalEndLineNumber - lineChange.originalStartLineNumber + 1) : 0); var lineChangeModifiedLength = (lineChange.modifiedEndLineNumber > 0 ? (lineChange.modifiedEndLineNumber - lineChange.modifiedStartLineNumber + 1) : 0); var delta = lineNumber - modifiedEquivalentLineNumber; if (delta <= lineChangeModifiedLength) { return originalEquivalentLineNumber + Math.min(delta, lineChangeOriginalLength); } return originalEquivalentLineNumber + lineChangeOriginalLength - lineChangeModifiedLength + delta; }; DiffEditorWidget.prototype.getDiffLineInformationForOriginal = function (lineNumber) { if (!this._diffComputationResult) { // Cannot answer that which I don't know return null; } return { equivalentLineNumber: this._getEquivalentLineForOriginalLineNumber(lineNumber) }; }; DiffEditorWidget.prototype.getDiffLineInformationForModified = function (lineNumber) { if (!this._diffComputationResult) { // Cannot answer that which I don't know return null; } return { equivalentLineNumber: this._getEquivalentLineForModifiedLineNumber(lineNumber) }; }; DiffEditorWidget.ONE_OVERVIEW_WIDTH = 15; DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH = 30; DiffEditorWidget.UPDATE_DIFF_DECORATIONS_DELAY = 200; // ms DiffEditorWidget = __decorate([ __param(3, editorWorkerService_1.IEditorWorkerService), __param(4, contextkey_1.IContextKeyService), __param(5, instantiation_1.IInstantiationService), __param(6, codeEditorService_1.ICodeEditorService), __param(7, themeService_1.IThemeService), __param(8, notification_1.INotificationService), __param(9, contextView_1.IContextMenuService), __param(10, progress_1.IEditorProgressService) ], DiffEditorWidget); return DiffEditorWidget; }(lifecycle_1.Disposable)); exports.DiffEditorWidget = DiffEditorWidget; var DiffEditorWidgetStyle = /** @class */ (function (_super) { __extends(DiffEditorWidgetStyle, _super); function DiffEditorWidgetStyle(dataSource) { var _this = _super.call(this) || this; _this._dataSource = dataSource; _this._insertColor = null; _this._removeColor = null; return _this; } DiffEditorWidgetStyle.prototype.applyColors = function (theme) { var newInsertColor = (theme.getColor(colorRegistry_1.diffInserted) || colorRegistry_1.defaultInsertColor).transparent(2); var newRemoveColor = (theme.getColor(colorRegistry_1.diffRemoved) || colorRegistry_1.defaultRemoveColor).transparent(2); var hasChanges = !newInsertColor.equals(this._insertColor) || !newRemoveColor.equals(this._removeColor); this._insertColor = newInsertColor; this._removeColor = newRemoveColor; return hasChanges; }; DiffEditorWidgetStyle.prototype.getEditorsDiffDecorations = function (lineChanges, ignoreTrimWhitespace, renderIndicators, originalWhitespaces, modifiedWhitespaces, originalEditor, modifiedEditor) { // Get view zones modifiedWhitespaces = modifiedWhitespaces.sort(function (a, b) { return a.afterLineNumber - b.afterLineNumber; }); originalWhitespaces = originalWhitespaces.sort(function (a, b) { return a.afterLineNumber - b.afterLineNumber; }); var zones = this._getViewZones(lineChanges, originalWhitespaces, modifiedWhitespaces, originalEditor, modifiedEditor, renderIndicators); // Get decorations & overview ruler zones var originalDecorations = this._getOriginalEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor); var modifiedDecorations = this._getModifiedEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor); return { original: { decorations: originalDecorations.decorations, overviewZones: originalDecorations.overviewZones, zones: zones.original }, modified: { decorations: modifiedDecorations.decorations, overviewZones: modifiedDecorations.overviewZones, zones: zones.modified } }; }; return DiffEditorWidgetStyle; }(lifecycle_1.Disposable)); var ForeignViewZonesIterator = /** @class */ (function () { function ForeignViewZonesIterator(source) { this._source = source; this._index = -1; this.current = null; this.advance(); } ForeignViewZonesIterator.prototype.advance = function () { this._index++; if (this._index < this._source.length) { this.current = this._source[this._index]; } else { this.current = null; } }; return ForeignViewZonesIterator; }()); var ViewZonesComputer = /** @class */ (function () { function ViewZonesComputer(lineChanges, originalForeignVZ, originalLineHeight, modifiedForeignVZ, modifiedLineHeight) { this.lineChanges = lineChanges; this.originalForeignVZ = originalForeignVZ; this.originalLineHeight = originalLineHeight; this.modifiedForeignVZ = modifiedForeignVZ; this.modifiedLineHeight = modifiedLineHeight; } ViewZonesComputer.prototype.getViewZones = function () { var result = { original: [], modified: [] }; var lineChangeModifiedLength = 0; var lineChangeOriginalLength = 0; var originalEquivalentLineNumber = 0; var modifiedEquivalentLineNumber = 0; var originalEndEquivalentLineNumber = 0; var modifiedEndEquivalentLineNumber = 0; var sortMyViewZones = function (a, b) { return a.afterLineNumber - b.afterLineNumber; }; var addAndCombineIfPossible = function (destination, item) { if (item.domNode === null && destination.length > 0) { var lastItem = destination[destination.length - 1]; if (lastItem.afterLineNumber === item.afterLineNumber && lastItem.domNode === null) { lastItem.heightInLines += item.heightInLines; return; } } destination.push(item); }; var modifiedForeignVZ = new ForeignViewZonesIterator(this.modifiedForeignVZ); var originalForeignVZ = new ForeignViewZonesIterator(this.originalForeignVZ); // In order to include foreign view zones after the last line change, the for loop will iterate once more after the end of the `lineChanges` array for (var i = 0, length_5 = this.lineChanges.length; i <= length_5; i++) { var lineChange = (i < length_5 ? this.lineChanges[i] : null); if (lineChange !== null) { originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0); modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0); lineChangeOriginalLength = (lineChange.originalEndLineNumber > 0 ? (lineChange.originalEndLineNumber - lineChange.originalStartLineNumber + 1) : 0); lineChangeModifiedLength = (lineChange.modifiedEndLineNumber > 0 ? (lineChange.modifiedEndLineNumber - lineChange.modifiedStartLineNumber + 1) : 0); originalEndEquivalentLineNumber = Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber); modifiedEndEquivalentLineNumber = Math.max(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber); } else { // Increase to very large value to get the producing tests of foreign view zones running originalEquivalentLineNumber += 10000000 + lineChangeOriginalLength; modifiedEquivalentLineNumber += 10000000 + lineChangeModifiedLength; originalEndEquivalentLineNumber = originalEquivalentLineNumber; modifiedEndEquivalentLineNumber = modifiedEquivalentLineNumber; } // Each step produces view zones, and after producing them, we try to cancel them out, to avoid empty-empty view zone cases var stepOriginal = []; var stepModified = []; // ---------------------------- PRODUCE VIEW ZONES // [PRODUCE] View zone(s) in original-side due to foreign view zone(s) in modified-side while (modifiedForeignVZ.current && modifiedForeignVZ.current.afterLineNumber <= modifiedEndEquivalentLineNumber) { var viewZoneLineNumber = void 0; if (modifiedForeignVZ.current.afterLineNumber <= modifiedEquivalentLineNumber) { viewZoneLineNumber = originalEquivalentLineNumber - modifiedEquivalentLineNumber + modifiedForeignVZ.current.afterLineNumber; } else { viewZoneLineNumber = originalEndEquivalentLineNumber; } var marginDomNode = null; if (lineChange && lineChange.modifiedStartLineNumber <= modifiedForeignVZ.current.afterLineNumber && modifiedForeignVZ.current.afterLineNumber <= lineChange.modifiedEndLineNumber) { marginDomNode = this._createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion(); } stepOriginal.push({ afterLineNumber: viewZoneLineNumber, heightInLines: modifiedForeignVZ.current.height / this.modifiedLineHeight, domNode: null, marginDomNode: marginDomNode }); modifiedForeignVZ.advance(); } // [PRODUCE] View zone(s) in modified-side due to foreign view zone(s) in original-side while (originalForeignVZ.current && originalForeignVZ.current.afterLineNumber <= originalEndEquivalentLineNumber) { var viewZoneLineNumber = void 0; if (originalForeignVZ.current.afterLineNumber <= originalEquivalentLineNumber) { viewZoneLineNumber = modifiedEquivalentLineNumber - originalEquivalentLineNumber + originalForeignVZ.current.afterLineNumber; } else { viewZoneLineNumber = modifiedEndEquivalentLineNumber; } stepModified.push({ afterLineNumber: viewZoneLineNumber, heightInLines: originalForeignVZ.current.height / this.originalLineHeight, domNode: null }); originalForeignVZ.advance(); } if (lineChange !== null && isChangeOrInsert(lineChange)) { var r = this._produceOriginalFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength); if (r) { stepOriginal.push(r); } } if (lineChange !== null && isChangeOrDelete(lineChange)) { var r = this._produceModifiedFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength); if (r) { stepModified.push(r); } } // ---------------------------- END PRODUCE VIEW ZONES // ---------------------------- EMIT MINIMAL VIEW ZONES // [CANCEL & EMIT] Try to cancel view zones out var stepOriginalIndex = 0; var stepModifiedIndex = 0; stepOriginal = stepOriginal.sort(sortMyViewZones); stepModified = stepModified.sort(sortMyViewZones); while (stepOriginalIndex < stepOriginal.length && stepModifiedIndex < stepModified.length) { var original = stepOriginal[stepOriginalIndex]; var modified = stepModified[stepModifiedIndex]; var originalDelta = original.afterLineNumber - originalEquivalentLineNumber; var modifiedDelta = modified.afterLineNumber - modifiedEquivalentLineNumber; if (originalDelta < modifiedDelta) { addAndCombineIfPossible(result.original, original); stepOriginalIndex++; } else if (modifiedDelta < originalDelta) { addAndCombineIfPossible(result.modified, modified); stepModifiedIndex++; } else if (original.shouldNotShrink) { addAndCombineIfPossible(result.original, original); stepOriginalIndex++; } else if (modified.shouldNotShrink) { addAndCombineIfPossible(result.modified, modified); stepModifiedIndex++; } else { if (original.heightInLines >= modified.heightInLines) { // modified view zone gets removed original.heightInLines -= modified.heightInLines; stepModifiedIndex++; } else { // original view zone gets removed modified.heightInLines -= original.heightInLines; stepOriginalIndex++; } } } // [EMIT] Remaining original view zones while (stepOriginalIndex < stepOriginal.length) { addAndCombineIfPossible(result.original, stepOriginal[stepOriginalIndex]); stepOriginalIndex++; } // [EMIT] Remaining modified view zones while (stepModifiedIndex < stepModified.length) { addAndCombineIfPossible(result.modified, stepModified[stepModifiedIndex]); stepModifiedIndex++; } // ---------------------------- END EMIT MINIMAL VIEW ZONES } return { original: ViewZonesComputer._ensureDomNodes(result.original), modified: ViewZonesComputer._ensureDomNodes(result.modified), }; }; ViewZonesComputer._ensureDomNodes = function (zones) { return zones.map(function (z) { if (!z.domNode) { z.domNode = createFakeLinesDiv(); } return z; }); }; return ViewZonesComputer; }()); function createDecoration(startLineNumber, startColumn, endLineNumber, endColumn, options) { return { range: new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn), options: options }; } var DECORATIONS = { charDelete: textModel_1.ModelDecorationOptions.register({ className: 'char-delete' }), charDeleteWholeLine: textModel_1.ModelDecorationOptions.register({ className: 'char-delete', isWholeLine: true }), charInsert: textModel_1.ModelDecorationOptions.register({ className: 'char-insert' }), charInsertWholeLine: textModel_1.ModelDecorationOptions.register({ className: 'char-insert', isWholeLine: true }), lineInsert: textModel_1.ModelDecorationOptions.register({ className: 'line-insert', marginClassName: 'line-insert', isWholeLine: true }), lineInsertWithSign: textModel_1.ModelDecorationOptions.register({ className: 'line-insert', linesDecorationsClassName: 'insert-sign codicon codicon-add', marginClassName: 'line-insert', isWholeLine: true }), lineDelete: textModel_1.ModelDecorationOptions.register({ className: 'line-delete', marginClassName: 'line-delete', isWholeLine: true }), lineDeleteWithSign: textModel_1.ModelDecorationOptions.register({ className: 'line-delete', linesDecorationsClassName: 'delete-sign codicon codicon-remove', marginClassName: 'line-delete', isWholeLine: true }), lineDeleteMargin: textModel_1.ModelDecorationOptions.register({ marginClassName: 'line-delete', }) }; var DiffEditorWidgetSideBySide = /** @class */ (function (_super) { __extends(DiffEditorWidgetSideBySide, _super); function DiffEditorWidgetSideBySide(dataSource, enableSplitViewResizing) { var _this = _super.call(this, dataSource) || this; _this._disableSash = (enableSplitViewResizing === false); _this._sashRatio = null; _this._sashPosition = null; _this._startSashPosition = null; _this._sash = _this._register(new sash_1.Sash(_this._dataSource.getContainerDomNode(), _this)); if (_this._disableSash) { _this._sash.state = 0 /* Disabled */; } _this._sash.onDidStart(function () { return _this.onSashDragStart(); }); _this._sash.onDidChange(function (e) { return _this.onSashDrag(e); }); _this._sash.onDidEnd(function () { return _this.onSashDragEnd(); }); _this._sash.onDidReset(function () { return _this.onSashReset(); }); return _this; } DiffEditorWidgetSideBySide.prototype.setEnableSplitViewResizing = function (enableSplitViewResizing) { var newDisableSash = (enableSplitViewResizing === false); if (this._disableSash !== newDisableSash) { this._disableSash = newDisableSash; this._sash.state = this._disableSash ? 0 /* Disabled */ : 3 /* Enabled */; } }; DiffEditorWidgetSideBySide.prototype.layout = function (sashRatio) { if (sashRatio === void 0) { sashRatio = this._sashRatio; } var w = this._dataSource.getWidth(); var contentWidth = w - DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH; var sashPosition = Math.floor((sashRatio || 0.5) * contentWidth); var midPoint = Math.floor(0.5 * contentWidth); sashPosition = this._disableSash ? midPoint : sashPosition || midPoint; if (contentWidth > DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH * 2) { if (sashPosition < DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH) { sashPosition = DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH; } if (sashPosition > contentWidth - DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH) { sashPosition = contentWidth - DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH; } } else { sashPosition = midPoint; } if (this._sashPosition !== sashPosition) { this._sashPosition = sashPosition; this._sash.layout(); } return this._sashPosition; }; DiffEditorWidgetSideBySide.prototype.onSashDragStart = function () { this._startSashPosition = this._sashPosition; }; DiffEditorWidgetSideBySide.prototype.onSashDrag = function (e) { var w = this._dataSource.getWidth(); var contentWidth = w - DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH; var sashPosition = this.layout((this._startSashPosition + (e.currentX - e.startX)) / contentWidth); this._sashRatio = sashPosition / contentWidth; this._dataSource.relayoutEditors(); }; DiffEditorWidgetSideBySide.prototype.onSashDragEnd = function () { this._sash.layout(); }; DiffEditorWidgetSideBySide.prototype.onSashReset = function () { this._sashRatio = 0.5; this._dataSource.relayoutEditors(); this._sash.layout(); }; DiffEditorWidgetSideBySide.prototype.getVerticalSashTop = function (sash) { return 0; }; DiffEditorWidgetSideBySide.prototype.getVerticalSashLeft = function (sash) { return this._sashPosition; }; DiffEditorWidgetSideBySide.prototype.getVerticalSashHeight = function (sash) { return this._dataSource.getHeight(); }; DiffEditorWidgetSideBySide.prototype._getViewZones = function (lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor) { var c = new SideBySideViewZonesComputer(lineChanges, originalForeignVZ, originalEditor.getOption(49 /* lineHeight */), modifiedForeignVZ, modifiedEditor.getOption(49 /* lineHeight */)); return c.getViewZones(); }; DiffEditorWidgetSideBySide.prototype._getOriginalEditorDecorations = function (lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor) { var overviewZoneColor = String(this._removeColor); var result = { decorations: [], overviewZones: [] }; var originalModel = originalEditor.getModel(); for (var i = 0, length_6 = lineChanges.length; i < length_6; i++) { var lineChange = lineChanges[i]; if (isChangeOrDelete(lineChange)) { result.decorations.push({ range: new range_1.Range(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */), options: (renderIndicators ? DECORATIONS.lineDeleteWithSign : DECORATIONS.lineDelete) }); if (!isChangeOrInsert(lineChange) || !lineChange.charChanges) { result.decorations.push(createDecoration(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, DECORATIONS.charDeleteWholeLine)); } result.overviewZones.push(new overviewZoneManager_1.OverviewRulerZone(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber, overviewZoneColor)); if (lineChange.charChanges) { for (var j = 0, lengthJ = lineChange.charChanges.length; j < lengthJ; j++) { var charChange = lineChange.charChanges[j]; if (isChangeOrDelete(charChange)) { if (ignoreTrimWhitespace) { for (var lineNumber = charChange.originalStartLineNumber; lineNumber <= charChange.originalEndLineNumber; lineNumber++) { var startColumn = void 0; var endColumn = void 0; if (lineNumber === charChange.originalStartLineNumber) { startColumn = charChange.originalStartColumn; } else { startColumn = originalModel.getLineFirstNonWhitespaceColumn(lineNumber); } if (lineNumber === charChange.originalEndLineNumber) { endColumn = charChange.originalEndColumn; } else { endColumn = originalModel.getLineLastNonWhitespaceColumn(lineNumber); } result.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charDelete)); } } else { result.decorations.push(createDecoration(charChange.originalStartLineNumber, charChange.originalStartColumn, charChange.originalEndLineNumber, charChange.originalEndColumn, DECORATIONS.charDelete)); } } } } } } return result; }; DiffEditorWidgetSideBySide.prototype._getModifiedEditorDecorations = function (lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor) { var overviewZoneColor = String(this._insertColor); var result = { decorations: [], overviewZones: [] }; var modifiedModel = modifiedEditor.getModel(); for (var i = 0, length_7 = lineChanges.length; i < length_7; i++) { var lineChange = lineChanges[i]; if (isChangeOrInsert(lineChange)) { result.decorations.push({ range: new range_1.Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */), options: (renderIndicators ? DECORATIONS.lineInsertWithSign : DECORATIONS.lineInsert) }); if (!isChangeOrDelete(lineChange) || !lineChange.charChanges) { result.decorations.push(createDecoration(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, DECORATIONS.charInsertWholeLine)); } result.overviewZones.push(new overviewZoneManager_1.OverviewRulerZone(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber, overviewZoneColor)); if (lineChange.charChanges) { for (var j = 0, lengthJ = lineChange.charChanges.length; j < lengthJ; j++) { var charChange = lineChange.charChanges[j]; if (isChangeOrInsert(charChange)) { if (ignoreTrimWhitespace) { for (var lineNumber = charChange.modifiedStartLineNumber; lineNumber <= charChange.modifiedEndLineNumber; lineNumber++) { var startColumn = void 0; var endColumn = void 0; if (lineNumber === charChange.modifiedStartLineNumber) { startColumn = charChange.modifiedStartColumn; } else { startColumn = modifiedModel.getLineFirstNonWhitespaceColumn(lineNumber); } if (lineNumber === charChange.modifiedEndLineNumber) { endColumn = charChange.modifiedEndColumn; } else { endColumn = modifiedModel.getLineLastNonWhitespaceColumn(lineNumber); } result.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charInsert)); } } else { result.decorations.push(createDecoration(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn, DECORATIONS.charInsert)); } } } } } } return result; }; DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH = 100; return DiffEditorWidgetSideBySide; }(DiffEditorWidgetStyle)); var SideBySideViewZonesComputer = /** @class */ (function (_super) { __extends(SideBySideViewZonesComputer, _super); function SideBySideViewZonesComputer(lineChanges, originalForeignVZ, originalLineHeight, modifiedForeignVZ, modifiedLineHeight) { return _super.call(this, lineChanges, originalForeignVZ, originalLineHeight, modifiedForeignVZ, modifiedLineHeight) || this; } SideBySideViewZonesComputer.prototype._createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion = function () { return null; }; SideBySideViewZonesComputer.prototype._produceOriginalFromDiff = function (lineChange, lineChangeOriginalLength, lineChangeModifiedLength) { if (lineChangeModifiedLength > lineChangeOriginalLength) { return { afterLineNumber: Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber), heightInLines: (lineChangeModifiedLength - lineChangeOriginalLength), domNode: null }; } return null; }; SideBySideViewZonesComputer.prototype._produceModifiedFromDiff = function (lineChange, lineChangeOriginalLength, lineChangeModifiedLength) { if (lineChangeOriginalLength > lineChangeModifiedLength) { return { afterLineNumber: Math.max(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber), heightInLines: (lineChangeOriginalLength - lineChangeModifiedLength), domNode: null }; } return null; }; return SideBySideViewZonesComputer; }(ViewZonesComputer)); var DiffEditorWidgetInline = /** @class */ (function (_super) { __extends(DiffEditorWidgetInline, _super); function DiffEditorWidgetInline(dataSource, enableSplitViewResizing) { var _this = _super.call(this, dataSource) || this; _this.decorationsLeft = dataSource.getOriginalEditor().getLayoutInfo().decorationsLeft; _this._register(dataSource.getOriginalEditor().onDidLayoutChange(function (layoutInfo) { if (_this.decorationsLeft !== layoutInfo.decorationsLeft) { _this.decorationsLeft = layoutInfo.decorationsLeft; dataSource.relayoutEditors(); } })); return _this; } DiffEditorWidgetInline.prototype.setEnableSplitViewResizing = function (enableSplitViewResizing) { // Nothing to do.. }; DiffEditorWidgetInline.prototype._getViewZones = function (lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators) { var computer = new InlineViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators); return computer.getViewZones(); }; DiffEditorWidgetInline.prototype._getOriginalEditorDecorations = function (lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor) { var overviewZoneColor = String(this._removeColor); var result = { decorations: [], overviewZones: [] }; for (var i = 0, length_8 = lineChanges.length; i < length_8; i++) { var lineChange = lineChanges[i]; // Add overview zones in the overview ruler if (isChangeOrDelete(lineChange)) { result.decorations.push({ range: new range_1.Range(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */), options: DECORATIONS.lineDeleteMargin }); result.overviewZones.push(new overviewZoneManager_1.OverviewRulerZone(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber, overviewZoneColor)); } } return result; }; DiffEditorWidgetInline.prototype._getModifiedEditorDecorations = function (lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor) { var overviewZoneColor = String(this._insertColor); var result = { decorations: [], overviewZones: [] }; var modifiedModel = modifiedEditor.getModel(); for (var i = 0, length_9 = lineChanges.length; i < length_9; i++) { var lineChange = lineChanges[i]; // Add decorations & overview zones if (isChangeOrInsert(lineChange)) { result.decorations.push({ range: new range_1.Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */), options: (renderIndicators ? DECORATIONS.lineInsertWithSign : DECORATIONS.lineInsert) }); result.overviewZones.push(new overviewZoneManager_1.OverviewRulerZone(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber, overviewZoneColor)); if (lineChange.charChanges) { for (var j = 0, lengthJ = lineChange.charChanges.length; j < lengthJ; j++) { var charChange = lineChange.charChanges[j]; if (isChangeOrInsert(charChange)) { if (ignoreTrimWhitespace) { for (var lineNumber = charChange.modifiedStartLineNumber; lineNumber <= charChange.modifiedEndLineNumber; lineNumber++) { var startColumn = void 0; var endColumn = void 0; if (lineNumber === charChange.modifiedStartLineNumber) { startColumn = charChange.modifiedStartColumn; } else { startColumn = modifiedModel.getLineFirstNonWhitespaceColumn(lineNumber); } if (lineNumber === charChange.modifiedEndLineNumber) { endColumn = charChange.modifiedEndColumn; } else { endColumn = modifiedModel.getLineLastNonWhitespaceColumn(lineNumber); } result.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charInsert)); } } else { result.decorations.push(createDecoration(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn, DECORATIONS.charInsert)); } } } } else { result.decorations.push(createDecoration(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, DECORATIONS.charInsertWholeLine)); } } } return result; }; DiffEditorWidgetInline.prototype.layout = function () { // An editor should not be smaller than 5px return Math.max(5, this.decorationsLeft); }; return DiffEditorWidgetInline; }(DiffEditorWidgetStyle)); var InlineViewZonesComputer = /** @class */ (function (_super) { __extends(InlineViewZonesComputer, _super); function InlineViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators) { var _this = _super.call(this, lineChanges, originalForeignVZ, originalEditor.getOption(49 /* lineHeight */), modifiedForeignVZ, modifiedEditor.getOption(49 /* lineHeight */)) || this; _this.originalModel = originalEditor.getModel(); _this.modifiedEditorOptions = modifiedEditor.getOptions(); _this.modifiedEditorTabSize = modifiedEditor.getModel().getOptions().tabSize; _this.renderIndicators = renderIndicators; return _this; } InlineViewZonesComputer.prototype._createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion = function () { var result = document.createElement('div'); result.className = 'inline-added-margin-view-zone'; return result; }; InlineViewZonesComputer.prototype._produceOriginalFromDiff = function (lineChange, lineChangeOriginalLength, lineChangeModifiedLength) { var marginDomNode = document.createElement('div'); marginDomNode.className = 'inline-added-margin-view-zone'; return { afterLineNumber: Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber), heightInLines: lineChangeModifiedLength, domNode: document.createElement('div'), marginDomNode: marginDomNode }; }; InlineViewZonesComputer.prototype._produceModifiedFromDiff = function (lineChange, lineChangeOriginalLength, lineChangeModifiedLength) { var decorations = []; if (lineChange.charChanges) { for (var j = 0, lengthJ = lineChange.charChanges.length; j < lengthJ; j++) { var charChange = lineChange.charChanges[j]; if (isChangeOrDelete(charChange)) { decorations.push(new viewModel_1.InlineDecoration(new range_1.Range(charChange.originalStartLineNumber, charChange.originalStartColumn, charChange.originalEndLineNumber, charChange.originalEndColumn), 'char-delete', 0 /* Regular */)); } } } var sb = stringBuilder_1.createStringBuilder(10000); var marginHTML = []; var layoutInfo = this.modifiedEditorOptions.get(107 /* layoutInfo */); var fontInfo = this.modifiedEditorOptions.get(34 /* fontInfo */); var lineDecorationsWidth = layoutInfo.decorationsWidth; var lineHeight = this.modifiedEditorOptions.get(49 /* lineHeight */); var typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth; var maxCharsPerLine = 0; var originalContent = []; for (var lineNumber = lineChange.originalStartLineNumber; lineNumber <= lineChange.originalEndLineNumber; lineNumber++) { maxCharsPerLine = Math.max(maxCharsPerLine, this._renderOriginalLine(lineNumber - lineChange.originalStartLineNumber, this.originalModel, this.modifiedEditorOptions, this.modifiedEditorTabSize, lineNumber, decorations, sb)); originalContent.push(this.originalModel.getLineContent(lineNumber)); if (this.renderIndicators) { var index = lineNumber - lineChange.originalStartLineNumber; marginHTML = marginHTML.concat([ "
    " ]); } } maxCharsPerLine += this.modifiedEditorOptions.get(79 /* scrollBeyondLastColumn */); var domNode = document.createElement('div'); domNode.className = 'view-lines line-delete'; domNode.innerHTML = sb.build(); configuration_1.Configuration.applyFontInfoSlow(domNode, fontInfo); var marginDomNode = document.createElement('div'); marginDomNode.className = 'inline-deleted-margin-view-zone'; marginDomNode.innerHTML = marginHTML.join(''); configuration_1.Configuration.applyFontInfoSlow(marginDomNode, fontInfo); return { shouldNotShrink: true, afterLineNumber: (lineChange.modifiedEndLineNumber === 0 ? lineChange.modifiedStartLineNumber : lineChange.modifiedStartLineNumber - 1), heightInLines: lineChangeOriginalLength, minWidthInPx: (maxCharsPerLine * typicalHalfwidthCharacterWidth), domNode: domNode, marginDomNode: marginDomNode, diff: { originalStartLineNumber: lineChange.originalStartLineNumber, originalEndLineNumber: lineChange.originalEndLineNumber, modifiedStartLineNumber: lineChange.modifiedStartLineNumber, modifiedEndLineNumber: lineChange.modifiedEndLineNumber, originalContent: originalContent } }; }; InlineViewZonesComputer.prototype._renderOriginalLine = function (count, originalModel, options, tabSize, lineNumber, decorations, sb) { var lineTokens = originalModel.getLineTokens(lineNumber); var lineContent = lineTokens.getLineContent(); var fontInfo = options.get(34 /* fontInfo */); var actualDecorations = lineDecorations_1.LineDecoration.filter(decorations, lineNumber, 1, lineContent.length + 1); sb.appendASCIIString('
    '); var isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(lineContent, originalModel.mightContainNonBasicASCII()); var containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(lineContent, isBasicASCII, originalModel.mightContainRTL()); var output = viewLineRenderer_1.renderViewLine(new viewLineRenderer_1.RenderLineInput((fontInfo.isMonospace && !options.get(23 /* disableMonospaceOptimizations */)), fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII, containsRTL, 0, lineTokens, actualDecorations, tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, options.get(88 /* stopRenderingLineAfter */), options.get(74 /* renderWhitespace */), options.get(69 /* renderControlCharacters */), options.get(35 /* fontLigatures */) !== editorOptions_1.EditorFontLigatures.OFF, null // Send no selections, original line cannot be selected ), sb); sb.appendASCIIString('
    '); var absoluteOffsets = output.characterMapping.getAbsoluteOffsets(); return absoluteOffsets.length > 0 ? absoluteOffsets[absoluteOffsets.length - 1] : 0; }; return InlineViewZonesComputer; }(ViewZonesComputer)); function isChangeOrInsert(lineChange) { return lineChange.modifiedEndLineNumber > 0; } function isChangeOrDelete(lineChange) { return lineChange.originalEndLineNumber > 0; } function createFakeLinesDiv() { var r = document.createElement('div'); r.className = 'diagonal-fill'; return r; } themeService_1.registerThemingParticipant(function (theme, collector) { var added = theme.getColor(colorRegistry_1.diffInserted); if (added) { collector.addRule(".monaco-editor .line-insert, .monaco-editor .char-insert { background-color: " + added + "; }"); collector.addRule(".monaco-diff-editor .line-insert, .monaco-diff-editor .char-insert { background-color: " + added + "; }"); collector.addRule(".monaco-editor .inline-added-margin-view-zone { background-color: " + added + "; }"); } var removed = theme.getColor(colorRegistry_1.diffRemoved); if (removed) { collector.addRule(".monaco-editor .line-delete, .monaco-editor .char-delete { background-color: " + removed + "; }"); collector.addRule(".monaco-diff-editor .line-delete, .monaco-diff-editor .char-delete { background-color: " + removed + "; }"); collector.addRule(".monaco-editor .inline-deleted-margin-view-zone { background-color: " + removed + "; }"); } var addedOutline = theme.getColor(colorRegistry_1.diffInsertedOutline); if (addedOutline) { collector.addRule(".monaco-editor .line-insert, .monaco-editor .char-insert { border: 1px " + (theme.type === 'hc' ? 'dashed' : 'solid') + " " + addedOutline + "; }"); } var removedOutline = theme.getColor(colorRegistry_1.diffRemovedOutline); if (removedOutline) { collector.addRule(".monaco-editor .line-delete, .monaco-editor .char-delete { border: 1px " + (theme.type === 'hc' ? 'dashed' : 'solid') + " " + removedOutline + "; }"); } var shadow = theme.getColor(colorRegistry_1.scrollbarShadow); if (shadow) { collector.addRule(".monaco-diff-editor.side-by-side .editor.modified { box-shadow: -6px 0 5px -5px " + shadow + "; }"); } var border = theme.getColor(colorRegistry_1.diffBorder); if (border) { collector.addRule(".monaco-diff-editor.side-by-side .editor.modified { border-left: 1px solid " + border + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[167/*vs/editor/browser/widget/embeddedCodeEditorWidget*/], __M([0/*require*/,1/*exports*/,31/*vs/base/common/objects*/,32/*vs/editor/browser/services/codeEditorService*/,121/*vs/editor/browser/widget/codeEditorWidget*/,29/*vs/platform/commands/common/commands*/,18/*vs/platform/contextkey/common/contextkey*/,11/*vs/platform/instantiation/common/instantiation*/,35/*vs/platform/notification/common/notification*/,14/*vs/platform/theme/common/themeService*/,64/*vs/platform/accessibility/common/accessibility*/]), function (require, exports, objects, codeEditorService_1, codeEditorWidget_1, commands_1, contextkey_1, instantiation_1, notification_1, themeService_1, accessibility_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var EmbeddedCodeEditorWidget = /** @class */ (function (_super) { __extends(EmbeddedCodeEditorWidget, _super); function EmbeddedCodeEditorWidget(domElement, options, parentEditor, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService) { var _this = _super.call(this, domElement, parentEditor.getRawOptions(), {}, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService) || this; _this._parentEditor = parentEditor; _this._overwriteOptions = options; // Overwrite parent's options _super.prototype.updateOptions.call(_this, _this._overwriteOptions); _this._register(parentEditor.onDidChangeConfiguration(function (e) { return _this._onParentConfigurationChanged(e); })); return _this; } EmbeddedCodeEditorWidget.prototype.getParentEditor = function () { return this._parentEditor; }; EmbeddedCodeEditorWidget.prototype._onParentConfigurationChanged = function (e) { _super.prototype.updateOptions.call(this, this._parentEditor.getRawOptions()); _super.prototype.updateOptions.call(this, this._overwriteOptions); }; EmbeddedCodeEditorWidget.prototype.updateOptions = function (newOptions) { objects.mixin(this._overwriteOptions, newOptions, true); _super.prototype.updateOptions.call(this, this._overwriteOptions); }; EmbeddedCodeEditorWidget = __decorate([ __param(3, instantiation_1.IInstantiationService), __param(4, codeEditorService_1.ICodeEditorService), __param(5, commands_1.ICommandService), __param(6, contextkey_1.IContextKeyService), __param(7, themeService_1.IThemeService), __param(8, notification_1.INotificationService), __param(9, accessibility_1.IAccessibilityService) ], EmbeddedCodeEditorWidget); return EmbeddedCodeEditorWidget; }(codeEditorWidget_1.CodeEditorWidget)); exports.EmbeddedCodeEditorWidget = EmbeddedCodeEditorWidget; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[565/*vs/editor/common/services/markerDecorationsServiceImpl*/], __M([0/*require*/,1/*exports*/,72/*vs/platform/markers/common/markers*/,2/*vs/base/common/lifecycle*/,48/*vs/editor/common/model*/,14/*vs/platform/theme/common/themeService*/,44/*vs/editor/common/view/editorColorRegistry*/,49/*vs/editor/common/services/modelService*/,3/*vs/editor/common/core/range*/,38/*vs/base/common/map*/,46/*vs/base/common/network*/,4/*vs/base/common/event*/,21/*vs/base/common/types*/,20/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, markers_1, lifecycle_1, model_1, themeService_1, editorColorRegistry_1, modelService_1, range_1, map_1, network_1, event_1, types_1, colorRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function MODEL_ID(resource) { return resource.toString(); } var MarkerDecorations = /** @class */ (function (_super) { __extends(MarkerDecorations, _super); function MarkerDecorations(model) { var _this = _super.call(this) || this; _this.model = model; _this._markersData = new Map(); _this._register(lifecycle_1.toDisposable(function () { _this.model.deltaDecorations(map_1.keys(_this._markersData), []); _this._markersData.clear(); })); return _this; } MarkerDecorations.prototype.update = function (markers, newDecorations) { var oldIds = map_1.keys(this._markersData); this._markersData.clear(); var ids = this.model.deltaDecorations(oldIds, newDecorations); for (var index = 0; index < ids.length; index++) { this._markersData.set(ids[index], markers[index]); } }; MarkerDecorations.prototype.getMarker = function (decoration) { return this._markersData.get(decoration.id); }; return MarkerDecorations; }(lifecycle_1.Disposable)); var MarkerDecorationsService = /** @class */ (function (_super) { __extends(MarkerDecorationsService, _super); function MarkerDecorationsService(modelService, _markerService) { var _this = _super.call(this) || this; _this._markerService = _markerService; _this._onDidChangeMarker = _this._register(new event_1.Emitter()); _this._markerDecorations = new Map(); modelService.getModels().forEach(function (model) { return _this._onModelAdded(model); }); _this._register(modelService.onModelAdded(_this._onModelAdded, _this)); _this._register(modelService.onModelRemoved(_this._onModelRemoved, _this)); _this._register(_this._markerService.onMarkerChanged(_this._handleMarkerChange, _this)); return _this; } MarkerDecorationsService.prototype.dispose = function () { _super.prototype.dispose.call(this); this._markerDecorations.forEach(function (value) { return value.dispose(); }); this._markerDecorations.clear(); }; MarkerDecorationsService.prototype.getMarker = function (model, decoration) { var markerDecorations = this._markerDecorations.get(MODEL_ID(model.uri)); return markerDecorations ? types_1.withUndefinedAsNull(markerDecorations.getMarker(decoration)) : null; }; MarkerDecorationsService.prototype._handleMarkerChange = function (changedResources) { var _this = this; changedResources.forEach(function (resource) { var markerDecorations = _this._markerDecorations.get(MODEL_ID(resource)); if (markerDecorations) { _this._updateDecorations(markerDecorations); } }); }; MarkerDecorationsService.prototype._onModelAdded = function (model) { var markerDecorations = new MarkerDecorations(model); this._markerDecorations.set(MODEL_ID(model.uri), markerDecorations); this._updateDecorations(markerDecorations); }; MarkerDecorationsService.prototype._onModelRemoved = function (model) { var _this = this; var markerDecorations = this._markerDecorations.get(MODEL_ID(model.uri)); if (markerDecorations) { markerDecorations.dispose(); this._markerDecorations.delete(MODEL_ID(model.uri)); } // clean up markers for internal, transient models if (model.uri.scheme === network_1.Schemas.inMemory || model.uri.scheme === network_1.Schemas.internal || model.uri.scheme === network_1.Schemas.vscode) { if (this._markerService) { this._markerService.read({ resource: model.uri }).map(function (marker) { return marker.owner; }).forEach(function (owner) { return _this._markerService.remove(owner, [model.uri]); }); } } }; MarkerDecorationsService.prototype._updateDecorations = function (markerDecorations) { var _this = this; // Limit to the first 500 errors/warnings var markers = this._markerService.read({ resource: markerDecorations.model.uri, take: 500 }); var newModelDecorations = markers.map(function (marker) { return { range: _this._createDecorationRange(markerDecorations.model, marker), options: _this._createDecorationOption(marker) }; }); markerDecorations.update(markers, newModelDecorations); this._onDidChangeMarker.fire(markerDecorations.model); }; MarkerDecorationsService.prototype._createDecorationRange = function (model, rawMarker) { var ret = range_1.Range.lift(rawMarker); if (rawMarker.severity === markers_1.MarkerSeverity.Hint && !this._hasMarkerTag(rawMarker, 1 /* Unnecessary */) && !this._hasMarkerTag(rawMarker, 2 /* Deprecated */)) { // * never render hints on multiple lines // * make enough space for three dots ret = ret.setEndPosition(ret.startLineNumber, ret.startColumn + 2); } ret = model.validateRange(ret); if (ret.isEmpty()) { var word = model.getWordAtPosition(ret.getStartPosition()); if (word) { ret = new range_1.Range(ret.startLineNumber, word.startColumn, ret.endLineNumber, word.endColumn); } else { var maxColumn = model.getLineLastNonWhitespaceColumn(ret.startLineNumber) || model.getLineMaxColumn(ret.startLineNumber); if (maxColumn === 1) { // empty line // console.warn('marker on empty line:', marker); } else if (ret.endColumn >= maxColumn) { // behind eol ret = new range_1.Range(ret.startLineNumber, maxColumn - 1, ret.endLineNumber, maxColumn); } else { // extend marker to width = 1 ret = new range_1.Range(ret.startLineNumber, ret.startColumn, ret.endLineNumber, ret.endColumn + 1); } } } else if (rawMarker.endColumn === Number.MAX_VALUE && rawMarker.startColumn === 1 && ret.startLineNumber === ret.endLineNumber) { var minColumn = model.getLineFirstNonWhitespaceColumn(rawMarker.startLineNumber); if (minColumn < ret.endColumn) { ret = new range_1.Range(ret.startLineNumber, minColumn, ret.endLineNumber, ret.endColumn); rawMarker.startColumn = minColumn; } } return ret; }; MarkerDecorationsService.prototype._createDecorationOption = function (marker) { var className; var color = undefined; var zIndex; var inlineClassName = undefined; var minimap; switch (marker.severity) { case markers_1.MarkerSeverity.Hint: if (this._hasMarkerTag(marker, 2 /* Deprecated */)) { className = undefined; } else if (this._hasMarkerTag(marker, 1 /* Unnecessary */)) { className = "squiggly-unnecessary" /* EditorUnnecessaryDecoration */; } else { className = "squiggly-hint" /* EditorHintDecoration */; } zIndex = 0; break; case markers_1.MarkerSeverity.Warning: className = "squiggly-warning" /* EditorWarningDecoration */; color = themeService_1.themeColorFromId(editorColorRegistry_1.overviewRulerWarning); zIndex = 20; minimap = { color: themeService_1.themeColorFromId(colorRegistry_1.minimapWarning), position: model_1.MinimapPosition.Inline }; break; case markers_1.MarkerSeverity.Info: className = "squiggly-info" /* EditorInfoDecoration */; color = themeService_1.themeColorFromId(editorColorRegistry_1.overviewRulerInfo); zIndex = 10; break; case markers_1.MarkerSeverity.Error: default: className = "squiggly-error" /* EditorErrorDecoration */; color = themeService_1.themeColorFromId(editorColorRegistry_1.overviewRulerError); zIndex = 30; minimap = { color: themeService_1.themeColorFromId(colorRegistry_1.minimapError), position: model_1.MinimapPosition.Inline }; break; } if (marker.tags) { if (marker.tags.indexOf(1 /* Unnecessary */) !== -1) { inlineClassName = "squiggly-inline-unnecessary" /* EditorUnnecessaryInlineDecoration */; } if (marker.tags.indexOf(2 /* Deprecated */) !== -1) { inlineClassName = "squiggly-inline-deprecated" /* EditorDeprecatedInlineDecoration */; } } return { stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: className, showIfCollapsed: true, overviewRuler: { color: color, position: model_1.OverviewRulerLane.Right }, minimap: minimap, zIndex: zIndex, inlineClassName: inlineClassName, }; }; MarkerDecorationsService.prototype._hasMarkerTag = function (marker, tag) { if (marker.tags) { return marker.tags.indexOf(tag) >= 0; } return false; }; MarkerDecorationsService = __decorate([ __param(0, modelService_1.IModelService), __param(1, markers_1.IMarkerService) ], MarkerDecorationsService); return MarkerDecorationsService; }(lifecycle_1.Disposable)); exports.MarkerDecorationsService = MarkerDecorationsService; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[566/*vs/editor/contrib/bracketMatching/bracketMatching*/], __M([0/*require*/,1/*exports*/,428/*vs/nls!vs/editor/contrib/bracketMatching/bracketMatching*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,12/*vs/editor/browser/editorExtensions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,23/*vs/editor/common/editorContextKeys*/,48/*vs/editor/common/model*/,30/*vs/editor/common/model/textModel*/,44/*vs/editor/common/view/editorColorRegistry*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,65/*vs/platform/actions/common/actions*/,302/*vs/css!vs/editor/contrib/bracketMatching/bracketMatching*/]), function (require, exports, nls, async_1, lifecycle_1, editorExtensions_1, position_1, range_1, selection_1, editorContextKeys_1, model_1, textModel_1, editorColorRegistry_1, colorRegistry_1, themeService_1, actions_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var overviewRulerBracketMatchForeground = colorRegistry_1.registerColor('editorOverviewRuler.bracketMatchForeground', { dark: '#A0A0A0', light: '#A0A0A0', hc: '#A0A0A0' }, nls.localize(0, null)); var JumpToBracketAction = /** @class */ (function (_super) { __extends(JumpToBracketAction, _super); function JumpToBracketAction() { return _super.call(this, { id: 'editor.action.jumpToBracket', label: nls.localize(1, null), alias: 'Go to Bracket', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 88 /* US_BACKSLASH */, weight: 100 /* EditorContrib */ } }) || this; } JumpToBracketAction.prototype.run = function (accessor, editor) { var controller = BracketMatchingController.get(editor); if (!controller) { return; } controller.jumpToBracket(); }; return JumpToBracketAction; }(editorExtensions_1.EditorAction)); var SelectToBracketAction = /** @class */ (function (_super) { __extends(SelectToBracketAction, _super); function SelectToBracketAction() { return _super.call(this, { id: 'editor.action.selectToBracket', label: nls.localize(2, null), alias: 'Select to Bracket', precondition: undefined, description: { description: "Select to Bracket", args: [{ name: 'args', schema: { type: 'object', properties: { 'selectBrackets': { type: 'boolean', default: true } }, } }] } }) || this; } SelectToBracketAction.prototype.run = function (accessor, editor, args) { var controller = BracketMatchingController.get(editor); if (!controller) { return; } var selectBrackets = true; if (args && args.selectBrackets === false) { selectBrackets = false; } controller.selectToBracket(selectBrackets); }; return SelectToBracketAction; }(editorExtensions_1.EditorAction)); var BracketsData = /** @class */ (function () { function BracketsData(position, brackets, options) { this.position = position; this.brackets = brackets; this.options = options; } return BracketsData; }()); var BracketMatchingController = /** @class */ (function (_super) { __extends(BracketMatchingController, _super); function BracketMatchingController(editor) { var _this = _super.call(this) || this; _this._editor = editor; _this._lastBracketsData = []; _this._lastVersionId = 0; _this._decorations = []; _this._updateBracketsSoon = _this._register(new async_1.RunOnceScheduler(function () { return _this._updateBrackets(); }, 50)); _this._matchBrackets = _this._editor.getOption(53 /* matchBrackets */); _this._updateBracketsSoon.schedule(); _this._register(editor.onDidChangeCursorPosition(function (e) { if (_this._matchBrackets === 'never') { // Early exit if nothing needs to be done! // Leave some form of early exit check here if you wish to continue being a cursor position change listener ;) return; } _this._updateBracketsSoon.schedule(); })); _this._register(editor.onDidChangeModelContent(function (e) { _this._updateBracketsSoon.schedule(); })); _this._register(editor.onDidChangeModel(function (e) { _this._lastBracketsData = []; _this._decorations = []; _this._updateBracketsSoon.schedule(); })); _this._register(editor.onDidChangeModelLanguageConfiguration(function (e) { _this._lastBracketsData = []; _this._updateBracketsSoon.schedule(); })); _this._register(editor.onDidChangeConfiguration(function (e) { if (e.hasChanged(53 /* matchBrackets */)) { _this._matchBrackets = _this._editor.getOption(53 /* matchBrackets */); _this._decorations = _this._editor.deltaDecorations(_this._decorations, []); _this._lastBracketsData = []; _this._lastVersionId = 0; _this._updateBracketsSoon.schedule(); } })); return _this; } BracketMatchingController.get = function (editor) { return editor.getContribution(BracketMatchingController.ID); }; BracketMatchingController.prototype.jumpToBracket = function () { if (!this._editor.hasModel()) { return; } var model = this._editor.getModel(); var newSelections = this._editor.getSelections().map(function (selection) { var position = selection.getStartPosition(); // find matching brackets if position is on a bracket var brackets = model.matchBracket(position); var newCursorPosition = null; if (brackets) { if (brackets[0].containsPosition(position)) { newCursorPosition = brackets[1].getStartPosition(); } else if (brackets[1].containsPosition(position)) { newCursorPosition = brackets[0].getStartPosition(); } } else { // find the enclosing brackets if the position isn't on a matching bracket var enclosingBrackets = model.findEnclosingBrackets(position); if (enclosingBrackets) { newCursorPosition = enclosingBrackets[0].getStartPosition(); } else { // no enclosing brackets, try the very first next bracket var nextBracket = model.findNextBracket(position); if (nextBracket && nextBracket.range) { newCursorPosition = nextBracket.range.getStartPosition(); } } } if (newCursorPosition) { return new selection_1.Selection(newCursorPosition.lineNumber, newCursorPosition.column, newCursorPosition.lineNumber, newCursorPosition.column); } return new selection_1.Selection(position.lineNumber, position.column, position.lineNumber, position.column); }); this._editor.setSelections(newSelections); this._editor.revealRange(newSelections[0]); }; BracketMatchingController.prototype.selectToBracket = function (selectBrackets) { if (!this._editor.hasModel()) { return; } var model = this._editor.getModel(); var newSelections = []; this._editor.getSelections().forEach(function (selection) { var position = selection.getStartPosition(); var brackets = model.matchBracket(position); if (!brackets) { brackets = model.findEnclosingBrackets(position); if (!brackets) { var nextBracket = model.findNextBracket(position); if (nextBracket && nextBracket.range) { brackets = model.matchBracket(nextBracket.range.getStartPosition()); } } } var selectFrom = null; var selectTo = null; if (brackets) { brackets.sort(range_1.Range.compareRangesUsingStarts); var open_1 = brackets[0], close_1 = brackets[1]; selectFrom = selectBrackets ? open_1.getStartPosition() : open_1.getEndPosition(); selectTo = selectBrackets ? close_1.getEndPosition() : close_1.getStartPosition(); } if (selectFrom && selectTo) { newSelections.push(new selection_1.Selection(selectFrom.lineNumber, selectFrom.column, selectTo.lineNumber, selectTo.column)); } }); if (newSelections.length > 0) { this._editor.setSelections(newSelections); this._editor.revealRange(newSelections[0]); } }; BracketMatchingController.prototype._updateBrackets = function () { if (this._matchBrackets === 'never') { return; } this._recomputeBrackets(); var newDecorations = [], newDecorationsLen = 0; for (var _i = 0, _a = this._lastBracketsData; _i < _a.length; _i++) { var bracketData = _a[_i]; var brackets = bracketData.brackets; if (brackets) { newDecorations[newDecorationsLen++] = { range: brackets[0], options: bracketData.options }; newDecorations[newDecorationsLen++] = { range: brackets[1], options: bracketData.options }; } } this._decorations = this._editor.deltaDecorations(this._decorations, newDecorations); }; BracketMatchingController.prototype._recomputeBrackets = function () { if (!this._editor.hasModel()) { // no model => no brackets! this._lastBracketsData = []; this._lastVersionId = 0; return; } var selections = this._editor.getSelections(); if (selections.length > 100) { // no bracket matching for high numbers of selections this._lastBracketsData = []; this._lastVersionId = 0; return; } var model = this._editor.getModel(); var versionId = model.getVersionId(); var previousData = []; if (this._lastVersionId === versionId) { // use the previous data only if the model is at the same version id previousData = this._lastBracketsData; } var positions = [], positionsLen = 0; for (var i = 0, len = selections.length; i < len; i++) { var selection = selections[i]; if (selection.isEmpty()) { // will bracket match a cursor only if the selection is collapsed positions[positionsLen++] = selection.getStartPosition(); } } // sort positions for `previousData` cache hits if (positions.length > 1) { positions.sort(position_1.Position.compare); } var newData = [], newDataLen = 0; var previousIndex = 0, previousLen = previousData.length; for (var i = 0, len = positions.length; i < len; i++) { var position = positions[i]; while (previousIndex < previousLen && previousData[previousIndex].position.isBefore(position)) { previousIndex++; } if (previousIndex < previousLen && previousData[previousIndex].position.equals(position)) { newData[newDataLen++] = previousData[previousIndex]; } else { var brackets = model.matchBracket(position); var options = BracketMatchingController._DECORATION_OPTIONS_WITH_OVERVIEW_RULER; if (!brackets && this._matchBrackets === 'always') { brackets = model.findEnclosingBrackets(position, 20 /* give at most 20ms to compute */); options = BracketMatchingController._DECORATION_OPTIONS_WITHOUT_OVERVIEW_RULER; } newData[newDataLen++] = new BracketsData(position, brackets, options); } } this._lastBracketsData = newData; this._lastVersionId = versionId; }; BracketMatchingController.ID = 'editor.contrib.bracketMatchingController'; BracketMatchingController._DECORATION_OPTIONS_WITH_OVERVIEW_RULER = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'bracket-match', overviewRuler: { color: themeService_1.themeColorFromId(overviewRulerBracketMatchForeground), position: model_1.OverviewRulerLane.Center } }); BracketMatchingController._DECORATION_OPTIONS_WITHOUT_OVERVIEW_RULER = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'bracket-match' }); return BracketMatchingController; }(lifecycle_1.Disposable)); exports.BracketMatchingController = BracketMatchingController; editorExtensions_1.registerEditorContribution(BracketMatchingController.ID, BracketMatchingController); editorExtensions_1.registerEditorAction(SelectToBracketAction); editorExtensions_1.registerEditorAction(JumpToBracketAction); themeService_1.registerThemingParticipant(function (theme, collector) { var bracketMatchBackground = theme.getColor(editorColorRegistry_1.editorBracketMatchBackground); if (bracketMatchBackground) { collector.addRule(".monaco-editor .bracket-match { background-color: " + bracketMatchBackground + "; }"); } var bracketMatchBorder = theme.getColor(editorColorRegistry_1.editorBracketMatchBorder); if (bracketMatchBorder) { collector.addRule(".monaco-editor .bracket-match { border: 1px solid " + bracketMatchBorder + "; }"); } }); // Go to menu actions_1.MenuRegistry.appendMenuItem(19 /* MenubarGoMenu */, { group: '5_infile_nav', command: { id: 'editor.action.jumpToBracket', title: nls.localize(3, null) }, order: 2 }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[567/*vs/editor/contrib/codeAction/lightBulbWidget*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,78/*vs/base/browser/globalMouseMoveMonitor*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,30/*vs/editor/common/model/textModel*/,433/*vs/nls!vs/editor/contrib/codeAction/lightBulbWidget*/,34/*vs/platform/keybinding/common/keybinding*/,14/*vs/platform/theme/common/themeService*/,20/*vs/platform/theme/common/colorRegistry*/,57/*vs/base/browser/touch*/,304/*vs/css!vs/editor/contrib/codeAction/lightBulbWidget*/]), function (require, exports, dom, globalMouseMoveMonitor_1, event_1, lifecycle_1, textModel_1, nls, keybinding_1, themeService_1, colorRegistry_1, touch_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LightBulbState; (function (LightBulbState) { LightBulbState.Hidden = { type: 0 /* Hidden */ }; var Showing = /** @class */ (function () { function Showing(actions, trigger, editorPosition, widgetPosition) { this.actions = actions; this.trigger = trigger; this.editorPosition = editorPosition; this.widgetPosition = widgetPosition; this.type = 1 /* Showing */; } return Showing; }()); LightBulbState.Showing = Showing; })(LightBulbState || (LightBulbState = {})); var LightBulbWidget = /** @class */ (function (_super) { __extends(LightBulbWidget, _super); function LightBulbWidget(_editor, _quickFixActionId, _preferredFixActionId, _keybindingService) { var _this = _super.call(this) || this; _this._editor = _editor; _this._quickFixActionId = _quickFixActionId; _this._preferredFixActionId = _preferredFixActionId; _this._keybindingService = _keybindingService; _this._onClick = _this._register(new event_1.Emitter()); _this.onClick = _this._onClick.event; _this._state = LightBulbState.Hidden; _this._domNode = document.createElement('div'); _this._domNode.className = 'codicon codicon-lightbulb'; _this._editor.addContentWidget(_this); _this._register(_this._editor.onDidChangeModelContent(function (_) { // cancel when the line in question has been removed var editorModel = _this._editor.getModel(); if (_this.state.type !== 1 /* Showing */ || !editorModel || _this.state.editorPosition.lineNumber >= editorModel.getLineCount()) { _this.hide(); } })); touch_1.Gesture.ignoreTarget(_this._domNode); _this._register(dom.addStandardDisposableGenericMouseDownListner(_this._domNode, function (e) { if (_this.state.type !== 1 /* Showing */) { return; } // Make sure that focus / cursor location is not lost when clicking widget icon _this._editor.focus(); e.preventDefault(); // a bit of extra work to make sure the menu // doesn't cover the line-text var _a = dom.getDomNodePagePosition(_this._domNode), top = _a.top, height = _a.height; var lineHeight = _this._editor.getOption(49 /* lineHeight */); var pad = Math.floor(lineHeight / 3); if (_this.state.widgetPosition.position !== null && _this.state.widgetPosition.position.lineNumber < _this.state.editorPosition.lineNumber) { pad += lineHeight; } _this._onClick.fire({ x: e.posx, y: top + height + pad, actions: _this.state.actions, trigger: _this.state.trigger, }); })); _this._register(dom.addDisposableListener(_this._domNode, 'mouseenter', function (e) { if ((e.buttons & 1) !== 1) { return; } // mouse enters lightbulb while the primary/left button // is being pressed -> hide the lightbulb and block future // showings until mouse is released _this.hide(); var monitor = new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor(); monitor.startMonitoring(e.target, e.buttons, globalMouseMoveMonitor_1.standardMouseMoveMerger, function () { }, function () { monitor.dispose(); }); })); _this._register(_this._editor.onDidChangeConfiguration(function (e) { // hide when told to do so if (e.hasChanged(47 /* lightbulb */) && !_this._editor.getOption(47 /* lightbulb */).enabled) { _this.hide(); } })); _this._updateLightBulbTitle(); _this._register(_this._keybindingService.onDidUpdateKeybindings(_this._updateLightBulbTitle, _this)); return _this; } LightBulbWidget.prototype.dispose = function () { _super.prototype.dispose.call(this); this._editor.removeContentWidget(this); }; LightBulbWidget.prototype.getId = function () { return 'LightBulbWidget'; }; LightBulbWidget.prototype.getDomNode = function () { return this._domNode; }; LightBulbWidget.prototype.getPosition = function () { return this._state.type === 1 /* Showing */ ? this._state.widgetPosition : null; }; LightBulbWidget.prototype.update = function (actions, trigger, atPosition) { var _this = this; if (actions.validActions.length <= 0) { return this.hide(); } var options = this._editor.getOptions(); if (!options.get(47 /* lightbulb */).enabled) { return this.hide(); } var lineNumber = atPosition.lineNumber, column = atPosition.column; var model = this._editor.getModel(); if (!model) { return this.hide(); } var tabSize = model.getOptions().tabSize; var fontInfo = options.get(34 /* fontInfo */); var lineContent = model.getLineContent(lineNumber); var indent = textModel_1.TextModel.computeIndentLevel(lineContent, tabSize); var lineHasSpace = fontInfo.spaceWidth * indent > 22; var isFolded = function (lineNumber) { return lineNumber > 2 && _this._editor.getTopForLineNumber(lineNumber) === _this._editor.getTopForLineNumber(lineNumber - 1); }; var effectiveLineNumber = lineNumber; if (!lineHasSpace) { if (lineNumber > 1 && !isFolded(lineNumber - 1)) { effectiveLineNumber -= 1; } else if (!isFolded(lineNumber + 1)) { effectiveLineNumber += 1; } else if (column * fontInfo.spaceWidth < 22) { // cannot show lightbulb above/below and showing // it inline would overlay the cursor... return this.hide(); } } this.state = new LightBulbState.Showing(actions, trigger, atPosition, { position: { lineNumber: effectiveLineNumber, column: 1 }, preference: LightBulbWidget._posPref }); dom.toggleClass(this._domNode, 'codicon-lightbulb-autofix', actions.hasAutoFix); this._editor.layoutContentWidget(this); }; LightBulbWidget.prototype.hide = function () { this.state = LightBulbState.Hidden; this._editor.layoutContentWidget(this); }; Object.defineProperty(LightBulbWidget.prototype, "state", { get: function () { return this._state; }, set: function (value) { this._state = value; this._updateLightBulbTitle(); }, enumerable: true, configurable: true }); LightBulbWidget.prototype._updateLightBulbTitle = function () { if (this.state.type === 1 /* Showing */ && this.state.actions.hasAutoFix) { var preferredKb = this._keybindingService.lookupKeybinding(this._preferredFixActionId); if (preferredKb) { this.title = nls.localize(0, null, preferredKb.getLabel()); return; } } var kb = this._keybindingService.lookupKeybinding(this._quickFixActionId); if (kb) { this.title = nls.localize(1, null, kb.getLabel()); } else { this.title = nls.localize(2, null); } }; Object.defineProperty(LightBulbWidget.prototype, "title", { set: function (value) { this._domNode.title = value; }, enumerable: true, configurable: true }); LightBulbWidget._posPref = [0 /* EXACT */]; LightBulbWidget = __decorate([ __param(3, keybinding_1.IKeybindingService) ], LightBulbWidget); return LightBulbWidget; }(lifecycle_1.Disposable)); exports.LightBulbWidget = LightBulbWidget; themeService_1.registerThemingParticipant(function (theme, collector) { // Lightbulb Icon var editorLightBulbForegroundColor = theme.getColor(colorRegistry_1.editorLightBulbForeground); if (editorLightBulbForegroundColor) { collector.addRule("\n\t\t.monaco-editor .contentWidgets .codicon-lightbulb {\n\t\t\tcolor: " + editorLightBulbForegroundColor + ";\n\t\t}"); } // Lightbulb Auto Fix Icon var editorLightBulbAutoFixForegroundColor = theme.getColor(colorRegistry_1.editorLightBulbAutoFixForeground); if (editorLightBulbAutoFixForegroundColor) { collector.addRule("\n\t\t.monaco-editor .contentWidgets .codicon-lightbulb-autofix {\n\t\t\tcolor: " + editorLightBulbAutoFixForegroundColor + ";\n\t\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[568/*vs/editor/contrib/codelens/codelensWidget*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,100/*vs/base/common/codicons*/,5/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/,30/*vs/editor/common/model/textModel*/,44/*vs/editor/common/view/editorColorRegistry*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,305/*vs/css!vs/editor/contrib/codelens/codelensWidget*/]), function (require, exports, dom, codicons_1, strings_1, range_1, textModel_1, editorColorRegistry_1, colorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CodeLensViewZone = /** @class */ (function () { function CodeLensViewZone(afterLineNumber, onHeight) { this.afterLineNumber = afterLineNumber; this._onHeight = onHeight; this.heightInLines = 1; this.suppressMouseDown = true; this.domNode = document.createElement('div'); } CodeLensViewZone.prototype.onComputedHeight = function (height) { if (this._lastHeight === undefined) { this._lastHeight = height; } else if (this._lastHeight !== height) { this._lastHeight = height; this._onHeight(); } }; return CodeLensViewZone; }()); var CodeLensContentWidget = /** @class */ (function () { function CodeLensContentWidget(editor, className, line) { // Editor.IContentWidget.allowEditorOverflow this.allowEditorOverflow = false; this.suppressMouseDown = true; this._commands = new Map(); this._isEmpty = true; this._editor = editor; this._id = "codelens.widget-" + (CodeLensContentWidget._idPool++); this.updatePosition(line); this._domNode = document.createElement('span'); this._domNode.className = "codelens-decoration " + className; } CodeLensContentWidget.prototype.withCommands = function (lenses, animate) { this._commands.clear(); var innerHtml = ''; var hasSymbol = false; for (var i = 0; i < lenses.length; i++) { var lens = lenses[i]; if (!lens) { continue; } hasSymbol = true; if (lens.command) { var title = codicons_1.renderCodicons(strings_1.escape(lens.command.title)); if (lens.command.id) { innerHtml += "" + title + ""; this._commands.set(String(i), lens.command); } else { innerHtml += "" + title + ""; } if (i + 1 < lenses.length) { innerHtml += ' | '; } } } if (!hasSymbol) { // symbols but no commands this._domNode.innerHTML = 'no commands'; } else { // symbols and commands if (!innerHtml) { innerHtml = ' '; } this._domNode.innerHTML = innerHtml; if (this._isEmpty && animate) { dom.addClass(this._domNode, 'fadein'); } this._isEmpty = false; } }; CodeLensContentWidget.prototype.getCommand = function (link) { return link.parentElement === this._domNode ? this._commands.get(link.id) : undefined; }; CodeLensContentWidget.prototype.getId = function () { return this._id; }; CodeLensContentWidget.prototype.getDomNode = function () { return this._domNode; }; CodeLensContentWidget.prototype.updatePosition = function (line) { var column = this._editor.getModel().getLineFirstNonWhitespaceColumn(line); this._widgetPosition = { position: { lineNumber: line, column: column }, preference: [1 /* ABOVE */] }; }; CodeLensContentWidget.prototype.getPosition = function () { return this._widgetPosition || null; }; CodeLensContentWidget._idPool = 0; return CodeLensContentWidget; }()); var CodeLensHelper = /** @class */ (function () { function CodeLensHelper() { this._removeDecorations = []; this._addDecorations = []; this._addDecorationsCallbacks = []; } CodeLensHelper.prototype.addDecoration = function (decoration, callback) { this._addDecorations.push(decoration); this._addDecorationsCallbacks.push(callback); }; CodeLensHelper.prototype.removeDecoration = function (decorationId) { this._removeDecorations.push(decorationId); }; CodeLensHelper.prototype.commit = function (changeAccessor) { var resultingDecorations = changeAccessor.deltaDecorations(this._removeDecorations, this._addDecorations); for (var i = 0, len = resultingDecorations.length; i < len; i++) { this._addDecorationsCallbacks[i](resultingDecorations[i]); } }; return CodeLensHelper; }()); exports.CodeLensHelper = CodeLensHelper; var CodeLensWidget = /** @class */ (function () { function CodeLensWidget(data, editor, className, helper, viewZoneChangeAccessor, updateCallback) { var _this = this; this._isDisposed = false; this._editor = editor; this._className = className; this._data = data; // create combined range, track all ranges with decorations, // check if there is already something to render this._decorationIds = []; var range; var lenses = []; this._data.forEach(function (codeLensData, i) { if (codeLensData.symbol.command) { lenses.push(codeLensData.symbol); } helper.addDecoration({ range: codeLensData.symbol.range, options: textModel_1.ModelDecorationOptions.EMPTY }, function (id) { return _this._decorationIds[i] = id; }); // the range contains all lenses on this line if (!range) { range = range_1.Range.lift(codeLensData.symbol.range); } else { range = range_1.Range.plusRange(range, codeLensData.symbol.range); } }); this._viewZone = new CodeLensViewZone(range.startLineNumber - 1, updateCallback); this._viewZoneId = viewZoneChangeAccessor.addZone(this._viewZone); if (lenses.length > 0) { this._createContentWidgetIfNecessary(); this._contentWidget.withCommands(lenses, false); } } CodeLensWidget.prototype._createContentWidgetIfNecessary = function () { if (!this._contentWidget) { this._contentWidget = new CodeLensContentWidget(this._editor, this._className, this._viewZone.afterLineNumber + 1); this._editor.addContentWidget(this._contentWidget); } }; CodeLensWidget.prototype.dispose = function (helper, viewZoneChangeAccessor) { this._decorationIds.forEach(helper.removeDecoration, helper); this._decorationIds = []; if (viewZoneChangeAccessor) { viewZoneChangeAccessor.removeZone(this._viewZoneId); } if (this._contentWidget) { this._editor.removeContentWidget(this._contentWidget); this._contentWidget = undefined; } this._isDisposed = true; }; CodeLensWidget.prototype.isDisposed = function () { return this._isDisposed; }; CodeLensWidget.prototype.isValid = function () { var _this = this; return this._decorationIds.some(function (id, i) { var range = _this._editor.getModel().getDecorationRange(id); var symbol = _this._data[i].symbol; return !!(range && range_1.Range.isEmpty(symbol.range) === range.isEmpty()); }); }; CodeLensWidget.prototype.updateCodeLensSymbols = function (data, helper) { var _this = this; this._decorationIds.forEach(helper.removeDecoration, helper); this._decorationIds = []; this._data = data; this._data.forEach(function (codeLensData, i) { helper.addDecoration({ range: codeLensData.symbol.range, options: textModel_1.ModelDecorationOptions.EMPTY }, function (id) { return _this._decorationIds[i] = id; }); }); }; CodeLensWidget.prototype.computeIfNecessary = function (model) { if (!this._viewZone.domNode.hasAttribute('monaco-visible-view-zone')) { return null; } // Read editor current state for (var i = 0; i < this._decorationIds.length; i++) { var range = model.getDecorationRange(this._decorationIds[i]); if (range) { this._data[i].symbol.range = range; } } return this._data; }; CodeLensWidget.prototype.updateCommands = function (symbols) { this._createContentWidgetIfNecessary(); this._contentWidget.withCommands(symbols, true); for (var i = 0; i < this._data.length; i++) { var resolved = symbols[i]; if (resolved) { var symbol = this._data[i].symbol; symbol.command = resolved.command || symbol.command; } } }; CodeLensWidget.prototype.getCommand = function (link) { var _a; return (_a = this._contentWidget) === null || _a === void 0 ? void 0 : _a.getCommand(link); }; CodeLensWidget.prototype.getLineNumber = function () { var range = this._editor.getModel().getDecorationRange(this._decorationIds[0]); if (range) { return range.startLineNumber; } return -1; }; CodeLensWidget.prototype.update = function (viewZoneChangeAccessor) { if (this.isValid()) { var range = this._editor.getModel().getDecorationRange(this._decorationIds[0]); if (range) { this._viewZone.afterLineNumber = range.startLineNumber - 1; viewZoneChangeAccessor.layoutZone(this._viewZoneId); if (this._contentWidget) { this._contentWidget.updatePosition(range.startLineNumber); this._editor.layoutContentWidget(this._contentWidget); } } } }; return CodeLensWidget; }()); exports.CodeLensWidget = CodeLensWidget; themeService_1.registerThemingParticipant(function (theme, collector) { var codeLensForeground = theme.getColor(editorColorRegistry_1.editorCodeLensForeground); if (codeLensForeground) { collector.addRule(".monaco-editor .codelens-decoration { color: " + codeLensForeground + "; }"); collector.addRule(".monaco-editor .codelens-decoration .codicon { color: " + codeLensForeground + "; }"); } var activeLinkForeground = theme.getColor(colorRegistry_1.editorActiveLinkForeground); if (activeLinkForeground) { collector.addRule(".monaco-editor .codelens-decoration > a:hover { color: " + activeLinkForeground + " !important; }"); collector.addRule(".monaco-editor .codelens-decoration > a:hover .codicon { color: " + activeLinkForeground + " !important; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[569/*vs/editor/contrib/codelens/codelensController*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,67/*vs/editor/browser/core/editorState*/,12/*vs/editor/browser/editorExtensions*/,17/*vs/editor/common/modes*/,221/*vs/editor/contrib/codelens/codelens*/,568/*vs/editor/contrib/codelens/codelensWidget*/,29/*vs/platform/commands/common/commands*/,35/*vs/platform/notification/common/notification*/,529/*vs/editor/contrib/codelens/codeLensCache*/,6/*vs/base/browser/dom*/,125/*vs/base/common/hash*/]), function (require, exports, async_1, errors_1, lifecycle_1, editorState_1, editorExtensions_1, modes_1, codelens_1, codelensWidget_1, commands_1, notification_1, codeLensCache_1, dom, hash_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CodeLensContribution = /** @class */ (function () { function CodeLensContribution(_editor, _commandService, _notificationService, _codeLensCache) { var _this = this; this._editor = _editor; this._commandService = _commandService; this._notificationService = _notificationService; this._codeLensCache = _codeLensCache; this._globalToDispose = new lifecycle_1.DisposableStore(); this._localToDispose = new lifecycle_1.DisposableStore(); this._lenses = []; this._oldCodeLensModels = new lifecycle_1.DisposableStore(); this._modelChangeCounter = 0; this._isEnabled = this._editor.getOption(11 /* codeLens */); this._globalToDispose.add(this._editor.onDidChangeModel(function () { return _this._onModelChange(); })); this._globalToDispose.add(this._editor.onDidChangeModelLanguage(function () { return _this._onModelChange(); })); this._globalToDispose.add(this._editor.onDidChangeConfiguration(function () { var prevIsEnabled = _this._isEnabled; _this._isEnabled = _this._editor.getOption(11 /* codeLens */); if (prevIsEnabled !== _this._isEnabled) { _this._onModelChange(); } })); this._globalToDispose.add(modes_1.CodeLensProviderRegistry.onDidChange(this._onModelChange, this)); this._globalToDispose.add(this._editor.onDidChangeConfiguration(function (e) { if (e.hasChanged(34 /* fontInfo */)) { _this._updateLensStyle(); } })); this._onModelChange(); this._styleClassName = hash_1.hash(this._editor.getId()).toString(16); this._styleElement = dom.createStyleSheet(dom.isInShadowDOM(this._editor.getContainerDomNode()) ? this._editor.getContainerDomNode() : undefined); this._updateLensStyle(); } CodeLensContribution.prototype.dispose = function () { this._localDispose(); this._globalToDispose.dispose(); this._oldCodeLensModels.dispose(); lifecycle_1.dispose(this._currentCodeLensModel); }; CodeLensContribution.prototype._updateLensStyle = function () { var options = this._editor.getOptions(); var fontInfo = options.get(34 /* fontInfo */); var lineHeight = options.get(49 /* lineHeight */); var height = Math.round(lineHeight * 1.1); var fontSize = Math.round(fontInfo.fontSize * 0.9); var newStyle = "\n\t\t.monaco-editor .codelens-decoration." + this._styleClassName + " { height: " + height + "px; line-height: " + lineHeight + "px; font-size: " + fontSize + "px; padding-right: " + Math.round(fontInfo.fontSize * 0.45) + "px;}\n\t\t.monaco-editor .codelens-decoration." + this._styleClassName + " > a > .codicon { line-height: " + lineHeight + "px; font-size: " + fontSize + "px; }\n\t\t"; this._styleElement.innerHTML = newStyle; }; CodeLensContribution.prototype._localDispose = function () { if (this._currentFindCodeLensSymbolsPromise) { this._currentFindCodeLensSymbolsPromise.cancel(); this._currentFindCodeLensSymbolsPromise = undefined; this._modelChangeCounter++; } if (this._currentResolveCodeLensSymbolsPromise) { this._currentResolveCodeLensSymbolsPromise.cancel(); this._currentResolveCodeLensSymbolsPromise = undefined; } this._localToDispose.clear(); this._oldCodeLensModels.clear(); lifecycle_1.dispose(this._currentCodeLensModel); }; CodeLensContribution.prototype._onModelChange = function () { var _this = this; this._localDispose(); var model = this._editor.getModel(); if (!model) { return; } if (!this._isEnabled) { return; } var cachedLenses = this._codeLensCache.get(model); if (cachedLenses) { this._renderCodeLensSymbols(cachedLenses); } if (!modes_1.CodeLensProviderRegistry.has(model)) { // no provider -> return but check with // cached lenses. they expire after 30 seconds if (cachedLenses) { this._localToDispose.add(async_1.disposableTimeout(function () { var cachedLensesNow = _this._codeLensCache.get(model); if (cachedLenses === cachedLensesNow) { _this._codeLensCache.delete(model); _this._onModelChange(); } }, 30 * 1000)); } return; } for (var _i = 0, _a = modes_1.CodeLensProviderRegistry.all(model); _i < _a.length; _i++) { var provider = _a[_i]; if (typeof provider.onDidChange === 'function') { var registration = provider.onDidChange(function () { return scheduler.schedule(); }); this._localToDispose.add(registration); } } var detectVisibleLenses = this._detectVisibleLenses = new async_1.RunOnceScheduler(function () { return _this._onViewportChanged(); }, 250); var scheduler = new async_1.RunOnceScheduler(function () { var counterValue = ++_this._modelChangeCounter; if (_this._currentFindCodeLensSymbolsPromise) { _this._currentFindCodeLensSymbolsPromise.cancel(); } _this._currentFindCodeLensSymbolsPromise = async_1.createCancelablePromise(function (token) { return codelens_1.getCodeLensData(model, token); }); _this._currentFindCodeLensSymbolsPromise.then(function (result) { if (counterValue === _this._modelChangeCounter) { // only the last one wins if (_this._currentCodeLensModel) { _this._oldCodeLensModels.add(_this._currentCodeLensModel); } _this._currentCodeLensModel = result; // cache model to reduce flicker _this._codeLensCache.put(model, result); // render lenses _this._renderCodeLensSymbols(result); detectVisibleLenses.schedule(); } }, errors_1.onUnexpectedError); }, 250); this._localToDispose.add(scheduler); this._localToDispose.add(detectVisibleLenses); this._localToDispose.add(this._editor.onDidChangeModelContent(function () { _this._editor.changeDecorations(function (decorationsAccessor) { _this._editor.changeViewZones(function (viewZonesAccessor) { var toDispose = []; var lastLensLineNumber = -1; _this._lenses.forEach(function (lens) { if (!lens.isValid() || lastLensLineNumber === lens.getLineNumber()) { // invalid -> lens collapsed, attach range doesn't exist anymore // line_number -> lenses should never be on the same line toDispose.push(lens); } else { lens.update(viewZonesAccessor); lastLensLineNumber = lens.getLineNumber(); } }); var helper = new codelensWidget_1.CodeLensHelper(); toDispose.forEach(function (l) { l.dispose(helper, viewZonesAccessor); _this._lenses.splice(_this._lenses.indexOf(l), 1); }); helper.commit(decorationsAccessor); }); }); // Compute new `visible` code lenses detectVisibleLenses.schedule(); // Ask for all references again scheduler.schedule(); })); this._localToDispose.add(this._editor.onDidScrollChange(function (e) { if (e.scrollTopChanged && _this._lenses.length > 0) { detectVisibleLenses.schedule(); } })); this._localToDispose.add(this._editor.onDidLayoutChange(function () { detectVisibleLenses.schedule(); })); this._localToDispose.add(lifecycle_1.toDisposable(function () { if (_this._editor.getModel()) { var scrollState = editorState_1.StableEditorScrollState.capture(_this._editor); _this._editor.changeDecorations(function (decorationsAccessor) { _this._editor.changeViewZones(function (viewZonesAccessor) { _this._disposeAllLenses(decorationsAccessor, viewZonesAccessor); }); }); scrollState.restore(_this._editor); } else { // No accessors available _this._disposeAllLenses(undefined, undefined); } })); this._localToDispose.add(this._editor.onMouseUp(function (e) { var _a; if (e.target.type !== 9 /* CONTENT_WIDGET */) { return; } var target = e.target.element; if ((target === null || target === void 0 ? void 0 : target.tagName) === 'SPAN') { target = target.parentElement; } if ((target === null || target === void 0 ? void 0 : target.tagName) === 'A') { for (var _i = 0, _b = _this._lenses; _i < _b.length; _i++) { var lens = _b[_i]; var command = lens.getCommand(target); if (command) { (_a = _this._commandService).executeCommand.apply(_a, __spreadArrays([command.id], (command.arguments || []))).catch(function (err) { return _this._notificationService.error(err); }); break; } } } })); scheduler.schedule(); }; CodeLensContribution.prototype._disposeAllLenses = function (decChangeAccessor, viewZoneChangeAccessor) { var helper = new codelensWidget_1.CodeLensHelper(); for (var _i = 0, _a = this._lenses; _i < _a.length; _i++) { var lens = _a[_i]; lens.dispose(helper, viewZoneChangeAccessor); } if (decChangeAccessor) { helper.commit(decChangeAccessor); } this._lenses = []; }; CodeLensContribution.prototype._renderCodeLensSymbols = function (symbols) { var _this = this; if (!this._editor.hasModel()) { return; } var maxLineNumber = this._editor.getModel().getLineCount(); var groups = []; var lastGroup; for (var _i = 0, _a = symbols.lenses; _i < _a.length; _i++) { var symbol = _a[_i]; var line = symbol.symbol.range.startLineNumber; if (line < 1 || line > maxLineNumber) { // invalid code lens continue; } else if (lastGroup && lastGroup[lastGroup.length - 1].symbol.range.startLineNumber === line) { // on same line as previous lastGroup.push(symbol); } else { // on later line as previous lastGroup = [symbol]; groups.push(lastGroup); } } var scrollState = editorState_1.StableEditorScrollState.capture(this._editor); this._editor.changeDecorations(function (decorationsAccessor) { _this._editor.changeViewZones(function (viewZoneAccessor) { var helper = new codelensWidget_1.CodeLensHelper(); var codeLensIndex = 0; var groupsIndex = 0; while (groupsIndex < groups.length && codeLensIndex < _this._lenses.length) { var symbolsLineNumber = groups[groupsIndex][0].symbol.range.startLineNumber; var codeLensLineNumber = _this._lenses[codeLensIndex].getLineNumber(); if (codeLensLineNumber < symbolsLineNumber) { _this._lenses[codeLensIndex].dispose(helper, viewZoneAccessor); _this._lenses.splice(codeLensIndex, 1); } else if (codeLensLineNumber === symbolsLineNumber) { _this._lenses[codeLensIndex].updateCodeLensSymbols(groups[groupsIndex], helper); groupsIndex++; codeLensIndex++; } else { _this._lenses.splice(codeLensIndex, 0, new codelensWidget_1.CodeLensWidget(groups[groupsIndex], _this._editor, _this._styleClassName, helper, viewZoneAccessor, function () { return _this._detectVisibleLenses && _this._detectVisibleLenses.schedule(); })); codeLensIndex++; groupsIndex++; } } // Delete extra code lenses while (codeLensIndex < _this._lenses.length) { _this._lenses[codeLensIndex].dispose(helper, viewZoneAccessor); _this._lenses.splice(codeLensIndex, 1); } // Create extra symbols while (groupsIndex < groups.length) { _this._lenses.push(new codelensWidget_1.CodeLensWidget(groups[groupsIndex], _this._editor, _this._styleClassName, helper, viewZoneAccessor, function () { return _this._detectVisibleLenses && _this._detectVisibleLenses.schedule(); })); groupsIndex++; } helper.commit(decorationsAccessor); }); }); scrollState.restore(this._editor); }; CodeLensContribution.prototype._onViewportChanged = function () { var _this = this; if (this._currentResolveCodeLensSymbolsPromise) { this._currentResolveCodeLensSymbolsPromise.cancel(); this._currentResolveCodeLensSymbolsPromise = undefined; } var model = this._editor.getModel(); if (!model) { return; } var toResolve = []; var lenses = []; this._lenses.forEach(function (lens) { var request = lens.computeIfNecessary(model); if (request) { toResolve.push(request); lenses.push(lens); } }); if (toResolve.length === 0) { return; } var resolvePromise = async_1.createCancelablePromise(function (token) { var promises = toResolve.map(function (request, i) { var resolvedSymbols = new Array(request.length); var promises = request.map(function (request, i) { if (!request.symbol.command && typeof request.provider.resolveCodeLens === 'function') { return Promise.resolve(request.provider.resolveCodeLens(model, request.symbol, token)).then(function (symbol) { resolvedSymbols[i] = symbol; }, errors_1.onUnexpectedExternalError); } else { resolvedSymbols[i] = request.symbol; return Promise.resolve(undefined); } }); return Promise.all(promises).then(function () { if (!token.isCancellationRequested && !lenses[i].isDisposed()) { lenses[i].updateCommands(resolvedSymbols); } }); }); return Promise.all(promises); }); this._currentResolveCodeLensSymbolsPromise = resolvePromise; this._currentResolveCodeLensSymbolsPromise.then(function () { if (_this._currentCodeLensModel) { // update the cached state with new resolved items _this._codeLensCache.put(model, _this._currentCodeLensModel); } _this._oldCodeLensModels.clear(); // dispose old models once we have updated the UI with the current model if (resolvePromise === _this._currentResolveCodeLensSymbolsPromise) { _this._currentResolveCodeLensSymbolsPromise = undefined; } }, function (err) { errors_1.onUnexpectedError(err); // can also be cancellation! if (resolvePromise === _this._currentResolveCodeLensSymbolsPromise) { _this._currentResolveCodeLensSymbolsPromise = undefined; } }); }; CodeLensContribution.ID = 'css.editor.codeLens'; CodeLensContribution = __decorate([ __param(1, commands_1.ICommandService), __param(2, notification_1.INotificationService), __param(3, codeLensCache_1.ICodeLensCache) ], CodeLensContribution); return CodeLensContribution; }()); exports.CodeLensContribution = CodeLensContribution; editorExtensions_1.registerEditorContribution(CodeLensContribution.ID, CodeLensContribution); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[570/*vs/editor/contrib/colorPicker/colorPickerWidget*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,6/*vs/base/browser/dom*/,78/*vs/base/browser/globalMouseMoveMonitor*/,47/*vs/base/browser/ui/widget*/,27/*vs/base/common/color*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,306/*vs/css!vs/editor/contrib/colorPicker/colorPicker*/]), function (require, exports, browser_1, dom, globalMouseMoveMonitor_1, widget_1, color_1, event_1, lifecycle_1, colorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var $ = dom.$; var ColorPickerHeader = /** @class */ (function (_super) { __extends(ColorPickerHeader, _super); function ColorPickerHeader(container, model, themeService) { var _this = _super.call(this) || this; _this.model = model; _this.domNode = $('.colorpicker-header'); dom.append(container, _this.domNode); _this.pickedColorNode = dom.append(_this.domNode, $('.picked-color')); var colorBox = dom.append(_this.domNode, $('.original-color')); colorBox.style.backgroundColor = color_1.Color.Format.CSS.format(_this.model.originalColor) || ''; _this.backgroundColor = themeService.getTheme().getColor(colorRegistry_1.editorHoverBackground) || color_1.Color.white; _this._register(themeService_1.registerThemingParticipant(function (theme, collector) { _this.backgroundColor = theme.getColor(colorRegistry_1.editorHoverBackground) || color_1.Color.white; })); _this._register(dom.addDisposableListener(_this.pickedColorNode, dom.EventType.CLICK, function () { return _this.model.selectNextColorPresentation(); })); _this._register(dom.addDisposableListener(colorBox, dom.EventType.CLICK, function () { _this.model.color = _this.model.originalColor; _this.model.flushColor(); })); _this._register(model.onDidChangeColor(_this.onDidChangeColor, _this)); _this._register(model.onDidChangePresentation(_this.onDidChangePresentation, _this)); _this.pickedColorNode.style.backgroundColor = color_1.Color.Format.CSS.format(model.color) || ''; dom.toggleClass(_this.pickedColorNode, 'light', model.color.rgba.a < 0.5 ? _this.backgroundColor.isLighter() : model.color.isLighter()); return _this; } ColorPickerHeader.prototype.onDidChangeColor = function (color) { this.pickedColorNode.style.backgroundColor = color_1.Color.Format.CSS.format(color) || ''; dom.toggleClass(this.pickedColorNode, 'light', color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : color.isLighter()); this.onDidChangePresentation(); }; ColorPickerHeader.prototype.onDidChangePresentation = function () { this.pickedColorNode.textContent = this.model.presentation ? this.model.presentation.label : ''; }; return ColorPickerHeader; }(lifecycle_1.Disposable)); exports.ColorPickerHeader = ColorPickerHeader; var ColorPickerBody = /** @class */ (function (_super) { __extends(ColorPickerBody, _super); function ColorPickerBody(container, model, pixelRatio) { var _this = _super.call(this) || this; _this.model = model; _this.pixelRatio = pixelRatio; _this.domNode = $('.colorpicker-body'); dom.append(container, _this.domNode); _this.saturationBox = new SaturationBox(_this.domNode, _this.model, _this.pixelRatio); _this._register(_this.saturationBox); _this._register(_this.saturationBox.onDidChange(_this.onDidSaturationValueChange, _this)); _this._register(_this.saturationBox.onColorFlushed(_this.flushColor, _this)); _this.opacityStrip = new OpacityStrip(_this.domNode, _this.model); _this._register(_this.opacityStrip); _this._register(_this.opacityStrip.onDidChange(_this.onDidOpacityChange, _this)); _this._register(_this.opacityStrip.onColorFlushed(_this.flushColor, _this)); _this.hueStrip = new HueStrip(_this.domNode, _this.model); _this._register(_this.hueStrip); _this._register(_this.hueStrip.onDidChange(_this.onDidHueChange, _this)); _this._register(_this.hueStrip.onColorFlushed(_this.flushColor, _this)); return _this; } ColorPickerBody.prototype.flushColor = function () { this.model.flushColor(); }; ColorPickerBody.prototype.onDidSaturationValueChange = function (_a) { var s = _a.s, v = _a.v; var hsva = this.model.color.hsva; this.model.color = new color_1.Color(new color_1.HSVA(hsva.h, s, v, hsva.a)); }; ColorPickerBody.prototype.onDidOpacityChange = function (a) { var hsva = this.model.color.hsva; this.model.color = new color_1.Color(new color_1.HSVA(hsva.h, hsva.s, hsva.v, a)); }; ColorPickerBody.prototype.onDidHueChange = function (value) { var hsva = this.model.color.hsva; var h = (1 - value) * 360; this.model.color = new color_1.Color(new color_1.HSVA(h === 360 ? 0 : h, hsva.s, hsva.v, hsva.a)); }; ColorPickerBody.prototype.layout = function () { this.saturationBox.layout(); this.opacityStrip.layout(); this.hueStrip.layout(); }; return ColorPickerBody; }(lifecycle_1.Disposable)); exports.ColorPickerBody = ColorPickerBody; var SaturationBox = /** @class */ (function (_super) { __extends(SaturationBox, _super); function SaturationBox(container, model, pixelRatio) { var _this = _super.call(this) || this; _this.model = model; _this.pixelRatio = pixelRatio; _this._onDidChange = new event_1.Emitter(); _this.onDidChange = _this._onDidChange.event; _this._onColorFlushed = new event_1.Emitter(); _this.onColorFlushed = _this._onColorFlushed.event; _this.domNode = $('.saturation-wrap'); dom.append(container, _this.domNode); // Create canvas, draw selected color _this.canvas = document.createElement('canvas'); _this.canvas.className = 'saturation-box'; dom.append(_this.domNode, _this.canvas); // Add selection circle _this.selection = $('.saturation-selection'); dom.append(_this.domNode, _this.selection); _this.layout(); _this._register(dom.addDisposableGenericMouseDownListner(_this.domNode, function (e) { return _this.onMouseDown(e); })); _this._register(_this.model.onDidChangeColor(_this.onDidChangeColor, _this)); _this.monitor = null; return _this; } SaturationBox.prototype.onMouseDown = function (e) { var _this = this; this.monitor = this._register(new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor()); var origin = dom.getDomNodePagePosition(this.domNode); if (e.target !== this.selection) { this.onDidChangePosition(e.offsetX, e.offsetY); } this.monitor.startMonitoring(e.target, e.buttons, globalMouseMoveMonitor_1.standardMouseMoveMerger, function (event) { return _this.onDidChangePosition(event.posx - origin.left, event.posy - origin.top); }, function () { return null; }); var mouseUpListener = dom.addDisposableGenericMouseUpListner(document, function () { _this._onColorFlushed.fire(); mouseUpListener.dispose(); if (_this.monitor) { _this.monitor.stopMonitoring(true); _this.monitor = null; } }, true); }; SaturationBox.prototype.onDidChangePosition = function (left, top) { var s = Math.max(0, Math.min(1, left / this.width)); var v = Math.max(0, Math.min(1, 1 - (top / this.height))); this.paintSelection(s, v); this._onDidChange.fire({ s: s, v: v }); }; SaturationBox.prototype.layout = function () { this.width = this.domNode.offsetWidth; this.height = this.domNode.offsetHeight; this.canvas.width = this.width * this.pixelRatio; this.canvas.height = this.height * this.pixelRatio; this.paint(); var hsva = this.model.color.hsva; this.paintSelection(hsva.s, hsva.v); }; SaturationBox.prototype.paint = function () { var hsva = this.model.color.hsva; var saturatedColor = new color_1.Color(new color_1.HSVA(hsva.h, 1, 1, 1)); var ctx = this.canvas.getContext('2d'); var whiteGradient = ctx.createLinearGradient(0, 0, this.canvas.width, 0); whiteGradient.addColorStop(0, 'rgba(255, 255, 255, 1)'); whiteGradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.5)'); whiteGradient.addColorStop(1, 'rgba(255, 255, 255, 0)'); var blackGradient = ctx.createLinearGradient(0, 0, 0, this.canvas.height); blackGradient.addColorStop(0, 'rgba(0, 0, 0, 0)'); blackGradient.addColorStop(1, 'rgba(0, 0, 0, 1)'); ctx.rect(0, 0, this.canvas.width, this.canvas.height); ctx.fillStyle = color_1.Color.Format.CSS.format(saturatedColor); ctx.fill(); ctx.fillStyle = whiteGradient; ctx.fill(); ctx.fillStyle = blackGradient; ctx.fill(); }; SaturationBox.prototype.paintSelection = function (s, v) { this.selection.style.left = s * this.width + "px"; this.selection.style.top = this.height - v * this.height + "px"; }; SaturationBox.prototype.onDidChangeColor = function () { if (this.monitor && this.monitor.isMonitoring()) { return; } this.paint(); }; return SaturationBox; }(lifecycle_1.Disposable)); var Strip = /** @class */ (function (_super) { __extends(Strip, _super); function Strip(container, model) { var _this = _super.call(this) || this; _this.model = model; _this._onDidChange = new event_1.Emitter(); _this.onDidChange = _this._onDidChange.event; _this._onColorFlushed = new event_1.Emitter(); _this.onColorFlushed = _this._onColorFlushed.event; _this.domNode = dom.append(container, $('.strip')); _this.overlay = dom.append(_this.domNode, $('.overlay')); _this.slider = dom.append(_this.domNode, $('.slider')); _this.slider.style.top = "0px"; _this._register(dom.addDisposableGenericMouseDownListner(_this.domNode, function (e) { return _this.onMouseDown(e); })); _this.layout(); return _this; } Strip.prototype.layout = function () { this.height = this.domNode.offsetHeight - this.slider.offsetHeight; var value = this.getValue(this.model.color); this.updateSliderPosition(value); }; Strip.prototype.onMouseDown = function (e) { var _this = this; var monitor = this._register(new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor()); var origin = dom.getDomNodePagePosition(this.domNode); dom.addClass(this.domNode, 'grabbing'); if (e.target !== this.slider) { this.onDidChangeTop(e.offsetY); } monitor.startMonitoring(e.target, e.buttons, globalMouseMoveMonitor_1.standardMouseMoveMerger, function (event) { return _this.onDidChangeTop(event.posy - origin.top); }, function () { return null; }); var mouseUpListener = dom.addDisposableGenericMouseUpListner(document, function () { _this._onColorFlushed.fire(); mouseUpListener.dispose(); monitor.stopMonitoring(true); dom.removeClass(_this.domNode, 'grabbing'); }, true); }; Strip.prototype.onDidChangeTop = function (top) { var value = Math.max(0, Math.min(1, 1 - (top / this.height))); this.updateSliderPosition(value); this._onDidChange.fire(value); }; Strip.prototype.updateSliderPosition = function (value) { this.slider.style.top = (1 - value) * this.height + "px"; }; return Strip; }(lifecycle_1.Disposable)); var OpacityStrip = /** @class */ (function (_super) { __extends(OpacityStrip, _super); function OpacityStrip(container, model) { var _this = _super.call(this, container, model) || this; dom.addClass(_this.domNode, 'opacity-strip'); _this._register(model.onDidChangeColor(_this.onDidChangeColor, _this)); _this.onDidChangeColor(_this.model.color); return _this; } OpacityStrip.prototype.onDidChangeColor = function (color) { var _a = color.rgba, r = _a.r, g = _a.g, b = _a.b; var opaque = new color_1.Color(new color_1.RGBA(r, g, b, 1)); var transparent = new color_1.Color(new color_1.RGBA(r, g, b, 0)); this.overlay.style.background = "linear-gradient(to bottom, " + opaque + " 0%, " + transparent + " 100%)"; }; OpacityStrip.prototype.getValue = function (color) { return color.hsva.a; }; return OpacityStrip; }(Strip)); var HueStrip = /** @class */ (function (_super) { __extends(HueStrip, _super); function HueStrip(container, model) { var _this = _super.call(this, container, model) || this; dom.addClass(_this.domNode, 'hue-strip'); return _this; } HueStrip.prototype.getValue = function (color) { return 1 - (color.hsva.h / 360); }; return HueStrip; }(Strip)); var ColorPickerWidget = /** @class */ (function (_super) { __extends(ColorPickerWidget, _super); function ColorPickerWidget(container, model, pixelRatio, themeService) { var _this = _super.call(this) || this; _this.model = model; _this.pixelRatio = pixelRatio; _this._register(browser_1.onDidChangeZoomLevel(function () { return _this.layout(); })); var element = $('.colorpicker-widget'); container.appendChild(element); var header = new ColorPickerHeader(element, _this.model, themeService); _this.body = new ColorPickerBody(element, _this.model, _this.pixelRatio); _this._register(header); _this._register(_this.body); return _this; } ColorPickerWidget.prototype.layout = function () { this.body.layout(); }; return ColorPickerWidget; }(widget_1.Widget)); exports.ColorPickerWidget = ColorPickerWidget; }); define(__m[231/*vs/editor/contrib/documentSymbols/outlineTree*/], __M([0/*require*/,1/*exports*/,437/*vs/nls!vs/editor/contrib/documentSymbols/outlineTree*/,14/*vs/platform/theme/common/themeService*/,20/*vs/platform/theme/common/colorRegistry*/,308/*vs/css!vs/editor/contrib/documentSymbols/media/outlineTree*/,309/*vs/css!vs/editor/contrib/documentSymbols/media/symbol-icons*/]), function (require, exports, nls_1, themeService_1, colorRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SYMBOL_ICON_ARRAY_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.arrayForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(0, null)); exports.SYMBOL_ICON_BOOLEAN_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.booleanForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(1, null)); exports.SYMBOL_ICON_CLASS_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.classForeground', { dark: '#EE9D28', light: '#D67E00', hc: '#EE9D28' }, nls_1.localize(2, null)); exports.SYMBOL_ICON_COLOR_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.colorForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(3, null)); exports.SYMBOL_ICON_CONSTANT_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.constantForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(4, null)); exports.SYMBOL_ICON_CONSTRUCTOR_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.constructorForeground', { dark: '#B180D7', light: '#652D90', hc: '#B180D7' }, nls_1.localize(5, null)); exports.SYMBOL_ICON_ENUMERATOR_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.enumeratorForeground', { dark: '#EE9D28', light: '#D67E00', hc: '#EE9D28' }, nls_1.localize(6, null)); exports.SYMBOL_ICON_ENUMERATOR_MEMBER_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.enumeratorMemberForeground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, nls_1.localize(7, null)); exports.SYMBOL_ICON_EVENT_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.eventForeground', { dark: '#EE9D28', light: '#D67E00', hc: '#EE9D28' }, nls_1.localize(8, null)); exports.SYMBOL_ICON_FIELD_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.fieldForeground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, nls_1.localize(9, null)); exports.SYMBOL_ICON_FILE_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.fileForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(10, null)); exports.SYMBOL_ICON_FOLDER_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.folderForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(11, null)); exports.SYMBOL_ICON_FUNCTION_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.functionForeground', { dark: '#B180D7', light: '#652D90', hc: '#B180D7' }, nls_1.localize(12, null)); exports.SYMBOL_ICON_INTERFACE_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.interfaceForeground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, nls_1.localize(13, null)); exports.SYMBOL_ICON_KEY_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.keyForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(14, null)); exports.SYMBOL_ICON_KEYWORD_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.keywordForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(15, null)); exports.SYMBOL_ICON_METHOD_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.methodForeground', { dark: '#B180D7', light: '#652D90', hc: '#B180D7' }, nls_1.localize(16, null)); exports.SYMBOL_ICON_MODULE_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.moduleForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(17, null)); exports.SYMBOL_ICON_NAMESPACE_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.namespaceForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(18, null)); exports.SYMBOL_ICON_NULL_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.nullForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(19, null)); exports.SYMBOL_ICON_NUMBER_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.numberForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(20, null)); exports.SYMBOL_ICON_OBJECT_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.objectForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(21, null)); exports.SYMBOL_ICON_OPERATOR_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.operatorForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(22, null)); exports.SYMBOL_ICON_PACKAGE_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.packageForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(23, null)); exports.SYMBOL_ICON_PROPERTY_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.propertyForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(24, null)); exports.SYMBOL_ICON_REFERENCE_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.referenceForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(25, null)); exports.SYMBOL_ICON_SNIPPET_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.snippetForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(26, null)); exports.SYMBOL_ICON_STRING_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.stringForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(27, null)); exports.SYMBOL_ICON_STRUCT_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.structForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(28, null)); exports.SYMBOL_ICON_TEXT_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.textForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(29, null)); exports.SYMBOL_ICON_TYPEPARAMETER_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.typeParameterForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(30, null)); exports.SYMBOL_ICON_UNIT_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.unitForeground', { dark: colorRegistry_1.foreground, light: colorRegistry_1.foreground, hc: colorRegistry_1.foreground }, nls_1.localize(31, null)); exports.SYMBOL_ICON_VARIABLE_FOREGROUND = colorRegistry_1.registerColor('symbolIcon.variableForeground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, nls_1.localize(32, null)); themeService_1.registerThemingParticipant(function (theme, collector) { var symbolIconArrayColor = theme.getColor(exports.SYMBOL_ICON_ARRAY_FOREGROUND); if (symbolIconArrayColor) { collector.addRule(".codicon-symbol-array { color: " + symbolIconArrayColor + " !important; }"); } var symbolIconBooleanColor = theme.getColor(exports.SYMBOL_ICON_BOOLEAN_FOREGROUND); if (symbolIconBooleanColor) { collector.addRule(".codicon-symbol-boolean { color: " + symbolIconBooleanColor + " !important; }"); } var symbolIconClassColor = theme.getColor(exports.SYMBOL_ICON_CLASS_FOREGROUND); if (symbolIconClassColor) { collector.addRule(".codicon-symbol-class { color: " + symbolIconClassColor + " !important; }"); } var symbolIconMethodColor = theme.getColor(exports.SYMBOL_ICON_METHOD_FOREGROUND); if (symbolIconMethodColor) { collector.addRule(".codicon-symbol-method { color: " + symbolIconMethodColor + " !important; }"); } var symbolIconColorColor = theme.getColor(exports.SYMBOL_ICON_COLOR_FOREGROUND); if (symbolIconColorColor) { collector.addRule(".codicon-symbol-color { color: " + symbolIconColorColor + " !important; }"); } var symbolIconConstantColor = theme.getColor(exports.SYMBOL_ICON_CONSTANT_FOREGROUND); if (symbolIconConstantColor) { collector.addRule(".codicon-symbol-constant { color: " + symbolIconConstantColor + " !important; }"); } var symbolIconConstructorColor = theme.getColor(exports.SYMBOL_ICON_CONSTRUCTOR_FOREGROUND); if (symbolIconConstructorColor) { collector.addRule(".codicon-symbol-constructor { color: " + symbolIconConstructorColor + " !important; }"); } var symbolIconEnumeratorColor = theme.getColor(exports.SYMBOL_ICON_ENUMERATOR_FOREGROUND); if (symbolIconEnumeratorColor) { collector.addRule("\n\t\t\t.codicon-symbol-value,.codicon-symbol-enum { color: " + symbolIconEnumeratorColor + " !important; }"); } var symbolIconEnumeratorMemberColor = theme.getColor(exports.SYMBOL_ICON_ENUMERATOR_MEMBER_FOREGROUND); if (symbolIconEnumeratorMemberColor) { collector.addRule(".codicon-symbol-enum-member { color: " + symbolIconEnumeratorMemberColor + " !important; }"); } var symbolIconEventColor = theme.getColor(exports.SYMBOL_ICON_EVENT_FOREGROUND); if (symbolIconEventColor) { collector.addRule(".codicon-symbol-event { color: " + symbolIconEventColor + " !important; }"); } var symbolIconFieldColor = theme.getColor(exports.SYMBOL_ICON_FIELD_FOREGROUND); if (symbolIconFieldColor) { collector.addRule(".codicon-symbol-field { color: " + symbolIconFieldColor + " !important; }"); } var symbolIconFileColor = theme.getColor(exports.SYMBOL_ICON_FILE_FOREGROUND); if (symbolIconFileColor) { collector.addRule(".codicon-symbol-file { color: " + symbolIconFileColor + " !important; }"); } var symbolIconFolderColor = theme.getColor(exports.SYMBOL_ICON_FOLDER_FOREGROUND); if (symbolIconFolderColor) { collector.addRule(".codicon-symbol-folder { color: " + symbolIconFolderColor + " !important; }"); } var symbolIconFunctionColor = theme.getColor(exports.SYMBOL_ICON_FUNCTION_FOREGROUND); if (symbolIconFunctionColor) { collector.addRule(".codicon-symbol-function { color: " + symbolIconFunctionColor + " !important; }"); } var symbolIconInterfaceColor = theme.getColor(exports.SYMBOL_ICON_INTERFACE_FOREGROUND); if (symbolIconInterfaceColor) { collector.addRule(".codicon-symbol-interface { color: " + symbolIconInterfaceColor + " !important; }"); } var symbolIconKeyColor = theme.getColor(exports.SYMBOL_ICON_KEY_FOREGROUND); if (symbolIconKeyColor) { collector.addRule(".codicon-symbol-key { color: " + symbolIconKeyColor + " !important; }"); } var symbolIconKeywordColor = theme.getColor(exports.SYMBOL_ICON_KEYWORD_FOREGROUND); if (symbolIconKeywordColor) { collector.addRule(".codicon-symbol-keyword { color: " + symbolIconKeywordColor + " !important; }"); } var symbolIconModuleColor = theme.getColor(exports.SYMBOL_ICON_MODULE_FOREGROUND); if (symbolIconModuleColor) { collector.addRule(".codicon-symbol-module { color: " + symbolIconModuleColor + " !important; }"); } var outlineNamespaceColor = theme.getColor(exports.SYMBOL_ICON_NAMESPACE_FOREGROUND); if (outlineNamespaceColor) { collector.addRule(".codicon-symbol-namespace { color: " + outlineNamespaceColor + " !important; }"); } var symbolIconNullColor = theme.getColor(exports.SYMBOL_ICON_NULL_FOREGROUND); if (symbolIconNullColor) { collector.addRule(".codicon-symbol-null { color: " + symbolIconNullColor + " !important; }"); } var symbolIconNumberColor = theme.getColor(exports.SYMBOL_ICON_NUMBER_FOREGROUND); if (symbolIconNumberColor) { collector.addRule(".codicon-symbol-number { color: " + symbolIconNumberColor + " !important; }"); } var symbolIconObjectColor = theme.getColor(exports.SYMBOL_ICON_OBJECT_FOREGROUND); if (symbolIconObjectColor) { collector.addRule(".codicon-symbol-object { color: " + symbolIconObjectColor + " !important; }"); } var symbolIconOperatorColor = theme.getColor(exports.SYMBOL_ICON_OPERATOR_FOREGROUND); if (symbolIconOperatorColor) { collector.addRule(".codicon-symbol-operator { color: " + symbolIconOperatorColor + " !important; }"); } var symbolIconPackageColor = theme.getColor(exports.SYMBOL_ICON_PACKAGE_FOREGROUND); if (symbolIconPackageColor) { collector.addRule(".codicon-symbol-package { color: " + symbolIconPackageColor + " !important; }"); } var symbolIconPropertyColor = theme.getColor(exports.SYMBOL_ICON_PROPERTY_FOREGROUND); if (symbolIconPropertyColor) { collector.addRule(".codicon-symbol-property { color: " + symbolIconPropertyColor + " !important; }"); } var symbolIconReferenceColor = theme.getColor(exports.SYMBOL_ICON_REFERENCE_FOREGROUND); if (symbolIconReferenceColor) { collector.addRule(".codicon-symbol-reference { color: " + symbolIconReferenceColor + " !important; }"); } var symbolIconSnippetColor = theme.getColor(exports.SYMBOL_ICON_SNIPPET_FOREGROUND); if (symbolIconSnippetColor) { collector.addRule(".codicon-symbol-snippet { color: " + symbolIconSnippetColor + " !important; }"); } var symbolIconStringColor = theme.getColor(exports.SYMBOL_ICON_STRING_FOREGROUND); if (symbolIconStringColor) { collector.addRule(".codicon-symbol-string { color: " + symbolIconStringColor + " !important; }"); } var symbolIconStructColor = theme.getColor(exports.SYMBOL_ICON_STRUCT_FOREGROUND); if (symbolIconStructColor) { collector.addRule(".codicon-symbol-struct { color: " + symbolIconStructColor + " !important; }"); } var symbolIconTextColor = theme.getColor(exports.SYMBOL_ICON_TEXT_FOREGROUND); if (symbolIconTextColor) { collector.addRule(".codicon-symbol-text { color: " + symbolIconTextColor + " !important; }"); } var symbolIconTypeParameterColor = theme.getColor(exports.SYMBOL_ICON_TYPEPARAMETER_FOREGROUND); if (symbolIconTypeParameterColor) { collector.addRule(".codicon-symbol-type-parameter { color: " + symbolIconTypeParameterColor + " !important; }"); } var symbolIconUnitColor = theme.getColor(exports.SYMBOL_ICON_UNIT_FOREGROUND); if (symbolIconUnitColor) { collector.addRule(".codicon-symbol-unit { color: " + symbolIconUnitColor + " !important; }"); } var symbolIconVariableColor = theme.getColor(exports.SYMBOL_ICON_VARIABLE_FOREGROUND); if (symbolIconVariableColor) { collector.addRule(".codicon-symbol-variable { color: " + symbolIconVariableColor + " !important; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[571/*vs/editor/contrib/find/findDecorations*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,48/*vs/editor/common/model*/,30/*vs/editor/common/model/textModel*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, range_1, model_1, textModel_1, colorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var FindDecorations = /** @class */ (function () { function FindDecorations(editor) { this._editor = editor; this._decorations = []; this._overviewRulerApproximateDecorations = []; this._findScopeDecorationId = null; this._rangeHighlightDecorationId = null; this._highlightedDecorationId = null; this._startPosition = this._editor.getPosition(); } FindDecorations.prototype.dispose = function () { this._editor.deltaDecorations(this._allDecorations(), []); this._decorations = []; this._overviewRulerApproximateDecorations = []; this._findScopeDecorationId = null; this._rangeHighlightDecorationId = null; this._highlightedDecorationId = null; }; FindDecorations.prototype.reset = function () { this._decorations = []; this._overviewRulerApproximateDecorations = []; this._findScopeDecorationId = null; this._rangeHighlightDecorationId = null; this._highlightedDecorationId = null; }; FindDecorations.prototype.getCount = function () { return this._decorations.length; }; FindDecorations.prototype.getFindScope = function () { if (this._findScopeDecorationId) { return this._editor.getModel().getDecorationRange(this._findScopeDecorationId); } return null; }; FindDecorations.prototype.getStartPosition = function () { return this._startPosition; }; FindDecorations.prototype.setStartPosition = function (newStartPosition) { this._startPosition = newStartPosition; this.setCurrentFindMatch(null); }; FindDecorations.prototype._getDecorationIndex = function (decorationId) { var index = this._decorations.indexOf(decorationId); if (index >= 0) { return index + 1; } return 1; }; FindDecorations.prototype.getCurrentMatchesPosition = function (desiredRange) { var candidates = this._editor.getModel().getDecorationsInRange(desiredRange); for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { var candidate = candidates_1[_i]; var candidateOpts = candidate.options; if (candidateOpts === FindDecorations._FIND_MATCH_DECORATION || candidateOpts === FindDecorations._CURRENT_FIND_MATCH_DECORATION) { return this._getDecorationIndex(candidate.id); } } return 1; }; FindDecorations.prototype.setCurrentFindMatch = function (nextMatch) { var _this = this; var newCurrentDecorationId = null; var matchPosition = 0; if (nextMatch) { for (var i = 0, len = this._decorations.length; i < len; i++) { var range = this._editor.getModel().getDecorationRange(this._decorations[i]); if (nextMatch.equalsRange(range)) { newCurrentDecorationId = this._decorations[i]; matchPosition = (i + 1); break; } } } if (this._highlightedDecorationId !== null || newCurrentDecorationId !== null) { this._editor.changeDecorations(function (changeAccessor) { if (_this._highlightedDecorationId !== null) { changeAccessor.changeDecorationOptions(_this._highlightedDecorationId, FindDecorations._FIND_MATCH_DECORATION); _this._highlightedDecorationId = null; } if (newCurrentDecorationId !== null) { _this._highlightedDecorationId = newCurrentDecorationId; changeAccessor.changeDecorationOptions(_this._highlightedDecorationId, FindDecorations._CURRENT_FIND_MATCH_DECORATION); } if (_this._rangeHighlightDecorationId !== null) { changeAccessor.removeDecoration(_this._rangeHighlightDecorationId); _this._rangeHighlightDecorationId = null; } if (newCurrentDecorationId !== null) { var rng = _this._editor.getModel().getDecorationRange(newCurrentDecorationId); if (rng.startLineNumber !== rng.endLineNumber && rng.endColumn === 1) { var lineBeforeEnd = rng.endLineNumber - 1; var lineBeforeEndMaxColumn = _this._editor.getModel().getLineMaxColumn(lineBeforeEnd); rng = new range_1.Range(rng.startLineNumber, rng.startColumn, lineBeforeEnd, lineBeforeEndMaxColumn); } _this._rangeHighlightDecorationId = changeAccessor.addDecoration(rng, FindDecorations._RANGE_HIGHLIGHT_DECORATION); } }); } return matchPosition; }; FindDecorations.prototype.set = function (findMatches, findScope) { var _this = this; this._editor.changeDecorations(function (accessor) { var findMatchesOptions = FindDecorations._FIND_MATCH_DECORATION; var newOverviewRulerApproximateDecorations = []; if (findMatches.length > 1000) { // we go into a mode where the overview ruler gets "approximate" decorations // the reason is that the overview ruler paints all the decorations in the file and we don't want to cause freezes findMatchesOptions = FindDecorations._FIND_MATCH_NO_OVERVIEW_DECORATION; // approximate a distance in lines where matches should be merged var lineCount = _this._editor.getModel().getLineCount(); var height = _this._editor.getLayoutInfo().height; var approxPixelsPerLine = height / lineCount; var mergeLinesDelta = Math.max(2, Math.ceil(3 / approxPixelsPerLine)); // merge decorations as much as possible var prevStartLineNumber = findMatches[0].range.startLineNumber; var prevEndLineNumber = findMatches[0].range.endLineNumber; for (var i = 1, len = findMatches.length; i < len; i++) { var range = findMatches[i].range; if (prevEndLineNumber + mergeLinesDelta >= range.startLineNumber) { if (range.endLineNumber > prevEndLineNumber) { prevEndLineNumber = range.endLineNumber; } } else { newOverviewRulerApproximateDecorations.push({ range: new range_1.Range(prevStartLineNumber, 1, prevEndLineNumber, 1), options: FindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION }); prevStartLineNumber = range.startLineNumber; prevEndLineNumber = range.endLineNumber; } } newOverviewRulerApproximateDecorations.push({ range: new range_1.Range(prevStartLineNumber, 1, prevEndLineNumber, 1), options: FindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION }); } // Find matches var newFindMatchesDecorations = new Array(findMatches.length); for (var i = 0, len = findMatches.length; i < len; i++) { newFindMatchesDecorations[i] = { range: findMatches[i].range, options: findMatchesOptions }; } _this._decorations = accessor.deltaDecorations(_this._decorations, newFindMatchesDecorations); // Overview ruler approximate decorations _this._overviewRulerApproximateDecorations = accessor.deltaDecorations(_this._overviewRulerApproximateDecorations, newOverviewRulerApproximateDecorations); // Range highlight if (_this._rangeHighlightDecorationId) { accessor.removeDecoration(_this._rangeHighlightDecorationId); _this._rangeHighlightDecorationId = null; } // Find scope if (_this._findScopeDecorationId) { accessor.removeDecoration(_this._findScopeDecorationId); _this._findScopeDecorationId = null; } if (findScope) { _this._findScopeDecorationId = accessor.addDecoration(findScope, FindDecorations._FIND_SCOPE_DECORATION); } }); }; FindDecorations.prototype.matchBeforePosition = function (position) { if (this._decorations.length === 0) { return null; } for (var i = this._decorations.length - 1; i >= 0; i--) { var decorationId = this._decorations[i]; var r = this._editor.getModel().getDecorationRange(decorationId); if (!r || r.endLineNumber > position.lineNumber) { continue; } if (r.endLineNumber < position.lineNumber) { return r; } if (r.endColumn > position.column) { continue; } return r; } return this._editor.getModel().getDecorationRange(this._decorations[this._decorations.length - 1]); }; FindDecorations.prototype.matchAfterPosition = function (position) { if (this._decorations.length === 0) { return null; } for (var i = 0, len = this._decorations.length; i < len; i++) { var decorationId = this._decorations[i]; var r = this._editor.getModel().getDecorationRange(decorationId); if (!r || r.startLineNumber < position.lineNumber) { continue; } if (r.startLineNumber > position.lineNumber) { return r; } if (r.startColumn < position.column) { continue; } return r; } return this._editor.getModel().getDecorationRange(this._decorations[0]); }; FindDecorations.prototype._allDecorations = function () { var result = []; result = result.concat(this._decorations); result = result.concat(this._overviewRulerApproximateDecorations); if (this._findScopeDecorationId) { result.push(this._findScopeDecorationId); } if (this._rangeHighlightDecorationId) { result.push(this._rangeHighlightDecorationId); } return result; }; FindDecorations._CURRENT_FIND_MATCH_DECORATION = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, zIndex: 13, className: 'currentFindMatch', showIfCollapsed: true, overviewRuler: { color: themeService_1.themeColorFromId(colorRegistry_1.overviewRulerFindMatchForeground), position: model_1.OverviewRulerLane.Center }, minimap: { color: themeService_1.themeColorFromId(colorRegistry_1.minimapFindMatch), position: model_1.MinimapPosition.Inline } }); FindDecorations._FIND_MATCH_DECORATION = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'findMatch', showIfCollapsed: true, overviewRuler: { color: themeService_1.themeColorFromId(colorRegistry_1.overviewRulerFindMatchForeground), position: model_1.OverviewRulerLane.Center }, minimap: { color: themeService_1.themeColorFromId(colorRegistry_1.minimapFindMatch), position: model_1.MinimapPosition.Inline } }); FindDecorations._FIND_MATCH_NO_OVERVIEW_DECORATION = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'findMatch', showIfCollapsed: true }); FindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, overviewRuler: { color: themeService_1.themeColorFromId(colorRegistry_1.overviewRulerFindMatchForeground), position: model_1.OverviewRulerLane.Center } }); FindDecorations._RANGE_HIGHLIGHT_DECORATION = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'rangeHighlight', isWholeLine: true }); FindDecorations._FIND_SCOPE_DECORATION = textModel_1.ModelDecorationOptions.register({ className: 'findScope', isWholeLine: true }); return FindDecorations; }()); exports.FindDecorations = FindDecorations; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[168/*vs/editor/contrib/find/findModel*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,80/*vs/editor/common/commands/replaceCommand*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,144/*vs/editor/common/model/textModelSearch*/,571/*vs/editor/contrib/find/findDecorations*/,379/*vs/editor/contrib/find/replaceAllCommand*/,380/*vs/editor/contrib/find/replacePattern*/,18/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, async_1, lifecycle_1, replaceCommand_1, position_1, range_1, selection_1, textModelSearch_1, findDecorations_1, replaceAllCommand_1, replacePattern_1, contextkey_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CONTEXT_FIND_WIDGET_VISIBLE = new contextkey_1.RawContextKey('findWidgetVisible', false); // Keep ContextKey use of 'Focussed' to not break when clauses exports.CONTEXT_FIND_INPUT_FOCUSED = new contextkey_1.RawContextKey('findInputFocussed', false); exports.CONTEXT_REPLACE_INPUT_FOCUSED = new contextkey_1.RawContextKey('replaceInputFocussed', false); exports.ToggleCaseSensitiveKeybinding = { primary: 512 /* Alt */ | 33 /* KEY_C */, mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 33 /* KEY_C */ } }; exports.ToggleWholeWordKeybinding = { primary: 512 /* Alt */ | 53 /* KEY_W */, mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 53 /* KEY_W */ } }; exports.ToggleRegexKeybinding = { primary: 512 /* Alt */ | 48 /* KEY_R */, mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 48 /* KEY_R */ } }; exports.ToggleSearchScopeKeybinding = { primary: 512 /* Alt */ | 42 /* KEY_L */, mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 42 /* KEY_L */ } }; exports.FIND_IDS = { StartFindAction: 'actions.find', StartFindWithSelection: 'actions.findWithSelection', NextMatchFindAction: 'editor.action.nextMatchFindAction', PreviousMatchFindAction: 'editor.action.previousMatchFindAction', NextSelectionMatchFindAction: 'editor.action.nextSelectionMatchFindAction', PreviousSelectionMatchFindAction: 'editor.action.previousSelectionMatchFindAction', StartFindReplaceAction: 'editor.action.startFindReplaceAction', CloseFindWidgetCommand: 'closeFindWidget', ToggleCaseSensitiveCommand: 'toggleFindCaseSensitive', ToggleWholeWordCommand: 'toggleFindWholeWord', ToggleRegexCommand: 'toggleFindRegex', ToggleSearchScopeCommand: 'toggleFindInSelection', TogglePreserveCaseCommand: 'togglePreserveCase', ReplaceOneAction: 'editor.action.replaceOne', ReplaceAllAction: 'editor.action.replaceAll', SelectAllMatchesAction: 'editor.action.selectAllMatches' }; exports.MATCHES_LIMIT = 19999; var RESEARCH_DELAY = 240; var FindModelBoundToEditorModel = /** @class */ (function () { function FindModelBoundToEditorModel(editor, state) { var _this = this; this._toDispose = new lifecycle_1.DisposableStore(); this._editor = editor; this._state = state; this._isDisposed = false; this._startSearchingTimer = new async_1.TimeoutTimer(); this._decorations = new findDecorations_1.FindDecorations(editor); this._toDispose.add(this._decorations); this._updateDecorationsScheduler = new async_1.RunOnceScheduler(function () { return _this.research(false); }, 100); this._toDispose.add(this._updateDecorationsScheduler); this._toDispose.add(this._editor.onDidChangeCursorPosition(function (e) { if (e.reason === 3 /* Explicit */ || e.reason === 5 /* Undo */ || e.reason === 6 /* Redo */) { _this._decorations.setStartPosition(_this._editor.getPosition()); } })); this._ignoreModelContentChanged = false; this._toDispose.add(this._editor.onDidChangeModelContent(function (e) { if (_this._ignoreModelContentChanged) { return; } if (e.isFlush) { // a model.setValue() was called _this._decorations.reset(); } _this._decorations.setStartPosition(_this._editor.getPosition()); _this._updateDecorationsScheduler.schedule(); })); this._toDispose.add(this._state.onFindReplaceStateChange(function (e) { return _this._onStateChanged(e); })); this.research(false, this._state.searchScope); } FindModelBoundToEditorModel.prototype.dispose = function () { this._isDisposed = true; lifecycle_1.dispose(this._startSearchingTimer); this._toDispose.dispose(); }; FindModelBoundToEditorModel.prototype._onStateChanged = function (e) { var _this = this; if (this._isDisposed) { // The find model is disposed during a find state changed event return; } if (!this._editor.hasModel()) { // The find model will be disposed momentarily return; } if (e.searchString || e.isReplaceRevealed || e.isRegex || e.wholeWord || e.matchCase || e.searchScope) { var model = this._editor.getModel(); if (model.isTooLargeForSyncing()) { this._startSearchingTimer.cancel(); this._startSearchingTimer.setIfNotSet(function () { if (e.searchScope) { _this.research(e.moveCursor, _this._state.searchScope); } else { _this.research(e.moveCursor); } }, RESEARCH_DELAY); } else { if (e.searchScope) { this.research(e.moveCursor, this._state.searchScope); } else { this.research(e.moveCursor); } } } }; FindModelBoundToEditorModel._getSearchRange = function (model, findScope) { // If we have set now or before a find scope, use it for computing the search range if (findScope) { return findScope; } return model.getFullModelRange(); }; FindModelBoundToEditorModel.prototype.research = function (moveCursor, newFindScope) { var findScope = null; if (typeof newFindScope !== 'undefined') { findScope = newFindScope; } else { findScope = this._decorations.getFindScope(); } if (findScope !== null) { if (findScope.startLineNumber !== findScope.endLineNumber) { if (findScope.endColumn === 1) { findScope = new range_1.Range(findScope.startLineNumber, 1, findScope.endLineNumber - 1, this._editor.getModel().getLineMaxColumn(findScope.endLineNumber - 1)); } else { // multiline find scope => expand to line starts / ends findScope = new range_1.Range(findScope.startLineNumber, 1, findScope.endLineNumber, this._editor.getModel().getLineMaxColumn(findScope.endLineNumber)); } } } var findMatches = this._findMatches(findScope, false, exports.MATCHES_LIMIT); this._decorations.set(findMatches, findScope); this._state.changeMatchInfo(this._decorations.getCurrentMatchesPosition(this._editor.getSelection()), this._decorations.getCount(), undefined); if (moveCursor) { this._moveToNextMatch(this._decorations.getStartPosition()); } }; FindModelBoundToEditorModel.prototype._hasMatches = function () { return (this._state.matchesCount > 0); }; FindModelBoundToEditorModel.prototype._cannotFind = function () { if (!this._hasMatches()) { var findScope = this._decorations.getFindScope(); if (findScope) { // Reveal the selection so user is reminded that 'selection find' is on. this._editor.revealRangeInCenterIfOutsideViewport(findScope, 0 /* Smooth */); } return true; } return false; }; FindModelBoundToEditorModel.prototype._setCurrentFindMatch = function (match) { var matchesPosition = this._decorations.setCurrentFindMatch(match); this._state.changeMatchInfo(matchesPosition, this._decorations.getCount(), match); this._editor.setSelection(match); this._editor.revealRangeInCenterIfOutsideViewport(match, 0 /* Smooth */); }; FindModelBoundToEditorModel.prototype._prevSearchPosition = function (before) { var isUsingLineStops = this._state.isRegex && (this._state.searchString.indexOf('^') >= 0 || this._state.searchString.indexOf('$') >= 0); var lineNumber = before.lineNumber, column = before.column; var model = this._editor.getModel(); if (isUsingLineStops || column === 1) { if (lineNumber === 1) { lineNumber = model.getLineCount(); } else { lineNumber--; } column = model.getLineMaxColumn(lineNumber); } else { column--; } return new position_1.Position(lineNumber, column); }; FindModelBoundToEditorModel.prototype._moveToPrevMatch = function (before, isRecursed) { if (isRecursed === void 0) { isRecursed = false; } if (this._decorations.getCount() < exports.MATCHES_LIMIT) { var prevMatchRange = this._decorations.matchBeforePosition(before); if (prevMatchRange && prevMatchRange.isEmpty() && prevMatchRange.getStartPosition().equals(before)) { before = this._prevSearchPosition(before); prevMatchRange = this._decorations.matchBeforePosition(before); } if (prevMatchRange) { this._setCurrentFindMatch(prevMatchRange); } return; } if (this._cannotFind()) { return; } var findScope = this._decorations.getFindScope(); var searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), findScope); // ...(----)...|... if (searchRange.getEndPosition().isBefore(before)) { before = searchRange.getEndPosition(); } // ...|...(----)... if (before.isBefore(searchRange.getStartPosition())) { before = searchRange.getEndPosition(); } var lineNumber = before.lineNumber, column = before.column; var model = this._editor.getModel(); var position = new position_1.Position(lineNumber, column); var prevMatch = model.findPreviousMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(96 /* wordSeparators */) : null, false); if (prevMatch && prevMatch.range.isEmpty() && prevMatch.range.getStartPosition().equals(position)) { // Looks like we're stuck at this position, unacceptable! position = this._prevSearchPosition(position); prevMatch = model.findPreviousMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(96 /* wordSeparators */) : null, false); } if (!prevMatch) { // there is precisely one match and selection is on top of it return; } if (!isRecursed && !searchRange.containsRange(prevMatch.range)) { return this._moveToPrevMatch(prevMatch.range.getStartPosition(), true); } this._setCurrentFindMatch(prevMatch.range); }; FindModelBoundToEditorModel.prototype.moveToPrevMatch = function () { this._moveToPrevMatch(this._editor.getSelection().getStartPosition()); }; FindModelBoundToEditorModel.prototype._nextSearchPosition = function (after) { var isUsingLineStops = this._state.isRegex && (this._state.searchString.indexOf('^') >= 0 || this._state.searchString.indexOf('$') >= 0); var lineNumber = after.lineNumber, column = after.column; var model = this._editor.getModel(); if (isUsingLineStops || column === model.getLineMaxColumn(lineNumber)) { if (lineNumber === model.getLineCount()) { lineNumber = 1; } else { lineNumber++; } column = 1; } else { column++; } return new position_1.Position(lineNumber, column); }; FindModelBoundToEditorModel.prototype._moveToNextMatch = function (after) { if (this._decorations.getCount() < exports.MATCHES_LIMIT) { var nextMatchRange = this._decorations.matchAfterPosition(after); if (nextMatchRange && nextMatchRange.isEmpty() && nextMatchRange.getStartPosition().equals(after)) { // Looks like we're stuck at this position, unacceptable! after = this._nextSearchPosition(after); nextMatchRange = this._decorations.matchAfterPosition(after); } if (nextMatchRange) { this._setCurrentFindMatch(nextMatchRange); } return; } var nextMatch = this._getNextMatch(after, false, true); if (nextMatch) { this._setCurrentFindMatch(nextMatch.range); } }; FindModelBoundToEditorModel.prototype._getNextMatch = function (after, captureMatches, forceMove, isRecursed) { if (isRecursed === void 0) { isRecursed = false; } if (this._cannotFind()) { return null; } var findScope = this._decorations.getFindScope(); var searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), findScope); // ...(----)...|... if (searchRange.getEndPosition().isBefore(after)) { after = searchRange.getStartPosition(); } // ...|...(----)... if (after.isBefore(searchRange.getStartPosition())) { after = searchRange.getStartPosition(); } var lineNumber = after.lineNumber, column = after.column; var model = this._editor.getModel(); var position = new position_1.Position(lineNumber, column); var nextMatch = model.findNextMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(96 /* wordSeparators */) : null, captureMatches); if (forceMove && nextMatch && nextMatch.range.isEmpty() && nextMatch.range.getStartPosition().equals(position)) { // Looks like we're stuck at this position, unacceptable! position = this._nextSearchPosition(position); nextMatch = model.findNextMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(96 /* wordSeparators */) : null, captureMatches); } if (!nextMatch) { // there is precisely one match and selection is on top of it return null; } if (!isRecursed && !searchRange.containsRange(nextMatch.range)) { return this._getNextMatch(nextMatch.range.getEndPosition(), captureMatches, forceMove, true); } return nextMatch; }; FindModelBoundToEditorModel.prototype.moveToNextMatch = function () { this._moveToNextMatch(this._editor.getSelection().getEndPosition()); }; FindModelBoundToEditorModel.prototype._getReplacePattern = function () { if (this._state.isRegex) { return replacePattern_1.parseReplaceString(this._state.replaceString); } return replacePattern_1.ReplacePattern.fromStaticValue(this._state.replaceString); }; FindModelBoundToEditorModel.prototype.replace = function () { if (!this._hasMatches()) { return; } var replacePattern = this._getReplacePattern(); var selection = this._editor.getSelection(); var nextMatch = this._getNextMatch(selection.getStartPosition(), true, false); if (nextMatch) { if (selection.equalsRange(nextMatch.range)) { // selection sits on a find match => replace it! var replaceString = replacePattern.buildReplaceString(nextMatch.matches, this._state.preserveCase); var command = new replaceCommand_1.ReplaceCommand(selection, replaceString); this._executeEditorCommand('replace', command); this._decorations.setStartPosition(new position_1.Position(selection.startLineNumber, selection.startColumn + replaceString.length)); this.research(true); } else { this._decorations.setStartPosition(this._editor.getPosition()); this._setCurrentFindMatch(nextMatch.range); } } }; FindModelBoundToEditorModel.prototype._findMatches = function (findScope, captureMatches, limitResultCount) { var searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), findScope); return this._editor.getModel().findMatches(this._state.searchString, searchRange, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(96 /* wordSeparators */) : null, captureMatches, limitResultCount); }; FindModelBoundToEditorModel.prototype.replaceAll = function () { if (!this._hasMatches()) { return; } var findScope = this._decorations.getFindScope(); if (findScope === null && this._state.matchesCount >= exports.MATCHES_LIMIT) { // Doing a replace on the entire file that is over ${MATCHES_LIMIT} matches this._largeReplaceAll(); } else { this._regularReplaceAll(findScope); } this.research(false); }; FindModelBoundToEditorModel.prototype._largeReplaceAll = function () { var searchParams = new textModelSearch_1.SearchParams(this._state.searchString, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(96 /* wordSeparators */) : null); var searchData = searchParams.parseSearchRequest(); if (!searchData) { return; } var searchRegex = searchData.regex; if (!searchRegex.multiline) { var mod = 'mu'; if (searchRegex.ignoreCase) { mod += 'i'; } if (searchRegex.global) { mod += 'g'; } searchRegex = new RegExp(searchRegex.source, mod); } var model = this._editor.getModel(); var modelText = model.getValue(1 /* LF */); var fullModelRange = model.getFullModelRange(); var replacePattern = this._getReplacePattern(); var resultText; var preserveCase = this._state.preserveCase; if (replacePattern.hasReplacementPatterns || preserveCase) { resultText = modelText.replace(searchRegex, function () { return replacePattern.buildReplaceString(arguments, preserveCase); }); } else { resultText = modelText.replace(searchRegex, replacePattern.buildReplaceString(null, preserveCase)); } var command = new replaceCommand_1.ReplaceCommandThatPreservesSelection(fullModelRange, resultText, this._editor.getSelection()); this._executeEditorCommand('replaceAll', command); }; FindModelBoundToEditorModel.prototype._regularReplaceAll = function (findScope) { var replacePattern = this._getReplacePattern(); // Get all the ranges (even more than the highlighted ones) var matches = this._findMatches(findScope, replacePattern.hasReplacementPatterns || this._state.preserveCase, 1073741824 /* MAX_SAFE_SMALL_INTEGER */); var replaceStrings = []; for (var i = 0, len = matches.length; i < len; i++) { replaceStrings[i] = replacePattern.buildReplaceString(matches[i].matches, this._state.preserveCase); } var command = new replaceAllCommand_1.ReplaceAllCommand(this._editor.getSelection(), matches.map(function (m) { return m.range; }), replaceStrings); this._executeEditorCommand('replaceAll', command); }; FindModelBoundToEditorModel.prototype.selectAllMatches = function () { if (!this._hasMatches()) { return; } var findScope = this._decorations.getFindScope(); // Get all the ranges (even more than the highlighted ones) var matches = this._findMatches(findScope, false, 1073741824 /* MAX_SAFE_SMALL_INTEGER */); var selections = matches.map(function (m) { return new selection_1.Selection(m.range.startLineNumber, m.range.startColumn, m.range.endLineNumber, m.range.endColumn); }); // If one of the ranges is the editor selection, then maintain it as primary var editorSelection = this._editor.getSelection(); for (var i = 0, len = selections.length; i < len; i++) { var sel = selections[i]; if (sel.equalsRange(editorSelection)) { selections = [editorSelection].concat(selections.slice(0, i)).concat(selections.slice(i + 1)); break; } } this._editor.setSelections(selections); }; FindModelBoundToEditorModel.prototype._executeEditorCommand = function (source, command) { try { this._ignoreModelContentChanged = true; this._editor.pushUndoStop(); this._editor.executeCommand(source, command); this._editor.pushUndoStop(); } finally { this._ignoreModelContentChanged = false; } }; return FindModelBoundToEditorModel; }()); exports.FindModelBoundToEditorModel = FindModelBoundToEditorModel; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[572/*vs/editor/contrib/find/findOptionsWidget*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,204/*vs/base/browser/ui/findinput/findInputCheckboxes*/,47/*vs/base/browser/ui/widget*/,15/*vs/base/common/async*/,168/*vs/editor/contrib/find/findModel*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, dom, findInputCheckboxes_1, widget_1, async_1, findModel_1, colorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var FindOptionsWidget = /** @class */ (function (_super) { __extends(FindOptionsWidget, _super); function FindOptionsWidget(editor, state, keybindingService, themeService) { var _this = _super.call(this) || this; _this._hideSoon = _this._register(new async_1.RunOnceScheduler(function () { return _this._hide(); }, 2000)); _this._isVisible = false; _this._editor = editor; _this._state = state; _this._keybindingService = keybindingService; _this._domNode = document.createElement('div'); _this._domNode.className = 'findOptionsWidget'; _this._domNode.style.display = 'none'; _this._domNode.style.top = '10px'; _this._domNode.setAttribute('role', 'presentation'); _this._domNode.setAttribute('aria-hidden', 'true'); var inputActiveOptionBorderColor = themeService.getTheme().getColor(colorRegistry_1.inputActiveOptionBorder); var inputActiveOptionBackgroundColor = themeService.getTheme().getColor(colorRegistry_1.inputActiveOptionBackground); _this.caseSensitive = _this._register(new findInputCheckboxes_1.CaseSensitiveCheckbox({ appendTitle: _this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleCaseSensitiveCommand), isChecked: _this._state.matchCase, inputActiveOptionBorder: inputActiveOptionBorderColor, inputActiveOptionBackground: inputActiveOptionBackgroundColor })); _this._domNode.appendChild(_this.caseSensitive.domNode); _this._register(_this.caseSensitive.onChange(function () { _this._state.change({ matchCase: _this.caseSensitive.checked }, false); })); _this.wholeWords = _this._register(new findInputCheckboxes_1.WholeWordsCheckbox({ appendTitle: _this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleWholeWordCommand), isChecked: _this._state.wholeWord, inputActiveOptionBorder: inputActiveOptionBorderColor, inputActiveOptionBackground: inputActiveOptionBackgroundColor })); _this._domNode.appendChild(_this.wholeWords.domNode); _this._register(_this.wholeWords.onChange(function () { _this._state.change({ wholeWord: _this.wholeWords.checked }, false); })); _this.regex = _this._register(new findInputCheckboxes_1.RegexCheckbox({ appendTitle: _this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleRegexCommand), isChecked: _this._state.isRegex, inputActiveOptionBorder: inputActiveOptionBorderColor, inputActiveOptionBackground: inputActiveOptionBackgroundColor })); _this._domNode.appendChild(_this.regex.domNode); _this._register(_this.regex.onChange(function () { _this._state.change({ isRegex: _this.regex.checked }, false); })); _this._editor.addOverlayWidget(_this); _this._register(_this._state.onFindReplaceStateChange(function (e) { var somethingChanged = false; if (e.isRegex) { _this.regex.checked = _this._state.isRegex; somethingChanged = true; } if (e.wholeWord) { _this.wholeWords.checked = _this._state.wholeWord; somethingChanged = true; } if (e.matchCase) { _this.caseSensitive.checked = _this._state.matchCase; somethingChanged = true; } if (!_this._state.isRevealed && somethingChanged) { _this._revealTemporarily(); } })); _this._register(dom.addDisposableNonBubblingMouseOutListener(_this._domNode, function (e) { return _this._onMouseOut(); })); _this._register(dom.addDisposableListener(_this._domNode, 'mouseover', function (e) { return _this._onMouseOver(); })); _this._applyTheme(themeService.getTheme()); _this._register(themeService.onThemeChange(_this._applyTheme.bind(_this))); return _this; } FindOptionsWidget.prototype._keybindingLabelFor = function (actionId) { var kb = this._keybindingService.lookupKeybinding(actionId); if (!kb) { return ''; } return " (" + kb.getLabel() + ")"; }; FindOptionsWidget.prototype.dispose = function () { this._editor.removeOverlayWidget(this); _super.prototype.dispose.call(this); }; // ----- IOverlayWidget API FindOptionsWidget.prototype.getId = function () { return FindOptionsWidget.ID; }; FindOptionsWidget.prototype.getDomNode = function () { return this._domNode; }; FindOptionsWidget.prototype.getPosition = function () { return { preference: 0 /* TOP_RIGHT_CORNER */ }; }; FindOptionsWidget.prototype.highlightFindOptions = function () { this._revealTemporarily(); }; FindOptionsWidget.prototype._revealTemporarily = function () { this._show(); this._hideSoon.schedule(); }; FindOptionsWidget.prototype._onMouseOut = function () { this._hideSoon.schedule(); }; FindOptionsWidget.prototype._onMouseOver = function () { this._hideSoon.cancel(); }; FindOptionsWidget.prototype._show = function () { if (this._isVisible) { return; } this._isVisible = true; this._domNode.style.display = 'block'; }; FindOptionsWidget.prototype._hide = function () { if (!this._isVisible) { return; } this._isVisible = false; this._domNode.style.display = 'none'; }; FindOptionsWidget.prototype._applyTheme = function (theme) { var inputStyles = { inputActiveOptionBorder: theme.getColor(colorRegistry_1.inputActiveOptionBorder), inputActiveOptionBackground: theme.getColor(colorRegistry_1.inputActiveOptionBackground) }; this.caseSensitive.style(inputStyles); this.wholeWords.style(inputStyles); this.regex.style(inputStyles); }; FindOptionsWidget.ID = 'editor.contrib.findOptionsWidget'; return FindOptionsWidget; }(widget_1.Widget)); exports.FindOptionsWidget = FindOptionsWidget; themeService_1.registerThemingParticipant(function (theme, collector) { var widgetBackground = theme.getColor(colorRegistry_1.editorWidgetBackground); if (widgetBackground) { collector.addRule(".monaco-editor .findOptionsWidget { background-color: " + widgetBackground + "; }"); } var widgetForeground = theme.getColor(colorRegistry_1.editorWidgetForeground); if (widgetForeground) { collector.addRule(".monaco-editor .findOptionsWidget { color: " + widgetForeground + "; }"); } var widgetShadowColor = theme.getColor(colorRegistry_1.widgetShadow); if (widgetShadowColor) { collector.addRule(".monaco-editor .findOptionsWidget { box-shadow: 0 2px 8px " + widgetShadowColor + "; }"); } var hcBorder = theme.getColor(colorRegistry_1.contrastBorder); if (hcBorder) { collector.addRule(".monaco-editor .findOptionsWidget { border: 2px solid " + hcBorder + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[573/*vs/editor/contrib/find/findWidget*/], __M([0/*require*/,1/*exports*/,439/*vs/nls!vs/editor/contrib/find/findWidget*/,6/*vs/base/browser/dom*/,50/*vs/base/browser/ui/aria/aria*/,138/*vs/base/browser/ui/checkbox/checkbox*/,104/*vs/base/browser/ui/sash/sash*/,47/*vs/base/browser/ui/widget*/,15/*vs/base/common/async*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,5/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/,168/*vs/editor/contrib/find/findModel*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,520/*vs/platform/browser/contextScopedHistoryWidget*/,310/*vs/css!vs/editor/contrib/find/findWidget*/]), function (require, exports, nls, dom, aria_1, checkbox_1, sash_1, widget_1, async_1, errors_1, lifecycle_1, platform, strings, range_1, findModel_1, colorRegistry_1, themeService_1, contextScopedHistoryWidget_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var NLS_FIND_INPUT_LABEL = nls.localize(0, null); var NLS_FIND_INPUT_PLACEHOLDER = nls.localize(1, null); var NLS_PREVIOUS_MATCH_BTN_LABEL = nls.localize(2, null); var NLS_NEXT_MATCH_BTN_LABEL = nls.localize(3, null); var NLS_TOGGLE_SELECTION_FIND_TITLE = nls.localize(4, null); var NLS_CLOSE_BTN_LABEL = nls.localize(5, null); var NLS_REPLACE_INPUT_LABEL = nls.localize(6, null); var NLS_REPLACE_INPUT_PLACEHOLDER = nls.localize(7, null); var NLS_REPLACE_BTN_LABEL = nls.localize(8, null); var NLS_REPLACE_ALL_BTN_LABEL = nls.localize(9, null); var NLS_TOGGLE_REPLACE_MODE_BTN_LABEL = nls.localize(10, null); var NLS_MATCHES_COUNT_LIMIT_TITLE = nls.localize(11, null, findModel_1.MATCHES_LIMIT); var NLS_MATCHES_LOCATION = nls.localize(12, null); var NLS_NO_RESULTS = nls.localize(13, null); var FIND_WIDGET_INITIAL_WIDTH = 419; var PART_WIDTH = 275; var FIND_INPUT_AREA_WIDTH = PART_WIDTH - 54; var MAX_MATCHES_COUNT_WIDTH = 69; // let FIND_ALL_CONTROLS_WIDTH = 17/** Find Input margin-left */ + (MAX_MATCHES_COUNT_WIDTH + 3 + 1) /** Match Results */ + 23 /** Button */ * 4 + 2/** sash */; var FIND_INPUT_AREA_HEIGHT = 33; // The height of Find Widget when Replace Input is not visible. var ctrlEnterReplaceAllWarningPromptedKey = 'ctrlEnterReplaceAll.windows.donotask'; var ctrlKeyMod = (platform.isMacintosh ? 256 /* WinCtrl */ : 2048 /* CtrlCmd */); var FindWidgetViewZone = /** @class */ (function () { function FindWidgetViewZone(afterLineNumber) { this.afterLineNumber = afterLineNumber; this.heightInPx = FIND_INPUT_AREA_HEIGHT; this.suppressMouseDown = false; this.domNode = document.createElement('div'); this.domNode.className = 'dock-find-viewzone'; } return FindWidgetViewZone; }()); exports.FindWidgetViewZone = FindWidgetViewZone; function stopPropagationForMultiLineUpwards(event, value, textarea) { var isMultiline = !!value.match(/\n/); if (textarea && isMultiline && textarea.selectionStart > 0) { event.stopPropagation(); return; } } function stopPropagationForMultiLineDownwards(event, value, textarea) { var isMultiline = !!value.match(/\n/); if (textarea && isMultiline && textarea.selectionEnd < textarea.value.length) { event.stopPropagation(); return; } } var FindWidget = /** @class */ (function (_super) { __extends(FindWidget, _super); function FindWidget(codeEditor, controller, state, contextViewProvider, keybindingService, contextKeyService, themeService, storageService, notificationService) { var _this = _super.call(this) || this; _this._cachedHeight = null; _this._codeEditor = codeEditor; _this._controller = controller; _this._state = state; _this._contextViewProvider = contextViewProvider; _this._keybindingService = keybindingService; _this._contextKeyService = contextKeyService; _this._storageService = storageService; _this._notificationService = notificationService; _this._ctrlEnterReplaceAllWarningPrompted = !!storageService.getBoolean(ctrlEnterReplaceAllWarningPromptedKey, 0 /* GLOBAL */); _this._isVisible = false; _this._isReplaceVisible = false; _this._ignoreChangeEvent = false; _this._updateHistoryDelayer = new async_1.Delayer(500); _this._register(lifecycle_1.toDisposable(function () { return _this._updateHistoryDelayer.cancel(); })); _this._register(_this._state.onFindReplaceStateChange(function (e) { return _this._onStateChanged(e); })); _this._buildDomNode(); _this._updateButtons(); _this._tryUpdateWidgetWidth(); _this._findInput.inputBox.layout(); _this._register(_this._codeEditor.onDidChangeConfiguration(function (e) { if (e.hasChanged(68 /* readOnly */)) { if (_this._codeEditor.getOption(68 /* readOnly */)) { // Hide replace part if editor becomes read only _this._state.change({ isReplaceRevealed: false }, false); } _this._updateButtons(); } if (e.hasChanged(107 /* layoutInfo */)) { _this._tryUpdateWidgetWidth(); } if (e.hasChanged(2 /* accessibilitySupport */)) { _this.updateAccessibilitySupport(); } if (e.hasChanged(28 /* find */)) { var addExtraSpaceOnTop = _this._codeEditor.getOption(28 /* find */).addExtraSpaceOnTop; if (addExtraSpaceOnTop && !_this._viewZone) { _this._viewZone = new FindWidgetViewZone(0); _this._showViewZone(); } if (!addExtraSpaceOnTop && _this._viewZone) { _this._removeViewZone(); } } })); _this.updateAccessibilitySupport(); _this._register(_this._codeEditor.onDidChangeCursorSelection(function () { if (_this._isVisible) { _this._updateToggleSelectionFindButton(); } })); _this._register(_this._codeEditor.onDidFocusEditorWidget(function () { if (_this._isVisible) { var globalBufferTerm = _this._controller.getGlobalBufferTerm(); if (globalBufferTerm && globalBufferTerm !== _this._state.searchString) { _this._state.change({ searchString: globalBufferTerm }, true); _this._findInput.select(); } } })); _this._findInputFocused = findModel_1.CONTEXT_FIND_INPUT_FOCUSED.bindTo(contextKeyService); _this._findFocusTracker = _this._register(dom.trackFocus(_this._findInput.inputBox.inputElement)); _this._register(_this._findFocusTracker.onDidFocus(function () { _this._findInputFocused.set(true); _this._updateSearchScope(); })); _this._register(_this._findFocusTracker.onDidBlur(function () { _this._findInputFocused.set(false); })); _this._replaceInputFocused = findModel_1.CONTEXT_REPLACE_INPUT_FOCUSED.bindTo(contextKeyService); _this._replaceFocusTracker = _this._register(dom.trackFocus(_this._replaceInput.inputBox.inputElement)); _this._register(_this._replaceFocusTracker.onDidFocus(function () { _this._replaceInputFocused.set(true); _this._updateSearchScope(); })); _this._register(_this._replaceFocusTracker.onDidBlur(function () { _this._replaceInputFocused.set(false); })); _this._codeEditor.addOverlayWidget(_this); if (_this._codeEditor.getOption(28 /* find */).addExtraSpaceOnTop) { _this._viewZone = new FindWidgetViewZone(0); // Put it before the first line then users can scroll beyond the first line. } _this._applyTheme(themeService.getTheme()); _this._register(themeService.onThemeChange(_this._applyTheme.bind(_this))); _this._register(_this._codeEditor.onDidChangeModel(function () { if (!_this._isVisible) { return; } _this._viewZoneId = undefined; })); _this._register(_this._codeEditor.onDidScrollChange(function (e) { if (e.scrollTopChanged) { _this._layoutViewZone(); return; } // for other scroll changes, layout the viewzone in next tick to avoid ruining current rendering. setTimeout(function () { _this._layoutViewZone(); }, 0); })); return _this; } // ----- IOverlayWidget API FindWidget.prototype.getId = function () { return FindWidget.ID; }; FindWidget.prototype.getDomNode = function () { return this._domNode; }; FindWidget.prototype.getPosition = function () { if (this._isVisible) { return { preference: 0 /* TOP_RIGHT_CORNER */ }; } return null; }; // ----- React to state changes FindWidget.prototype._onStateChanged = function (e) { if (e.searchString) { try { this._ignoreChangeEvent = true; this._findInput.setValue(this._state.searchString); } finally { this._ignoreChangeEvent = false; } this._updateButtons(); } if (e.replaceString) { this._replaceInput.inputBox.value = this._state.replaceString; } if (e.isRevealed) { if (this._state.isRevealed) { this._reveal(); } else { this._hide(true); } } if (e.isReplaceRevealed) { if (this._state.isReplaceRevealed) { if (!this._codeEditor.getOption(68 /* readOnly */) && !this._isReplaceVisible) { this._isReplaceVisible = true; this._replaceInput.width = dom.getTotalWidth(this._findInput.domNode); this._updateButtons(); this._replaceInput.inputBox.layout(); } } else { if (this._isReplaceVisible) { this._isReplaceVisible = false; this._updateButtons(); } } } if ((e.isRevealed || e.isReplaceRevealed) && (this._state.isRevealed || this._state.isReplaceRevealed)) { if (this._tryUpdateHeight()) { this._showViewZone(); } } if (e.isRegex) { this._findInput.setRegex(this._state.isRegex); } if (e.wholeWord) { this._findInput.setWholeWords(this._state.wholeWord); } if (e.matchCase) { this._findInput.setCaseSensitive(this._state.matchCase); } if (e.searchScope) { if (this._state.searchScope) { this._toggleSelectionFind.checked = true; } else { this._toggleSelectionFind.checked = false; } this._updateToggleSelectionFindButton(); } if (e.searchString || e.matchesCount || e.matchesPosition) { var showRedOutline = (this._state.searchString.length > 0 && this._state.matchesCount === 0); dom.toggleClass(this._domNode, 'no-results', showRedOutline); this._updateMatchesCount(); this._updateButtons(); } if (e.searchString || e.currentMatch) { this._layoutViewZone(); } if (e.updateHistory) { this._delayedUpdateHistory(); } }; FindWidget.prototype._delayedUpdateHistory = function () { this._updateHistoryDelayer.trigger(this._updateHistory.bind(this)); }; FindWidget.prototype._updateHistory = function () { if (this._state.searchString) { this._findInput.inputBox.addToHistory(); } if (this._state.replaceString) { this._replaceInput.inputBox.addToHistory(); } }; FindWidget.prototype._updateMatchesCount = function () { this._matchesCount.style.minWidth = MAX_MATCHES_COUNT_WIDTH + 'px'; if (this._state.matchesCount >= findModel_1.MATCHES_LIMIT) { this._matchesCount.title = NLS_MATCHES_COUNT_LIMIT_TITLE; } else { this._matchesCount.title = ''; } // remove previous content if (this._matchesCount.firstChild) { this._matchesCount.removeChild(this._matchesCount.firstChild); } var label; if (this._state.matchesCount > 0) { var matchesCount = String(this._state.matchesCount); if (this._state.matchesCount >= findModel_1.MATCHES_LIMIT) { matchesCount += '+'; } var matchesPosition = String(this._state.matchesPosition); if (matchesPosition === '0') { matchesPosition = '?'; } label = strings.format(NLS_MATCHES_LOCATION, matchesPosition, matchesCount); } else { label = NLS_NO_RESULTS; } this._matchesCount.appendChild(document.createTextNode(label)); aria_1.alert(this._getAriaLabel(label, this._state.currentMatch, this._state.searchString), true); MAX_MATCHES_COUNT_WIDTH = Math.max(MAX_MATCHES_COUNT_WIDTH, this._matchesCount.clientWidth); }; // ----- actions FindWidget.prototype._getAriaLabel = function (label, currentMatch, searchString) { if (label === NLS_NO_RESULTS) { return searchString === '' ? nls.localize(14, null, label) : nls.localize(15, null, label, searchString); } return currentMatch ? nls.localize(16, null, label, searchString, currentMatch.startLineNumber + ':' + currentMatch.startColumn) : nls.localize(17, null, label, searchString); }; /** * If 'selection find' is ON we should not disable the button (its function is to cancel 'selection find'). * If 'selection find' is OFF we enable the button only if there is a selection. */ FindWidget.prototype._updateToggleSelectionFindButton = function () { var selection = this._codeEditor.getSelection(); var isSelection = selection ? (selection.startLineNumber !== selection.endLineNumber || selection.startColumn !== selection.endColumn) : false; var isChecked = this._toggleSelectionFind.checked; if (this._isVisible && (isChecked || isSelection)) { this._toggleSelectionFind.enable(); } else { this._toggleSelectionFind.disable(); } }; FindWidget.prototype._updateButtons = function () { this._findInput.setEnabled(this._isVisible); this._replaceInput.setEnabled(this._isVisible && this._isReplaceVisible); this._updateToggleSelectionFindButton(); this._closeBtn.setEnabled(this._isVisible); var findInputIsNonEmpty = (this._state.searchString.length > 0); var matchesCount = this._state.matchesCount ? true : false; this._prevBtn.setEnabled(this._isVisible && findInputIsNonEmpty && matchesCount); this._nextBtn.setEnabled(this._isVisible && findInputIsNonEmpty && matchesCount); this._replaceBtn.setEnabled(this._isVisible && this._isReplaceVisible && findInputIsNonEmpty); this._replaceAllBtn.setEnabled(this._isVisible && this._isReplaceVisible && findInputIsNonEmpty); dom.toggleClass(this._domNode, 'replaceToggled', this._isReplaceVisible); this._toggleReplaceBtn.toggleClass('codicon-chevron-right', !this._isReplaceVisible); this._toggleReplaceBtn.toggleClass('codicon-chevron-down', this._isReplaceVisible); this._toggleReplaceBtn.setExpanded(this._isReplaceVisible); var canReplace = !this._codeEditor.getOption(68 /* readOnly */); this._toggleReplaceBtn.setEnabled(this._isVisible && canReplace); }; FindWidget.prototype._reveal = function () { var _this = this; if (!this._isVisible) { this._isVisible = true; var selection = this._codeEditor.getSelection(); switch (this._codeEditor.getOption(28 /* find */).autoFindInSelection) { case 'always': this._toggleSelectionFind.checked = true; break; case 'never': this._toggleSelectionFind.checked = false; break; case 'multiline': var isSelectionMultipleLine = !!selection && selection.startLineNumber !== selection.endLineNumber; this._toggleSelectionFind.checked = isSelectionMultipleLine; break; default: break; } this._tryUpdateWidgetWidth(); this._updateButtons(); setTimeout(function () { dom.addClass(_this._domNode, 'visible'); _this._domNode.setAttribute('aria-hidden', 'false'); }, 0); // validate query again as it's being dismissed when we hide the find widget. setTimeout(function () { _this._findInput.validate(); }, 200); this._codeEditor.layoutOverlayWidget(this); var adjustEditorScrollTop = true; if (this._codeEditor.getOption(28 /* find */).seedSearchStringFromSelection && selection) { var domNode = this._codeEditor.getDomNode(); if (domNode) { var editorCoords = dom.getDomNodePagePosition(domNode); var startCoords = this._codeEditor.getScrolledVisiblePosition(selection.getStartPosition()); var startLeft = editorCoords.left + (startCoords ? startCoords.left : 0); var startTop = startCoords ? startCoords.top : 0; if (this._viewZone && startTop < this._viewZone.heightInPx) { if (selection.endLineNumber > selection.startLineNumber) { adjustEditorScrollTop = false; } var leftOfFindWidget = dom.getTopLeftOffset(this._domNode).left; if (startLeft > leftOfFindWidget) { adjustEditorScrollTop = false; } var endCoords = this._codeEditor.getScrolledVisiblePosition(selection.getEndPosition()); var endLeft = editorCoords.left + (endCoords ? endCoords.left : 0); if (endLeft > leftOfFindWidget) { adjustEditorScrollTop = false; } } } } this._showViewZone(adjustEditorScrollTop); } }; FindWidget.prototype._hide = function (focusTheEditor) { if (this._isVisible) { this._isVisible = false; this._updateButtons(); dom.removeClass(this._domNode, 'visible'); this._domNode.setAttribute('aria-hidden', 'true'); this._findInput.clearMessage(); if (focusTheEditor) { this._codeEditor.focus(); } this._codeEditor.layoutOverlayWidget(this); this._removeViewZone(); } }; FindWidget.prototype._layoutViewZone = function () { var _this = this; var addExtraSpaceOnTop = this._codeEditor.getOption(28 /* find */).addExtraSpaceOnTop; if (!addExtraSpaceOnTop) { this._removeViewZone(); return; } if (!this._isVisible) { return; } var viewZone = this._viewZone; if (this._viewZoneId !== undefined || !viewZone) { return; } this._codeEditor.changeViewZones(function (accessor) { viewZone.heightInPx = _this._getHeight(); _this._viewZoneId = accessor.addZone(viewZone); // scroll top adjust to make sure the editor doesn't scroll when adding viewzone at the beginning. _this._codeEditor.setScrollTop(_this._codeEditor.getScrollTop() + viewZone.heightInPx); }); }; FindWidget.prototype._showViewZone = function (adjustScroll) { var _this = this; if (adjustScroll === void 0) { adjustScroll = true; } if (!this._isVisible) { return; } var addExtraSpaceOnTop = this._codeEditor.getOption(28 /* find */).addExtraSpaceOnTop; if (!addExtraSpaceOnTop) { return; } if (this._viewZone === undefined) { this._viewZone = new FindWidgetViewZone(0); } var viewZone = this._viewZone; this._codeEditor.changeViewZones(function (accessor) { if (_this._viewZoneId !== undefined) { // the view zone already exists, we need to update the height var newHeight = _this._getHeight(); if (newHeight === viewZone.heightInPx) { return; } var scrollAdjustment = newHeight - viewZone.heightInPx; viewZone.heightInPx = newHeight; accessor.layoutZone(_this._viewZoneId); if (adjustScroll) { _this._codeEditor.setScrollTop(_this._codeEditor.getScrollTop() + scrollAdjustment); } return; } else { var scrollAdjustment = _this._getHeight(); viewZone.heightInPx = scrollAdjustment; _this._viewZoneId = accessor.addZone(viewZone); if (adjustScroll) { _this._codeEditor.setScrollTop(_this._codeEditor.getScrollTop() + scrollAdjustment); } } }); }; FindWidget.prototype._removeViewZone = function () { var _this = this; this._codeEditor.changeViewZones(function (accessor) { if (_this._viewZoneId !== undefined) { accessor.removeZone(_this._viewZoneId); _this._viewZoneId = undefined; if (_this._viewZone) { _this._codeEditor.setScrollTop(_this._codeEditor.getScrollTop() - _this._viewZone.heightInPx); _this._viewZone = undefined; } } }); }; FindWidget.prototype._applyTheme = function (theme) { var inputStyles = { inputActiveOptionBorder: theme.getColor(colorRegistry_1.inputActiveOptionBorder), inputActiveOptionBackground: theme.getColor(colorRegistry_1.inputActiveOptionBackground), inputBackground: theme.getColor(colorRegistry_1.inputBackground), inputForeground: theme.getColor(colorRegistry_1.inputForeground), inputBorder: theme.getColor(colorRegistry_1.inputBorder), inputValidationInfoBackground: theme.getColor(colorRegistry_1.inputValidationInfoBackground), inputValidationInfoForeground: theme.getColor(colorRegistry_1.inputValidationInfoForeground), inputValidationInfoBorder: theme.getColor(colorRegistry_1.inputValidationInfoBorder), inputValidationWarningBackground: theme.getColor(colorRegistry_1.inputValidationWarningBackground), inputValidationWarningForeground: theme.getColor(colorRegistry_1.inputValidationWarningForeground), inputValidationWarningBorder: theme.getColor(colorRegistry_1.inputValidationWarningBorder), inputValidationErrorBackground: theme.getColor(colorRegistry_1.inputValidationErrorBackground), inputValidationErrorForeground: theme.getColor(colorRegistry_1.inputValidationErrorForeground), inputValidationErrorBorder: theme.getColor(colorRegistry_1.inputValidationErrorBorder), }; this._findInput.style(inputStyles); this._replaceInput.style(inputStyles); this._toggleSelectionFind.style(inputStyles); }; FindWidget.prototype._tryUpdateWidgetWidth = function () { if (!this._isVisible) { return; } if (!dom.isInDOM(this._domNode)) { // the widget is not in the DOM return; } var layoutInfo = this._codeEditor.getLayoutInfo(); var editorContentWidth = layoutInfo.contentWidth; if (editorContentWidth <= 0) { // for example, diff view original editor dom.addClass(this._domNode, 'hiddenEditor'); return; } else if (dom.hasClass(this._domNode, 'hiddenEditor')) { dom.removeClass(this._domNode, 'hiddenEditor'); } var editorWidth = layoutInfo.width; var minimapWidth = layoutInfo.minimapWidth; var collapsedFindWidget = false; var reducedFindWidget = false; var narrowFindWidget = false; if (this._resized) { var widgetWidth = dom.getTotalWidth(this._domNode); if (widgetWidth > FIND_WIDGET_INITIAL_WIDTH) { // as the widget is resized by users, we may need to change the max width of the widget as the editor width changes. this._domNode.style.maxWidth = editorWidth - 28 - minimapWidth - 15 + "px"; this._replaceInput.width = dom.getTotalWidth(this._findInput.domNode); return; } } if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth >= editorWidth) { reducedFindWidget = true; } if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth - MAX_MATCHES_COUNT_WIDTH >= editorWidth) { narrowFindWidget = true; } if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth - MAX_MATCHES_COUNT_WIDTH >= editorWidth + 50) { collapsedFindWidget = true; } dom.toggleClass(this._domNode, 'collapsed-find-widget', collapsedFindWidget); dom.toggleClass(this._domNode, 'narrow-find-widget', narrowFindWidget); dom.toggleClass(this._domNode, 'reduced-find-widget', reducedFindWidget); if (!narrowFindWidget && !collapsedFindWidget) { // the minimal left offset of findwidget is 15px. this._domNode.style.maxWidth = editorWidth - 28 - minimapWidth - 15 + "px"; } if (this._resized) { this._findInput.inputBox.layout(); var findInputWidth = this._findInput.inputBox.element.clientWidth; if (findInputWidth > 0) { this._replaceInput.width = findInputWidth; } } else if (this._isReplaceVisible) { this._replaceInput.width = dom.getTotalWidth(this._findInput.domNode); } }; FindWidget.prototype._getHeight = function () { var totalheight = 0; // find input margin top totalheight += 4; // find input height totalheight += this._findInput.inputBox.height + 2 /** input box border */; if (this._isReplaceVisible) { // replace input margin totalheight += 4; totalheight += this._replaceInput.inputBox.height + 2 /** input box border */; } // margin bottom totalheight += 4; return totalheight; }; FindWidget.prototype._tryUpdateHeight = function () { var totalHeight = this._getHeight(); if (this._cachedHeight !== null && this._cachedHeight === totalHeight) { return false; } this._cachedHeight = totalHeight; this._domNode.style.height = totalHeight + "px"; return true; }; // ----- Public FindWidget.prototype.focusFindInput = function () { this._findInput.select(); // Edge browser requires focus() in addition to select() this._findInput.focus(); }; FindWidget.prototype.focusReplaceInput = function () { this._replaceInput.select(); // Edge browser requires focus() in addition to select() this._replaceInput.focus(); }; FindWidget.prototype.highlightFindOptions = function () { this._findInput.highlightFindOptions(); }; FindWidget.prototype._updateSearchScope = function () { if (!this._codeEditor.hasModel()) { return; } if (this._toggleSelectionFind.checked) { var selection = this._codeEditor.getSelection(); if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) { selection = selection.setEndPosition(selection.endLineNumber - 1, this._codeEditor.getModel().getLineMaxColumn(selection.endLineNumber - 1)); } var currentMatch = this._state.currentMatch; if (selection.startLineNumber !== selection.endLineNumber) { if (!range_1.Range.equalsRange(selection, currentMatch)) { // Reseed find scope this._state.change({ searchScope: selection }, true); } } } }; FindWidget.prototype._onFindInputMouseDown = function (e) { // on linux, middle key does pasting. if (e.middleButton) { e.stopPropagation(); } }; FindWidget.prototype._onFindInputKeyDown = function (e) { if (e.equals(ctrlKeyMod | 3 /* Enter */)) { this._findInput.inputBox.insertAtCursor('\n'); e.preventDefault(); return; } if (e.equals(2 /* Tab */)) { if (this._isReplaceVisible) { this._replaceInput.focus(); } else { this._findInput.focusOnCaseSensitive(); } e.preventDefault(); return; } if (e.equals(2048 /* CtrlCmd */ | 18 /* DownArrow */)) { this._codeEditor.focus(); e.preventDefault(); return; } if (e.equals(16 /* UpArrow */)) { return stopPropagationForMultiLineUpwards(e, this._findInput.getValue(), this._findInput.domNode.querySelector('textarea')); } if (e.equals(18 /* DownArrow */)) { return stopPropagationForMultiLineDownwards(e, this._findInput.getValue(), this._findInput.domNode.querySelector('textarea')); } }; FindWidget.prototype._onReplaceInputKeyDown = function (e) { if (e.equals(ctrlKeyMod | 3 /* Enter */)) { if (platform.isWindows && platform.isNative && !this._ctrlEnterReplaceAllWarningPrompted) { // this is the first time when users press Ctrl + Enter to replace all this._notificationService.info(nls.localize(18, null)); this._ctrlEnterReplaceAllWarningPrompted = true; this._storageService.store(ctrlEnterReplaceAllWarningPromptedKey, true, 0 /* GLOBAL */); } this._replaceInput.inputBox.insertAtCursor('\n'); e.preventDefault(); return; } if (e.equals(2 /* Tab */)) { this._findInput.focusOnCaseSensitive(); e.preventDefault(); return; } if (e.equals(1024 /* Shift */ | 2 /* Tab */)) { this._findInput.focus(); e.preventDefault(); return; } if (e.equals(2048 /* CtrlCmd */ | 18 /* DownArrow */)) { this._codeEditor.focus(); e.preventDefault(); return; } if (e.equals(16 /* UpArrow */)) { return stopPropagationForMultiLineUpwards(e, this._replaceInput.inputBox.value, this._replaceInput.inputBox.element.querySelector('textarea')); } if (e.equals(18 /* DownArrow */)) { return stopPropagationForMultiLineDownwards(e, this._replaceInput.inputBox.value, this._replaceInput.inputBox.element.querySelector('textarea')); } }; // ----- sash FindWidget.prototype.getHorizontalSashTop = function (_sash) { return 0; }; FindWidget.prototype.getHorizontalSashLeft = function (_sash) { return 0; }; FindWidget.prototype.getHorizontalSashWidth = function (_sash) { return 500; }; // ----- initialization FindWidget.prototype._keybindingLabelFor = function (actionId) { var kb = this._keybindingService.lookupKeybinding(actionId); if (!kb) { return ''; } return " (" + kb.getLabel() + ")"; }; FindWidget.prototype._buildDomNode = function () { var _this = this; var flexibleHeight = true; var flexibleWidth = true; // Find input this._findInput = this._register(new contextScopedHistoryWidget_1.ContextScopedFindInput(null, this._contextViewProvider, { width: FIND_INPUT_AREA_WIDTH, label: NLS_FIND_INPUT_LABEL, placeholder: NLS_FIND_INPUT_PLACEHOLDER, appendCaseSensitiveLabel: this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleCaseSensitiveCommand), appendWholeWordsLabel: this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleWholeWordCommand), appendRegexLabel: this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleRegexCommand), validation: function (value) { if (value.length === 0 || !_this._findInput.getRegex()) { return null; } try { new RegExp(value); return null; } catch (e) { return { content: e.message }; } }, flexibleHeight: flexibleHeight, flexibleWidth: flexibleWidth, flexibleMaxHeight: 118 }, this._contextKeyService, true)); this._findInput.setRegex(!!this._state.isRegex); this._findInput.setCaseSensitive(!!this._state.matchCase); this._findInput.setWholeWords(!!this._state.wholeWord); this._register(this._findInput.onKeyDown(function (e) { return _this._onFindInputKeyDown(e); })); this._register(this._findInput.inputBox.onDidChange(function () { if (_this._ignoreChangeEvent) { return; } _this._state.change({ searchString: _this._findInput.getValue() }, true); })); this._register(this._findInput.onDidOptionChange(function () { _this._state.change({ isRegex: _this._findInput.getRegex(), wholeWord: _this._findInput.getWholeWords(), matchCase: _this._findInput.getCaseSensitive() }, true); })); this._register(this._findInput.onCaseSensitiveKeyDown(function (e) { if (e.equals(1024 /* Shift */ | 2 /* Tab */)) { if (_this._isReplaceVisible) { _this._replaceInput.focus(); e.preventDefault(); } } })); this._register(this._findInput.onRegexKeyDown(function (e) { if (e.equals(2 /* Tab */)) { if (_this._isReplaceVisible) { _this._replaceInput.focusOnPreserve(); e.preventDefault(); } } })); this._register(this._findInput.inputBox.onDidHeightChange(function (e) { if (_this._tryUpdateHeight()) { _this._showViewZone(); } })); if (platform.isLinux) { this._register(this._findInput.onMouseDown(function (e) { return _this._onFindInputMouseDown(e); })); } this._matchesCount = document.createElement('div'); this._matchesCount.className = 'matchesCount'; this._updateMatchesCount(); // Previous button this._prevBtn = this._register(new SimpleButton({ label: NLS_PREVIOUS_MATCH_BTN_LABEL + this._keybindingLabelFor(findModel_1.FIND_IDS.PreviousMatchFindAction), className: 'codicon codicon-arrow-up', onTrigger: function () { _this._codeEditor.getAction(findModel_1.FIND_IDS.PreviousMatchFindAction).run().then(undefined, errors_1.onUnexpectedError); } })); // Next button this._nextBtn = this._register(new SimpleButton({ label: NLS_NEXT_MATCH_BTN_LABEL + this._keybindingLabelFor(findModel_1.FIND_IDS.NextMatchFindAction), className: 'codicon codicon-arrow-down', onTrigger: function () { _this._codeEditor.getAction(findModel_1.FIND_IDS.NextMatchFindAction).run().then(undefined, errors_1.onUnexpectedError); } })); var findPart = document.createElement('div'); findPart.className = 'find-part'; findPart.appendChild(this._findInput.domNode); var actionsContainer = document.createElement('div'); actionsContainer.className = 'find-actions'; findPart.appendChild(actionsContainer); actionsContainer.appendChild(this._matchesCount); actionsContainer.appendChild(this._prevBtn.domNode); actionsContainer.appendChild(this._nextBtn.domNode); // Toggle selection button this._toggleSelectionFind = this._register(new checkbox_1.Checkbox({ actionClassName: 'codicon codicon-selection', title: NLS_TOGGLE_SELECTION_FIND_TITLE + this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleSearchScopeCommand), isChecked: false })); this._register(this._toggleSelectionFind.onChange(function () { if (_this._toggleSelectionFind.checked) { if (_this._codeEditor.hasModel()) { var selection = _this._codeEditor.getSelection(); if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) { selection = selection.setEndPosition(selection.endLineNumber - 1, _this._codeEditor.getModel().getLineMaxColumn(selection.endLineNumber - 1)); } if (!selection.isEmpty()) { _this._state.change({ searchScope: selection }, true); } } } else { _this._state.change({ searchScope: null }, true); } })); actionsContainer.appendChild(this._toggleSelectionFind.domNode); // Close button this._closeBtn = this._register(new SimpleButton({ label: NLS_CLOSE_BTN_LABEL + this._keybindingLabelFor(findModel_1.FIND_IDS.CloseFindWidgetCommand), className: 'codicon codicon-close', onTrigger: function () { _this._state.change({ isRevealed: false, searchScope: null }, false); }, onKeyDown: function (e) { if (e.equals(2 /* Tab */)) { if (_this._isReplaceVisible) { if (_this._replaceBtn.isEnabled()) { _this._replaceBtn.focus(); } else { _this._codeEditor.focus(); } e.preventDefault(); } } } })); actionsContainer.appendChild(this._closeBtn.domNode); // Replace input this._replaceInput = this._register(new contextScopedHistoryWidget_1.ContextScopedReplaceInput(null, undefined, { label: NLS_REPLACE_INPUT_LABEL, placeholder: NLS_REPLACE_INPUT_PLACEHOLDER, history: [], flexibleHeight: flexibleHeight, flexibleWidth: flexibleWidth, flexibleMaxHeight: 118 }, this._contextKeyService, true)); this._replaceInput.setPreserveCase(!!this._state.preserveCase); this._register(this._replaceInput.onKeyDown(function (e) { return _this._onReplaceInputKeyDown(e); })); this._register(this._replaceInput.inputBox.onDidChange(function () { _this._state.change({ replaceString: _this._replaceInput.inputBox.value }, false); })); this._register(this._replaceInput.inputBox.onDidHeightChange(function (e) { if (_this._isReplaceVisible && _this._tryUpdateHeight()) { _this._showViewZone(); } })); this._register(this._replaceInput.onDidOptionChange(function () { _this._state.change({ preserveCase: _this._replaceInput.getPreserveCase() }, true); })); this._register(this._replaceInput.onPreserveCaseKeyDown(function (e) { if (e.equals(2 /* Tab */)) { if (_this._prevBtn.isEnabled()) { _this._prevBtn.focus(); } else if (_this._nextBtn.isEnabled()) { _this._nextBtn.focus(); } else if (_this._toggleSelectionFind.enabled) { _this._toggleSelectionFind.focus(); } else if (_this._closeBtn.isEnabled()) { _this._closeBtn.focus(); } e.preventDefault(); } })); // Replace one button this._replaceBtn = this._register(new SimpleButton({ label: NLS_REPLACE_BTN_LABEL + this._keybindingLabelFor(findModel_1.FIND_IDS.ReplaceOneAction), className: 'codicon codicon-replace', onTrigger: function () { _this._controller.replace(); }, onKeyDown: function (e) { if (e.equals(1024 /* Shift */ | 2 /* Tab */)) { _this._closeBtn.focus(); e.preventDefault(); } } })); // Replace all button this._replaceAllBtn = this._register(new SimpleButton({ label: NLS_REPLACE_ALL_BTN_LABEL + this._keybindingLabelFor(findModel_1.FIND_IDS.ReplaceAllAction), className: 'codicon codicon-replace-all', onTrigger: function () { _this._controller.replaceAll(); } })); var replacePart = document.createElement('div'); replacePart.className = 'replace-part'; replacePart.appendChild(this._replaceInput.domNode); var replaceActionsContainer = document.createElement('div'); replaceActionsContainer.className = 'replace-actions'; replacePart.appendChild(replaceActionsContainer); replaceActionsContainer.appendChild(this._replaceBtn.domNode); replaceActionsContainer.appendChild(this._replaceAllBtn.domNode); // Toggle replace button this._toggleReplaceBtn = this._register(new SimpleButton({ label: NLS_TOGGLE_REPLACE_MODE_BTN_LABEL, className: 'codicon toggle left', onTrigger: function () { _this._state.change({ isReplaceRevealed: !_this._isReplaceVisible }, false); if (_this._isReplaceVisible) { _this._replaceInput.width = dom.getTotalWidth(_this._findInput.domNode); _this._replaceInput.inputBox.layout(); } _this._showViewZone(); } })); this._toggleReplaceBtn.toggleClass('codicon-chevron-down', this._isReplaceVisible); this._toggleReplaceBtn.toggleClass('codicon-chevron-right', !this._isReplaceVisible); this._toggleReplaceBtn.setExpanded(this._isReplaceVisible); // Widget this._domNode = document.createElement('div'); this._domNode.className = 'editor-widget find-widget'; this._domNode.setAttribute('aria-hidden', 'true'); // We need to set this explicitly, otherwise on IE11, the width inheritence of flex doesn't work. this._domNode.style.width = FIND_WIDGET_INITIAL_WIDTH + "px"; this._domNode.appendChild(this._toggleReplaceBtn.domNode); this._domNode.appendChild(findPart); this._domNode.appendChild(replacePart); this._resizeSash = new sash_1.Sash(this._domNode, this, { orientation: 0 /* VERTICAL */ }); this._resized = false; var originalWidth = FIND_WIDGET_INITIAL_WIDTH; this._register(this._resizeSash.onDidStart(function () { originalWidth = dom.getTotalWidth(_this._domNode); })); this._register(this._resizeSash.onDidChange(function (evt) { _this._resized = true; var width = originalWidth + evt.startX - evt.currentX; if (width < FIND_WIDGET_INITIAL_WIDTH) { // narrow down the find widget should be handled by CSS. return; } var maxWidth = parseFloat(dom.getComputedStyle(_this._domNode).maxWidth) || 0; if (width > maxWidth) { return; } _this._domNode.style.width = width + "px"; if (_this._isReplaceVisible) { _this._replaceInput.width = dom.getTotalWidth(_this._findInput.domNode); } _this._findInput.inputBox.layout(); _this._tryUpdateHeight(); })); this._register(this._resizeSash.onDidReset(function () { // users double click on the sash var currentWidth = dom.getTotalWidth(_this._domNode); if (currentWidth < FIND_WIDGET_INITIAL_WIDTH) { // The editor is narrow and the width of the find widget is controlled fully by CSS. return; } var width = FIND_WIDGET_INITIAL_WIDTH; if (!_this._resized || currentWidth === FIND_WIDGET_INITIAL_WIDTH) { // 1. never resized before, double click should maximizes it // 2. users resized it already but its width is the same as default var layoutInfo = _this._codeEditor.getLayoutInfo(); width = layoutInfo.width - 28 - layoutInfo.minimapWidth - 15; _this._resized = true; } else { /** * no op, the find widget should be shrinked to its default size. */ } _this._domNode.style.width = width + "px"; if (_this._isReplaceVisible) { _this._replaceInput.width = dom.getTotalWidth(_this._findInput.domNode); } _this._findInput.inputBox.layout(); })); }; FindWidget.prototype.updateAccessibilitySupport = function () { var value = this._codeEditor.getOption(2 /* accessibilitySupport */); this._findInput.setFocusInputOnOptionClick(value !== 2 /* Enabled */); }; FindWidget.ID = 'editor.contrib.findWidget'; return FindWidget; }(widget_1.Widget)); exports.FindWidget = FindWidget; var SimpleButton = /** @class */ (function (_super) { __extends(SimpleButton, _super); function SimpleButton(opts) { var _this = _super.call(this) || this; _this._opts = opts; _this._domNode = document.createElement('div'); _this._domNode.title = _this._opts.label; _this._domNode.tabIndex = 0; _this._domNode.className = 'button ' + _this._opts.className; _this._domNode.setAttribute('role', 'button'); _this._domNode.setAttribute('aria-label', _this._opts.label); _this.onclick(_this._domNode, function (e) { _this._opts.onTrigger(); e.preventDefault(); }); _this.onkeydown(_this._domNode, function (e) { if (e.equals(10 /* Space */) || e.equals(3 /* Enter */)) { _this._opts.onTrigger(); e.preventDefault(); return; } if (_this._opts.onKeyDown) { _this._opts.onKeyDown(e); } }); return _this; } Object.defineProperty(SimpleButton.prototype, "domNode", { get: function () { return this._domNode; }, enumerable: true, configurable: true }); SimpleButton.prototype.isEnabled = function () { return (this._domNode.tabIndex >= 0); }; SimpleButton.prototype.focus = function () { this._domNode.focus(); }; SimpleButton.prototype.setEnabled = function (enabled) { dom.toggleClass(this._domNode, 'disabled', !enabled); this._domNode.setAttribute('aria-disabled', String(!enabled)); this._domNode.tabIndex = enabled ? 0 : -1; }; SimpleButton.prototype.setExpanded = function (expanded) { this._domNode.setAttribute('aria-expanded', String(!!expanded)); }; SimpleButton.prototype.toggleClass = function (className, shouldHaveIt) { dom.toggleClass(this._domNode, className, shouldHaveIt); }; return SimpleButton; }(widget_1.Widget)); exports.SimpleButton = SimpleButton; // theming themeService_1.registerThemingParticipant(function (theme, collector) { var addBackgroundColorRule = function (selector, color) { if (color) { collector.addRule(".monaco-editor " + selector + " { background-color: " + color + "; }"); } }; addBackgroundColorRule('.findMatch', theme.getColor(colorRegistry_1.editorFindMatchHighlight)); addBackgroundColorRule('.currentFindMatch', theme.getColor(colorRegistry_1.editorFindMatch)); addBackgroundColorRule('.findScope', theme.getColor(colorRegistry_1.editorFindRangeHighlight)); var widgetBackground = theme.getColor(colorRegistry_1.editorWidgetBackground); addBackgroundColorRule('.find-widget', widgetBackground); var widgetShadowColor = theme.getColor(colorRegistry_1.widgetShadow); if (widgetShadowColor) { collector.addRule(".monaco-editor .find-widget { box-shadow: 0 2px 8px " + widgetShadowColor + "; }"); } var findMatchHighlightBorder = theme.getColor(colorRegistry_1.editorFindMatchHighlightBorder); if (findMatchHighlightBorder) { collector.addRule(".monaco-editor .findMatch { border: 1px " + (theme.type === 'hc' ? 'dotted' : 'solid') + " " + findMatchHighlightBorder + "; box-sizing: border-box; }"); } var findMatchBorder = theme.getColor(colorRegistry_1.editorFindMatchBorder); if (findMatchBorder) { collector.addRule(".monaco-editor .currentFindMatch { border: 2px solid " + findMatchBorder + "; padding: 1px; box-sizing: border-box; }"); } var findRangeHighlightBorder = theme.getColor(colorRegistry_1.editorFindRangeHighlightBorder); if (findRangeHighlightBorder) { collector.addRule(".monaco-editor .findScope { border: 1px " + (theme.type === 'hc' ? 'dashed' : 'solid') + " " + findRangeHighlightBorder + "; }"); } var hcBorder = theme.getColor(colorRegistry_1.contrastBorder); if (hcBorder) { collector.addRule(".monaco-editor .find-widget { border: 1px solid " + hcBorder + "; }"); } var foreground = theme.getColor(colorRegistry_1.editorWidgetForeground); if (foreground) { collector.addRule(".monaco-editor .find-widget { color: " + foreground + "; }"); } var error = theme.getColor(colorRegistry_1.errorForeground); if (error) { collector.addRule(".monaco-editor .find-widget.no-results .matchesCount { color: " + error + "; }"); } var resizeBorderBackground = theme.getColor(colorRegistry_1.editorWidgetResizeBorder); if (resizeBorderBackground) { collector.addRule(".monaco-editor .find-widget .monaco-sash { background-color: " + resizeBorderBackground + "; width: 3px !important; margin-left: -4px;}"); } else { var border = theme.getColor(colorRegistry_1.editorWidgetBorder); if (border) { collector.addRule(".monaco-editor .find-widget .monaco-sash { background-color: " + border + "; width: 3px !important; margin-left: -4px;}"); } } // This rule is used to override the outline color for synthetic-focus find input. var focusOutline = theme.getColor(colorRegistry_1.focusBorder); if (focusOutline) { collector.addRule(".monaco-editor .find-widget .monaco-inputbox.synthetic-focus { outline-color: " + focusOutline + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[232/*vs/editor/contrib/find/findController*/], __M([0/*require*/,1/*exports*/,438/*vs/nls!vs/editor/contrib/find/findController*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,12/*vs/editor/browser/editorExtensions*/,23/*vs/editor/common/editorContextKeys*/,168/*vs/editor/contrib/find/findModel*/,572/*vs/editor/contrib/find/findOptionsWidget*/,378/*vs/editor/contrib/find/findState*/,573/*vs/editor/contrib/find/findWidget*/,162/*vs/platform/clipboard/common/clipboardService*/,18/*vs/platform/contextkey/common/contextkey*/,66/*vs/platform/contextview/browser/contextView*/,11/*vs/platform/instantiation/common/instantiation*/,34/*vs/platform/keybinding/common/keybinding*/,74/*vs/platform/storage/common/storage*/,14/*vs/platform/theme/common/themeService*/,35/*vs/platform/notification/common/notification*/]), function (require, exports, nls, async_1, lifecycle_1, strings, editorExtensions_1, editorContextKeys_1, findModel_1, findOptionsWidget_1, findState_1, findWidget_1, clipboardService_1, contextkey_1, contextView_1, instantiation_1, keybinding_1, storage_1, themeService_1, notification_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var SEARCH_STRING_MAX_LENGTH = 524288; function getSelectionSearchString(editor) { if (!editor.hasModel()) { return null; } var selection = editor.getSelection(); // if selection spans multiple lines, default search string to empty if (selection.startLineNumber === selection.endLineNumber) { if (selection.isEmpty()) { var wordAtPosition = editor.getModel().getWordAtPosition(selection.getStartPosition()); if (wordAtPosition) { return wordAtPosition.word; } } else { if (editor.getModel().getValueLengthInRange(selection) < SEARCH_STRING_MAX_LENGTH) { return editor.getModel().getValueInRange(selection); } } } return null; } exports.getSelectionSearchString = getSelectionSearchString; var CommonFindController = /** @class */ (function (_super) { __extends(CommonFindController, _super); function CommonFindController(editor, contextKeyService, storageService, clipboardService) { var _this = _super.call(this) || this; _this._editor = editor; _this._findWidgetVisible = findModel_1.CONTEXT_FIND_WIDGET_VISIBLE.bindTo(contextKeyService); _this._contextKeyService = contextKeyService; _this._storageService = storageService; _this._clipboardService = clipboardService; _this._updateHistoryDelayer = new async_1.Delayer(500); _this._state = _this._register(new findState_1.FindReplaceState()); _this.loadQueryState(); _this._register(_this._state.onFindReplaceStateChange(function (e) { return _this._onStateChanged(e); })); _this._model = null; _this._register(_this._editor.onDidChangeModel(function () { var shouldRestartFind = (_this._editor.getModel() && _this._state.isRevealed); _this.disposeModel(); _this._state.change({ searchScope: null, matchCase: _this._storageService.getBoolean('editor.matchCase', 1 /* WORKSPACE */, false), wholeWord: _this._storageService.getBoolean('editor.wholeWord', 1 /* WORKSPACE */, false), isRegex: _this._storageService.getBoolean('editor.isRegex', 1 /* WORKSPACE */, false), preserveCase: _this._storageService.getBoolean('editor.preserveCase', 1 /* WORKSPACE */, false) }, false); if (shouldRestartFind) { _this._start({ forceRevealReplace: false, seedSearchStringFromSelection: false && _this._editor.getOption(28 /* find */).seedSearchStringFromSelection, seedSearchStringFromGlobalClipboard: false, shouldFocus: 0 /* NoFocusChange */, shouldAnimate: false, updateSearchScope: false }); } })); return _this; } CommonFindController.get = function (editor) { return editor.getContribution(CommonFindController.ID); }; CommonFindController.prototype.dispose = function () { this.disposeModel(); _super.prototype.dispose.call(this); }; CommonFindController.prototype.disposeModel = function () { if (this._model) { this._model.dispose(); this._model = null; } }; CommonFindController.prototype._onStateChanged = function (e) { this.saveQueryState(e); if (e.isRevealed) { if (this._state.isRevealed) { this._findWidgetVisible.set(true); } else { this._findWidgetVisible.reset(); this.disposeModel(); } } if (e.searchString) { this.setGlobalBufferTerm(this._state.searchString); } }; CommonFindController.prototype.saveQueryState = function (e) { if (e.isRegex) { this._storageService.store('editor.isRegex', this._state.actualIsRegex, 1 /* WORKSPACE */); } if (e.wholeWord) { this._storageService.store('editor.wholeWord', this._state.actualWholeWord, 1 /* WORKSPACE */); } if (e.matchCase) { this._storageService.store('editor.matchCase', this._state.actualMatchCase, 1 /* WORKSPACE */); } if (e.preserveCase) { this._storageService.store('editor.preserveCase', this._state.actualPreserveCase, 1 /* WORKSPACE */); } }; CommonFindController.prototype.loadQueryState = function () { this._state.change({ matchCase: this._storageService.getBoolean('editor.matchCase', 1 /* WORKSPACE */, this._state.matchCase), wholeWord: this._storageService.getBoolean('editor.wholeWord', 1 /* WORKSPACE */, this._state.wholeWord), isRegex: this._storageService.getBoolean('editor.isRegex', 1 /* WORKSPACE */, this._state.isRegex), preserveCase: this._storageService.getBoolean('editor.preserveCase', 1 /* WORKSPACE */, this._state.preserveCase) }, false); }; CommonFindController.prototype.isFindInputFocused = function () { return !!findModel_1.CONTEXT_FIND_INPUT_FOCUSED.getValue(this._contextKeyService); }; CommonFindController.prototype.getState = function () { return this._state; }; CommonFindController.prototype.closeFindWidget = function () { this._state.change({ isRevealed: false, searchScope: null }, false); this._editor.focus(); }; CommonFindController.prototype.toggleCaseSensitive = function () { this._state.change({ matchCase: !this._state.matchCase }, false); if (!this._state.isRevealed) { this.highlightFindOptions(); } }; CommonFindController.prototype.toggleWholeWords = function () { this._state.change({ wholeWord: !this._state.wholeWord }, false); if (!this._state.isRevealed) { this.highlightFindOptions(); } }; CommonFindController.prototype.toggleRegex = function () { this._state.change({ isRegex: !this._state.isRegex }, false); if (!this._state.isRevealed) { this.highlightFindOptions(); } }; CommonFindController.prototype.toggleSearchScope = function () { if (this._state.searchScope) { this._state.change({ searchScope: null }, true); } else { if (this._editor.hasModel()) { var selection = this._editor.getSelection(); if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) { selection = selection.setEndPosition(selection.endLineNumber - 1, this._editor.getModel().getLineMaxColumn(selection.endLineNumber - 1)); } if (!selection.isEmpty()) { this._state.change({ searchScope: selection }, true); } } } }; CommonFindController.prototype.setSearchString = function (searchString) { if (this._state.isRegex) { searchString = strings.escapeRegExpCharacters(searchString); } this._state.change({ searchString: searchString }, false); }; CommonFindController.prototype.highlightFindOptions = function () { // overwritten in subclass }; CommonFindController.prototype._start = function (opts) { this.disposeModel(); if (!this._editor.hasModel()) { // cannot do anything with an editor that doesn't have a model... return; } var stateChanges = { isRevealed: true }; if (opts.seedSearchStringFromSelection) { var selectionSearchString = getSelectionSearchString(this._editor); if (selectionSearchString) { if (this._state.isRegex) { stateChanges.searchString = strings.escapeRegExpCharacters(selectionSearchString); } else { stateChanges.searchString = selectionSearchString; } } } if (!stateChanges.searchString && opts.seedSearchStringFromGlobalClipboard) { var selectionSearchString = this.getGlobalBufferTerm(); if (selectionSearchString) { stateChanges.searchString = selectionSearchString; } } // Overwrite isReplaceRevealed if (opts.forceRevealReplace) { stateChanges.isReplaceRevealed = true; } else if (!this._findWidgetVisible.get()) { stateChanges.isReplaceRevealed = false; } if (opts.updateSearchScope) { var currentSelection = this._editor.getSelection(); if (!currentSelection.isEmpty()) { stateChanges.searchScope = currentSelection; } } this._state.change(stateChanges, false); if (!this._model) { this._model = new findModel_1.FindModelBoundToEditorModel(this._editor, this._state); } }; CommonFindController.prototype.start = function (opts) { this._start(opts); }; CommonFindController.prototype.moveToNextMatch = function () { if (this._model) { this._model.moveToNextMatch(); return true; } return false; }; CommonFindController.prototype.moveToPrevMatch = function () { if (this._model) { this._model.moveToPrevMatch(); return true; } return false; }; CommonFindController.prototype.replace = function () { if (this._model) { this._model.replace(); return true; } return false; }; CommonFindController.prototype.replaceAll = function () { if (this._model) { this._model.replaceAll(); return true; } return false; }; CommonFindController.prototype.selectAllMatches = function () { if (this._model) { this._model.selectAllMatches(); this._editor.focus(); return true; } return false; }; CommonFindController.prototype.getGlobalBufferTerm = function () { if (this._editor.getOption(28 /* find */).globalFindClipboard && this._clipboardService && this._editor.hasModel() && !this._editor.getModel().isTooLargeForSyncing()) { return this._clipboardService.readFindText(); } return ''; }; CommonFindController.prototype.setGlobalBufferTerm = function (text) { if (this._editor.getOption(28 /* find */).globalFindClipboard && this._clipboardService && this._editor.hasModel() && !this._editor.getModel().isTooLargeForSyncing()) { this._clipboardService.writeFindText(text); } }; CommonFindController.ID = 'editor.contrib.findController'; CommonFindController = __decorate([ __param(1, contextkey_1.IContextKeyService), __param(2, storage_1.IStorageService), __param(3, clipboardService_1.IClipboardService) ], CommonFindController); return CommonFindController; }(lifecycle_1.Disposable)); exports.CommonFindController = CommonFindController; var FindController = /** @class */ (function (_super) { __extends(FindController, _super); function FindController(editor, _contextViewService, _contextKeyService, _keybindingService, _themeService, _notificationService, _storageService, clipboardService) { var _this = _super.call(this, editor, _contextKeyService, _storageService, clipboardService) || this; _this._contextViewService = _contextViewService; _this._keybindingService = _keybindingService; _this._themeService = _themeService; _this._notificationService = _notificationService; _this._widget = null; _this._findOptionsWidget = null; return _this; } FindController.prototype._start = function (opts) { if (!this._widget) { this._createFindWidget(); } var selection = this._editor.getSelection(); var updateSearchScope = false; switch (this._editor.getOption(28 /* find */).autoFindInSelection) { case 'always': updateSearchScope = true; break; case 'never': updateSearchScope = false; break; case 'multiline': var isSelectionMultipleLine = !!selection && selection.startLineNumber !== selection.endLineNumber; updateSearchScope = isSelectionMultipleLine; break; default: break; } opts.updateSearchScope = updateSearchScope; _super.prototype._start.call(this, opts); if (opts.shouldFocus === 2 /* FocusReplaceInput */) { this._widget.focusReplaceInput(); } else if (opts.shouldFocus === 1 /* FocusFindInput */) { this._widget.focusFindInput(); } }; FindController.prototype.highlightFindOptions = function () { if (!this._widget) { this._createFindWidget(); } if (this._state.isRevealed) { this._widget.highlightFindOptions(); } else { this._findOptionsWidget.highlightFindOptions(); } }; FindController.prototype._createFindWidget = function () { this._widget = this._register(new findWidget_1.FindWidget(this._editor, this, this._state, this._contextViewService, this._keybindingService, this._contextKeyService, this._themeService, this._storageService, this._notificationService)); this._findOptionsWidget = this._register(new findOptionsWidget_1.FindOptionsWidget(this._editor, this._state, this._keybindingService, this._themeService)); }; FindController = __decorate([ __param(1, contextView_1.IContextViewService), __param(2, contextkey_1.IContextKeyService), __param(3, keybinding_1.IKeybindingService), __param(4, themeService_1.IThemeService), __param(5, notification_1.INotificationService), __param(6, storage_1.IStorageService), __param(7, instantiation_1.optional(clipboardService_1.IClipboardService)) ], FindController); return FindController; }(CommonFindController)); exports.FindController = FindController; var StartFindAction = /** @class */ (function (_super) { __extends(StartFindAction, _super); function StartFindAction() { return _super.call(this, { id: findModel_1.FIND_IDS.StartFindAction, label: nls.localize(0, null), alias: 'Find', precondition: undefined, kbOpts: { kbExpr: null, primary: 2048 /* CtrlCmd */ | 36 /* KEY_F */, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 17 /* MenubarEditMenu */, group: '3_find', title: nls.localize(1, null), order: 1 } }) || this; } StartFindAction.prototype.run = function (accessor, editor) { var controller = CommonFindController.get(editor); if (controller) { controller.start({ forceRevealReplace: false, seedSearchStringFromSelection: editor.getOption(28 /* find */).seedSearchStringFromSelection, seedSearchStringFromGlobalClipboard: editor.getOption(28 /* find */).globalFindClipboard, shouldFocus: 1 /* FocusFindInput */, shouldAnimate: true, updateSearchScope: false }); } }; return StartFindAction; }(editorExtensions_1.EditorAction)); exports.StartFindAction = StartFindAction; var StartFindWithSelectionAction = /** @class */ (function (_super) { __extends(StartFindWithSelectionAction, _super); function StartFindWithSelectionAction() { return _super.call(this, { id: findModel_1.FIND_IDS.StartFindWithSelection, label: nls.localize(2, null), alias: 'Find With Selection', precondition: undefined, kbOpts: { kbExpr: null, primary: 0, mac: { primary: 2048 /* CtrlCmd */ | 35 /* KEY_E */, }, weight: 100 /* EditorContrib */ } }) || this; } StartFindWithSelectionAction.prototype.run = function (accessor, editor) { var controller = CommonFindController.get(editor); if (controller) { controller.start({ forceRevealReplace: false, seedSearchStringFromSelection: true, seedSearchStringFromGlobalClipboard: false, shouldFocus: 0 /* NoFocusChange */, shouldAnimate: true, updateSearchScope: false }); controller.setGlobalBufferTerm(controller.getState().searchString); } }; return StartFindWithSelectionAction; }(editorExtensions_1.EditorAction)); exports.StartFindWithSelectionAction = StartFindWithSelectionAction; var MatchFindAction = /** @class */ (function (_super) { __extends(MatchFindAction, _super); function MatchFindAction() { return _super !== null && _super.apply(this, arguments) || this; } MatchFindAction.prototype.run = function (accessor, editor) { var controller = CommonFindController.get(editor); if (controller && !this._run(controller)) { controller.start({ forceRevealReplace: false, seedSearchStringFromSelection: (controller.getState().searchString.length === 0) && editor.getOption(28 /* find */).seedSearchStringFromSelection, seedSearchStringFromGlobalClipboard: true, shouldFocus: 0 /* NoFocusChange */, shouldAnimate: true, updateSearchScope: false }); this._run(controller); } }; return MatchFindAction; }(editorExtensions_1.EditorAction)); exports.MatchFindAction = MatchFindAction; var NextMatchFindAction = /** @class */ (function (_super) { __extends(NextMatchFindAction, _super); function NextMatchFindAction() { return _super.call(this, { id: findModel_1.FIND_IDS.NextMatchFindAction, label: nls.localize(3, null), alias: 'Find Next', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 61 /* F3 */, mac: { primary: 2048 /* CtrlCmd */ | 37 /* KEY_G */, secondary: [61 /* F3 */] }, weight: 100 /* EditorContrib */ } }) || this; } NextMatchFindAction.prototype._run = function (controller) { return controller.moveToNextMatch(); }; return NextMatchFindAction; }(MatchFindAction)); exports.NextMatchFindAction = NextMatchFindAction; var NextMatchFindAction2 = /** @class */ (function (_super) { __extends(NextMatchFindAction2, _super); function NextMatchFindAction2() { return _super.call(this, { id: findModel_1.FIND_IDS.NextMatchFindAction, label: nls.localize(4, null), alias: 'Find Next', precondition: undefined, kbOpts: { kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, findModel_1.CONTEXT_FIND_INPUT_FOCUSED), primary: 3 /* Enter */, weight: 100 /* EditorContrib */ } }) || this; } NextMatchFindAction2.prototype._run = function (controller) { return controller.moveToNextMatch(); }; return NextMatchFindAction2; }(MatchFindAction)); exports.NextMatchFindAction2 = NextMatchFindAction2; var PreviousMatchFindAction = /** @class */ (function (_super) { __extends(PreviousMatchFindAction, _super); function PreviousMatchFindAction() { return _super.call(this, { id: findModel_1.FIND_IDS.PreviousMatchFindAction, label: nls.localize(5, null), alias: 'Find Previous', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 1024 /* Shift */ | 61 /* F3 */, mac: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 37 /* KEY_G */, secondary: [1024 /* Shift */ | 61 /* F3 */] }, weight: 100 /* EditorContrib */ } }) || this; } PreviousMatchFindAction.prototype._run = function (controller) { return controller.moveToPrevMatch(); }; return PreviousMatchFindAction; }(MatchFindAction)); exports.PreviousMatchFindAction = PreviousMatchFindAction; var PreviousMatchFindAction2 = /** @class */ (function (_super) { __extends(PreviousMatchFindAction2, _super); function PreviousMatchFindAction2() { return _super.call(this, { id: findModel_1.FIND_IDS.PreviousMatchFindAction, label: nls.localize(6, null), alias: 'Find Previous', precondition: undefined, kbOpts: { kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, findModel_1.CONTEXT_FIND_INPUT_FOCUSED), primary: 1024 /* Shift */ | 3 /* Enter */, weight: 100 /* EditorContrib */ } }) || this; } PreviousMatchFindAction2.prototype._run = function (controller) { return controller.moveToPrevMatch(); }; return PreviousMatchFindAction2; }(MatchFindAction)); exports.PreviousMatchFindAction2 = PreviousMatchFindAction2; var SelectionMatchFindAction = /** @class */ (function (_super) { __extends(SelectionMatchFindAction, _super); function SelectionMatchFindAction() { return _super !== null && _super.apply(this, arguments) || this; } SelectionMatchFindAction.prototype.run = function (accessor, editor) { var controller = CommonFindController.get(editor); if (!controller) { return; } var selectionSearchString = getSelectionSearchString(editor); if (selectionSearchString) { controller.setSearchString(selectionSearchString); } if (!this._run(controller)) { controller.start({ forceRevealReplace: false, seedSearchStringFromSelection: editor.getOption(28 /* find */).seedSearchStringFromSelection, seedSearchStringFromGlobalClipboard: false, shouldFocus: 0 /* NoFocusChange */, shouldAnimate: true, updateSearchScope: false }); this._run(controller); } }; return SelectionMatchFindAction; }(editorExtensions_1.EditorAction)); exports.SelectionMatchFindAction = SelectionMatchFindAction; var NextSelectionMatchFindAction = /** @class */ (function (_super) { __extends(NextSelectionMatchFindAction, _super); function NextSelectionMatchFindAction() { return _super.call(this, { id: findModel_1.FIND_IDS.NextSelectionMatchFindAction, label: nls.localize(7, null), alias: 'Find Next Selection', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 2048 /* CtrlCmd */ | 61 /* F3 */, weight: 100 /* EditorContrib */ } }) || this; } NextSelectionMatchFindAction.prototype._run = function (controller) { return controller.moveToNextMatch(); }; return NextSelectionMatchFindAction; }(SelectionMatchFindAction)); exports.NextSelectionMatchFindAction = NextSelectionMatchFindAction; var PreviousSelectionMatchFindAction = /** @class */ (function (_super) { __extends(PreviousSelectionMatchFindAction, _super); function PreviousSelectionMatchFindAction() { return _super.call(this, { id: findModel_1.FIND_IDS.PreviousSelectionMatchFindAction, label: nls.localize(8, null), alias: 'Find Previous Selection', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 61 /* F3 */, weight: 100 /* EditorContrib */ } }) || this; } PreviousSelectionMatchFindAction.prototype._run = function (controller) { return controller.moveToPrevMatch(); }; return PreviousSelectionMatchFindAction; }(SelectionMatchFindAction)); exports.PreviousSelectionMatchFindAction = PreviousSelectionMatchFindAction; var StartFindReplaceAction = /** @class */ (function (_super) { __extends(StartFindReplaceAction, _super); function StartFindReplaceAction() { return _super.call(this, { id: findModel_1.FIND_IDS.StartFindReplaceAction, label: nls.localize(9, null), alias: 'Replace', precondition: undefined, kbOpts: { kbExpr: null, primary: 2048 /* CtrlCmd */ | 38 /* KEY_H */, mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 36 /* KEY_F */ }, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 17 /* MenubarEditMenu */, group: '3_find', title: nls.localize(10, null), order: 2 } }) || this; } StartFindReplaceAction.prototype.run = function (accessor, editor) { if (!editor.hasModel() || editor.getOption(68 /* readOnly */)) { return; } var controller = CommonFindController.get(editor); var currentSelection = editor.getSelection(); var findInputFocused = controller.isFindInputFocused(); // we only seed search string from selection when the current selection is single line and not empty, // + the find input is not focused var seedSearchStringFromSelection = !currentSelection.isEmpty() && currentSelection.startLineNumber === currentSelection.endLineNumber && editor.getOption(28 /* find */).seedSearchStringFromSelection && !findInputFocused; /* * if the existing search string in find widget is empty and we don't seed search string from selection, it means the Find Input is still empty, so we should focus the Find Input instead of Replace Input. * findInputFocused true -> seedSearchStringFromSelection false, FocusReplaceInput * findInputFocused false, seedSearchStringFromSelection true FocusReplaceInput * findInputFocused false seedSearchStringFromSelection false FocusFindInput */ var shouldFocus = (findInputFocused || seedSearchStringFromSelection) ? 2 /* FocusReplaceInput */ : 1 /* FocusFindInput */; if (controller) { controller.start({ forceRevealReplace: true, seedSearchStringFromSelection: seedSearchStringFromSelection, seedSearchStringFromGlobalClipboard: editor.getOption(28 /* find */).seedSearchStringFromSelection, shouldFocus: shouldFocus, shouldAnimate: true, updateSearchScope: false }); } }; return StartFindReplaceAction; }(editorExtensions_1.EditorAction)); exports.StartFindReplaceAction = StartFindReplaceAction; editorExtensions_1.registerEditorContribution(CommonFindController.ID, FindController); editorExtensions_1.registerEditorAction(StartFindAction); editorExtensions_1.registerEditorAction(StartFindWithSelectionAction); editorExtensions_1.registerEditorAction(NextMatchFindAction); editorExtensions_1.registerEditorAction(NextMatchFindAction2); editorExtensions_1.registerEditorAction(PreviousMatchFindAction); editorExtensions_1.registerEditorAction(PreviousMatchFindAction2); editorExtensions_1.registerEditorAction(NextSelectionMatchFindAction); editorExtensions_1.registerEditorAction(PreviousSelectionMatchFindAction); editorExtensions_1.registerEditorAction(StartFindReplaceAction); var FindCommand = editorExtensions_1.EditorCommand.bindToContribution(CommonFindController.get); editorExtensions_1.registerEditorCommand(new FindCommand({ id: findModel_1.FIND_IDS.CloseFindWidgetCommand, precondition: findModel_1.CONTEXT_FIND_WIDGET_VISIBLE, handler: function (x) { return x.closeFindWidget(); }, kbOpts: { weight: 100 /* EditorContrib */ + 5, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 9 /* Escape */, secondary: [1024 /* Shift */ | 9 /* Escape */] } })); editorExtensions_1.registerEditorCommand(new FindCommand({ id: findModel_1.FIND_IDS.ToggleCaseSensitiveCommand, precondition: undefined, handler: function (x) { return x.toggleCaseSensitive(); }, kbOpts: { weight: 100 /* EditorContrib */ + 5, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: findModel_1.ToggleCaseSensitiveKeybinding.primary, mac: findModel_1.ToggleCaseSensitiveKeybinding.mac, win: findModel_1.ToggleCaseSensitiveKeybinding.win, linux: findModel_1.ToggleCaseSensitiveKeybinding.linux } })); editorExtensions_1.registerEditorCommand(new FindCommand({ id: findModel_1.FIND_IDS.ToggleWholeWordCommand, precondition: undefined, handler: function (x) { return x.toggleWholeWords(); }, kbOpts: { weight: 100 /* EditorContrib */ + 5, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: findModel_1.ToggleWholeWordKeybinding.primary, mac: findModel_1.ToggleWholeWordKeybinding.mac, win: findModel_1.ToggleWholeWordKeybinding.win, linux: findModel_1.ToggleWholeWordKeybinding.linux } })); editorExtensions_1.registerEditorCommand(new FindCommand({ id: findModel_1.FIND_IDS.ToggleRegexCommand, precondition: undefined, handler: function (x) { return x.toggleRegex(); }, kbOpts: { weight: 100 /* EditorContrib */ + 5, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: findModel_1.ToggleRegexKeybinding.primary, mac: findModel_1.ToggleRegexKeybinding.mac, win: findModel_1.ToggleRegexKeybinding.win, linux: findModel_1.ToggleRegexKeybinding.linux } })); editorExtensions_1.registerEditorCommand(new FindCommand({ id: findModel_1.FIND_IDS.ToggleSearchScopeCommand, precondition: undefined, handler: function (x) { return x.toggleSearchScope(); }, kbOpts: { weight: 100 /* EditorContrib */ + 5, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: findModel_1.ToggleSearchScopeKeybinding.primary, mac: findModel_1.ToggleSearchScopeKeybinding.mac, win: findModel_1.ToggleSearchScopeKeybinding.win, linux: findModel_1.ToggleSearchScopeKeybinding.linux } })); editorExtensions_1.registerEditorCommand(new FindCommand({ id: findModel_1.FIND_IDS.ReplaceOneAction, precondition: findModel_1.CONTEXT_FIND_WIDGET_VISIBLE, handler: function (x) { return x.replace(); }, kbOpts: { weight: 100 /* EditorContrib */ + 5, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 22 /* KEY_1 */ } })); editorExtensions_1.registerEditorCommand(new FindCommand({ id: findModel_1.FIND_IDS.ReplaceOneAction, precondition: findModel_1.CONTEXT_FIND_WIDGET_VISIBLE, handler: function (x) { return x.replace(); }, kbOpts: { weight: 100 /* EditorContrib */ + 5, kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, findModel_1.CONTEXT_REPLACE_INPUT_FOCUSED), primary: 3 /* Enter */ } })); editorExtensions_1.registerEditorCommand(new FindCommand({ id: findModel_1.FIND_IDS.ReplaceAllAction, precondition: findModel_1.CONTEXT_FIND_WIDGET_VISIBLE, handler: function (x) { return x.replaceAll(); }, kbOpts: { weight: 100 /* EditorContrib */ + 5, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 3 /* Enter */ } })); editorExtensions_1.registerEditorCommand(new FindCommand({ id: findModel_1.FIND_IDS.ReplaceAllAction, precondition: findModel_1.CONTEXT_FIND_WIDGET_VISIBLE, handler: function (x) { return x.replaceAll(); }, kbOpts: { weight: 100 /* EditorContrib */ + 5, kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, findModel_1.CONTEXT_REPLACE_INPUT_FOCUSED), primary: undefined, mac: { primary: 2048 /* CtrlCmd */ | 3 /* Enter */, } } })); editorExtensions_1.registerEditorCommand(new FindCommand({ id: findModel_1.FIND_IDS.SelectAllMatchesAction, precondition: findModel_1.CONTEXT_FIND_WIDGET_VISIBLE, handler: function (x) { return x.selectAllMatches(); }, kbOpts: { weight: 100 /* EditorContrib */ + 5, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 512 /* Alt */ | 3 /* Enter */ } })); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[574/*vs/editor/contrib/folding/folding*/], __M([0/*require*/,1/*exports*/,440/*vs/nls!vs/editor/contrib/folding/folding*/,21/*vs/base/common/types*/,5/*vs/base/common/strings*/,15/*vs/base/common/async*/,36/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,12/*vs/editor/browser/editorExtensions*/,381/*vs/editor/contrib/folding/foldingModel*/,490/*vs/editor/contrib/folding/foldingDecorations*/,23/*vs/editor/common/editorContextKeys*/,382/*vs/editor/contrib/folding/hiddenRangeModel*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/,491/*vs/editor/contrib/folding/indentRangeProvider*/,17/*vs/editor/common/modes*/,197/*vs/editor/contrib/folding/syntaxRangeProvider*/,383/*vs/editor/contrib/folding/intializingRangeProvider*/,10/*vs/base/common/errors*/,18/*vs/platform/contextkey/common/contextkey*/,14/*vs/platform/theme/common/themeService*/,20/*vs/platform/theme/common/colorRegistry*/,311/*vs/css!vs/editor/contrib/folding/folding*/]), function (require, exports, nls, types, strings_1, async_1, keyCodes_1, lifecycle_1, editorExtensions_1, foldingModel_1, foldingDecorations_1, editorContextKeys_1, hiddenRangeModel_1, languageConfigurationRegistry_1, indentRangeProvider_1, modes_1, syntaxRangeProvider_1, intializingRangeProvider_1, errors_1, contextkey_1, themeService_1, colorRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CONTEXT_FOLDING_ENABLED = new contextkey_1.RawContextKey('foldingEnabled', false); var FoldingController = /** @class */ (function (_super) { __extends(FoldingController, _super); function FoldingController(editor, contextKeyService) { var _this = _super.call(this) || this; _this.contextKeyService = contextKeyService; _this.localToDispose = _this._register(new lifecycle_1.DisposableStore()); _this.editor = editor; var options = _this.editor.getOptions(); _this._isEnabled = options.get(30 /* folding */); _this._useFoldingProviders = options.get(31 /* foldingStrategy */) !== 'indentation'; _this.foldingModel = null; _this.hiddenRangeModel = null; _this.rangeProvider = null; _this.foldingRegionPromise = null; _this.foldingStateMemento = null; _this.foldingModelPromise = null; _this.updateScheduler = null; _this.cursorChangedScheduler = null; _this.mouseDownInfo = null; _this.foldingDecorationProvider = new foldingDecorations_1.FoldingDecorationProvider(editor); _this.foldingDecorationProvider.autoHideFoldingControls = options.get(84 /* showFoldingControls */) === 'mouseover'; _this.foldingDecorationProvider.showFoldingHighlights = options.get(32 /* foldingHighlight */); _this.foldingEnabled = CONTEXT_FOLDING_ENABLED.bindTo(_this.contextKeyService); _this.foldingEnabled.set(_this._isEnabled); _this._register(_this.editor.onDidChangeModel(function () { return _this.onModelChanged(); })); _this._register(_this.editor.onDidChangeConfiguration(function (e) { if (e.hasChanged(30 /* folding */)) { var options_1 = _this.editor.getOptions(); _this._isEnabled = options_1.get(30 /* folding */); _this.foldingEnabled.set(_this._isEnabled); _this.onModelChanged(); } if (e.hasChanged(84 /* showFoldingControls */) || e.hasChanged(32 /* foldingHighlight */)) { var options_2 = _this.editor.getOptions(); _this.foldingDecorationProvider.autoHideFoldingControls = options_2.get(84 /* showFoldingControls */) === 'mouseover'; _this.foldingDecorationProvider.showFoldingHighlights = options_2.get(32 /* foldingHighlight */); _this.onModelContentChanged(); } if (e.hasChanged(31 /* foldingStrategy */)) { var options_3 = _this.editor.getOptions(); _this._useFoldingProviders = options_3.get(31 /* foldingStrategy */) !== 'indentation'; _this.onFoldingStrategyChanged(); } })); _this.onModelChanged(); return _this; } FoldingController.get = function (editor) { return editor.getContribution(FoldingController.ID); }; /** * Store view state. */ FoldingController.prototype.saveViewState = function () { var model = this.editor.getModel(); if (!model || !this._isEnabled || model.isTooLargeForTokenization()) { return {}; } if (this.foldingModel) { // disposed ? var collapsedRegions = this.foldingModel.isInitialized ? this.foldingModel.getMemento() : this.hiddenRangeModel.getMemento(); var provider = this.rangeProvider ? this.rangeProvider.id : undefined; return { collapsedRegions: collapsedRegions, lineCount: model.getLineCount(), provider: provider }; } return undefined; }; /** * Restore view state. */ FoldingController.prototype.restoreViewState = function (state) { var model = this.editor.getModel(); if (!model || !this._isEnabled || model.isTooLargeForTokenization() || !this.hiddenRangeModel) { return; } if (!state || !state.collapsedRegions || state.lineCount !== model.getLineCount()) { return; } if (state.provider === syntaxRangeProvider_1.ID_SYNTAX_PROVIDER || state.provider === intializingRangeProvider_1.ID_INIT_PROVIDER) { this.foldingStateMemento = state; } var collapsedRegions = state.collapsedRegions; // set the hidden ranges right away, before waiting for the folding model. if (this.hiddenRangeModel.applyMemento(collapsedRegions)) { var foldingModel = this.getFoldingModel(); if (foldingModel) { foldingModel.then(function (foldingModel) { if (foldingModel) { foldingModel.applyMemento(collapsedRegions); } }).then(undefined, errors_1.onUnexpectedError); } } }; FoldingController.prototype.onModelChanged = function () { var _this = this; this.localToDispose.clear(); var model = this.editor.getModel(); if (!this._isEnabled || !model || model.isTooLargeForTokenization()) { // huge files get no view model, so they cannot support hidden areas return; } this.foldingModel = new foldingModel_1.FoldingModel(model, this.foldingDecorationProvider); this.localToDispose.add(this.foldingModel); this.hiddenRangeModel = new hiddenRangeModel_1.HiddenRangeModel(this.foldingModel); this.localToDispose.add(this.hiddenRangeModel); this.localToDispose.add(this.hiddenRangeModel.onDidChange(function (hr) { return _this.onHiddenRangesChanges(hr); })); this.updateScheduler = new async_1.Delayer(200); this.cursorChangedScheduler = new async_1.RunOnceScheduler(function () { return _this.revealCursor(); }, 200); this.localToDispose.add(this.cursorChangedScheduler); this.localToDispose.add(modes_1.FoldingRangeProviderRegistry.onDidChange(function () { return _this.onFoldingStrategyChanged(); })); this.localToDispose.add(this.editor.onDidChangeModelLanguageConfiguration(function () { return _this.onFoldingStrategyChanged(); })); // covers model language changes as well this.localToDispose.add(this.editor.onDidChangeModelContent(function () { return _this.onModelContentChanged(); })); this.localToDispose.add(this.editor.onDidChangeCursorPosition(function () { return _this.onCursorPositionChanged(); })); this.localToDispose.add(this.editor.onMouseDown(function (e) { return _this.onEditorMouseDown(e); })); this.localToDispose.add(this.editor.onMouseUp(function (e) { return _this.onEditorMouseUp(e); })); this.localToDispose.add({ dispose: function () { if (_this.foldingRegionPromise) { _this.foldingRegionPromise.cancel(); _this.foldingRegionPromise = null; } if (_this.updateScheduler) { _this.updateScheduler.cancel(); } _this.updateScheduler = null; _this.foldingModel = null; _this.foldingModelPromise = null; _this.hiddenRangeModel = null; _this.cursorChangedScheduler = null; _this.foldingStateMemento = null; if (_this.rangeProvider) { _this.rangeProvider.dispose(); } _this.rangeProvider = null; } }); this.onModelContentChanged(); }; FoldingController.prototype.onFoldingStrategyChanged = function () { if (this.rangeProvider) { this.rangeProvider.dispose(); } this.rangeProvider = null; this.onModelContentChanged(); }; FoldingController.prototype.getRangeProvider = function (editorModel) { var _this = this; if (this.rangeProvider) { return this.rangeProvider; } this.rangeProvider = new indentRangeProvider_1.IndentRangeProvider(editorModel); // fallback if (this._useFoldingProviders && this.foldingModel) { var foldingProviders = modes_1.FoldingRangeProviderRegistry.ordered(this.foldingModel.textModel); if (foldingProviders.length === 0 && this.foldingStateMemento && this.foldingStateMemento.collapsedRegions) { var rangeProvider = this.rangeProvider = new intializingRangeProvider_1.InitializingRangeProvider(editorModel, this.foldingStateMemento.collapsedRegions, function () { // if after 30 the InitializingRangeProvider is still not replaced, force a refresh _this.foldingStateMemento = null; _this.onFoldingStrategyChanged(); }, 30000); return rangeProvider; // keep memento in case there are still no foldingProviders on the next request. } else if (foldingProviders.length > 0) { this.rangeProvider = new syntaxRangeProvider_1.SyntaxRangeProvider(editorModel, foldingProviders); } } this.foldingStateMemento = null; return this.rangeProvider; }; FoldingController.prototype.getFoldingModel = function () { return this.foldingModelPromise; }; FoldingController.prototype.onModelContentChanged = function () { var _this = this; if (this.updateScheduler) { if (this.foldingRegionPromise) { this.foldingRegionPromise.cancel(); this.foldingRegionPromise = null; } this.foldingModelPromise = this.updateScheduler.trigger(function () { var foldingModel = _this.foldingModel; if (!foldingModel) { // null if editor has been disposed, or folding turned off return null; } var foldingRegionPromise = _this.foldingRegionPromise = async_1.createCancelablePromise(function (token) { return _this.getRangeProvider(foldingModel.textModel).compute(token); }); return foldingRegionPromise.then(function (foldingRanges) { if (foldingRanges && foldingRegionPromise === _this.foldingRegionPromise) { // new request or cancelled in the meantime? // some cursors might have moved into hidden regions, make sure they are in expanded regions var selections = _this.editor.getSelections(); var selectionLineNumbers = selections ? selections.map(function (s) { return s.startLineNumber; }) : []; foldingModel.update(foldingRanges, selectionLineNumbers); } return foldingModel; }); }).then(undefined, function (err) { errors_1.onUnexpectedError(err); return null; }); } }; FoldingController.prototype.onHiddenRangesChanges = function (hiddenRanges) { if (this.hiddenRangeModel && hiddenRanges.length) { var selections = this.editor.getSelections(); if (selections) { if (this.hiddenRangeModel.adjustSelections(selections)) { this.editor.setSelections(selections); } } } this.editor.setHiddenAreas(hiddenRanges); }; FoldingController.prototype.onCursorPositionChanged = function () { if (this.hiddenRangeModel && this.hiddenRangeModel.hasRanges()) { this.cursorChangedScheduler.schedule(); } }; FoldingController.prototype.revealCursor = function () { var _this = this; var foldingModel = this.getFoldingModel(); if (!foldingModel) { return; } foldingModel.then(function (foldingModel) { if (foldingModel) { var selections = _this.editor.getSelections(); if (selections && selections.length > 0) { var toToggle = []; var _loop_1 = function (selection) { var lineNumber = selection.selectionStartLineNumber; if (_this.hiddenRangeModel && _this.hiddenRangeModel.isHidden(lineNumber)) { toToggle.push.apply(toToggle, foldingModel.getAllRegionsAtLine(lineNumber, function (r) { return r.isCollapsed && lineNumber > r.startLineNumber; })); } }; for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) { var selection = selections_1[_i]; _loop_1(selection); } if (toToggle.length) { foldingModel.toggleCollapseState(toToggle); _this.reveal(selections[0].getPosition()); } } } }).then(undefined, errors_1.onUnexpectedError); }; FoldingController.prototype.onEditorMouseDown = function (e) { this.mouseDownInfo = null; if (!this.hiddenRangeModel || !e.target || !e.target.range) { return; } if (!e.event.leftButton && !e.event.middleButton) { return; } var range = e.target.range; var iconClicked = false; switch (e.target.type) { case 4 /* GUTTER_LINE_DECORATIONS */: var data = e.target.detail; var offsetLeftInGutter = e.target.element.offsetLeft; var gutterOffsetX = data.offsetX - offsetLeftInGutter; // const gutterOffsetX = data.offsetX - data.glyphMarginWidth - data.lineNumbersWidth - data.glyphMarginLeft; // TODO@joao TODO@alex TODO@martin this is such that we don't collide with dirty diff if (gutterOffsetX < 5) { // the whitespace between the border and the real folding icon border is 5px return; } iconClicked = true; break; case 6 /* CONTENT_TEXT */: { if (this.hiddenRangeModel.hasRanges()) { var model = this.editor.getModel(); if (model && range.startColumn === model.getLineMaxColumn(range.startLineNumber)) { break; } } return; } default: return; } this.mouseDownInfo = { lineNumber: range.startLineNumber, iconClicked: iconClicked }; }; FoldingController.prototype.onEditorMouseUp = function (e) { var _this = this; var foldingModel = this.getFoldingModel(); if (!foldingModel || !this.mouseDownInfo || !e.target) { return; } var lineNumber = this.mouseDownInfo.lineNumber; var iconClicked = this.mouseDownInfo.iconClicked; var range = e.target.range; if (!range || range.startLineNumber !== lineNumber) { return; } if (iconClicked) { if (e.target.type !== 4 /* GUTTER_LINE_DECORATIONS */) { return; } } else { var model = this.editor.getModel(); if (!model || range.startColumn !== model.getLineMaxColumn(lineNumber)) { return; } } foldingModel.then(function (foldingModel) { if (foldingModel) { var region = foldingModel.getRegionAtLine(lineNumber); if (region && region.startLineNumber === lineNumber) { var isCollapsed = region.isCollapsed; if (iconClicked || isCollapsed) { var toToggle = []; var recursive = e.event.middleButton || e.event.shiftKey; if (recursive) { for (var _i = 0, _a = foldingModel.getRegionsInside(region); _i < _a.length; _i++) { var r = _a[_i]; if (r.isCollapsed === isCollapsed) { toToggle.push(r); } } } // when recursive, first only collapse all children. If all are already folded or there are no children, also fold parent. if (isCollapsed || !recursive || toToggle.length === 0) { toToggle.push(region); } foldingModel.toggleCollapseState(toToggle); _this.reveal({ lineNumber: lineNumber, column: 1 }); } } } }).then(undefined, errors_1.onUnexpectedError); }; FoldingController.prototype.reveal = function (position) { this.editor.revealPositionInCenterIfOutsideViewport(position, 0 /* Smooth */); }; FoldingController.ID = 'editor.contrib.folding'; FoldingController = __decorate([ __param(1, contextkey_1.IContextKeyService) ], FoldingController); return FoldingController; }(lifecycle_1.Disposable)); exports.FoldingController = FoldingController; var FoldingAction = /** @class */ (function (_super) { __extends(FoldingAction, _super); function FoldingAction() { return _super !== null && _super.apply(this, arguments) || this; } FoldingAction.prototype.runEditorCommand = function (accessor, editor, args) { var _this = this; var foldingController = FoldingController.get(editor); if (!foldingController) { return; } var foldingModelPromise = foldingController.getFoldingModel(); if (foldingModelPromise) { this.reportTelemetry(accessor, editor); return foldingModelPromise.then(function (foldingModel) { if (foldingModel) { _this.invoke(foldingController, foldingModel, editor, args); var selection = editor.getSelection(); if (selection) { foldingController.reveal(selection.getStartPosition()); } } }); } }; FoldingAction.prototype.getSelectedLines = function (editor) { var selections = editor.getSelections(); return selections ? selections.map(function (s) { return s.startLineNumber; }) : []; }; FoldingAction.prototype.getLineNumbers = function (args, editor) { if (args && args.selectionLines) { return args.selectionLines.map(function (l) { return l + 1; }); // to 0-bases line numbers } return this.getSelectedLines(editor); }; FoldingAction.prototype.run = function (_accessor, _editor) { }; return FoldingAction; }(editorExtensions_1.EditorAction)); function foldingArgumentsConstraint(args) { if (!types.isUndefined(args)) { if (!types.isObject(args)) { return false; } var foldingArgs = args; if (!types.isUndefined(foldingArgs.levels) && !types.isNumber(foldingArgs.levels)) { return false; } if (!types.isUndefined(foldingArgs.direction) && !types.isString(foldingArgs.direction)) { return false; } if (!types.isUndefined(foldingArgs.selectionLines) && (!types.isArray(foldingArgs.selectionLines) || !foldingArgs.selectionLines.every(types.isNumber))) { return false; } } return true; } var UnfoldAction = /** @class */ (function (_super) { __extends(UnfoldAction, _super); function UnfoldAction() { return _super.call(this, { id: 'editor.unfold', label: nls.localize(0, null), alias: 'Unfold', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 89 /* US_CLOSE_SQUARE_BRACKET */, mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 89 /* US_CLOSE_SQUARE_BRACKET */ }, weight: 100 /* EditorContrib */ }, description: { description: 'Unfold the content in the editor', args: [ { name: 'Unfold editor argument', description: "Property-value pairs that can be passed through this argument:\n\t\t\t\t\t\t* 'levels': Number of levels to unfold. If not set, defaults to 1.\n\t\t\t\t\t\t* 'direction': If 'up', unfold given number of levels up otherwise unfolds down.\n\t\t\t\t\t\t* 'selectionLines': The start lines (0-based) of the editor selections to apply the unfold action to. If not set, the active selection(s) will be used.\n\t\t\t\t\t\t", constraint: foldingArgumentsConstraint, schema: { 'type': 'object', 'properties': { 'levels': { 'type': 'number', 'default': 1 }, 'direction': { 'type': 'string', 'enum': ['up', 'down'], 'default': 'down' }, 'selectionLines': { 'type': 'array', 'items': { 'type': 'number' } } } } } ] } }) || this; } UnfoldAction.prototype.invoke = function (_foldingController, foldingModel, editor, args) { var levels = args && args.levels || 1; var lineNumbers = this.getLineNumbers(args, editor); if (args && args.direction === 'up') { foldingModel_1.setCollapseStateLevelsUp(foldingModel, false, levels, lineNumbers); } else { foldingModel_1.setCollapseStateLevelsDown(foldingModel, false, levels, lineNumbers); } }; return UnfoldAction; }(FoldingAction)); var UnFoldRecursivelyAction = /** @class */ (function (_super) { __extends(UnFoldRecursivelyAction, _super); function UnFoldRecursivelyAction() { return _super.call(this, { id: 'editor.unfoldRecursively', label: nls.localize(1, null), alias: 'Unfold Recursively', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 89 /* US_CLOSE_SQUARE_BRACKET */), weight: 100 /* EditorContrib */ } }) || this; } UnFoldRecursivelyAction.prototype.invoke = function (_foldingController, foldingModel, editor, _args) { foldingModel_1.setCollapseStateLevelsDown(foldingModel, false, Number.MAX_VALUE, this.getSelectedLines(editor)); }; return UnFoldRecursivelyAction; }(FoldingAction)); var FoldAction = /** @class */ (function (_super) { __extends(FoldAction, _super); function FoldAction() { return _super.call(this, { id: 'editor.fold', label: nls.localize(2, null), alias: 'Fold', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 87 /* US_OPEN_SQUARE_BRACKET */, mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 87 /* US_OPEN_SQUARE_BRACKET */ }, weight: 100 /* EditorContrib */ }, description: { description: 'Fold the content in the editor', args: [ { name: 'Fold editor argument', description: "Property-value pairs that can be passed through this argument:\n\t\t\t\t\t\t\t* 'levels': Number of levels to fold.\n\t\t\t\t\t\t\t* 'direction': If 'up', folds given number of levels up otherwise folds down.\n\t\t\t\t\t\t\t* 'selectionLines': The start lines (0-based) of the editor selections to apply the fold action to. If not set, the active selection(s) will be used.\n\t\t\t\t\t\t\tIf no levels or direction is set, folds the region at the locations or if already collapsed, the first uncollapsed parent instead.\n\t\t\t\t\t\t", constraint: foldingArgumentsConstraint, schema: { 'type': 'object', 'properties': { 'levels': { 'type': 'number', }, 'direction': { 'type': 'string', 'enum': ['up', 'down'], }, 'selectionLines': { 'type': 'array', 'items': { 'type': 'number' } } } } } ] } }) || this; } FoldAction.prototype.invoke = function (_foldingController, foldingModel, editor, args) { var lineNumbers = this.getLineNumbers(args, editor); var levels = args && args.levels; var direction = args && args.direction; if (typeof levels !== 'number' && typeof direction !== 'string') { // fold the region at the location or if already collapsed, the first uncollapsed parent instead. foldingModel_1.setCollapseStateUp(foldingModel, true, lineNumbers); } else { if (direction === 'up') { foldingModel_1.setCollapseStateLevelsUp(foldingModel, true, levels || 1, lineNumbers); } else { foldingModel_1.setCollapseStateLevelsDown(foldingModel, true, levels || 1, lineNumbers); } } }; return FoldAction; }(FoldingAction)); var ToggleFoldAction = /** @class */ (function (_super) { __extends(ToggleFoldAction, _super); function ToggleFoldAction() { return _super.call(this, { id: 'editor.toggleFold', label: nls.localize(3, null), alias: 'Toggle Fold', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 42 /* KEY_L */), weight: 100 /* EditorContrib */ } }) || this; } ToggleFoldAction.prototype.invoke = function (_foldingController, foldingModel, editor) { var selectedLines = this.getSelectedLines(editor); foldingModel_1.toggleCollapseState(foldingModel, 1, selectedLines); }; return ToggleFoldAction; }(FoldingAction)); var FoldRecursivelyAction = /** @class */ (function (_super) { __extends(FoldRecursivelyAction, _super); function FoldRecursivelyAction() { return _super.call(this, { id: 'editor.foldRecursively', label: nls.localize(4, null), alias: 'Fold Recursively', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 87 /* US_OPEN_SQUARE_BRACKET */), weight: 100 /* EditorContrib */ } }) || this; } FoldRecursivelyAction.prototype.invoke = function (_foldingController, foldingModel, editor) { var selectedLines = this.getSelectedLines(editor); foldingModel_1.setCollapseStateLevelsDown(foldingModel, true, Number.MAX_VALUE, selectedLines); }; return FoldRecursivelyAction; }(FoldingAction)); var FoldAllBlockCommentsAction = /** @class */ (function (_super) { __extends(FoldAllBlockCommentsAction, _super); function FoldAllBlockCommentsAction() { return _super.call(this, { id: 'editor.foldAllBlockComments', label: nls.localize(5, null), alias: 'Fold All Block Comments', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 85 /* US_SLASH */), weight: 100 /* EditorContrib */ } }) || this; } FoldAllBlockCommentsAction.prototype.invoke = function (_foldingController, foldingModel, editor) { if (foldingModel.regions.hasTypes()) { foldingModel_1.setCollapseStateForType(foldingModel, modes_1.FoldingRangeKind.Comment.value, true); } else { var editorModel = editor.getModel(); if (!editorModel) { return; } var comments = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getComments(editorModel.getLanguageIdentifier().id); if (comments && comments.blockCommentStartToken) { var regExp = new RegExp('^\\s*' + strings_1.escapeRegExpCharacters(comments.blockCommentStartToken)); foldingModel_1.setCollapseStateForMatchingLines(foldingModel, regExp, true); } } }; return FoldAllBlockCommentsAction; }(FoldingAction)); var FoldAllRegionsAction = /** @class */ (function (_super) { __extends(FoldAllRegionsAction, _super); function FoldAllRegionsAction() { return _super.call(this, { id: 'editor.foldAllMarkerRegions', label: nls.localize(6, null), alias: 'Fold All Regions', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 29 /* KEY_8 */), weight: 100 /* EditorContrib */ } }) || this; } FoldAllRegionsAction.prototype.invoke = function (_foldingController, foldingModel, editor) { if (foldingModel.regions.hasTypes()) { foldingModel_1.setCollapseStateForType(foldingModel, modes_1.FoldingRangeKind.Region.value, true); } else { var editorModel = editor.getModel(); if (!editorModel) { return; } var foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(editorModel.getLanguageIdentifier().id); if (foldingRules && foldingRules.markers && foldingRules.markers.start) { var regExp = new RegExp(foldingRules.markers.start); foldingModel_1.setCollapseStateForMatchingLines(foldingModel, regExp, true); } } }; return FoldAllRegionsAction; }(FoldingAction)); var UnfoldAllRegionsAction = /** @class */ (function (_super) { __extends(UnfoldAllRegionsAction, _super); function UnfoldAllRegionsAction() { return _super.call(this, { id: 'editor.unfoldAllMarkerRegions', label: nls.localize(7, null), alias: 'Unfold All Regions', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 30 /* KEY_9 */), weight: 100 /* EditorContrib */ } }) || this; } UnfoldAllRegionsAction.prototype.invoke = function (_foldingController, foldingModel, editor) { if (foldingModel.regions.hasTypes()) { foldingModel_1.setCollapseStateForType(foldingModel, modes_1.FoldingRangeKind.Region.value, false); } else { var editorModel = editor.getModel(); if (!editorModel) { return; } var foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(editorModel.getLanguageIdentifier().id); if (foldingRules && foldingRules.markers && foldingRules.markers.start) { var regExp = new RegExp(foldingRules.markers.start); foldingModel_1.setCollapseStateForMatchingLines(foldingModel, regExp, false); } } }; return UnfoldAllRegionsAction; }(FoldingAction)); var FoldAllAction = /** @class */ (function (_super) { __extends(FoldAllAction, _super); function FoldAllAction() { return _super.call(this, { id: 'editor.foldAll', label: nls.localize(8, null), alias: 'Fold All', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 21 /* KEY_0 */), weight: 100 /* EditorContrib */ } }) || this; } FoldAllAction.prototype.invoke = function (_foldingController, foldingModel, _editor) { foldingModel_1.setCollapseStateLevelsDown(foldingModel, true); }; return FoldAllAction; }(FoldingAction)); var UnfoldAllAction = /** @class */ (function (_super) { __extends(UnfoldAllAction, _super); function UnfoldAllAction() { return _super.call(this, { id: 'editor.unfoldAll', label: nls.localize(9, null), alias: 'Unfold All', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 40 /* KEY_J */), weight: 100 /* EditorContrib */ } }) || this; } UnfoldAllAction.prototype.invoke = function (_foldingController, foldingModel, _editor) { foldingModel_1.setCollapseStateLevelsDown(foldingModel, false); }; return UnfoldAllAction; }(FoldingAction)); var FoldLevelAction = /** @class */ (function (_super) { __extends(FoldLevelAction, _super); function FoldLevelAction() { return _super !== null && _super.apply(this, arguments) || this; } FoldLevelAction.prototype.getFoldingLevel = function () { return parseInt(this.id.substr(FoldLevelAction.ID_PREFIX.length)); }; FoldLevelAction.prototype.invoke = function (_foldingController, foldingModel, editor) { foldingModel_1.setCollapseStateAtLevel(foldingModel, this.getFoldingLevel(), true, this.getSelectedLines(editor)); }; FoldLevelAction.ID_PREFIX = 'editor.foldLevel'; FoldLevelAction.ID = function (level) { return FoldLevelAction.ID_PREFIX + level; }; return FoldLevelAction; }(FoldingAction)); editorExtensions_1.registerEditorContribution(FoldingController.ID, FoldingController); editorExtensions_1.registerEditorAction(UnfoldAction); editorExtensions_1.registerEditorAction(UnFoldRecursivelyAction); editorExtensions_1.registerEditorAction(FoldAction); editorExtensions_1.registerEditorAction(FoldRecursivelyAction); editorExtensions_1.registerEditorAction(FoldAllAction); editorExtensions_1.registerEditorAction(UnfoldAllAction); editorExtensions_1.registerEditorAction(FoldAllBlockCommentsAction); editorExtensions_1.registerEditorAction(FoldAllRegionsAction); editorExtensions_1.registerEditorAction(UnfoldAllRegionsAction); editorExtensions_1.registerEditorAction(ToggleFoldAction); for (var i = 1; i <= 7; i++) { editorExtensions_1.registerInstantiatedEditorAction(new FoldLevelAction({ id: FoldLevelAction.ID(i), label: nls.localize(10, null, i), alias: "Fold Level " + i, precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | (21 /* KEY_0 */ + i)), weight: 100 /* EditorContrib */ } })); } exports.foldBackgroundBackground = colorRegistry_1.registerColor('editor.foldBackground', { light: colorRegistry_1.transparent(colorRegistry_1.editorSelectionBackground, 0.3), dark: colorRegistry_1.transparent(colorRegistry_1.editorSelectionBackground, 0.3), hc: null }, nls.localize(11, null)); themeService_1.registerThemingParticipant(function (theme, collector) { var foldBackground = theme.getColor(exports.foldBackgroundBackground); if (foldBackground) { collector.addRule(".monaco-editor .folded-background { background-color: " + foldBackground + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[575/*vs/editor/contrib/gotoSymbol/peek/referencesTree*/], __M([0/*require*/,1/*exports*/,113/*vs/editor/contrib/gotoSymbol/referencesModel*/,84/*vs/editor/common/services/resolverService*/,139/*vs/base/browser/ui/iconLabel/iconLabel*/,267/*vs/base/browser/ui/countBadge/countBadge*/,116/*vs/platform/label/common/label*/,14/*vs/platform/theme/common/themeService*/,97/*vs/platform/theme/common/styler*/,6/*vs/base/browser/dom*/,449/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesTree*/,136/*vs/base/common/labels*/,39/*vs/base/common/resources*/,2/*vs/base/common/lifecycle*/,11/*vs/platform/instantiation/common/instantiation*/,34/*vs/platform/keybinding/common/keybinding*/,61/*vs/base/common/filters*/,133/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/]), function (require, exports, referencesModel_1, resolverService_1, iconLabel_1, countBadge_1, label_1, themeService_1, styler_1, dom, nls_1, labels_1, resources_1, lifecycle_1, instantiation_1, keybinding_1, filters_1, highlightedLabel_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DataSource = /** @class */ (function () { function DataSource(_resolverService) { this._resolverService = _resolverService; } DataSource.prototype.hasChildren = function (element) { if (element instanceof referencesModel_1.ReferencesModel) { return true; } if (element instanceof referencesModel_1.FileReferences && !element.failure) { return true; } return false; }; DataSource.prototype.getChildren = function (element) { if (element instanceof referencesModel_1.ReferencesModel) { return element.groups; } if (element instanceof referencesModel_1.FileReferences) { return element.resolve(this._resolverService).then(function (val) { // if (element.failure) { // // refresh the element on failure so that // // we can update its rendering // return tree.refresh(element).then(() => val.children); // } return val.children; }); } throw new Error('bad tree'); }; DataSource = __decorate([ __param(0, resolverService_1.ITextModelService) ], DataSource); return DataSource; }()); exports.DataSource = DataSource; //#endregion var Delegate = /** @class */ (function () { function Delegate() { } Delegate.prototype.getHeight = function () { return 23; }; Delegate.prototype.getTemplateId = function (element) { if (element instanceof referencesModel_1.FileReferences) { return FileReferencesRenderer.id; } else { return OneReferenceRenderer.id; } }; return Delegate; }()); exports.Delegate = Delegate; var StringRepresentationProvider = /** @class */ (function () { function StringRepresentationProvider(_keybindingService) { this._keybindingService = _keybindingService; } StringRepresentationProvider.prototype.getKeyboardNavigationLabel = function (element) { if (element instanceof referencesModel_1.OneReference) { var preview = element.parent.preview; var parts = preview && preview.preview(element.range); if (parts) { return parts.value; } } // FileReferences or unresolved OneReference return resources_1.basename(element.uri); }; StringRepresentationProvider = __decorate([ __param(0, keybinding_1.IKeybindingService) ], StringRepresentationProvider); return StringRepresentationProvider; }()); exports.StringRepresentationProvider = StringRepresentationProvider; var IdentityProvider = /** @class */ (function () { function IdentityProvider() { } IdentityProvider.prototype.getId = function (element) { return element instanceof referencesModel_1.OneReference ? element.id : element.uri; }; return IdentityProvider; }()); exports.IdentityProvider = IdentityProvider; //#region render: File var FileReferencesTemplate = /** @class */ (function (_super) { __extends(FileReferencesTemplate, _super); function FileReferencesTemplate(container, _uriLabel, themeService) { var _this = _super.call(this) || this; _this._uriLabel = _uriLabel; var parent = document.createElement('div'); dom.addClass(parent, 'reference-file'); _this.file = _this._register(new iconLabel_1.IconLabel(parent, { supportHighlights: true })); _this.badge = new countBadge_1.CountBadge(dom.append(parent, dom.$('.count'))); _this._register(styler_1.attachBadgeStyler(_this.badge, themeService)); container.appendChild(parent); return _this; } FileReferencesTemplate.prototype.set = function (element, matches) { var parent = resources_1.dirname(element.uri); this.file.setLabel(labels_1.getBaseLabel(element.uri), this._uriLabel.getUriLabel(parent, { relative: true }), { title: this._uriLabel.getUriLabel(element.uri), matches: matches }); var len = element.children.length; this.badge.setCount(len); if (element.failure) { this.badge.setTitleFormat(nls_1.localize(0, null)); } else if (len > 1) { this.badge.setTitleFormat(nls_1.localize(1, null, len)); } else { this.badge.setTitleFormat(nls_1.localize(2, null, len)); } }; FileReferencesTemplate = __decorate([ __param(1, label_1.ILabelService), __param(2, themeService_1.IThemeService) ], FileReferencesTemplate); return FileReferencesTemplate; }(lifecycle_1.Disposable)); var FileReferencesRenderer = /** @class */ (function () { function FileReferencesRenderer(_instantiationService) { this._instantiationService = _instantiationService; this.templateId = FileReferencesRenderer.id; } FileReferencesRenderer.prototype.renderTemplate = function (container) { return this._instantiationService.createInstance(FileReferencesTemplate, container); }; FileReferencesRenderer.prototype.renderElement = function (node, index, template) { template.set(node.element, filters_1.createMatches(node.filterData)); }; FileReferencesRenderer.prototype.disposeTemplate = function (templateData) { templateData.dispose(); }; FileReferencesRenderer.id = 'FileReferencesRenderer'; FileReferencesRenderer = __decorate([ __param(0, instantiation_1.IInstantiationService) ], FileReferencesRenderer); return FileReferencesRenderer; }()); exports.FileReferencesRenderer = FileReferencesRenderer; //#endregion //#region render: Reference var OneReferenceTemplate = /** @class */ (function () { function OneReferenceTemplate(container) { this.label = new highlightedLabel_1.HighlightedLabel(container, false); } OneReferenceTemplate.prototype.set = function (element, score) { var filePreview = element.parent.preview; var preview = filePreview && filePreview.preview(element.range); if (!preview) { // this means we FAILED to resolve the document... this.label.set(resources_1.basename(element.uri) + ":" + (element.range.startLineNumber + 1) + ":" + (element.range.startColumn + 1)); } else { // render search match as highlight unless // we have score, then render the score var value = preview.value, highlight = preview.highlight; if (score && !filters_1.FuzzyScore.isDefault(score)) { dom.toggleClass(this.label.element, 'referenceMatch', false); this.label.set(value, filters_1.createMatches(score)); } else { dom.toggleClass(this.label.element, 'referenceMatch', true); this.label.set(value, [highlight]); } } }; return OneReferenceTemplate; }()); var OneReferenceRenderer = /** @class */ (function () { function OneReferenceRenderer() { this.templateId = OneReferenceRenderer.id; } OneReferenceRenderer.prototype.renderTemplate = function (container) { return new OneReferenceTemplate(container); }; OneReferenceRenderer.prototype.renderElement = function (node, index, templateData) { templateData.set(node.element, node.filterData); }; OneReferenceRenderer.prototype.disposeTemplate = function () { }; OneReferenceRenderer.id = 'OneReferenceRenderer'; return OneReferenceRenderer; }()); exports.OneReferenceRenderer = OneReferenceRenderer; //#endregion var AriaProvider = /** @class */ (function () { function AriaProvider() { } AriaProvider.prototype.getAriaLabel = function (element) { return element.ariaMessage; }; return AriaProvider; }()); exports.AriaProvider = AriaProvider; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[576/*vs/editor/contrib/inPlaceReplace/inPlaceReplace*/], __M([0/*require*/,1/*exports*/,455/*vs/nls!vs/editor/contrib/inPlaceReplace/inPlaceReplace*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,23/*vs/editor/common/editorContextKeys*/,12/*vs/editor/browser/editorExtensions*/,62/*vs/editor/common/services/editorWorkerService*/,384/*vs/editor/contrib/inPlaceReplace/inPlaceReplaceCommand*/,67/*vs/editor/browser/core/editorState*/,14/*vs/platform/theme/common/themeService*/,44/*vs/editor/common/view/editorColorRegistry*/,30/*vs/editor/common/model/textModel*/,15/*vs/base/common/async*/,10/*vs/base/common/errors*/]), function (require, exports, nls, range_1, selection_1, editorContextKeys_1, editorExtensions_1, editorWorkerService_1, inPlaceReplaceCommand_1, editorState_1, themeService_1, editorColorRegistry_1, textModel_1, async_1, errors_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var InPlaceReplaceController = /** @class */ (function () { function InPlaceReplaceController(editor, editorWorkerService) { this.decorationIds = []; this.editor = editor; this.editorWorkerService = editorWorkerService; } InPlaceReplaceController.get = function (editor) { return editor.getContribution(InPlaceReplaceController.ID); }; InPlaceReplaceController.prototype.dispose = function () { }; InPlaceReplaceController.prototype.run = function (source, up) { var _this = this; // cancel any pending request if (this.currentRequest) { this.currentRequest.cancel(); } var editorSelection = this.editor.getSelection(); var model = this.editor.getModel(); if (!model || !editorSelection) { return undefined; } var selection = editorSelection; if (selection.startLineNumber !== selection.endLineNumber) { // Can't accept multiline selection return undefined; } var state = new editorState_1.EditorState(this.editor, 1 /* Value */ | 4 /* Position */); var modelURI = model.uri; if (!this.editorWorkerService.canNavigateValueSet(modelURI)) { return Promise.resolve(undefined); } this.currentRequest = async_1.createCancelablePromise(function (token) { return _this.editorWorkerService.navigateValueSet(modelURI, selection, up); }); return this.currentRequest.then(function (result) { if (!result || !result.range || !result.value) { // No proper result return; } if (!state.validate(_this.editor)) { // state has changed return; } // Selection var editRange = range_1.Range.lift(result.range); var highlightRange = result.range; var diff = result.value.length - (selection.endColumn - selection.startColumn); // highlight highlightRange = { startLineNumber: highlightRange.startLineNumber, startColumn: highlightRange.startColumn, endLineNumber: highlightRange.endLineNumber, endColumn: highlightRange.startColumn + result.value.length }; if (diff > 1) { selection = new selection_1.Selection(selection.startLineNumber, selection.startColumn, selection.endLineNumber, selection.endColumn + diff - 1); } // Insert new text var command = new inPlaceReplaceCommand_1.InPlaceReplaceCommand(editRange, selection, result.value); _this.editor.pushUndoStop(); _this.editor.executeCommand(source, command); _this.editor.pushUndoStop(); // add decoration _this.decorationIds = _this.editor.deltaDecorations(_this.decorationIds, [{ range: highlightRange, options: InPlaceReplaceController.DECORATION }]); // remove decoration after delay if (_this.decorationRemover) { _this.decorationRemover.cancel(); } _this.decorationRemover = async_1.timeout(350); _this.decorationRemover.then(function () { return _this.decorationIds = _this.editor.deltaDecorations(_this.decorationIds, []); }).catch(errors_1.onUnexpectedError); }).catch(errors_1.onUnexpectedError); }; InPlaceReplaceController.ID = 'editor.contrib.inPlaceReplaceController'; InPlaceReplaceController.DECORATION = textModel_1.ModelDecorationOptions.register({ className: 'valueSetReplacement' }); InPlaceReplaceController = __decorate([ __param(1, editorWorkerService_1.IEditorWorkerService) ], InPlaceReplaceController); return InPlaceReplaceController; }()); var InPlaceReplaceUp = /** @class */ (function (_super) { __extends(InPlaceReplaceUp, _super); function InPlaceReplaceUp() { return _super.call(this, { id: 'editor.action.inPlaceReplace.up', label: nls.localize(0, null), alias: 'Replace with Previous Value', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 82 /* US_COMMA */, weight: 100 /* EditorContrib */ } }) || this; } InPlaceReplaceUp.prototype.run = function (accessor, editor) { var controller = InPlaceReplaceController.get(editor); if (!controller) { return Promise.resolve(undefined); } return controller.run(this.id, true); }; return InPlaceReplaceUp; }(editorExtensions_1.EditorAction)); var InPlaceReplaceDown = /** @class */ (function (_super) { __extends(InPlaceReplaceDown, _super); function InPlaceReplaceDown() { return _super.call(this, { id: 'editor.action.inPlaceReplace.down', label: nls.localize(1, null), alias: 'Replace with Next Value', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 84 /* US_DOT */, weight: 100 /* EditorContrib */ } }) || this; } InPlaceReplaceDown.prototype.run = function (accessor, editor) { var controller = InPlaceReplaceController.get(editor); if (!controller) { return Promise.resolve(undefined); } return controller.run(this.id, false); }; return InPlaceReplaceDown; }(editorExtensions_1.EditorAction)); editorExtensions_1.registerEditorContribution(InPlaceReplaceController.ID, InPlaceReplaceController); editorExtensions_1.registerEditorAction(InPlaceReplaceUp); editorExtensions_1.registerEditorAction(InPlaceReplaceDown); themeService_1.registerThemingParticipant(function (theme, collector) { var border = theme.getColor(editorColorRegistry_1.editorBracketMatchBorder); if (border) { collector.addRule(".monaco-editor.vs .valueSetReplacement { outline: solid 2px " + border + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[577/*vs/editor/contrib/links/links*/], __M([0/*require*/,1/*exports*/,457/*vs/nls!vs/editor/contrib/links/links*/,15/*vs/base/common/async*/,26/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,75/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,12/*vs/editor/browser/editorExtensions*/,30/*vs/editor/common/model/textModel*/,17/*vs/editor/common/modes*/,199/*vs/editor/contrib/gotoSymbol/link/clickLinkGesture*/,495/*vs/editor/contrib/links/getLinks*/,35/*vs/platform/notification/common/notification*/,51/*vs/platform/opener/common/opener*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,316/*vs/css!vs/editor/contrib/links/links*/]), function (require, exports, nls, async, cancellation_1, errors_1, htmlContent_1, lifecycle_1, platform, editorExtensions_1, textModel_1, modes_1, clickLinkGesture_1, getLinks_1, notification_1, opener_1, colorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function getHoverMessage(link, useMetaKey) { var executeCmd = link.url && /^command:/i.test(link.url.toString()); var label = link.tooltip ? link.tooltip : executeCmd ? nls.localize(0, null) : nls.localize(1, null); var kb = useMetaKey ? platform.isMacintosh ? nls.localize(2, null) : nls.localize(3, null) : platform.isMacintosh ? nls.localize(4, null) : nls.localize(5, null); if (link.url) { var hoverMessage = new htmlContent_1.MarkdownString('', true).appendMarkdown("[" + label + "](" + link.url.toString() + ") (" + kb + ")"); return hoverMessage; } else { return new htmlContent_1.MarkdownString().appendText(label + " (" + kb + ")"); } } var decoration = { general: textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, collapseOnReplaceEdit: true, inlineClassName: 'detected-link' }), active: textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, collapseOnReplaceEdit: true, inlineClassName: 'detected-link-active' }) }; var LinkOccurrence = /** @class */ (function () { function LinkOccurrence(link, decorationId) { this.link = link; this.decorationId = decorationId; } LinkOccurrence.decoration = function (link, useMetaKey) { return { range: link.range, options: LinkOccurrence._getOptions(link, useMetaKey, false) }; }; LinkOccurrence._getOptions = function (link, useMetaKey, isActive) { var options = __assign({}, (isActive ? decoration.active : decoration.general)); options.hoverMessage = getHoverMessage(link, useMetaKey); return options; }; LinkOccurrence.prototype.activate = function (changeAccessor, useMetaKey) { changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurrence._getOptions(this.link, useMetaKey, true)); }; LinkOccurrence.prototype.deactivate = function (changeAccessor, useMetaKey) { changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurrence._getOptions(this.link, useMetaKey, false)); }; return LinkOccurrence; }()); var LinkDetector = /** @class */ (function () { function LinkDetector(editor, openerService, notificationService) { var _this = this; this.listenersToRemove = new lifecycle_1.DisposableStore(); this.editor = editor; this.openerService = openerService; this.notificationService = notificationService; var clickLinkGesture = new clickLinkGesture_1.ClickLinkGesture(editor); this.listenersToRemove.add(clickLinkGesture); this.listenersToRemove.add(clickLinkGesture.onMouseMoveOrRelevantKeyDown(function (_a) { var mouseEvent = _a[0], keyboardEvent = _a[1]; _this._onEditorMouseMove(mouseEvent, keyboardEvent); })); this.listenersToRemove.add(clickLinkGesture.onExecute(function (e) { _this.onEditorMouseUp(e); })); this.listenersToRemove.add(clickLinkGesture.onCancel(function (e) { _this.cleanUpActiveLinkDecoration(); })); this.enabled = editor.getOption(52 /* links */); this.listenersToRemove.add(editor.onDidChangeConfiguration(function (e) { var enabled = editor.getOption(52 /* links */); if (_this.enabled === enabled) { // No change in our configuration option return; } _this.enabled = enabled; // Remove any links (for the getting disabled case) _this.updateDecorations([]); // Stop any computation (for the getting disabled case) _this.stop(); // Start computing (for the getting enabled case) _this.beginCompute(); })); this.listenersToRemove.add(editor.onDidChangeModelContent(function (e) { return _this.onChange(); })); this.listenersToRemove.add(editor.onDidChangeModel(function (e) { return _this.onModelChanged(); })); this.listenersToRemove.add(editor.onDidChangeModelLanguage(function (e) { return _this.onModelModeChanged(); })); this.listenersToRemove.add(modes_1.LinkProviderRegistry.onDidChange(function (e) { return _this.onModelModeChanged(); })); this.timeout = new async.TimeoutTimer(); this.computePromise = null; this.activeLinksList = null; this.currentOccurrences = {}; this.activeLinkDecorationId = null; this.beginCompute(); } LinkDetector.get = function (editor) { return editor.getContribution(LinkDetector.ID); }; LinkDetector.prototype.onModelChanged = function () { this.currentOccurrences = {}; this.activeLinkDecorationId = null; this.stop(); this.beginCompute(); }; LinkDetector.prototype.onModelModeChanged = function () { this.stop(); this.beginCompute(); }; LinkDetector.prototype.onChange = function () { var _this = this; this.timeout.setIfNotSet(function () { return _this.beginCompute(); }, LinkDetector.RECOMPUTE_TIME); }; LinkDetector.prototype.beginCompute = function () { return __awaiter(this, void 0, void 0, function () { var model, _a, err_1; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!this.editor.hasModel() || !this.enabled) { return [2 /*return*/]; } model = this.editor.getModel(); if (!modes_1.LinkProviderRegistry.has(model)) { return [2 /*return*/]; } if (this.activeLinksList) { this.activeLinksList.dispose(); this.activeLinksList = null; } this.computePromise = async.createCancelablePromise(function (token) { return getLinks_1.getLinks(model, token); }); _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); _a = this; return [4 /*yield*/, this.computePromise]; case 2: _a.activeLinksList = _b.sent(); this.updateDecorations(this.activeLinksList.links); return [3 /*break*/, 5]; case 3: err_1 = _b.sent(); errors_1.onUnexpectedError(err_1); return [3 /*break*/, 5]; case 4: this.computePromise = null; return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; LinkDetector.prototype.updateDecorations = function (links) { var useMetaKey = (this.editor.getOption(59 /* multiCursorModifier */) === 'altKey'); var oldDecorations = []; var keys = Object.keys(this.currentOccurrences); for (var i = 0, len = keys.length; i < len; i++) { var decorationId = keys[i]; var occurance = this.currentOccurrences[decorationId]; oldDecorations.push(occurance.decorationId); } var newDecorations = []; if (links) { // Not sure why this is sometimes null for (var _i = 0, links_1 = links; _i < links_1.length; _i++) { var link = links_1[_i]; newDecorations.push(LinkOccurrence.decoration(link, useMetaKey)); } } var decorations = this.editor.deltaDecorations(oldDecorations, newDecorations); this.currentOccurrences = {}; this.activeLinkDecorationId = null; for (var i = 0, len = decorations.length; i < len; i++) { var occurance = new LinkOccurrence(links[i], decorations[i]); this.currentOccurrences[occurance.decorationId] = occurance; } }; LinkDetector.prototype._onEditorMouseMove = function (mouseEvent, withKey) { var _this = this; var useMetaKey = (this.editor.getOption(59 /* multiCursorModifier */) === 'altKey'); if (this.isEnabled(mouseEvent, withKey)) { this.cleanUpActiveLinkDecoration(); // always remove previous link decoration as their can only be one var occurrence_1 = this.getLinkOccurrence(mouseEvent.target.position); if (occurrence_1) { this.editor.changeDecorations(function (changeAccessor) { occurrence_1.activate(changeAccessor, useMetaKey); _this.activeLinkDecorationId = occurrence_1.decorationId; }); } } else { this.cleanUpActiveLinkDecoration(); } }; LinkDetector.prototype.cleanUpActiveLinkDecoration = function () { var useMetaKey = (this.editor.getOption(59 /* multiCursorModifier */) === 'altKey'); if (this.activeLinkDecorationId) { var occurrence_2 = this.currentOccurrences[this.activeLinkDecorationId]; if (occurrence_2) { this.editor.changeDecorations(function (changeAccessor) { occurrence_2.deactivate(changeAccessor, useMetaKey); }); } this.activeLinkDecorationId = null; } }; LinkDetector.prototype.onEditorMouseUp = function (mouseEvent) { if (!this.isEnabled(mouseEvent)) { return; } var occurrence = this.getLinkOccurrence(mouseEvent.target.position); if (!occurrence) { return; } this.openLinkOccurrence(occurrence, mouseEvent.hasSideBySideModifier, true /* from user gesture */); }; LinkDetector.prototype.openLinkOccurrence = function (occurrence, openToSide, fromUserGesture) { var _this = this; if (fromUserGesture === void 0) { fromUserGesture = false; } if (!this.openerService) { return; } var link = occurrence.link; link.resolve(cancellation_1.CancellationToken.None).then(function (uri) { // open the uri return _this.openerService.open(uri, { openToSide: openToSide, fromUserGesture: fromUserGesture }); }, function (err) { var messageOrError = err instanceof Error ? err.message : err; // different error cases if (messageOrError === 'invalid') { _this.notificationService.warn(nls.localize(6, null, link.url.toString())); } else if (messageOrError === 'missing') { _this.notificationService.warn(nls.localize(7, null)); } else { errors_1.onUnexpectedError(err); } }); }; LinkDetector.prototype.getLinkOccurrence = function (position) { if (!this.editor.hasModel() || !position) { return null; } var decorations = this.editor.getModel().getDecorationsInRange({ startLineNumber: position.lineNumber, startColumn: position.column, endLineNumber: position.lineNumber, endColumn: position.column }, 0, true); for (var _i = 0, decorations_1 = decorations; _i < decorations_1.length; _i++) { var decoration_1 = decorations_1[_i]; var currentOccurrence = this.currentOccurrences[decoration_1.id]; if (currentOccurrence) { return currentOccurrence; } } return null; }; LinkDetector.prototype.isEnabled = function (mouseEvent, withKey) { return Boolean((mouseEvent.target.type === 6 /* CONTENT_TEXT */) && (mouseEvent.hasTriggerModifier || (withKey && withKey.keyCodeIsTriggerKey))); }; LinkDetector.prototype.stop = function () { this.timeout.cancel(); if (this.activeLinksList) { this.activeLinksList.dispose(); } if (this.computePromise) { this.computePromise.cancel(); this.computePromise = null; } }; LinkDetector.prototype.dispose = function () { this.listenersToRemove.dispose(); this.stop(); this.timeout.dispose(); }; LinkDetector.ID = 'editor.linkDetector'; LinkDetector.RECOMPUTE_TIME = 1000; // ms LinkDetector = __decorate([ __param(1, opener_1.IOpenerService), __param(2, notification_1.INotificationService) ], LinkDetector); return LinkDetector; }()); var OpenLinkAction = /** @class */ (function (_super) { __extends(OpenLinkAction, _super); function OpenLinkAction() { return _super.call(this, { id: 'editor.action.openLink', label: nls.localize(8, null), alias: 'Open Link', precondition: undefined }) || this; } OpenLinkAction.prototype.run = function (accessor, editor) { var linkDetector = LinkDetector.get(editor); if (!linkDetector) { return; } if (!editor.hasModel()) { return; } var selections = editor.getSelections(); for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) { var sel = selections_1[_i]; var link = linkDetector.getLinkOccurrence(sel.getEndPosition()); if (link) { linkDetector.openLinkOccurrence(link, false); } } }; return OpenLinkAction; }(editorExtensions_1.EditorAction)); editorExtensions_1.registerEditorContribution(LinkDetector.ID, LinkDetector); editorExtensions_1.registerEditorAction(OpenLinkAction); themeService_1.registerThemingParticipant(function (theme, collector) { var activeLinkForeground = theme.getColor(colorRegistry_1.editorActiveLinkForeground); if (activeLinkForeground) { collector.addRule(".monaco-editor .detected-link-active { color: " + activeLinkForeground + " !important; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[122/*vs/editor/contrib/message/messageController*/], __M([0/*require*/,1/*exports*/,458/*vs/nls!vs/editor/contrib/message/messageController*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,50/*vs/base/browser/ui/aria/aria*/,3/*vs/editor/common/core/range*/,12/*vs/editor/browser/editorExtensions*/,18/*vs/platform/contextkey/common/contextkey*/,14/*vs/platform/theme/common/themeService*/,20/*vs/platform/theme/common/colorRegistry*/,317/*vs/css!vs/editor/contrib/message/messageController*/]), function (require, exports, nls, async_1, lifecycle_1, aria_1, range_1, editorExtensions_1, contextkey_1, themeService_1, colorRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MessageController = /** @class */ (function (_super) { __extends(MessageController, _super); function MessageController(editor, contextKeyService) { var _this = _super.call(this) || this; _this.closeTimeout = 3000; // close after 3s _this._messageWidget = _this._register(new lifecycle_1.MutableDisposable()); _this._messageListeners = _this._register(new lifecycle_1.DisposableStore()); _this._editor = editor; _this._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService); _this._register(_this._editor.onDidAttemptReadOnlyEdit(function () { return _this._onDidAttemptReadOnlyEdit(); })); return _this; } MessageController.get = function (editor) { return editor.getContribution(MessageController.ID); }; MessageController.prototype.dispose = function () { _super.prototype.dispose.call(this); this._visible.reset(); }; MessageController.prototype.showMessage = function (message, position) { var _this = this; aria_1.alert(message); this._visible.set(true); this._messageWidget.clear(); this._messageListeners.clear(); this._messageWidget.value = new MessageWidget(this._editor, position, message); // close on blur, cursor, model change, dispose this._messageListeners.add(this._editor.onDidBlurEditorText(function () { return _this.closeMessage(); })); this._messageListeners.add(this._editor.onDidChangeCursorPosition(function () { return _this.closeMessage(); })); this._messageListeners.add(this._editor.onDidDispose(function () { return _this.closeMessage(); })); this._messageListeners.add(this._editor.onDidChangeModel(function () { return _this.closeMessage(); })); this._messageListeners.add(new async_1.TimeoutTimer(function () { return _this.closeMessage(); }, this.closeTimeout)); // close on mouse move var bounds; this._messageListeners.add(this._editor.onMouseMove(function (e) { // outside the text area if (!e.target.position) { return; } if (!bounds) { // define bounding box around position and first mouse occurance bounds = new range_1.Range(position.lineNumber - 3, 1, e.target.position.lineNumber + 3, 1); } else if (!bounds.containsPosition(e.target.position)) { // check if position is still in bounds _this.closeMessage(); } })); }; MessageController.prototype.closeMessage = function () { this._visible.reset(); this._messageListeners.clear(); if (this._messageWidget.value) { this._messageListeners.add(MessageWidget.fadeOut(this._messageWidget.value)); } }; MessageController.prototype._onDidAttemptReadOnlyEdit = function () { if (this._editor.hasModel()) { this.showMessage(nls.localize(0, null), this._editor.getPosition()); } }; MessageController.ID = 'editor.contrib.messageController'; MessageController.MESSAGE_VISIBLE = new contextkey_1.RawContextKey('messageVisible', false); MessageController = __decorate([ __param(1, contextkey_1.IContextKeyService) ], MessageController); return MessageController; }(lifecycle_1.Disposable)); exports.MessageController = MessageController; var MessageCommand = editorExtensions_1.EditorCommand.bindToContribution(MessageController.get); editorExtensions_1.registerEditorCommand(new MessageCommand({ id: 'leaveEditorMessage', precondition: MessageController.MESSAGE_VISIBLE, handler: function (c) { return c.closeMessage(); }, kbOpts: { weight: 100 /* EditorContrib */ + 30, primary: 9 /* Escape */ } })); var MessageWidget = /** @class */ (function () { function MessageWidget(editor, _a, text) { var lineNumber = _a.lineNumber, column = _a.column; // Editor.IContentWidget.allowEditorOverflow this.allowEditorOverflow = true; this.suppressMouseDown = false; this._editor = editor; this._editor.revealLinesInCenterIfOutsideViewport(lineNumber, lineNumber, 0 /* Smooth */); this._position = { lineNumber: lineNumber, column: column - 1 }; this._domNode = document.createElement('div'); this._domNode.classList.add('monaco-editor-overlaymessage'); var message = document.createElement('div'); message.classList.add('message'); message.textContent = text; this._domNode.appendChild(message); var anchor = document.createElement('div'); anchor.classList.add('anchor'); this._domNode.appendChild(anchor); this._editor.addContentWidget(this); this._domNode.classList.add('fadeIn'); } MessageWidget.fadeOut = function (messageWidget) { var handle; var dispose = function () { messageWidget.dispose(); clearTimeout(handle); messageWidget.getDomNode().removeEventListener('animationend', dispose); }; handle = setTimeout(dispose, 110); messageWidget.getDomNode().addEventListener('animationend', dispose); messageWidget.getDomNode().classList.add('fadeOut'); return { dispose: dispose }; }; MessageWidget.prototype.dispose = function () { this._editor.removeContentWidget(this); }; MessageWidget.prototype.getId = function () { return 'messageoverlay'; }; MessageWidget.prototype.getDomNode = function () { return this._domNode; }; MessageWidget.prototype.getPosition = function () { return { position: this._position, preference: [1 /* ABOVE */, 2 /* BELOW */] }; }; return MessageWidget; }()); editorExtensions_1.registerEditorContribution(MessageController.ID, MessageController); themeService_1.registerThemingParticipant(function (theme, collector) { var border = theme.getColor(colorRegistry_1.inputValidationInfoBorder); if (border) { var borderWidth = theme.type === themeService_1.HIGH_CONTRAST ? 2 : 1; collector.addRule(".monaco-editor .monaco-editor-overlaymessage .anchor { border-top-color: " + border + "; }"); collector.addRule(".monaco-editor .monaco-editor-overlaymessage .message { border: " + borderWidth + "px solid " + border + "; }"); } var background = theme.getColor(colorRegistry_1.inputValidationInfoBackground); if (background) { collector.addRule(".monaco-editor .monaco-editor-overlaymessage .message { background-color: " + background + "; }"); } var foreground = theme.getColor(colorRegistry_1.inputValidationInfoForeground); if (foreground) { collector.addRule(".monaco-editor .monaco-editor-overlaymessage .message { color: " + foreground + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[578/*vs/editor/contrib/codeAction/codeActionUi*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,10/*vs/base/common/errors*/,128/*vs/base/common/lazy*/,2/*vs/base/common/lifecycle*/,122/*vs/editor/contrib/message/messageController*/,11/*vs/platform/instantiation/common/instantiation*/,527/*vs/editor/contrib/codeAction/codeActionMenu*/,567/*vs/editor/contrib/codeAction/lightBulbWidget*/]), function (require, exports, arrays_1, errors_1, lazy_1, lifecycle_1, messageController_1, instantiation_1, codeActionMenu_1, lightBulbWidget_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CodeActionUi = /** @class */ (function (_super) { __extends(CodeActionUi, _super); function CodeActionUi(_editor, quickFixActionId, preferredFixActionId, delegate, instantiationService) { var _this = _super.call(this) || this; _this._editor = _editor; _this.delegate = delegate; _this._activeCodeActions = _this._register(new lifecycle_1.MutableDisposable()); _this._codeActionWidget = new lazy_1.Lazy(function () { return _this._register(instantiationService.createInstance(codeActionMenu_1.CodeActionMenu, _this._editor, { onSelectCodeAction: function (action) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { this.delegate.applyCodeAction(action, /* retrigger */ true); return [2 /*return*/]; }); }); } })); }); _this._lightBulbWidget = new lazy_1.Lazy(function () { var widget = _this._register(instantiationService.createInstance(lightBulbWidget_1.LightBulbWidget, _this._editor, quickFixActionId, preferredFixActionId)); _this._register(widget.onClick(function (e) { return _this.showCodeActionList(e.trigger, e.actions, e, { includeDisabledActions: false }); })); return widget; }); return _this; } CodeActionUi.prototype.update = function (newState) { var _a, _b, _c; return __awaiter(this, void 0, void 0, function () { var actions, e_1, validActionToApply, invalidAction, includeDisabledActions; return __generator(this, function (_d) { switch (_d.label) { case 0: if (newState.type !== 1 /* Triggered */) { (_a = this._lightBulbWidget.rawValue) === null || _a === void 0 ? void 0 : _a.hide(); return [2 /*return*/]; } _d.label = 1; case 1: _d.trys.push([1, 3, , 4]); return [4 /*yield*/, newState.actions]; case 2: actions = _d.sent(); return [3 /*break*/, 4]; case 3: e_1 = _d.sent(); errors_1.onUnexpectedError(e_1); return [2 /*return*/]; case 4: this._lightBulbWidget.getValue().update(actions, newState.trigger, newState.position); if (!(newState.trigger.type === 2 /* Manual */)) return [3 /*break*/, 11]; if (!((_b = newState.trigger.filter) === null || _b === void 0 ? void 0 : _b.include)) return [3 /*break*/, 10]; validActionToApply = this.tryGetValidActionToApply(newState.trigger, actions); if (!validActionToApply) return [3 /*break*/, 9]; _d.label = 5; case 5: _d.trys.push([5, , 7, 8]); return [4 /*yield*/, this.delegate.applyCodeAction(validActionToApply, false)]; case 6: _d.sent(); return [3 /*break*/, 8]; case 7: actions.dispose(); return [7 /*endfinally*/]; case 8: return [2 /*return*/]; case 9: // Check to see if there is an action that we would have applied were it not invalid if (newState.trigger.context) { invalidAction = this.getInvalidActionThatWouldHaveBeenApplied(newState.trigger, actions); if (invalidAction && invalidAction.disabled) { messageController_1.MessageController.get(this._editor).showMessage(invalidAction.disabled, newState.trigger.context.position); actions.dispose(); return [2 /*return*/]; } } _d.label = 10; case 10: includeDisabledActions = !!((_c = newState.trigger.filter) === null || _c === void 0 ? void 0 : _c.include); if (newState.trigger.context) { if (!actions.allActions.length || !includeDisabledActions && !actions.validActions.length) { messageController_1.MessageController.get(this._editor).showMessage(newState.trigger.context.notAvailableMessage, newState.trigger.context.position); this._activeCodeActions.value = actions; actions.dispose(); return [2 /*return*/]; } } this._activeCodeActions.value = actions; this._codeActionWidget.getValue().show(newState.trigger, actions, newState.position, { includeDisabledActions: includeDisabledActions }); return [3 /*break*/, 12]; case 11: // auto magically triggered if (this._codeActionWidget.getValue().isVisible) { // TODO: Figure out if we should update the showing menu? actions.dispose(); } else { this._activeCodeActions.value = actions; } _d.label = 12; case 12: return [2 /*return*/]; } }); }); }; CodeActionUi.prototype.getInvalidActionThatWouldHaveBeenApplied = function (trigger, actions) { if (!actions.allActions.length) { return undefined; } if ((trigger.autoApply === "first" /* First */ && actions.validActions.length === 0) || (trigger.autoApply === "ifSingle" /* IfSingle */ && actions.allActions.length === 1)) { return arrays_1.find(actions.allActions, function (action) { return action.disabled; }); } return undefined; }; CodeActionUi.prototype.tryGetValidActionToApply = function (trigger, actions) { if (!actions.validActions.length) { return undefined; } if ((trigger.autoApply === "first" /* First */ && actions.validActions.length > 0) || (trigger.autoApply === "ifSingle" /* IfSingle */ && actions.validActions.length === 1)) { return actions.validActions[0]; } return undefined; }; CodeActionUi.prototype.showCodeActionList = function (trigger, actions, at, options) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { this._codeActionWidget.getValue().show(trigger, actions, at, options); return [2 /*return*/]; }); }); }; CodeActionUi = __decorate([ __param(4, instantiation_1.IInstantiationService) ], CodeActionUi); return CodeActionUi; }(lifecycle_1.Disposable)); exports.CodeActionUi = CodeActionUi; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[233/*vs/editor/contrib/codeAction/codeActionCommands*/], __M([0/*require*/,1/*exports*/,128/*vs/base/common/lazy*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,12/*vs/editor/browser/editorExtensions*/,156/*vs/editor/browser/services/bulkEditService*/,23/*vs/editor/common/editorContextKeys*/,119/*vs/editor/contrib/codeAction/codeAction*/,578/*vs/editor/contrib/codeAction/codeActionUi*/,122/*vs/editor/contrib/message/messageController*/,432/*vs/nls!vs/editor/contrib/codeAction/codeActionCommands*/,29/*vs/platform/commands/common/commands*/,18/*vs/platform/contextkey/common/contextkey*/,11/*vs/platform/instantiation/common/instantiation*/,72/*vs/platform/markers/common/markers*/,35/*vs/platform/notification/common/notification*/,73/*vs/platform/progress/common/progress*/,96/*vs/platform/telemetry/common/telemetry*/,528/*vs/editor/contrib/codeAction/codeActionModel*/,111/*vs/editor/contrib/codeAction/types*/]), function (require, exports, lazy_1, lifecycle_1, strings_1, editorExtensions_1, bulkEditService_1, editorContextKeys_1, codeAction_1, codeActionUi_1, messageController_1, nls, commands_1, contextkey_1, instantiation_1, markers_1, notification_1, progress_1, telemetry_1, codeActionModel_1, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function contextKeyForSupportedActions(kind) { return contextkey_1.ContextKeyExpr.regex(codeActionModel_1.SUPPORTED_CODE_ACTIONS.keys()[0], new RegExp('(\\s|^)' + strings_1.escapeRegExpCharacters(kind.value) + '\\b')); } var argsSchema = { type: 'object', required: ['kind'], defaultSnippets: [{ body: { kind: '' } }], properties: { 'kind': { type: 'string', description: nls.localize(0, null), }, 'apply': { type: 'string', description: nls.localize(1, null), default: "ifSingle" /* IfSingle */, enum: ["first" /* First */, "ifSingle" /* IfSingle */, "never" /* Never */], enumDescriptions: [ nls.localize(2, null), nls.localize(3, null), nls.localize(4, null), ] }, 'preferred': { type: 'boolean', default: false, description: nls.localize(5, null), } } }; var QuickFixController = /** @class */ (function (_super) { __extends(QuickFixController, _super); function QuickFixController(editor, markerService, contextKeyService, progressService, _instantiationService) { var _this = _super.call(this) || this; _this._instantiationService = _instantiationService; _this._editor = editor; _this._model = _this._register(new codeActionModel_1.CodeActionModel(_this._editor, markerService, contextKeyService, progressService)); _this._register(_this._model.onDidChangeState(function (newState) { return _this.update(newState); })); _this._ui = new lazy_1.Lazy(function () { return _this._register(new codeActionUi_1.CodeActionUi(editor, QuickFixAction.Id, AutoFixAction.Id, { applyCodeAction: function (action, retrigger) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, , 2, 3]); return [4 /*yield*/, this._applyCodeAction(action)]; case 1: _a.sent(); return [3 /*break*/, 3]; case 2: if (retrigger) { this._trigger({ type: 1 /* Auto */, filter: {} }); } return [7 /*endfinally*/]; case 3: return [2 /*return*/]; } }); }); } }, _this._instantiationService)); }); return _this; } QuickFixController.get = function (editor) { return editor.getContribution(QuickFixController.ID); }; QuickFixController.prototype.update = function (newState) { this._ui.getValue().update(newState); }; QuickFixController.prototype.showCodeActions = function (trigger, actions, at) { return this._ui.getValue().showCodeActionList(trigger, actions, at, { includeDisabledActions: false }); }; QuickFixController.prototype.manualTriggerAtCurrentPosition = function (notAvailableMessage, filter, autoApply) { if (!this._editor.hasModel()) { return; } messageController_1.MessageController.get(this._editor).closeMessage(); var triggerPosition = this._editor.getPosition(); this._trigger({ type: 2 /* Manual */, filter: filter, autoApply: autoApply, context: { notAvailableMessage: notAvailableMessage, position: triggerPosition } }); }; QuickFixController.prototype._trigger = function (trigger) { return this._model.trigger(trigger); }; QuickFixController.prototype._applyCodeAction = function (action) { return this._instantiationService.invokeFunction(applyCodeAction, action, this._editor); }; QuickFixController.ID = 'editor.contrib.quickFixController'; QuickFixController = __decorate([ __param(1, markers_1.IMarkerService), __param(2, contextkey_1.IContextKeyService), __param(3, progress_1.IEditorProgressService), __param(4, instantiation_1.IInstantiationService) ], QuickFixController); return QuickFixController; }(lifecycle_1.Disposable)); exports.QuickFixController = QuickFixController; function applyCodeAction(accessor, action, editor) { return __awaiter(this, void 0, void 0, function () { var bulkEditService, commandService, telemetryService, notificationService, err_1, message; return __generator(this, function (_a) { switch (_a.label) { case 0: bulkEditService = accessor.get(bulkEditService_1.IBulkEditService); commandService = accessor.get(commands_1.ICommandService); telemetryService = accessor.get(telemetry_1.ITelemetryService); notificationService = accessor.get(notification_1.INotificationService); telemetryService.publicLog2('codeAction.applyCodeAction', { codeActionTitle: action.title, codeActionKind: action.kind, codeActionIsPreferred: !!action.isPreferred, }); if (!action.edit) return [3 /*break*/, 2]; return [4 /*yield*/, bulkEditService.apply(action.edit, { editor: editor })]; case 1: _a.sent(); _a.label = 2; case 2: if (!action.command) return [3 /*break*/, 6]; _a.label = 3; case 3: _a.trys.push([3, 5, , 6]); return [4 /*yield*/, commandService.executeCommand.apply(commandService, __spreadArrays([action.command.id], (action.command.arguments || [])))]; case 4: _a.sent(); return [3 /*break*/, 6]; case 5: err_1 = _a.sent(); message = asMessage(err_1); notificationService.error(typeof message === 'string' ? message : nls.localize(6, null)); return [3 /*break*/, 6]; case 6: return [2 /*return*/]; } }); }); } exports.applyCodeAction = applyCodeAction; function asMessage(err) { if (typeof err === 'string') { return err; } else if (err instanceof Error && typeof err.message === 'string') { return err.message; } else { return undefined; } } function triggerCodeActionsForEditorSelection(editor, notAvailableMessage, filter, autoApply) { if (editor.hasModel()) { var controller = QuickFixController.get(editor); if (controller) { controller.manualTriggerAtCurrentPosition(notAvailableMessage, filter, autoApply); } } } var QuickFixAction = /** @class */ (function (_super) { __extends(QuickFixAction, _super); function QuickFixAction() { return _super.call(this, { id: QuickFixAction.Id, label: nls.localize(7, null), alias: 'Quick Fix...', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasCodeActionsProvider), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 84 /* US_DOT */, weight: 100 /* EditorContrib */ } }) || this; } QuickFixAction.prototype.run = function (_accessor, editor) { return triggerCodeActionsForEditorSelection(editor, nls.localize(8, null), undefined, undefined); }; QuickFixAction.Id = 'editor.action.quickFix'; return QuickFixAction; }(editorExtensions_1.EditorAction)); exports.QuickFixAction = QuickFixAction; var CodeActionCommand = /** @class */ (function (_super) { __extends(CodeActionCommand, _super); function CodeActionCommand() { return _super.call(this, { id: codeAction_1.codeActionCommandId, precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasCodeActionsProvider), description: { description: 'Trigger a code action', args: [{ name: 'args', schema: argsSchema, }] } }) || this; } CodeActionCommand.prototype.runEditorCommand = function (_accessor, editor, userArgs) { var args = types_1.CodeActionCommandArgs.fromUser(userArgs, { kind: types_1.CodeActionKind.Empty, apply: "ifSingle" /* IfSingle */, }); return triggerCodeActionsForEditorSelection(editor, typeof (userArgs === null || userArgs === void 0 ? void 0 : userArgs.kind) === 'string' ? args.preferred ? nls.localize(9, null, userArgs.kind) : nls.localize(10, null, userArgs.kind) : args.preferred ? nls.localize(11, null) : nls.localize(12, null), { include: args.kind, includeSourceActions: true, onlyIncludePreferredActions: args.preferred, }, args.apply); }; return CodeActionCommand; }(editorExtensions_1.EditorCommand)); exports.CodeActionCommand = CodeActionCommand; var RefactorAction = /** @class */ (function (_super) { __extends(RefactorAction, _super); function RefactorAction() { return _super.call(this, { id: codeAction_1.refactorCommandId, label: nls.localize(13, null), alias: 'Refactor...', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasCodeActionsProvider), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 48 /* KEY_R */, mac: { primary: 256 /* WinCtrl */ | 1024 /* Shift */ | 48 /* KEY_R */ }, weight: 100 /* EditorContrib */ }, contextMenuOpts: { group: '1_modification', order: 2, when: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(types_1.CodeActionKind.Refactor)), }, description: { description: 'Refactor...', args: [{ name: 'args', schema: argsSchema }] } }) || this; } RefactorAction.prototype.run = function (_accessor, editor, userArgs) { var args = types_1.CodeActionCommandArgs.fromUser(userArgs, { kind: types_1.CodeActionKind.Refactor, apply: "never" /* Never */ }); return triggerCodeActionsForEditorSelection(editor, typeof (userArgs === null || userArgs === void 0 ? void 0 : userArgs.kind) === 'string' ? args.preferred ? nls.localize(14, null, userArgs.kind) : nls.localize(15, null, userArgs.kind) : args.preferred ? nls.localize(16, null) : nls.localize(17, null), { include: types_1.CodeActionKind.Refactor.contains(args.kind) ? args.kind : types_1.CodeActionKind.None, onlyIncludePreferredActions: args.preferred, }, args.apply); }; return RefactorAction; }(editorExtensions_1.EditorAction)); exports.RefactorAction = RefactorAction; var SourceAction = /** @class */ (function (_super) { __extends(SourceAction, _super); function SourceAction() { return _super.call(this, { id: codeAction_1.sourceActionCommandId, label: nls.localize(18, null), alias: 'Source Action...', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasCodeActionsProvider), contextMenuOpts: { group: '1_modification', order: 2.1, when: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(types_1.CodeActionKind.Source)), }, description: { description: 'Source Action...', args: [{ name: 'args', schema: argsSchema }] } }) || this; } SourceAction.prototype.run = function (_accessor, editor, userArgs) { var args = types_1.CodeActionCommandArgs.fromUser(userArgs, { kind: types_1.CodeActionKind.Source, apply: "never" /* Never */ }); return triggerCodeActionsForEditorSelection(editor, typeof (userArgs === null || userArgs === void 0 ? void 0 : userArgs.kind) === 'string' ? args.preferred ? nls.localize(19, null, userArgs.kind) : nls.localize(20, null, userArgs.kind) : args.preferred ? nls.localize(21, null) : nls.localize(22, null), { include: types_1.CodeActionKind.Source.contains(args.kind) ? args.kind : types_1.CodeActionKind.None, includeSourceActions: true, onlyIncludePreferredActions: args.preferred, }, args.apply); }; return SourceAction; }(editorExtensions_1.EditorAction)); exports.SourceAction = SourceAction; var OrganizeImportsAction = /** @class */ (function (_super) { __extends(OrganizeImportsAction, _super); function OrganizeImportsAction() { return _super.call(this, { id: codeAction_1.organizeImportsCommandId, label: nls.localize(23, null), alias: 'Organize Imports', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(types_1.CodeActionKind.SourceOrganizeImports)), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 1024 /* Shift */ | 512 /* Alt */ | 45 /* KEY_O */, weight: 100 /* EditorContrib */ }, }) || this; } OrganizeImportsAction.prototype.run = function (_accessor, editor) { return triggerCodeActionsForEditorSelection(editor, nls.localize(24, null), { include: types_1.CodeActionKind.SourceOrganizeImports, includeSourceActions: true }, "ifSingle" /* IfSingle */); }; return OrganizeImportsAction; }(editorExtensions_1.EditorAction)); exports.OrganizeImportsAction = OrganizeImportsAction; var FixAllAction = /** @class */ (function (_super) { __extends(FixAllAction, _super); function FixAllAction() { return _super.call(this, { id: codeAction_1.fixAllCommandId, label: nls.localize(25, null), alias: 'Fix All', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(types_1.CodeActionKind.SourceFixAll)) }) || this; } FixAllAction.prototype.run = function (_accessor, editor) { return triggerCodeActionsForEditorSelection(editor, nls.localize(26, null), { include: types_1.CodeActionKind.SourceFixAll, includeSourceActions: true }, "ifSingle" /* IfSingle */); }; return FixAllAction; }(editorExtensions_1.EditorAction)); exports.FixAllAction = FixAllAction; var AutoFixAction = /** @class */ (function (_super) { __extends(AutoFixAction, _super); function AutoFixAction() { return _super.call(this, { id: AutoFixAction.Id, label: nls.localize(27, null), alias: 'Auto Fix...', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(types_1.CodeActionKind.QuickFix)), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 512 /* Alt */ | 1024 /* Shift */ | 84 /* US_DOT */, mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 84 /* US_DOT */ }, weight: 100 /* EditorContrib */ } }) || this; } AutoFixAction.prototype.run = function (_accessor, editor) { return triggerCodeActionsForEditorSelection(editor, nls.localize(28, null), { include: types_1.CodeActionKind.QuickFix, onlyIncludePreferredActions: true }, "ifSingle" /* IfSingle */); }; AutoFixAction.Id = 'editor.action.autoFix'; return AutoFixAction; }(editorExtensions_1.EditorAction)); exports.AutoFixAction = AutoFixAction; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[579/*vs/editor/contrib/codeAction/codeActionContributions*/], __M([0/*require*/,1/*exports*/,12/*vs/editor/browser/editorExtensions*/,233/*vs/editor/contrib/codeAction/codeActionCommands*/]), function (require, exports, editorExtensions_1, codeActionCommands_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); editorExtensions_1.registerEditorContribution(codeActionCommands_1.QuickFixController.ID, codeActionCommands_1.QuickFixController); editorExtensions_1.registerEditorAction(codeActionCommands_1.QuickFixAction); editorExtensions_1.registerEditorAction(codeActionCommands_1.RefactorAction); editorExtensions_1.registerEditorAction(codeActionCommands_1.SourceAction); editorExtensions_1.registerEditorAction(codeActionCommands_1.OrganizeImportsAction); editorExtensions_1.registerEditorAction(codeActionCommands_1.AutoFixAction); editorExtensions_1.registerEditorAction(codeActionCommands_1.FixAllAction); editorExtensions_1.registerEditorCommand(new codeActionCommands_1.CodeActionCommand()); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[580/*vs/editor/contrib/multicursor/multicursor*/], __M([0/*require*/,1/*exports*/,459/*vs/nls!vs/editor/contrib/multicursor/multicursor*/,15/*vs/base/common/async*/,36/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,12/*vs/editor/browser/editorExtensions*/,213/*vs/editor/common/controller/cursorMoveCommands*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,23/*vs/editor/common/editorContextKeys*/,48/*vs/editor/common/model*/,30/*vs/editor/common/model/textModel*/,17/*vs/editor/common/modes*/,232/*vs/editor/contrib/find/findController*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,18/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, nls, async_1, keyCodes_1, lifecycle_1, editorExtensions_1, cursorMoveCommands_1, range_1, selection_1, editorContextKeys_1, model_1, textModel_1, modes_1, findController_1, colorRegistry_1, themeService_1, contextkey_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var InsertCursorAbove = /** @class */ (function (_super) { __extends(InsertCursorAbove, _super); function InsertCursorAbove() { return _super.call(this, { id: 'editor.action.insertCursorAbove', label: nls.localize(0, null), alias: 'Add Cursor Above', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 16 /* UpArrow */, linux: { primary: 1024 /* Shift */ | 512 /* Alt */ | 16 /* UpArrow */, secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 16 /* UpArrow */] }, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 25 /* MenubarSelectionMenu */, group: '3_multi', title: nls.localize(1, null), order: 2 } }) || this; } InsertCursorAbove.prototype.run = function (accessor, editor, args) { if (!editor.hasModel()) { return; } var useLogicalLine = (args && args.logicalLine === true); var cursors = editor._getCursors(); var context = cursors.context; if (context.config.readOnly) { return; } context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, cursorMoveCommands_1.CursorMoveCommands.addCursorUp(context, cursors.getAll(), useLogicalLine)); cursors.reveal(args.source, true, 1 /* TopMost */, 0 /* Smooth */); }; return InsertCursorAbove; }(editorExtensions_1.EditorAction)); exports.InsertCursorAbove = InsertCursorAbove; var InsertCursorBelow = /** @class */ (function (_super) { __extends(InsertCursorBelow, _super); function InsertCursorBelow() { return _super.call(this, { id: 'editor.action.insertCursorBelow', label: nls.localize(2, null), alias: 'Add Cursor Below', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 18 /* DownArrow */, linux: { primary: 1024 /* Shift */ | 512 /* Alt */ | 18 /* DownArrow */, secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 18 /* DownArrow */] }, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 25 /* MenubarSelectionMenu */, group: '3_multi', title: nls.localize(3, null), order: 3 } }) || this; } InsertCursorBelow.prototype.run = function (accessor, editor, args) { if (!editor.hasModel()) { return; } var useLogicalLine = (args && args.logicalLine === true); var cursors = editor._getCursors(); var context = cursors.context; if (context.config.readOnly) { return; } context.model.pushStackElement(); cursors.setStates(args.source, 3 /* Explicit */, cursorMoveCommands_1.CursorMoveCommands.addCursorDown(context, cursors.getAll(), useLogicalLine)); cursors.reveal(args.source, true, 2 /* BottomMost */, 0 /* Smooth */); }; return InsertCursorBelow; }(editorExtensions_1.EditorAction)); exports.InsertCursorBelow = InsertCursorBelow; var InsertCursorAtEndOfEachLineSelected = /** @class */ (function (_super) { __extends(InsertCursorAtEndOfEachLineSelected, _super); function InsertCursorAtEndOfEachLineSelected() { return _super.call(this, { id: 'editor.action.insertCursorAtEndOfEachLineSelected', label: nls.localize(4, null), alias: 'Add Cursors to Line Ends', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 1024 /* Shift */ | 512 /* Alt */ | 39 /* KEY_I */, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 25 /* MenubarSelectionMenu */, group: '3_multi', title: nls.localize(5, null), order: 4 } }) || this; } InsertCursorAtEndOfEachLineSelected.prototype.getCursorsForSelection = function (selection, model, result) { if (selection.isEmpty()) { return; } for (var i = selection.startLineNumber; i < selection.endLineNumber; i++) { var currentLineMaxColumn = model.getLineMaxColumn(i); result.push(new selection_1.Selection(i, currentLineMaxColumn, i, currentLineMaxColumn)); } if (selection.endColumn > 1) { result.push(new selection_1.Selection(selection.endLineNumber, selection.endColumn, selection.endLineNumber, selection.endColumn)); } }; InsertCursorAtEndOfEachLineSelected.prototype.run = function (accessor, editor) { var _this = this; if (!editor.hasModel()) { return; } var model = editor.getModel(); var selections = editor.getSelections(); var newSelections = []; selections.forEach(function (sel) { return _this.getCursorsForSelection(sel, model, newSelections); }); if (newSelections.length > 0) { editor.setSelections(newSelections); } }; return InsertCursorAtEndOfEachLineSelected; }(editorExtensions_1.EditorAction)); var InsertCursorAtEndOfLineSelected = /** @class */ (function (_super) { __extends(InsertCursorAtEndOfLineSelected, _super); function InsertCursorAtEndOfLineSelected() { return _super.call(this, { id: 'editor.action.addCursorsToBottom', label: nls.localize(6, null), alias: 'Add Cursors To Bottom', precondition: undefined }) || this; } InsertCursorAtEndOfLineSelected.prototype.run = function (accessor, editor) { if (!editor.hasModel()) { return; } var selections = editor.getSelections(); var lineCount = editor.getModel().getLineCount(); var newSelections = []; for (var i = selections[0].startLineNumber; i <= lineCount; i++) { newSelections.push(new selection_1.Selection(i, selections[0].startColumn, i, selections[0].endColumn)); } if (newSelections.length > 0) { editor.setSelections(newSelections); } }; return InsertCursorAtEndOfLineSelected; }(editorExtensions_1.EditorAction)); var InsertCursorAtTopOfLineSelected = /** @class */ (function (_super) { __extends(InsertCursorAtTopOfLineSelected, _super); function InsertCursorAtTopOfLineSelected() { return _super.call(this, { id: 'editor.action.addCursorsToTop', label: nls.localize(7, null), alias: 'Add Cursors To Top', precondition: undefined }) || this; } InsertCursorAtTopOfLineSelected.prototype.run = function (accessor, editor) { if (!editor.hasModel()) { return; } var selections = editor.getSelections(); var newSelections = []; for (var i = selections[0].startLineNumber; i >= 1; i--) { newSelections.push(new selection_1.Selection(i, selections[0].startColumn, i, selections[0].endColumn)); } if (newSelections.length > 0) { editor.setSelections(newSelections); } }; return InsertCursorAtTopOfLineSelected; }(editorExtensions_1.EditorAction)); var MultiCursorSessionResult = /** @class */ (function () { function MultiCursorSessionResult(selections, revealRange, revealScrollType) { this.selections = selections; this.revealRange = revealRange; this.revealScrollType = revealScrollType; } return MultiCursorSessionResult; }()); exports.MultiCursorSessionResult = MultiCursorSessionResult; var MultiCursorSession = /** @class */ (function () { function MultiCursorSession(_editor, findController, isDisconnectedFromFindController, searchText, wholeWord, matchCase, currentMatch) { this._editor = _editor; this.findController = findController; this.isDisconnectedFromFindController = isDisconnectedFromFindController; this.searchText = searchText; this.wholeWord = wholeWord; this.matchCase = matchCase; this.currentMatch = currentMatch; } MultiCursorSession.create = function (editor, findController) { if (!editor.hasModel()) { return null; } var findState = findController.getState(); // Find widget owns entirely what we search for if: // - focus is not in the editor (i.e. it is in the find widget) // - and the search widget is visible // - and the search string is non-empty if (!editor.hasTextFocus() && findState.isRevealed && findState.searchString.length > 0) { // Find widget owns what is searched for return new MultiCursorSession(editor, findController, false, findState.searchString, findState.wholeWord, findState.matchCase, null); } // Otherwise, the selection gives the search text, and the find widget gives the search settings // The exception is the find state disassociation case: when beginning with a single, collapsed selection var isDisconnectedFromFindController = false; var wholeWord; var matchCase; var selections = editor.getSelections(); if (selections.length === 1 && selections[0].isEmpty()) { isDisconnectedFromFindController = true; wholeWord = true; matchCase = true; } else { wholeWord = findState.wholeWord; matchCase = findState.matchCase; } // Selection owns what is searched for var s = editor.getSelection(); var searchText; var currentMatch = null; if (s.isEmpty()) { // selection is empty => expand to current word var word = editor.getModel().getWordAtPosition(s.getStartPosition()); if (!word) { return null; } searchText = word.word; currentMatch = new selection_1.Selection(s.startLineNumber, word.startColumn, s.startLineNumber, word.endColumn); } else { searchText = editor.getModel().getValueInRange(s).replace(/\r\n/g, '\n'); } return new MultiCursorSession(editor, findController, isDisconnectedFromFindController, searchText, wholeWord, matchCase, currentMatch); }; MultiCursorSession.prototype.addSelectionToNextFindMatch = function () { if (!this._editor.hasModel()) { return null; } var nextMatch = this._getNextMatch(); if (!nextMatch) { return null; } var allSelections = this._editor.getSelections(); return new MultiCursorSessionResult(allSelections.concat(nextMatch), nextMatch, 0 /* Smooth */); }; MultiCursorSession.prototype.moveSelectionToNextFindMatch = function () { if (!this._editor.hasModel()) { return null; } var nextMatch = this._getNextMatch(); if (!nextMatch) { return null; } var allSelections = this._editor.getSelections(); return new MultiCursorSessionResult(allSelections.slice(0, allSelections.length - 1).concat(nextMatch), nextMatch, 0 /* Smooth */); }; MultiCursorSession.prototype._getNextMatch = function () { if (!this._editor.hasModel()) { return null; } if (this.currentMatch) { var result = this.currentMatch; this.currentMatch = null; return result; } this.findController.highlightFindOptions(); var allSelections = this._editor.getSelections(); var lastAddedSelection = allSelections[allSelections.length - 1]; var nextMatch = this._editor.getModel().findNextMatch(this.searchText, lastAddedSelection.getEndPosition(), false, this.matchCase, this.wholeWord ? this._editor.getOption(96 /* wordSeparators */) : null, false); if (!nextMatch) { return null; } return new selection_1.Selection(nextMatch.range.startLineNumber, nextMatch.range.startColumn, nextMatch.range.endLineNumber, nextMatch.range.endColumn); }; MultiCursorSession.prototype.addSelectionToPreviousFindMatch = function () { if (!this._editor.hasModel()) { return null; } var previousMatch = this._getPreviousMatch(); if (!previousMatch) { return null; } var allSelections = this._editor.getSelections(); return new MultiCursorSessionResult(allSelections.concat(previousMatch), previousMatch, 0 /* Smooth */); }; MultiCursorSession.prototype.moveSelectionToPreviousFindMatch = function () { if (!this._editor.hasModel()) { return null; } var previousMatch = this._getPreviousMatch(); if (!previousMatch) { return null; } var allSelections = this._editor.getSelections(); return new MultiCursorSessionResult(allSelections.slice(0, allSelections.length - 1).concat(previousMatch), previousMatch, 0 /* Smooth */); }; MultiCursorSession.prototype._getPreviousMatch = function () { if (!this._editor.hasModel()) { return null; } if (this.currentMatch) { var result = this.currentMatch; this.currentMatch = null; return result; } this.findController.highlightFindOptions(); var allSelections = this._editor.getSelections(); var lastAddedSelection = allSelections[allSelections.length - 1]; var previousMatch = this._editor.getModel().findPreviousMatch(this.searchText, lastAddedSelection.getStartPosition(), false, this.matchCase, this.wholeWord ? this._editor.getOption(96 /* wordSeparators */) : null, false); if (!previousMatch) { return null; } return new selection_1.Selection(previousMatch.range.startLineNumber, previousMatch.range.startColumn, previousMatch.range.endLineNumber, previousMatch.range.endColumn); }; MultiCursorSession.prototype.selectAll = function () { if (!this._editor.hasModel()) { return []; } this.findController.highlightFindOptions(); return this._editor.getModel().findMatches(this.searchText, true, false, this.matchCase, this.wholeWord ? this._editor.getOption(96 /* wordSeparators */) : null, false, 1073741824 /* MAX_SAFE_SMALL_INTEGER */); }; return MultiCursorSession; }()); exports.MultiCursorSession = MultiCursorSession; var MultiCursorSelectionController = /** @class */ (function (_super) { __extends(MultiCursorSelectionController, _super); function MultiCursorSelectionController(editor) { var _this = _super.call(this) || this; _this._sessionDispose = _this._register(new lifecycle_1.DisposableStore()); _this._editor = editor; _this._ignoreSelectionChange = false; _this._session = null; return _this; } MultiCursorSelectionController.get = function (editor) { return editor.getContribution(MultiCursorSelectionController.ID); }; MultiCursorSelectionController.prototype.dispose = function () { this._endSession(); _super.prototype.dispose.call(this); }; MultiCursorSelectionController.prototype._beginSessionIfNeeded = function (findController) { var _this = this; if (!this._session) { // Create a new session var session = MultiCursorSession.create(this._editor, findController); if (!session) { return; } this._session = session; var newState = { searchString: this._session.searchText }; if (this._session.isDisconnectedFromFindController) { newState.wholeWordOverride = 1 /* True */; newState.matchCaseOverride = 1 /* True */; newState.isRegexOverride = 2 /* False */; } findController.getState().change(newState, false); this._sessionDispose.add(this._editor.onDidChangeCursorSelection(function (e) { if (_this._ignoreSelectionChange) { return; } _this._endSession(); })); this._sessionDispose.add(this._editor.onDidBlurEditorText(function () { _this._endSession(); })); this._sessionDispose.add(findController.getState().onFindReplaceStateChange(function (e) { if (e.matchCase || e.wholeWord) { _this._endSession(); } })); } }; MultiCursorSelectionController.prototype._endSession = function () { this._sessionDispose.clear(); if (this._session && this._session.isDisconnectedFromFindController) { var newState = { wholeWordOverride: 0 /* NotSet */, matchCaseOverride: 0 /* NotSet */, isRegexOverride: 0 /* NotSet */, }; this._session.findController.getState().change(newState, false); } this._session = null; }; MultiCursorSelectionController.prototype._setSelections = function (selections) { this._ignoreSelectionChange = true; this._editor.setSelections(selections); this._ignoreSelectionChange = false; }; MultiCursorSelectionController.prototype._expandEmptyToWord = function (model, selection) { if (!selection.isEmpty()) { return selection; } var word = model.getWordAtPosition(selection.getStartPosition()); if (!word) { return selection; } return new selection_1.Selection(selection.startLineNumber, word.startColumn, selection.startLineNumber, word.endColumn); }; MultiCursorSelectionController.prototype._applySessionResult = function (result) { if (!result) { return; } this._setSelections(result.selections); if (result.revealRange) { this._editor.revealRangeInCenterIfOutsideViewport(result.revealRange, result.revealScrollType); } }; MultiCursorSelectionController.prototype.getSession = function (findController) { return this._session; }; MultiCursorSelectionController.prototype.addSelectionToNextFindMatch = function (findController) { if (!this._editor.hasModel()) { return; } if (!this._session) { // If there are multiple cursors, handle the case where they do not all select the same text. var allSelections = this._editor.getSelections(); if (allSelections.length > 1) { var findState = findController.getState(); var matchCase = findState.matchCase; var selectionsContainSameText = modelRangesContainSameText(this._editor.getModel(), allSelections, matchCase); if (!selectionsContainSameText) { var model = this._editor.getModel(); var resultingSelections = []; for (var i = 0, len = allSelections.length; i < len; i++) { resultingSelections[i] = this._expandEmptyToWord(model, allSelections[i]); } this._editor.setSelections(resultingSelections); return; } } } this._beginSessionIfNeeded(findController); if (this._session) { this._applySessionResult(this._session.addSelectionToNextFindMatch()); } }; MultiCursorSelectionController.prototype.addSelectionToPreviousFindMatch = function (findController) { this._beginSessionIfNeeded(findController); if (this._session) { this._applySessionResult(this._session.addSelectionToPreviousFindMatch()); } }; MultiCursorSelectionController.prototype.moveSelectionToNextFindMatch = function (findController) { this._beginSessionIfNeeded(findController); if (this._session) { this._applySessionResult(this._session.moveSelectionToNextFindMatch()); } }; MultiCursorSelectionController.prototype.moveSelectionToPreviousFindMatch = function (findController) { this._beginSessionIfNeeded(findController); if (this._session) { this._applySessionResult(this._session.moveSelectionToPreviousFindMatch()); } }; MultiCursorSelectionController.prototype.selectAll = function (findController) { if (!this._editor.hasModel()) { return; } var matches = null; var findState = findController.getState(); // Special case: find widget owns entirely what we search for if: // - focus is not in the editor (i.e. it is in the find widget) // - and the search widget is visible // - and the search string is non-empty // - and we're searching for a regex if (findState.isRevealed && findState.searchString.length > 0 && findState.isRegex) { matches = this._editor.getModel().findMatches(findState.searchString, true, findState.isRegex, findState.matchCase, findState.wholeWord ? this._editor.getOption(96 /* wordSeparators */) : null, false, 1073741824 /* MAX_SAFE_SMALL_INTEGER */); } else { this._beginSessionIfNeeded(findController); if (!this._session) { return; } matches = this._session.selectAll(); } if (findState.searchScope) { var state = findState.searchScope; var inSelection = []; for (var i = 0; i < matches.length; i++) { if (matches[i].range.endLineNumber <= state.endLineNumber && matches[i].range.startLineNumber >= state.startLineNumber) { inSelection.push(matches[i]); } } matches = inSelection; } if (matches.length > 0) { var editorSelection = this._editor.getSelection(); // Have the primary cursor remain the one where the action was invoked for (var i = 0, len = matches.length; i < len; i++) { var match = matches[i]; var intersection = match.range.intersectRanges(editorSelection); if (intersection) { // bingo! matches[i] = matches[0]; matches[0] = match; break; } } this._setSelections(matches.map(function (m) { return new selection_1.Selection(m.range.startLineNumber, m.range.startColumn, m.range.endLineNumber, m.range.endColumn); })); } }; MultiCursorSelectionController.ID = 'editor.contrib.multiCursorController'; return MultiCursorSelectionController; }(lifecycle_1.Disposable)); exports.MultiCursorSelectionController = MultiCursorSelectionController; var MultiCursorSelectionControllerAction = /** @class */ (function (_super) { __extends(MultiCursorSelectionControllerAction, _super); function MultiCursorSelectionControllerAction() { return _super !== null && _super.apply(this, arguments) || this; } MultiCursorSelectionControllerAction.prototype.run = function (accessor, editor) { var multiCursorController = MultiCursorSelectionController.get(editor); if (!multiCursorController) { return; } var findController = findController_1.CommonFindController.get(editor); if (!findController) { return; } this._run(multiCursorController, findController); }; return MultiCursorSelectionControllerAction; }(editorExtensions_1.EditorAction)); exports.MultiCursorSelectionControllerAction = MultiCursorSelectionControllerAction; var AddSelectionToNextFindMatchAction = /** @class */ (function (_super) { __extends(AddSelectionToNextFindMatchAction, _super); function AddSelectionToNextFindMatchAction() { return _super.call(this, { id: 'editor.action.addSelectionToNextFindMatch', label: nls.localize(8, null), alias: 'Add Selection To Next Find Match', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 2048 /* CtrlCmd */ | 34 /* KEY_D */, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 25 /* MenubarSelectionMenu */, group: '3_multi', title: nls.localize(9, null), order: 5 } }) || this; } AddSelectionToNextFindMatchAction.prototype._run = function (multiCursorController, findController) { multiCursorController.addSelectionToNextFindMatch(findController); }; return AddSelectionToNextFindMatchAction; }(MultiCursorSelectionControllerAction)); exports.AddSelectionToNextFindMatchAction = AddSelectionToNextFindMatchAction; var AddSelectionToPreviousFindMatchAction = /** @class */ (function (_super) { __extends(AddSelectionToPreviousFindMatchAction, _super); function AddSelectionToPreviousFindMatchAction() { return _super.call(this, { id: 'editor.action.addSelectionToPreviousFindMatch', label: nls.localize(10, null), alias: 'Add Selection To Previous Find Match', precondition: undefined, menuOpts: { menuId: 25 /* MenubarSelectionMenu */, group: '3_multi', title: nls.localize(11, null), order: 6 } }) || this; } AddSelectionToPreviousFindMatchAction.prototype._run = function (multiCursorController, findController) { multiCursorController.addSelectionToPreviousFindMatch(findController); }; return AddSelectionToPreviousFindMatchAction; }(MultiCursorSelectionControllerAction)); exports.AddSelectionToPreviousFindMatchAction = AddSelectionToPreviousFindMatchAction; var MoveSelectionToNextFindMatchAction = /** @class */ (function (_super) { __extends(MoveSelectionToNextFindMatchAction, _super); function MoveSelectionToNextFindMatchAction() { return _super.call(this, { id: 'editor.action.moveSelectionToNextFindMatch', label: nls.localize(12, null), alias: 'Move Last Selection To Next Find Match', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 34 /* KEY_D */), weight: 100 /* EditorContrib */ } }) || this; } MoveSelectionToNextFindMatchAction.prototype._run = function (multiCursorController, findController) { multiCursorController.moveSelectionToNextFindMatch(findController); }; return MoveSelectionToNextFindMatchAction; }(MultiCursorSelectionControllerAction)); exports.MoveSelectionToNextFindMatchAction = MoveSelectionToNextFindMatchAction; var MoveSelectionToPreviousFindMatchAction = /** @class */ (function (_super) { __extends(MoveSelectionToPreviousFindMatchAction, _super); function MoveSelectionToPreviousFindMatchAction() { return _super.call(this, { id: 'editor.action.moveSelectionToPreviousFindMatch', label: nls.localize(13, null), alias: 'Move Last Selection To Previous Find Match', precondition: undefined }) || this; } MoveSelectionToPreviousFindMatchAction.prototype._run = function (multiCursorController, findController) { multiCursorController.moveSelectionToPreviousFindMatch(findController); }; return MoveSelectionToPreviousFindMatchAction; }(MultiCursorSelectionControllerAction)); exports.MoveSelectionToPreviousFindMatchAction = MoveSelectionToPreviousFindMatchAction; var SelectHighlightsAction = /** @class */ (function (_super) { __extends(SelectHighlightsAction, _super); function SelectHighlightsAction() { return _super.call(this, { id: 'editor.action.selectHighlights', label: nls.localize(14, null), alias: 'Select All Occurrences of Find Match', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 42 /* KEY_L */, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 25 /* MenubarSelectionMenu */, group: '3_multi', title: nls.localize(15, null), order: 7 } }) || this; } SelectHighlightsAction.prototype._run = function (multiCursorController, findController) { multiCursorController.selectAll(findController); }; return SelectHighlightsAction; }(MultiCursorSelectionControllerAction)); exports.SelectHighlightsAction = SelectHighlightsAction; var CompatChangeAll = /** @class */ (function (_super) { __extends(CompatChangeAll, _super); function CompatChangeAll() { return _super.call(this, { id: 'editor.action.changeAll', label: nls.localize(16, null), alias: 'Change All Occurrences', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.editorTextFocus), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 60 /* F2 */, weight: 100 /* EditorContrib */ }, contextMenuOpts: { group: '1_modification', order: 1.2 } }) || this; } CompatChangeAll.prototype._run = function (multiCursorController, findController) { multiCursorController.selectAll(findController); }; return CompatChangeAll; }(MultiCursorSelectionControllerAction)); exports.CompatChangeAll = CompatChangeAll; var SelectionHighlighterState = /** @class */ (function () { function SelectionHighlighterState(searchText, matchCase, wordSeparators) { this.searchText = searchText; this.matchCase = matchCase; this.wordSeparators = wordSeparators; } /** * Everything equals except for `lastWordUnderCursor` */ SelectionHighlighterState.softEquals = function (a, b) { if (!a && !b) { return true; } if (!a || !b) { return false; } return (a.searchText === b.searchText && a.matchCase === b.matchCase && a.wordSeparators === b.wordSeparators); }; return SelectionHighlighterState; }()); var SelectionHighlighter = /** @class */ (function (_super) { __extends(SelectionHighlighter, _super); function SelectionHighlighter(editor) { var _this = _super.call(this) || this; _this.editor = editor; _this._isEnabled = editor.getOption(82 /* selectionHighlight */); _this.decorations = []; _this.updateSoon = _this._register(new async_1.RunOnceScheduler(function () { return _this._update(); }, 300)); _this.state = null; _this._register(editor.onDidChangeConfiguration(function (e) { _this._isEnabled = editor.getOption(82 /* selectionHighlight */); })); _this._register(editor.onDidChangeCursorSelection(function (e) { if (!_this._isEnabled) { // Early exit if nothing needs to be done! // Leave some form of early exit check here if you wish to continue being a cursor position change listener ;) return; } if (e.selection.isEmpty()) { if (e.reason === 3 /* Explicit */) { if (_this.state) { // no longer valid _this._setState(null); } _this.updateSoon.schedule(); } else { _this._setState(null); } } else { _this._update(); } })); _this._register(editor.onDidChangeModel(function (e) { _this._setState(null); })); _this._register(findController_1.CommonFindController.get(editor).getState().onFindReplaceStateChange(function (e) { _this._update(); })); return _this; } SelectionHighlighter.prototype._update = function () { this._setState(SelectionHighlighter._createState(this._isEnabled, this.editor)); }; SelectionHighlighter._createState = function (isEnabled, editor) { if (!isEnabled) { return null; } if (!editor.hasModel()) { return null; } var s = editor.getSelection(); if (s.startLineNumber !== s.endLineNumber) { // multiline forbidden for perf reasons return null; } var multiCursorController = MultiCursorSelectionController.get(editor); if (!multiCursorController) { return null; } var findController = findController_1.CommonFindController.get(editor); if (!findController) { return null; } var r = multiCursorController.getSession(findController); if (!r) { var allSelections = editor.getSelections(); if (allSelections.length > 1) { var findState_1 = findController.getState(); var matchCase = findState_1.matchCase; var selectionsContainSameText = modelRangesContainSameText(editor.getModel(), allSelections, matchCase); if (!selectionsContainSameText) { return null; } } r = MultiCursorSession.create(editor, findController); } if (!r) { return null; } if (r.currentMatch) { // This is an empty selection // Do not interfere with semantic word highlighting in the no selection case return null; } if (/^[ \t]+$/.test(r.searchText)) { // whitespace only selection return null; } if (r.searchText.length > 200) { // very long selection return null; } // TODO: better handling of this case var findState = findController.getState(); var caseSensitive = findState.matchCase; // Return early if the find widget shows the exact same matches if (findState.isRevealed) { var findStateSearchString = findState.searchString; if (!caseSensitive) { findStateSearchString = findStateSearchString.toLowerCase(); } var mySearchString = r.searchText; if (!caseSensitive) { mySearchString = mySearchString.toLowerCase(); } if (findStateSearchString === mySearchString && r.matchCase === findState.matchCase && r.wholeWord === findState.wholeWord && !findState.isRegex) { return null; } } return new SelectionHighlighterState(r.searchText, r.matchCase, r.wholeWord ? editor.getOption(96 /* wordSeparators */) : null); }; SelectionHighlighter.prototype._setState = function (state) { if (SelectionHighlighterState.softEquals(this.state, state)) { this.state = state; return; } this.state = state; if (!this.state) { this.decorations = this.editor.deltaDecorations(this.decorations, []); return; } if (!this.editor.hasModel()) { return; } var model = this.editor.getModel(); if (model.isTooLargeForTokenization()) { // the file is too large, so searching word under cursor in the whole document takes is blocking the UI. return; } var hasFindOccurrences = modes_1.DocumentHighlightProviderRegistry.has(model); var allMatches = model.findMatches(this.state.searchText, true, false, this.state.matchCase, this.state.wordSeparators, false).map(function (m) { return m.range; }); allMatches.sort(range_1.Range.compareRangesUsingStarts); var selections = this.editor.getSelections(); selections.sort(range_1.Range.compareRangesUsingStarts); // do not overlap with selection (issue #64 and #512) var matches = []; for (var i = 0, j = 0, len = allMatches.length, lenJ = selections.length; i < len;) { var match = allMatches[i]; if (j >= lenJ) { // finished all editor selections matches.push(match); i++; } else { var cmp = range_1.Range.compareRangesUsingStarts(match, selections[j]); if (cmp < 0) { // match is before sel if (selections[j].isEmpty() || !range_1.Range.areIntersecting(match, selections[j])) { matches.push(match); } i++; } else if (cmp > 0) { // sel is before match j++; } else { // sel is equal to match i++; j++; } } } var decorations = matches.map(function (r) { return { range: r, // Show in overviewRuler only if model has no semantic highlighting options: (hasFindOccurrences ? SelectionHighlighter._SELECTION_HIGHLIGHT : SelectionHighlighter._SELECTION_HIGHLIGHT_OVERVIEW) }; }); this.decorations = this.editor.deltaDecorations(this.decorations, decorations); }; SelectionHighlighter.prototype.dispose = function () { this._setState(null); _super.prototype.dispose.call(this); }; SelectionHighlighter.ID = 'editor.contrib.selectionHighlighter'; SelectionHighlighter._SELECTION_HIGHLIGHT_OVERVIEW = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'selectionHighlight', overviewRuler: { color: themeService_1.themeColorFromId(colorRegistry_1.overviewRulerSelectionHighlightForeground), position: model_1.OverviewRulerLane.Center } }); SelectionHighlighter._SELECTION_HIGHLIGHT = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'selectionHighlight', }); return SelectionHighlighter; }(lifecycle_1.Disposable)); exports.SelectionHighlighter = SelectionHighlighter; function modelRangesContainSameText(model, ranges, matchCase) { var selectedText = getValueInRange(model, ranges[0], !matchCase); for (var i = 1, len = ranges.length; i < len; i++) { var range = ranges[i]; if (range.isEmpty()) { return false; } var thisSelectedText = getValueInRange(model, range, !matchCase); if (selectedText !== thisSelectedText) { return false; } } return true; } function getValueInRange(model, range, toLowerCase) { var text = model.getValueInRange(range); return (toLowerCase ? text.toLowerCase() : text); } editorExtensions_1.registerEditorContribution(MultiCursorSelectionController.ID, MultiCursorSelectionController); editorExtensions_1.registerEditorContribution(SelectionHighlighter.ID, SelectionHighlighter); editorExtensions_1.registerEditorAction(InsertCursorAbove); editorExtensions_1.registerEditorAction(InsertCursorBelow); editorExtensions_1.registerEditorAction(InsertCursorAtEndOfEachLineSelected); editorExtensions_1.registerEditorAction(AddSelectionToNextFindMatchAction); editorExtensions_1.registerEditorAction(AddSelectionToPreviousFindMatchAction); editorExtensions_1.registerEditorAction(MoveSelectionToNextFindMatchAction); editorExtensions_1.registerEditorAction(MoveSelectionToPreviousFindMatchAction); editorExtensions_1.registerEditorAction(SelectHighlightsAction); editorExtensions_1.registerEditorAction(CompatChangeAll); editorExtensions_1.registerEditorAction(InsertCursorAtEndOfLineSelected); editorExtensions_1.registerEditorAction(InsertCursorAtTopOfLineSelected); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[581/*vs/editor/contrib/parameterHints/parameterHintsWidget*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,52/*vs/base/browser/event*/,50/*vs/base/browser/ui/aria/aria*/,53/*vs/base/browser/ui/scrollbar/scrollableElement*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,71/*vs/editor/common/services/modeService*/,117/*vs/editor/contrib/markdown/markdownRenderer*/,165/*vs/editor/contrib/parameterHints/provideSignatureHelp*/,461/*vs/nls!vs/editor/contrib/parameterHints/parameterHintsWidget*/,18/*vs/platform/contextkey/common/contextkey*/,51/*vs/platform/opener/common/opener*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,540/*vs/editor/contrib/parameterHints/parameterHintsModel*/,5/*vs/base/common/strings*/,318/*vs/css!vs/editor/contrib/parameterHints/parameterHints*/]), function (require, exports, dom, event_1, aria, scrollableElement_1, event_2, lifecycle_1, modeService_1, markdownRenderer_1, provideSignatureHelp_1, nls, contextkey_1, opener_1, colorRegistry_1, themeService_1, parameterHintsModel_1, strings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var $ = dom.$; var ParameterHintsWidget = /** @class */ (function (_super) { __extends(ParameterHintsWidget, _super); function ParameterHintsWidget(editor, contextKeyService, openerService, modeService) { var _this = _super.call(this) || this; _this.editor = editor; _this.renderDisposeables = _this._register(new lifecycle_1.DisposableStore()); _this.visible = false; _this.announcedLabel = null; // Editor.IContentWidget.allowEditorOverflow _this.allowEditorOverflow = true; _this.markdownRenderer = _this._register(new markdownRenderer_1.MarkdownRenderer(editor, modeService, openerService)); _this.model = _this._register(new parameterHintsModel_1.ParameterHintsModel(editor)); _this.keyVisible = provideSignatureHelp_1.Context.Visible.bindTo(contextKeyService); _this.keyMultipleSignatures = provideSignatureHelp_1.Context.MultipleSignatures.bindTo(contextKeyService); _this._register(_this.model.onChangedHints(function (newParameterHints) { if (newParameterHints) { _this.show(); _this.render(newParameterHints); } else { _this.hide(); } })); return _this; } ParameterHintsWidget.prototype.createParamaterHintDOMNodes = function () { var _this = this; var element = $('.editor-widget.parameter-hints-widget'); var wrapper = dom.append(element, $('.wrapper')); wrapper.tabIndex = -1; var controls = dom.append(wrapper, $('.controls')); var previous = dom.append(controls, $('.button.codicon.codicon-chevron-up')); var overloads = dom.append(controls, $('.overloads')); var next = dom.append(controls, $('.button.codicon.codicon-chevron-down')); var onPreviousClick = event_1.stop(event_1.domEvent(previous, 'click')); this._register(onPreviousClick(this.previous, this)); var onNextClick = event_1.stop(event_1.domEvent(next, 'click')); this._register(onNextClick(this.next, this)); var body = $('.body'); var scrollbar = new scrollableElement_1.DomScrollableElement(body, {}); this._register(scrollbar); wrapper.appendChild(scrollbar.getDomNode()); var signature = dom.append(body, $('.signature')); var docs = dom.append(body, $('.docs')); element.style.userSelect = 'text'; this.domNodes = { element: element, signature: signature, overloads: overloads, docs: docs, scrollbar: scrollbar, }; this.editor.addContentWidget(this); this.hide(); this._register(this.editor.onDidChangeCursorSelection(function (e) { if (_this.visible) { _this.editor.layoutContentWidget(_this); } })); var updateFont = function () { if (!_this.domNodes) { return; } var fontInfo = _this.editor.getOption(34 /* fontInfo */); _this.domNodes.element.style.fontSize = fontInfo.fontSize + "px"; }; updateFont(); this._register(event_2.Event.chain(this.editor.onDidChangeConfiguration.bind(this.editor)) .filter(function (e) { return e.hasChanged(34 /* fontInfo */); }) .on(updateFont, null)); this._register(this.editor.onDidLayoutChange(function (e) { return _this.updateMaxHeight(); })); this.updateMaxHeight(); }; ParameterHintsWidget.prototype.show = function () { var _this = this; if (this.visible) { return; } if (!this.domNodes) { this.createParamaterHintDOMNodes(); } this.keyVisible.set(true); this.visible = true; setTimeout(function () { if (_this.domNodes) { dom.addClass(_this.domNodes.element, 'visible'); } }, 100); this.editor.layoutContentWidget(this); }; ParameterHintsWidget.prototype.hide = function () { if (!this.visible) { return; } this.keyVisible.reset(); this.visible = false; this.announcedLabel = null; if (this.domNodes) { dom.removeClass(this.domNodes.element, 'visible'); } this.editor.layoutContentWidget(this); }; ParameterHintsWidget.prototype.getPosition = function () { if (this.visible) { return { position: this.editor.getPosition(), preference: [1 /* ABOVE */, 2 /* BELOW */] }; } return null; }; ParameterHintsWidget.prototype.render = function (hints) { if (!this.domNodes) { return; } var multiple = hints.signatures.length > 1; dom.toggleClass(this.domNodes.element, 'multiple', multiple); this.keyMultipleSignatures.set(multiple); this.domNodes.signature.innerHTML = ''; this.domNodes.docs.innerHTML = ''; var signature = hints.signatures[hints.activeSignature]; if (!signature) { return; } var code = dom.append(this.domNodes.signature, $('.code')); var hasParameters = signature.parameters.length > 0; var fontInfo = this.editor.getOption(34 /* fontInfo */); code.style.fontSize = fontInfo.fontSize + "px"; code.style.fontFamily = fontInfo.fontFamily; if (!hasParameters) { var label = dom.append(code, $('span')); label.textContent = signature.label; } else { this.renderParameters(code, signature, hints.activeParameter); } this.renderDisposeables.clear(); var activeParameter = signature.parameters[hints.activeParameter]; if (activeParameter && activeParameter.documentation) { var documentation = $('span.documentation'); if (typeof activeParameter.documentation === 'string') { documentation.textContent = activeParameter.documentation; } else { var renderedContents = this.markdownRenderer.render(activeParameter.documentation); dom.addClass(renderedContents.element, 'markdown-docs'); this.renderDisposeables.add(renderedContents); documentation.appendChild(renderedContents.element); } dom.append(this.domNodes.docs, $('p', {}, documentation)); } if (signature.documentation === undefined) { /** no op */ } else if (typeof signature.documentation === 'string') { dom.append(this.domNodes.docs, $('p', {}, signature.documentation)); } else { var renderedContents = this.markdownRenderer.render(signature.documentation); dom.addClass(renderedContents.element, 'markdown-docs'); this.renderDisposeables.add(renderedContents); dom.append(this.domNodes.docs, renderedContents.element); } var hasDocs = this.hasDocs(signature, activeParameter); dom.toggleClass(this.domNodes.signature, 'has-docs', hasDocs); dom.toggleClass(this.domNodes.docs, 'empty', !hasDocs); this.domNodes.overloads.textContent = strings_1.pad(hints.activeSignature + 1, hints.signatures.length.toString().length) + '/' + hints.signatures.length; if (activeParameter) { var labelToAnnounce = this.getParameterLabel(signature, hints.activeParameter); // Select method gets called on every user type while parameter hints are visible. // We do not want to spam the user with same announcements, so we only announce if the current parameter changed. if (this.announcedLabel !== labelToAnnounce) { aria.alert(nls.localize(0, null, labelToAnnounce)); this.announcedLabel = labelToAnnounce; } } this.editor.layoutContentWidget(this); this.domNodes.scrollbar.scanDomNode(); }; ParameterHintsWidget.prototype.hasDocs = function (signature, activeParameter) { if (activeParameter && typeof (activeParameter.documentation) === 'string' && activeParameter.documentation.length > 0) { return true; } if (activeParameter && typeof (activeParameter.documentation) === 'object' && activeParameter.documentation.value.length > 0) { return true; } if (typeof (signature.documentation) === 'string' && signature.documentation.length > 0) { return true; } if (typeof (signature.documentation) === 'object' && signature.documentation.value.length > 0) { return true; } return false; }; ParameterHintsWidget.prototype.renderParameters = function (parent, signature, currentParameter) { var _a = this.getParameterLabelOffsets(signature, currentParameter), start = _a[0], end = _a[1]; var beforeSpan = document.createElement('span'); beforeSpan.textContent = signature.label.substring(0, start); var paramSpan = document.createElement('span'); paramSpan.textContent = signature.label.substring(start, end); paramSpan.className = 'parameter active'; var afterSpan = document.createElement('span'); afterSpan.textContent = signature.label.substring(end); dom.append(parent, beforeSpan, paramSpan, afterSpan); }; ParameterHintsWidget.prototype.getParameterLabel = function (signature, paramIdx) { var param = signature.parameters[paramIdx]; if (typeof param.label === 'string') { return param.label; } else { return signature.label.substring(param.label[0], param.label[1]); } }; ParameterHintsWidget.prototype.getParameterLabelOffsets = function (signature, paramIdx) { var param = signature.parameters[paramIdx]; if (!param) { return [0, 0]; } else if (Array.isArray(param.label)) { return param.label; } else { var idx = signature.label.lastIndexOf(param.label); return idx >= 0 ? [idx, idx + param.label.length] : [0, 0]; } }; ParameterHintsWidget.prototype.next = function () { this.editor.focus(); this.model.next(); }; ParameterHintsWidget.prototype.previous = function () { this.editor.focus(); this.model.previous(); }; ParameterHintsWidget.prototype.cancel = function () { this.model.cancel(); }; ParameterHintsWidget.prototype.getDomNode = function () { if (!this.domNodes) { this.createParamaterHintDOMNodes(); } return this.domNodes.element; }; ParameterHintsWidget.prototype.getId = function () { return ParameterHintsWidget.ID; }; ParameterHintsWidget.prototype.trigger = function (context) { this.model.trigger(context, 0); }; ParameterHintsWidget.prototype.updateMaxHeight = function () { if (!this.domNodes) { return; } var height = Math.max(this.editor.getLayoutInfo().height / 4, 250); var maxHeight = height + "px"; this.domNodes.element.style.maxHeight = maxHeight; var wrapper = this.domNodes.element.getElementsByClassName('wrapper'); if (wrapper.length) { wrapper[0].style.maxHeight = maxHeight; } }; ParameterHintsWidget.ID = 'editor.widget.parameterHintsWidget'; ParameterHintsWidget = __decorate([ __param(1, contextkey_1.IContextKeyService), __param(2, opener_1.IOpenerService), __param(3, modeService_1.IModeService) ], ParameterHintsWidget); return ParameterHintsWidget; }(lifecycle_1.Disposable)); exports.ParameterHintsWidget = ParameterHintsWidget; themeService_1.registerThemingParticipant(function (theme, collector) { var border = theme.getColor(colorRegistry_1.editorHoverBorder); if (border) { var borderWidth = theme.type === themeService_1.HIGH_CONTRAST ? 2 : 1; collector.addRule(".monaco-editor .parameter-hints-widget { border: " + borderWidth + "px solid " + border + "; }"); collector.addRule(".monaco-editor .parameter-hints-widget.multiple .body { border-left: 1px solid " + border.transparent(0.5) + "; }"); collector.addRule(".monaco-editor .parameter-hints-widget .signature.has-docs { border-bottom: 1px solid " + border.transparent(0.5) + "; }"); } var background = theme.getColor(colorRegistry_1.editorHoverBackground); if (background) { collector.addRule(".monaco-editor .parameter-hints-widget { background-color: " + background + "; }"); } var link = theme.getColor(colorRegistry_1.textLinkForeground); if (link) { collector.addRule(".monaco-editor .parameter-hints-widget a { color: " + link + "; }"); } var foreground = theme.getColor(colorRegistry_1.editorHoverForeground); if (foreground) { collector.addRule(".monaco-editor .parameter-hints-widget { color: " + foreground + "; }"); } var codeBackground = theme.getColor(colorRegistry_1.textCodeBlockBackground); if (codeBackground) { collector.addRule(".monaco-editor .parameter-hints-widget code { background-color: " + codeBackground + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[582/*vs/editor/contrib/parameterHints/parameterHints*/], __M([0/*require*/,1/*exports*/,460/*vs/nls!vs/editor/contrib/parameterHints/parameterHints*/,2/*vs/base/common/lifecycle*/,11/*vs/platform/instantiation/common/instantiation*/,23/*vs/editor/common/editorContextKeys*/,18/*vs/platform/contextkey/common/contextkey*/,12/*vs/editor/browser/editorExtensions*/,581/*vs/editor/contrib/parameterHints/parameterHintsWidget*/,165/*vs/editor/contrib/parameterHints/provideSignatureHelp*/,17/*vs/editor/common/modes*/]), function (require, exports, nls, lifecycle_1, instantiation_1, editorContextKeys_1, contextkey_1, editorExtensions_1, parameterHintsWidget_1, provideSignatureHelp_1, modes) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ParameterHintsController = /** @class */ (function (_super) { __extends(ParameterHintsController, _super); function ParameterHintsController(editor, instantiationService) { var _this = _super.call(this) || this; _this.editor = editor; _this.widget = _this._register(instantiationService.createInstance(parameterHintsWidget_1.ParameterHintsWidget, _this.editor)); return _this; } ParameterHintsController.get = function (editor) { return editor.getContribution(ParameterHintsController.ID); }; ParameterHintsController.prototype.cancel = function () { this.widget.cancel(); }; ParameterHintsController.prototype.previous = function () { this.widget.previous(); }; ParameterHintsController.prototype.next = function () { this.widget.next(); }; ParameterHintsController.prototype.trigger = function (context) { this.widget.trigger(context); }; ParameterHintsController.ID = 'editor.controller.parameterHints'; ParameterHintsController = __decorate([ __param(1, instantiation_1.IInstantiationService) ], ParameterHintsController); return ParameterHintsController; }(lifecycle_1.Disposable)); var TriggerParameterHintsAction = /** @class */ (function (_super) { __extends(TriggerParameterHintsAction, _super); function TriggerParameterHintsAction() { return _super.call(this, { id: 'editor.action.triggerParameterHints', label: nls.localize(0, null), alias: 'Trigger Parameter Hints', precondition: editorContextKeys_1.EditorContextKeys.hasSignatureHelpProvider, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 10 /* Space */, weight: 100 /* EditorContrib */ } }) || this; } TriggerParameterHintsAction.prototype.run = function (accessor, editor) { var controller = ParameterHintsController.get(editor); if (controller) { controller.trigger({ triggerKind: modes.SignatureHelpTriggerKind.Invoke }); } }; return TriggerParameterHintsAction; }(editorExtensions_1.EditorAction)); exports.TriggerParameterHintsAction = TriggerParameterHintsAction; editorExtensions_1.registerEditorContribution(ParameterHintsController.ID, ParameterHintsController); editorExtensions_1.registerEditorAction(TriggerParameterHintsAction); var weight = 100 /* EditorContrib */ + 75; var ParameterHintsCommand = editorExtensions_1.EditorCommand.bindToContribution(ParameterHintsController.get); editorExtensions_1.registerEditorCommand(new ParameterHintsCommand({ id: 'closeParameterHints', precondition: provideSignatureHelp_1.Context.Visible, handler: function (x) { return x.cancel(); }, kbOpts: { weight: weight, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 9 /* Escape */, secondary: [1024 /* Shift */ | 9 /* Escape */] } })); editorExtensions_1.registerEditorCommand(new ParameterHintsCommand({ id: 'showPrevParameterHint', precondition: contextkey_1.ContextKeyExpr.and(provideSignatureHelp_1.Context.Visible, provideSignatureHelp_1.Context.MultipleSignatures), handler: function (x) { return x.previous(); }, kbOpts: { weight: weight, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 16 /* UpArrow */, secondary: [512 /* Alt */ | 16 /* UpArrow */], mac: { primary: 16 /* UpArrow */, secondary: [512 /* Alt */ | 16 /* UpArrow */, 256 /* WinCtrl */ | 46 /* KEY_P */] } } })); editorExtensions_1.registerEditorCommand(new ParameterHintsCommand({ id: 'showNextParameterHint', precondition: contextkey_1.ContextKeyExpr.and(provideSignatureHelp_1.Context.Visible, provideSignatureHelp_1.Context.MultipleSignatures), handler: function (x) { return x.next(); }, kbOpts: { weight: weight, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 18 /* DownArrow */, secondary: [512 /* Alt */ | 18 /* DownArrow */], mac: { primary: 18 /* DownArrow */, secondary: [512 /* Alt */ | 18 /* DownArrow */, 256 /* WinCtrl */ | 44 /* KEY_N */] } } })); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[123/*vs/editor/contrib/peekView/peekView*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,70/*vs/base/browser/ui/actionbar/actionbar*/,55/*vs/base/common/actions*/,27/*vs/base/common/color*/,4/*vs/base/common/event*/,31/*vs/base/common/objects*/,5/*vs/base/common/strings*/,32/*vs/editor/browser/services/codeEditorService*/,167/*vs/editor/browser/widget/embeddedCodeEditorWidget*/,493/*vs/editor/contrib/zoneWidget/zoneWidget*/,462/*vs/nls!vs/editor/contrib/peekView/peekView*/,18/*vs/platform/contextkey/common/contextkey*/,11/*vs/platform/instantiation/common/instantiation*/,83/*vs/platform/instantiation/common/extensions*/,12/*vs/editor/browser/editorExtensions*/,20/*vs/platform/theme/common/colorRegistry*/,319/*vs/css!vs/editor/contrib/peekView/media/peekViewWidget*/]), function (require, exports, dom, actionbar_1, actions_1, color_1, event_1, objects, strings, codeEditorService_1, embeddedCodeEditorWidget_1, zoneWidget_1, nls, contextkey_1, instantiation_1, extensions_1, editorExtensions_1, colorRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IPeekViewService = instantiation_1.createDecorator('IPeekViewService'); extensions_1.registerSingleton(exports.IPeekViewService, /** @class */ (function () { function class_1() { this._widgets = new Map(); } class_1.prototype.addExclusiveWidget = function (editor, widget) { var _this = this; var existing = this._widgets.get(editor); if (existing) { existing.listener.dispose(); existing.widget.dispose(); } var remove = function () { var data = _this._widgets.get(editor); if (data && data.widget === widget) { data.listener.dispose(); _this._widgets.delete(editor); } }; this._widgets.set(editor, { widget: widget, listener: widget.onDidClose(remove) }); }; return class_1; }())); var PeekContext; (function (PeekContext) { PeekContext.inPeekEditor = new contextkey_1.RawContextKey('inReferenceSearchEditor', true); PeekContext.notInPeekEditor = PeekContext.inPeekEditor.toNegated(); })(PeekContext = exports.PeekContext || (exports.PeekContext = {})); var PeekContextController = /** @class */ (function () { function PeekContextController(editor, contextKeyService) { if (editor instanceof embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget) { PeekContext.inPeekEditor.bindTo(contextKeyService); } } PeekContextController.prototype.dispose = function () { }; PeekContextController.ID = 'editor.contrib.referenceController'; PeekContextController = __decorate([ __param(1, contextkey_1.IContextKeyService) ], PeekContextController); return PeekContextController; }()); editorExtensions_1.registerEditorContribution(PeekContextController.ID, PeekContextController); function getOuterEditor(accessor) { var editor = accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor(); if (editor instanceof embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget) { return editor.getParentEditor(); } return editor; } exports.getOuterEditor = getOuterEditor; var defaultOptions = { headerBackgroundColor: color_1.Color.white, primaryHeadingColor: color_1.Color.fromHex('#333333'), secondaryHeadingColor: color_1.Color.fromHex('#6c6c6cb3') }; var PeekViewWidget = /** @class */ (function (_super) { __extends(PeekViewWidget, _super); function PeekViewWidget(editor, options) { if (options === void 0) { options = {}; } var _this = _super.call(this, editor, options) || this; _this._onDidClose = new event_1.Emitter(); _this.onDidClose = _this._onDidClose.event; objects.mixin(_this.options, defaultOptions, false); return _this; } PeekViewWidget.prototype.dispose = function () { _super.prototype.dispose.call(this); this._onDidClose.fire(this); }; PeekViewWidget.prototype.style = function (styles) { var options = this.options; if (styles.headerBackgroundColor) { options.headerBackgroundColor = styles.headerBackgroundColor; } if (styles.primaryHeadingColor) { options.primaryHeadingColor = styles.primaryHeadingColor; } if (styles.secondaryHeadingColor) { options.secondaryHeadingColor = styles.secondaryHeadingColor; } _super.prototype.style.call(this, styles); }; PeekViewWidget.prototype._applyStyles = function () { _super.prototype._applyStyles.call(this); var options = this.options; if (this._headElement && options.headerBackgroundColor) { this._headElement.style.backgroundColor = options.headerBackgroundColor.toString(); } if (this._primaryHeading && options.primaryHeadingColor) { this._primaryHeading.style.color = options.primaryHeadingColor.toString(); } if (this._secondaryHeading && options.secondaryHeadingColor) { this._secondaryHeading.style.color = options.secondaryHeadingColor.toString(); } if (this._bodyElement && options.frameColor) { this._bodyElement.style.borderColor = options.frameColor.toString(); } }; PeekViewWidget.prototype._fillContainer = function (container) { this.setCssClass('peekview-widget'); this._headElement = dom.$('.head'); this._bodyElement = dom.$('.body'); this._fillHead(this._headElement); this._fillBody(this._bodyElement); container.appendChild(this._headElement); container.appendChild(this._bodyElement); }; PeekViewWidget.prototype._fillHead = function (container) { var _this = this; var titleElement = dom.$('.peekview-title'); dom.append(this._headElement, titleElement); dom.addStandardDisposableListener(titleElement, 'click', function (event) { return _this._onTitleClick(event); }); this._fillTitleIcon(titleElement); this._primaryHeading = dom.$('span.filename'); this._secondaryHeading = dom.$('span.dirname'); this._metaHeading = dom.$('span.meta'); dom.append(titleElement, this._primaryHeading, this._secondaryHeading, this._metaHeading); var actionsContainer = dom.$('.peekview-actions'); dom.append(this._headElement, actionsContainer); var actionBarOptions = this._getActionBarOptions(); this._actionbarWidget = new actionbar_1.ActionBar(actionsContainer, actionBarOptions); this._disposables.add(this._actionbarWidget); this._actionbarWidget.push(new actions_1.Action('peekview.close', nls.localize(0, null), 'codicon-close', true, function () { _this.dispose(); return Promise.resolve(); }), { label: false, icon: true }); }; PeekViewWidget.prototype._fillTitleIcon = function (container) { }; PeekViewWidget.prototype._getActionBarOptions = function () { return {}; }; PeekViewWidget.prototype._onTitleClick = function (event) { // implement me }; PeekViewWidget.prototype.setTitle = function (primaryHeading, secondaryHeading) { if (this._primaryHeading && this._secondaryHeading) { this._primaryHeading.innerHTML = strings.escape(primaryHeading); this._primaryHeading.setAttribute('aria-label', primaryHeading); if (secondaryHeading) { this._secondaryHeading.innerHTML = strings.escape(secondaryHeading); } else { dom.clearNode(this._secondaryHeading); } } }; PeekViewWidget.prototype.setMetaTitle = function (value) { if (this._metaHeading) { if (value) { this._metaHeading.innerHTML = strings.escape(value); dom.show(this._metaHeading); } else { dom.hide(this._metaHeading); } } }; PeekViewWidget.prototype._doLayout = function (heightInPixel, widthInPixel) { if (!this._isShowing && heightInPixel < 0) { // Looks like the view zone got folded away! this.dispose(); return; } var headHeight = Math.ceil(this.editor.getOption(49 /* lineHeight */) * 1.2); var bodyHeight = Math.round(heightInPixel - (headHeight + 2 /* the border-top/bottom width*/)); this._doLayoutHead(headHeight, widthInPixel); this._doLayoutBody(bodyHeight, widthInPixel); }; PeekViewWidget.prototype._doLayoutHead = function (heightInPixel, widthInPixel) { if (this._headElement) { this._headElement.style.height = heightInPixel + "px"; this._headElement.style.lineHeight = this._headElement.style.height; } }; PeekViewWidget.prototype._doLayoutBody = function (heightInPixel, widthInPixel) { if (this._bodyElement) { this._bodyElement.style.height = heightInPixel + "px"; } }; return PeekViewWidget; }(zoneWidget_1.ZoneWidget)); exports.PeekViewWidget = PeekViewWidget; exports.peekViewTitleBackground = colorRegistry_1.registerColor('peekViewTitle.background', { dark: '#1E1E1E', light: '#FFFFFF', hc: '#0C141F' }, nls.localize(1, null)); exports.peekViewTitleForeground = colorRegistry_1.registerColor('peekViewTitleLabel.foreground', { dark: '#FFFFFF', light: '#333333', hc: '#FFFFFF' }, nls.localize(2, null)); exports.peekViewTitleInfoForeground = colorRegistry_1.registerColor('peekViewTitleDescription.foreground', { dark: '#ccccccb3', light: '#616161e6', hc: '#FFFFFF99' }, nls.localize(3, null)); exports.peekViewBorder = colorRegistry_1.registerColor('peekView.border', { dark: '#007acc', light: '#007acc', hc: colorRegistry_1.contrastBorder }, nls.localize(4, null)); exports.peekViewResultsBackground = colorRegistry_1.registerColor('peekViewResult.background', { dark: '#252526', light: '#F3F3F3', hc: color_1.Color.black }, nls.localize(5, null)); exports.peekViewResultsMatchForeground = colorRegistry_1.registerColor('peekViewResult.lineForeground', { dark: '#bbbbbb', light: '#646465', hc: color_1.Color.white }, nls.localize(6, null)); exports.peekViewResultsFileForeground = colorRegistry_1.registerColor('peekViewResult.fileForeground', { dark: color_1.Color.white, light: '#1E1E1E', hc: color_1.Color.white }, nls.localize(7, null)); exports.peekViewResultsSelectionBackground = colorRegistry_1.registerColor('peekViewResult.selectionBackground', { dark: '#3399ff33', light: '#3399ff33', hc: null }, nls.localize(8, null)); exports.peekViewResultsSelectionForeground = colorRegistry_1.registerColor('peekViewResult.selectionForeground', { dark: color_1.Color.white, light: '#6C6C6C', hc: color_1.Color.white }, nls.localize(9, null)); exports.peekViewEditorBackground = colorRegistry_1.registerColor('peekViewEditor.background', { dark: '#001F33', light: '#F2F8FC', hc: color_1.Color.black }, nls.localize(10, null)); exports.peekViewEditorGutterBackground = colorRegistry_1.registerColor('peekViewEditorGutter.background', { dark: exports.peekViewEditorBackground, light: exports.peekViewEditorBackground, hc: exports.peekViewEditorBackground }, nls.localize(11, null)); exports.peekViewResultsMatchHighlight = colorRegistry_1.registerColor('peekViewResult.matchHighlightBackground', { dark: '#ea5c004d', light: '#ea5c004d', hc: null }, nls.localize(12, null)); exports.peekViewEditorMatchHighlight = colorRegistry_1.registerColor('peekViewEditor.matchHighlightBackground', { dark: '#ff8f0099', light: '#f5d802de', hc: null }, nls.localize(13, null)); exports.peekViewEditorMatchHighlightBorder = colorRegistry_1.registerColor('peekViewEditor.matchHighlightBorder', { dark: null, light: null, hc: colorRegistry_1.activeContrastBorder }, nls.localize(14, 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[583/*vs/editor/contrib/rename/renameInputField*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,464/*vs/nls!vs/editor/contrib/rename/renameInputField*/,18/*vs/platform/contextkey/common/contextkey*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,34/*vs/platform/keybinding/common/keybinding*/,6/*vs/base/browser/dom*/,320/*vs/css!vs/editor/contrib/rename/renameInputField*/]), function (require, exports, lifecycle_1, position_1, range_1, nls_1, contextkey_1, colorRegistry_1, themeService_1, keybinding_1, dom_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CONTEXT_RENAME_INPUT_VISIBLE = new contextkey_1.RawContextKey('renameInputVisible', false); var RenameInputField = /** @class */ (function () { function RenameInputField(_editor, _acceptKeybindings, _themeService, _keybindingService, contextKeyService) { var _this = this; this._editor = _editor; this._acceptKeybindings = _acceptKeybindings; this._themeService = _themeService; this._keybindingService = _keybindingService; this._disposables = new lifecycle_1.DisposableStore(); this.allowEditorOverflow = true; this._visibleContextKey = exports.CONTEXT_RENAME_INPUT_VISIBLE.bindTo(contextKeyService); this._editor.addContentWidget(this); this._disposables.add(this._editor.onDidChangeConfiguration(function (e) { if (e.hasChanged(34 /* fontInfo */)) { _this._updateFont(); } })); this._disposables.add(_themeService.onThemeChange(this._updateStyles, this)); } RenameInputField.prototype.dispose = function () { this._disposables.dispose(); this._editor.removeContentWidget(this); }; RenameInputField.prototype.getId = function () { return '__renameInputWidget'; }; RenameInputField.prototype.getDomNode = function () { var _this = this; if (!this._domNode) { this._domNode = document.createElement('div'); this._domNode.className = 'monaco-editor rename-box'; this._input = document.createElement('input'); this._input.className = 'rename-input'; this._input.type = 'text'; this._input.setAttribute('aria-label', nls_1.localize(0, null)); this._domNode.appendChild(this._input); this._label = document.createElement('div'); this._label.className = 'rename-label'; this._domNode.appendChild(this._label); var updateLabel = function () { var _a, _b; var _c = _this._acceptKeybindings, accept = _c[0], preview = _c[1]; _this._keybindingService.lookupKeybinding(accept); _this._label.innerText = nls_1.localize(1, null, (_a = _this._keybindingService.lookupKeybinding(accept)) === null || _a === void 0 ? void 0 : _a.getLabel(), (_b = _this._keybindingService.lookupKeybinding(preview)) === null || _b === void 0 ? void 0 : _b.getLabel()); }; updateLabel(); this._disposables.add(this._keybindingService.onDidUpdateKeybindings(updateLabel)); this._updateFont(); this._updateStyles(this._themeService.getTheme()); } return this._domNode; }; RenameInputField.prototype._updateStyles = function (theme) { var _a, _b, _c, _d; if (!this._input || !this._domNode) { return; } var widgetShadowColor = theme.getColor(colorRegistry_1.widgetShadow); this._domNode.style.backgroundColor = String((_a = theme.getColor(colorRegistry_1.editorWidgetBackground)) !== null && _a !== void 0 ? _a : ''); this._domNode.style.boxShadow = widgetShadowColor ? " 0 2px 8px " + widgetShadowColor : ''; this._domNode.style.color = String((_b = theme.getColor(colorRegistry_1.inputForeground)) !== null && _b !== void 0 ? _b : ''); this._input.style.backgroundColor = String((_c = theme.getColor(colorRegistry_1.inputBackground)) !== null && _c !== void 0 ? _c : ''); // this._input.style.color = String(theme.getColor(inputForeground) ?? ''); var border = theme.getColor(colorRegistry_1.inputBorder); this._input.style.borderWidth = border ? '1px' : '0px'; this._input.style.borderStyle = border ? 'solid' : 'none'; this._input.style.borderColor = (_d = border === null || border === void 0 ? void 0 : border.toString()) !== null && _d !== void 0 ? _d : 'none'; }; RenameInputField.prototype._updateFont = function () { if (!this._input || !this._label) { return; } var fontInfo = this._editor.getOption(34 /* fontInfo */); this._input.style.fontFamily = fontInfo.fontFamily; this._input.style.fontWeight = fontInfo.fontWeight; this._input.style.fontSize = fontInfo.fontSize + "px"; this._label.style.fontSize = fontInfo.fontSize * 0.8 + "px"; }; RenameInputField.prototype.getPosition = function () { if (!this._visible) { return null; } return { position: this._position, preference: [2 /* BELOW */, 1 /* ABOVE */] }; }; RenameInputField.prototype.acceptInput = function (wantsPreview) { if (this._currentAcceptInput) { this._currentAcceptInput(wantsPreview); } }; RenameInputField.prototype.cancelInput = function (focusEditor) { if (this._currentCancelInput) { this._currentCancelInput(focusEditor); } }; RenameInputField.prototype.getInput = function (where, value, selectionStart, selectionEnd, supportPreview) { var _this = this; dom_1.toggleClass(this._domNode, 'preview', supportPreview); this._position = new position_1.Position(where.startLineNumber, where.startColumn); this._input.value = value; this._input.setAttribute('selectionStart', selectionStart.toString()); this._input.setAttribute('selectionEnd', selectionEnd.toString()); this._input.size = Math.max((where.endColumn - where.startColumn) * 1.1, 20); var disposeOnDone = new lifecycle_1.DisposableStore(); return new Promise(function (resolve) { _this._currentCancelInput = function (focusEditor) { _this._currentAcceptInput = undefined; _this._currentCancelInput = undefined; resolve(focusEditor); return true; }; _this._currentAcceptInput = function (wantsPreview) { if (_this._input.value.trim().length === 0 || _this._input.value === value) { // empty or whitespace only or not changed _this.cancelInput(true); return; } _this._currentAcceptInput = undefined; _this._currentCancelInput = undefined; resolve({ newName: _this._input.value, wantsPreview: supportPreview && wantsPreview }); }; var onCursorChanged = function () { var editorPosition = _this._editor.getPosition(); if (!editorPosition || !range_1.Range.containsPosition(where, editorPosition)) { _this.cancelInput(true); } }; disposeOnDone.add(_this._editor.onDidChangeCursorSelection(onCursorChanged)); disposeOnDone.add(_this._editor.onDidBlurEditorWidget(function () { return _this.cancelInput(false); })); _this._show(); }).finally(function () { disposeOnDone.dispose(); _this._hide(); }); }; RenameInputField.prototype._show = function () { var _this = this; this._editor.revealLineInCenterIfOutsideViewport(this._position.lineNumber, 0 /* Smooth */); this._visible = true; this._visibleContextKey.set(true); this._editor.layoutContentWidget(this); setTimeout(function () { _this._input.focus(); _this._input.setSelectionRange(parseInt(_this._input.getAttribute('selectionStart')), parseInt(_this._input.getAttribute('selectionEnd'))); }, 100); }; RenameInputField.prototype._hide = function () { this._visible = false; this._visibleContextKey.reset(); this._editor.layoutContentWidget(this); }; RenameInputField = __decorate([ __param(2, themeService_1.IThemeService), __param(3, keybinding_1.IKeybindingService), __param(4, contextkey_1.IContextKeyService) ], RenameInputField); return RenameInputField; }()); exports.RenameInputField = RenameInputField; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[584/*vs/editor/contrib/rename/rename*/], __M([0/*require*/,1/*exports*/,463/*vs/nls!vs/editor/contrib/rename/rename*/,10/*vs/base/common/errors*/,18/*vs/platform/contextkey/common/contextkey*/,73/*vs/platform/progress/common/progress*/,12/*vs/editor/browser/editorExtensions*/,23/*vs/editor/common/editorContextKeys*/,583/*vs/editor/contrib/rename/renameInputField*/,17/*vs/editor/common/modes*/,13/*vs/editor/common/core/position*/,50/*vs/base/browser/ui/aria/aria*/,3/*vs/editor/common/core/range*/,122/*vs/editor/contrib/message/messageController*/,67/*vs/editor/browser/core/editorState*/,35/*vs/platform/notification/common/notification*/,156/*vs/editor/browser/services/bulkEditService*/,25/*vs/base/common/uri*/,32/*vs/editor/browser/services/codeEditorService*/,26/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,15/*vs/base/common/async*/,21/*vs/base/common/types*/,95/*vs/platform/log/common/log*/,11/*vs/platform/instantiation/common/instantiation*/,42/*vs/platform/registry/common/platform*/,85/*vs/platform/configuration/common/configurationRegistry*/,114/*vs/editor/common/services/textResourceConfigurationService*/]), function (require, exports, nls, errors_1, contextkey_1, progress_1, editorExtensions_1, editorContextKeys_1, renameInputField_1, modes_1, position_1, aria_1, range_1, messageController_1, editorState_1, notification_1, bulkEditService_1, uri_1, codeEditorService_1, cancellation_1, lifecycle_1, async_1, types_1, log_1, instantiation_1, platform_1, configurationRegistry_1, textResourceConfigurationService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var RenameSkeleton = /** @class */ (function () { function RenameSkeleton(model, position) { this.model = model; this.position = position; this._providers = modes_1.RenameProviderRegistry.ordered(model); } RenameSkeleton.prototype.hasProvider = function () { return this._providers.length > 0; }; RenameSkeleton.prototype.resolveRenameLocation = function (token) { return __awaiter(this, void 0, void 0, function () { var firstProvider, res, _a, word; return __generator(this, function (_b) { switch (_b.label) { case 0: firstProvider = this._providers[0]; if (!firstProvider) { return [2 /*return*/, undefined]; } if (!firstProvider.resolveRenameLocation) return [3 /*break*/, 2]; _a = types_1.withNullAsUndefined; return [4 /*yield*/, firstProvider.resolveRenameLocation(this.model, this.position, token)]; case 1: res = _a.apply(void 0, [_b.sent()]); _b.label = 2; case 2: if (!res) { word = this.model.getWordAtPosition(this.position); if (word) { return [2 /*return*/, { range: new range_1.Range(this.position.lineNumber, word.startColumn, this.position.lineNumber, word.endColumn), text: word.word }]; } } return [2 /*return*/, res]; } }); }); }; RenameSkeleton.prototype.provideRenameEdits = function (newName, i, rejects, token) { return __awaiter(this, void 0, void 0, function () { var provider, result; return __generator(this, function (_a) { switch (_a.label) { case 0: provider = this._providers[i]; if (!provider) { return [2 /*return*/, { edits: [], rejectReason: rejects.join('\n') }]; } return [4 /*yield*/, provider.provideRenameEdits(this.model, this.position, newName, token)]; case 1: result = _a.sent(); if (!result) { return [2 /*return*/, this.provideRenameEdits(newName, i + 1, rejects.concat(nls.localize(0, null)), token)]; } else if (result.rejectReason) { return [2 /*return*/, this.provideRenameEdits(newName, i + 1, rejects.concat(result.rejectReason), token)]; } return [2 /*return*/, result]; } }); }); }; return RenameSkeleton; }()); function rename(model, position, newName) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, new RenameSkeleton(model, position).provideRenameEdits(newName, 0, [], cancellation_1.CancellationToken.None)]; }); }); } exports.rename = rename; // --- register actions and commands var RenameController = /** @class */ (function () { function RenameController(editor, _instaService, _notificationService, _bulkEditService, _progressService, _logService, _configService) { var _this = this; this.editor = editor; this._instaService = _instaService; this._notificationService = _notificationService; this._bulkEditService = _bulkEditService; this._progressService = _progressService; this._logService = _logService; this._configService = _configService; this._dispoableStore = new lifecycle_1.DisposableStore(); this._cts = new cancellation_1.CancellationTokenSource(); this._renameInputField = this._dispoableStore.add(new async_1.IdleValue(function () { return _this._dispoableStore.add(_this._instaService.createInstance(renameInputField_1.RenameInputField, _this.editor, ['acceptRenameInput', 'acceptRenameInputWithPreview'])); })); } RenameController.get = function (editor) { return editor.getContribution(RenameController.ID); }; RenameController.prototype.dispose = function () { this._dispoableStore.dispose(); this._cts.dispose(true); }; RenameController.prototype.run = function () { return __awaiter(this, void 0, void 0, function () { var position, skeleton, loc, resolveLocationOperation, e_1, selection, selectionStart, selectionEnd, supportPreview, inputFieldResult, renameOperation; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: this._cts.dispose(true); if (!this.editor.hasModel()) { return [2 /*return*/, undefined]; } position = this.editor.getPosition(); skeleton = new RenameSkeleton(this.editor.getModel(), position); if (!skeleton.hasProvider()) { return [2 /*return*/, undefined]; } this._cts = new editorState_1.EditorStateCancellationTokenSource(this.editor, 4 /* Position */ | 1 /* Value */); _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); resolveLocationOperation = skeleton.resolveRenameLocation(this._cts.token); this._progressService.showWhile(resolveLocationOperation, 250); return [4 /*yield*/, resolveLocationOperation]; case 2: loc = _a.sent(); return [3 /*break*/, 4]; case 3: e_1 = _a.sent(); messageController_1.MessageController.get(this.editor).showMessage(e_1 || nls.localize(1, null), position); return [2 /*return*/, undefined]; case 4: if (!loc) { return [2 /*return*/, undefined]; } if (loc.rejectReason) { messageController_1.MessageController.get(this.editor).showMessage(loc.rejectReason, position); return [2 /*return*/, undefined]; } if (this._cts.token.isCancellationRequested) { return [2 /*return*/, undefined]; } selection = this.editor.getSelection(); selectionStart = 0; selectionEnd = loc.text.length; if (!range_1.Range.isEmpty(selection) && !range_1.Range.spansMultipleLines(selection) && range_1.Range.containsRange(loc.range, selection)) { selectionStart = Math.max(0, selection.startColumn - loc.range.startColumn); selectionEnd = Math.min(loc.range.endColumn, selection.endColumn) - loc.range.startColumn; } supportPreview = this._bulkEditService.hasPreviewHandler() && this._configService.getValue(this.editor.getModel().uri, 'editor.rename.enablePreview'); return [4 /*yield*/, this._renameInputField.getValue().getInput(loc.range, loc.text, selectionStart, selectionEnd, supportPreview)]; case 5: inputFieldResult = _a.sent(); // no result, only hint to focus the editor or not if (typeof inputFieldResult === 'boolean') { if (inputFieldResult) { this.editor.focus(); } return [2 /*return*/, undefined]; } this.editor.focus(); renameOperation = async_1.raceCancellation(skeleton.provideRenameEdits(inputFieldResult.newName, 0, [], this._cts.token), this._cts.token).then(function (renameResult) { return __awaiter(_this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { if (!renameResult || !this.editor.hasModel()) { return [2 /*return*/]; } if (renameResult.rejectReason) { this._notificationService.info(renameResult.rejectReason); return [2 /*return*/]; } this._bulkEditService.apply(renameResult, { editor: this.editor, showPreview: inputFieldResult.wantsPreview, label: nls.localize(2, null, loc === null || loc === void 0 ? void 0 : loc.text) }).then(function (result) { if (result.ariaSummary) { aria_1.alert(nls.localize(3, null, loc.text, inputFieldResult.newName, result.ariaSummary)); } }).catch(function (err) { _this._notificationService.error(nls.localize(4, null)); _this._logService.error(err); }); return [2 /*return*/]; }); }); }, function (err) { _this._notificationService.error(nls.localize(5, null)); _this._logService.error(err); }); this._progressService.showWhile(renameOperation, 250); return [2 /*return*/, renameOperation]; } }); }); }; RenameController.prototype.acceptRenameInput = function (wantsPreview) { this._renameInputField.getValue().acceptInput(wantsPreview); }; RenameController.prototype.cancelRenameInput = function () { this._renameInputField.getValue().cancelInput(true); }; RenameController.ID = 'editor.contrib.renameController'; RenameController = __decorate([ __param(1, instantiation_1.IInstantiationService), __param(2, notification_1.INotificationService), __param(3, bulkEditService_1.IBulkEditService), __param(4, progress_1.IEditorProgressService), __param(5, log_1.ILogService), __param(6, textResourceConfigurationService_1.ITextResourceConfigurationService) ], RenameController); return RenameController; }()); // ---- action implementation var RenameAction = /** @class */ (function (_super) { __extends(RenameAction, _super); function RenameAction() { return _super.call(this, { id: 'editor.action.rename', label: nls.localize(6, null), alias: 'Rename Symbol', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasRenameProvider), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 60 /* F2 */, weight: 100 /* EditorContrib */ }, contextMenuOpts: { group: '1_modification', order: 1.1 } }) || this; } RenameAction.prototype.runCommand = function (accessor, args) { var _this = this; var editorService = accessor.get(codeEditorService_1.ICodeEditorService); var _a = Array.isArray(args) && args || [undefined, undefined], uri = _a[0], pos = _a[1]; if (uri_1.URI.isUri(uri) && position_1.Position.isIPosition(pos)) { return editorService.openCodeEditor({ resource: uri }, editorService.getActiveCodeEditor()).then(function (editor) { if (!editor) { return; } editor.setPosition(pos); editor.invokeWithinContext(function (accessor) { _this.reportTelemetry(accessor, editor); return _this.run(accessor, editor); }); }, errors_1.onUnexpectedError); } return _super.prototype.runCommand.call(this, accessor, args); }; RenameAction.prototype.run = function (accessor, editor) { var controller = RenameController.get(editor); if (controller) { return controller.run(); } return Promise.resolve(); }; return RenameAction; }(editorExtensions_1.EditorAction)); exports.RenameAction = RenameAction; editorExtensions_1.registerEditorContribution(RenameController.ID, RenameController); editorExtensions_1.registerEditorAction(RenameAction); var RenameCommand = editorExtensions_1.EditorCommand.bindToContribution(RenameController.get); editorExtensions_1.registerEditorCommand(new RenameCommand({ id: 'acceptRenameInput', precondition: renameInputField_1.CONTEXT_RENAME_INPUT_VISIBLE, handler: function (x) { return x.acceptRenameInput(false); }, kbOpts: { weight: 100 /* EditorContrib */ + 99, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 3 /* Enter */ } })); editorExtensions_1.registerEditorCommand(new RenameCommand({ id: 'acceptRenameInputWithPreview', precondition: contextkey_1.ContextKeyExpr.and(renameInputField_1.CONTEXT_RENAME_INPUT_VISIBLE, contextkey_1.ContextKeyExpr.has('config.editor.rename.enablePreview')), handler: function (x) { return x.acceptRenameInput(true); }, kbOpts: { weight: 100 /* EditorContrib */ + 99, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 1024 /* Shift */ + 3 /* Enter */ } })); editorExtensions_1.registerEditorCommand(new RenameCommand({ id: 'cancelRenameInput', precondition: renameInputField_1.CONTEXT_RENAME_INPUT_VISIBLE, handler: function (x) { return x.cancelRenameInput(); }, kbOpts: { weight: 100 /* EditorContrib */ + 99, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 9 /* Escape */, secondary: [1024 /* Shift */ | 9 /* Escape */] } })); // ---- api bridge command editorExtensions_1.registerDefaultLanguageCommand('_executeDocumentRenameProvider', function (model, position, args) { var newName = args.newName; if (typeof newName !== 'string') { throw errors_1.illegalArgument('newName'); } return rename(model, position, newName); }); //todo@joh use editor options world platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).registerConfiguration({ id: 'editor', properties: { 'editor.rename.enablePreview': { scope: 5 /* LANGUAGE_OVERRIDABLE */, description: nls.localize(7, null), default: true, type: 'boolean' } } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[585/*vs/editor/contrib/suggest/suggestWidget*/], __M([0/*require*/,1/*exports*/,468/*vs/nls!vs/editor/contrib/suggest/suggestWidget*/,61/*vs/base/common/filters*/,5/*vs/base/common/strings*/,4/*vs/base/common/event*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,6/*vs/base/browser/dom*/,153/*vs/base/browser/ui/list/listWidget*/,53/*vs/base/browser/ui/scrollbar/scrollableElement*/,34/*vs/platform/keybinding/common/keybinding*/,18/*vs/platform/contextkey/common/contextkey*/,120/*vs/editor/contrib/suggest/suggest*/,96/*vs/platform/telemetry/common/telemetry*/,97/*vs/platform/theme/common/styler*/,14/*vs/platform/theme/common/themeService*/,20/*vs/platform/theme/common/colorRegistry*/,74/*vs/platform/storage/common/storage*/,117/*vs/editor/contrib/markdown/markdownRenderer*/,71/*vs/editor/common/services/modeService*/,51/*vs/platform/opener/common/opener*/,15/*vs/base/common/async*/,17/*vs/editor/common/modes*/,139/*vs/base/browser/ui/iconLabel/iconLabel*/,511/*vs/editor/common/services/getIconClasses*/,49/*vs/editor/common/services/modelService*/,25/*vs/base/common/uri*/,11/*vs/platform/instantiation/common/instantiation*/,208/*vs/platform/files/common/files*/,75/*vs/base/common/htmlContent*/,19/*vs/base/common/arrays*/,13/*vs/editor/common/core/position*/,322/*vs/css!vs/editor/contrib/suggest/media/suggest*/,323/*vs/css!vs/editor/contrib/suggest/media/suggestStatusBar*/,183/*vs/base/browser/ui/codiconLabel/codiconLabel*/,231/*vs/editor/contrib/documentSymbols/outlineTree*/]), function (require, exports, nls, filters_1, strings, event_1, errors_1, lifecycle_1, dom_1, listWidget_1, scrollableElement_1, keybinding_1, contextkey_1, suggest_1, telemetry_1, styler_1, themeService_1, colorRegistry_1, storage_1, markdownRenderer_1, modeService_1, opener_1, async_1, modes_1, iconLabel_1, getIconClasses_1, modelService_1, uri_1, instantiation_1, files_1, htmlContent_1, arrays_1, position_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var expandSuggestionDocsByDefault = false; /** * Suggest widget colors */ exports.editorSuggestWidgetBackground = colorRegistry_1.registerColor('editorSuggestWidget.background', { dark: colorRegistry_1.editorWidgetBackground, light: colorRegistry_1.editorWidgetBackground, hc: colorRegistry_1.editorWidgetBackground }, nls.localize(0, null)); exports.editorSuggestWidgetBorder = colorRegistry_1.registerColor('editorSuggestWidget.border', { dark: colorRegistry_1.editorWidgetBorder, light: colorRegistry_1.editorWidgetBorder, hc: colorRegistry_1.editorWidgetBorder }, nls.localize(1, null)); exports.editorSuggestWidgetForeground = colorRegistry_1.registerColor('editorSuggestWidget.foreground', { dark: colorRegistry_1.editorForeground, light: colorRegistry_1.editorForeground, hc: colorRegistry_1.editorForeground }, nls.localize(2, null)); exports.editorSuggestWidgetSelectedBackground = colorRegistry_1.registerColor('editorSuggestWidget.selectedBackground', { dark: colorRegistry_1.listFocusBackground, light: colorRegistry_1.listFocusBackground, hc: colorRegistry_1.listFocusBackground }, nls.localize(3, null)); exports.editorSuggestWidgetHighlightForeground = colorRegistry_1.registerColor('editorSuggestWidget.highlightForeground', { dark: colorRegistry_1.listHighlightForeground, light: colorRegistry_1.listHighlightForeground, hc: colorRegistry_1.listHighlightForeground }, nls.localize(4, null)); var colorRegExp = /^(#([\da-f]{3}){1,2}|(rgb|hsl)a\(\s*(\d{1,3}%?\s*,\s*){3}(1|0?\.\d+)\)|(rgb|hsl)\(\s*\d{1,3}%?(\s*,\s*\d{1,3}%?){2}\s*\))$/i; function extractColor(item, out) { var label = typeof item.completion.label === 'string' ? item.completion.label : item.completion.label.name; if (label.match(colorRegExp)) { out[0] = label; return true; } if (typeof item.completion.documentation === 'string' && item.completion.documentation.match(colorRegExp)) { out[0] = item.completion.documentation; return true; } return false; } function canExpandCompletionItem(item) { if (!item) { return false; } var suggestion = item.completion; if (suggestion.documentation) { return true; } return (suggestion.detail && suggestion.detail !== suggestion.label); } function getAriaId(index) { return "suggest-aria-id:" + index; } var ItemRenderer = /** @class */ (function () { function ItemRenderer(widget, editor, triggerKeybindingLabel, _modelService, _modeService, _themeService) { this.widget = widget; this.editor = editor; this.triggerKeybindingLabel = triggerKeybindingLabel; this._modelService = _modelService; this._modeService = _modeService; this._themeService = _themeService; } Object.defineProperty(ItemRenderer.prototype, "templateId", { get: function () { return 'suggestion'; }, enumerable: true, configurable: true }); ItemRenderer.prototype.renderTemplate = function (container) { var _this = this; var data = Object.create(null); data.disposables = new lifecycle_1.DisposableStore(); data.root = container; dom_1.addClass(data.root, 'show-file-icons'); data.icon = dom_1.append(container, dom_1.$('.icon')); data.colorspan = dom_1.append(data.icon, dom_1.$('span.colorspan')); var text = dom_1.append(container, dom_1.$('.contents')); var main = dom_1.append(text, dom_1.$('.main')); data.left = dom_1.append(main, dom_1.$('span.left')); data.right = dom_1.append(main, dom_1.$('span.right')); data.iconContainer = dom_1.append(data.left, dom_1.$('.icon-label.codicon')); data.iconLabel = new iconLabel_1.IconLabel(data.left, { supportHighlights: true, supportCodicons: true }); data.disposables.add(data.iconLabel); data.signatureLabel = dom_1.append(data.left, dom_1.$('span.signature-label')); data.qualifierLabel = dom_1.append(data.left, dom_1.$('span.qualifier-label')); data.detailsLabel = dom_1.append(data.right, dom_1.$('span.details-label')); data.readMore = dom_1.append(data.right, dom_1.$('span.readMore.codicon.codicon-info')); data.readMore.title = nls.localize(5, null, this.triggerKeybindingLabel); var configureFont = function () { var options = _this.editor.getOptions(); var fontInfo = options.get(34 /* fontInfo */); var fontFamily = fontInfo.fontFamily; var fontFeatureSettings = fontInfo.fontFeatureSettings; var fontSize = options.get(90 /* suggestFontSize */) || fontInfo.fontSize; var lineHeight = options.get(91 /* suggestLineHeight */) || fontInfo.lineHeight; var fontWeight = fontInfo.fontWeight; var fontSizePx = fontSize + "px"; var lineHeightPx = lineHeight + "px"; data.root.style.fontSize = fontSizePx; data.root.style.fontWeight = fontWeight; main.style.fontFamily = fontFamily; main.style.fontFeatureSettings = fontFeatureSettings; main.style.lineHeight = lineHeightPx; data.icon.style.height = lineHeightPx; data.icon.style.width = lineHeightPx; data.readMore.style.height = lineHeightPx; data.readMore.style.width = lineHeightPx; }; configureFont(); data.disposables.add(event_1.Event.chain(this.editor.onDidChangeConfiguration.bind(this.editor)) .filter(function (e) { return e.hasChanged(34 /* fontInfo */) || e.hasChanged(90 /* suggestFontSize */) || e.hasChanged(91 /* suggestLineHeight */); }) .on(configureFont, null)); return data; }; ItemRenderer.prototype.renderElement = function (element, index, templateData) { var _this = this; var data = templateData; var suggestion = element.completion; var textLabel = typeof suggestion.label === 'string' ? suggestion.label : suggestion.label.name; data.root.id = getAriaId(index); data.icon.className = 'icon ' + modes_1.completionKindToCssClass(suggestion.kind); data.colorspan.style.backgroundColor = ''; var labelOptions = { labelEscapeNewLines: true, matches: filters_1.createMatches(element.score) }; var color = []; if (suggestion.kind === 19 /* Color */ && extractColor(element, color)) { // special logic for 'color' completion items data.icon.className = 'icon customcolor'; data.iconContainer.className = 'icon hide'; data.colorspan.style.backgroundColor = color[0]; } else if (suggestion.kind === 20 /* File */ && this._themeService.getIconTheme().hasFileIcons) { // special logic for 'file' completion items data.icon.className = 'icon hide'; data.iconContainer.className = 'icon hide'; var labelClasses = getIconClasses_1.getIconClasses(this._modelService, this._modeService, uri_1.URI.from({ scheme: 'fake', path: textLabel }), files_1.FileKind.FILE); var detailClasses = getIconClasses_1.getIconClasses(this._modelService, this._modeService, uri_1.URI.from({ scheme: 'fake', path: suggestion.detail }), files_1.FileKind.FILE); labelOptions.extraClasses = labelClasses.length > detailClasses.length ? labelClasses : detailClasses; } else if (suggestion.kind === 23 /* Folder */ && this._themeService.getIconTheme().hasFolderIcons) { // special logic for 'folder' completion items data.icon.className = 'icon hide'; data.iconContainer.className = 'icon hide'; labelOptions.extraClasses = arrays_1.flatten([ getIconClasses_1.getIconClasses(this._modelService, this._modeService, uri_1.URI.from({ scheme: 'fake', path: textLabel }), files_1.FileKind.FOLDER), getIconClasses_1.getIconClasses(this._modelService, this._modeService, uri_1.URI.from({ scheme: 'fake', path: suggestion.detail }), files_1.FileKind.FOLDER) ]); } else { // normal icon data.icon.className = 'icon hide'; data.iconContainer.className = ''; dom_1.addClasses(data.iconContainer, "suggest-icon codicon codicon-symbol-" + modes_1.completionKindToCssClass(suggestion.kind)); } if (suggestion.tags && suggestion.tags.indexOf(1 /* Deprecated */) >= 0) { labelOptions.extraClasses = (labelOptions.extraClasses || []).concat(['deprecated']); labelOptions.matches = []; } data.iconLabel.setLabel(textLabel, undefined, labelOptions); if (typeof suggestion.label === 'string') { data.signatureLabel.textContent = ''; data.qualifierLabel.textContent = ''; data.detailsLabel.textContent = (suggestion.detail || '').replace(/\n.*$/m, ''); dom_1.removeClass(data.right, 'always-show-details'); } else { data.signatureLabel.textContent = (suggestion.label.signature || '').replace(/\n.*$/m, ''); data.qualifierLabel.textContent = (suggestion.label.qualifier || '').replace(/\n.*$/m, ''); data.detailsLabel.textContent = (suggestion.label.type || '').replace(/\n.*$/m, ''); dom_1.addClass(data.right, 'always-show-details'); } if (canExpandCompletionItem(element)) { dom_1.addClass(data.right, 'can-expand-details'); dom_1.show(data.readMore); data.readMore.onmousedown = function (e) { e.stopPropagation(); e.preventDefault(); }; data.readMore.onclick = function (e) { e.stopPropagation(); e.preventDefault(); _this.widget.toggleDetails(); }; } else { dom_1.removeClass(data.right, 'can-expand-details'); dom_1.hide(data.readMore); data.readMore.onmousedown = null; data.readMore.onclick = null; } }; ItemRenderer.prototype.disposeTemplate = function (templateData) { templateData.disposables.dispose(); }; ItemRenderer = __decorate([ __param(3, modelService_1.IModelService), __param(4, modeService_1.IModeService), __param(5, themeService_1.IThemeService) ], ItemRenderer); return ItemRenderer; }()); var SuggestionDetails = /** @class */ (function () { function SuggestionDetails(container, widget, editor, markdownRenderer, kbToggleDetails) { var _this = this; this.widget = widget; this.editor = editor; this.markdownRenderer = markdownRenderer; this.kbToggleDetails = kbToggleDetails; this.borderWidth = 1; this.disposables = new lifecycle_1.DisposableStore(); this.el = dom_1.append(container, dom_1.$('.details')); this.disposables.add(lifecycle_1.toDisposable(function () { return container.removeChild(_this.el); })); this.body = dom_1.$('.body'); this.scrollbar = new scrollableElement_1.DomScrollableElement(this.body, {}); dom_1.append(this.el, this.scrollbar.getDomNode()); this.disposables.add(this.scrollbar); this.header = dom_1.append(this.body, dom_1.$('.header')); this.close = dom_1.append(this.header, dom_1.$('span.codicon.codicon-close')); this.close.title = nls.localize(6, null, this.kbToggleDetails); this.type = dom_1.append(this.header, dom_1.$('p.type')); this.docs = dom_1.append(this.body, dom_1.$('p.docs')); this.configureFont(); event_1.Event.chain(this.editor.onDidChangeConfiguration.bind(this.editor)) .filter(function (e) { return e.hasChanged(34 /* fontInfo */); }) .on(this.configureFont, this, this.disposables); markdownRenderer.onDidRenderCodeBlock(function () { return _this.scrollbar.scanDomNode(); }, this, this.disposables); } Object.defineProperty(SuggestionDetails.prototype, "element", { get: function () { return this.el; }, enumerable: true, configurable: true }); SuggestionDetails.prototype.renderLoading = function () { this.type.textContent = nls.localize(7, null); this.docs.textContent = ''; }; SuggestionDetails.prototype.renderItem = function (item, explainMode) { var _this = this; this.renderDisposeable = lifecycle_1.dispose(this.renderDisposeable); var _a = item.completion, documentation = _a.documentation, detail = _a.detail; // --- documentation if (explainMode) { var md = ''; md += "score: " + item.score[0] + (item.word ? ", compared '" + (item.completion.filterText && (item.completion.filterText + ' (filterText)') || item.completion.label) + "' with '" + item.word + "'" : ' (no prefix)') + "\n"; md += "distance: " + item.distance + ", see localityBonus-setting\n"; md += "index: " + item.idx + ", based on " + (item.completion.sortText && "sortText: \"" + item.completion.sortText + "\"" || 'label') + "\n"; documentation = new htmlContent_1.MarkdownString().appendCodeblock('empty', md); detail = "Provider: " + item.provider._debugDisplayName; } if (!explainMode && !canExpandCompletionItem(item)) { this.type.textContent = ''; this.docs.textContent = ''; dom_1.addClass(this.el, 'no-docs'); return; } dom_1.removeClass(this.el, 'no-docs'); if (typeof documentation === 'string') { dom_1.removeClass(this.docs, 'markdown-docs'); this.docs.textContent = documentation; } else { dom_1.addClass(this.docs, 'markdown-docs'); this.docs.innerHTML = ''; var renderedContents = this.markdownRenderer.render(documentation); this.renderDisposeable = renderedContents; this.docs.appendChild(renderedContents.element); } // --- details if (detail) { this.type.innerText = detail; dom_1.show(this.type); } else { this.type.innerText = ''; dom_1.hide(this.type); } this.el.style.height = this.header.offsetHeight + this.docs.offsetHeight + (this.borderWidth * 2) + 'px'; this.el.style.userSelect = 'text'; this.el.tabIndex = -1; this.close.onmousedown = function (e) { e.preventDefault(); e.stopPropagation(); }; this.close.onclick = function (e) { e.preventDefault(); e.stopPropagation(); _this.widget.toggleDetails(); }; this.body.scrollTop = 0; this.scrollbar.scanDomNode(); }; SuggestionDetails.prototype.scrollDown = function (much) { if (much === void 0) { much = 8; } this.body.scrollTop += much; }; SuggestionDetails.prototype.scrollUp = function (much) { if (much === void 0) { much = 8; } this.body.scrollTop -= much; }; SuggestionDetails.prototype.scrollTop = function () { this.body.scrollTop = 0; }; SuggestionDetails.prototype.scrollBottom = function () { this.body.scrollTop = this.body.scrollHeight; }; SuggestionDetails.prototype.pageDown = function () { this.scrollDown(80); }; SuggestionDetails.prototype.pageUp = function () { this.scrollUp(80); }; SuggestionDetails.prototype.setBorderWidth = function (width) { this.borderWidth = width; }; SuggestionDetails.prototype.configureFont = function () { var options = this.editor.getOptions(); var fontInfo = options.get(34 /* fontInfo */); var fontFamily = fontInfo.fontFamily; var fontSize = options.get(90 /* suggestFontSize */) || fontInfo.fontSize; var lineHeight = options.get(91 /* suggestLineHeight */) || fontInfo.lineHeight; var fontWeight = fontInfo.fontWeight; var fontSizePx = fontSize + "px"; var lineHeightPx = lineHeight + "px"; this.el.style.fontSize = fontSizePx; this.el.style.fontWeight = fontWeight; this.el.style.fontFeatureSettings = fontInfo.fontFeatureSettings; this.type.style.fontFamily = fontFamily; this.close.style.height = lineHeightPx; this.close.style.width = lineHeightPx; }; SuggestionDetails.prototype.dispose = function () { this.disposables.dispose(); this.renderDisposeable = lifecycle_1.dispose(this.renderDisposeable); }; return SuggestionDetails; }()); var SuggestWidget = /** @class */ (function () { function SuggestWidget(editor, telemetryService, keybindingService, contextKeyService, themeService, storageService, modeService, openerService, instantiationService) { var _this = this; var _a, _b; this.editor = editor; this.telemetryService = telemetryService; this.keybindingService = keybindingService; // Editor.IContentWidget.allowEditorOverflow this.allowEditorOverflow = true; this.suppressMouseDown = false; this.state = null; this.isAuto = false; this.loadingTimeout = lifecycle_1.Disposable.None; this.currentSuggestionDetails = null; this.ignoreFocusEvents = false; this.completionModel = null; this.showTimeout = new async_1.TimeoutTimer(); this.toDispose = new lifecycle_1.DisposableStore(); this.onDidSelectEmitter = new event_1.Emitter(); this.onDidFocusEmitter = new event_1.Emitter(); this.onDidHideEmitter = new event_1.Emitter(); this.onDidShowEmitter = new event_1.Emitter(); this.onDidSelect = this.onDidSelectEmitter.event; this.onDidFocus = this.onDidFocusEmitter.event; this.onDidHide = this.onDidHideEmitter.event; this.onDidShow = this.onDidShowEmitter.event; this.maxWidgetWidth = 660; this.listWidth = 330; this.firstFocusInCurrentList = false; this.preferDocPositionTop = false; this.docsPositionPreviousWidgetY = null; this.explainMode = false; this._onDetailsKeydown = new event_1.Emitter(); this.onDetailsKeyDown = this._onDetailsKeydown.event; var markdownRenderer = this.toDispose.add(new markdownRenderer_1.MarkdownRenderer(editor, modeService, openerService)); var kbToggleDetails = (_b = (_a = keybindingService.lookupKeybinding('toggleSuggestionDetails')) === null || _a === void 0 ? void 0 : _a.getLabel()) !== null && _b !== void 0 ? _b : ''; this.msgDetailsLess = nls.localize(10, null, kbToggleDetails); this.msgDetailMore = nls.localize(11, null, kbToggleDetails); this.isAuto = false; this.focusedItem = null; this.storageService = storageService; this.element = dom_1.$('.editor-widget.suggest-widget'); this.toDispose.add(dom_1.addDisposableListener(this.element, 'click', function (e) { if (e.target === _this.element) { _this.hideWidget(); } })); this.messageElement = dom_1.append(this.element, dom_1.$('.message')); this.listElement = dom_1.append(this.element, dom_1.$('.tree')); var applyStatusBarStyle = function () { return dom_1.toggleClass(_this.element, 'with-status-bar', !_this.editor.getOption(89 /* suggest */).hideStatusBar); }; applyStatusBarStyle(); this.statusBarElement = dom_1.append(this.element, dom_1.$('.suggest-status-bar')); this.statusBarLeftSpan = dom_1.append(this.statusBarElement, dom_1.$('span')); this.statusBarRightSpan = dom_1.append(this.statusBarElement, dom_1.$('span')); this.setStatusBarLeftText(''); this.setStatusBarRightText(''); this.details = instantiationService.createInstance(SuggestionDetails, this.element, this, this.editor, markdownRenderer, kbToggleDetails); var applyIconStyle = function () { return dom_1.toggleClass(_this.element, 'no-icons', !_this.editor.getOption(89 /* suggest */).showIcons); }; applyIconStyle(); var renderer = instantiationService.createInstance(ItemRenderer, this, this.editor, kbToggleDetails); this.list = new listWidget_1.List('SuggestWidget', this.listElement, this, [renderer], { useShadows: false, openController: { shouldOpen: function () { return false; } }, mouseSupport: false, accessibilityProvider: { getAriaLabel: function (item) { var textLabel = typeof item.completion.label === 'string' ? item.completion.label : item.completion.label.name; if (item.isResolved && _this.expandDocsSettingFromStorage()) { var _a = item.completion, documentation = _a.documentation, detail = _a.detail; var docs = strings.format('{0}{1}', detail || '', documentation ? (typeof documentation === 'string' ? documentation : documentation.value) : ''); return nls.localize(12, null, textLabel, docs); } else { return textLabel; } } } }); this.toDispose.add(styler_1.attachListStyler(this.list, themeService, { listInactiveFocusBackground: exports.editorSuggestWidgetSelectedBackground, listInactiveFocusOutline: colorRegistry_1.activeContrastBorder })); this.toDispose.add(themeService.onThemeChange(function (t) { return _this.onThemeChange(t); })); this.toDispose.add(editor.onDidLayoutChange(function () { return _this.onEditorLayoutChange(); })); this.toDispose.add(this.list.onMouseDown(function (e) { return _this.onListMouseDownOrTap(e); })); this.toDispose.add(this.list.onTap(function (e) { return _this.onListMouseDownOrTap(e); })); this.toDispose.add(this.list.onSelectionChange(function (e) { return _this.onListSelection(e); })); this.toDispose.add(this.list.onFocusChange(function (e) { return _this.onListFocus(e); })); this.toDispose.add(this.editor.onDidChangeCursorSelection(function () { return _this.onCursorSelectionChanged(); })); this.toDispose.add(this.editor.onDidChangeConfiguration(function (e) { if (e.hasChanged(89 /* suggest */)) { applyStatusBarStyle(); applyIconStyle(); } })); this.suggestWidgetVisible = suggest_1.Context.Visible.bindTo(contextKeyService); this.suggestWidgetMultipleSuggestions = suggest_1.Context.MultipleSuggestions.bindTo(contextKeyService); this.editor.addContentWidget(this); this.setState(0 /* Hidden */); this.onThemeChange(themeService.getTheme()); this.toDispose.add(dom_1.addStandardDisposableListener(this.details.element, 'keydown', function (e) { _this._onDetailsKeydown.fire(e); })); this.toDispose.add(this.editor.onMouseDown(function (e) { return _this.onEditorMouseDown(e); })); } SuggestWidget.prototype.onEditorMouseDown = function (mouseEvent) { // Clicking inside details if (this.details.element.contains(mouseEvent.target.element)) { this.details.element.focus(); } // Clicking outside details and inside suggest else { if (this.element.contains(mouseEvent.target.element)) { this.editor.focus(); } } }; SuggestWidget.prototype.onCursorSelectionChanged = function () { if (this.state === 0 /* Hidden */) { return; } this.editor.layoutContentWidget(this); }; SuggestWidget.prototype.onEditorLayoutChange = function () { if ((this.state === 3 /* Open */ || this.state === 5 /* Details */) && this.expandDocsSettingFromStorage()) { this.expandSideOrBelow(); } }; SuggestWidget.prototype.onListMouseDownOrTap = function (e) { if (typeof e.element === 'undefined' || typeof e.index === 'undefined') { return; } // prevent stealing browser focus from the editor e.browserEvent.preventDefault(); e.browserEvent.stopPropagation(); this.select(e.element, e.index); }; SuggestWidget.prototype.onListSelection = function (e) { if (!e.elements.length) { return; } this.select(e.elements[0], e.indexes[0]); }; SuggestWidget.prototype.select = function (item, index) { var completionModel = this.completionModel; if (!completionModel) { return; } this.onDidSelectEmitter.fire({ item: item, index: index, model: completionModel }); this.editor.focus(); }; SuggestWidget.prototype.onThemeChange = function (theme) { var backgroundColor = theme.getColor(exports.editorSuggestWidgetBackground); if (backgroundColor) { this.listElement.style.backgroundColor = backgroundColor.toString(); this.statusBarElement.style.backgroundColor = backgroundColor.toString(); this.details.element.style.backgroundColor = backgroundColor.toString(); this.messageElement.style.backgroundColor = backgroundColor.toString(); } var borderColor = theme.getColor(exports.editorSuggestWidgetBorder); if (borderColor) { this.listElement.style.borderColor = borderColor.toString(); this.statusBarElement.style.borderColor = borderColor.toString(); this.details.element.style.borderColor = borderColor.toString(); this.messageElement.style.borderColor = borderColor.toString(); this.detailsBorderColor = borderColor.toString(); } var focusBorderColor = theme.getColor(colorRegistry_1.focusBorder); if (focusBorderColor) { this.detailsFocusBorderColor = focusBorderColor.toString(); } this.details.setBorderWidth(theme.type === 'hc' ? 2 : 1); }; SuggestWidget.prototype.onListFocus = function (e) { var _this = this; var _a, _b; if (this.ignoreFocusEvents) { return; } if (!e.elements.length) { if (this.currentSuggestionDetails) { this.currentSuggestionDetails.cancel(); this.currentSuggestionDetails = null; this.focusedItem = null; } this.editor.setAriaOptions({ activeDescendant: undefined }); return; } if (!this.completionModel) { return; } var item = e.elements[0]; var index = e.indexes[0]; this.firstFocusInCurrentList = !this.focusedItem; if (item !== this.focusedItem) { // update statusbar // todo@joh,pine -> this should a toolbar with actions so that these things become // mouse clickable and fit for accessibility... var wantsInsert = this.editor.getOption(89 /* suggest */).insertMode === 'insert'; var kbAccept = (_a = this.keybindingService.lookupKeybinding('acceptSelectedSuggestion')) === null || _a === void 0 ? void 0 : _a.getLabel(); var kbAcceptAlt = (_b = this.keybindingService.lookupKeybinding('acceptAlternativeSelectedSuggestion')) === null || _b === void 0 ? void 0 : _b.getLabel(); if (!position_1.Position.equals(item.editInsertEnd, item.editReplaceEnd)) { // insert AND replace if (wantsInsert) { this.setStatusBarLeftText(nls.localize(13, null, kbAccept, kbAcceptAlt)); } else { this.setStatusBarLeftText(nls.localize(14, null, kbAccept, kbAcceptAlt)); } } else { this.setStatusBarLeftText(nls.localize(15, null, kbAccept)); } if (this.currentSuggestionDetails) { this.currentSuggestionDetails.cancel(); this.currentSuggestionDetails = null; } this.focusedItem = item; this.list.reveal(index); this.currentSuggestionDetails = async_1.createCancelablePromise(function (token) { return __awaiter(_this, void 0, void 0, function () { var loading, result; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: loading = async_1.disposableTimeout(function () { return _this.showDetails(true); }, 250); token.onCancellationRequested(function () { return loading.dispose(); }); return [4 /*yield*/, item.resolve(token)]; case 1: result = _a.sent(); loading.dispose(); return [2 /*return*/, result]; } }); }); }); this.currentSuggestionDetails.then(function () { if (index >= _this.list.length || item !== _this.list.element(index)) { return; } // item can have extra information, so re-render _this.ignoreFocusEvents = true; _this.list.splice(index, 1, [item]); _this.list.setFocus([index]); _this.ignoreFocusEvents = false; if (_this.expandDocsSettingFromStorage()) { _this.showDetails(false); } else { dom_1.removeClass(_this.element, 'docs-side'); } if (canExpandCompletionItem(_this.focusedItem)) { if (_this.expandDocsSettingFromStorage()) { _this.setStatusBarRightText(_this.msgDetailsLess); } else { _this.setStatusBarRightText(_this.msgDetailMore); } } else { _this.statusBarRightSpan.innerText = ''; } _this.editor.setAriaOptions({ activeDescendant: getAriaId(index) }); }).catch(errors_1.onUnexpectedError); } // emit an event this.onDidFocusEmitter.fire({ item: item, index: index, model: this.completionModel }); }; SuggestWidget.prototype.setState = function (state) { if (!this.element) { return; } var stateChanged = this.state !== state; this.state = state; dom_1.toggleClass(this.element, 'frozen', state === 4 /* Frozen */); switch (state) { case 0 /* Hidden */: dom_1.hide(this.messageElement, this.details.element, this.listElement, this.statusBarElement); this.hide(); this.listHeight = 0; if (stateChanged) { this.list.splice(0, this.list.length); } this.focusedItem = null; break; case 1 /* Loading */: this.messageElement.textContent = SuggestWidget.LOADING_MESSAGE; dom_1.hide(this.listElement, this.details.element, this.statusBarElement); dom_1.show(this.messageElement); dom_1.removeClass(this.element, 'docs-side'); this.show(); this.focusedItem = null; break; case 2 /* Empty */: this.messageElement.textContent = SuggestWidget.NO_SUGGESTIONS_MESSAGE; dom_1.hide(this.listElement, this.details.element, this.statusBarElement); dom_1.show(this.messageElement); dom_1.removeClass(this.element, 'docs-side'); this.show(); this.focusedItem = null; break; case 3 /* Open */: dom_1.hide(this.messageElement); dom_1.show(this.listElement, this.statusBarElement); this.show(); break; case 4 /* Frozen */: dom_1.hide(this.messageElement); dom_1.show(this.listElement); this.show(); break; case 5 /* Details */: dom_1.hide(this.messageElement); dom_1.show(this.details.element, this.listElement, this.statusBarElement); this.show(); break; } }; SuggestWidget.prototype.showTriggered = function (auto, delay) { var _this = this; if (this.state !== 0 /* Hidden */) { return; } this.isAuto = !!auto; if (!this.isAuto) { this.loadingTimeout = async_1.disposableTimeout(function () { return _this.setState(1 /* Loading */); }, delay); } }; SuggestWidget.prototype.showSuggestions = function (completionModel, selectionIndex, isFrozen, isAuto) { this.preferDocPositionTop = false; this.docsPositionPreviousWidgetY = null; this.loadingTimeout.dispose(); if (this.currentSuggestionDetails) { this.currentSuggestionDetails.cancel(); this.currentSuggestionDetails = null; } if (this.completionModel !== completionModel) { this.completionModel = completionModel; } if (isFrozen && this.state !== 2 /* Empty */ && this.state !== 0 /* Hidden */) { this.setState(4 /* Frozen */); return; } var visibleCount = this.completionModel.items.length; var isEmpty = visibleCount === 0; this.suggestWidgetMultipleSuggestions.set(visibleCount > 1); if (isEmpty) { if (isAuto) { this.setState(0 /* Hidden */); } else { this.setState(2 /* Empty */); } this.completionModel = null; } else { if (this.state !== 3 /* Open */) { var stats = this.completionModel.stats; stats['wasAutomaticallyTriggered'] = !!isAuto; /* __GDPR__ "suggestWidget" : { "wasAutomaticallyTriggered" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "${include}": [ "${ICompletionStats}" ] } */ this.telemetryService.publicLog('suggestWidget', __assign({}, stats)); } this.focusedItem = null; this.list.splice(0, this.list.length, this.completionModel.items); if (isFrozen) { this.setState(4 /* Frozen */); } else { this.setState(3 /* Open */); } this.list.reveal(selectionIndex, 0); this.list.setFocus([selectionIndex]); // Reset focus border if (this.detailsBorderColor) { this.details.element.style.borderColor = this.detailsBorderColor; } } }; SuggestWidget.prototype.selectNextPage = function () { switch (this.state) { case 0 /* Hidden */: return false; case 5 /* Details */: this.details.pageDown(); return true; case 1 /* Loading */: return !this.isAuto; default: this.list.focusNextPage(); return true; } }; SuggestWidget.prototype.selectNext = function () { switch (this.state) { case 0 /* Hidden */: return false; case 1 /* Loading */: return !this.isAuto; default: this.list.focusNext(1, true); return true; } }; SuggestWidget.prototype.selectLast = function () { switch (this.state) { case 0 /* Hidden */: return false; case 5 /* Details */: this.details.scrollBottom(); return true; case 1 /* Loading */: return !this.isAuto; default: this.list.focusLast(); return true; } }; SuggestWidget.prototype.selectPreviousPage = function () { switch (this.state) { case 0 /* Hidden */: return false; case 5 /* Details */: this.details.pageUp(); return true; case 1 /* Loading */: return !this.isAuto; default: this.list.focusPreviousPage(); return true; } }; SuggestWidget.prototype.selectPrevious = function () { switch (this.state) { case 0 /* Hidden */: return false; case 1 /* Loading */: return !this.isAuto; default: this.list.focusPrevious(1, true); return false; } }; SuggestWidget.prototype.selectFirst = function () { switch (this.state) { case 0 /* Hidden */: return false; case 5 /* Details */: this.details.scrollTop(); return true; case 1 /* Loading */: return !this.isAuto; default: this.list.focusFirst(); return true; } }; SuggestWidget.prototype.getFocusedItem = function () { if (this.state !== 0 /* Hidden */ && this.state !== 2 /* Empty */ && this.state !== 1 /* Loading */ && this.completionModel) { return { item: this.list.getFocusedElements()[0], index: this.list.getFocus()[0], model: this.completionModel }; } return undefined; }; SuggestWidget.prototype.toggleDetailsFocus = function () { if (this.state === 5 /* Details */) { this.setState(3 /* Open */); if (this.detailsBorderColor) { this.details.element.style.borderColor = this.detailsBorderColor; } } else if (this.state === 3 /* Open */ && this.expandDocsSettingFromStorage()) { this.setState(5 /* Details */); if (this.detailsFocusBorderColor) { this.details.element.style.borderColor = this.detailsFocusBorderColor; } } this.telemetryService.publicLog2('suggestWidget:toggleDetailsFocus'); }; SuggestWidget.prototype.toggleDetails = function () { if (!canExpandCompletionItem(this.list.getFocusedElements()[0])) { return; } if (this.expandDocsSettingFromStorage()) { this.updateExpandDocsSetting(false); dom_1.hide(this.details.element); dom_1.removeClass(this.element, 'docs-side'); dom_1.removeClass(this.element, 'docs-below'); this.editor.layoutContentWidget(this); this.setStatusBarRightText(this.msgDetailMore); this.telemetryService.publicLog2('suggestWidget:collapseDetails'); } else { if (this.state !== 3 /* Open */ && this.state !== 5 /* Details */ && this.state !== 4 /* Frozen */) { return; } this.updateExpandDocsSetting(true); this.showDetails(false); this.setStatusBarRightText(this.msgDetailsLess); this.telemetryService.publicLog2('suggestWidget:expandDetails'); } }; SuggestWidget.prototype.showDetails = function (loading) { if (!loading) { // When loading, don't re-layout docs, as item is not resolved yet #88731 this.expandSideOrBelow(); } dom_1.show(this.details.element); this.details.element.style.maxHeight = this.maxWidgetHeight + 'px'; if (loading) { this.details.renderLoading(); } else { this.details.renderItem(this.list.getFocusedElements()[0], this.explainMode); } // Reset margin-top that was set as Fix for #26416 this.listElement.style.marginTop = '0px'; // with docs showing up widget width/height may change, so reposition the widget this.editor.layoutContentWidget(this); this.adjustDocsPosition(); this.editor.focus(); }; SuggestWidget.prototype.toggleExplainMode = function () { if (this.list.getFocusedElements()[0] && this.expandDocsSettingFromStorage()) { this.explainMode = !this.explainMode; this.showDetails(false); } }; SuggestWidget.prototype.show = function () { var _this = this; var newHeight = this.updateListHeight(); if (newHeight !== this.listHeight) { this.editor.layoutContentWidget(this); this.listHeight = newHeight; } this.suggestWidgetVisible.set(true); this.showTimeout.cancelAndSet(function () { dom_1.addClass(_this.element, 'visible'); _this.onDidShowEmitter.fire(_this); }, 100); }; SuggestWidget.prototype.hide = function () { this.suggestWidgetVisible.reset(); this.suggestWidgetMultipleSuggestions.reset(); dom_1.removeClass(this.element, 'visible'); }; SuggestWidget.prototype.hideWidget = function () { this.loadingTimeout.dispose(); this.setState(0 /* Hidden */); this.onDidHideEmitter.fire(this); }; SuggestWidget.prototype.getPosition = function () { if (this.state === 0 /* Hidden */) { return null; } var preference = [2 /* BELOW */, 1 /* ABOVE */]; if (this.preferDocPositionTop) { preference = [1 /* ABOVE */]; } return { position: this.editor.getPosition(), preference: preference }; }; SuggestWidget.prototype.getDomNode = function () { return this.element; }; SuggestWidget.prototype.getId = function () { return SuggestWidget.ID; }; SuggestWidget.prototype.isFrozen = function () { return this.state === 4 /* Frozen */; }; SuggestWidget.prototype.updateListHeight = function () { var height = 0; if (this.state === 2 /* Empty */ || this.state === 1 /* Loading */) { height = this.unfocusedHeight; } else { var suggestionCount = this.list.contentHeight / this.unfocusedHeight; var maxVisibleSuggestions = this.editor.getOption(89 /* suggest */).maxVisibleSuggestions; height = Math.min(suggestionCount, maxVisibleSuggestions) * this.unfocusedHeight; } this.element.style.lineHeight = this.unfocusedHeight + "px"; this.listElement.style.height = height + "px"; this.statusBarElement.style.top = height + "px"; this.list.layout(height); return height; }; /** * Adds the propert classes, margins when positioning the docs to the side */ SuggestWidget.prototype.adjustDocsPosition = function () { if (!this.editor.hasModel()) { return; } var lineHeight = this.editor.getOption(49 /* lineHeight */); var cursorCoords = this.editor.getScrolledVisiblePosition(this.editor.getPosition()); var editorCoords = dom_1.getDomNodePagePosition(this.editor.getDomNode()); var cursorX = editorCoords.left + cursorCoords.left; var cursorY = editorCoords.top + cursorCoords.top + cursorCoords.height; var widgetCoords = dom_1.getDomNodePagePosition(this.element); var widgetX = widgetCoords.left; var widgetY = widgetCoords.top; // Fixes #27649 // Check if the Y changed to the top of the cursor and keep the widget flagged to prefer top if (this.docsPositionPreviousWidgetY && this.docsPositionPreviousWidgetY < widgetY && !this.preferDocPositionTop) { this.preferDocPositionTop = true; this.adjustDocsPosition(); return; } this.docsPositionPreviousWidgetY = widgetY; if (widgetX < cursorX - this.listWidth) { // Widget is too far to the left of cursor, swap list and docs dom_1.addClass(this.element, 'list-right'); } else { dom_1.removeClass(this.element, 'list-right'); } // Compare top of the cursor (cursorY - lineheight) with widgetTop to determine if // margin-top needs to be applied on list to make it appear right above the cursor // Cannot compare cursorY directly as it may be a few decimals off due to zoooming if (dom_1.hasClass(this.element, 'docs-side') && cursorY - lineHeight > widgetY && this.details.element.offsetHeight > this.listElement.offsetHeight) { // Fix for #26416 // Docs is bigger than list and widget is above cursor, apply margin-top so that list appears right above cursor this.listElement.style.marginTop = this.details.element.offsetHeight - this.listElement.offsetHeight + "px"; } }; /** * Adds the proper classes for positioning the docs to the side or below depending on item */ SuggestWidget.prototype.expandSideOrBelow = function () { if (!canExpandCompletionItem(this.focusedItem) && this.firstFocusInCurrentList) { dom_1.removeClass(this.element, 'docs-side'); dom_1.removeClass(this.element, 'docs-below'); return; } var matches = this.element.style.maxWidth.match(/(\d+)px/); if (!matches || Number(matches[1]) < this.maxWidgetWidth) { dom_1.addClass(this.element, 'docs-below'); dom_1.removeClass(this.element, 'docs-side'); } else if (canExpandCompletionItem(this.focusedItem)) { dom_1.addClass(this.element, 'docs-side'); dom_1.removeClass(this.element, 'docs-below'); } }; Object.defineProperty(SuggestWidget.prototype, "maxWidgetHeight", { // Heights get: function () { return this.unfocusedHeight * this.editor.getOption(89 /* suggest */).maxVisibleSuggestions; }, enumerable: true, configurable: true }); Object.defineProperty(SuggestWidget.prototype, "unfocusedHeight", { get: function () { var options = this.editor.getOptions(); return options.get(91 /* suggestLineHeight */) || options.get(34 /* fontInfo */).lineHeight; }, enumerable: true, configurable: true }); // IDelegate SuggestWidget.prototype.getHeight = function (element) { return this.unfocusedHeight; }; SuggestWidget.prototype.getTemplateId = function (element) { return 'suggestion'; }; SuggestWidget.prototype.expandDocsSettingFromStorage = function () { return this.storageService.getBoolean('expandSuggestionDocs', 0 /* GLOBAL */, expandSuggestionDocsByDefault); }; SuggestWidget.prototype.updateExpandDocsSetting = function (value) { this.storageService.store('expandSuggestionDocs', value, 0 /* GLOBAL */); }; SuggestWidget.prototype.setStatusBarLeftText = function (s) { this.statusBarLeftSpan.innerText = s; }; SuggestWidget.prototype.setStatusBarRightText = function (s) { this.statusBarRightSpan.innerText = s; }; SuggestWidget.prototype.dispose = function () { this.details.dispose(); this.list.dispose(); this.toDispose.dispose(); this.loadingTimeout.dispose(); this.showTimeout.dispose(); }; SuggestWidget.ID = 'editor.widget.suggestWidget'; SuggestWidget.LOADING_MESSAGE = nls.localize(8, null); SuggestWidget.NO_SUGGESTIONS_MESSAGE = nls.localize(9, null); SuggestWidget = __decorate([ __param(1, telemetry_1.ITelemetryService), __param(2, keybinding_1.IKeybindingService), __param(3, contextkey_1.IContextKeyService), __param(4, themeService_1.IThemeService), __param(5, storage_1.IStorageService), __param(6, modeService_1.IModeService), __param(7, opener_1.IOpenerService), __param(8, instantiation_1.IInstantiationService) ], SuggestWidget); return SuggestWidget; }()); exports.SuggestWidget = SuggestWidget; themeService_1.registerThemingParticipant(function (theme, collector) { var matchHighlight = theme.getColor(exports.editorSuggestWidgetHighlightForeground); if (matchHighlight) { collector.addRule(".monaco-editor .suggest-widget .monaco-list .monaco-list-row .monaco-highlighted-label .highlight { color: " + matchHighlight + "; }"); } var foreground = theme.getColor(exports.editorSuggestWidgetForeground); if (foreground) { collector.addRule(".monaco-editor .suggest-widget { color: " + foreground + "; }"); } var link = theme.getColor(colorRegistry_1.textLinkForeground); if (link) { collector.addRule(".monaco-editor .suggest-widget a { color: " + link + "; }"); } var codeBackground = theme.getColor(colorRegistry_1.textCodeBlockBackground); if (codeBackground) { collector.addRule(".monaco-editor .suggest-widget code { background-color: " + codeBackground + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[586/*vs/editor/contrib/wordHighlighter/wordHighlighter*/], __M([0/*require*/,1/*exports*/,471/*vs/nls!vs/editor/contrib/wordHighlighter/wordHighlighter*/,19/*vs/base/common/arrays*/,15/*vs/base/common/async*/,26/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,12/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,23/*vs/editor/common/editorContextKeys*/,48/*vs/editor/common/model*/,30/*vs/editor/common/model/textModel*/,17/*vs/editor/common/modes*/,18/*vs/platform/contextkey/common/contextkey*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, nls, arrays, async_1, cancellation_1, errors_1, lifecycle_1, editorExtensions_1, range_1, editorContextKeys_1, model_1, textModel_1, modes_1, contextkey_1, colorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var editorWordHighlight = colorRegistry_1.registerColor('editor.wordHighlightBackground', { dark: '#575757B8', light: '#57575740', hc: null }, nls.localize(0, null), true); var editorWordHighlightStrong = colorRegistry_1.registerColor('editor.wordHighlightStrongBackground', { dark: '#004972B8', light: '#0e639c40', hc: null }, nls.localize(1, null), true); var editorWordHighlightBorder = colorRegistry_1.registerColor('editor.wordHighlightBorder', { light: null, dark: null, hc: colorRegistry_1.activeContrastBorder }, nls.localize(2, null)); var editorWordHighlightStrongBorder = colorRegistry_1.registerColor('editor.wordHighlightStrongBorder', { light: null, dark: null, hc: colorRegistry_1.activeContrastBorder }, nls.localize(3, null)); var overviewRulerWordHighlightForeground = colorRegistry_1.registerColor('editorOverviewRuler.wordHighlightForeground', { dark: '#A0A0A0CC', light: '#A0A0A0CC', hc: '#A0A0A0CC' }, nls.localize(4, null), true); var overviewRulerWordHighlightStrongForeground = colorRegistry_1.registerColor('editorOverviewRuler.wordHighlightStrongForeground', { dark: '#C0A0C0CC', light: '#C0A0C0CC', hc: '#C0A0C0CC' }, nls.localize(5, null), true); var ctxHasWordHighlights = new contextkey_1.RawContextKey('hasWordHighlights', false); function getOccurrencesAtPosition(model, position, token) { var orderedByScore = modes_1.DocumentHighlightProviderRegistry.ordered(model); // in order of score ask the occurrences provider // until someone response with a good result // (good = none empty array) return async_1.first(orderedByScore.map(function (provider) { return function () { return Promise.resolve(provider.provideDocumentHighlights(model, position, token)) .then(undefined, errors_1.onUnexpectedExternalError); }; }), arrays.isNonEmptyArray); } exports.getOccurrencesAtPosition = getOccurrencesAtPosition; var OccurenceAtPositionRequest = /** @class */ (function () { function OccurenceAtPositionRequest(model, selection, wordSeparators) { var _this = this; this._wordRange = this._getCurrentWordRange(model, selection); this.result = async_1.createCancelablePromise(function (token) { return _this._compute(model, selection, wordSeparators, token); }); } OccurenceAtPositionRequest.prototype._getCurrentWordRange = function (model, selection) { var word = model.getWordAtPosition(selection.getPosition()); if (word) { return new range_1.Range(selection.startLineNumber, word.startColumn, selection.startLineNumber, word.endColumn); } return null; }; OccurenceAtPositionRequest.prototype.isValid = function (model, selection, decorationIds) { var lineNumber = selection.startLineNumber; var startColumn = selection.startColumn; var endColumn = selection.endColumn; var currentWordRange = this._getCurrentWordRange(model, selection); var requestIsValid = Boolean(this._wordRange && this._wordRange.equalsRange(currentWordRange)); // Even if we are on a different word, if that word is in the decorations ranges, the request is still valid // (Same symbol) for (var i = 0, len = decorationIds.length; !requestIsValid && i < len; i++) { var range = model.getDecorationRange(decorationIds[i]); if (range && range.startLineNumber === lineNumber) { if (range.startColumn <= startColumn && range.endColumn >= endColumn) { requestIsValid = true; } } } return requestIsValid; }; OccurenceAtPositionRequest.prototype.cancel = function () { this.result.cancel(); }; return OccurenceAtPositionRequest; }()); var SemanticOccurenceAtPositionRequest = /** @class */ (function (_super) { __extends(SemanticOccurenceAtPositionRequest, _super); function SemanticOccurenceAtPositionRequest() { return _super !== null && _super.apply(this, arguments) || this; } SemanticOccurenceAtPositionRequest.prototype._compute = function (model, selection, wordSeparators, token) { return getOccurrencesAtPosition(model, selection.getPosition(), token).then(function (value) { return value || []; }); }; return SemanticOccurenceAtPositionRequest; }(OccurenceAtPositionRequest)); var TextualOccurenceAtPositionRequest = /** @class */ (function (_super) { __extends(TextualOccurenceAtPositionRequest, _super); function TextualOccurenceAtPositionRequest(model, selection, wordSeparators) { var _this = _super.call(this, model, selection, wordSeparators) || this; _this._selectionIsEmpty = selection.isEmpty(); return _this; } TextualOccurenceAtPositionRequest.prototype._compute = function (model, selection, wordSeparators, token) { return async_1.timeout(250, token).then(function () { if (!selection.isEmpty()) { return []; } var word = model.getWordAtPosition(selection.getPosition()); if (!word) { return []; } var matches = model.findMatches(word.word, true, false, true, wordSeparators, false); return matches.map(function (m) { return { range: m.range, kind: modes_1.DocumentHighlightKind.Text }; }); }); }; TextualOccurenceAtPositionRequest.prototype.isValid = function (model, selection, decorationIds) { var currentSelectionIsEmpty = selection.isEmpty(); if (this._selectionIsEmpty !== currentSelectionIsEmpty) { return false; } return _super.prototype.isValid.call(this, model, selection, decorationIds); }; return TextualOccurenceAtPositionRequest; }(OccurenceAtPositionRequest)); function computeOccurencesAtPosition(model, selection, wordSeparators) { if (modes_1.DocumentHighlightProviderRegistry.has(model)) { return new SemanticOccurenceAtPositionRequest(model, selection, wordSeparators); } return new TextualOccurenceAtPositionRequest(model, selection, wordSeparators); } editorExtensions_1.registerModelAndPositionCommand('_executeDocumentHighlights', function (model, position) { return getOccurrencesAtPosition(model, position, cancellation_1.CancellationToken.None); }); var WordHighlighter = /** @class */ (function () { function WordHighlighter(editor, contextKeyService) { var _this = this; this.toUnhook = new lifecycle_1.DisposableStore(); this.workerRequestTokenId = 0; this.workerRequestCompleted = false; this.workerRequestValue = []; this.lastCursorPositionChangeTime = 0; this.renderDecorationsTimer = -1; this.editor = editor; this._hasWordHighlights = ctxHasWordHighlights.bindTo(contextKeyService); this._ignorePositionChangeEvent = false; this.occurrencesHighlight = this.editor.getOption(61 /* occurrencesHighlight */); this.model = this.editor.getModel(); this.toUnhook.add(editor.onDidChangeCursorPosition(function (e) { if (_this._ignorePositionChangeEvent) { // We are changing the position => ignore this event return; } if (!_this.occurrencesHighlight) { // Early exit if nothing needs to be done! // Leave some form of early exit check here if you wish to continue being a cursor position change listener ;) return; } _this._onPositionChanged(e); })); this.toUnhook.add(editor.onDidChangeModelContent(function (e) { _this._stopAll(); })); this.toUnhook.add(editor.onDidChangeConfiguration(function (e) { var newValue = _this.editor.getOption(61 /* occurrencesHighlight */); if (_this.occurrencesHighlight !== newValue) { _this.occurrencesHighlight = newValue; _this._stopAll(); } })); this._decorationIds = []; this.workerRequestTokenId = 0; this.workerRequest = null; this.workerRequestCompleted = false; this.lastCursorPositionChangeTime = 0; this.renderDecorationsTimer = -1; } WordHighlighter.prototype.hasDecorations = function () { return (this._decorationIds.length > 0); }; WordHighlighter.prototype.restore = function () { if (!this.occurrencesHighlight) { return; } this._run(); }; WordHighlighter.prototype._getSortedHighlights = function () { var _this = this; return arrays.coalesce(this._decorationIds .map(function (id) { return _this.model.getDecorationRange(id); }) .sort(range_1.Range.compareRangesUsingStarts)); }; WordHighlighter.prototype.moveNext = function () { var _this = this; var highlights = this._getSortedHighlights(); var index = arrays.firstIndex(highlights, function (range) { return range.containsPosition(_this.editor.getPosition()); }); var newIndex = ((index + 1) % highlights.length); var dest = highlights[newIndex]; try { this._ignorePositionChangeEvent = true; this.editor.setPosition(dest.getStartPosition()); this.editor.revealRangeInCenterIfOutsideViewport(dest); } finally { this._ignorePositionChangeEvent = false; } }; WordHighlighter.prototype.moveBack = function () { var _this = this; var highlights = this._getSortedHighlights(); var index = arrays.firstIndex(highlights, function (range) { return range.containsPosition(_this.editor.getPosition()); }); var newIndex = ((index - 1 + highlights.length) % highlights.length); var dest = highlights[newIndex]; try { this._ignorePositionChangeEvent = true; this.editor.setPosition(dest.getStartPosition()); this.editor.revealRangeInCenterIfOutsideViewport(dest); } finally { this._ignorePositionChangeEvent = false; } }; WordHighlighter.prototype._removeDecorations = function () { if (this._decorationIds.length > 0) { // remove decorations this._decorationIds = this.editor.deltaDecorations(this._decorationIds, []); this._hasWordHighlights.set(false); } }; WordHighlighter.prototype._stopAll = function () { // Remove any existing decorations this._removeDecorations(); // Cancel any renderDecorationsTimer if (this.renderDecorationsTimer !== -1) { clearTimeout(this.renderDecorationsTimer); this.renderDecorationsTimer = -1; } // Cancel any worker request if (this.workerRequest !== null) { this.workerRequest.cancel(); this.workerRequest = null; } // Invalidate any worker request callback if (!this.workerRequestCompleted) { this.workerRequestTokenId++; this.workerRequestCompleted = true; } }; WordHighlighter.prototype._onPositionChanged = function (e) { // disabled if (!this.occurrencesHighlight) { this._stopAll(); return; } // ignore typing & other if (e.reason !== 3 /* Explicit */) { this._stopAll(); return; } this._run(); }; WordHighlighter.prototype._run = function () { var _this = this; var editorSelection = this.editor.getSelection(); // ignore multiline selection if (editorSelection.startLineNumber !== editorSelection.endLineNumber) { this._stopAll(); return; } var lineNumber = editorSelection.startLineNumber; var startColumn = editorSelection.startColumn; var endColumn = editorSelection.endColumn; var word = this.model.getWordAtPosition({ lineNumber: lineNumber, column: startColumn }); // The selection must be inside a word or surround one word at most if (!word || word.startColumn > startColumn || word.endColumn < endColumn) { this._stopAll(); return; } // All the effort below is trying to achieve this: // - when cursor is moved to a word, trigger immediately a findOccurrences request // - 250ms later after the last cursor move event, render the occurrences // - no flickering! var workerRequestIsValid = (this.workerRequest && this.workerRequest.isValid(this.model, editorSelection, this._decorationIds)); // There are 4 cases: // a) old workerRequest is valid & completed, renderDecorationsTimer fired // b) old workerRequest is valid & completed, renderDecorationsTimer not fired // c) old workerRequest is valid, but not completed // d) old workerRequest is not valid // For a) no action is needed // For c), member 'lastCursorPositionChangeTime' will be used when installing the timer so no action is needed this.lastCursorPositionChangeTime = (new Date()).getTime(); if (workerRequestIsValid) { if (this.workerRequestCompleted && this.renderDecorationsTimer !== -1) { // case b) // Delay the firing of renderDecorationsTimer by an extra 250 ms clearTimeout(this.renderDecorationsTimer); this.renderDecorationsTimer = -1; this._beginRenderDecorations(); } } else { // case d) // Stop all previous actions and start fresh this._stopAll(); var myRequestId_1 = ++this.workerRequestTokenId; this.workerRequestCompleted = false; this.workerRequest = computeOccurencesAtPosition(this.model, this.editor.getSelection(), this.editor.getOption(96 /* wordSeparators */)); this.workerRequest.result.then(function (data) { if (myRequestId_1 === _this.workerRequestTokenId) { _this.workerRequestCompleted = true; _this.workerRequestValue = data || []; _this._beginRenderDecorations(); } }, errors_1.onUnexpectedError); } }; WordHighlighter.prototype._beginRenderDecorations = function () { var _this = this; var currentTime = (new Date()).getTime(); var minimumRenderTime = this.lastCursorPositionChangeTime + 250; if (currentTime >= minimumRenderTime) { // Synchronous this.renderDecorationsTimer = -1; this.renderDecorations(); } else { // Asynchronous this.renderDecorationsTimer = setTimeout(function () { _this.renderDecorations(); }, (minimumRenderTime - currentTime)); } }; WordHighlighter.prototype.renderDecorations = function () { this.renderDecorationsTimer = -1; var decorations = []; for (var i = 0, len = this.workerRequestValue.length; i < len; i++) { var info = this.workerRequestValue[i]; decorations.push({ range: info.range, options: WordHighlighter._getDecorationOptions(info.kind) }); } this._decorationIds = this.editor.deltaDecorations(this._decorationIds, decorations); this._hasWordHighlights.set(this.hasDecorations()); }; WordHighlighter._getDecorationOptions = function (kind) { if (kind === modes_1.DocumentHighlightKind.Write) { return this._WRITE_OPTIONS; } else if (kind === modes_1.DocumentHighlightKind.Text) { return this._TEXT_OPTIONS; } else { return this._REGULAR_OPTIONS; } }; WordHighlighter.prototype.dispose = function () { this._stopAll(); this.toUnhook.dispose(); }; WordHighlighter._WRITE_OPTIONS = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'wordHighlightStrong', overviewRuler: { color: themeService_1.themeColorFromId(overviewRulerWordHighlightStrongForeground), position: model_1.OverviewRulerLane.Center } }); WordHighlighter._TEXT_OPTIONS = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'selectionHighlight', overviewRuler: { color: themeService_1.themeColorFromId(colorRegistry_1.overviewRulerSelectionHighlightForeground), position: model_1.OverviewRulerLane.Center } }); WordHighlighter._REGULAR_OPTIONS = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'wordHighlight', overviewRuler: { color: themeService_1.themeColorFromId(overviewRulerWordHighlightForeground), position: model_1.OverviewRulerLane.Center } }); return WordHighlighter; }()); var WordHighlighterContribution = /** @class */ (function (_super) { __extends(WordHighlighterContribution, _super); function WordHighlighterContribution(editor, contextKeyService) { var _this = _super.call(this) || this; _this.wordHighligher = null; var createWordHighlighterIfPossible = function () { if (editor.hasModel()) { _this.wordHighligher = new WordHighlighter(editor, contextKeyService); } }; _this._register(editor.onDidChangeModel(function (e) { if (_this.wordHighligher) { _this.wordHighligher.dispose(); _this.wordHighligher = null; } createWordHighlighterIfPossible(); })); createWordHighlighterIfPossible(); return _this; } WordHighlighterContribution.get = function (editor) { return editor.getContribution(WordHighlighterContribution.ID); }; WordHighlighterContribution.prototype.saveViewState = function () { if (this.wordHighligher && this.wordHighligher.hasDecorations()) { return true; } return false; }; WordHighlighterContribution.prototype.moveNext = function () { if (this.wordHighligher) { this.wordHighligher.moveNext(); } }; WordHighlighterContribution.prototype.moveBack = function () { if (this.wordHighligher) { this.wordHighligher.moveBack(); } }; WordHighlighterContribution.prototype.restoreViewState = function (state) { if (this.wordHighligher && state) { this.wordHighligher.restore(); } }; WordHighlighterContribution.prototype.dispose = function () { if (this.wordHighligher) { this.wordHighligher.dispose(); this.wordHighligher = null; } _super.prototype.dispose.call(this); }; WordHighlighterContribution.ID = 'editor.contrib.wordHighlighter'; WordHighlighterContribution = __decorate([ __param(1, contextkey_1.IContextKeyService) ], WordHighlighterContribution); return WordHighlighterContribution; }(lifecycle_1.Disposable)); var WordHighlightNavigationAction = /** @class */ (function (_super) { __extends(WordHighlightNavigationAction, _super); function WordHighlightNavigationAction(next, opts) { var _this = _super.call(this, opts) || this; _this._isNext = next; return _this; } WordHighlightNavigationAction.prototype.run = function (accessor, editor) { var controller = WordHighlighterContribution.get(editor); if (!controller) { return; } if (this._isNext) { controller.moveNext(); } else { controller.moveBack(); } }; return WordHighlightNavigationAction; }(editorExtensions_1.EditorAction)); var NextWordHighlightAction = /** @class */ (function (_super) { __extends(NextWordHighlightAction, _super); function NextWordHighlightAction() { return _super.call(this, true, { id: 'editor.action.wordHighlight.next', label: nls.localize(6, null), alias: 'Go to Next Symbol Highlight', precondition: ctxHasWordHighlights, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 65 /* F7 */, weight: 100 /* EditorContrib */ } }) || this; } return NextWordHighlightAction; }(WordHighlightNavigationAction)); var PrevWordHighlightAction = /** @class */ (function (_super) { __extends(PrevWordHighlightAction, _super); function PrevWordHighlightAction() { return _super.call(this, false, { id: 'editor.action.wordHighlight.prev', label: nls.localize(7, null), alias: 'Go to Previous Symbol Highlight', precondition: ctxHasWordHighlights, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 1024 /* Shift */ | 65 /* F7 */, weight: 100 /* EditorContrib */ } }) || this; } return PrevWordHighlightAction; }(WordHighlightNavigationAction)); var TriggerWordHighlightAction = /** @class */ (function (_super) { __extends(TriggerWordHighlightAction, _super); function TriggerWordHighlightAction() { return _super.call(this, { id: 'editor.action.wordHighlight.trigger', label: nls.localize(8, null), alias: 'Trigger Symbol Highlight', precondition: ctxHasWordHighlights.toNegated(), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 0, weight: 100 /* EditorContrib */ } }) || this; } TriggerWordHighlightAction.prototype.run = function (accessor, editor, args) { var controller = WordHighlighterContribution.get(editor); if (!controller) { return; } controller.restoreViewState(true); }; return TriggerWordHighlightAction; }(editorExtensions_1.EditorAction)); editorExtensions_1.registerEditorContribution(WordHighlighterContribution.ID, WordHighlighterContribution); editorExtensions_1.registerEditorAction(NextWordHighlightAction); editorExtensions_1.registerEditorAction(PrevWordHighlightAction); editorExtensions_1.registerEditorAction(TriggerWordHighlightAction); themeService_1.registerThemingParticipant(function (theme, collector) { var selectionHighlight = theme.getColor(colorRegistry_1.editorSelectionHighlight); if (selectionHighlight) { collector.addRule(".monaco-editor .focused .selectionHighlight { background-color: " + selectionHighlight + "; }"); collector.addRule(".monaco-editor .selectionHighlight { background-color: " + selectionHighlight.transparent(0.5) + "; }"); } var wordHighlight = theme.getColor(editorWordHighlight); if (wordHighlight) { collector.addRule(".monaco-editor .wordHighlight { background-color: " + wordHighlight + "; }"); } var wordHighlightStrong = theme.getColor(editorWordHighlightStrong); if (wordHighlightStrong) { collector.addRule(".monaco-editor .wordHighlightStrong { background-color: " + wordHighlightStrong + "; }"); } var selectionHighlightBorder = theme.getColor(colorRegistry_1.editorSelectionHighlightBorder); if (selectionHighlightBorder) { collector.addRule(".monaco-editor .selectionHighlight { border: 1px " + (theme.type === 'hc' ? 'dotted' : 'solid') + " " + selectionHighlightBorder + "; box-sizing: border-box; }"); } var wordHighlightBorder = theme.getColor(editorWordHighlightBorder); if (wordHighlightBorder) { collector.addRule(".monaco-editor .wordHighlight { border: 1px " + (theme.type === 'hc' ? 'dashed' : 'solid') + " " + wordHighlightBorder + "; box-sizing: border-box; }"); } var wordHighlightStrongBorder = theme.getColor(editorWordHighlightStrongBorder); if (wordHighlightStrongBorder) { collector.addRule(".monaco-editor .wordHighlightStrong { border: 1px " + (theme.type === 'hc' ? 'dashed' : 'solid') + " " + wordHighlightStrongBorder + "; box-sizing: border-box; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[587/*vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,6/*vs/base/browser/dom*/,28/*vs/base/browser/fastDomNode*/,134/*vs/base/browser/formattedTextRenderer*/,50/*vs/base/browser/ui/aria/aria*/,47/*vs/base/browser/ui/widget*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,5/*vs/base/common/strings*/,25/*vs/base/common/uri*/,12/*vs/editor/browser/editorExtensions*/,23/*vs/editor/common/editorContextKeys*/,225/*vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/,18/*vs/platform/contextkey/common/contextkey*/,11/*vs/platform/instantiation/common/instantiation*/,34/*vs/platform/keybinding/common/keybinding*/,51/*vs/platform/opener/common/opener*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,59/*vs/editor/common/standaloneStrings*/,325/*vs/css!vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/]), function (require, exports, browser, dom, fastDomNode_1, formattedTextRenderer_1, aria_1, widget_1, lifecycle_1, platform, strings, uri_1, editorExtensions_1, editorContextKeys_1, toggleTabFocusMode_1, contextkey_1, instantiation_1, keybinding_1, opener_1, colorRegistry_1, themeService_1, standaloneStrings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE = new contextkey_1.RawContextKey('accessibilityHelpWidgetVisible', false); var AccessibilityHelpController = /** @class */ (function (_super) { __extends(AccessibilityHelpController, _super); function AccessibilityHelpController(editor, instantiationService) { var _this = _super.call(this) || this; _this._editor = editor; _this._widget = _this._register(instantiationService.createInstance(AccessibilityHelpWidget, _this._editor)); return _this; } AccessibilityHelpController.get = function (editor) { return editor.getContribution(AccessibilityHelpController.ID); }; AccessibilityHelpController.prototype.show = function () { this._widget.show(); }; AccessibilityHelpController.prototype.hide = function () { this._widget.hide(); }; AccessibilityHelpController.ID = 'editor.contrib.accessibilityHelpController'; AccessibilityHelpController = __decorate([ __param(1, instantiation_1.IInstantiationService) ], AccessibilityHelpController); return AccessibilityHelpController; }(lifecycle_1.Disposable)); function getSelectionLabel(selections, charactersSelected) { if (!selections || selections.length === 0) { return standaloneStrings_1.AccessibilityHelpNLS.noSelection; } if (selections.length === 1) { if (charactersSelected) { return strings.format(standaloneStrings_1.AccessibilityHelpNLS.singleSelectionRange, selections[0].positionLineNumber, selections[0].positionColumn, charactersSelected); } return strings.format(standaloneStrings_1.AccessibilityHelpNLS.singleSelection, selections[0].positionLineNumber, selections[0].positionColumn); } if (charactersSelected) { return strings.format(standaloneStrings_1.AccessibilityHelpNLS.multiSelectionRange, selections.length, charactersSelected); } if (selections.length > 0) { return strings.format(standaloneStrings_1.AccessibilityHelpNLS.multiSelection, selections.length); } return ''; } var AccessibilityHelpWidget = /** @class */ (function (_super) { __extends(AccessibilityHelpWidget, _super); function AccessibilityHelpWidget(editor, _contextKeyService, _keybindingService, _openerService) { var _this = _super.call(this) || this; _this._contextKeyService = _contextKeyService; _this._keybindingService = _keybindingService; _this._openerService = _openerService; _this._editor = editor; _this._isVisibleKey = CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE.bindTo(_this._contextKeyService); _this._domNode = fastDomNode_1.createFastDomNode(document.createElement('div')); _this._domNode.setClassName('accessibilityHelpWidget'); _this._domNode.setDisplay('none'); _this._domNode.setAttribute('role', 'dialog'); _this._domNode.setAttribute('aria-hidden', 'true'); _this._contentDomNode = fastDomNode_1.createFastDomNode(document.createElement('div')); _this._contentDomNode.setAttribute('role', 'document'); _this._domNode.appendChild(_this._contentDomNode); _this._isVisible = false; _this._register(_this._editor.onDidLayoutChange(function () { if (_this._isVisible) { _this._layout(); } })); // Intentionally not configurable! _this._register(dom.addStandardDisposableListener(_this._contentDomNode.domNode, 'keydown', function (e) { if (!_this._isVisible) { return; } if (e.equals(2048 /* CtrlCmd */ | 35 /* KEY_E */)) { aria_1.alert(standaloneStrings_1.AccessibilityHelpNLS.emergencyConfOn); _this._editor.updateOptions({ accessibilitySupport: 'on' }); dom.clearNode(_this._contentDomNode.domNode); _this._buildContent(); _this._contentDomNode.domNode.focus(); e.preventDefault(); e.stopPropagation(); } if (e.equals(2048 /* CtrlCmd */ | 38 /* KEY_H */)) { aria_1.alert(standaloneStrings_1.AccessibilityHelpNLS.openingDocs); var url = _this._editor.getRawOptions().accessibilityHelpUrl; if (typeof url === 'undefined') { url = 'https://go.microsoft.com/fwlink/?linkid=852450'; } _this._openerService.open(uri_1.URI.parse(url)); e.preventDefault(); e.stopPropagation(); } })); _this.onblur(_this._contentDomNode.domNode, function () { _this.hide(); }); _this._editor.addOverlayWidget(_this); return _this; } AccessibilityHelpWidget.prototype.dispose = function () { this._editor.removeOverlayWidget(this); _super.prototype.dispose.call(this); }; AccessibilityHelpWidget.prototype.getId = function () { return AccessibilityHelpWidget.ID; }; AccessibilityHelpWidget.prototype.getDomNode = function () { return this._domNode.domNode; }; AccessibilityHelpWidget.prototype.getPosition = function () { return { preference: null }; }; AccessibilityHelpWidget.prototype.show = function () { if (this._isVisible) { return; } this._isVisible = true; this._isVisibleKey.set(true); this._layout(); this._domNode.setDisplay('block'); this._domNode.setAttribute('aria-hidden', 'false'); this._contentDomNode.domNode.tabIndex = 0; this._buildContent(); this._contentDomNode.domNode.focus(); }; AccessibilityHelpWidget.prototype._descriptionForCommand = function (commandId, msg, noKbMsg) { var kb = this._keybindingService.lookupKeybinding(commandId); if (kb) { return strings.format(msg, kb.getAriaLabel()); } return strings.format(noKbMsg, commandId); }; AccessibilityHelpWidget.prototype._buildContent = function () { var options = this._editor.getOptions(); var selections = this._editor.getSelections(); var charactersSelected = 0; if (selections) { var model_1 = this._editor.getModel(); if (model_1) { selections.forEach(function (selection) { charactersSelected += model_1.getValueLengthInRange(selection); }); } } var text = getSelectionLabel(selections, charactersSelected); if (options.get(45 /* inDiffEditor */)) { if (options.get(68 /* readOnly */)) { text += standaloneStrings_1.AccessibilityHelpNLS.readonlyDiffEditor; } else { text += standaloneStrings_1.AccessibilityHelpNLS.editableDiffEditor; } } else { if (options.get(68 /* readOnly */)) { text += standaloneStrings_1.AccessibilityHelpNLS.readonlyEditor; } else { text += standaloneStrings_1.AccessibilityHelpNLS.editableEditor; } } var turnOnMessage = (platform.isMacintosh ? standaloneStrings_1.AccessibilityHelpNLS.changeConfigToOnMac : standaloneStrings_1.AccessibilityHelpNLS.changeConfigToOnWinLinux); switch (options.get(2 /* accessibilitySupport */)) { case 0 /* Unknown */: text += '\n\n - ' + turnOnMessage; break; case 2 /* Enabled */: text += '\n\n - ' + standaloneStrings_1.AccessibilityHelpNLS.auto_on; break; case 1 /* Disabled */: text += '\n\n - ' + standaloneStrings_1.AccessibilityHelpNLS.auto_off; text += ' ' + turnOnMessage; break; } if (options.get(106 /* tabFocusMode */)) { text += '\n\n - ' + this._descriptionForCommand(toggleTabFocusMode_1.ToggleTabFocusModeAction.ID, standaloneStrings_1.AccessibilityHelpNLS.tabFocusModeOnMsg, standaloneStrings_1.AccessibilityHelpNLS.tabFocusModeOnMsgNoKb); } else { text += '\n\n - ' + this._descriptionForCommand(toggleTabFocusMode_1.ToggleTabFocusModeAction.ID, standaloneStrings_1.AccessibilityHelpNLS.tabFocusModeOffMsg, standaloneStrings_1.AccessibilityHelpNLS.tabFocusModeOffMsgNoKb); } var openDocMessage = (platform.isMacintosh ? standaloneStrings_1.AccessibilityHelpNLS.openDocMac : standaloneStrings_1.AccessibilityHelpNLS.openDocWinLinux); text += '\n\n - ' + openDocMessage; text += '\n\n' + standaloneStrings_1.AccessibilityHelpNLS.outroMsg; this._contentDomNode.domNode.appendChild(formattedTextRenderer_1.renderFormattedText(text)); // Per https://www.w3.org/TR/wai-aria/roles#document, Authors SHOULD provide a title or label for documents this._contentDomNode.domNode.setAttribute('aria-label', text); }; AccessibilityHelpWidget.prototype.hide = function () { if (!this._isVisible) { return; } this._isVisible = false; this._isVisibleKey.reset(); this._domNode.setDisplay('none'); this._domNode.setAttribute('aria-hidden', 'true'); this._contentDomNode.domNode.tabIndex = -1; dom.clearNode(this._contentDomNode.domNode); this._editor.focus(); }; AccessibilityHelpWidget.prototype._layout = function () { var editorLayout = this._editor.getLayoutInfo(); var w = Math.max(5, Math.min(AccessibilityHelpWidget.WIDTH, editorLayout.width - 40)); var h = Math.max(5, Math.min(AccessibilityHelpWidget.HEIGHT, editorLayout.height - 40)); this._domNode.setWidth(w); this._domNode.setHeight(h); var top = Math.round((editorLayout.height - h) / 2); this._domNode.setTop(top); var left = Math.round((editorLayout.width - w) / 2); this._domNode.setLeft(left); }; AccessibilityHelpWidget.ID = 'editor.contrib.accessibilityHelpWidget'; AccessibilityHelpWidget.WIDTH = 500; AccessibilityHelpWidget.HEIGHT = 300; AccessibilityHelpWidget = __decorate([ __param(1, contextkey_1.IContextKeyService), __param(2, keybinding_1.IKeybindingService), __param(3, opener_1.IOpenerService) ], AccessibilityHelpWidget); return AccessibilityHelpWidget; }(widget_1.Widget)); var ShowAccessibilityHelpAction = /** @class */ (function (_super) { __extends(ShowAccessibilityHelpAction, _super); function ShowAccessibilityHelpAction() { return _super.call(this, { id: 'editor.action.showAccessibilityHelp', label: standaloneStrings_1.AccessibilityHelpNLS.showAccessibilityHelpAction, alias: 'Show Accessibility Help', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: (browser.isIE ? 2048 /* CtrlCmd */ | 59 /* F1 */ : 512 /* Alt */ | 59 /* F1 */), weight: 100 /* EditorContrib */ } }) || this; } ShowAccessibilityHelpAction.prototype.run = function (accessor, editor) { var controller = AccessibilityHelpController.get(editor); if (controller) { controller.show(); } }; return ShowAccessibilityHelpAction; }(editorExtensions_1.EditorAction)); editorExtensions_1.registerEditorContribution(AccessibilityHelpController.ID, AccessibilityHelpController); editorExtensions_1.registerEditorAction(ShowAccessibilityHelpAction); var AccessibilityHelpCommand = editorExtensions_1.EditorCommand.bindToContribution(AccessibilityHelpController.get); editorExtensions_1.registerEditorCommand(new AccessibilityHelpCommand({ id: 'closeAccessibilityHelp', precondition: CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE, handler: function (x) { return x.hide(); }, kbOpts: { weight: 100 /* EditorContrib */ + 100, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 9 /* Escape */, secondary: [1024 /* Shift */ | 9 /* Escape */] } })); themeService_1.registerThemingParticipant(function (theme, collector) { var widgetBackground = theme.getColor(colorRegistry_1.editorWidgetBackground); if (widgetBackground) { collector.addRule(".monaco-editor .accessibilityHelpWidget { background-color: " + widgetBackground + "; }"); } var widgetForeground = theme.getColor(colorRegistry_1.editorWidgetForeground); if (widgetForeground) { collector.addRule(".monaco-editor .accessibilityHelpWidget { color: " + widgetForeground + "; }"); } var widgetShadowColor = theme.getColor(colorRegistry_1.widgetShadow); if (widgetShadowColor) { collector.addRule(".monaco-editor .accessibilityHelpWidget { box-shadow: 0 2px 8px " + widgetShadowColor + "; }"); } var hcBorder = theme.getColor(colorRegistry_1.contrastBorder); if (hcBorder) { collector.addRule(".monaco-editor .accessibilityHelpWidget { border: 2px solid " + hcBorder + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[588/*vs/editor/standalone/browser/inspectTokens/inspectTokens*/], __M([0/*require*/,1/*exports*/,27/*vs/base/common/color*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,12/*vs/editor/browser/editorExtensions*/,17/*vs/editor/common/modes*/,63/*vs/editor/common/modes/nullMode*/,71/*vs/editor/common/services/modeService*/,94/*vs/editor/standalone/common/standaloneThemeService*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,59/*vs/editor/common/standaloneStrings*/,327/*vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens*/]), function (require, exports, color_1, lifecycle_1, strings_1, editorExtensions_1, modes_1, nullMode_1, modeService_1, standaloneThemeService_1, colorRegistry_1, themeService_1, standaloneStrings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var InspectTokensController = /** @class */ (function (_super) { __extends(InspectTokensController, _super); function InspectTokensController(editor, standaloneColorService, modeService) { var _this = _super.call(this) || this; _this._editor = editor; _this._modeService = modeService; _this._widget = null; _this._register(_this._editor.onDidChangeModel(function (e) { return _this.stop(); })); _this._register(_this._editor.onDidChangeModelLanguage(function (e) { return _this.stop(); })); _this._register(modes_1.TokenizationRegistry.onDidChange(function (e) { return _this.stop(); })); return _this; } InspectTokensController.get = function (editor) { return editor.getContribution(InspectTokensController.ID); }; InspectTokensController.prototype.dispose = function () { this.stop(); _super.prototype.dispose.call(this); }; InspectTokensController.prototype.launch = function () { if (this._widget) { return; } if (!this._editor.hasModel()) { return; } this._widget = new InspectTokensWidget(this._editor, this._modeService); }; InspectTokensController.prototype.stop = function () { if (this._widget) { this._widget.dispose(); this._widget = null; } }; InspectTokensController.ID = 'editor.contrib.inspectTokens'; InspectTokensController = __decorate([ __param(1, standaloneThemeService_1.IStandaloneThemeService), __param(2, modeService_1.IModeService) ], InspectTokensController); return InspectTokensController; }(lifecycle_1.Disposable)); var InspectTokens = /** @class */ (function (_super) { __extends(InspectTokens, _super); function InspectTokens() { return _super.call(this, { id: 'editor.action.inspectTokens', label: standaloneStrings_1.InspectTokensNLS.inspectTokensAction, alias: 'Developer: Inspect Tokens', precondition: undefined }) || this; } InspectTokens.prototype.run = function (accessor, editor) { var controller = InspectTokensController.get(editor); if (controller) { controller.launch(); } }; return InspectTokens; }(editorExtensions_1.EditorAction)); function renderTokenText(tokenText) { var result = ''; for (var charIndex = 0, len = tokenText.length; charIndex < len; charIndex++) { var charCode = tokenText.charCodeAt(charIndex); switch (charCode) { case 9 /* Tab */: result += '→'; break; case 32 /* Space */: result += '·'; break; case 60 /* LessThan */: result += '<'; break; case 62 /* GreaterThan */: result += '>'; break; case 38 /* Ampersand */: result += '&'; break; default: result += String.fromCharCode(charCode); } } return result; } function getSafeTokenizationSupport(languageIdentifier) { var tokenizationSupport = modes_1.TokenizationRegistry.get(languageIdentifier.language); if (tokenizationSupport) { return tokenizationSupport; } return { getInitialState: function () { return nullMode_1.NULL_STATE; }, tokenize: function (line, state, deltaOffset) { return nullMode_1.nullTokenize(languageIdentifier.language, line, state, deltaOffset); }, tokenize2: function (line, state, deltaOffset) { return nullMode_1.nullTokenize2(languageIdentifier.id, line, state, deltaOffset); } }; } var InspectTokensWidget = /** @class */ (function (_super) { __extends(InspectTokensWidget, _super); function InspectTokensWidget(editor, modeService) { var _this = _super.call(this) || this; // Editor.IContentWidget.allowEditorOverflow _this.allowEditorOverflow = true; _this._editor = editor; _this._modeService = modeService; _this._model = _this._editor.getModel(); _this._domNode = document.createElement('div'); _this._domNode.className = 'tokens-inspect-widget'; _this._tokenizationSupport = getSafeTokenizationSupport(_this._model.getLanguageIdentifier()); _this._compute(_this._editor.getPosition()); _this._register(_this._editor.onDidChangeCursorPosition(function (e) { return _this._compute(_this._editor.getPosition()); })); _this._editor.addContentWidget(_this); return _this; } InspectTokensWidget.prototype.dispose = function () { this._editor.removeContentWidget(this); _super.prototype.dispose.call(this); }; InspectTokensWidget.prototype.getId = function () { return InspectTokensWidget._ID; }; InspectTokensWidget.prototype._compute = function (position) { var data = this._getTokensAtLine(position.lineNumber); var token1Index = 0; for (var i = data.tokens1.length - 1; i >= 0; i--) { var t = data.tokens1[i]; if (position.column - 1 >= t.offset) { token1Index = i; break; } } var token2Index = 0; for (var i = (data.tokens2.length >>> 1); i >= 0; i--) { if (position.column - 1 >= data.tokens2[(i << 1)]) { token2Index = i; break; } } var result = ''; var lineContent = this._model.getLineContent(position.lineNumber); var tokenText = ''; if (token1Index < data.tokens1.length) { var tokenStartIndex = data.tokens1[token1Index].offset; var tokenEndIndex = token1Index + 1 < data.tokens1.length ? data.tokens1[token1Index + 1].offset : lineContent.length; tokenText = lineContent.substring(tokenStartIndex, tokenEndIndex); } result += "

    " + renderTokenText(tokenText) + "(" + tokenText.length + " " + (tokenText.length === 1 ? 'char' : 'chars') + ")

    "; result += "
    "; var metadata = this._decodeMetadata(data.tokens2[(token2Index << 1) + 1]); result += ""; result += ""; result += ""; result += ""; result += ""; result += ""; result += ""; result += "
    "; if (token1Index < data.tokens1.length) { result += "" + strings_1.escape(data.tokens1[token1Index].type) + ""; } this._domNode.innerHTML = result; this._editor.layoutContentWidget(this); }; InspectTokensWidget.prototype._decodeMetadata = function (metadata) { var colorMap = modes_1.TokenizationRegistry.getColorMap(); var languageId = modes_1.TokenMetadata.getLanguageId(metadata); var tokenType = modes_1.TokenMetadata.getTokenType(metadata); var fontStyle = modes_1.TokenMetadata.getFontStyle(metadata); var foreground = modes_1.TokenMetadata.getForeground(metadata); var background = modes_1.TokenMetadata.getBackground(metadata); return { languageIdentifier: this._modeService.getLanguageIdentifier(languageId), tokenType: tokenType, fontStyle: fontStyle, foreground: colorMap[foreground], background: colorMap[background] }; }; InspectTokensWidget.prototype._tokenTypeToString = function (tokenType) { switch (tokenType) { case 0 /* Other */: return 'Other'; case 1 /* Comment */: return 'Comment'; case 2 /* String */: return 'String'; case 4 /* RegEx */: return 'RegEx'; } return '??'; }; InspectTokensWidget.prototype._fontStyleToString = function (fontStyle) { var r = ''; if (fontStyle & 1 /* Italic */) { r += 'italic '; } if (fontStyle & 2 /* Bold */) { r += 'bold '; } if (fontStyle & 4 /* Underline */) { r += 'underline '; } if (r.length === 0) { r = '---'; } return r; }; InspectTokensWidget.prototype._getTokensAtLine = function (lineNumber) { var stateBeforeLine = this._getStateBeforeLine(lineNumber); var tokenizationResult1 = this._tokenizationSupport.tokenize(this._model.getLineContent(lineNumber), stateBeforeLine, 0); var tokenizationResult2 = this._tokenizationSupport.tokenize2(this._model.getLineContent(lineNumber), stateBeforeLine, 0); return { startState: stateBeforeLine, tokens1: tokenizationResult1.tokens, tokens2: tokenizationResult2.tokens, endState: tokenizationResult1.endState }; }; InspectTokensWidget.prototype._getStateBeforeLine = function (lineNumber) { var state = this._tokenizationSupport.getInitialState(); for (var i = 1; i < lineNumber; i++) { var tokenizationResult = this._tokenizationSupport.tokenize(this._model.getLineContent(i), state, 0); state = tokenizationResult.endState; } return state; }; InspectTokensWidget.prototype.getDomNode = function () { return this._domNode; }; InspectTokensWidget.prototype.getPosition = function () { return { position: this._editor.getPosition(), preference: [2 /* BELOW */, 1 /* ABOVE */] }; }; InspectTokensWidget._ID = 'editor.contrib.inspectTokensWidget'; return InspectTokensWidget; }(lifecycle_1.Disposable)); editorExtensions_1.registerEditorContribution(InspectTokensController.ID, InspectTokensController); editorExtensions_1.registerEditorAction(InspectTokens); themeService_1.registerThemingParticipant(function (theme, collector) { var border = theme.getColor(colorRegistry_1.editorHoverBorder); if (border) { var borderWidth = theme.type === themeService_1.HIGH_CONTRAST ? 2 : 1; collector.addRule(".monaco-editor .tokens-inspect-widget { border: " + borderWidth + "px solid " + border + "; }"); collector.addRule(".monaco-editor .tokens-inspect-widget .tokens-inspect-separator { background-color: " + border + "; }"); } var background = theme.getColor(colorRegistry_1.editorHoverBackground); if (background) { collector.addRule(".monaco-editor .tokens-inspect-widget { background-color: " + background + "; }"); } var foreground = theme.getColor(colorRegistry_1.editorHoverForeground); if (foreground) { collector.addRule(".monaco-editor .tokens-inspect-widget { color: " + foreground + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[169/*vs/editor/standalone/browser/quickOpen/editorQuickOpen*/], __M([0/*require*/,1/*exports*/,12/*vs/editor/browser/editorExtensions*/,30/*vs/editor/common/model/textModel*/,546/*vs/editor/standalone/browser/quickOpen/quickOpenEditorWidget*/,14/*vs/platform/theme/common/themeService*/,328/*vs/css!vs/editor/standalone/browser/quickOpen/editorQuickOpen*/]), function (require, exports, editorExtensions_1, textModel_1, quickOpenEditorWidget_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var QuickOpenController = /** @class */ (function () { function QuickOpenController(editor, themeService) { this.themeService = themeService; this.widget = null; this.rangeHighlightDecorationId = null; this.lastKnownEditorSelection = null; this.editor = editor; } QuickOpenController.get = function (editor) { return editor.getContribution(QuickOpenController.ID); }; QuickOpenController.prototype.dispose = function () { // Dispose widget if (this.widget) { this.widget.destroy(); this.widget = null; } }; QuickOpenController.prototype.run = function (opts) { var _this = this; if (this.widget) { this.widget.destroy(); this.widget = null; } // Create goto line widget var onClose = function (canceled) { // Clear Highlight Decorations if present _this.clearDecorations(); // Restore selection if canceled if (canceled && _this.lastKnownEditorSelection) { _this.editor.setSelection(_this.lastKnownEditorSelection); _this.editor.revealRangeInCenterIfOutsideViewport(_this.lastKnownEditorSelection, 0 /* Smooth */); } _this.lastKnownEditorSelection = null; // Return focus to the editor if // - focus is back on the element because no other focusable element was clicked // - a command was picked from the picker which indicates the editor should get focused if (document.activeElement === document.body || !canceled) { _this.editor.focus(); } }; this.widget = new quickOpenEditorWidget_1.QuickOpenEditorWidget(this.editor, function () { return onClose(false); }, function () { return onClose(true); }, function (value) { _this.widget.setInput(opts.getModel(value), opts.getAutoFocus(value)); }, { inputAriaLabel: opts.inputAriaLabel }, this.themeService); // Remember selection to be able to restore on cancel if (!this.lastKnownEditorSelection) { this.lastKnownEditorSelection = this.editor.getSelection(); } // Show this.widget.show(''); }; QuickOpenController.prototype.decorateLine = function (range, editor) { var oldDecorations = []; if (this.rangeHighlightDecorationId) { oldDecorations.push(this.rangeHighlightDecorationId); this.rangeHighlightDecorationId = null; } var newDecorations = [ { range: range, options: QuickOpenController._RANGE_HIGHLIGHT_DECORATION } ]; var decorations = editor.deltaDecorations(oldDecorations, newDecorations); this.rangeHighlightDecorationId = decorations[0]; }; QuickOpenController.prototype.clearDecorations = function () { if (this.rangeHighlightDecorationId) { this.editor.deltaDecorations([this.rangeHighlightDecorationId], []); this.rangeHighlightDecorationId = null; } }; QuickOpenController.ID = 'editor.controller.quickOpenController'; QuickOpenController._RANGE_HIGHLIGHT_DECORATION = textModel_1.ModelDecorationOptions.register({ className: 'rangeHighlight', isWholeLine: true }); QuickOpenController = __decorate([ __param(1, themeService_1.IThemeService) ], QuickOpenController); return QuickOpenController; }()); exports.QuickOpenController = QuickOpenController; /** * Base class for providing quick open in the editor. */ var BaseEditorQuickOpenAction = /** @class */ (function (_super) { __extends(BaseEditorQuickOpenAction, _super); function BaseEditorQuickOpenAction(inputAriaLabel, opts) { var _this = _super.call(this, opts) || this; _this._inputAriaLabel = inputAriaLabel; return _this; } BaseEditorQuickOpenAction.prototype.getController = function (editor) { return QuickOpenController.get(editor); }; BaseEditorQuickOpenAction.prototype._show = function (controller, opts) { controller.run({ inputAriaLabel: this._inputAriaLabel, getModel: function (value) { return opts.getModel(value); }, getAutoFocus: function (searchValue) { return opts.getAutoFocus(searchValue); } }); }; return BaseEditorQuickOpenAction; }(editorExtensions_1.EditorAction)); exports.BaseEditorQuickOpenAction = BaseEditorQuickOpenAction; editorExtensions_1.registerEditorContribution(QuickOpenController.ID, QuickOpenController); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[589/*vs/editor/standalone/browser/quickOpen/gotoLine*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,155/*vs/base/parts/quickopen/browser/quickOpenModel*/,108/*vs/editor/browser/editorBrowser*/,12/*vs/editor/browser/editorExtensions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,23/*vs/editor/common/editorContextKeys*/,169/*vs/editor/standalone/browser/quickOpen/editorQuickOpen*/,59/*vs/editor/common/standaloneStrings*/,329/*vs/css!vs/editor/standalone/browser/quickOpen/gotoLine*/]), function (require, exports, strings, quickOpenModel_1, editorBrowser_1, editorExtensions_1, position_1, range_1, editorContextKeys_1, editorQuickOpen_1, standaloneStrings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var GotoLineEntry = /** @class */ (function (_super) { __extends(GotoLineEntry, _super); function GotoLineEntry(line, editor, decorator) { var _this = _super.call(this) || this; _this.editor = editor; _this.decorator = decorator; _this.parseResult = _this.parseInput(line); return _this; } GotoLineEntry.prototype.parseInput = function (line) { var numbers = line.split(',').map(function (part) { return parseInt(part, 10); }).filter(function (part) { return !isNaN(part); }); var position; if (numbers.length === 0) { position = new position_1.Position(-1, -1); } else if (numbers.length === 1) { position = new position_1.Position(numbers[0], 1); } else { position = new position_1.Position(numbers[0], numbers[1]); } var model; if (editorBrowser_1.isCodeEditor(this.editor)) { model = this.editor.getModel(); } else { var diffModel = this.editor.getModel(); model = diffModel ? diffModel.modified : null; } var isValid = model ? model.validatePosition(position).equals(position) : false; var label; if (isValid) { if (position.column && position.column > 1) { label = strings.format(standaloneStrings_1.GoToLineNLS.gotoLineLabelValidLineAndColumn, position.lineNumber, position.column); } else { label = strings.format(standaloneStrings_1.GoToLineNLS.gotoLineLabelValidLine, position.lineNumber); } } else if (position.lineNumber < 1 || position.lineNumber > (model ? model.getLineCount() : 0)) { label = strings.format(standaloneStrings_1.GoToLineNLS.gotoLineLabelEmptyWithLineLimit, model ? model.getLineCount() : 0); } else { label = strings.format(standaloneStrings_1.GoToLineNLS.gotoLineLabelEmptyWithLineAndColumnLimit, model ? model.getLineMaxColumn(position.lineNumber) : 0); } return { position: position, isValid: isValid, label: label }; }; GotoLineEntry.prototype.getLabel = function () { return this.parseResult.label; }; GotoLineEntry.prototype.getAriaLabel = function () { var position = this.editor.getPosition(); var currentLine = position ? position.lineNumber : 0; return strings.format(standaloneStrings_1.GoToLineNLS.gotoLineAriaLabel, currentLine, this.parseResult.label); }; GotoLineEntry.prototype.run = function (mode, _context) { if (mode === 1 /* OPEN */) { return this.runOpen(); } return this.runPreview(); }; GotoLineEntry.prototype.runOpen = function () { // No-op if range is not valid if (!this.parseResult.isValid) { return false; } // Apply selection and focus var range = this.toSelection(); this.editor.setSelection(range); this.editor.revealRangeInCenter(range, 0 /* Smooth */); this.editor.focus(); return true; }; GotoLineEntry.prototype.runPreview = function () { // No-op if range is not valid if (!this.parseResult.isValid) { this.decorator.clearDecorations(); return false; } // Select Line Position var range = this.toSelection(); this.editor.revealRangeInCenter(range, 0 /* Smooth */); // Decorate if possible this.decorator.decorateLine(range, this.editor); return false; }; GotoLineEntry.prototype.toSelection = function () { return new range_1.Range(this.parseResult.position.lineNumber, this.parseResult.position.column, this.parseResult.position.lineNumber, this.parseResult.position.column); }; return GotoLineEntry; }(quickOpenModel_1.QuickOpenEntry)); exports.GotoLineEntry = GotoLineEntry; var GotoLineAction = /** @class */ (function (_super) { __extends(GotoLineAction, _super); function GotoLineAction() { return _super.call(this, standaloneStrings_1.GoToLineNLS.gotoLineActionInput, { id: 'editor.action.gotoLine', label: standaloneStrings_1.GoToLineNLS.gotoLineActionLabel, alias: 'Go to Line...', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 2048 /* CtrlCmd */ | 37 /* KEY_G */, mac: { primary: 256 /* WinCtrl */ | 37 /* KEY_G */ }, weight: 100 /* EditorContrib */ } }) || this; } GotoLineAction.prototype.run = function (accessor, editor) { var _this = this; this._show(this.getController(editor), { getModel: function (value) { return new quickOpenModel_1.QuickOpenModel([new GotoLineEntry(value, editor, _this.getController(editor))]); }, getAutoFocus: function (searchValue) { return { autoFocusFirstEntry: searchValue.length > 0 }; } }); }; return GotoLineAction; }(editorQuickOpen_1.BaseEditorQuickOpenAction)); exports.GotoLineAction = GotoLineAction; editorExtensions_1.registerEditorAction(GotoLineAction); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[590/*vs/editor/standalone/browser/quickOpen/quickCommand*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,24/*vs/base/browser/browser*/,10/*vs/base/common/errors*/,61/*vs/base/common/filters*/,155/*vs/base/parts/quickopen/browser/quickOpenModel*/,12/*vs/editor/browser/editorExtensions*/,23/*vs/editor/common/editorContextKeys*/,169/*vs/editor/standalone/browser/quickOpen/editorQuickOpen*/,34/*vs/platform/keybinding/common/keybinding*/,59/*vs/editor/common/standaloneStrings*/]), function (require, exports, strings, browser, errors_1, filters_1, quickOpenModel_1, editorExtensions_1, editorContextKeys_1, editorQuickOpen_1, keybinding_1, standaloneStrings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var EditorActionCommandEntry = /** @class */ (function (_super) { __extends(EditorActionCommandEntry, _super); function EditorActionCommandEntry(key, keyAriaLabel, highlights, action, editor) { var _this = _super.call(this) || this; _this.key = key; _this.keyAriaLabel = keyAriaLabel; _this.setHighlights(highlights); _this.action = action; _this.editor = editor; return _this; } EditorActionCommandEntry.prototype.getLabel = function () { return this.action.label; }; EditorActionCommandEntry.prototype.getAriaLabel = function () { if (this.keyAriaLabel) { return strings.format(standaloneStrings_1.QuickCommandNLS.ariaLabelEntryWithKey, this.getLabel(), this.keyAriaLabel); } return strings.format(standaloneStrings_1.QuickCommandNLS.ariaLabelEntry, this.getLabel()); }; EditorActionCommandEntry.prototype.getGroupLabel = function () { return this.key; }; EditorActionCommandEntry.prototype.run = function (mode, context) { var _this = this; if (mode === 1 /* OPEN */) { // Use a timeout to give the quick open widget a chance to close itself first setTimeout(function () { // Some actions are enabled only when editor has focus _this.editor.focus(); try { var promise = _this.action.run() || Promise.resolve(); promise.then(undefined, errors_1.onUnexpectedError); } catch (error) { errors_1.onUnexpectedError(error); } }, 50); return true; } return false; }; return EditorActionCommandEntry; }(quickOpenModel_1.QuickOpenEntryGroup)); exports.EditorActionCommandEntry = EditorActionCommandEntry; var QuickCommandAction = /** @class */ (function (_super) { __extends(QuickCommandAction, _super); function QuickCommandAction() { return _super.call(this, standaloneStrings_1.QuickCommandNLS.quickCommandActionInput, { id: 'editor.action.quickCommand', label: standaloneStrings_1.QuickCommandNLS.quickCommandActionLabel, alias: 'Command Palette', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: (browser.isIE ? 512 /* Alt */ | 59 /* F1 */ : 59 /* F1 */), weight: 100 /* EditorContrib */ }, contextMenuOpts: { group: 'z_commands', order: 1 } }) || this; } QuickCommandAction.prototype.run = function (accessor, editor) { var _this = this; var keybindingService = accessor.get(keybinding_1.IKeybindingService); this._show(this.getController(editor), { getModel: function (value) { return new quickOpenModel_1.QuickOpenModel(_this._editorActionsToEntries(keybindingService, editor, value)); }, getAutoFocus: function (searchValue) { return { autoFocusFirstEntry: true, autoFocusPrefixMatch: searchValue }; } }); }; QuickCommandAction.prototype._sort = function (elementA, elementB) { var elementAName = (elementA.getLabel() || '').toLowerCase(); var elementBName = (elementB.getLabel() || '').toLowerCase(); return elementAName.localeCompare(elementBName); }; QuickCommandAction.prototype._editorActionsToEntries = function (keybindingService, editor, searchValue) { var actions = editor.getSupportedActions(); var entries = []; for (var _i = 0, actions_1 = actions; _i < actions_1.length; _i++) { var action = actions_1[_i]; var keybinding = keybindingService.lookupKeybinding(action.id); if (action.label) { var highlights = filters_1.matchesFuzzy(searchValue, action.label); if (highlights) { entries.push(new EditorActionCommandEntry(keybinding ? keybinding.getLabel() || '' : '', keybinding ? keybinding.getAriaLabel() || '' : '', highlights, action, editor)); } } } // Sort by name entries = entries.sort(this._sort); return entries; }; return QuickCommandAction; }(editorQuickOpen_1.BaseEditorQuickOpenAction)); exports.QuickCommandAction = QuickCommandAction; editorExtensions_1.registerEditorAction(QuickCommandAction); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[591/*vs/editor/standalone/browser/quickOpen/quickOutline*/], __M([0/*require*/,1/*exports*/,26/*vs/base/common/cancellation*/,61/*vs/base/common/filters*/,5/*vs/base/common/strings*/,155/*vs/base/parts/quickopen/browser/quickOpenModel*/,12/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,23/*vs/editor/common/editorContextKeys*/,17/*vs/editor/common/modes*/,496/*vs/editor/contrib/quickOpen/quickOpen*/,169/*vs/editor/standalone/browser/quickOpen/editorQuickOpen*/,59/*vs/editor/common/standaloneStrings*/,330/*vs/css!vs/editor/standalone/browser/quickOpen/quickOutline*/,183/*vs/base/browser/ui/codiconLabel/codiconLabel*/,231/*vs/editor/contrib/documentSymbols/outlineTree*/]), function (require, exports, cancellation_1, filters_1, strings, quickOpenModel_1, editorExtensions_1, range_1, editorContextKeys_1, modes_1, quickOpen_1, editorQuickOpen_1, standaloneStrings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var SCOPE_PREFIX = ':'; var SymbolEntry = /** @class */ (function (_super) { __extends(SymbolEntry, _super); function SymbolEntry(name, type, description, range, highlights, editor, decorator) { var _this = _super.call(this) || this; _this.name = name; _this.type = type; _this.description = description; _this.range = range; _this.setHighlights(highlights); _this.editor = editor; _this.decorator = decorator; return _this; } SymbolEntry.prototype.getLabel = function () { return this.name; }; SymbolEntry.prototype.getAriaLabel = function () { return strings.format(standaloneStrings_1.QuickOutlineNLS.entryAriaLabel, this.name); }; SymbolEntry.prototype.getIcon = function () { return this.type; }; SymbolEntry.prototype.getDescription = function () { return this.description; }; SymbolEntry.prototype.getType = function () { return this.type; }; SymbolEntry.prototype.getRange = function () { return this.range; }; SymbolEntry.prototype.run = function (mode, context) { if (mode === 1 /* OPEN */) { return this.runOpen(context); } return this.runPreview(); }; SymbolEntry.prototype.runOpen = function (_context) { // Apply selection and focus var range = this.toSelection(); this.editor.setSelection(range); this.editor.revealRangeInCenter(range, 0 /* Smooth */); this.editor.focus(); return true; }; SymbolEntry.prototype.runPreview = function () { // Select Outline Position var range = this.toSelection(); this.editor.revealRangeInCenter(range, 0 /* Smooth */); // Decorate if possible this.decorator.decorateLine(this.range, this.editor); return false; }; SymbolEntry.prototype.toSelection = function () { return new range_1.Range(this.range.startLineNumber, this.range.startColumn || 1, this.range.startLineNumber, this.range.startColumn || 1); }; return SymbolEntry; }(quickOpenModel_1.QuickOpenEntryGroup)); exports.SymbolEntry = SymbolEntry; var QuickOutlineAction = /** @class */ (function (_super) { __extends(QuickOutlineAction, _super); function QuickOutlineAction() { return _super.call(this, standaloneStrings_1.QuickOutlineNLS.quickOutlineActionInput, { id: 'editor.action.quickOutline', label: standaloneStrings_1.QuickOutlineNLS.quickOutlineActionLabel, alias: 'Go to Symbol...', precondition: editorContextKeys_1.EditorContextKeys.hasDocumentSymbolProvider, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 45 /* KEY_O */, weight: 100 /* EditorContrib */ }, contextMenuOpts: { group: 'navigation', order: 3 } }) || this; } QuickOutlineAction.prototype.run = function (accessor, editor) { var _this = this; if (!editor.hasModel()) { return undefined; } var model = editor.getModel(); if (!modes_1.DocumentSymbolProviderRegistry.has(model)) { return undefined; } // Resolve outline return quickOpen_1.getDocumentSymbols(model, true, cancellation_1.CancellationToken.None).then(function (result) { if (result.length === 0) { return; } _this._run(editor, result); }); }; QuickOutlineAction.prototype._run = function (editor, result) { var _this = this; this._show(this.getController(editor), { getModel: function (value) { return new quickOpenModel_1.QuickOpenModel(_this.toQuickOpenEntries(editor, result, value)); }, getAutoFocus: function (searchValue) { // Remove any type pattern (:) from search value as needed if (searchValue.indexOf(SCOPE_PREFIX) === 0) { searchValue = searchValue.substr(SCOPE_PREFIX.length); } return { autoFocusPrefixMatch: searchValue, autoFocusFirstEntry: !!searchValue }; } }); }; QuickOutlineAction.prototype.symbolEntry = function (name, type, description, range, highlights, editor, decorator) { return new SymbolEntry(name, type, description, range_1.Range.lift(range), highlights, editor, decorator); }; QuickOutlineAction.prototype.toQuickOpenEntries = function (editor, flattened, searchValue) { var controller = this.getController(editor); var results = []; // Convert to Entries var normalizedSearchValue = searchValue; if (searchValue.indexOf(SCOPE_PREFIX) === 0) { normalizedSearchValue = normalizedSearchValue.substr(SCOPE_PREFIX.length); } for (var _i = 0, flattened_1 = flattened; _i < flattened_1.length; _i++) { var element = flattened_1[_i]; var label = strings.trim(element.name); // Check for meatch var highlights = filters_1.matchesFuzzy(normalizedSearchValue, label); if (highlights) { // Show parent scope as description var description = undefined; if (element.containerName) { description = element.containerName; } // Add results.push(this.symbolEntry(label, modes_1.SymbolKinds.toCssClassName(element.kind), description, element.range, highlights, editor, controller)); } } // Sort properly if actually searching if (searchValue) { if (searchValue.indexOf(SCOPE_PREFIX) === 0) { results = results.sort(this.sortScoped.bind(this, searchValue.toLowerCase())); } else { results = results.sort(this.sortNormal.bind(this, searchValue.toLowerCase())); } } // Mark all type groups if (results.length > 0 && searchValue.indexOf(SCOPE_PREFIX) === 0) { var currentType = null; var currentResult = null; var typeCounter = 0; for (var i = 0; i < results.length; i++) { var result = results[i]; // Found new type if (currentType !== result.getType()) { // Update previous result with count if (currentResult) { currentResult.setGroupLabel(this.typeToLabel(currentType || '', typeCounter)); } currentType = result.getType(); currentResult = result; typeCounter = 1; result.setShowBorder(i > 0); } // Existing type, keep counting else { typeCounter++; } } // Update previous result with count if (currentResult) { currentResult.setGroupLabel(this.typeToLabel(currentType || '', typeCounter)); } } // Mark first entry as outline else if (results.length > 0) { results[0].setGroupLabel(strings.format(standaloneStrings_1.QuickOutlineNLS._symbols_, results.length)); } return results; }; QuickOutlineAction.prototype.typeToLabel = function (type, count) { switch (type) { case 'module': return strings.format(standaloneStrings_1.QuickOutlineNLS._modules_, count); case 'class': return strings.format(standaloneStrings_1.QuickOutlineNLS._class_, count); case 'interface': return strings.format(standaloneStrings_1.QuickOutlineNLS._interface_, count); case 'method': return strings.format(standaloneStrings_1.QuickOutlineNLS._method_, count); case 'function': return strings.format(standaloneStrings_1.QuickOutlineNLS._function_, count); case 'property': return strings.format(standaloneStrings_1.QuickOutlineNLS._property_, count); case 'variable': return strings.format(standaloneStrings_1.QuickOutlineNLS._variable_, count); case 'var': return strings.format(standaloneStrings_1.QuickOutlineNLS._variable2_, count); case 'constructor': return strings.format(standaloneStrings_1.QuickOutlineNLS._constructor_, count); case 'call': return strings.format(standaloneStrings_1.QuickOutlineNLS._call_, count); } return type; }; QuickOutlineAction.prototype.sortNormal = function (searchValue, elementA, elementB) { var elementAName = elementA.getLabel().toLowerCase(); var elementBName = elementB.getLabel().toLowerCase(); // Compare by name var r = elementAName.localeCompare(elementBName); if (r !== 0) { return r; } // If name identical sort by range instead var elementARange = elementA.getRange(); var elementBRange = elementB.getRange(); return elementARange.startLineNumber - elementBRange.startLineNumber; }; QuickOutlineAction.prototype.sortScoped = function (searchValue, elementA, elementB) { // Remove scope char searchValue = searchValue.substr(SCOPE_PREFIX.length); // Sort by type first if scoped search var elementAType = elementA.getType(); var elementBType = elementB.getType(); var r = elementAType.localeCompare(elementBType); if (r !== 0) { return r; } // Special sort when searching in scoped mode if (searchValue) { var elementAName = elementA.getLabel().toLowerCase(); var elementBName = elementB.getLabel().toLowerCase(); // Compare by name var r_1 = elementAName.localeCompare(elementBName); if (r_1 !== 0) { return r_1; } } // Default to sort by range var elementARange = elementA.getRange(); var elementBRange = elementB.getRange(); return elementARange.startLineNumber - elementBRange.startLineNumber; }; return QuickOutlineAction; }(editorQuickOpen_1.BaseEditorQuickOpenAction)); exports.QuickOutlineAction = QuickOutlineAction; editorExtensions_1.registerEditorAction(QuickOutlineAction); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[592/*vs/editor/standalone/browser/standaloneCodeServiceImpl*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,46/*vs/base/common/network*/,548/*vs/editor/browser/services/codeEditorServiceImpl*/]), function (require, exports, dom_1, network_1, codeEditorServiceImpl_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var StandaloneCodeEditorServiceImpl = /** @class */ (function (_super) { __extends(StandaloneCodeEditorServiceImpl, _super); function StandaloneCodeEditorServiceImpl() { return _super !== null && _super.apply(this, arguments) || this; } StandaloneCodeEditorServiceImpl.prototype.getActiveCodeEditor = function () { return null; // not supported in the standalone case }; StandaloneCodeEditorServiceImpl.prototype.openCodeEditor = function (input, source, sideBySide) { if (!source) { return Promise.resolve(null); } return Promise.resolve(this.doOpenEditor(source, input)); }; StandaloneCodeEditorServiceImpl.prototype.doOpenEditor = function (editor, input) { var model = this.findModel(editor, input.resource); if (!model) { if (input.resource) { var schema = input.resource.scheme; if (schema === network_1.Schemas.http || schema === network_1.Schemas.https) { // This is a fully qualified http or https URL dom_1.windowOpenNoOpener(input.resource.toString()); return editor; } } return null; } var selection = (input.options ? input.options.selection : null); if (selection) { if (typeof selection.endLineNumber === 'number' && typeof selection.endColumn === 'number') { editor.setSelection(selection); editor.revealRangeInCenter(selection, 1 /* Immediate */); } else { var pos = { lineNumber: selection.startLineNumber, column: selection.startColumn }; editor.setPosition(pos); editor.revealPositionInCenter(pos, 1 /* Immediate */); } } return editor; }; StandaloneCodeEditorServiceImpl.prototype.findModel = function (editor, resource) { var model = editor.getModel(); if (model && model.uri.toString() !== resource.toString()) { return null; } return model; }; return StandaloneCodeEditorServiceImpl; }(codeEditorServiceImpl_1.CodeEditorServiceImpl)); exports.StandaloneCodeEditorServiceImpl = StandaloneCodeEditorServiceImpl; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[593/*vs/editor/standalone/common/themes*/], __M([0/*require*/,1/*exports*/,44/*vs/editor/common/view/editorColorRegistry*/,20/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, editorColorRegistry_1, colorRegistry_1) { "use strict"; var _a, _b, _c; Object.defineProperty(exports, "__esModule", { value: true }); /* -------------------------------- Begin vs theme -------------------------------- */ exports.vs = { base: 'vs', inherit: false, rules: [ { token: '', foreground: '000000', background: 'fffffe' }, { token: 'invalid', foreground: 'cd3131' }, { token: 'emphasis', fontStyle: 'italic' }, { token: 'strong', fontStyle: 'bold' }, { token: 'variable', foreground: '001188' }, { token: 'variable.predefined', foreground: '4864AA' }, { token: 'constant', foreground: 'dd0000' }, { token: 'comment', foreground: '008000' }, { token: 'number', foreground: '098658' }, { token: 'number.hex', foreground: '3030c0' }, { token: 'regexp', foreground: '800000' }, { token: 'annotation', foreground: '808080' }, { token: 'type', foreground: '008080' }, { token: 'delimiter', foreground: '000000' }, { token: 'delimiter.html', foreground: '383838' }, { token: 'delimiter.xml', foreground: '0000FF' }, { token: 'tag', foreground: '800000' }, { token: 'tag.id.pug', foreground: '4F76AC' }, { token: 'tag.class.pug', foreground: '4F76AC' }, { token: 'meta.scss', foreground: '800000' }, { token: 'metatag', foreground: 'e00000' }, { token: 'metatag.content.html', foreground: 'FF0000' }, { token: 'metatag.html', foreground: '808080' }, { token: 'metatag.xml', foreground: '808080' }, { token: 'metatag.php', fontStyle: 'bold' }, { token: 'key', foreground: '863B00' }, { token: 'string.key.json', foreground: 'A31515' }, { token: 'string.value.json', foreground: '0451A5' }, { token: 'attribute.name', foreground: 'FF0000' }, { token: 'attribute.value', foreground: '0451A5' }, { token: 'attribute.value.number', foreground: '098658' }, { token: 'attribute.value.unit', foreground: '098658' }, { token: 'attribute.value.html', foreground: '0000FF' }, { token: 'attribute.value.xml', foreground: '0000FF' }, { token: 'string', foreground: 'A31515' }, { token: 'string.html', foreground: '0000FF' }, { token: 'string.sql', foreground: 'FF0000' }, { token: 'string.yaml', foreground: '0451A5' }, { token: 'keyword', foreground: '0000FF' }, { token: 'keyword.json', foreground: '0451A5' }, { token: 'keyword.flow', foreground: 'AF00DB' }, { token: 'keyword.flow.scss', foreground: '0000FF' }, { token: 'operator.scss', foreground: '666666' }, { token: 'operator.sql', foreground: '778899' }, { token: 'operator.swift', foreground: '666666' }, { token: 'predefined.sql', foreground: 'FF00FF' }, ], colors: (_a = {}, _a[colorRegistry_1.editorBackground] = '#FFFFFE', _a[colorRegistry_1.editorForeground] = '#000000', _a[colorRegistry_1.editorInactiveSelection] = '#E5EBF1', _a[editorColorRegistry_1.editorIndentGuides] = '#D3D3D3', _a[editorColorRegistry_1.editorActiveIndentGuides] = '#939393', _a[colorRegistry_1.editorSelectionHighlight] = '#ADD6FF4D', _a) }; /* -------------------------------- End vs theme -------------------------------- */ /* -------------------------------- Begin vs-dark theme -------------------------------- */ exports.vs_dark = { base: 'vs-dark', inherit: false, rules: [ { token: '', foreground: 'D4D4D4', background: '1E1E1E' }, { token: 'invalid', foreground: 'f44747' }, { token: 'emphasis', fontStyle: 'italic' }, { token: 'strong', fontStyle: 'bold' }, { token: 'variable', foreground: '74B0DF' }, { token: 'variable.predefined', foreground: '4864AA' }, { token: 'variable.parameter', foreground: '9CDCFE' }, { token: 'constant', foreground: '569CD6' }, { token: 'comment', foreground: '608B4E' }, { token: 'number', foreground: 'B5CEA8' }, { token: 'number.hex', foreground: '5BB498' }, { token: 'regexp', foreground: 'B46695' }, { token: 'annotation', foreground: 'cc6666' }, { token: 'type', foreground: '3DC9B0' }, { token: 'delimiter', foreground: 'DCDCDC' }, { token: 'delimiter.html', foreground: '808080' }, { token: 'delimiter.xml', foreground: '808080' }, { token: 'tag', foreground: '569CD6' }, { token: 'tag.id.pug', foreground: '4F76AC' }, { token: 'tag.class.pug', foreground: '4F76AC' }, { token: 'meta.scss', foreground: 'A79873' }, { token: 'meta.tag', foreground: 'CE9178' }, { token: 'metatag', foreground: 'DD6A6F' }, { token: 'metatag.content.html', foreground: '9CDCFE' }, { token: 'metatag.html', foreground: '569CD6' }, { token: 'metatag.xml', foreground: '569CD6' }, { token: 'metatag.php', fontStyle: 'bold' }, { token: 'key', foreground: '9CDCFE' }, { token: 'string.key.json', foreground: '9CDCFE' }, { token: 'string.value.json', foreground: 'CE9178' }, { token: 'attribute.name', foreground: '9CDCFE' }, { token: 'attribute.value', foreground: 'CE9178' }, { token: 'attribute.value.number.css', foreground: 'B5CEA8' }, { token: 'attribute.value.unit.css', foreground: 'B5CEA8' }, { token: 'attribute.value.hex.css', foreground: 'D4D4D4' }, { token: 'string', foreground: 'CE9178' }, { token: 'string.sql', foreground: 'FF0000' }, { token: 'keyword', foreground: '569CD6' }, { token: 'keyword.flow', foreground: 'C586C0' }, { token: 'keyword.json', foreground: 'CE9178' }, { token: 'keyword.flow.scss', foreground: '569CD6' }, { token: 'operator.scss', foreground: '909090' }, { token: 'operator.sql', foreground: '778899' }, { token: 'operator.swift', foreground: '909090' }, { token: 'predefined.sql', foreground: 'FF00FF' }, ], colors: (_b = {}, _b[colorRegistry_1.editorBackground] = '#1E1E1E', _b[colorRegistry_1.editorForeground] = '#D4D4D4', _b[colorRegistry_1.editorInactiveSelection] = '#3A3D41', _b[editorColorRegistry_1.editorIndentGuides] = '#404040', _b[editorColorRegistry_1.editorActiveIndentGuides] = '#707070', _b[colorRegistry_1.editorSelectionHighlight] = '#ADD6FF26', _b) }; /* -------------------------------- End vs-dark theme -------------------------------- */ /* -------------------------------- Begin hc-black theme -------------------------------- */ exports.hc_black = { base: 'hc-black', inherit: false, rules: [ { token: '', foreground: 'FFFFFF', background: '000000' }, { token: 'invalid', foreground: 'f44747' }, { token: 'emphasis', fontStyle: 'italic' }, { token: 'strong', fontStyle: 'bold' }, { token: 'variable', foreground: '1AEBFF' }, { token: 'variable.parameter', foreground: '9CDCFE' }, { token: 'constant', foreground: '569CD6' }, { token: 'comment', foreground: '608B4E' }, { token: 'number', foreground: 'FFFFFF' }, { token: 'regexp', foreground: 'C0C0C0' }, { token: 'annotation', foreground: '569CD6' }, { token: 'type', foreground: '3DC9B0' }, { token: 'delimiter', foreground: 'FFFF00' }, { token: 'delimiter.html', foreground: 'FFFF00' }, { token: 'tag', foreground: '569CD6' }, { token: 'tag.id.pug', foreground: '4F76AC' }, { token: 'tag.class.pug', foreground: '4F76AC' }, { token: 'meta', foreground: 'D4D4D4' }, { token: 'meta.tag', foreground: 'CE9178' }, { token: 'metatag', foreground: '569CD6' }, { token: 'metatag.content.html', foreground: '1AEBFF' }, { token: 'metatag.html', foreground: '569CD6' }, { token: 'metatag.xml', foreground: '569CD6' }, { token: 'metatag.php', fontStyle: 'bold' }, { token: 'key', foreground: '9CDCFE' }, { token: 'string.key', foreground: '9CDCFE' }, { token: 'string.value', foreground: 'CE9178' }, { token: 'attribute.name', foreground: '569CD6' }, { token: 'attribute.value', foreground: '3FF23F' }, { token: 'string', foreground: 'CE9178' }, { token: 'string.sql', foreground: 'FF0000' }, { token: 'keyword', foreground: '569CD6' }, { token: 'keyword.flow', foreground: 'C586C0' }, { token: 'operator.sql', foreground: '778899' }, { token: 'operator.swift', foreground: '909090' }, { token: 'predefined.sql', foreground: 'FF00FF' }, ], colors: (_c = {}, _c[colorRegistry_1.editorBackground] = '#000000', _c[colorRegistry_1.editorForeground] = '#FFFFFF', _c[editorColorRegistry_1.editorIndentGuides] = '#FFFFFF', _c[editorColorRegistry_1.editorActiveIndentGuides] = '#FFFFFF', _c) }; }); /* -------------------------------- End hc-black theme -------------------------------- */ /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[594/*vs/editor/standalone/browser/standaloneThemeServiceImpl*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,27/*vs/base/common/color*/,4/*vs/base/common/event*/,17/*vs/editor/common/modes*/,357/*vs/editor/common/modes/supports/tokenization*/,593/*vs/editor/standalone/common/themes*/,42/*vs/platform/registry/common/platform*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,2/*vs/base/common/lifecycle*/]), function (require, exports, dom, color_1, event_1, modes_1, tokenization_1, themes_1, platform_1, colorRegistry_1, themeService_1, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var VS_THEME_NAME = 'vs'; var VS_DARK_THEME_NAME = 'vs-dark'; var HC_BLACK_THEME_NAME = 'hc-black'; var colorRegistry = platform_1.Registry.as(colorRegistry_1.Extensions.ColorContribution); var themingRegistry = platform_1.Registry.as(themeService_1.Extensions.ThemingContribution); var StandaloneTheme = /** @class */ (function () { function StandaloneTheme(name, standaloneThemeData) { this.themeData = standaloneThemeData; var base = standaloneThemeData.base; if (name.length > 0) { this.id = base + ' ' + name; this.themeName = name; } else { this.id = base; this.themeName = base; } this.colors = null; this.defaultColors = Object.create(null); this._tokenTheme = null; } Object.defineProperty(StandaloneTheme.prototype, "base", { get: function () { return this.themeData.base; }, enumerable: true, configurable: true }); StandaloneTheme.prototype.notifyBaseUpdated = function () { if (this.themeData.inherit) { this.colors = null; this._tokenTheme = null; } }; StandaloneTheme.prototype.getColors = function () { if (!this.colors) { var colors = new Map(); for (var id in this.themeData.colors) { colors.set(id, color_1.Color.fromHex(this.themeData.colors[id])); } if (this.themeData.inherit) { var baseData = getBuiltinRules(this.themeData.base); for (var id in baseData.colors) { if (!colors.has(id)) { colors.set(id, color_1.Color.fromHex(baseData.colors[id])); } } } this.colors = colors; } return this.colors; }; StandaloneTheme.prototype.getColor = function (colorId, useDefault) { var color = this.getColors().get(colorId); if (color) { return color; } if (useDefault !== false) { return this.getDefault(colorId); } return undefined; }; StandaloneTheme.prototype.getDefault = function (colorId) { var color = this.defaultColors[colorId]; if (color) { return color; } color = colorRegistry.resolveDefaultColor(colorId, this); this.defaultColors[colorId] = color; return color; }; StandaloneTheme.prototype.defines = function (colorId) { return Object.prototype.hasOwnProperty.call(this.getColors(), colorId); }; Object.defineProperty(StandaloneTheme.prototype, "type", { get: function () { switch (this.base) { case VS_THEME_NAME: return 'light'; case HC_BLACK_THEME_NAME: return 'hc'; default: return 'dark'; } }, enumerable: true, configurable: true }); Object.defineProperty(StandaloneTheme.prototype, "tokenTheme", { get: function () { if (!this._tokenTheme) { var rules = []; var encodedTokensColors = []; if (this.themeData.inherit) { var baseData = getBuiltinRules(this.themeData.base); rules = baseData.rules; if (baseData.encodedTokensColors) { encodedTokensColors = baseData.encodedTokensColors; } } rules = rules.concat(this.themeData.rules); if (this.themeData.encodedTokensColors) { encodedTokensColors = this.themeData.encodedTokensColors; } this._tokenTheme = tokenization_1.TokenTheme.createFromRawTokenTheme(rules, encodedTokensColors); } return this._tokenTheme; }, enumerable: true, configurable: true }); StandaloneTheme.prototype.getTokenStyleMetadata = function (type, modifiers) { return undefined; }; return StandaloneTheme; }()); function isBuiltinTheme(themeName) { return (themeName === VS_THEME_NAME || themeName === VS_DARK_THEME_NAME || themeName === HC_BLACK_THEME_NAME); } function getBuiltinRules(builtinTheme) { switch (builtinTheme) { case VS_THEME_NAME: return themes_1.vs; case VS_DARK_THEME_NAME: return themes_1.vs_dark; case HC_BLACK_THEME_NAME: return themes_1.hc_black; } } function newBuiltInTheme(builtinTheme) { var themeData = getBuiltinRules(builtinTheme); return new StandaloneTheme(builtinTheme, themeData); } var StandaloneThemeServiceImpl = /** @class */ (function (_super) { __extends(StandaloneThemeServiceImpl, _super); function StandaloneThemeServiceImpl() { var _this = _super.call(this) || this; _this._onThemeChange = _this._register(new event_1.Emitter()); _this.onThemeChange = _this._onThemeChange.event; _this._environment = Object.create(null); _this._knownThemes = new Map(); _this._knownThemes.set(VS_THEME_NAME, newBuiltInTheme(VS_THEME_NAME)); _this._knownThemes.set(VS_DARK_THEME_NAME, newBuiltInTheme(VS_DARK_THEME_NAME)); _this._knownThemes.set(HC_BLACK_THEME_NAME, newBuiltInTheme(HC_BLACK_THEME_NAME)); _this._css = ''; _this._globalStyleElement = null; _this._styleElements = []; _this.setTheme(VS_THEME_NAME); return _this; } StandaloneThemeServiceImpl.prototype.registerEditorContainer = function (domNode) { if (dom.isInShadowDOM(domNode)) { return this._registerShadowDomContainer(domNode); } return this._registerRegularEditorContainer(); }; StandaloneThemeServiceImpl.prototype._registerRegularEditorContainer = function () { if (!this._globalStyleElement) { this._globalStyleElement = dom.createStyleSheet(); this._globalStyleElement.className = 'monaco-colors'; this._globalStyleElement.innerHTML = this._css; this._styleElements.push(this._globalStyleElement); } return lifecycle_1.Disposable.None; }; StandaloneThemeServiceImpl.prototype._registerShadowDomContainer = function (domNode) { var _this = this; var styleElement = dom.createStyleSheet(domNode); styleElement.className = 'monaco-colors'; styleElement.innerHTML = this._css; this._styleElements.push(styleElement); return { dispose: function () { for (var i = 0; i < _this._styleElements.length; i++) { if (_this._styleElements[i] === styleElement) { _this._styleElements.splice(i, 1); return; } } } }; }; StandaloneThemeServiceImpl.prototype.defineTheme = function (themeName, themeData) { if (!/^[a-z0-9\-]+$/i.test(themeName)) { throw new Error('Illegal theme name!'); } if (!isBuiltinTheme(themeData.base) && !isBuiltinTheme(themeName)) { throw new Error('Illegal theme base!'); } // set or replace theme this._knownThemes.set(themeName, new StandaloneTheme(themeName, themeData)); if (isBuiltinTheme(themeName)) { this._knownThemes.forEach(function (theme) { if (theme.base === themeName) { theme.notifyBaseUpdated(); } }); } if (this._theme && this._theme.themeName === themeName) { this.setTheme(themeName); // refresh theme } }; StandaloneThemeServiceImpl.prototype.getTheme = function () { return this._theme; }; StandaloneThemeServiceImpl.prototype.setTheme = function (themeName) { var _this = this; var theme; if (this._knownThemes.has(themeName)) { theme = this._knownThemes.get(themeName); } else { theme = this._knownThemes.get(VS_THEME_NAME); } if (this._theme === theme) { // Nothing to do return theme.id; } this._theme = theme; var cssRules = []; var hasRule = {}; var ruleCollector = { addRule: function (rule) { if (!hasRule[rule]) { cssRules.push(rule); hasRule[rule] = true; } } }; themingRegistry.getThemingParticipants().forEach(function (p) { return p(theme, ruleCollector, _this._environment); }); var tokenTheme = theme.tokenTheme; var colorMap = tokenTheme.getColorMap(); ruleCollector.addRule(tokenization_1.generateTokensCSSForColorMap(colorMap)); this._css = cssRules.join('\n'); this._styleElements.forEach(function (styleElement) { return styleElement.innerHTML = _this._css; }); modes_1.TokenizationRegistry.setColorMap(colorMap); this._onThemeChange.fire(theme); return theme.id; }; StandaloneThemeServiceImpl.prototype.getIconTheme = function () { return { hasFileIcons: false, hasFolderIcons: false, hidesExplorerArrows: false }; }; return StandaloneThemeServiceImpl; }(lifecycle_1.Disposable)); exports.StandaloneThemeServiceImpl = StandaloneThemeServiceImpl; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[595/*vs/platform/contextview/browser/contextMenuService*/], __M([0/*require*/,1/*exports*/,547/*vs/platform/contextview/browser/contextMenuHandler*/,66/*vs/platform/contextview/browser/contextView*/,96/*vs/platform/telemetry/common/telemetry*/,4/*vs/base/common/event*/,35/*vs/platform/notification/common/notification*/,14/*vs/platform/theme/common/themeService*/,34/*vs/platform/keybinding/common/keybinding*/,2/*vs/base/common/lifecycle*/]), function (require, exports, contextMenuHandler_1, contextView_1, telemetry_1, event_1, notification_1, themeService_1, keybinding_1, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ContextMenuService = /** @class */ (function (_super) { __extends(ContextMenuService, _super); function ContextMenuService(telemetryService, notificationService, contextViewService, keybindingService, themeService) { var _this = _super.call(this) || this; _this._onDidContextMenu = _this._register(new event_1.Emitter()); _this.contextMenuHandler = new contextMenuHandler_1.ContextMenuHandler(contextViewService, telemetryService, notificationService, keybindingService, themeService); return _this; } ContextMenuService.prototype.configure = function (options) { this.contextMenuHandler.configure(options); }; // ContextMenu ContextMenuService.prototype.showContextMenu = function (delegate) { this.contextMenuHandler.showContextMenu(delegate); this._onDidContextMenu.fire(); }; ContextMenuService = __decorate([ __param(0, telemetry_1.ITelemetryService), __param(1, notification_1.INotificationService), __param(2, contextView_1.IContextViewService), __param(3, keybinding_1.IKeybindingService), __param(4, themeService_1.IThemeService) ], ContextMenuService); return ContextMenuService; }(lifecycle_1.Disposable)); exports.ContextMenuService = ContextMenuService; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[170/*vs/platform/list/browser/listService*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,153/*vs/base/browser/ui/list/listWidget*/,2/*vs/base/common/lifecycle*/,474/*vs/nls!vs/platform/list/browser/listService*/,43/*vs/platform/configuration/common/configuration*/,85/*vs/platform/configuration/common/configurationRegistry*/,18/*vs/platform/contextkey/common/contextkey*/,11/*vs/platform/instantiation/common/instantiation*/,34/*vs/platform/keybinding/common/keybinding*/,42/*vs/platform/registry/common/platform*/,97/*vs/platform/theme/common/styler*/,14/*vs/platform/theme/common/themeService*/,477/*vs/platform/contextkey/common/contextkeys*/,206/*vs/base/browser/ui/tree/objectTree*/,408/*vs/base/browser/ui/tree/asyncDataTree*/,407/*vs/base/browser/ui/tree/dataTree*/,64/*vs/platform/accessibility/common/accessibility*/]), function (require, exports, dom_1, listWidget_1, lifecycle_1, nls_1, configuration_1, configurationRegistry_1, contextkey_1, instantiation_1, keybinding_1, platform_1, styler_1, themeService_1, contextkeys_1, objectTree_1, asyncDataTree_1, dataTree_1, accessibility_1) { "use strict"; var _a; Object.defineProperty(exports, "__esModule", { value: true }); exports.IListService = instantiation_1.createDecorator('listService'); var ListService = /** @class */ (function () { function ListService(_themeService) { this._themeService = _themeService; this.disposables = new lifecycle_1.DisposableStore(); this.lists = []; this._lastFocusedWidget = undefined; this._hasCreatedStyleController = false; } Object.defineProperty(ListService.prototype, "lastFocusedList", { get: function () { return this._lastFocusedWidget; }, enumerable: true, configurable: true }); ListService.prototype.register = function (widget, extraContextKeys) { var _this = this; if (!this._hasCreatedStyleController) { this._hasCreatedStyleController = true; // create a shared default tree style sheet for performance reasons var styleController = new listWidget_1.DefaultStyleController(dom_1.createStyleSheet(), ''); this.disposables.add(styler_1.attachListStyler(styleController, this._themeService)); } if (this.lists.some(function (l) { return l.widget === widget; })) { throw new Error('Cannot register the same widget multiple times'); } // Keep in our lists list var registeredList = { widget: widget, extraContextKeys: extraContextKeys }; this.lists.push(registeredList); // Check for currently being focused if (widget.getHTMLElement() === document.activeElement) { this._lastFocusedWidget = widget; } return lifecycle_1.combinedDisposable(widget.onDidFocus(function () { return _this._lastFocusedWidget = widget; }), lifecycle_1.toDisposable(function () { return _this.lists.splice(_this.lists.indexOf(registeredList), 1); }), widget.onDidDispose(function () { _this.lists = _this.lists.filter(function (l) { return l !== registeredList; }); if (_this._lastFocusedWidget === widget) { _this._lastFocusedWidget = undefined; } })); }; ListService.prototype.dispose = function () { this.disposables.dispose(); }; ListService = __decorate([ __param(0, themeService_1.IThemeService) ], ListService); return ListService; }()); exports.ListService = ListService; var RawWorkbenchListFocusContextKey = new contextkey_1.RawContextKey('listFocus', true); exports.WorkbenchListSupportsMultiSelectContextKey = new contextkey_1.RawContextKey('listSupportsMultiselect', true); exports.WorkbenchListFocusContextKey = contextkey_1.ContextKeyExpr.and(RawWorkbenchListFocusContextKey, contextkey_1.ContextKeyExpr.not(contextkeys_1.InputFocusedContextKey)); exports.WorkbenchListHasSelectionOrFocus = new contextkey_1.RawContextKey('listHasSelectionOrFocus', false); exports.WorkbenchListDoubleSelection = new contextkey_1.RawContextKey('listDoubleSelection', false); exports.WorkbenchListMultiSelection = new contextkey_1.RawContextKey('listMultiSelection', false); exports.WorkbenchListSupportsKeyboardNavigation = new contextkey_1.RawContextKey('listSupportsKeyboardNavigation', true); exports.WorkbenchListAutomaticKeyboardNavigationKey = 'listAutomaticKeyboardNavigation'; exports.WorkbenchListAutomaticKeyboardNavigation = new contextkey_1.RawContextKey(exports.WorkbenchListAutomaticKeyboardNavigationKey, true); exports.didBindWorkbenchListAutomaticKeyboardNavigation = false; function createScopedContextKeyService(contextKeyService, widget) { var result = contextKeyService.createScoped(widget.getHTMLElement()); RawWorkbenchListFocusContextKey.bindTo(result); return result; } exports.multiSelectModifierSettingKey = 'workbench.list.multiSelectModifier'; exports.openModeSettingKey = 'workbench.list.openMode'; exports.horizontalScrollingKey = 'workbench.list.horizontalScrolling'; exports.keyboardNavigationSettingKey = 'workbench.list.keyboardNavigation'; exports.automaticKeyboardNavigationSettingKey = 'workbench.list.automaticKeyboardNavigation'; var treeIndentKey = 'workbench.tree.indent'; var treeRenderIndentGuidesKey = 'workbench.tree.renderIndentGuides'; function getHorizontalScrollingSetting(configurationService) { return configuration_1.getMigratedSettingValue(configurationService, exports.horizontalScrollingKey, 'workbench.tree.horizontalScrolling'); } function useAltAsMultipleSelectionModifier(configurationService) { return configurationService.getValue(exports.multiSelectModifierSettingKey) === 'alt'; } function useSingleClickToOpen(configurationService) { return configurationService.getValue(exports.openModeSettingKey) !== 'doubleClick'; } var MultipleSelectionController = /** @class */ (function (_super) { __extends(MultipleSelectionController, _super); function MultipleSelectionController(configurationService) { var _this = _super.call(this) || this; _this.configurationService = configurationService; _this.useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService); _this.registerListeners(); return _this; } MultipleSelectionController.prototype.registerListeners = function () { var _this = this; this._register(this.configurationService.onDidChangeConfiguration(function (e) { if (e.affectsConfiguration(exports.multiSelectModifierSettingKey)) { _this.useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(_this.configurationService); } })); }; MultipleSelectionController.prototype.isSelectionSingleChangeEvent = function (event) { if (this.useAltAsMultipleSelectionModifier) { return event.browserEvent.altKey; } return listWidget_1.isSelectionSingleChangeEvent(event); }; MultipleSelectionController.prototype.isSelectionRangeChangeEvent = function (event) { return listWidget_1.isSelectionRangeChangeEvent(event); }; return MultipleSelectionController; }(lifecycle_1.Disposable)); var WorkbenchOpenController = /** @class */ (function (_super) { __extends(WorkbenchOpenController, _super); function WorkbenchOpenController(configurationService, existingOpenController) { var _this = _super.call(this) || this; _this.configurationService = configurationService; _this.existingOpenController = existingOpenController; _this.openOnSingleClick = useSingleClickToOpen(configurationService); _this.registerListeners(); return _this; } WorkbenchOpenController.prototype.registerListeners = function () { var _this = this; this._register(this.configurationService.onDidChangeConfiguration(function (e) { if (e.affectsConfiguration(exports.openModeSettingKey)) { _this.openOnSingleClick = useSingleClickToOpen(_this.configurationService); } })); }; WorkbenchOpenController.prototype.shouldOpen = function (event) { if (event instanceof MouseEvent) { var isLeftButton = event.button === 0; var isDoubleClick = event.detail === 2; if (isLeftButton && !this.openOnSingleClick && !isDoubleClick) { return false; } if (isLeftButton /* left mouse button */ || event.button === 1 /* middle mouse button */) { return this.existingOpenController ? this.existingOpenController.shouldOpen(event) : true; } return false; } return this.existingOpenController ? this.existingOpenController.shouldOpen(event) : true; }; return WorkbenchOpenController; }(lifecycle_1.Disposable)); function toWorkbenchListOptions(options, configurationService, keybindingService) { var disposables = new lifecycle_1.DisposableStore(); var result = __assign({}, options); if (options.multipleSelectionSupport !== false && !options.multipleSelectionController) { var multipleSelectionController = new MultipleSelectionController(configurationService); result.multipleSelectionController = multipleSelectionController; disposables.add(multipleSelectionController); } var openController = new WorkbenchOpenController(configurationService, options.openController); result.openController = openController; disposables.add(openController); result.keyboardNavigationDelegate = { mightProducePrintableCharacter: function (e) { return keybindingService.mightProducePrintableCharacter(e); } }; return [result, disposables]; } function createKeyboardNavigationEventFilter(container, keybindingService) { var inChord = false; return function (event) { if (inChord) { inChord = false; return false; } var result = keybindingService.softDispatch(event, container); if (result && result.enterChord) { inChord = true; return false; } inChord = false; return true; }; } var WorkbenchObjectTree = /** @class */ (function (_super) { __extends(WorkbenchObjectTree, _super); function WorkbenchObjectTree(user, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) { var _this = this; var _a = workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService), treeOptions = _a.options, getAutomaticKeyboardNavigation = _a.getAutomaticKeyboardNavigation, disposable = _a.disposable; _this = _super.call(this, user, container, delegate, renderers, treeOptions) || this; _this.disposables.add(disposable); _this.internals = new WorkbenchTreeInternals(_this, treeOptions, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService); _this.disposables.add(_this.internals); return _this; } WorkbenchObjectTree = __decorate([ __param(5, contextkey_1.IContextKeyService), __param(6, exports.IListService), __param(7, themeService_1.IThemeService), __param(8, configuration_1.IConfigurationService), __param(9, keybinding_1.IKeybindingService), __param(10, accessibility_1.IAccessibilityService) ], WorkbenchObjectTree); return WorkbenchObjectTree; }(objectTree_1.ObjectTree)); exports.WorkbenchObjectTree = WorkbenchObjectTree; var WorkbenchDataTree = /** @class */ (function (_super) { __extends(WorkbenchDataTree, _super); function WorkbenchDataTree(user, container, delegate, renderers, dataSource, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) { var _this = this; var _a = workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService), treeOptions = _a.options, getAutomaticKeyboardNavigation = _a.getAutomaticKeyboardNavigation, disposable = _a.disposable; _this = _super.call(this, user, container, delegate, renderers, dataSource, treeOptions) || this; _this.disposables.add(disposable); _this.internals = new WorkbenchTreeInternals(_this, treeOptions, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService); _this.disposables.add(_this.internals); return _this; } WorkbenchDataTree.prototype.updateOptions = function (options) { if (options === void 0) { options = {}; } _super.prototype.updateOptions.call(this, options); if (options.overrideStyles) { this.internals.updateStyleOverrides(options.overrideStyles); } }; WorkbenchDataTree = __decorate([ __param(6, contextkey_1.IContextKeyService), __param(7, exports.IListService), __param(8, themeService_1.IThemeService), __param(9, configuration_1.IConfigurationService), __param(10, keybinding_1.IKeybindingService), __param(11, accessibility_1.IAccessibilityService) ], WorkbenchDataTree); return WorkbenchDataTree; }(dataTree_1.DataTree)); exports.WorkbenchDataTree = WorkbenchDataTree; var WorkbenchAsyncDataTree = /** @class */ (function (_super) { __extends(WorkbenchAsyncDataTree, _super); function WorkbenchAsyncDataTree(user, container, delegate, renderers, dataSource, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) { var _this = this; var _a = workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService), treeOptions = _a.options, getAutomaticKeyboardNavigation = _a.getAutomaticKeyboardNavigation, disposable = _a.disposable; _this = _super.call(this, user, container, delegate, renderers, dataSource, treeOptions) || this; _this.disposables.add(disposable); _this.internals = new WorkbenchTreeInternals(_this, treeOptions, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService); _this.disposables.add(_this.internals); return _this; } WorkbenchAsyncDataTree.prototype.updateOptions = function (options) { if (options === void 0) { options = {}; } _super.prototype.updateOptions.call(this, options); if (options.overrideStyles) { this.internals.updateStyleOverrides(options.overrideStyles); } }; WorkbenchAsyncDataTree = __decorate([ __param(6, contextkey_1.IContextKeyService), __param(7, exports.IListService), __param(8, themeService_1.IThemeService), __param(9, configuration_1.IConfigurationService), __param(10, keybinding_1.IKeybindingService), __param(11, accessibility_1.IAccessibilityService) ], WorkbenchAsyncDataTree); return WorkbenchAsyncDataTree; }(asyncDataTree_1.AsyncDataTree)); exports.WorkbenchAsyncDataTree = WorkbenchAsyncDataTree; var WorkbenchCompressibleAsyncDataTree = /** @class */ (function (_super) { __extends(WorkbenchCompressibleAsyncDataTree, _super); function WorkbenchCompressibleAsyncDataTree(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) { var _this = this; var _a = workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService), treeOptions = _a.options, getAutomaticKeyboardNavigation = _a.getAutomaticKeyboardNavigation, disposable = _a.disposable; _this = _super.call(this, user, container, virtualDelegate, compressionDelegate, renderers, dataSource, treeOptions) || this; _this.disposables.add(disposable); _this.internals = new WorkbenchTreeInternals(_this, treeOptions, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService); _this.disposables.add(_this.internals); return _this; } WorkbenchCompressibleAsyncDataTree = __decorate([ __param(7, contextkey_1.IContextKeyService), __param(8, exports.IListService), __param(9, themeService_1.IThemeService), __param(10, configuration_1.IConfigurationService), __param(11, keybinding_1.IKeybindingService), __param(12, accessibility_1.IAccessibilityService) ], WorkbenchCompressibleAsyncDataTree); return WorkbenchCompressibleAsyncDataTree; }(asyncDataTree_1.CompressibleAsyncDataTree)); exports.WorkbenchCompressibleAsyncDataTree = WorkbenchCompressibleAsyncDataTree; function workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService) { exports.WorkbenchListSupportsKeyboardNavigation.bindTo(contextKeyService); if (!exports.didBindWorkbenchListAutomaticKeyboardNavigation) { exports.WorkbenchListAutomaticKeyboardNavigation.bindTo(contextKeyService); exports.didBindWorkbenchListAutomaticKeyboardNavigation = true; } var getAutomaticKeyboardNavigation = function () { // give priority to the context key value to disable this completely var automaticKeyboardNavigation = contextKeyService.getContextKeyValue(exports.WorkbenchListAutomaticKeyboardNavigationKey); if (automaticKeyboardNavigation) { automaticKeyboardNavigation = configurationService.getValue(exports.automaticKeyboardNavigationSettingKey); } return automaticKeyboardNavigation; }; var accessibilityOn = accessibilityService.isScreenReaderOptimized(); var keyboardNavigation = accessibilityOn ? 'simple' : configurationService.getValue(exports.keyboardNavigationSettingKey); var horizontalScrolling = typeof options.horizontalScrolling !== 'undefined' ? options.horizontalScrolling : getHorizontalScrollingSetting(configurationService); var openOnSingleClick = useSingleClickToOpen(configurationService); var _a = toWorkbenchListOptions(options, configurationService, keybindingService), workbenchListOptions = _a[0], disposable = _a[1]; var additionalScrollHeight = options.additionalScrollHeight; return { getAutomaticKeyboardNavigation: getAutomaticKeyboardNavigation, disposable: disposable, options: __assign(__assign({ // ...options, // TODO@Joao why is this not splatted here? keyboardSupport: false }, workbenchListOptions), { indent: configurationService.getValue(treeIndentKey), renderIndentGuides: configurationService.getValue(treeRenderIndentGuidesKey), automaticKeyboardNavigation: getAutomaticKeyboardNavigation(), simpleKeyboardNavigation: keyboardNavigation === 'simple', filterOnType: keyboardNavigation === 'filter', horizontalScrolling: horizontalScrolling, openOnSingleClick: openOnSingleClick, keyboardNavigationEventFilter: createKeyboardNavigationEventFilter(container, keybindingService), additionalScrollHeight: additionalScrollHeight, hideTwistiesOfChildlessElements: options.hideTwistiesOfChildlessElements }) }; } var WorkbenchTreeInternals = /** @class */ (function () { function WorkbenchTreeInternals(tree, options, getAutomaticKeyboardNavigation, overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService) { var _this = this; this.tree = tree; this.themeService = themeService; this.disposables = []; this.contextKeyService = createScopedContextKeyService(contextKeyService, tree); var listSupportsMultiSelect = exports.WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService); listSupportsMultiSelect.set(!(options.multipleSelectionSupport === false)); this.hasSelectionOrFocus = exports.WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService); this.hasDoubleSelection = exports.WorkbenchListDoubleSelection.bindTo(this.contextKeyService); this.hasMultiSelection = exports.WorkbenchListMultiSelection.bindTo(this.contextKeyService); this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService); var interestingContextKeys = new Set(); interestingContextKeys.add(exports.WorkbenchListAutomaticKeyboardNavigationKey); var updateKeyboardNavigation = function () { var accessibilityOn = accessibilityService.isScreenReaderOptimized(); var keyboardNavigation = accessibilityOn ? 'simple' : configurationService.getValue(exports.keyboardNavigationSettingKey); tree.updateOptions({ simpleKeyboardNavigation: keyboardNavigation === 'simple', filterOnType: keyboardNavigation === 'filter' }); }; this.updateStyleOverrides(overrideStyles); this.disposables.push(this.contextKeyService, listService.register(tree), tree.onDidChangeSelection(function () { var selection = tree.getSelection(); var focus = tree.getFocus(); _this.hasSelectionOrFocus.set(selection.length > 0 || focus.length > 0); _this.hasMultiSelection.set(selection.length > 1); _this.hasDoubleSelection.set(selection.length === 2); }), tree.onDidChangeFocus(function () { var selection = tree.getSelection(); var focus = tree.getFocus(); _this.hasSelectionOrFocus.set(selection.length > 0 || focus.length > 0); }), configurationService.onDidChangeConfiguration(function (e) { if (e.affectsConfiguration(exports.openModeSettingKey)) { tree.updateOptions({ openOnSingleClick: useSingleClickToOpen(configurationService) }); } if (e.affectsConfiguration(exports.multiSelectModifierSettingKey)) { _this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService); } if (e.affectsConfiguration(treeIndentKey)) { var indent = configurationService.getValue(treeIndentKey); tree.updateOptions({ indent: indent }); } if (e.affectsConfiguration(treeRenderIndentGuidesKey)) { var renderIndentGuides = configurationService.getValue(treeRenderIndentGuidesKey); tree.updateOptions({ renderIndentGuides: renderIndentGuides }); } if (e.affectsConfiguration(exports.keyboardNavigationSettingKey)) { updateKeyboardNavigation(); } if (e.affectsConfiguration(exports.automaticKeyboardNavigationSettingKey)) { tree.updateOptions({ automaticKeyboardNavigation: getAutomaticKeyboardNavigation() }); } }), this.contextKeyService.onDidChangeContext(function (e) { if (e.affectsSome(interestingContextKeys)) { tree.updateOptions({ automaticKeyboardNavigation: getAutomaticKeyboardNavigation() }); } }), accessibilityService.onDidChangeScreenReaderOptimized(function () { return updateKeyboardNavigation(); })); } WorkbenchTreeInternals.prototype.updateStyleOverrides = function (overrideStyles) { lifecycle_1.dispose(this.styler); this.styler = overrideStyles ? styler_1.attachListStyler(this.tree, this.themeService, overrideStyles) : lifecycle_1.Disposable.None; }; WorkbenchTreeInternals.prototype.dispose = function () { this.disposables = lifecycle_1.dispose(this.disposables); this.styler = lifecycle_1.dispose(this.styler); }; WorkbenchTreeInternals = __decorate([ __param(4, contextkey_1.IContextKeyService), __param(5, exports.IListService), __param(6, themeService_1.IThemeService), __param(7, configuration_1.IConfigurationService), __param(8, accessibility_1.IAccessibilityService) ], WorkbenchTreeInternals); return WorkbenchTreeInternals; }()); var configurationRegistry = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration); configurationRegistry.registerConfiguration({ 'id': 'workbench', 'order': 7, 'title': nls_1.localize(0, null), 'type': 'object', 'properties': (_a = {}, _a[exports.multiSelectModifierSettingKey] = { 'type': 'string', 'enum': ['ctrlCmd', 'alt'], 'enumDescriptions': [ nls_1.localize(1, null), nls_1.localize(2, null) ], 'default': 'ctrlCmd', 'description': nls_1.localize(3, null) }, _a[exports.openModeSettingKey] = { 'type': 'string', 'enum': ['singleClick', 'doubleClick'], 'default': 'singleClick', 'description': nls_1.localize(4, null) }, _a[exports.horizontalScrollingKey] = { 'type': 'boolean', 'default': false, 'description': nls_1.localize(5, null) }, _a['workbench.tree.horizontalScrolling'] = { 'type': 'boolean', 'default': false, 'description': nls_1.localize(6, null), 'deprecationMessage': nls_1.localize(7, null, exports.horizontalScrollingKey) }, _a[treeIndentKey] = { 'type': 'number', 'default': 8, minimum: 0, maximum: 40, 'description': nls_1.localize(8, null) }, _a[treeRenderIndentGuidesKey] = { type: 'string', enum: ['none', 'onHover', 'always'], default: 'onHover', description: nls_1.localize(9, null) }, _a[exports.keyboardNavigationSettingKey] = { 'type': 'string', 'enum': ['simple', 'highlight', 'filter'], 'enumDescriptions': [ nls_1.localize(10, null), nls_1.localize(11, null), nls_1.localize(12, null) ], 'default': 'highlight', 'description': nls_1.localize(13, null) }, _a[exports.automaticKeyboardNavigationSettingKey] = { 'type': 'boolean', 'default': true, markdownDescription: nls_1.localize(14, null) }, _a) }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[596/*vs/editor/contrib/gotoSymbol/peek/referencesWidget*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,27/*vs/base/common/color*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,46/*vs/base/common/network*/,39/*vs/base/common/resources*/,167/*vs/editor/browser/widget/embeddedCodeEditorWidget*/,3/*vs/editor/common/core/range*/,30/*vs/editor/common/model/textModel*/,84/*vs/editor/common/services/resolverService*/,575/*vs/editor/contrib/gotoSymbol/peek/referencesTree*/,450/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesWidget*/,11/*vs/platform/instantiation/common/instantiation*/,116/*vs/platform/label/common/label*/,170/*vs/platform/list/browser/listService*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,123/*vs/editor/contrib/peekView/peekView*/,113/*vs/editor/contrib/gotoSymbol/referencesModel*/,279/*vs/base/browser/ui/splitview/splitview*/,314/*vs/css!vs/editor/contrib/gotoSymbol/peek/referencesWidget*/]), function (require, exports, dom, color_1, event_1, lifecycle_1, network_1, resources_1, embeddedCodeEditorWidget_1, range_1, textModel_1, resolverService_1, referencesTree_1, nls, instantiation_1, label_1, listService_1, colorRegistry_1, themeService_1, peekView, referencesModel_1, splitview_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DecorationsManager = /** @class */ (function () { function DecorationsManager(_editor, _model) { var _this = this; this._editor = _editor; this._model = _model; this._decorations = new Map(); this._decorationIgnoreSet = new Set(); this._callOnDispose = new lifecycle_1.DisposableStore(); this._callOnModelChange = new lifecycle_1.DisposableStore(); this._callOnDispose.add(this._editor.onDidChangeModel(function () { return _this._onModelChanged(); })); this._onModelChanged(); } DecorationsManager.prototype.dispose = function () { this._callOnModelChange.dispose(); this._callOnDispose.dispose(); this.removeDecorations(); }; DecorationsManager.prototype._onModelChanged = function () { this._callOnModelChange.clear(); var model = this._editor.getModel(); if (model) { for (var _i = 0, _a = this._model.groups; _i < _a.length; _i++) { var ref = _a[_i]; if (resources_1.isEqual(ref.uri, model.uri)) { this._addDecorations(ref); return; } } } }; DecorationsManager.prototype._addDecorations = function (reference) { var _this = this; if (!this._editor.hasModel()) { return; } this._callOnModelChange.add(this._editor.getModel().onDidChangeDecorations(function (event) { return _this._onDecorationChanged(); })); var newDecorations = []; var newDecorationsActualIndex = []; for (var i = 0, len = reference.children.length; i < len; i++) { var oneReference = reference.children[i]; if (this._decorationIgnoreSet.has(oneReference.id)) { continue; } newDecorations.push({ range: oneReference.range, options: DecorationsManager.DecorationOptions }); newDecorationsActualIndex.push(i); } var decorations = this._editor.deltaDecorations([], newDecorations); for (var i = 0; i < decorations.length; i++) { this._decorations.set(decorations[i], reference.children[newDecorationsActualIndex[i]]); } }; DecorationsManager.prototype._onDecorationChanged = function () { var _this = this; var toRemove = []; var model = this._editor.getModel(); if (!model) { return; } this._decorations.forEach(function (reference, decorationId) { var newRange = model.getDecorationRange(decorationId); if (!newRange) { return; } var ignore = false; if (range_1.Range.equalsRange(newRange, reference.range)) { return; } else if (range_1.Range.spansMultipleLines(newRange)) { ignore = true; } else { var lineLength = reference.range.endColumn - reference.range.startColumn; var newLineLength = newRange.endColumn - newRange.startColumn; if (lineLength !== newLineLength) { ignore = true; } } if (ignore) { _this._decorationIgnoreSet.add(reference.id); toRemove.push(decorationId); } else { reference.range = newRange; } }); for (var i = 0, len = toRemove.length; i < len; i++) { this._decorations.delete(toRemove[i]); } this._editor.deltaDecorations(toRemove, []); }; DecorationsManager.prototype.removeDecorations = function () { var toRemove = []; this._decorations.forEach(function (value, key) { toRemove.push(key); }); this._editor.deltaDecorations(toRemove, []); this._decorations.clear(); }; DecorationsManager.DecorationOptions = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'reference-decoration' }); return DecorationsManager; }()); var LayoutData = /** @class */ (function () { function LayoutData() { this.ratio = 0.7; this.heightInLines = 18; } LayoutData.fromJSON = function (raw) { var ratio; var heightInLines; try { var data = JSON.parse(raw); ratio = data.ratio; heightInLines = data.heightInLines; } catch (_a) { // } return { ratio: ratio || 0.7, heightInLines: heightInLines || 18 }; }; return LayoutData; }()); exports.LayoutData = LayoutData; /** * ZoneWidget that is shown inside the editor */ var ReferenceWidget = /** @class */ (function (_super) { __extends(ReferenceWidget, _super); function ReferenceWidget(editor, _defaultTreeKeyboardSupport, layoutData, themeService, _textModelResolverService, _instantiationService, _peekViewService, _uriLabel) { var _this = _super.call(this, editor, { showFrame: false, showArrow: true, isResizeable: true, isAccessible: true }) || this; _this._defaultTreeKeyboardSupport = _defaultTreeKeyboardSupport; _this.layoutData = layoutData; _this._textModelResolverService = _textModelResolverService; _this._instantiationService = _instantiationService; _this._peekViewService = _peekViewService; _this._uriLabel = _uriLabel; _this._disposeOnNewModel = new lifecycle_1.DisposableStore(); _this._callOnDispose = new lifecycle_1.DisposableStore(); _this._onDidSelectReference = new event_1.Emitter(); _this.onDidSelectReference = _this._onDidSelectReference.event; _this._dim = { height: 0, width: 0 }; _this._applyTheme(themeService.getTheme()); _this._callOnDispose.add(themeService.onThemeChange(_this._applyTheme.bind(_this))); _this._peekViewService.addExclusiveWidget(editor, _this); _this.create(); return _this; } ReferenceWidget.prototype.dispose = function () { this.setModel(undefined); this._callOnDispose.dispose(); this._disposeOnNewModel.dispose(); lifecycle_1.dispose(this._preview); lifecycle_1.dispose(this._previewNotAvailableMessage); lifecycle_1.dispose(this._tree); lifecycle_1.dispose(this._previewModelReference); this._splitView.dispose(); _super.prototype.dispose.call(this); }; ReferenceWidget.prototype._applyTheme = function (theme) { var borderColor = theme.getColor(peekView.peekViewBorder) || color_1.Color.transparent; this.style({ arrowColor: borderColor, frameColor: borderColor, headerBackgroundColor: theme.getColor(peekView.peekViewTitleBackground) || color_1.Color.transparent, primaryHeadingColor: theme.getColor(peekView.peekViewTitleForeground), secondaryHeadingColor: theme.getColor(peekView.peekViewTitleInfoForeground) }); }; ReferenceWidget.prototype.show = function (where) { this.editor.revealRangeInCenterIfOutsideViewport(where, 0 /* Smooth */); _super.prototype.show.call(this, where, this.layoutData.heightInLines || 18); }; ReferenceWidget.prototype.focusOnReferenceTree = function () { this._tree.domFocus(); }; ReferenceWidget.prototype.focusOnPreviewEditor = function () { this._preview.focus(); }; ReferenceWidget.prototype.isPreviewEditorFocused = function () { return this._preview.hasTextFocus(); }; ReferenceWidget.prototype._onTitleClick = function (e) { if (this._preview && this._preview.getModel()) { this._onDidSelectReference.fire({ element: this._getFocusedReference(), kind: e.ctrlKey || e.metaKey || e.altKey ? 'side' : 'open', source: 'title' }); } }; ReferenceWidget.prototype._fillBody = function (containerElement) { var _this = this; this.setCssClass('reference-zone-widget'); // message pane this._messageContainer = dom.append(containerElement, dom.$('div.messages')); dom.hide(this._messageContainer); this._splitView = new splitview_1.SplitView(containerElement, { orientation: 1 /* HORIZONTAL */ }); // editor this._previewContainer = dom.append(containerElement, dom.$('div.preview.inline')); var options = { scrollBeyondLastLine: false, scrollbar: { verticalScrollbarSize: 14, horizontal: 'auto', useShadows: true, verticalHasArrows: false, horizontalHasArrows: false, alwaysConsumeMouseWheel: false }, overviewRulerLanes: 2, fixedOverflowWidgets: true, minimap: { enabled: false } }; this._preview = this._instantiationService.createInstance(embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget, this._previewContainer, options, this.editor); dom.hide(this._previewContainer); this._previewNotAvailableMessage = textModel_1.TextModel.createFromString(nls.localize(0, null)); // tree this._treeContainer = dom.append(containerElement, dom.$('div.ref-tree.inline')); var treeOptions = { ariaLabel: nls.localize(1, null), keyboardSupport: this._defaultTreeKeyboardSupport, accessibilityProvider: new referencesTree_1.AriaProvider(), keyboardNavigationLabelProvider: this._instantiationService.createInstance(referencesTree_1.StringRepresentationProvider), identityProvider: new referencesTree_1.IdentityProvider(), overrideStyles: { listBackground: peekView.peekViewResultsBackground } }; this._tree = this._instantiationService.createInstance(listService_1.WorkbenchAsyncDataTree, 'ReferencesWidget', this._treeContainer, new referencesTree_1.Delegate(), [ this._instantiationService.createInstance(referencesTree_1.FileReferencesRenderer), this._instantiationService.createInstance(referencesTree_1.OneReferenceRenderer), ], this._instantiationService.createInstance(referencesTree_1.DataSource), treeOptions); // split stuff this._splitView.addView({ onDidChange: event_1.Event.None, element: this._previewContainer, minimumSize: 200, maximumSize: Number.MAX_VALUE, layout: function (width) { _this._preview.layout({ height: _this._dim.height, width: width }); } }, splitview_1.Sizing.Distribute); this._splitView.addView({ onDidChange: event_1.Event.None, element: this._treeContainer, minimumSize: 100, maximumSize: Number.MAX_VALUE, layout: function (width) { _this._treeContainer.style.height = _this._dim.height + "px"; _this._treeContainer.style.width = width + "px"; _this._tree.layout(_this._dim.height, width); } }, splitview_1.Sizing.Distribute); this._disposables.add(this._splitView.onDidSashChange(function () { if (_this._dim.width) { _this.layoutData.ratio = _this._splitView.getViewSize(0) / _this._dim.width; } }, undefined)); // listen on selection and focus var onEvent = function (element, kind) { if (element instanceof referencesModel_1.OneReference) { if (kind === 'show') { _this._revealReference(element, false); } _this._onDidSelectReference.fire({ element: element, kind: kind, source: 'tree' }); } }; this._tree.onDidChangeFocus(function (e) { onEvent(e.elements[0], 'show'); }); this._tree.onDidOpen(function (e) { if (e.browserEvent instanceof MouseEvent && (e.browserEvent.ctrlKey || e.browserEvent.metaKey || e.browserEvent.altKey)) { // modifier-click -> open to the side onEvent(e.elements[0], 'side'); } else if (e.browserEvent instanceof KeyboardEvent || (e.browserEvent instanceof MouseEvent && e.browserEvent.detail === 2) || e.browserEvent.tapCount === 2) { // keybinding (list service command) // OR double click // OR double tap // -> close widget and goto target onEvent(e.elements[0], 'goto'); } else { // preview location onEvent(e.elements[0], 'show'); } }); dom.hide(this._treeContainer); }; ReferenceWidget.prototype._onWidth = function (width) { if (this._dim) { this._doLayoutBody(this._dim.height, width); } }; ReferenceWidget.prototype._doLayoutBody = function (heightInPixel, widthInPixel) { _super.prototype._doLayoutBody.call(this, heightInPixel, widthInPixel); this._dim = { height: heightInPixel, width: widthInPixel }; this.layoutData.heightInLines = this._viewZone ? this._viewZone.heightInLines : this.layoutData.heightInLines; this._splitView.layout(widthInPixel); this._splitView.resizeView(0, widthInPixel * this.layoutData.ratio); }; ReferenceWidget.prototype.setSelection = function (selection) { var _this = this; return this._revealReference(selection, true).then(function () { if (!_this._model) { // disposed return; } // show in tree _this._tree.setSelection([selection]); _this._tree.setFocus([selection]); }); }; ReferenceWidget.prototype.setModel = function (newModel) { // clean up this._disposeOnNewModel.clear(); this._model = newModel; if (this._model) { return this._onNewModel(); } return Promise.resolve(); }; ReferenceWidget.prototype._onNewModel = function () { var _this = this; if (!this._model) { return Promise.resolve(undefined); } if (this._model.isEmpty) { this.setTitle(''); this._messageContainer.innerHTML = nls.localize(2, null); dom.show(this._messageContainer); return Promise.resolve(undefined); } dom.hide(this._messageContainer); this._decorationsManager = new DecorationsManager(this._preview, this._model); this._disposeOnNewModel.add(this._decorationsManager); // listen on model changes this._disposeOnNewModel.add(this._model.onDidChangeReferenceRange(function (reference) { return _this._tree.rerender(reference); })); // listen on editor this._disposeOnNewModel.add(this._preview.onMouseDown(function (e) { var event = e.event, target = e.target; if (event.detail !== 2) { return; } var element = _this._getFocusedReference(); if (!element) { return; } _this._onDidSelectReference.fire({ element: { uri: element.uri, range: target.range }, kind: (event.ctrlKey || event.metaKey || event.altKey) ? 'side' : 'open', source: 'editor' }); })); // make sure things are rendered dom.addClass(this.container, 'results-loaded'); dom.show(this._treeContainer); dom.show(this._previewContainer); this._splitView.layout(this._dim.width); this.focusOnReferenceTree(); // pick input and a reference to begin with return this._tree.setInput(this._model.groups.length === 1 ? this._model.groups[0] : this._model); }; ReferenceWidget.prototype._getFocusedReference = function () { var element = this._tree.getFocus()[0]; if (element instanceof referencesModel_1.OneReference) { return element; } else if (element instanceof referencesModel_1.FileReferences) { if (element.children.length > 0) { return element.children[0]; } } return undefined; }; ReferenceWidget.prototype._revealReference = function (reference, revealParent) { return __awaiter(this, void 0, void 0, function () { var promise, ref, model, scrollType, sel; return __generator(this, function (_a) { switch (_a.label) { case 0: // check if there is anything to do... if (this._revealedReference === reference) { return [2 /*return*/]; } this._revealedReference = reference; // Update widget header if (reference.uri.scheme !== network_1.Schemas.inMemory) { this.setTitle(resources_1.basenameOrAuthority(reference.uri), this._uriLabel.getUriLabel(resources_1.dirname(reference.uri))); } else { this.setTitle(nls.localize(3, null)); } promise = this._textModelResolverService.createModelReference(reference.uri); if (!(this._tree.getInput() === reference.parent)) return [3 /*break*/, 1]; this._tree.reveal(reference); return [3 /*break*/, 3]; case 1: if (revealParent) { this._tree.reveal(reference.parent); } return [4 /*yield*/, this._tree.expand(reference.parent)]; case 2: _a.sent(); this._tree.reveal(reference); _a.label = 3; case 3: return [4 /*yield*/, promise]; case 4: ref = _a.sent(); if (!this._model) { // disposed ref.dispose(); return [2 /*return*/]; } lifecycle_1.dispose(this._previewModelReference); model = ref.object; if (model) { scrollType = this._preview.getModel() === model.textEditorModel ? 0 /* Smooth */ : 1 /* Immediate */; sel = range_1.Range.lift(reference.range).collapseToStart(); this._previewModelReference = ref; this._preview.setModel(model.textEditorModel); this._preview.setSelection(sel); this._preview.revealRangeInCenter(sel, scrollType); } else { this._preview.setModel(this._previewNotAvailableMessage); ref.dispose(); } return [2 /*return*/]; } }); }); }; ReferenceWidget = __decorate([ __param(3, themeService_1.IThemeService), __param(4, resolverService_1.ITextModelService), __param(5, instantiation_1.IInstantiationService), __param(6, peekView.IPeekViewService), __param(7, label_1.ILabelService) ], ReferenceWidget); return ReferenceWidget; }(peekView.PeekViewWidget)); exports.ReferenceWidget = ReferenceWidget; // theming themeService_1.registerThemingParticipant(function (theme, collector) { var findMatchHighlightColor = theme.getColor(peekView.peekViewResultsMatchHighlight); if (findMatchHighlightColor) { collector.addRule(".monaco-editor .reference-zone-widget .ref-tree .referenceMatch .highlight { background-color: " + findMatchHighlightColor + "; }"); } var referenceHighlightColor = theme.getColor(peekView.peekViewEditorMatchHighlight); if (referenceHighlightColor) { collector.addRule(".monaco-editor .reference-zone-widget .preview .reference-decoration { background-color: " + referenceHighlightColor + "; }"); } var referenceHighlightBorder = theme.getColor(peekView.peekViewEditorMatchHighlightBorder); if (referenceHighlightBorder) { collector.addRule(".monaco-editor .reference-zone-widget .preview .reference-decoration { border: 2px solid " + referenceHighlightBorder + "; box-sizing: border-box; }"); } var hcOutline = theme.getColor(colorRegistry_1.activeContrastBorder); if (hcOutline) { collector.addRule(".monaco-editor .reference-zone-widget .ref-tree .referenceMatch .highlight { border: 1px dotted " + hcOutline + "; box-sizing: border-box; }"); } var resultsBackground = theme.getColor(peekView.peekViewResultsBackground); if (resultsBackground) { collector.addRule(".monaco-editor .reference-zone-widget .ref-tree { background-color: " + resultsBackground + "; }"); } var resultsMatchForeground = theme.getColor(peekView.peekViewResultsMatchForeground); if (resultsMatchForeground) { collector.addRule(".monaco-editor .reference-zone-widget .ref-tree { color: " + resultsMatchForeground + "; }"); } var resultsFileForeground = theme.getColor(peekView.peekViewResultsFileForeground); if (resultsFileForeground) { collector.addRule(".monaco-editor .reference-zone-widget .ref-tree .reference-file { color: " + resultsFileForeground + "; }"); } var resultsSelectedBackground = theme.getColor(peekView.peekViewResultsSelectionBackground); if (resultsSelectedBackground) { collector.addRule(".monaco-editor .reference-zone-widget .ref-tree .monaco-list:focus .monaco-list-rows > .monaco-list-row.selected:not(.highlighted) { background-color: " + resultsSelectedBackground + "; }"); } var resultsSelectedForeground = theme.getColor(peekView.peekViewResultsSelectionForeground); if (resultsSelectedForeground) { collector.addRule(".monaco-editor .reference-zone-widget .ref-tree .monaco-list:focus .monaco-list-rows > .monaco-list-row.selected:not(.highlighted) { color: " + resultsSelectedForeground + " !important; }"); } var editorBackground = theme.getColor(peekView.peekViewEditorBackground); if (editorBackground) { collector.addRule(".monaco-editor .reference-zone-widget .preview .monaco-editor .monaco-editor-background," + ".monaco-editor .reference-zone-widget .preview .monaco-editor .inputarea.ime-input {" + ("\tbackground-color: " + editorBackground + ";") + "}"); } var editorGutterBackground = theme.getColor(peekView.peekViewEditorGutterBackground); if (editorGutterBackground) { collector.addRule(".monaco-editor .reference-zone-widget .preview .monaco-editor .margin {" + ("\tbackground-color: " + editorGutterBackground + ";") + "}"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[234/*vs/editor/contrib/gotoSymbol/peek/referencesController*/], __M([0/*require*/,1/*exports*/,448/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesController*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,32/*vs/editor/browser/services/codeEditorService*/,11/*vs/platform/instantiation/common/instantiation*/,18/*vs/platform/contextkey/common/contextkey*/,43/*vs/platform/configuration/common/configuration*/,74/*vs/platform/storage/common/storage*/,113/*vs/editor/contrib/gotoSymbol/referencesModel*/,596/*vs/editor/contrib/gotoSymbol/peek/referencesWidget*/,3/*vs/editor/common/core/range*/,13/*vs/editor/common/core/position*/,35/*vs/platform/notification/common/notification*/,15/*vs/base/common/async*/,123/*vs/editor/contrib/peekView/peekView*/,170/*vs/platform/list/browser/listService*/,86/*vs/platform/keybinding/common/keybindingsRegistry*/,36/*vs/base/common/keyCodes*/,29/*vs/platform/commands/common/commands*/]), function (require, exports, nls, errors_1, lifecycle_1, codeEditorService_1, instantiation_1, contextkey_1, configuration_1, storage_1, referencesModel_1, referencesWidget_1, range_1, position_1, notification_1, async_1, peekView_1, listService_1, keybindingsRegistry_1, keyCodes_1, commands_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ctxReferenceSearchVisible = new contextkey_1.RawContextKey('referenceSearchVisible', false); var ReferencesController = /** @class */ (function () { function ReferencesController(_defaultTreeKeyboardSupport, _editor, contextKeyService, _editorService, _notificationService, _instantiationService, _storageService, _configurationService) { this._defaultTreeKeyboardSupport = _defaultTreeKeyboardSupport; this._editor = _editor; this._editorService = _editorService; this._notificationService = _notificationService; this._instantiationService = _instantiationService; this._storageService = _storageService; this._configurationService = _configurationService; this._disposables = new lifecycle_1.DisposableStore(); this._requestIdPool = 0; this._ignoreModelChangeEvent = false; this._referenceSearchVisible = exports.ctxReferenceSearchVisible.bindTo(contextKeyService); } ReferencesController.get = function (editor) { return editor.getContribution(ReferencesController.ID); }; ReferencesController.prototype.dispose = function () { this._referenceSearchVisible.reset(); this._disposables.dispose(); lifecycle_1.dispose(this._widget); lifecycle_1.dispose(this._model); this._widget = undefined; this._model = undefined; }; ReferencesController.prototype.toggleWidget = function (range, modelPromise, peekMode) { var _this = this; // close current widget and return early is position didn't change var widgetPosition; if (this._widget) { widgetPosition = this._widget.position; } this.closeWidget(); if (!!widgetPosition && range.containsPosition(widgetPosition)) { return; } this._peekMode = peekMode; this._referenceSearchVisible.set(true); // close the widget on model/mode changes this._disposables.add(this._editor.onDidChangeModelLanguage(function () { _this.closeWidget(); })); this._disposables.add(this._editor.onDidChangeModel(function () { if (!_this._ignoreModelChangeEvent) { _this.closeWidget(); } })); var storageKey = 'peekViewLayout'; var data = referencesWidget_1.LayoutData.fromJSON(this._storageService.get(storageKey, 0 /* GLOBAL */, '{}')); this._widget = this._instantiationService.createInstance(referencesWidget_1.ReferenceWidget, this._editor, this._defaultTreeKeyboardSupport, data); this._widget.setTitle(nls.localize(0, null)); this._widget.show(range); this._disposables.add(this._widget.onDidClose(function () { modelPromise.cancel(); if (_this._widget) { _this._storageService.store(storageKey, JSON.stringify(_this._widget.layoutData), 0 /* GLOBAL */); _this._widget = undefined; } _this.closeWidget(); })); this._disposables.add(this._widget.onDidSelectReference(function (event) { var element = event.element, kind = event.kind; if (!element) { return; } switch (kind) { case 'open': if (event.source !== 'editor' || !_this._configurationService.getValue('editor.stablePeek')) { // when stable peek is configured we don't close // the peek window on selecting the editor _this.openReference(element, false); } break; case 'side': _this.openReference(element, true); break; case 'goto': if (peekMode) { _this._gotoReference(element); } else { _this.openReference(element, false); } break; } })); var requestId = ++this._requestIdPool; modelPromise.then(function (model) { // still current request? widget still open? if (requestId !== _this._requestIdPool || !_this._widget) { return undefined; } if (_this._model) { _this._model.dispose(); } _this._model = model; // show widget return _this._widget.setModel(_this._model).then(function () { if (_this._widget && _this._model && _this._editor.hasModel()) { // might have been closed // set title if (!_this._model.isEmpty) { _this._widget.setMetaTitle(nls.localize(1, null, _this._model.title, _this._model.references.length)); } else { _this._widget.setMetaTitle(''); } // set 'best' selection var uri = _this._editor.getModel().uri; var pos = new position_1.Position(range.startLineNumber, range.startColumn); var selection = _this._model.nearestReference(uri, pos); if (selection) { return _this._widget.setSelection(selection).then(function () { if (_this._widget && _this._editor.getOption(65 /* peekWidgetDefaultFocus */) === 'editor') { _this._widget.focusOnPreviewEditor(); } }); } } return undefined; }); }, function (error) { _this._notificationService.error(error); }); }; ReferencesController.prototype.changeFocusBetweenPreviewAndReferences = function () { if (!this._widget) { // can be called while still resolving... return; } if (this._widget.isPreviewEditorFocused()) { this._widget.focusOnReferenceTree(); } else { this._widget.focusOnPreviewEditor(); } }; ReferencesController.prototype.goToNextOrPreviousReference = function (fwd) { return __awaiter(this, void 0, void 0, function () { var currentPosition, source, target, editorFocus, previewEditorFocus; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this._editor.hasModel() || !this._model || !this._widget) { // can be called while still resolving... return [2 /*return*/]; } currentPosition = this._widget.position; if (!currentPosition) { return [2 /*return*/]; } source = this._model.nearestReference(this._editor.getModel().uri, currentPosition); if (!source) { return [2 /*return*/]; } target = this._model.nextOrPreviousReference(source, fwd); editorFocus = this._editor.hasTextFocus(); previewEditorFocus = this._widget.isPreviewEditorFocused(); return [4 /*yield*/, this._widget.setSelection(target)]; case 1: _a.sent(); return [4 /*yield*/, this._gotoReference(target)]; case 2: _a.sent(); if (editorFocus) { this._editor.focus(); } else if (this._widget && previewEditorFocus) { this._widget.focusOnPreviewEditor(); } return [2 /*return*/]; } }); }); }; ReferencesController.prototype.closeWidget = function (focusEditor) { if (focusEditor === void 0) { focusEditor = true; } this._referenceSearchVisible.reset(); this._disposables.clear(); lifecycle_1.dispose(this._widget); lifecycle_1.dispose(this._model); this._widget = undefined; this._model = undefined; if (focusEditor) { this._editor.focus(); } this._requestIdPool += 1; // Cancel pending requests }; ReferencesController.prototype._gotoReference = function (ref) { var _this = this; if (this._widget) { this._widget.hide(); } this._ignoreModelChangeEvent = true; var range = range_1.Range.lift(ref.range).collapseToStart(); return this._editorService.openCodeEditor({ resource: ref.uri, options: { selection: range } }, this._editor).then(function (openedEditor) { var _a; _this._ignoreModelChangeEvent = false; if (!openedEditor || !_this._widget) { // something went wrong... _this.closeWidget(); return; } if (_this._editor === openedEditor) { // _this._widget.show(range); _this._widget.focusOnReferenceTree(); } else { // we opened a different editor instance which means a different controller instance. // therefore we stop with this controller and continue with the other var other = ReferencesController.get(openedEditor); var model_1 = _this._model.clone(); _this.closeWidget(); openedEditor.focus(); other.toggleWidget(range, async_1.createCancelablePromise(function (_) { return Promise.resolve(model_1); }), (_a = _this._peekMode) !== null && _a !== void 0 ? _a : false); } }, function (err) { _this._ignoreModelChangeEvent = false; errors_1.onUnexpectedError(err); }); }; ReferencesController.prototype.openReference = function (ref, sideBySide) { // clear stage if (!sideBySide) { this.closeWidget(); } var uri = ref.uri, range = ref.range; this._editorService.openCodeEditor({ resource: uri, options: { selection: range } }, this._editor, sideBySide); }; ReferencesController.ID = 'editor.contrib.referencesController'; ReferencesController = __decorate([ __param(2, contextkey_1.IContextKeyService), __param(3, codeEditorService_1.ICodeEditorService), __param(4, notification_1.INotificationService), __param(5, instantiation_1.IInstantiationService), __param(6, storage_1.IStorageService), __param(7, configuration_1.IConfigurationService) ], ReferencesController); return ReferencesController; }()); exports.ReferencesController = ReferencesController; function withController(accessor, fn) { var outerEditor = peekView_1.getOuterEditor(accessor); if (!outerEditor) { return; } var controller = ReferencesController.get(outerEditor); if (controller) { fn(controller); } } keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'togglePeekWidgetFocus', weight: 100 /* EditorContrib */, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 60 /* F2 */), when: contextkey_1.ContextKeyExpr.or(exports.ctxReferenceSearchVisible, peekView_1.PeekContext.inPeekEditor), handler: function (accessor) { withController(accessor, function (controller) { controller.changeFocusBetweenPreviewAndReferences(); }); } }); keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'goToNextReference', weight: 100 /* EditorContrib */ - 10, primary: 62 /* F4 */, secondary: [70 /* F12 */], when: contextkey_1.ContextKeyExpr.or(exports.ctxReferenceSearchVisible, peekView_1.PeekContext.inPeekEditor), handler: function (accessor) { withController(accessor, function (controller) { controller.goToNextOrPreviousReference(true); }); } }); keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'goToPreviousReference', weight: 100 /* EditorContrib */ - 10, primary: 1024 /* Shift */ | 62 /* F4 */, secondary: [1024 /* Shift */ | 70 /* F12 */], when: contextkey_1.ContextKeyExpr.or(exports.ctxReferenceSearchVisible, peekView_1.PeekContext.inPeekEditor), handler: function (accessor) { withController(accessor, function (controller) { controller.goToNextOrPreviousReference(false); }); } }); // commands that aren't needed anymore because there is now ContextKeyExpr.OR commands_1.CommandsRegistry.registerCommandAlias('goToNextReferenceFromEmbeddedEditor', 'goToNextReference'); commands_1.CommandsRegistry.registerCommandAlias('goToPreviousReferenceFromEmbeddedEditor', 'goToPreviousReference'); // close commands_1.CommandsRegistry.registerCommandAlias('closeReferenceSearchEditor', 'closeReferenceSearch'); commands_1.CommandsRegistry.registerCommand('closeReferenceSearch', function (accessor) { return withController(accessor, function (controller) { return controller.closeWidget(); }); }); keybindingsRegistry_1.KeybindingsRegistry.registerKeybindingRule({ id: 'closeReferenceSearch', weight: 100 /* EditorContrib */ - 101, primary: 9 /* Escape */, secondary: [1024 /* Shift */ | 9 /* Escape */], when: contextkey_1.ContextKeyExpr.and(peekView_1.PeekContext.inPeekEditor, contextkey_1.ContextKeyExpr.not('config.editor.stablePeek')) }); keybindingsRegistry_1.KeybindingsRegistry.registerKeybindingRule({ id: 'closeReferenceSearch', weight: 200 /* WorkbenchContrib */ + 50, primary: 9 /* Escape */, secondary: [1024 /* Shift */ | 9 /* Escape */], when: contextkey_1.ContextKeyExpr.and(exports.ctxReferenceSearchVisible, contextkey_1.ContextKeyExpr.not('config.editor.stablePeek')) }); keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'openReferenceToSide', weight: 100 /* EditorContrib */, primary: 2048 /* CtrlCmd */ | 3 /* Enter */, mac: { primary: 256 /* WinCtrl */ | 3 /* Enter */ }, when: contextkey_1.ContextKeyExpr.and(exports.ctxReferenceSearchVisible, listService_1.WorkbenchListFocusContextKey), handler: function (accessor) { var _a; var listService = accessor.get(listService_1.IListService); var focus = (_a = listService.lastFocusedList) === null || _a === void 0 ? void 0 : _a.getFocus(); if (Array.isArray(focus) && focus[0] instanceof referencesModel_1.OneReference) { withController(accessor, function (controller) { return controller.openReference(focus[0], true); }); } } }); commands_1.CommandsRegistry.registerCommand('openReference', function (accessor) { var _a; var listService = accessor.get(listService_1.IListService); var focus = (_a = listService.lastFocusedList) === null || _a === void 0 ? void 0 : _a.getFocus(); if (Array.isArray(focus) && focus[0] instanceof referencesModel_1.OneReference) { withController(accessor, function (controller) { return controller.openReference(focus[0], 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[235/*vs/editor/contrib/gotoSymbol/goToCommands*/], __M([0/*require*/,1/*exports*/,50/*vs/base/browser/ui/aria/aria*/,15/*vs/base/common/async*/,36/*vs/base/common/keyCodes*/,16/*vs/base/common/platform*/,108/*vs/editor/browser/editorBrowser*/,12/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,23/*vs/editor/common/editorContextKeys*/,17/*vs/editor/common/modes*/,122/*vs/editor/contrib/message/messageController*/,123/*vs/editor/contrib/peekView/peekView*/,234/*vs/editor/contrib/gotoSymbol/peek/referencesController*/,113/*vs/editor/contrib/gotoSymbol/referencesModel*/,446/*vs/nls!vs/editor/contrib/gotoSymbol/goToCommands*/,65/*vs/platform/actions/common/actions*/,18/*vs/platform/contextkey/common/contextkey*/,35/*vs/platform/notification/common/notification*/,73/*vs/platform/progress/common/progress*/,224/*vs/editor/contrib/gotoSymbol/goToSymbol*/,29/*vs/platform/commands/common/commands*/,67/*vs/editor/browser/core/editorState*/,537/*vs/editor/contrib/gotoSymbol/symbolNavigation*/,24/*vs/base/browser/browser*/,25/*vs/base/common/uri*/,11/*vs/platform/instantiation/common/instantiation*/,21/*vs/base/common/types*/,167/*vs/editor/browser/widget/embeddedCodeEditorWidget*/]), function (require, exports, aria_1, async_1, keyCodes_1, platform_1, editorBrowser_1, editorExtensions_1, codeEditorService_1, corePosition, range_1, editorContextKeys_1, modes_1, messageController_1, peekView_1, referencesController_1, referencesModel_1, nls, actions_1, contextkey_1, notification_1, progress_1, goToSymbol_1, commands_1, editorState_1, symbolNavigation_1, browser_1, uri_1, instantiation_1, types_1, embeddedCodeEditorWidget_1) { "use strict"; var _a, _b, _c, _d, _e, _f, _g, _h; Object.defineProperty(exports, "__esModule", { value: true }); actions_1.MenuRegistry.appendMenuItem(7 /* EditorContext */, { submenu: 8 /* EditorContextPeek */, title: nls.localize(0, null), group: 'navigation', order: 100 }); var SymbolNavigationAction = /** @class */ (function (_super) { __extends(SymbolNavigationAction, _super); function SymbolNavigationAction(configuration, opts) { var _this = _super.call(this, opts) || this; _this._configuration = configuration; return _this; } SymbolNavigationAction.prototype.run = function (accessor, editor) { var _this = this; if (!editor.hasModel()) { return Promise.resolve(undefined); } var notificationService = accessor.get(notification_1.INotificationService); var editorService = accessor.get(codeEditorService_1.ICodeEditorService); var progressService = accessor.get(progress_1.IEditorProgressService); var symbolNavService = accessor.get(symbolNavigation_1.ISymbolNavigationService); var model = editor.getModel(); var pos = editor.getPosition(); var cts = new editorState_1.EditorStateCancellationTokenSource(editor, 1 /* Value */ | 4 /* Position */); var promise = async_1.raceCancellation(this._getLocationModel(model, pos, cts.token), cts.token).then(function (references) { return __awaiter(_this, void 0, void 0, function () { var altAction, altActionId, referenceCount, info; return __generator(this, function (_a) { if (!references || cts.token.isCancellationRequested) { return [2 /*return*/]; } aria_1.alert(references.ariaMessage); if (references.referenceAt(model.uri, pos)) { altActionId = this._getAlternativeCommand(editor); if (altActionId !== this.id) { altAction = editor.getAction(altActionId); } } referenceCount = references.references.length; if (referenceCount === 0) { // no result -> show message if (!this._configuration.muteMessage) { info = model.getWordAtPosition(pos); messageController_1.MessageController.get(editor).showMessage(this._getNoResultFoundMessage(info), pos); } } else if (referenceCount === 1 && altAction) { // already at the only result, run alternative altAction.run(); } else { // normal results handling return [2 /*return*/, this._onResult(editorService, symbolNavService, editor, references)]; } return [2 /*return*/]; }); }); }, function (err) { // report an error notificationService.error(err); }).finally(function () { cts.dispose(); }); progressService.showWhile(promise, 250); return promise; }; SymbolNavigationAction.prototype._onResult = function (editorService, symbolNavService, editor, model) { return __awaiter(this, void 0, void 0, function () { var gotoLocation, next, peek, targetEditor; return __generator(this, function (_a) { switch (_a.label) { case 0: gotoLocation = this._getGoToPreference(editor); if (!(!(editor instanceof embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget) && (this._configuration.openInPeek || (gotoLocation === 'peek' && model.references.length > 1)))) return [3 /*break*/, 1]; this._openInPeek(editor, model); return [3 /*break*/, 3]; case 1: next = model.firstReference(); peek = model.references.length > 1 && gotoLocation === 'gotoAndPeek'; return [4 /*yield*/, this._openReference(editor, editorService, next, this._configuration.openToSide, !peek)]; case 2: targetEditor = _a.sent(); if (peek && targetEditor) { this._openInPeek(targetEditor, model); } else { model.dispose(); } // keep remaining locations around when using // 'goto'-mode if (gotoLocation === 'goto') { symbolNavService.put(next); } _a.label = 3; case 3: return [2 /*return*/]; } }); }); }; SymbolNavigationAction.prototype._openReference = function (editor, editorService, reference, sideBySide, highlight) { return __awaiter(this, void 0, void 0, function () { var range, targetEditor, modelNow_1, ids_1; return __generator(this, function (_a) { switch (_a.label) { case 0: range = undefined; if (modes_1.isLocationLink(reference)) { range = reference.targetSelectionRange; } if (!range) { range = reference.range; } return [4 /*yield*/, editorService.openCodeEditor({ resource: reference.uri, options: { selection: range_1.Range.collapseToStart(range), revealInCenterIfOutsideViewport: true } }, editor, sideBySide)]; case 1: targetEditor = _a.sent(); if (!targetEditor) { return [2 /*return*/, undefined]; } if (highlight) { modelNow_1 = targetEditor.getModel(); ids_1 = targetEditor.deltaDecorations([], [{ range: range, options: { className: 'symbolHighlight' } }]); setTimeout(function () { if (targetEditor.getModel() === modelNow_1) { targetEditor.deltaDecorations(ids_1, []); } }, 350); } return [2 /*return*/, targetEditor]; } }); }); }; SymbolNavigationAction.prototype._openInPeek = function (target, model) { var controller = referencesController_1.ReferencesController.get(target); if (controller && target.hasModel()) { controller.toggleWidget(target.getSelection(), async_1.createCancelablePromise(function (_) { return Promise.resolve(model); }), this._configuration.openInPeek); } else { model.dispose(); } }; return SymbolNavigationAction; }(editorExtensions_1.EditorAction)); //#region --- DEFINITION var DefinitionAction = /** @class */ (function (_super) { __extends(DefinitionAction, _super); function DefinitionAction() { return _super !== null && _super.apply(this, arguments) || this; } DefinitionAction.prototype._getLocationModel = function (model, position, token) { return __awaiter(this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = referencesModel_1.ReferencesModel.bind; return [4 /*yield*/, goToSymbol_1.getDefinitionsAtPosition(model, position, token)]; case 1: return [2 /*return*/, new (_a.apply(referencesModel_1.ReferencesModel, [void 0, _b.sent(), nls.localize(1, null)]))()]; } }); }); }; DefinitionAction.prototype._getNoResultFoundMessage = function (info) { return info && info.word ? nls.localize(2, null, info.word) : nls.localize(3, null); }; DefinitionAction.prototype._getAlternativeCommand = function (editor) { return editor.getOption(41 /* gotoLocation */).alternativeDefinitionCommand; }; DefinitionAction.prototype._getGoToPreference = function (editor) { return editor.getOption(41 /* gotoLocation */).multipleDefinitions; }; return DefinitionAction; }(SymbolNavigationAction)); exports.DefinitionAction = DefinitionAction; var goToDefinitionKb = platform_1.isWeb && !browser_1.isStandalone ? 2048 /* CtrlCmd */ | 70 /* F12 */ : 70 /* F12 */; editorExtensions_1.registerEditorAction((_a = /** @class */ (function (_super) { __extends(GoToDefinitionAction, _super); function GoToDefinitionAction() { var _this = _super.call(this, { openToSide: false, openInPeek: false, muteMessage: false }, { id: GoToDefinitionAction.id, label: nls.localize(4, null), alias: 'Go to Definition', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDefinitionProvider, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: goToDefinitionKb, weight: 100 /* EditorContrib */ }, contextMenuOpts: { group: 'navigation', order: 1.1 }, menuOpts: { menuId: 19 /* MenubarGoMenu */, group: '4_symbol_nav', order: 2, title: nls.localize(5, null) } }) || this; commands_1.CommandsRegistry.registerCommandAlias('editor.action.goToDeclaration', GoToDefinitionAction.id); return _this; } return GoToDefinitionAction; }(DefinitionAction)), _a.id = 'editor.action.revealDefinition', _a)); editorExtensions_1.registerEditorAction((_b = /** @class */ (function (_super) { __extends(OpenDefinitionToSideAction, _super); function OpenDefinitionToSideAction() { var _this = _super.call(this, { openToSide: true, openInPeek: false, muteMessage: false }, { id: OpenDefinitionToSideAction.id, label: nls.localize(6, null), alias: 'Open Definition to the Side', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDefinitionProvider, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, goToDefinitionKb), weight: 100 /* EditorContrib */ } }) || this; commands_1.CommandsRegistry.registerCommandAlias('editor.action.openDeclarationToTheSide', OpenDefinitionToSideAction.id); return _this; } return OpenDefinitionToSideAction; }(DefinitionAction)), _b.id = 'editor.action.revealDefinitionAside', _b)); editorExtensions_1.registerEditorAction((_c = /** @class */ (function (_super) { __extends(PeekDefinitionAction, _super); function PeekDefinitionAction() { var _this = _super.call(this, { openToSide: false, openInPeek: true, muteMessage: false }, { id: PeekDefinitionAction.id, label: nls.localize(7, null), alias: 'Peek Definition', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDefinitionProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 512 /* Alt */ | 70 /* F12 */, linux: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 68 /* F10 */ }, weight: 100 /* EditorContrib */ }, contextMenuOpts: { menuId: 8 /* EditorContextPeek */, group: 'peek', order: 2 } }) || this; commands_1.CommandsRegistry.registerCommandAlias('editor.action.previewDeclaration', PeekDefinitionAction.id); return _this; } return PeekDefinitionAction; }(DefinitionAction)), _c.id = 'editor.action.peekDefinition', _c)); //#endregion //#region --- DECLARATION var DeclarationAction = /** @class */ (function (_super) { __extends(DeclarationAction, _super); function DeclarationAction() { return _super !== null && _super.apply(this, arguments) || this; } DeclarationAction.prototype._getLocationModel = function (model, position, token) { return __awaiter(this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = referencesModel_1.ReferencesModel.bind; return [4 /*yield*/, goToSymbol_1.getDeclarationsAtPosition(model, position, token)]; case 1: return [2 /*return*/, new (_a.apply(referencesModel_1.ReferencesModel, [void 0, _b.sent(), nls.localize(8, null)]))()]; } }); }); }; DeclarationAction.prototype._getNoResultFoundMessage = function (info) { return info && info.word ? nls.localize(9, null, info.word) : nls.localize(10, null); }; DeclarationAction.prototype._getAlternativeCommand = function (editor) { return editor.getOption(41 /* gotoLocation */).alternativeDeclarationCommand; }; DeclarationAction.prototype._getGoToPreference = function (editor) { return editor.getOption(41 /* gotoLocation */).multipleDeclarations; }; return DeclarationAction; }(SymbolNavigationAction)); editorExtensions_1.registerEditorAction((_d = /** @class */ (function (_super) { __extends(GoToDeclarationAction, _super); function GoToDeclarationAction() { return _super.call(this, { openToSide: false, openInPeek: false, muteMessage: false }, { id: GoToDeclarationAction.id, label: nls.localize(11, null), alias: 'Go to Declaration', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDeclarationProvider, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), contextMenuOpts: { group: 'navigation', order: 1.3 }, menuOpts: { menuId: 19 /* MenubarGoMenu */, group: '4_symbol_nav', order: 3, title: nls.localize(12, null) }, }) || this; } GoToDeclarationAction.prototype._getNoResultFoundMessage = function (info) { return info && info.word ? nls.localize(13, null, info.word) : nls.localize(14, null); }; return GoToDeclarationAction; }(DeclarationAction)), _d.id = 'editor.action.revealDeclaration', _d)); editorExtensions_1.registerEditorAction(/** @class */ (function (_super) { __extends(PeekDeclarationAction, _super); function PeekDeclarationAction() { return _super.call(this, { openToSide: false, openInPeek: true, muteMessage: false }, { id: 'editor.action.peekDeclaration', label: nls.localize(15, null), alias: 'Peek Declaration', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDeclarationProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), contextMenuOpts: { menuId: 8 /* EditorContextPeek */, group: 'peek', order: 3 } }) || this; } return PeekDeclarationAction; }(DeclarationAction))); //#endregion //#region --- TYPE DEFINITION var TypeDefinitionAction = /** @class */ (function (_super) { __extends(TypeDefinitionAction, _super); function TypeDefinitionAction() { return _super !== null && _super.apply(this, arguments) || this; } TypeDefinitionAction.prototype._getLocationModel = function (model, position, token) { return __awaiter(this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = referencesModel_1.ReferencesModel.bind; return [4 /*yield*/, goToSymbol_1.getTypeDefinitionsAtPosition(model, position, token)]; case 1: return [2 /*return*/, new (_a.apply(referencesModel_1.ReferencesModel, [void 0, _b.sent(), nls.localize(16, null)]))()]; } }); }); }; TypeDefinitionAction.prototype._getNoResultFoundMessage = function (info) { return info && info.word ? nls.localize(17, null, info.word) : nls.localize(18, null); }; TypeDefinitionAction.prototype._getAlternativeCommand = function (editor) { return editor.getOption(41 /* gotoLocation */).alternativeTypeDefinitionCommand; }; TypeDefinitionAction.prototype._getGoToPreference = function (editor) { return editor.getOption(41 /* gotoLocation */).multipleTypeDefinitions; }; return TypeDefinitionAction; }(SymbolNavigationAction)); editorExtensions_1.registerEditorAction((_e = /** @class */ (function (_super) { __extends(GoToTypeDefinitionAction, _super); function GoToTypeDefinitionAction() { return _super.call(this, { openToSide: false, openInPeek: false, muteMessage: false }, { id: GoToTypeDefinitionAction.ID, label: nls.localize(19, null), alias: 'Go to Type Definition', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasTypeDefinitionProvider, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 0, weight: 100 /* EditorContrib */ }, contextMenuOpts: { group: 'navigation', order: 1.4 }, menuOpts: { menuId: 19 /* MenubarGoMenu */, group: '4_symbol_nav', order: 3, title: nls.localize(20, null) } }) || this; } return GoToTypeDefinitionAction; }(TypeDefinitionAction)), _e.ID = 'editor.action.goToTypeDefinition', _e)); editorExtensions_1.registerEditorAction((_f = /** @class */ (function (_super) { __extends(PeekTypeDefinitionAction, _super); function PeekTypeDefinitionAction() { return _super.call(this, { openToSide: false, openInPeek: true, muteMessage: false }, { id: PeekTypeDefinitionAction.ID, label: nls.localize(21, null), alias: 'Peek Type Definition', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasTypeDefinitionProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), contextMenuOpts: { menuId: 8 /* EditorContextPeek */, group: 'peek', order: 4 } }) || this; } return PeekTypeDefinitionAction; }(TypeDefinitionAction)), _f.ID = 'editor.action.peekTypeDefinition', _f)); //#endregion //#region --- IMPLEMENTATION var ImplementationAction = /** @class */ (function (_super) { __extends(ImplementationAction, _super); function ImplementationAction() { return _super !== null && _super.apply(this, arguments) || this; } ImplementationAction.prototype._getLocationModel = function (model, position, token) { return __awaiter(this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = referencesModel_1.ReferencesModel.bind; return [4 /*yield*/, goToSymbol_1.getImplementationsAtPosition(model, position, token)]; case 1: return [2 /*return*/, new (_a.apply(referencesModel_1.ReferencesModel, [void 0, _b.sent(), nls.localize(22, null)]))()]; } }); }); }; ImplementationAction.prototype._getNoResultFoundMessage = function (info) { return info && info.word ? nls.localize(23, null, info.word) : nls.localize(24, null); }; ImplementationAction.prototype._getAlternativeCommand = function (editor) { return editor.getOption(41 /* gotoLocation */).alternativeImplementationCommand; }; ImplementationAction.prototype._getGoToPreference = function (editor) { return editor.getOption(41 /* gotoLocation */).multipleImplementations; }; return ImplementationAction; }(SymbolNavigationAction)); editorExtensions_1.registerEditorAction((_g = /** @class */ (function (_super) { __extends(GoToImplementationAction, _super); function GoToImplementationAction() { return _super.call(this, { openToSide: false, openInPeek: false, muteMessage: false }, { id: GoToImplementationAction.ID, label: nls.localize(25, null), alias: 'Go to Implementations', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasImplementationProvider, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 70 /* F12 */, weight: 100 /* EditorContrib */ }, menuOpts: { menuId: 19 /* MenubarGoMenu */, group: '4_symbol_nav', order: 4, title: nls.localize(26, null) }, contextMenuOpts: { group: 'navigation', order: 1.45 } }) || this; } return GoToImplementationAction; }(ImplementationAction)), _g.ID = 'editor.action.goToImplementation', _g)); editorExtensions_1.registerEditorAction((_h = /** @class */ (function (_super) { __extends(PeekImplementationAction, _super); function PeekImplementationAction() { return _super.call(this, { openToSide: false, openInPeek: true, muteMessage: false }, { id: PeekImplementationAction.ID, label: nls.localize(27, null), alias: 'Peek Implementations', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasImplementationProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 70 /* F12 */, weight: 100 /* EditorContrib */ }, contextMenuOpts: { menuId: 8 /* EditorContextPeek */, group: 'peek', order: 5 } }) || this; } return PeekImplementationAction; }(ImplementationAction)), _h.ID = 'editor.action.peekImplementation', _h)); //#endregion //#region --- REFERENCES var ReferencesAction = /** @class */ (function (_super) { __extends(ReferencesAction, _super); function ReferencesAction() { return _super !== null && _super.apply(this, arguments) || this; } ReferencesAction.prototype._getNoResultFoundMessage = function (info) { return info ? nls.localize(28, null, info.word) : nls.localize(29, null); }; ReferencesAction.prototype._getAlternativeCommand = function (editor) { return editor.getOption(41 /* gotoLocation */).alternativeReferenceCommand; }; ReferencesAction.prototype._getGoToPreference = function (editor) { return editor.getOption(41 /* gotoLocation */).multipleReferences; }; return ReferencesAction; }(SymbolNavigationAction)); editorExtensions_1.registerEditorAction(/** @class */ (function (_super) { __extends(GoToReferencesAction, _super); function GoToReferencesAction() { return _super.call(this, { openToSide: false, openInPeek: false, muteMessage: false }, { id: 'editor.action.goToReferences', label: nls.localize(30, null), alias: 'Go to References', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasReferenceProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 1024 /* Shift */ | 70 /* F12 */, weight: 100 /* EditorContrib */ }, contextMenuOpts: { group: 'navigation', order: 1.45 }, menuOpts: { menuId: 19 /* MenubarGoMenu */, group: '4_symbol_nav', order: 5, title: nls.localize(31, null) }, }) || this; } GoToReferencesAction.prototype._getLocationModel = function (model, position, token) { return __awaiter(this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = referencesModel_1.ReferencesModel.bind; return [4 /*yield*/, goToSymbol_1.getReferencesAtPosition(model, position, true, token)]; case 1: return [2 /*return*/, new (_a.apply(referencesModel_1.ReferencesModel, [void 0, _b.sent(), nls.localize(32, null)]))()]; } }); }); }; return GoToReferencesAction; }(ReferencesAction))); editorExtensions_1.registerEditorAction(/** @class */ (function (_super) { __extends(PeekReferencesAction, _super); function PeekReferencesAction() { return _super.call(this, { openToSide: false, openInPeek: true, muteMessage: false }, { id: 'editor.action.referenceSearch.trigger', label: nls.localize(33, null), alias: 'Peek References', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasReferenceProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), contextMenuOpts: { menuId: 8 /* EditorContextPeek */, group: 'peek', order: 6 } }) || this; } PeekReferencesAction.prototype._getLocationModel = function (model, position, token) { return __awaiter(this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = referencesModel_1.ReferencesModel.bind; return [4 /*yield*/, goToSymbol_1.getReferencesAtPosition(model, position, false, token)]; case 1: return [2 /*return*/, new (_a.apply(referencesModel_1.ReferencesModel, [void 0, _b.sent(), nls.localize(34, null)]))()]; } }); }); }; return PeekReferencesAction; }(ReferencesAction))); //#endregion //#region --- GENERIC goto symbols command var GenericGoToLocationAction = /** @class */ (function (_super) { __extends(GenericGoToLocationAction, _super); function GenericGoToLocationAction(config, _references, _gotoMultipleBehaviour) { var _this = _super.call(this, config, { id: 'editor.action.goToLocation', label: nls.localize(35, null), alias: 'Go To Any Symbol', precondition: contextkey_1.ContextKeyExpr.and(peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), }) || this; _this._references = _references; _this._gotoMultipleBehaviour = _gotoMultipleBehaviour; return _this; } GenericGoToLocationAction.prototype._getLocationModel = function (_model, _position, _token) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, new referencesModel_1.ReferencesModel(this._references, nls.localize(36, null))]; }); }); }; GenericGoToLocationAction.prototype._getNoResultFoundMessage = function (info) { return info && nls.localize(37, null, info.word) || ''; }; GenericGoToLocationAction.prototype._getGoToPreference = function (editor) { var _a; return (_a = this._gotoMultipleBehaviour) !== null && _a !== void 0 ? _a : editor.getOption(41 /* gotoLocation */).multipleReferences; }; GenericGoToLocationAction.prototype._getAlternativeCommand = function () { return ''; }; return GenericGoToLocationAction; }(SymbolNavigationAction)); commands_1.CommandsRegistry.registerCommand({ id: 'editor.action.goToLocations', description: { description: 'Go to locations from a position in a file', args: [ { name: 'uri', description: 'The text document in which to start', constraint: uri_1.URI }, { name: 'position', description: 'The position at which to start', constraint: corePosition.Position.isIPosition }, { name: 'locations', description: 'An array of locations.', constraint: Array }, { name: 'multiple', description: 'Define what to do when having multiple results, either `peek`, `gotoAndPeek`, or `goto' }, ] }, handler: function (accessor, resource, position, references, multiple, openInPeek) { return __awaiter(void 0, void 0, void 0, function () { var editorService, editor; return __generator(this, function (_a) { switch (_a.label) { case 0: types_1.assertType(uri_1.URI.isUri(resource)); types_1.assertType(corePosition.Position.isIPosition(position)); types_1.assertType(Array.isArray(references)); types_1.assertType(typeof multiple === 'undefined' || typeof multiple === 'string'); types_1.assertType(typeof openInPeek === 'undefined' || typeof openInPeek === 'boolean'); editorService = accessor.get(codeEditorService_1.ICodeEditorService); return [4 /*yield*/, editorService.openCodeEditor({ resource: resource }, editorService.getFocusedCodeEditor())]; case 1: editor = _a.sent(); if (editorBrowser_1.isCodeEditor(editor)) { editor.setPosition(position); editor.revealPositionInCenterIfOutsideViewport(position, 0 /* Smooth */); return [2 /*return*/, editor.invokeWithinContext(function (accessor) { var command = new GenericGoToLocationAction({ muteMessage: true, openInPeek: Boolean(openInPeek), openToSide: false }, references, multiple); accessor.get(instantiation_1.IInstantiationService).invokeFunction(command.run.bind(command), editor); })]; } return [2 /*return*/]; } }); }); } }); commands_1.CommandsRegistry.registerCommand({ id: 'editor.action.peekLocations', description: { description: 'Peek locations from a position in a file', args: [ { name: 'uri', description: 'The text document in which to start', constraint: uri_1.URI }, { name: 'position', description: 'The position at which to start', constraint: corePosition.Position.isIPosition }, { name: 'locations', description: 'An array of locations.', constraint: Array }, { name: 'multiple', description: 'Define what to do when having multiple results, either `peek`, `gotoAndPeek`, or `goto' }, ] }, handler: function (accessor, resource, position, references, multiple) { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { accessor.get(commands_1.ICommandService).executeCommand('editor.action.goToLocations', resource, position, references, multiple, true); return [2 /*return*/]; }); }); } }); //#endregion //#region --- REFERENCE search special commands commands_1.CommandsRegistry.registerCommand({ id: 'editor.action.findReferences', handler: function (accessor, resource, position) { types_1.assertType(uri_1.URI.isUri(resource)); types_1.assertType(corePosition.Position.isIPosition(position)); var codeEditorService = accessor.get(codeEditorService_1.ICodeEditorService); return codeEditorService.openCodeEditor({ resource: resource }, codeEditorService.getFocusedCodeEditor()).then(function (control) { if (!editorBrowser_1.isCodeEditor(control) || !control.hasModel()) { return undefined; } var controller = referencesController_1.ReferencesController.get(control); if (!controller) { return undefined; } var references = async_1.createCancelablePromise(function (token) { return goToSymbol_1.getReferencesAtPosition(control.getModel(), corePosition.Position.lift(position), false, token).then(function (references) { return new referencesModel_1.ReferencesModel(references, nls.localize(38, null)); }); }); var range = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column); return Promise.resolve(controller.toggleWidget(range, references, false)); }); } }); // use NEW command commands_1.CommandsRegistry.registerCommandAlias('editor.action.showReferences', 'editor.action.peekLocations'); }); //#endregion /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[236/*vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/], __M([0/*require*/,1/*exports*/,447/*vs/nls!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/,15/*vs/base/common/async*/,10/*vs/base/common/errors*/,75/*vs/base/common/htmlContent*/,71/*vs/editor/common/services/modeService*/,3/*vs/editor/common/core/range*/,17/*vs/editor/common/modes*/,12/*vs/editor/browser/editorExtensions*/,224/*vs/editor/contrib/gotoSymbol/goToSymbol*/,2/*vs/base/common/lifecycle*/,84/*vs/editor/common/services/resolverService*/,14/*vs/platform/theme/common/themeService*/,20/*vs/platform/theme/common/colorRegistry*/,67/*vs/editor/browser/core/editorState*/,235/*vs/editor/contrib/gotoSymbol/goToCommands*/,199/*vs/editor/contrib/gotoSymbol/link/clickLinkGesture*/,13/*vs/editor/common/core/position*/,21/*vs/base/common/types*/,313/*vs/css!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/]), function (require, exports, nls, async_1, errors_1, htmlContent_1, modeService_1, range_1, modes_1, editorExtensions_1, goToSymbol_1, lifecycle_1, resolverService_1, themeService_1, colorRegistry_1, editorState_1, goToCommands_1, clickLinkGesture_1, position_1, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var GotoDefinitionAtPositionEditorContribution = /** @class */ (function () { function GotoDefinitionAtPositionEditorContribution(editor, textModelResolverService, modeService) { var _this = this; this.textModelResolverService = textModelResolverService; this.modeService = modeService; this.toUnhook = new lifecycle_1.DisposableStore(); this.toUnhookForKeyboard = new lifecycle_1.DisposableStore(); this.linkDecorations = []; this.currentWordAtPosition = null; this.previousPromise = null; this.editor = editor; var linkGesture = new clickLinkGesture_1.ClickLinkGesture(editor); this.toUnhook.add(linkGesture); this.toUnhook.add(linkGesture.onMouseMoveOrRelevantKeyDown(function (_a) { var mouseEvent = _a[0], keyboardEvent = _a[1]; _this.startFindDefinitionFromMouse(mouseEvent, types_1.withNullAsUndefined(keyboardEvent)); })); this.toUnhook.add(linkGesture.onExecute(function (mouseEvent) { if (_this.isEnabled(mouseEvent)) { _this.gotoDefinition(mouseEvent.target.position, mouseEvent.hasSideBySideModifier).then(function () { _this.removeLinkDecorations(); }, function (error) { _this.removeLinkDecorations(); errors_1.onUnexpectedError(error); }); } })); this.toUnhook.add(linkGesture.onCancel(function () { _this.removeLinkDecorations(); _this.currentWordAtPosition = null; })); } GotoDefinitionAtPositionEditorContribution.get = function (editor) { return editor.getContribution(GotoDefinitionAtPositionEditorContribution.ID); }; GotoDefinitionAtPositionEditorContribution.prototype.startFindDefinitionFromCursor = function (position) { // For issue: https://github.com/microsoft/vscode/issues/46257 // equivalent to mouse move with meta/ctrl key var _this = this; // First find the definition and add decorations // to the editor to be shown with the content hover widget return this.startFindDefinition(position).then(function () { // Add listeners for editor cursor move and key down events // Dismiss the "extended" editor decorations when the user hides // the hover widget. There is no event for the widget itself so these // serve as a best effort. After removing the link decorations, the hover // widget is clean and will only show declarations per next request. _this.toUnhookForKeyboard.add(_this.editor.onDidChangeCursorPosition(function () { _this.currentWordAtPosition = null; _this.removeLinkDecorations(); _this.toUnhookForKeyboard.clear(); })); _this.toUnhookForKeyboard.add(_this.editor.onKeyDown(function (e) { if (e) { _this.currentWordAtPosition = null; _this.removeLinkDecorations(); _this.toUnhookForKeyboard.clear(); } })); }); }; GotoDefinitionAtPositionEditorContribution.prototype.startFindDefinitionFromMouse = function (mouseEvent, withKey) { // check if we are active and on a content widget if (mouseEvent.target.type === 9 /* CONTENT_WIDGET */ && this.linkDecorations.length > 0) { return; } if (!this.editor.hasModel() || !this.isEnabled(mouseEvent, withKey)) { this.currentWordAtPosition = null; this.removeLinkDecorations(); return; } var position = mouseEvent.target.position; this.startFindDefinition(position); }; GotoDefinitionAtPositionEditorContribution.prototype.startFindDefinition = function (position) { var _this = this; var _a; // Dispose listeners for updating decorations when using keyboard to show definition hover this.toUnhookForKeyboard.clear(); // Find word at mouse position var word = position ? (_a = this.editor.getModel()) === null || _a === void 0 ? void 0 : _a.getWordAtPosition(position) : null; if (!word) { this.currentWordAtPosition = null; this.removeLinkDecorations(); return Promise.resolve(0); } // Return early if word at position is still the same if (this.currentWordAtPosition && this.currentWordAtPosition.startColumn === word.startColumn && this.currentWordAtPosition.endColumn === word.endColumn && this.currentWordAtPosition.word === word.word) { return Promise.resolve(0); } this.currentWordAtPosition = word; // Find definition and decorate word if found var state = new editorState_1.EditorState(this.editor, 4 /* Position */ | 1 /* Value */ | 2 /* Selection */ | 8 /* Scroll */); if (this.previousPromise) { this.previousPromise.cancel(); this.previousPromise = null; } this.previousPromise = async_1.createCancelablePromise(function (token) { return _this.findDefinition(position, token); }); return this.previousPromise.then(function (results) { if (!results || !results.length || !state.validate(_this.editor)) { _this.removeLinkDecorations(); return; } // Multiple results if (results.length > 1) { _this.addDecoration(new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn), new htmlContent_1.MarkdownString().appendText(nls.localize(0, null, results.length))); } // Single result else { var result_1 = results[0]; if (!result_1.uri) { return; } _this.textModelResolverService.createModelReference(result_1.uri).then(function (ref) { if (!ref.object || !ref.object.textEditorModel) { ref.dispose(); return; } var textEditorModel = ref.object.textEditorModel; var startLineNumber = result_1.range.startLineNumber; if (startLineNumber < 1 || startLineNumber > textEditorModel.getLineCount()) { // invalid range ref.dispose(); return; } var previewValue = _this.getPreviewValue(textEditorModel, startLineNumber, result_1); var wordRange; if (result_1.originSelectionRange) { wordRange = range_1.Range.lift(result_1.originSelectionRange); } else { wordRange = new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn); } var modeId = _this.modeService.getModeIdByFilepathOrFirstLine(textEditorModel.uri); _this.addDecoration(wordRange, new htmlContent_1.MarkdownString().appendCodeblock(modeId ? modeId : '', previewValue)); ref.dispose(); }); } }).then(undefined, errors_1.onUnexpectedError); }; GotoDefinitionAtPositionEditorContribution.prototype.getPreviewValue = function (textEditorModel, startLineNumber, result) { var rangeToUse = result.targetSelectionRange ? result.range : this.getPreviewRangeBasedOnBrackets(textEditorModel, startLineNumber); var numberOfLinesInRange = rangeToUse.endLineNumber - rangeToUse.startLineNumber; if (numberOfLinesInRange >= GotoDefinitionAtPositionEditorContribution.MAX_SOURCE_PREVIEW_LINES) { rangeToUse = this.getPreviewRangeBasedOnIndentation(textEditorModel, startLineNumber); } var previewValue = this.stripIndentationFromPreviewRange(textEditorModel, startLineNumber, rangeToUse); return previewValue; }; GotoDefinitionAtPositionEditorContribution.prototype.stripIndentationFromPreviewRange = function (textEditorModel, startLineNumber, previewRange) { var startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber); var minIndent = startIndent; for (var endLineNumber = startLineNumber + 1; endLineNumber < previewRange.endLineNumber; endLineNumber++) { var endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber); minIndent = Math.min(minIndent, endIndent); } var previewValue = textEditorModel.getValueInRange(previewRange).replace(new RegExp("^\\s{" + (minIndent - 1) + "}", 'gm'), '').trim(); return previewValue; }; GotoDefinitionAtPositionEditorContribution.prototype.getPreviewRangeBasedOnIndentation = function (textEditorModel, startLineNumber) { var startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber); var maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + GotoDefinitionAtPositionEditorContribution.MAX_SOURCE_PREVIEW_LINES); var endLineNumber = startLineNumber + 1; for (; endLineNumber < maxLineNumber; endLineNumber++) { var endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber); if (startIndent === endIndent) { break; } } return new range_1.Range(startLineNumber, 1, endLineNumber + 1, 1); }; GotoDefinitionAtPositionEditorContribution.prototype.getPreviewRangeBasedOnBrackets = function (textEditorModel, startLineNumber) { var maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + GotoDefinitionAtPositionEditorContribution.MAX_SOURCE_PREVIEW_LINES); var brackets = []; var ignoreFirstEmpty = true; var currentBracket = textEditorModel.findNextBracket(new position_1.Position(startLineNumber, 1)); while (currentBracket !== null) { if (brackets.length === 0) { brackets.push(currentBracket); } else { var lastBracket = brackets[brackets.length - 1]; if (lastBracket.open[0] === currentBracket.open[0] && lastBracket.isOpen && !currentBracket.isOpen) { brackets.pop(); } else { brackets.push(currentBracket); } if (brackets.length === 0) { if (ignoreFirstEmpty) { ignoreFirstEmpty = false; } else { return new range_1.Range(startLineNumber, 1, currentBracket.range.endLineNumber + 1, 1); } } } var maxColumn = textEditorModel.getLineMaxColumn(startLineNumber); var nextLineNumber = currentBracket.range.endLineNumber; var nextColumn = currentBracket.range.endColumn; if (maxColumn === currentBracket.range.endColumn) { nextLineNumber++; nextColumn = 1; } if (nextLineNumber > maxLineNumber) { return new range_1.Range(startLineNumber, 1, maxLineNumber + 1, 1); } currentBracket = textEditorModel.findNextBracket(new position_1.Position(nextLineNumber, nextColumn)); } return new range_1.Range(startLineNumber, 1, maxLineNumber + 1, 1); }; GotoDefinitionAtPositionEditorContribution.prototype.addDecoration = function (range, hoverMessage) { var newDecorations = { range: range, options: { inlineClassName: 'goto-definition-link', hoverMessage: hoverMessage } }; this.linkDecorations = this.editor.deltaDecorations(this.linkDecorations, [newDecorations]); }; GotoDefinitionAtPositionEditorContribution.prototype.removeLinkDecorations = function () { if (this.linkDecorations.length > 0) { this.linkDecorations = this.editor.deltaDecorations(this.linkDecorations, []); } }; GotoDefinitionAtPositionEditorContribution.prototype.isEnabled = function (mouseEvent, withKey) { return this.editor.hasModel() && mouseEvent.isNoneOrSingleMouseDown && (mouseEvent.target.type === 6 /* CONTENT_TEXT */) && (mouseEvent.hasTriggerModifier || (withKey ? withKey.keyCodeIsTriggerKey : false)) && modes_1.DefinitionProviderRegistry.has(this.editor.getModel()); }; GotoDefinitionAtPositionEditorContribution.prototype.findDefinition = function (position, token) { var model = this.editor.getModel(); if (!model) { return Promise.resolve(null); } return goToSymbol_1.getDefinitionsAtPosition(model, position, token); }; GotoDefinitionAtPositionEditorContribution.prototype.gotoDefinition = function (position, openToSide) { var _this = this; this.editor.setPosition(position); var action = new goToCommands_1.DefinitionAction({ openToSide: openToSide, openInPeek: false, muteMessage: true }, { alias: '', label: '', id: '', precondition: undefined }); return this.editor.invokeWithinContext(function (accessor) { return action.run(accessor, _this.editor); }); }; GotoDefinitionAtPositionEditorContribution.prototype.dispose = function () { this.toUnhook.dispose(); }; GotoDefinitionAtPositionEditorContribution.ID = 'editor.contrib.gotodefinitionatposition'; GotoDefinitionAtPositionEditorContribution.MAX_SOURCE_PREVIEW_LINES = 8; GotoDefinitionAtPositionEditorContribution = __decorate([ __param(1, resolverService_1.ITextModelService), __param(2, modeService_1.IModeService) ], GotoDefinitionAtPositionEditorContribution); return GotoDefinitionAtPositionEditorContribution; }()); exports.GotoDefinitionAtPositionEditorContribution = GotoDefinitionAtPositionEditorContribution; editorExtensions_1.registerEditorContribution(GotoDefinitionAtPositionEditorContribution.ID, GotoDefinitionAtPositionEditorContribution); themeService_1.registerThemingParticipant(function (theme, collector) { var activeLinkForeground = theme.getColor(colorRegistry_1.editorActiveLinkForeground); if (activeLinkForeground) { collector.addRule(".monaco-editor .goto-definition-link { color: " + activeLinkForeground + " !important; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[597/*vs/editor/standalone/browser/referenceSearch/standaloneReferenceSearch*/], __M([0/*require*/,1/*exports*/,12/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,234/*vs/editor/contrib/gotoSymbol/peek/referencesController*/,43/*vs/platform/configuration/common/configuration*/,18/*vs/platform/contextkey/common/contextkey*/,11/*vs/platform/instantiation/common/instantiation*/,35/*vs/platform/notification/common/notification*/,74/*vs/platform/storage/common/storage*/]), function (require, exports, editorExtensions_1, codeEditorService_1, referencesController_1, configuration_1, contextkey_1, instantiation_1, notification_1, storage_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var StandaloneReferencesController = /** @class */ (function (_super) { __extends(StandaloneReferencesController, _super); function StandaloneReferencesController(editor, contextKeyService, editorService, notificationService, instantiationService, storageService, configurationService) { return _super.call(this, true, editor, contextKeyService, editorService, notificationService, instantiationService, storageService, configurationService) || this; } StandaloneReferencesController = __decorate([ __param(1, contextkey_1.IContextKeyService), __param(2, codeEditorService_1.ICodeEditorService), __param(3, notification_1.INotificationService), __param(4, instantiation_1.IInstantiationService), __param(5, storage_1.IStorageService), __param(6, configuration_1.IConfigurationService) ], StandaloneReferencesController); return StandaloneReferencesController; }(referencesController_1.ReferencesController)); exports.StandaloneReferencesController = StandaloneReferencesController; editorExtensions_1.registerEditorContribution(referencesController_1.ReferencesController.ID, StandaloneReferencesController); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[598/*vs/platform/severityIcon/common/severityIcon*/], __M([0/*require*/,1/*exports*/,112/*vs/base/common/severity*/,14/*vs/platform/theme/common/themeService*/,20/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, severity_1, themeService_1, colorRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var SeverityIcon; (function (SeverityIcon) { function className(severity) { switch (severity) { case severity_1.default.Ignore: return 'severity-ignore codicon-info'; case severity_1.default.Info: return 'codicon-info'; case severity_1.default.Warning: return 'codicon-warning'; case severity_1.default.Error: return 'codicon-error'; } return ''; } SeverityIcon.className = className; })(SeverityIcon = exports.SeverityIcon || (exports.SeverityIcon = {})); themeService_1.registerThemingParticipant(function (theme, collector) { var errorIconForeground = theme.getColor(colorRegistry_1.problemsErrorIconForeground); if (errorIconForeground) { collector.addRule("\n\t\t\t.monaco-editor .zone-widget .codicon-error,\n\t\t\t.markers-panel .marker-icon.codicon-error,\n\t\t\t.extensions-viewlet > .extensions .codicon-error,\n\t\t\t.monaco-dialog-box .dialog-message-row .codicon-error {\n\t\t\t\tcolor: " + errorIconForeground + ";\n\t\t\t}\n\t\t"); } var warningIconForeground = theme.getColor(colorRegistry_1.problemsWarningIconForeground); if (errorIconForeground) { collector.addRule("\n\t\t\t.monaco-editor .zone-widget .codicon-warning,\n\t\t\t.markers-panel .marker-icon.codicon-warning,\n\t\t\t.extensions-viewlet > .extensions .codicon-warning,\n\t\t\t.extension-editor .codicon-warning,\n\t\t\t.monaco-dialog-box .dialog-message-row .codicon-warning {\n\t\t\t\tcolor: " + warningIconForeground + ";\n\t\t\t}\n\t\t"); } var infoIconForeground = theme.getColor(colorRegistry_1.problemsInfoIconForeground); if (errorIconForeground) { collector.addRule("\n\t\t\t.monaco-editor .zone-widget .codicon-info,\n\t\t\t.markers-panel .marker-icon.codicon-info,\n\t\t\t.extensions-viewlet > .extensions .codicon-info,\n\t\t\t.extension-editor .codicon-info,\n\t\t\t.monaco-dialog-box .dialog-message-row .codicon-info {\n\t\t\t\tcolor: " + infoIconForeground + ";\n\t\t\t}\n\t\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[599/*vs/editor/contrib/gotoError/gotoErrorWidget*/], __M([0/*require*/,1/*exports*/,445/*vs/nls!vs/editor/contrib/gotoError/gotoErrorWidget*/,6/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,72/*vs/platform/markers/common/markers*/,3/*vs/editor/common/core/range*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,27/*vs/base/common/color*/,53/*vs/base/browser/ui/scrollbar/scrollableElement*/,136/*vs/base/common/labels*/,19/*vs/base/common/arrays*/,4/*vs/base/common/event*/,123/*vs/editor/contrib/peekView/peekView*/,39/*vs/base/common/resources*/,598/*vs/platform/severityIcon/common/severityIcon*/,312/*vs/css!vs/editor/contrib/gotoError/media/gotoErrorWidget*/]), function (require, exports, nls, dom, lifecycle_1, markers_1, range_1, colorRegistry_1, themeService_1, color_1, scrollableElement_1, labels_1, arrays_1, event_1, peekView_1, resources_1, severityIcon_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MessageWidget = /** @class */ (function () { function MessageWidget(parent, editor, onRelatedInformation, _openerService) { var _this = this; this._openerService = _openerService; this._lines = 0; this._longestLineLength = 0; this._relatedDiagnostics = new WeakMap(); this._disposables = new lifecycle_1.DisposableStore(); this._editor = editor; var domNode = document.createElement('div'); domNode.className = 'descriptioncontainer'; domNode.setAttribute('aria-live', 'assertive'); domNode.setAttribute('role', 'alert'); this._messageBlock = document.createElement('div'); dom.addClass(this._messageBlock, 'message'); domNode.appendChild(this._messageBlock); this._relatedBlock = document.createElement('div'); domNode.appendChild(this._relatedBlock); this._disposables.add(dom.addStandardDisposableListener(this._relatedBlock, 'click', function (event) { event.preventDefault(); var related = _this._relatedDiagnostics.get(event.target); if (related) { onRelatedInformation(related); } })); this._scrollable = new scrollableElement_1.ScrollableElement(domNode, { horizontal: 1 /* Auto */, vertical: 1 /* Auto */, useShadows: false, horizontalScrollbarSize: 3, verticalScrollbarSize: 3 }); parent.appendChild(this._scrollable.getDomNode()); this._disposables.add(this._scrollable.onScroll(function (e) { domNode.style.left = "-" + e.scrollLeft + "px"; domNode.style.top = "-" + e.scrollTop + "px"; })); this._disposables.add(this._scrollable); } MessageWidget.prototype.dispose = function () { lifecycle_1.dispose(this._disposables); }; MessageWidget.prototype.update = function (_a) { var _this = this; var source = _a.source, message = _a.message, relatedInformation = _a.relatedInformation, code = _a.code; var sourceAndCodeLength = ((source === null || source === void 0 ? void 0 : source.length) || 0) + '()'.length; if (code) { if (typeof code === 'string') { sourceAndCodeLength += code.length; } else { sourceAndCodeLength += code.value.length; } } var lines = message.split(/\r\n|\r|\n/g); this._lines = lines.length; this._longestLineLength = 0; for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { var line = lines_1[_i]; this._longestLineLength = Math.max(line.length + sourceAndCodeLength, this._longestLineLength); } dom.clearNode(this._messageBlock); this._editor.applyFontInfo(this._messageBlock); var lastLineElement = this._messageBlock; for (var _b = 0, lines_2 = lines; _b < lines_2.length; _b++) { var line = lines_2[_b]; lastLineElement = document.createElement('div'); lastLineElement.innerText = line; if (line === '') { lastLineElement.style.height = this._messageBlock.style.lineHeight; } this._messageBlock.appendChild(lastLineElement); } if (source || code) { var detailsElement = document.createElement('span'); dom.addClass(detailsElement, 'details'); lastLineElement.appendChild(detailsElement); if (source) { var sourceElement = document.createElement('span'); sourceElement.innerText = source; dom.addClass(sourceElement, 'source'); detailsElement.appendChild(sourceElement); } if (code) { if (typeof code === 'string') { var codeElement = document.createElement('span'); codeElement.innerText = "(" + code + ")"; dom.addClass(codeElement, 'code'); detailsElement.appendChild(codeElement); } else { this._codeLink = dom.$('a.code-link'); this._codeLink.setAttribute('href', "" + code.link.toString()); this._codeLink.onclick = function (e) { _this._openerService.open(code.link); e.preventDefault(); e.stopPropagation(); }; var codeElement = dom.append(this._codeLink, dom.$('span')); codeElement.innerText = code.value; detailsElement.appendChild(this._codeLink); } } } dom.clearNode(this._relatedBlock); this._editor.applyFontInfo(this._relatedBlock); if (arrays_1.isNonEmptyArray(relatedInformation)) { var relatedInformationNode = this._relatedBlock.appendChild(document.createElement('div')); relatedInformationNode.style.paddingTop = Math.floor(this._editor.getOption(49 /* lineHeight */) * 0.66) + "px"; this._lines += 1; for (var _c = 0, relatedInformation_1 = relatedInformation; _c < relatedInformation_1.length; _c++) { var related = relatedInformation_1[_c]; var container = document.createElement('div'); var relatedResource = document.createElement('a'); dom.addClass(relatedResource, 'filename'); relatedResource.innerHTML = labels_1.getBaseLabel(related.resource) + "(" + related.startLineNumber + ", " + related.startColumn + "): "; relatedResource.title = labels_1.getPathLabel(related.resource, undefined); this._relatedDiagnostics.set(relatedResource, related); var relatedMessage = document.createElement('span'); relatedMessage.innerText = related.message; container.appendChild(relatedResource); container.appendChild(relatedMessage); this._lines += 1; relatedInformationNode.appendChild(container); } } var fontInfo = this._editor.getOption(34 /* fontInfo */); var scrollWidth = Math.ceil(fontInfo.typicalFullwidthCharacterWidth * this._longestLineLength * 0.75); var scrollHeight = fontInfo.lineHeight * this._lines; this._scrollable.setScrollDimensions({ scrollWidth: scrollWidth, scrollHeight: scrollHeight }); }; MessageWidget.prototype.layout = function (height, width) { this._scrollable.getDomNode().style.height = height + "px"; this._scrollable.getDomNode().style.width = width + "px"; this._scrollable.setScrollDimensions({ width: width, height: height }); }; MessageWidget.prototype.getHeightInLines = function () { return Math.min(17, this._lines); }; return MessageWidget; }()); var MarkerNavigationWidget = /** @class */ (function (_super) { __extends(MarkerNavigationWidget, _super); function MarkerNavigationWidget(editor, actions, _themeService, _openerService) { var _this = _super.call(this, editor, { showArrow: true, showFrame: true, isAccessible: true }) || this; _this.actions = actions; _this._themeService = _themeService; _this._openerService = _openerService; _this._callOnDispose = new lifecycle_1.DisposableStore(); _this._onDidSelectRelatedInformation = new event_1.Emitter(); _this.onDidSelectRelatedInformation = _this._onDidSelectRelatedInformation.event; _this._severity = markers_1.MarkerSeverity.Warning; _this._backgroundColor = color_1.Color.white; _this._applyTheme(_themeService.getTheme()); _this._callOnDispose.add(_themeService.onThemeChange(_this._applyTheme.bind(_this))); _this.create(); return _this; } MarkerNavigationWidget.prototype._applyTheme = function (theme) { this._backgroundColor = theme.getColor(exports.editorMarkerNavigationBackground); var colorId = exports.editorMarkerNavigationError; if (this._severity === markers_1.MarkerSeverity.Warning) { colorId = exports.editorMarkerNavigationWarning; } else if (this._severity === markers_1.MarkerSeverity.Info) { colorId = exports.editorMarkerNavigationInfo; } var frameColor = theme.getColor(colorId); this.style({ arrowColor: frameColor, frameColor: frameColor, headerBackgroundColor: this._backgroundColor, primaryHeadingColor: theme.getColor(peekView_1.peekViewTitleForeground), secondaryHeadingColor: theme.getColor(peekView_1.peekViewTitleInfoForeground) }); // style() will trigger _applyStyles }; MarkerNavigationWidget.prototype._applyStyles = function () { if (this._parentContainer) { this._parentContainer.style.backgroundColor = this._backgroundColor ? this._backgroundColor.toString() : ''; } _super.prototype._applyStyles.call(this); }; MarkerNavigationWidget.prototype.dispose = function () { this._callOnDispose.dispose(); _super.prototype.dispose.call(this); }; MarkerNavigationWidget.prototype._fillHead = function (container) { _super.prototype._fillHead.call(this, container); this._actionbarWidget.push(this.actions, { label: false, icon: true, index: 0 }); }; MarkerNavigationWidget.prototype._fillTitleIcon = function (container) { this._icon = dom.append(container, dom.$('')); }; MarkerNavigationWidget.prototype._getActionBarOptions = function () { return { orientation: 0 /* HORIZONTAL */ }; }; MarkerNavigationWidget.prototype._fillBody = function (container) { var _this = this; this._parentContainer = container; dom.addClass(container, 'marker-widget'); this._parentContainer.tabIndex = 0; this._parentContainer.setAttribute('role', 'tooltip'); this._container = document.createElement('div'); container.appendChild(this._container); this._message = new MessageWidget(this._container, this.editor, function (related) { return _this._onDidSelectRelatedInformation.fire(related); }, this._openerService); this._disposables.add(this._message); }; MarkerNavigationWidget.prototype.show = function (where, heightInLines) { throw new Error('call showAtMarker'); }; MarkerNavigationWidget.prototype.showAtMarker = function (marker, markerIdx, markerCount) { // update: // * title // * message this._container.classList.remove('stale'); this._message.update(marker); // update frame color (only applied on 'show') this._severity = marker.severity; this._applyTheme(this._themeService.getTheme()); // show var range = range_1.Range.lift(marker); var editorPosition = this.editor.getPosition(); var position = editorPosition && range.containsPosition(editorPosition) ? editorPosition : range.getStartPosition(); _super.prototype.show.call(this, position, this.computeRequiredHeight()); var model = this.editor.getModel(); if (model) { var detail = markerCount > 1 ? nls.localize(0, null, markerIdx, markerCount) : nls.localize(1, null, markerIdx, markerCount); this.setTitle(resources_1.basename(model.uri), detail); } this._icon.className = "codicon " + severityIcon_1.SeverityIcon.className(markers_1.MarkerSeverity.toSeverity(this._severity)); this.editor.revealPositionInCenter(position, 0 /* Smooth */); this.editor.focus(); }; MarkerNavigationWidget.prototype.updateMarker = function (marker) { this._container.classList.remove('stale'); this._message.update(marker); }; MarkerNavigationWidget.prototype.showStale = function () { this._container.classList.add('stale'); this._relayout(); }; MarkerNavigationWidget.prototype._doLayoutBody = function (heightInPixel, widthInPixel) { _super.prototype._doLayoutBody.call(this, heightInPixel, widthInPixel); this._heightInPixel = heightInPixel; this._message.layout(heightInPixel, widthInPixel); this._container.style.height = heightInPixel + "px"; }; MarkerNavigationWidget.prototype._onWidth = function (widthInPixel) { this._message.layout(this._heightInPixel, widthInPixel); }; MarkerNavigationWidget.prototype._relayout = function () { _super.prototype._relayout.call(this, this.computeRequiredHeight()); }; MarkerNavigationWidget.prototype.computeRequiredHeight = function () { return 3 + this._message.getHeightInLines(); }; return MarkerNavigationWidget; }(peekView_1.PeekViewWidget)); exports.MarkerNavigationWidget = MarkerNavigationWidget; // theming var errorDefault = colorRegistry_1.oneOf(colorRegistry_1.editorErrorForeground, colorRegistry_1.editorErrorBorder); var warningDefault = colorRegistry_1.oneOf(colorRegistry_1.editorWarningForeground, colorRegistry_1.editorWarningBorder); var infoDefault = colorRegistry_1.oneOf(colorRegistry_1.editorInfoForeground, colorRegistry_1.editorInfoBorder); exports.editorMarkerNavigationError = colorRegistry_1.registerColor('editorMarkerNavigationError.background', { dark: errorDefault, light: errorDefault, hc: errorDefault }, nls.localize(2, null)); exports.editorMarkerNavigationWarning = colorRegistry_1.registerColor('editorMarkerNavigationWarning.background', { dark: warningDefault, light: warningDefault, hc: warningDefault }, nls.localize(3, null)); exports.editorMarkerNavigationInfo = colorRegistry_1.registerColor('editorMarkerNavigationInfo.background', { dark: infoDefault, light: infoDefault, hc: infoDefault }, nls.localize(4, null)); exports.editorMarkerNavigationBackground = colorRegistry_1.registerColor('editorMarkerNavigation.background', { dark: '#2D2D30', light: color_1.Color.white, hc: '#0C141F' }, nls.localize(5, null)); themeService_1.registerThemingParticipant(function (theme, collector) { var linkFg = theme.getColor(colorRegistry_1.textLinkForeground); if (linkFg) { collector.addRule(".monaco-editor .marker-widget a { color: " + linkFg + "; }"); collector.addRule(".monaco-editor .marker-widget a.code-link span:hover { color: " + linkFg + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * 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/contrib/gotoError/gotoError*/], __M([0/*require*/,1/*exports*/,444/*vs/nls!vs/editor/contrib/gotoError/gotoError*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,18/*vs/platform/contextkey/common/contextkey*/,72/*vs/platform/markers/common/markers*/,3/*vs/editor/common/core/range*/,12/*vs/editor/browser/editorExtensions*/,14/*vs/platform/theme/common/themeService*/,23/*vs/editor/common/editorContextKeys*/,599/*vs/editor/contrib/gotoError/gotoErrorWidget*/,5/*vs/base/common/strings*/,19/*vs/base/common/arrays*/,32/*vs/editor/browser/services/codeEditorService*/,10/*vs/base/common/errors*/,65/*vs/platform/actions/common/actions*/,55/*vs/base/common/actions*/,34/*vs/platform/keybinding/common/keybinding*/,39/*vs/base/common/resources*/,51/*vs/platform/opener/common/opener*/]), function (require, exports, nls, event_1, lifecycle_1, contextkey_1, markers_1, range_1, editorExtensions_1, themeService_1, editorContextKeys_1, gotoErrorWidget_1, strings_1, arrays_1, codeEditorService_1, errors_1, actions_1, actions_2, keybinding_1, resources_1, opener_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MarkerModel = /** @class */ (function () { function MarkerModel(editor, markers) { var _this = this; this._toUnbind = new lifecycle_1.DisposableStore(); this._editor = editor; this._markers = []; this._nextIdx = -1; this._ignoreSelectionChange = false; this._onCurrentMarkerChanged = new event_1.Emitter(); this._onMarkerSetChanged = new event_1.Emitter(); this.setMarkers(markers); // listen on editor this._toUnbind.add(this._editor.onDidDispose(function () { return _this.dispose(); })); this._toUnbind.add(this._editor.onDidChangeCursorPosition(function () { if (_this._ignoreSelectionChange) { return; } if (_this.currentMarker && _this._editor.getPosition() && range_1.Range.containsPosition(_this.currentMarker, _this._editor.getPosition())) { return; } _this._nextIdx = -1; })); } Object.defineProperty(MarkerModel.prototype, "onCurrentMarkerChanged", { get: function () { return this._onCurrentMarkerChanged.event; }, enumerable: true, configurable: true }); Object.defineProperty(MarkerModel.prototype, "onMarkerSetChanged", { get: function () { return this._onMarkerSetChanged.event; }, enumerable: true, configurable: true }); MarkerModel.prototype.setMarkers = function (markers) { var oldMarker = this._nextIdx >= 0 ? this._markers[this._nextIdx] : undefined; this._markers = markers || []; this._markers.sort(MarkerNavigationAction.compareMarker); if (!oldMarker) { this._nextIdx = -1; } else { this._nextIdx = Math.max(-1, arrays_1.binarySearch(this._markers, oldMarker, MarkerNavigationAction.compareMarker)); } this._onMarkerSetChanged.fire(this); }; MarkerModel.prototype.withoutWatchingEditorPosition = function (callback) { this._ignoreSelectionChange = true; try { callback(); } finally { this._ignoreSelectionChange = false; } }; MarkerModel.prototype._initIdx = function (fwd) { var found = false; var position = this._editor.getPosition(); for (var i = 0; i < this._markers.length; i++) { var range = range_1.Range.lift(this._markers[i]); if (range.isEmpty() && this._editor.getModel()) { var word = this._editor.getModel().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 (!found) { // after the last change this._nextIdx = fwd ? 0 : this._markers.length - 1; } if (this._nextIdx < 0) { this._nextIdx = this._markers.length - 1; } }; Object.defineProperty(MarkerModel.prototype, "currentMarker", { get: function () { return this.canNavigate() ? this._markers[this._nextIdx] : undefined; }, set: function (marker) { var idx = this._nextIdx; this._nextIdx = -1; if (marker) { this._nextIdx = this.indexOf(marker); } if (this._nextIdx !== idx) { this._onCurrentMarkerChanged.fire(marker); } }, enumerable: true, configurable: true }); MarkerModel.prototype.move = function (fwd, inCircles) { if (!this.canNavigate()) { this._onCurrentMarkerChanged.fire(undefined); return !inCircles; } var oldIdx = this._nextIdx; var atEdge = false; if (this._nextIdx === -1) { this._initIdx(fwd); } else if (fwd) { if (inCircles || this._nextIdx + 1 < this._markers.length) { this._nextIdx = (this._nextIdx + 1) % this._markers.length; } else { atEdge = true; } } else if (!fwd) { if (inCircles || this._nextIdx > 0) { this._nextIdx = (this._nextIdx - 1 + this._markers.length) % this._markers.length; } else { atEdge = true; } } if (oldIdx !== this._nextIdx) { var marker = this._markers[this._nextIdx]; this._onCurrentMarkerChanged.fire(marker); } return atEdge; }; MarkerModel.prototype.canNavigate = function () { return this._markers.length > 0; }; MarkerModel.prototype.findMarkerAtPosition = function (pos) { return arrays_1.find(this._markers, function (marker) { return range_1.Range.containsPosition(marker, pos); }); }; Object.defineProperty(MarkerModel.prototype, "total", { get: function () { return this._markers.length; }, enumerable: true, configurable: true }); MarkerModel.prototype.indexOf = function (marker) { return 1 + this._markers.indexOf(marker); }; MarkerModel.prototype.dispose = function () { this._toUnbind.dispose(); }; return MarkerModel; }()); var MarkerController = /** @class */ (function () { function MarkerController(editor, _markerService, _contextKeyService, _themeService, _editorService, _keybindingService, _openerService) { this._markerService = _markerService; this._contextKeyService = _contextKeyService; this._themeService = _themeService; this._editorService = _editorService; this._keybindingService = _keybindingService; this._openerService = _openerService; this._model = null; this._widget = null; this._disposeOnClose = new lifecycle_1.DisposableStore(); this._editor = editor; this._widgetVisible = CONTEXT_MARKERS_NAVIGATION_VISIBLE.bindTo(this._contextKeyService); } MarkerController.get = function (editor) { return editor.getContribution(MarkerController.ID); }; MarkerController.prototype.dispose = function () { this._cleanUp(); this._disposeOnClose.dispose(); }; MarkerController.prototype._cleanUp = function () { this._widgetVisible.reset(); this._disposeOnClose.clear(); this._widget = null; this._model = null; }; MarkerController.prototype.getOrCreateModel = function () { var _this = this; if (this._model) { return this._model; } var markers = this._getMarkers(); this._model = new MarkerModel(this._editor, markers); this._markerService.onMarkerChanged(this._onMarkerChanged, this, this._disposeOnClose); var prevMarkerKeybinding = this._keybindingService.lookupKeybinding(PrevMarkerAction.ID); var nextMarkerKeybinding = this._keybindingService.lookupKeybinding(NextMarkerAction.ID); var actions = [ new actions_2.Action(NextMarkerAction.ID, NextMarkerAction.LABEL + (nextMarkerKeybinding ? " (" + nextMarkerKeybinding.getLabel() + ")" : ''), 'show-next-problem codicon-chevron-down', this._model.canNavigate(), function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { if (this._model) { this._model.move(true, true); } return [2 /*return*/]; }); }); }), new actions_2.Action(PrevMarkerAction.ID, PrevMarkerAction.LABEL + (prevMarkerKeybinding ? " (" + prevMarkerKeybinding.getLabel() + ")" : ''), 'show-previous-problem codicon-chevron-up', this._model.canNavigate(), function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { if (this._model) { this._model.move(false, true); } return [2 /*return*/]; }); }); }) ]; this._widget = new gotoErrorWidget_1.MarkerNavigationWidget(this._editor, actions, this._themeService, this._openerService); this._widgetVisible.set(true); this._widget.onDidClose(function () { return _this.closeMarkersNavigation(); }, this, this._disposeOnClose); this._disposeOnClose.add(this._model); this._disposeOnClose.add(this._widget); for (var _i = 0, actions_3 = actions; _i < actions_3.length; _i++) { var action = actions_3[_i]; this._disposeOnClose.add(action); } this._disposeOnClose.add(this._widget.onDidSelectRelatedInformation(function (related) { _this._editorService.openCodeEditor({ resource: related.resource, options: { pinned: true, revealIfOpened: true, selection: range_1.Range.lift(related).collapseToStart() } }, _this._editor).then(undefined, errors_1.onUnexpectedError); _this.closeMarkersNavigation(false); })); this._disposeOnClose.add(this._editor.onDidChangeModel(function () { return _this._cleanUp(); })); this._disposeOnClose.add(this._model.onCurrentMarkerChanged(function (marker) { if (!marker || !_this._model) { _this._cleanUp(); } else { _this._model.withoutWatchingEditorPosition(function () { if (!_this._widget || !_this._model) { return; } _this._widget.showAtMarker(marker, _this._model.indexOf(marker), _this._model.total); }); } })); this._disposeOnClose.add(this._model.onMarkerSetChanged(function () { if (!_this._widget || !_this._widget.position || !_this._model) { return; } var marker = _this._model.findMarkerAtPosition(_this._widget.position); if (marker) { _this._widget.updateMarker(marker); } else { _this._widget.showStale(); } })); return this._model; }; MarkerController.prototype.closeMarkersNavigation = function (focusEditor) { if (focusEditor === void 0) { focusEditor = true; } this._cleanUp(); if (focusEditor) { this._editor.focus(); } }; MarkerController.prototype.show = function (marker) { var model = this.getOrCreateModel(); model.currentMarker = marker; }; MarkerController.prototype._onMarkerChanged = function (changedResources) { var editorModel = this._editor.getModel(); if (!editorModel) { return; } if (!this._model) { return; } if (!changedResources.some(function (r) { return resources_1.isEqual(editorModel.uri, r); })) { return; } this._model.setMarkers(this._getMarkers()); }; MarkerController.prototype._getMarkers = function () { var model = this._editor.getModel(); if (!model) { return []; } return this._markerService.read({ resource: model.uri, severities: markers_1.MarkerSeverity.Error | markers_1.MarkerSeverity.Warning | markers_1.MarkerSeverity.Info }); }; MarkerController.ID = 'editor.contrib.markerController'; MarkerController = __decorate([ __param(1, markers_1.IMarkerService), __param(2, contextkey_1.IContextKeyService), __param(3, themeService_1.IThemeService), __param(4, codeEditorService_1.ICodeEditorService), __param(5, keybinding_1.IKeybindingService), __param(6, opener_1.IOpenerService) ], MarkerController); return MarkerController; }()); exports.MarkerController = MarkerController; var MarkerNavigationAction = /** @class */ (function (_super) { __extends(MarkerNavigationAction, _super); function MarkerNavigationAction(next, multiFile, opts) { var _this = _super.call(this, opts) || this; _this._isNext = next; _this._multiFile = multiFile; return _this; } MarkerNavigationAction.prototype.run = function (accessor, editor) { var _this = this; var markerService = accessor.get(markers_1.IMarkerService); var editorService = accessor.get(codeEditorService_1.ICodeEditorService); var controller = MarkerController.get(editor); if (!controller) { return Promise.resolve(undefined); } var model = controller.getOrCreateModel(); var atEdge = model.move(this._isNext, !this._multiFile); if (!atEdge || !this._multiFile) { return Promise.resolve(undefined); } // try with the next/prev file var markers = markerService.read({ severities: markers_1.MarkerSeverity.Error | markers_1.MarkerSeverity.Warning | markers_1.MarkerSeverity.Info }).sort(MarkerNavigationAction.compareMarker); if (markers.length === 0) { return Promise.resolve(undefined); } var editorModel = editor.getModel(); if (!editorModel) { return Promise.resolve(undefined); } var oldMarker = model.currentMarker || { resource: editorModel.uri, severity: markers_1.MarkerSeverity.Error, startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 }; var idx = arrays_1.binarySearch(markers, oldMarker, MarkerNavigationAction.compareMarker); if (idx < 0) { // find best match... idx = ~idx; idx %= markers.length; } else if (this._isNext) { idx = (idx + 1) % markers.length; } else { idx = (idx + markers.length - 1) % markers.length; } var newMarker = markers[idx]; if (resources_1.isEqual(newMarker.resource, editorModel.uri)) { // the next `resource` is this resource which // means we cycle within this file model.move(this._isNext, true); return Promise.resolve(undefined); } // close the widget for this editor-instance, open the resource // for the next marker and re-start marker navigation in there controller.closeMarkersNavigation(); return editorService.openCodeEditor({ resource: newMarker.resource, options: { pinned: false, revealIfOpened: true, revealInCenterIfOutsideViewport: true, selection: newMarker } }, editor).then(function (editor) { if (!editor) { return undefined; } return editor.getAction(_this.id).run(); }); }; MarkerNavigationAction.compareMarker = function (a, b) { var res = strings_1.compare(a.resource.toString(), b.resource.toString()); if (res === 0) { res = markers_1.MarkerSeverity.compare(a.severity, b.severity); } if (res === 0) { res = range_1.Range.compareRangesUsingStarts(a, b); } return res; }; return MarkerNavigationAction; }(editorExtensions_1.EditorAction)); var NextMarkerAction = /** @class */ (function (_super) { __extends(NextMarkerAction, _super); function NextMarkerAction() { return _super.call(this, true, false, { id: NextMarkerAction.ID, label: NextMarkerAction.LABEL, alias: 'Go to Next Problem (Error, Warning, Info)', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 512 /* Alt */ | 66 /* F8 */, weight: 100 /* EditorContrib */ } }) || this; } NextMarkerAction.ID = 'editor.action.marker.next'; NextMarkerAction.LABEL = nls.localize(0, null); return NextMarkerAction; }(MarkerNavigationAction)); exports.NextMarkerAction = NextMarkerAction; var PrevMarkerAction = /** @class */ (function (_super) { __extends(PrevMarkerAction, _super); function PrevMarkerAction() { return _super.call(this, false, false, { id: PrevMarkerAction.ID, label: PrevMarkerAction.LABEL, alias: 'Go to Previous Problem (Error, Warning, Info)', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 1024 /* Shift */ | 512 /* Alt */ | 66 /* F8 */, weight: 100 /* EditorContrib */ } }) || this; } PrevMarkerAction.ID = 'editor.action.marker.prev'; PrevMarkerAction.LABEL = nls.localize(1, null); return PrevMarkerAction; }(MarkerNavigationAction)); var NextMarkerInFilesAction = /** @class */ (function (_super) { __extends(NextMarkerInFilesAction, _super); function NextMarkerInFilesAction() { return _super.call(this, true, true, { id: 'editor.action.marker.nextInFiles', label: nls.localize(2, null), alias: 'Go to Next Problem in Files (Error, Warning, Info)', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 66 /* F8 */, weight: 100 /* EditorContrib */ } }) || this; } return NextMarkerInFilesAction; }(MarkerNavigationAction)); var PrevMarkerInFilesAction = /** @class */ (function (_super) { __extends(PrevMarkerInFilesAction, _super); function PrevMarkerInFilesAction() { return _super.call(this, false, true, { id: 'editor.action.marker.prevInFiles', label: nls.localize(3, null), alias: 'Go to Previous Problem in Files (Error, Warning, Info)', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 1024 /* Shift */ | 66 /* F8 */, weight: 100 /* EditorContrib */ } }) || this; } return PrevMarkerInFilesAction; }(MarkerNavigationAction)); editorExtensions_1.registerEditorContribution(MarkerController.ID, MarkerController); editorExtensions_1.registerEditorAction(NextMarkerAction); editorExtensions_1.registerEditorAction(PrevMarkerAction); editorExtensions_1.registerEditorAction(NextMarkerInFilesAction); editorExtensions_1.registerEditorAction(PrevMarkerInFilesAction); var CONTEXT_MARKERS_NAVIGATION_VISIBLE = new contextkey_1.RawContextKey('markersNavigationVisible', false); var MarkerCommand = editorExtensions_1.EditorCommand.bindToContribution(MarkerController.get); editorExtensions_1.registerEditorCommand(new MarkerCommand({ id: 'closeMarkersNavigation', precondition: CONTEXT_MARKERS_NAVIGATION_VISIBLE, handler: function (x) { return x.closeMarkersNavigation(); }, kbOpts: { weight: 100 /* EditorContrib */ + 50, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 9 /* Escape */, secondary: [1024 /* Shift */ | 9 /* Escape */] } })); // Go to menu actions_1.MenuRegistry.appendMenuItem(19 /* MenubarGoMenu */, { group: '6_problem_nav', command: { id: 'editor.action.marker.nextInFiles', title: nls.localize(4, null) }, order: 1 }); actions_1.MenuRegistry.appendMenuItem(19 /* MenubarGoMenu */, { group: '6_problem_nav', command: { id: 'editor.action.marker.prevInFiles', title: nls.localize(5, null) }, order: 2 }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[600/*vs/editor/contrib/hover/modesContentHover*/], __M([0/*require*/,1/*exports*/,454/*vs/nls!vs/editor/contrib/hover/modesContentHover*/,6/*vs/base/browser/dom*/,26/*vs/base/common/cancellation*/,27/*vs/base/common/color*/,75/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,30/*vs/editor/common/model/textModel*/,17/*vs/editor/common/modes*/,222/*vs/editor/contrib/colorPicker/color*/,223/*vs/editor/contrib/colorPicker/colorDetector*/,375/*vs/editor/contrib/colorPicker/colorPickerModel*/,570/*vs/editor/contrib/colorPicker/colorPickerWidget*/,538/*vs/editor/contrib/hover/getHover*/,200/*vs/editor/contrib/hover/hoverOperation*/,201/*vs/editor/contrib/hover/hoverWidgets*/,117/*vs/editor/contrib/markdown/markdownRenderer*/,14/*vs/platform/theme/common/themeService*/,19/*vs/base/common/arrays*/,72/*vs/platform/markers/common/markers*/,39/*vs/base/common/resources*/,10/*vs/base/common/errors*/,51/*vs/platform/opener/common/opener*/,237/*vs/editor/contrib/gotoError/gotoError*/,15/*vs/base/common/async*/,119/*vs/editor/contrib/codeAction/codeAction*/,233/*vs/editor/contrib/codeAction/codeActionCommands*/,111/*vs/editor/contrib/codeAction/types*/,20/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, nls, dom, cancellation_1, color_1, htmlContent_1, lifecycle_1, position_1, range_1, textModel_1, modes_1, color_2, colorDetector_1, colorPickerModel_1, colorPickerWidget_1, getHover_1, hoverOperation_1, hoverWidgets_1, markdownRenderer_1, themeService_1, arrays_1, markers_1, resources_1, errors_1, opener_1, gotoError_1, async_1, codeAction_1, codeActionCommands_1, types_1, colorRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var $ = dom.$; var ColorHover = /** @class */ (function () { function ColorHover(range, color, provider) { this.range = range; this.color = color; this.provider = provider; } return ColorHover; }()); var MarkerHover = /** @class */ (function () { function MarkerHover(range, marker) { this.range = range; this.marker = marker; } return MarkerHover; }()); var ModesContentComputer = /** @class */ (function () { function ModesContentComputer(editor, _markerDecorationsService) { this._markerDecorationsService = _markerDecorationsService; this._editor = editor; this._result = []; } ModesContentComputer.prototype.setRange = function (range) { this._range = range; this._result = []; }; ModesContentComputer.prototype.clearResult = function () { this._result = []; }; ModesContentComputer.prototype.computeAsync = function (token) { if (!this._editor.hasModel() || !this._range) { return Promise.resolve([]); } var model = this._editor.getModel(); if (!modes_1.HoverProviderRegistry.has(model)) { return Promise.resolve([]); } return getHover_1.getHover(model, new position_1.Position(this._range.startLineNumber, this._range.startColumn), token); }; ModesContentComputer.prototype.computeSync = function () { var _this = this; if (!this._editor.hasModel() || !this._range) { return []; } var model = this._editor.getModel(); var lineNumber = this._range.startLineNumber; if (lineNumber > this._editor.getModel().getLineCount()) { // Illegal line number => no results return []; } var colorDetector = colorDetector_1.ColorDetector.get(this._editor); var maxColumn = model.getLineMaxColumn(lineNumber); var lineDecorations = this._editor.getLineDecorations(lineNumber); var didFindColor = false; var hoverRange = this._range; var result = lineDecorations.map(function (d) { var startColumn = (d.range.startLineNumber === lineNumber) ? d.range.startColumn : 1; var endColumn = (d.range.endLineNumber === lineNumber) ? d.range.endColumn : maxColumn; if (startColumn > hoverRange.startColumn || hoverRange.endColumn > endColumn) { return null; } var range = new range_1.Range(hoverRange.startLineNumber, startColumn, hoverRange.startLineNumber, endColumn); var marker = _this._markerDecorationsService.getMarker(model, d); if (marker) { return new MarkerHover(range, marker); } var colorData = colorDetector.getColorData(d.range.getStartPosition()); if (!didFindColor && colorData) { didFindColor = true; var _a = colorData.colorInfo, color = _a.color, range_2 = _a.range; return new ColorHover(range_2, color, colorData.provider); } else { if (htmlContent_1.isEmptyMarkdownString(d.options.hoverMessage)) { return null; } var contents = d.options.hoverMessage ? arrays_1.asArray(d.options.hoverMessage) : []; return { contents: contents, range: range }; } }); return arrays_1.coalesce(result); }; ModesContentComputer.prototype.onResult = function (result, isFromSynchronousComputation) { // Always put synchronous messages before asynchronous ones if (isFromSynchronousComputation) { this._result = result.concat(this._result.sort(function (a, b) { if (a instanceof ColorHover) { // sort picker messages at to the top return -1; } else if (b instanceof ColorHover) { return 1; } return 0; })); } else { this._result = this._result.concat(result); } }; ModesContentComputer.prototype.getResult = function () { return this._result.slice(0); }; ModesContentComputer.prototype.getResultWithLoadingMessage = function () { return this._result.slice(0).concat([this._getLoadingMessage()]); }; ModesContentComputer.prototype._getLoadingMessage = function () { return { range: this._range, contents: [new htmlContent_1.MarkdownString().appendText(nls.localize(0, null))] }; }; return ModesContentComputer; }()); var markerCodeActionTrigger = { type: 2 /* Manual */, filter: { include: types_1.CodeActionKind.QuickFix } }; var ModesContentHoverWidget = /** @class */ (function (_super) { __extends(ModesContentHoverWidget, _super); function ModesContentHoverWidget(editor, markerDecorationsService, _themeService, _keybindingService, _modeService, _openerService) { if (_openerService === void 0) { _openerService = opener_1.NullOpenerService; } var _this = _super.call(this, ModesContentHoverWidget.ID, editor) || this; _this._themeService = _themeService; _this._keybindingService = _keybindingService; _this._modeService = _modeService; _this._openerService = _openerService; _this.renderDisposable = _this._register(new lifecycle_1.MutableDisposable()); _this._messages = []; _this._lastRange = null; _this._computer = new ModesContentComputer(_this._editor, markerDecorationsService); _this._highlightDecorations = []; _this._isChangingDecorations = false; _this._shouldFocus = false; _this._colorPicker = null; _this._hoverOperation = new hoverOperation_1.HoverOperation(_this._computer, function (result) { return _this._withResult(result, true); }, null, function (result) { return _this._withResult(result, false); }, _this._editor.getOption(44 /* hover */).delay); _this._register(dom.addStandardDisposableListener(_this.getDomNode(), dom.EventType.FOCUS, function () { if (_this._colorPicker) { dom.addClass(_this.getDomNode(), 'colorpicker-hover'); } })); _this._register(dom.addStandardDisposableListener(_this.getDomNode(), dom.EventType.BLUR, function () { dom.removeClass(_this.getDomNode(), 'colorpicker-hover'); })); _this._register(editor.onDidChangeConfiguration(function (e) { _this._hoverOperation.setHoverTime(_this._editor.getOption(44 /* hover */).delay); })); _this._register(modes_1.TokenizationRegistry.onDidChange(function (e) { if (_this.isVisible && _this._lastRange && _this._messages.length > 0) { _this._domNode.textContent = ''; _this._renderMessages(_this._lastRange, _this._messages); } })); return _this; } ModesContentHoverWidget.prototype.dispose = function () { this._hoverOperation.cancel(); _super.prototype.dispose.call(this); }; ModesContentHoverWidget.prototype.onModelDecorationsChanged = function () { if (this._isChangingDecorations) { return; } if (this.isVisible) { // The decorations have changed and the hover is visible, // we need to recompute the displayed text this._hoverOperation.cancel(); this._computer.clearResult(); if (!this._colorPicker) { // TODO@Michel ensure that displayed text for other decorations is computed even if color picker is in place this._hoverOperation.start(0 /* Delayed */); } } }; ModesContentHoverWidget.prototype.startShowingAt = function (range, mode, focus) { if (this._lastRange && this._lastRange.equalsRange(range)) { // We have to show the widget at the exact same range as before, so no work is needed return; } this._hoverOperation.cancel(); if (this.isVisible) { // The range might have changed, but the hover is visible // Instead of hiding it completely, filter out messages that are still in the new range and // kick off a new computation if (!this._showAtPosition || this._showAtPosition.lineNumber !== range.startLineNumber) { this.hide(); } else { var filteredMessages = []; for (var i = 0, len = this._messages.length; i < len; i++) { var msg = this._messages[i]; var rng = msg.range; if (rng && rng.startColumn <= range.startColumn && rng.endColumn >= range.endColumn) { filteredMessages.push(msg); } } if (filteredMessages.length > 0) { if (hoverContentsEquals(filteredMessages, this._messages)) { return; } this._renderMessages(range, filteredMessages); } else { this.hide(); } } } this._lastRange = range; this._computer.setRange(range); this._shouldFocus = focus; this._hoverOperation.start(mode); }; ModesContentHoverWidget.prototype.hide = function () { this._lastRange = null; this._hoverOperation.cancel(); _super.prototype.hide.call(this); this._isChangingDecorations = true; this._highlightDecorations = this._editor.deltaDecorations(this._highlightDecorations, []); this._isChangingDecorations = false; this.renderDisposable.clear(); this._colorPicker = null; }; ModesContentHoverWidget.prototype.isColorPickerVisible = function () { if (this._colorPicker) { return true; } return false; }; ModesContentHoverWidget.prototype._withResult = function (result, complete) { this._messages = result; if (this._lastRange && this._messages.length > 0) { this._renderMessages(this._lastRange, this._messages); } else if (complete) { this.hide(); } }; ModesContentHoverWidget.prototype._renderMessages = function (renderRange, messages) { var _this = this; this.renderDisposable.dispose(); this._colorPicker = null; // update column from which to show var renderColumn = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; var highlightRange = messages[0].range ? range_1.Range.lift(messages[0].range) : null; var fragment = document.createDocumentFragment(); var isEmptyHoverContent = true; var containColorPicker = false; var markdownDisposeables = new lifecycle_1.DisposableStore(); var markerMessages = []; messages.forEach(function (msg) { if (!msg.range) { return; } renderColumn = Math.min(renderColumn, msg.range.startColumn); highlightRange = highlightRange ? range_1.Range.plusRange(highlightRange, msg.range) : range_1.Range.lift(msg.range); if (msg instanceof ColorHover) { containColorPicker = true; var _a = msg.color, red = _a.red, green = _a.green, blue = _a.blue, alpha = _a.alpha; var rgba = new color_1.RGBA(Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255), alpha); var color_3 = new color_1.Color(rgba); if (!_this._editor.hasModel()) { return; } var editorModel_1 = _this._editor.getModel(); var range_3 = new range_1.Range(msg.range.startLineNumber, msg.range.startColumn, msg.range.endLineNumber, msg.range.endColumn); var colorInfo = { range: msg.range, color: msg.color }; // create blank olor picker model and widget first to ensure it's positioned correctly. var model_1 = new colorPickerModel_1.ColorPickerModel(color_3, [], 0); var widget_1 = new colorPickerWidget_1.ColorPickerWidget(fragment, model_1, _this._editor.getOption(105 /* pixelRatio */), _this._themeService); color_2.getColorPresentations(editorModel_1, colorInfo, msg.provider, cancellation_1.CancellationToken.None).then(function (colorPresentations) { model_1.colorPresentations = colorPresentations || []; if (!_this._editor.hasModel()) { // gone... return; } var originalText = _this._editor.getModel().getValueInRange(msg.range); model_1.guessColorPresentation(color_3, originalText); var updateEditorModel = function () { var textEdits; var newRange; if (model_1.presentation.textEdit) { textEdits = [model_1.presentation.textEdit]; newRange = new range_1.Range(model_1.presentation.textEdit.range.startLineNumber, model_1.presentation.textEdit.range.startColumn, model_1.presentation.textEdit.range.endLineNumber, model_1.presentation.textEdit.range.endColumn); newRange = newRange.setEndPosition(newRange.endLineNumber, newRange.startColumn + model_1.presentation.textEdit.text.length); } else { textEdits = [{ identifier: null, range: range_3, text: model_1.presentation.label, forceMoveMarkers: false }]; newRange = range_3.setEndPosition(range_3.endLineNumber, range_3.startColumn + model_1.presentation.label.length); } _this._editor.pushUndoStop(); _this._editor.executeEdits('colorpicker', textEdits); if (model_1.presentation.additionalTextEdits) { textEdits = __spreadArrays(model_1.presentation.additionalTextEdits); _this._editor.executeEdits('colorpicker', textEdits); _this.hide(); } _this._editor.pushUndoStop(); range_3 = newRange; }; var updateColorPresentations = function (color) { return color_2.getColorPresentations(editorModel_1, { range: range_3, color: { red: color.rgba.r / 255, green: color.rgba.g / 255, blue: color.rgba.b / 255, alpha: color.rgba.a } }, msg.provider, cancellation_1.CancellationToken.None).then(function (colorPresentations) { model_1.colorPresentations = colorPresentations || []; }); }; var colorListener = model_1.onColorFlushed(function (color) { updateColorPresentations(color).then(updateEditorModel); }); var colorChangeListener = model_1.onDidChangeColor(updateColorPresentations); _this._colorPicker = widget_1; _this.showAt(range_3.getStartPosition(), range_3, _this._shouldFocus); _this.updateContents(fragment); _this._colorPicker.layout(); _this.renderDisposable.value = lifecycle_1.combinedDisposable(colorListener, colorChangeListener, widget_1, markdownDisposeables); }); } else { if (msg instanceof MarkerHover) { markerMessages.push(msg); isEmptyHoverContent = false; } else { msg.contents .filter(function (contents) { return !htmlContent_1.isEmptyMarkdownString(contents); }) .forEach(function (contents) { var markdownHoverElement = $('div.hover-row.markdown-hover'); var hoverContentsElement = dom.append(markdownHoverElement, $('div.hover-contents')); var renderer = markdownDisposeables.add(new markdownRenderer_1.MarkdownRenderer(_this._editor, _this._modeService, _this._openerService)); markdownDisposeables.add(renderer.onDidRenderCodeBlock(function () { hoverContentsElement.className = 'hover-contents code-hover-contents'; _this.onContentsChange(); })); var renderedContents = markdownDisposeables.add(renderer.render(contents)); hoverContentsElement.appendChild(renderedContents.element); fragment.appendChild(markdownHoverElement); isEmptyHoverContent = false; }); } } }); if (markerMessages.length) { markerMessages.forEach(function (msg) { return fragment.appendChild(_this.renderMarkerHover(msg)); }); var markerHoverForStatusbar = markerMessages.length === 1 ? markerMessages[0] : markerMessages.sort(function (a, b) { return markers_1.MarkerSeverity.compare(a.marker.severity, b.marker.severity); })[0]; fragment.appendChild(this.renderMarkerStatusbar(markerHoverForStatusbar)); } // show if (!containColorPicker && !isEmptyHoverContent) { this.showAt(new position_1.Position(renderRange.startLineNumber, renderColumn), highlightRange, this._shouldFocus); this.updateContents(fragment); } this._isChangingDecorations = true; this._highlightDecorations = this._editor.deltaDecorations(this._highlightDecorations, highlightRange ? [{ range: highlightRange, options: ModesContentHoverWidget._DECORATION_OPTIONS }] : []); this._isChangingDecorations = false; }; ModesContentHoverWidget.prototype.renderMarkerHover = function (markerHover) { var _this = this; var hoverElement = $('div.hover-row'); var markerElement = dom.append(hoverElement, $('div.marker.hover-contents')); var _a = markerHover.marker, source = _a.source, message = _a.message, code = _a.code, relatedInformation = _a.relatedInformation; this._editor.applyFontInfo(markerElement); var messageElement = dom.append(markerElement, $('span')); messageElement.style.whiteSpace = 'pre-wrap'; messageElement.innerText = message; if (source || code) { if (typeof code === 'string') { var detailsElement = dom.append(markerElement, $('span')); detailsElement.style.opacity = '0.6'; detailsElement.style.paddingLeft = '6px'; detailsElement.innerText = source && code ? source + "(" + code + ")" : source ? source : "(" + code + ")"; } else { if (code) { var sourceAndCodeElement = $('span'); if (source) { var sourceElement = dom.append(sourceAndCodeElement, $('span')); sourceElement.innerText = source; } this._codeLink = dom.append(sourceAndCodeElement, $('a.code-link')); this._codeLink.setAttribute('href', code.link.toString()); this._codeLink.onclick = function (e) { _this._openerService.open(code.link); e.preventDefault(); e.stopPropagation(); }; var codeElement = dom.append(this._codeLink, $('span')); codeElement.innerText = code.value; var detailsElement = dom.append(markerElement, sourceAndCodeElement); detailsElement.style.opacity = '0.6'; detailsElement.style.paddingLeft = '6px'; } } } if (arrays_1.isNonEmptyArray(relatedInformation)) { var _loop_1 = function (message_1, resource, startLineNumber, startColumn) { var relatedInfoContainer = dom.append(markerElement, $('div')); relatedInfoContainer.style.marginTop = '8px'; var a = dom.append(relatedInfoContainer, $('a')); a.innerText = resources_1.basename(resource) + "(" + startLineNumber + ", " + startColumn + "): "; a.style.cursor = 'pointer'; a.onclick = function (e) { e.stopPropagation(); e.preventDefault(); if (_this._openerService) { _this._openerService.open(resource.with({ fragment: startLineNumber + "," + startColumn }), { fromUserGesture: true }).catch(errors_1.onUnexpectedError); } }; var messageElement_1 = dom.append(relatedInfoContainer, $('span')); messageElement_1.innerText = message_1; this_1._editor.applyFontInfo(messageElement_1); }; var this_1 = this; for (var _i = 0, relatedInformation_1 = relatedInformation; _i < relatedInformation_1.length; _i++) { var _b = relatedInformation_1[_i], message_1 = _b.message, resource = _b.resource, startLineNumber = _b.startLineNumber, startColumn = _b.startColumn; _loop_1(message_1, resource, startLineNumber, startColumn); } } return hoverElement; }; ModesContentHoverWidget.prototype.renderMarkerStatusbar = function (markerHover) { var _this = this; var hoverElement = $('div.hover-row.status-bar'); var disposables = new lifecycle_1.DisposableStore(); var actionsElement = dom.append(hoverElement, $('div.actions')); if (markerHover.marker.severity === markers_1.MarkerSeverity.Error || markerHover.marker.severity === markers_1.MarkerSeverity.Warning || markerHover.marker.severity === markers_1.MarkerSeverity.Info) { disposables.add(this.renderAction(actionsElement, { label: nls.localize(1, null), commandId: gotoError_1.NextMarkerAction.ID, run: function () { _this.hide(); gotoError_1.MarkerController.get(_this._editor).show(markerHover.marker); _this._editor.focus(); } })); } var quickfixPlaceholderElement = dom.append(actionsElement, $('div')); quickfixPlaceholderElement.style.opacity = '0'; quickfixPlaceholderElement.style.transition = 'opacity 0.2s'; setTimeout(function () { return quickfixPlaceholderElement.style.opacity = '1'; }, 200); quickfixPlaceholderElement.textContent = nls.localize(2, null); disposables.add(lifecycle_1.toDisposable(function () { return quickfixPlaceholderElement.remove(); })); var codeActionsPromise = this.getCodeActions(markerHover.marker); disposables.add(lifecycle_1.toDisposable(function () { return codeActionsPromise.cancel(); })); codeActionsPromise.then(function (actions) { quickfixPlaceholderElement.style.transition = ''; quickfixPlaceholderElement.style.opacity = '1'; if (!actions.validActions.length) { actions.dispose(); quickfixPlaceholderElement.textContent = nls.localize(3, null); return; } quickfixPlaceholderElement.remove(); var showing = false; disposables.add(lifecycle_1.toDisposable(function () { if (!showing) { actions.dispose(); } })); disposables.add(_this.renderAction(actionsElement, { label: nls.localize(4, null), commandId: codeActionCommands_1.QuickFixAction.Id, run: function (target) { showing = true; var controller = codeActionCommands_1.QuickFixController.get(_this._editor); var elementPosition = dom.getDomNodePagePosition(target); controller.showCodeActions(markerCodeActionTrigger, actions, { x: elementPosition.left + 6, y: elementPosition.top + elementPosition.height + 6 }); } })); }); this.renderDisposable.value = disposables; return hoverElement; }; ModesContentHoverWidget.prototype.getCodeActions = function (marker) { var _this = this; return async_1.createCancelablePromise(function (cancellationToken) { return codeAction_1.getCodeActions(_this._editor.getModel(), new range_1.Range(marker.startLineNumber, marker.startColumn, marker.endLineNumber, marker.endColumn), markerCodeActionTrigger, cancellationToken); }); }; ModesContentHoverWidget.prototype.renderAction = function (parent, actionOptions) { var actionContainer = dom.append(parent, $('div.action-container')); var action = dom.append(actionContainer, $('a.action')); if (actionOptions.iconClass) { dom.append(action, $("span.icon." + actionOptions.iconClass)); } var label = dom.append(action, $('span')); label.textContent = actionOptions.label; var keybinding = this._keybindingService.lookupKeybinding(actionOptions.commandId); if (keybinding) { label.title = actionOptions.label + " (" + keybinding.getLabel() + ")"; } return dom.addDisposableListener(actionContainer, dom.EventType.CLICK, function (e) { e.stopPropagation(); e.preventDefault(); actionOptions.run(actionContainer); }); }; ModesContentHoverWidget.ID = 'editor.contrib.modesContentHoverWidget'; ModesContentHoverWidget._DECORATION_OPTIONS = textModel_1.ModelDecorationOptions.register({ className: 'hoverHighlight' }); return ModesContentHoverWidget; }(hoverWidgets_1.ContentHoverWidget)); exports.ModesContentHoverWidget = ModesContentHoverWidget; function hoverContentsEquals(first, second) { if ((!first && second) || (first && !second) || first.length !== second.length) { return false; } for (var i = 0; i < first.length; i++) { var firstElement = first[i]; var secondElement = second[i]; if (firstElement instanceof MarkerHover && secondElement instanceof MarkerHover) { return markers_1.IMarkerData.makeKey(firstElement.marker) === markers_1.IMarkerData.makeKey(secondElement.marker); } if (firstElement instanceof ColorHover || secondElement instanceof ColorHover) { return false; } if (firstElement instanceof MarkerHover || secondElement instanceof MarkerHover) { return false; } if (!htmlContent_1.markedStringsEquals(firstElement.contents, secondElement.contents)) { return false; } } return true; } themeService_1.registerThemingParticipant(function (theme, collector) { var linkFg = theme.getColor(colorRegistry_1.textLinkForeground); if (linkFg) { collector.addRule(".monaco-editor-hover .hover-contents a.code-link span:hover { color: " + linkFg + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * 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/hover/hover*/], __M([0/*require*/,1/*exports*/,453/*vs/nls!vs/editor/contrib/hover/hover*/,36/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,12/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,23/*vs/editor/common/editorContextKeys*/,71/*vs/editor/common/services/modeService*/,600/*vs/editor/contrib/hover/modesContentHover*/,510/*vs/editor/contrib/hover/modesGlyphHover*/,51/*vs/platform/opener/common/opener*/,20/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,210/*vs/editor/common/services/markersDecorationService*/,34/*vs/platform/keybinding/common/keybinding*/,236/*vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/,315/*vs/css!vs/editor/contrib/hover/hover*/]), function (require, exports, nls, keyCodes_1, lifecycle_1, editorExtensions_1, range_1, editorContextKeys_1, modeService_1, modesContentHover_1, modesGlyphHover_1, opener_1, colorRegistry_1, themeService_1, markersDecorationService_1, keybinding_1, goToDefinitionAtPosition_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ModesHoverController = /** @class */ (function () { function ModesHoverController(_editor, _openerService, _modeService, _markerDecorationsService, _keybindingService, _themeService) { var _this = this; this._editor = _editor; this._openerService = _openerService; this._modeService = _modeService; this._markerDecorationsService = _markerDecorationsService; this._keybindingService = _keybindingService; this._themeService = _themeService; this._toUnhook = new lifecycle_1.DisposableStore(); this._contentWidget = new lifecycle_1.MutableDisposable(); this._glyphWidget = new lifecycle_1.MutableDisposable(); this._isMouseDown = false; this._hoverClicked = false; this._hookEvents(); this._didChangeConfigurationHandler = this._editor.onDidChangeConfiguration(function (e) { if (e.hasChanged(44 /* hover */)) { _this._hideWidgets(); _this._unhookEvents(); _this._hookEvents(); } }); } Object.defineProperty(ModesHoverController.prototype, "contentWidget", { get: function () { if (!this._contentWidget.value) { this._createHoverWidgets(); } return this._contentWidget.value; }, enumerable: true, configurable: true }); Object.defineProperty(ModesHoverController.prototype, "glyphWidget", { get: function () { if (!this._glyphWidget.value) { this._createHoverWidgets(); } return this._glyphWidget.value; }, enumerable: true, configurable: true }); ModesHoverController.get = function (editor) { return editor.getContribution(ModesHoverController.ID); }; ModesHoverController.prototype._hookEvents = function () { var _this = this; var hideWidgetsEventHandler = function () { return _this._hideWidgets(); }; var hoverOpts = this._editor.getOption(44 /* hover */); this._isHoverEnabled = hoverOpts.enabled; this._isHoverSticky = hoverOpts.sticky; if (this._isHoverEnabled) { this._toUnhook.add(this._editor.onMouseDown(function (e) { return _this._onEditorMouseDown(e); })); this._toUnhook.add(this._editor.onMouseUp(function (e) { return _this._onEditorMouseUp(e); })); this._toUnhook.add(this._editor.onMouseMove(function (e) { return _this._onEditorMouseMove(e); })); this._toUnhook.add(this._editor.onKeyDown(function (e) { return _this._onKeyDown(e); })); this._toUnhook.add(this._editor.onDidChangeModelDecorations(function () { return _this._onModelDecorationsChanged(); })); } else { this._toUnhook.add(this._editor.onMouseMove(hideWidgetsEventHandler)); } this._toUnhook.add(this._editor.onMouseLeave(hideWidgetsEventHandler)); this._toUnhook.add(this._editor.onDidChangeModel(hideWidgetsEventHandler)); this._toUnhook.add(this._editor.onDidScrollChange(function (e) { return _this._onEditorScrollChanged(e); })); }; ModesHoverController.prototype._unhookEvents = function () { this._toUnhook.clear(); }; ModesHoverController.prototype._onModelDecorationsChanged = function () { this.contentWidget.onModelDecorationsChanged(); this.glyphWidget.onModelDecorationsChanged(); }; ModesHoverController.prototype._onEditorScrollChanged = function (e) { if (e.scrollTopChanged || e.scrollLeftChanged) { this._hideWidgets(); } }; ModesHoverController.prototype._onEditorMouseDown = function (mouseEvent) { this._isMouseDown = true; var targetType = mouseEvent.target.type; if (targetType === 9 /* CONTENT_WIDGET */ && mouseEvent.target.detail === modesContentHover_1.ModesContentHoverWidget.ID) { this._hoverClicked = true; // mouse down on top of content hover widget return; } if (targetType === 12 /* OVERLAY_WIDGET */ && mouseEvent.target.detail === modesGlyphHover_1.ModesGlyphHoverWidget.ID) { // mouse down on top of overlay hover widget return; } if (targetType !== 12 /* OVERLAY_WIDGET */ && mouseEvent.target.detail !== modesGlyphHover_1.ModesGlyphHoverWidget.ID) { this._hoverClicked = false; } this._hideWidgets(); }; ModesHoverController.prototype._onEditorMouseUp = function (mouseEvent) { this._isMouseDown = false; }; ModesHoverController.prototype._onEditorMouseMove = function (mouseEvent) { var targetType = mouseEvent.target.type; if (this._isMouseDown && this._hoverClicked && this.contentWidget.isColorPickerVisible()) { return; } if (this._isHoverSticky && targetType === 9 /* CONTENT_WIDGET */ && mouseEvent.target.detail === modesContentHover_1.ModesContentHoverWidget.ID) { // mouse moved on top of content hover widget return; } if (this._isHoverSticky && targetType === 12 /* OVERLAY_WIDGET */ && mouseEvent.target.detail === modesGlyphHover_1.ModesGlyphHoverWidget.ID) { // mouse moved on top of overlay hover widget return; } if (targetType === 7 /* CONTENT_EMPTY */) { var epsilon = this._editor.getOption(34 /* fontInfo */).typicalHalfwidthCharacterWidth / 2; var data = mouseEvent.target.detail; if (data && !data.isAfterLines && typeof data.horizontalDistanceToText === 'number' && data.horizontalDistanceToText < epsilon) { // Let hover kick in even when the mouse is technically in the empty area after a line, given the distance is small enough targetType = 6 /* CONTENT_TEXT */; } } if (targetType === 6 /* CONTENT_TEXT */) { this.glyphWidget.hide(); if (this._isHoverEnabled && mouseEvent.target.range) { this.contentWidget.startShowingAt(mouseEvent.target.range, 0 /* Delayed */, false); } } else if (targetType === 2 /* GUTTER_GLYPH_MARGIN */) { this.contentWidget.hide(); if (this._isHoverEnabled && mouseEvent.target.position) { this.glyphWidget.startShowingAt(mouseEvent.target.position.lineNumber); } } else { this._hideWidgets(); } }; ModesHoverController.prototype._onKeyDown = function (e) { if (e.keyCode !== 5 /* Ctrl */ && e.keyCode !== 6 /* Alt */ && e.keyCode !== 57 /* Meta */ && e.keyCode !== 4 /* Shift */) { // Do not hide hover when a modifier key is pressed this._hideWidgets(); } }; ModesHoverController.prototype._hideWidgets = function () { if (!this._glyphWidget.value || !this._contentWidget.value || (this._isMouseDown && this._hoverClicked && this._contentWidget.value.isColorPickerVisible())) { return; } this._glyphWidget.value.hide(); this._contentWidget.value.hide(); }; ModesHoverController.prototype._createHoverWidgets = function () { this._contentWidget.value = new modesContentHover_1.ModesContentHoverWidget(this._editor, this._markerDecorationsService, this._themeService, this._keybindingService, this._modeService, this._openerService); this._glyphWidget.value = new modesGlyphHover_1.ModesGlyphHoverWidget(this._editor, this._modeService, this._openerService); }; ModesHoverController.prototype.showContentHover = function (range, mode, focus) { this.contentWidget.startShowingAt(range, mode, focus); }; ModesHoverController.prototype.dispose = function () { this._unhookEvents(); this._toUnhook.dispose(); this._didChangeConfigurationHandler.dispose(); this._glyphWidget.dispose(); this._contentWidget.dispose(); }; ModesHoverController.ID = 'editor.contrib.hover'; ModesHoverController = __decorate([ __param(1, opener_1.IOpenerService), __param(2, modeService_1.IModeService), __param(3, markersDecorationService_1.IMarkerDecorationsService), __param(4, keybinding_1.IKeybindingService), __param(5, themeService_1.IThemeService) ], ModesHoverController); return ModesHoverController; }()); exports.ModesHoverController = ModesHoverController; var ShowHoverAction = /** @class */ (function (_super) { __extends(ShowHoverAction, _super); function ShowHoverAction() { return _super.call(this, { id: 'editor.action.showHover', label: nls.localize(0, null), alias: 'Show Hover', precondition: undefined, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 39 /* KEY_I */), weight: 100 /* EditorContrib */ } }) || this; } ShowHoverAction.prototype.run = function (accessor, editor) { if (!editor.hasModel()) { return; } var controller = ModesHoverController.get(editor); if (!controller) { return; } var position = editor.getPosition(); var range = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column); var focus = editor.getOption(2 /* accessibilitySupport */) === 2 /* Enabled */; controller.showContentHover(range, 1 /* Immediate */, focus); }; return ShowHoverAction; }(editorExtensions_1.EditorAction)); var ShowDefinitionPreviewHoverAction = /** @class */ (function (_super) { __extends(ShowDefinitionPreviewHoverAction, _super); function ShowDefinitionPreviewHoverAction() { return _super.call(this, { id: 'editor.action.showDefinitionPreviewHover', label: nls.localize(1, null), alias: 'Show Definition Preview Hover', precondition: undefined }) || this; } ShowDefinitionPreviewHoverAction.prototype.run = function (accessor, editor) { var controller = ModesHoverController.get(editor); if (!controller) { return; } var position = editor.getPosition(); if (!position) { return; } var range = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column); var goto = goToDefinitionAtPosition_1.GotoDefinitionAtPositionEditorContribution.get(editor); var promise = goto.startFindDefinitionFromCursor(position); if (promise) { promise.then(function () { controller.showContentHover(range, 1 /* Immediate */, true); }); } else { controller.showContentHover(range, 1 /* Immediate */, true); } }; return ShowDefinitionPreviewHoverAction; }(editorExtensions_1.EditorAction)); editorExtensions_1.registerEditorContribution(ModesHoverController.ID, ModesHoverController); editorExtensions_1.registerEditorAction(ShowHoverAction); editorExtensions_1.registerEditorAction(ShowDefinitionPreviewHoverAction); // theming themeService_1.registerThemingParticipant(function (theme, collector) { var editorHoverHighlightColor = theme.getColor(colorRegistry_1.editorHoverHighlight); if (editorHoverHighlightColor) { collector.addRule(".monaco-editor .hoverHighlight { background-color: " + editorHoverHighlightColor + "; }"); } var hoverBackground = theme.getColor(colorRegistry_1.editorHoverBackground); if (hoverBackground) { collector.addRule(".monaco-editor .monaco-editor-hover { background-color: " + hoverBackground + "; }"); } var hoverBorder = theme.getColor(colorRegistry_1.editorHoverBorder); if (hoverBorder) { collector.addRule(".monaco-editor .monaco-editor-hover { border: 1px solid " + hoverBorder + "; }"); collector.addRule(".monaco-editor .monaco-editor-hover .hover-row:not(:first-child):not(:empty) { border-top: 1px solid " + hoverBorder.transparent(0.5) + "; }"); collector.addRule(".monaco-editor .monaco-editor-hover hr { border-top: 1px solid " + hoverBorder.transparent(0.5) + "; }"); collector.addRule(".monaco-editor .monaco-editor-hover hr { border-bottom: 0px solid " + hoverBorder.transparent(0.5) + "; }"); } var link = theme.getColor(colorRegistry_1.textLinkForeground); if (link) { collector.addRule(".monaco-editor .monaco-editor-hover a { color: " + link + "; }"); } var hoverForeground = theme.getColor(colorRegistry_1.editorHoverForeground); if (hoverForeground) { collector.addRule(".monaco-editor .monaco-editor-hover { color: " + hoverForeground + "; }"); } var actionsBackground = theme.getColor(colorRegistry_1.editorHoverStatusBarBackground); if (actionsBackground) { collector.addRule(".monaco-editor .monaco-editor-hover .hover-row .actions { background-color: " + actionsBackground + "; }"); } var codeBackground = theme.getColor(colorRegistry_1.textCodeBlockBackground); if (codeBackground) { collector.addRule(".monaco-editor .monaco-editor-hover code { background-color: " + codeBackground + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[171/*vs/platform/workspace/common/workspace*/], __M([0/*require*/,1/*exports*/,25/*vs/base/common/uri*/,39/*vs/base/common/resources*/,11/*vs/platform/instantiation/common/instantiation*/,38/*vs/base/common/map*/]), function (require, exports, uri_1, resources, instantiation_1, map_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IWorkspaceContextService = instantiation_1.createDecorator('contextService'); var IWorkspace; (function (IWorkspace) { function isIWorkspace(thing) { return thing && typeof thing === 'object' && typeof thing.id === 'string' && Array.isArray(thing.folders); } IWorkspace.isIWorkspace = isIWorkspace; })(IWorkspace = exports.IWorkspace || (exports.IWorkspace = {})); var IWorkspaceFolder; (function (IWorkspaceFolder) { function isIWorkspaceFolder(thing) { return thing && typeof thing === 'object' && uri_1.URI.isUri(thing.uri) && typeof thing.name === 'string' && typeof thing.toResource === 'function'; } IWorkspaceFolder.isIWorkspaceFolder = isIWorkspaceFolder; })(IWorkspaceFolder = exports.IWorkspaceFolder || (exports.IWorkspaceFolder = {})); var Workspace = /** @class */ (function () { function Workspace(_id, folders, _configuration) { if (folders === void 0) { folders = []; } if (_configuration === void 0) { _configuration = null; } this._id = _id; this._configuration = _configuration; this._foldersMap = map_1.TernarySearchTree.forPaths(); this.folders = folders; } Object.defineProperty(Workspace.prototype, "folders", { get: function () { return this._folders; }, set: function (folders) { this._folders = folders; this.updateFoldersMap(); }, enumerable: true, configurable: true }); Object.defineProperty(Workspace.prototype, "id", { get: function () { return this._id; }, enumerable: true, configurable: true }); Object.defineProperty(Workspace.prototype, "configuration", { get: function () { return this._configuration; }, set: function (configuration) { this._configuration = configuration; }, enumerable: true, configurable: true }); Workspace.prototype.getFolder = function (resource) { if (!resource) { return null; } return this._foldersMap.findSubstr(resource.with({ scheme: resource.scheme, authority: resource.authority, path: resource.path }).toString()) || null; }; Workspace.prototype.updateFoldersMap = function () { this._foldersMap = map_1.TernarySearchTree.forPaths(); for (var _i = 0, _a = this.folders; _i < _a.length; _i++) { var folder = _a[_i]; this._foldersMap.set(folder.uri.toString(), folder); } }; Workspace.prototype.toJSON = function () { return { id: this.id, folders: this.folders, configuration: this.configuration }; }; return Workspace; }()); exports.Workspace = Workspace; var WorkspaceFolder = /** @class */ (function () { function WorkspaceFolder(data, raw) { this.raw = raw; this.uri = data.uri; this.index = data.index; this.name = data.name; } WorkspaceFolder.prototype.toResource = function (relativePath) { return resources.joinPath(this.uri, relativePath); }; WorkspaceFolder.prototype.toJSON = function () { return { uri: this.uri, name: this.name, index: this.index }; }; return WorkspaceFolder; }()); exports.WorkspaceFolder = WorkspaceFolder; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[172/*vs/editor/standalone/browser/simpleServices*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,6/*vs/base/browser/dom*/,56/*vs/base/browser/keyboardEvent*/,4/*vs/base/common/event*/,36/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,112/*vs/base/common/severity*/,25/*vs/base/common/uri*/,108/*vs/editor/browser/editorBrowser*/,163/*vs/editor/common/config/commonEditorConfig*/,58/*vs/editor/common/core/editOperation*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,17/*vs/editor/common/modes*/,29/*vs/platform/commands/common/commands*/,43/*vs/platform/configuration/common/configuration*/,518/*vs/platform/configuration/common/configurationModels*/,502/*vs/platform/keybinding/common/abstractKeybindingService*/,217/*vs/platform/keybinding/common/keybindingResolver*/,86/*vs/platform/keybinding/common/keybindingsRegistry*/,504/*vs/platform/keybinding/common/resolvedKeybindingItem*/,505/*vs/platform/keybinding/common/usLayoutResolvedKeybinding*/,35/*vs/platform/notification/common/notification*/,171/*vs/platform/workspace/common/workspace*/,59/*vs/editor/common/standaloneStrings*/]), function (require, exports, strings, dom, keyboardEvent_1, event_1, keyCodes_1, lifecycle_1, platform_1, severity_1, uri_1, editorBrowser_1, commonEditorConfig_1, editOperation_1, position_1, range_1, modes_1, commands_1, configuration_1, configurationModels_1, abstractKeybindingService_1, keybindingResolver_1, keybindingsRegistry_1, resolvedKeybindingItem_1, usLayoutResolvedKeybinding_1, notification_1, workspace_1, standaloneStrings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var SimpleModel = /** @class */ (function () { function SimpleModel(model) { this.model = model; this._onDispose = new event_1.Emitter(); } Object.defineProperty(SimpleModel.prototype, "textEditorModel", { get: function () { return this.model; }, enumerable: true, configurable: true }); SimpleModel.prototype.dispose = function () { this._onDispose.fire(); }; return SimpleModel; }()); exports.SimpleModel = SimpleModel; function withTypedEditor(widget, codeEditorCallback, diffEditorCallback) { if (editorBrowser_1.isCodeEditor(widget)) { // Single Editor return codeEditorCallback(widget); } else { // Diff Editor return diffEditorCallback(widget); } } var SimpleEditorModelResolverService = /** @class */ (function () { function SimpleEditorModelResolverService(modelService) { this.modelService = modelService; } SimpleEditorModelResolverService.prototype.setEditor = function (editor) { this.editor = editor; }; SimpleEditorModelResolverService.prototype.createModelReference = function (resource) { var _this = this; var model = null; if (this.editor) { model = withTypedEditor(this.editor, function (editor) { return _this.findModel(editor, resource); }, function (diffEditor) { return _this.findModel(diffEditor.getOriginalEditor(), resource) || _this.findModel(diffEditor.getModifiedEditor(), resource); }); } if (!model) { return Promise.reject(new Error("Model not found")); } return Promise.resolve(new lifecycle_1.ImmortalReference(new SimpleModel(model))); }; SimpleEditorModelResolverService.prototype.findModel = function (editor, resource) { var model = this.modelService ? this.modelService.getModel(resource) : editor.getModel(); if (model && model.uri.toString() !== resource.toString()) { return null; } return model; }; return SimpleEditorModelResolverService; }()); exports.SimpleEditorModelResolverService = SimpleEditorModelResolverService; var SimpleEditorProgressService = /** @class */ (function () { function SimpleEditorProgressService() { } SimpleEditorProgressService.prototype.show = function () { return SimpleEditorProgressService.NULL_PROGRESS_RUNNER; }; SimpleEditorProgressService.prototype.showWhile = function (promise, delay) { return Promise.resolve(undefined); }; SimpleEditorProgressService.NULL_PROGRESS_RUNNER = { done: function () { }, total: function () { }, worked: function () { } }; return SimpleEditorProgressService; }()); exports.SimpleEditorProgressService = SimpleEditorProgressService; var SimpleDialogService = /** @class */ (function () { function SimpleDialogService() { } return SimpleDialogService; }()); exports.SimpleDialogService = SimpleDialogService; var SimpleNotificationService = /** @class */ (function () { function SimpleNotificationService() { } SimpleNotificationService.prototype.info = function (message) { return this.notify({ severity: severity_1.default.Info, message: message }); }; SimpleNotificationService.prototype.warn = function (message) { return this.notify({ severity: severity_1.default.Warning, message: message }); }; SimpleNotificationService.prototype.error = function (error) { return this.notify({ severity: severity_1.default.Error, message: error }); }; SimpleNotificationService.prototype.notify = function (notification) { switch (notification.severity) { case severity_1.default.Error: console.error(notification.message); break; case severity_1.default.Warning: console.warn(notification.message); break; default: console.log(notification.message); break; } return SimpleNotificationService.NO_OP; }; SimpleNotificationService.prototype.status = function (message, options) { return lifecycle_1.Disposable.None; }; SimpleNotificationService.NO_OP = new notification_1.NoOpNotification(); return SimpleNotificationService; }()); exports.SimpleNotificationService = SimpleNotificationService; var StandaloneCommandService = /** @class */ (function () { function StandaloneCommandService(instantiationService) { this._onWillExecuteCommand = new event_1.Emitter(); this._onDidExecuteCommand = new event_1.Emitter(); this._instantiationService = instantiationService; this._dynamicCommands = Object.create(null); } StandaloneCommandService.prototype.addCommand = function (command) { var _this = this; var id = command.id; this._dynamicCommands[id] = command; return lifecycle_1.toDisposable(function () { delete _this._dynamicCommands[id]; }); }; StandaloneCommandService.prototype.executeCommand = function (id) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var command = (commands_1.CommandsRegistry.getCommand(id) || this._dynamicCommands[id]); if (!command) { return Promise.reject(new Error("command '" + id + "' not found")); } try { this._onWillExecuteCommand.fire({ commandId: id, args: args }); var result = this._instantiationService.invokeFunction.apply(this._instantiationService, __spreadArrays([command.handler], args)); this._onDidExecuteCommand.fire({ commandId: id, args: args }); return Promise.resolve(result); } catch (err) { return Promise.reject(err); } }; return StandaloneCommandService; }()); exports.StandaloneCommandService = StandaloneCommandService; var StandaloneKeybindingService = /** @class */ (function (_super) { __extends(StandaloneKeybindingService, _super); function StandaloneKeybindingService(contextKeyService, commandService, telemetryService, notificationService, domNode) { var _this = _super.call(this, contextKeyService, commandService, telemetryService, notificationService) || this; _this._cachedResolver = null; _this._dynamicKeybindings = []; _this._register(dom.addDisposableListener(domNode, dom.EventType.KEY_DOWN, function (e) { var keyEvent = new keyboardEvent_1.StandardKeyboardEvent(e); var shouldPreventDefault = _this._dispatch(keyEvent, keyEvent.target); if (shouldPreventDefault) { keyEvent.preventDefault(); keyEvent.stopPropagation(); } })); return _this; } StandaloneKeybindingService.prototype.addDynamicKeybinding = function (commandId, _keybinding, handler, when) { var _this = this; var keybinding = keyCodes_1.createKeybinding(_keybinding, platform_1.OS); var toDispose = new lifecycle_1.DisposableStore(); if (keybinding) { this._dynamicKeybindings.push({ keybinding: keybinding, command: commandId, when: when, weight1: 1000, weight2: 0 }); toDispose.add(lifecycle_1.toDisposable(function () { for (var i = 0; i < _this._dynamicKeybindings.length; i++) { var kb = _this._dynamicKeybindings[i]; if (kb.command === commandId) { _this._dynamicKeybindings.splice(i, 1); _this.updateResolver({ source: 1 /* Default */ }); return; } } })); } var commandService = this._commandService; if (commandService instanceof StandaloneCommandService) { toDispose.add(commandService.addCommand({ id: commandId, handler: handler })); } else { throw new Error('Unknown command service!'); } this.updateResolver({ source: 1 /* Default */ }); return toDispose; }; StandaloneKeybindingService.prototype.updateResolver = function (event) { this._cachedResolver = null; this._onDidUpdateKeybindings.fire(event); }; StandaloneKeybindingService.prototype._getResolver = function () { if (!this._cachedResolver) { var defaults = this._toNormalizedKeybindingItems(keybindingsRegistry_1.KeybindingsRegistry.getDefaultKeybindings(), true); var overrides = this._toNormalizedKeybindingItems(this._dynamicKeybindings, false); this._cachedResolver = new keybindingResolver_1.KeybindingResolver(defaults, overrides); } return this._cachedResolver; }; StandaloneKeybindingService.prototype._documentHasFocus = function () { return document.hasFocus(); }; StandaloneKeybindingService.prototype._toNormalizedKeybindingItems = function (items, isDefault) { var result = [], resultLen = 0; for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { var item = items_1[_i]; var when = item.when || undefined; var keybinding = item.keybinding; if (!keybinding) { // This might be a removal keybinding item in user settings => accept it result[resultLen++] = new resolvedKeybindingItem_1.ResolvedKeybindingItem(undefined, item.command, item.commandArgs, when, isDefault); } else { var resolvedKeybindings = this.resolveKeybinding(keybinding); for (var _a = 0, resolvedKeybindings_1 = resolvedKeybindings; _a < resolvedKeybindings_1.length; _a++) { var resolvedKeybinding = resolvedKeybindings_1[_a]; result[resultLen++] = new resolvedKeybindingItem_1.ResolvedKeybindingItem(resolvedKeybinding, item.command, item.commandArgs, when, isDefault); } } } return result; }; StandaloneKeybindingService.prototype.resolveKeybinding = function (keybinding) { return [new usLayoutResolvedKeybinding_1.USLayoutResolvedKeybinding(keybinding, platform_1.OS)]; }; StandaloneKeybindingService.prototype.resolveKeyboardEvent = function (keyboardEvent) { var keybinding = new keyCodes_1.SimpleKeybinding(keyboardEvent.ctrlKey, keyboardEvent.shiftKey, keyboardEvent.altKey, keyboardEvent.metaKey, keyboardEvent.keyCode).toChord(); return new usLayoutResolvedKeybinding_1.USLayoutResolvedKeybinding(keybinding, platform_1.OS); }; return StandaloneKeybindingService; }(abstractKeybindingService_1.AbstractKeybindingService)); exports.StandaloneKeybindingService = StandaloneKeybindingService; function isConfigurationOverrides(thing) { return thing && typeof thing === 'object' && (!thing.overrideIdentifier || typeof thing.overrideIdentifier === 'string') && (!thing.resource || thing.resource instanceof uri_1.URI); } var SimpleConfigurationService = /** @class */ (function () { function SimpleConfigurationService() { this._onDidChangeConfiguration = new event_1.Emitter(); this.onDidChangeConfiguration = this._onDidChangeConfiguration.event; this._configuration = new configurationModels_1.Configuration(new configurationModels_1.DefaultConfigurationModel(), new configurationModels_1.ConfigurationModel()); } SimpleConfigurationService.prototype.configuration = function () { return this._configuration; }; SimpleConfigurationService.prototype.getValue = function (arg1, arg2) { var section = typeof arg1 === 'string' ? arg1 : undefined; var overrides = isConfigurationOverrides(arg1) ? arg1 : isConfigurationOverrides(arg2) ? arg2 : {}; return this.configuration().getValue(section, overrides, undefined); }; SimpleConfigurationService.prototype.updateValue = function (key, value, arg3, arg4) { this.configuration().updateValue(key, value); return Promise.resolve(); }; SimpleConfigurationService.prototype.inspect = function (key, options) { if (options === void 0) { options = {}; } return this.configuration().inspect(key, options, undefined); }; return SimpleConfigurationService; }()); exports.SimpleConfigurationService = SimpleConfigurationService; var SimpleResourceConfigurationService = /** @class */ (function () { function SimpleResourceConfigurationService(configurationService) { var _this = this; this.configurationService = configurationService; this._onDidChangeConfiguration = new event_1.Emitter(); this.configurationService.onDidChangeConfiguration(function (e) { _this._onDidChangeConfiguration.fire({ affectedKeys: e.affectedKeys, affectsConfiguration: function (resource, configuration) { return e.affectsConfiguration(configuration); } }); }); } SimpleResourceConfigurationService.prototype.getValue = function (resource, arg2, arg3) { var position = position_1.Position.isIPosition(arg2) ? arg2 : null; var section = position ? (typeof arg3 === 'string' ? arg3 : undefined) : (typeof arg2 === 'string' ? arg2 : undefined); if (typeof section === 'undefined') { return this.configurationService.getValue(); } return this.configurationService.getValue(section); }; return SimpleResourceConfigurationService; }()); exports.SimpleResourceConfigurationService = SimpleResourceConfigurationService; var SimpleResourcePropertiesService = /** @class */ (function () { function SimpleResourcePropertiesService(configurationService) { this.configurationService = configurationService; } SimpleResourcePropertiesService.prototype.getEOL = function (resource, language) { var eol = this.configurationService.getValue('files.eol', { overrideIdentifier: language, resource: resource }); if (eol && eol !== 'auto') { return eol; } return (platform_1.isLinux || platform_1.isMacintosh) ? '\n' : '\r\n'; }; SimpleResourcePropertiesService = __decorate([ __param(0, configuration_1.IConfigurationService) ], SimpleResourcePropertiesService); return SimpleResourcePropertiesService; }()); exports.SimpleResourcePropertiesService = SimpleResourcePropertiesService; var StandaloneTelemetryService = /** @class */ (function () { function StandaloneTelemetryService() { } StandaloneTelemetryService.prototype.publicLog = function (eventName, data) { return Promise.resolve(undefined); }; StandaloneTelemetryService.prototype.publicLog2 = function (eventName, data) { return this.publicLog(eventName, data); }; return StandaloneTelemetryService; }()); exports.StandaloneTelemetryService = StandaloneTelemetryService; var SimpleWorkspaceContextService = /** @class */ (function () { function SimpleWorkspaceContextService() { var resource = uri_1.URI.from({ scheme: SimpleWorkspaceContextService.SCHEME, authority: 'model', path: '/' }); this.workspace = { id: '4064f6ec-cb38-4ad0-af64-ee6467e63c82', folders: [new workspace_1.WorkspaceFolder({ uri: resource, name: '', index: 0 })] }; } SimpleWorkspaceContextService.prototype.getWorkspace = function () { return this.workspace; }; SimpleWorkspaceContextService.prototype.getWorkspaceFolder = function (resource) { return resource && resource.scheme === SimpleWorkspaceContextService.SCHEME ? this.workspace.folders[0] : null; }; SimpleWorkspaceContextService.SCHEME = 'inmemory'; return SimpleWorkspaceContextService; }()); exports.SimpleWorkspaceContextService = SimpleWorkspaceContextService; function applyConfigurationValues(configurationService, source, isDiffEditor) { if (!source) { return; } if (!(configurationService instanceof SimpleConfigurationService)) { return; } Object.keys(source).forEach(function (key) { if (commonEditorConfig_1.isEditorConfigurationKey(key)) { configurationService.updateValue("editor." + key, source[key]); } if (isDiffEditor && commonEditorConfig_1.isDiffEditorConfigurationKey(key)) { configurationService.updateValue("diffEditor." + key, source[key]); } }); } exports.applyConfigurationValues = applyConfigurationValues; var SimpleBulkEditService = /** @class */ (function () { function SimpleBulkEditService(_modelService) { this._modelService = _modelService; // } SimpleBulkEditService.prototype.hasPreviewHandler = function () { return false; }; SimpleBulkEditService.prototype.apply = function (workspaceEdit, options) { var edits = new Map(); if (workspaceEdit.edits) { for (var _i = 0, _a = workspaceEdit.edits; _i < _a.length; _i++) { var edit = _a[_i]; if (!modes_1.WorkspaceTextEdit.is(edit)) { return Promise.reject(new Error('bad edit - only text edits are supported')); } var model = this._modelService.getModel(edit.resource); if (!model) { return Promise.reject(new Error('bad edit - model not found')); } var array = edits.get(model); if (!array) { array = []; edits.set(model, array); } array.push(edit.edit); } } var totalEdits = 0; var totalFiles = 0; edits.forEach(function (edits, model) { model.pushStackElement(); model.pushEditOperations([], edits.map(function (e) { return editOperation_1.EditOperation.replaceMove(range_1.Range.lift(e.range), e.text); }), function () { return []; }); model.pushStackElement(); totalFiles += 1; totalEdits += edits.length; }); return Promise.resolve({ selection: undefined, ariaSummary: strings.format(standaloneStrings_1.SimpleServicesNLS.bulkEditServiceSummary, totalEdits, totalFiles) }); }; return SimpleBulkEditService; }()); exports.SimpleBulkEditService = SimpleBulkEditService; var SimpleUriLabelService = /** @class */ (function () { function SimpleUriLabelService() { } SimpleUriLabelService.prototype.getUriLabel = function (resource, options) { if (resource.scheme === 'file') { return resource.fsPath; } return resource.path; }; return SimpleUriLabelService; }()); exports.SimpleUriLabelService = SimpleUriLabelService; var SimpleLayoutService = /** @class */ (function () { function SimpleLayoutService(_container) { this._container = _container; this.onLayout = event_1.Event.None; } Object.defineProperty(SimpleLayoutService.prototype, "container", { get: function () { return this._container; }, enumerable: true, configurable: true }); return SimpleLayoutService; }()); exports.SimpleLayoutService = SimpleLayoutService; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[602/*vs/editor/standalone/browser/standaloneCodeEditor*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,50/*vs/base/browser/ui/aria/aria*/,2/*vs/base/common/lifecycle*/,32/*vs/editor/browser/services/codeEditorService*/,121/*vs/editor/browser/widget/codeEditorWidget*/,230/*vs/editor/browser/widget/diffEditorWidget*/,190/*vs/editor/common/editorAction*/,62/*vs/editor/common/services/editorWorkerService*/,172/*vs/editor/standalone/browser/simpleServices*/,94/*vs/editor/standalone/common/standaloneThemeService*/,65/*vs/platform/actions/common/actions*/,29/*vs/platform/commands/common/commands*/,43/*vs/platform/configuration/common/configuration*/,18/*vs/platform/contextkey/common/contextkey*/,66/*vs/platform/contextview/browser/contextView*/,11/*vs/platform/instantiation/common/instantiation*/,34/*vs/platform/keybinding/common/keybinding*/,35/*vs/platform/notification/common/notification*/,14/*vs/platform/theme/common/themeService*/,64/*vs/platform/accessibility/common/accessibility*/,59/*vs/editor/common/standaloneStrings*/,162/*vs/platform/clipboard/common/clipboardService*/,73/*vs/platform/progress/common/progress*/]), function (require, exports, browser, aria, lifecycle_1, codeEditorService_1, codeEditorWidget_1, diffEditorWidget_1, editorAction_1, editorWorkerService_1, simpleServices_1, standaloneThemeService_1, actions_1, commands_1, configuration_1, contextkey_1, contextView_1, instantiation_1, keybinding_1, notification_1, themeService_1, accessibility_1, standaloneStrings_1, clipboardService_1, progress_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LAST_GENERATED_COMMAND_ID = 0; var ariaDomNodeCreated = false; function createAriaDomNode() { if (ariaDomNodeCreated) { return; } ariaDomNodeCreated = true; aria.setARIAContainer(document.body); } /** * A code editor to be used both by the standalone editor and the standalone diff editor. */ var StandaloneCodeEditor = /** @class */ (function (_super) { __extends(StandaloneCodeEditor, _super); function StandaloneCodeEditor(domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, themeService, notificationService, accessibilityService) { var _this = this; options = options || {}; options.ariaLabel = options.ariaLabel || standaloneStrings_1.StandaloneCodeEditorNLS.editorViewAccessibleLabel; options.ariaLabel = options.ariaLabel + ';' + (browser.isIE ? standaloneStrings_1.StandaloneCodeEditorNLS.accessibilityHelpMessageIE : standaloneStrings_1.StandaloneCodeEditorNLS.accessibilityHelpMessage); _this = _super.call(this, domElement, options, {}, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService) || this; if (keybindingService instanceof simpleServices_1.StandaloneKeybindingService) { _this._standaloneKeybindingService = keybindingService; } else { _this._standaloneKeybindingService = null; } // Create the ARIA dom node as soon as the first editor is instantiated createAriaDomNode(); return _this; } StandaloneCodeEditor.prototype.addCommand = function (keybinding, handler, context) { if (!this._standaloneKeybindingService) { console.warn('Cannot add command because the editor is configured with an unrecognized KeybindingService'); return null; } var commandId = 'DYNAMIC_' + (++LAST_GENERATED_COMMAND_ID); var whenExpression = contextkey_1.ContextKeyExpr.deserialize(context); this._standaloneKeybindingService.addDynamicKeybinding(commandId, keybinding, handler, whenExpression); return commandId; }; StandaloneCodeEditor.prototype.createContextKey = function (key, defaultValue) { return this._contextKeyService.createKey(key, defaultValue); }; StandaloneCodeEditor.prototype.addAction = function (_descriptor) { var _this = this; if ((typeof _descriptor.id !== 'string') || (typeof _descriptor.label !== 'string') || (typeof _descriptor.run !== 'function')) { throw new Error('Invalid action descriptor, `id`, `label` and `run` are required properties!'); } if (!this._standaloneKeybindingService) { console.warn('Cannot add keybinding because the editor is configured with an unrecognized KeybindingService'); return lifecycle_1.Disposable.None; } // Read descriptor options var id = _descriptor.id; var label = _descriptor.label; var precondition = contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.equals('editorId', this.getId()), contextkey_1.ContextKeyExpr.deserialize(_descriptor.precondition)); var keybindings = _descriptor.keybindings; var keybindingsWhen = contextkey_1.ContextKeyExpr.and(precondition, contextkey_1.ContextKeyExpr.deserialize(_descriptor.keybindingContext)); var contextMenuGroupId = _descriptor.contextMenuGroupId || null; var contextMenuOrder = _descriptor.contextMenuOrder || 0; var run = function (accessor) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } return Promise.resolve(_descriptor.run.apply(_descriptor, __spreadArrays([_this], args))); }; var toDispose = new lifecycle_1.DisposableStore(); // Generate a unique id to allow the same descriptor.id across multiple editor instances var uniqueId = this.getId() + ':' + id; // Register the command toDispose.add(commands_1.CommandsRegistry.registerCommand(uniqueId, run)); // Register the context menu item if (contextMenuGroupId) { var menuItem = { command: { id: uniqueId, title: label }, when: precondition, group: contextMenuGroupId, order: contextMenuOrder }; toDispose.add(actions_1.MenuRegistry.appendMenuItem(7 /* EditorContext */, menuItem)); } // Register the keybindings if (Array.isArray(keybindings)) { for (var _i = 0, keybindings_1 = keybindings; _i < keybindings_1.length; _i++) { var kb = keybindings_1[_i]; toDispose.add(this._standaloneKeybindingService.addDynamicKeybinding(uniqueId, kb, run, keybindingsWhen)); } } // Finally, register an internal editor action var internalAction = new editorAction_1.InternalEditorAction(uniqueId, label, label, precondition, run, this._contextKeyService); // Store it under the original id, such that trigger with the original id will work this._actions[id] = internalAction; toDispose.add(lifecycle_1.toDisposable(function () { delete _this._actions[id]; })); return toDispose; }; StandaloneCodeEditor = __decorate([ __param(2, instantiation_1.IInstantiationService), __param(3, codeEditorService_1.ICodeEditorService), __param(4, commands_1.ICommandService), __param(5, contextkey_1.IContextKeyService), __param(6, keybinding_1.IKeybindingService), __param(7, themeService_1.IThemeService), __param(8, notification_1.INotificationService), __param(9, accessibility_1.IAccessibilityService) ], StandaloneCodeEditor); return StandaloneCodeEditor; }(codeEditorWidget_1.CodeEditorWidget)); exports.StandaloneCodeEditor = StandaloneCodeEditor; var StandaloneEditor = /** @class */ (function (_super) { __extends(StandaloneEditor, _super); function StandaloneEditor(domElement, options, toDispose, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, contextViewService, themeService, notificationService, configurationService, accessibilityService) { var _this = this; simpleServices_1.applyConfigurationValues(configurationService, options, false); var themeDomRegistration = themeService.registerEditorContainer(domElement); options = options || {}; if (typeof options.theme === 'string') { themeService.setTheme(options.theme); } var _model = options.model; delete options.model; _this = _super.call(this, domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, themeService, notificationService, accessibilityService) || this; _this._contextViewService = contextViewService; _this._configurationService = configurationService; _this._register(toDispose); _this._register(themeDomRegistration); var model; if (typeof _model === 'undefined') { model = self.monaco.editor.createModel(options.value || '', options.language || 'text/plain'); _this._ownsModel = true; } else { model = _model; _this._ownsModel = false; } _this._attachModel(model); if (model) { var e = { oldModelUrl: null, newModelUrl: model.uri }; _this._onDidChangeModel.fire(e); } return _this; } StandaloneEditor.prototype.dispose = function () { _super.prototype.dispose.call(this); }; StandaloneEditor.prototype.updateOptions = function (newOptions) { simpleServices_1.applyConfigurationValues(this._configurationService, newOptions, false); _super.prototype.updateOptions.call(this, newOptions); }; StandaloneEditor.prototype._attachModel = function (model) { _super.prototype._attachModel.call(this, model); if (this._modelData) { this._contextViewService.setContainer(this._modelData.view.domNode.domNode); } }; StandaloneEditor.prototype._postDetachModelCleanup = function (detachedModel) { _super.prototype._postDetachModelCleanup.call(this, detachedModel); if (detachedModel && this._ownsModel) { detachedModel.dispose(); this._ownsModel = false; } }; StandaloneEditor = __decorate([ __param(3, instantiation_1.IInstantiationService), __param(4, codeEditorService_1.ICodeEditorService), __param(5, commands_1.ICommandService), __param(6, contextkey_1.IContextKeyService), __param(7, keybinding_1.IKeybindingService), __param(8, contextView_1.IContextViewService), __param(9, standaloneThemeService_1.IStandaloneThemeService), __param(10, notification_1.INotificationService), __param(11, configuration_1.IConfigurationService), __param(12, accessibility_1.IAccessibilityService) ], StandaloneEditor); return StandaloneEditor; }(StandaloneCodeEditor)); exports.StandaloneEditor = StandaloneEditor; var StandaloneDiffEditor = /** @class */ (function (_super) { __extends(StandaloneDiffEditor, _super); function StandaloneDiffEditor(domElement, options, toDispose, instantiationService, contextKeyService, keybindingService, contextViewService, editorWorkerService, codeEditorService, themeService, notificationService, configurationService, contextMenuService, editorProgressService, clipboardService) { var _this = this; simpleServices_1.applyConfigurationValues(configurationService, options, true); var themeDomRegistration = themeService.registerEditorContainer(domElement); options = options || {}; if (typeof options.theme === 'string') { options.theme = themeService.setTheme(options.theme); } _this = _super.call(this, domElement, options, clipboardService, editorWorkerService, contextKeyService, instantiationService, codeEditorService, themeService, notificationService, contextMenuService, editorProgressService) || this; _this._contextViewService = contextViewService; _this._configurationService = configurationService; _this._register(toDispose); _this._register(themeDomRegistration); _this._contextViewService.setContainer(_this._containerDomElement); return _this; } StandaloneDiffEditor.prototype.dispose = function () { _super.prototype.dispose.call(this); }; StandaloneDiffEditor.prototype.updateOptions = function (newOptions) { simpleServices_1.applyConfigurationValues(this._configurationService, newOptions, true); _super.prototype.updateOptions.call(this, newOptions); }; StandaloneDiffEditor.prototype._createInnerEditor = function (instantiationService, container, options) { return instantiationService.createInstance(StandaloneCodeEditor, container, options); }; StandaloneDiffEditor.prototype.getOriginalEditor = function () { return _super.prototype.getOriginalEditor.call(this); }; StandaloneDiffEditor.prototype.getModifiedEditor = function () { return _super.prototype.getModifiedEditor.call(this); }; StandaloneDiffEditor.prototype.addCommand = function (keybinding, handler, context) { return this.getModifiedEditor().addCommand(keybinding, handler, context); }; StandaloneDiffEditor.prototype.createContextKey = function (key, defaultValue) { return this.getModifiedEditor().createContextKey(key, defaultValue); }; StandaloneDiffEditor.prototype.addAction = function (descriptor) { return this.getModifiedEditor().addAction(descriptor); }; StandaloneDiffEditor = __decorate([ __param(3, instantiation_1.IInstantiationService), __param(4, contextkey_1.IContextKeyService), __param(5, keybinding_1.IKeybindingService), __param(6, contextView_1.IContextViewService), __param(7, editorWorkerService_1.IEditorWorkerService), __param(8, codeEditorService_1.ICodeEditorService), __param(9, standaloneThemeService_1.IStandaloneThemeService), __param(10, notification_1.INotificationService), __param(11, configuration_1.IConfigurationService), __param(12, contextView_1.IContextMenuService), __param(13, progress_1.IEditorProgressService), __param(14, instantiation_1.optional(clipboardService_1.IClipboardService)) ], StandaloneDiffEditor); return StandaloneDiffEditor; }(diffEditorWidget_1.DiffEditorWidget)); exports.StandaloneDiffEditor = StandaloneDiffEditor; }); /*--------------------------------------------------------------------------------------------- * 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/standalone/browser/standaloneServices*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,156/*vs/editor/browser/services/bulkEditService*/,32/*vs/editor/browser/services/codeEditorService*/,62/*vs/editor/common/services/editorWorkerService*/,219/*vs/editor/common/services/editorWorkerServiceImpl*/,71/*vs/editor/common/services/modeService*/,516/*vs/editor/common/services/modeServiceImpl*/,49/*vs/editor/common/services/modelService*/,556/*vs/editor/common/services/modelServiceImpl*/,114/*vs/editor/common/services/textResourceConfigurationService*/,172/*vs/editor/standalone/browser/simpleServices*/,592/*vs/editor/standalone/browser/standaloneCodeServiceImpl*/,594/*vs/editor/standalone/browser/standaloneThemeServiceImpl*/,94/*vs/editor/standalone/common/standaloneThemeService*/,65/*vs/platform/actions/common/actions*/,29/*vs/platform/commands/common/commands*/,43/*vs/platform/configuration/common/configuration*/,519/*vs/platform/contextkey/browser/contextKeyService*/,18/*vs/platform/contextkey/common/contextkey*/,595/*vs/platform/contextview/browser/contextMenuService*/,66/*vs/platform/contextview/browser/contextView*/,506/*vs/platform/contextview/browser/contextViewService*/,500/*vs/platform/dialogs/common/dialogs*/,11/*vs/platform/instantiation/common/instantiation*/,501/*vs/platform/instantiation/common/instantiationService*/,115/*vs/platform/instantiation/common/serviceCollection*/,34/*vs/platform/keybinding/common/keybinding*/,116/*vs/platform/label/common/label*/,170/*vs/platform/list/browser/listService*/,95/*vs/platform/log/common/log*/,508/*vs/platform/markers/common/markerService*/,72/*vs/platform/markers/common/markers*/,35/*vs/platform/notification/common/notification*/,73/*vs/platform/progress/common/progress*/,74/*vs/platform/storage/common/storage*/,96/*vs/platform/telemetry/common/telemetry*/,14/*vs/platform/theme/common/themeService*/,171/*vs/platform/workspace/common/workspace*/,499/*vs/platform/actions/common/menuService*/,210/*vs/editor/common/services/markersDecorationService*/,565/*vs/editor/common/services/markerDecorationsServiceImpl*/,64/*vs/platform/accessibility/common/accessibility*/,218/*vs/platform/layout/browser/layoutService*/,83/*vs/platform/instantiation/common/extensions*/,517/*vs/platform/accessibility/common/accessibilityService*/]), function (require, exports, lifecycle_1, bulkEditService_1, codeEditorService_1, editorWorkerService_1, editorWorkerServiceImpl_1, modeService_1, modeServiceImpl_1, modelService_1, modelServiceImpl_1, textResourceConfigurationService_1, simpleServices_1, standaloneCodeServiceImpl_1, standaloneThemeServiceImpl_1, standaloneThemeService_1, actions_1, commands_1, configuration_1, contextKeyService_1, contextkey_1, contextMenuService_1, contextView_1, contextViewService_1, dialogs_1, instantiation_1, instantiationService_1, serviceCollection_1, keybinding_1, label_1, listService_1, log_1, markerService_1, markers_1, notification_1, progress_1, storage_1, telemetry_1, themeService_1, workspace_1, menuService_1, markersDecorationService_1, markerDecorationsServiceImpl_1, accessibility_1, layoutService_1, extensions_1, accessibilityService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var StaticServices; (function (StaticServices) { var _serviceCollection = new serviceCollection_1.ServiceCollection(); var LazyStaticService = /** @class */ (function () { function LazyStaticService(serviceId, factory) { this._serviceId = serviceId; this._factory = factory; this._value = null; } Object.defineProperty(LazyStaticService.prototype, "id", { get: function () { return this._serviceId; }, enumerable: true, configurable: true }); LazyStaticService.prototype.get = function (overrides) { if (!this._value) { if (overrides) { this._value = overrides[this._serviceId.toString()]; } if (!this._value) { this._value = this._factory(overrides); } if (!this._value) { throw new Error('Service ' + this._serviceId + ' is missing!'); } _serviceCollection.set(this._serviceId, this._value); } return this._value; }; return LazyStaticService; }()); StaticServices.LazyStaticService = LazyStaticService; var _all = []; function define(serviceId, factory) { var r = new LazyStaticService(serviceId, factory); _all.push(r); return r; } function init(overrides) { // Create a fresh service collection var result = new serviceCollection_1.ServiceCollection(); // make sure to add all services that use `registerSingleton` for (var _i = 0, _a = extensions_1.getSingletonServiceDescriptors(); _i < _a.length; _i++) { var _b = _a[_i], id = _b[0], descriptor = _b[1]; result.set(id, descriptor); } // Initialize the service collection with the overrides for (var serviceId in overrides) { if (overrides.hasOwnProperty(serviceId)) { result.set(instantiation_1.createDecorator(serviceId), overrides[serviceId]); } } // Make sure the same static services are present in all service collections _all.forEach(function (service) { return result.set(service.id, service.get(overrides)); }); // Ensure the collection gets the correct instantiation service var instantiationService = new instantiationService_1.InstantiationService(result, true); result.set(instantiation_1.IInstantiationService, instantiationService); return [result, instantiationService]; } StaticServices.init = init; StaticServices.instantiationService = define(instantiation_1.IInstantiationService, function () { return new instantiationService_1.InstantiationService(_serviceCollection, true); }); var configurationServiceImpl = new simpleServices_1.SimpleConfigurationService(); StaticServices.configurationService = define(configuration_1.IConfigurationService, function () { return configurationServiceImpl; }); StaticServices.resourceConfigurationService = define(textResourceConfigurationService_1.ITextResourceConfigurationService, function () { return new simpleServices_1.SimpleResourceConfigurationService(configurationServiceImpl); }); StaticServices.resourcePropertiesService = define(textResourceConfigurationService_1.ITextResourcePropertiesService, function () { return new simpleServices_1.SimpleResourcePropertiesService(configurationServiceImpl); }); StaticServices.contextService = define(workspace_1.IWorkspaceContextService, function () { return new simpleServices_1.SimpleWorkspaceContextService(); }); StaticServices.labelService = define(label_1.ILabelService, function () { return new simpleServices_1.SimpleUriLabelService(); }); StaticServices.telemetryService = define(telemetry_1.ITelemetryService, function () { return new simpleServices_1.StandaloneTelemetryService(); }); StaticServices.dialogService = define(dialogs_1.IDialogService, function () { return new simpleServices_1.SimpleDialogService(); }); StaticServices.notificationService = define(notification_1.INotificationService, function () { return new simpleServices_1.SimpleNotificationService(); }); StaticServices.markerService = define(markers_1.IMarkerService, function () { return new markerService_1.MarkerService(); }); StaticServices.modeService = define(modeService_1.IModeService, function (o) { return new modeServiceImpl_1.ModeServiceImpl(); }); StaticServices.standaloneThemeService = define(standaloneThemeService_1.IStandaloneThemeService, function () { return new standaloneThemeServiceImpl_1.StandaloneThemeServiceImpl(); }); StaticServices.logService = define(log_1.ILogService, function () { return new log_1.NullLogService(); }); StaticServices.modelService = define(modelService_1.IModelService, function (o) { return new modelServiceImpl_1.ModelServiceImpl(StaticServices.configurationService.get(o), StaticServices.resourcePropertiesService.get(o), StaticServices.standaloneThemeService.get(o), StaticServices.logService.get(o)); }); StaticServices.markerDecorationsService = define(markersDecorationService_1.IMarkerDecorationsService, function (o) { return new markerDecorationsServiceImpl_1.MarkerDecorationsService(StaticServices.modelService.get(o), StaticServices.markerService.get(o)); }); StaticServices.codeEditorService = define(codeEditorService_1.ICodeEditorService, function (o) { return new standaloneCodeServiceImpl_1.StandaloneCodeEditorServiceImpl(StaticServices.standaloneThemeService.get(o)); }); StaticServices.editorProgressService = define(progress_1.IEditorProgressService, function () { return new simpleServices_1.SimpleEditorProgressService(); }); StaticServices.storageService = define(storage_1.IStorageService, function () { return new storage_1.InMemoryStorageService(); }); StaticServices.editorWorkerService = define(editorWorkerService_1.IEditorWorkerService, function (o) { return new editorWorkerServiceImpl_1.EditorWorkerServiceImpl(StaticServices.modelService.get(o), StaticServices.resourceConfigurationService.get(o), StaticServices.logService.get(o)); }); })(StaticServices = exports.StaticServices || (exports.StaticServices = {})); var DynamicStandaloneServices = /** @class */ (function (_super) { __extends(DynamicStandaloneServices, _super); function DynamicStandaloneServices(domElement, overrides) { var _this = _super.call(this) || this; var _a = StaticServices.init(overrides), _serviceCollection = _a[0], _instantiationService = _a[1]; _this._serviceCollection = _serviceCollection; _this._instantiationService = _instantiationService; var configurationService = _this.get(configuration_1.IConfigurationService); var notificationService = _this.get(notification_1.INotificationService); var telemetryService = _this.get(telemetry_1.ITelemetryService); var themeService = _this.get(themeService_1.IThemeService); var ensure = function (serviceId, factory) { var value = null; if (overrides) { value = overrides[serviceId.toString()]; } if (!value) { value = factory(); } _this._serviceCollection.set(serviceId, value); return value; }; var contextKeyService = ensure(contextkey_1.IContextKeyService, function () { return _this._register(new contextKeyService_1.ContextKeyService(configurationService)); }); ensure(accessibility_1.IAccessibilityService, function () { return new accessibilityService_1.AccessibilityService(contextKeyService, configurationService); }); ensure(listService_1.IListService, function () { return new listService_1.ListService(themeService); }); var commandService = ensure(commands_1.ICommandService, function () { return new simpleServices_1.StandaloneCommandService(_this._instantiationService); }); var keybindingService = ensure(keybinding_1.IKeybindingService, function () { return _this._register(new simpleServices_1.StandaloneKeybindingService(contextKeyService, commandService, telemetryService, notificationService, domElement)); }); var layoutService = ensure(layoutService_1.ILayoutService, function () { return new simpleServices_1.SimpleLayoutService(domElement); }); var contextViewService = ensure(contextView_1.IContextViewService, function () { return _this._register(new contextViewService_1.ContextViewService(layoutService)); }); ensure(contextView_1.IContextMenuService, function () { var contextMenuService = new contextMenuService_1.ContextMenuService(telemetryService, notificationService, contextViewService, keybindingService, themeService); contextMenuService.configure({ blockMouse: false }); // we do not want that in the standalone editor return _this._register(contextMenuService); }); ensure(actions_1.IMenuService, function () { return new menuService_1.MenuService(commandService); }); ensure(bulkEditService_1.IBulkEditService, function () { return new simpleServices_1.SimpleBulkEditService(StaticServices.modelService.get(modelService_1.IModelService)); }); return _this; } DynamicStandaloneServices.prototype.get = function (serviceId) { var r = this._serviceCollection.get(serviceId); if (!r) { throw new Error('Missing service ' + serviceId); } return r; }; DynamicStandaloneServices.prototype.set = function (serviceId, instance) { this._serviceCollection.set(serviceId, instance); }; DynamicStandaloneServices.prototype.has = function (serviceId) { return this._serviceCollection.has(serviceId); }; return DynamicStandaloneServices; }(lifecycle_1.Disposable)); exports.DynamicStandaloneServices = DynamicStandaloneServices; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[603/*vs/editor/standalone/browser/standaloneEditor*/], __M([0/*require*/,1/*exports*/,32/*vs/editor/browser/services/codeEditorService*/,509/*vs/editor/browser/services/openerService*/,188/*vs/editor/browser/widget/diffNavigator*/,33/*vs/editor/common/config/editorOptions*/,142/*vs/editor/common/config/fontInfo*/,68/*vs/editor/common/editorCommon*/,48/*vs/editor/common/model*/,17/*vs/editor/common/modes*/,63/*vs/editor/common/modes/nullMode*/,62/*vs/editor/common/services/editorWorkerService*/,84/*vs/editor/common/services/resolverService*/,507/*vs/editor/common/services/webWorker*/,147/*vs/editor/common/standalone/standaloneEnums*/,494/*vs/editor/standalone/browser/colorizer*/,172/*vs/editor/standalone/browser/simpleServices*/,602/*vs/editor/standalone/browser/standaloneCodeEditor*/,238/*vs/editor/standalone/browser/standaloneServices*/,94/*vs/editor/standalone/common/standaloneThemeService*/,29/*vs/platform/commands/common/commands*/,43/*vs/platform/configuration/common/configuration*/,18/*vs/platform/contextkey/common/contextkey*/,66/*vs/platform/contextview/browser/contextView*/,11/*vs/platform/instantiation/common/instantiation*/,34/*vs/platform/keybinding/common/keybinding*/,35/*vs/platform/notification/common/notification*/,51/*vs/platform/opener/common/opener*/,64/*vs/platform/accessibility/common/accessibility*/,60/*vs/editor/browser/config/configuration*/,73/*vs/platform/progress/common/progress*/,331/*vs/css!vs/editor/standalone/browser/standalone-tokens*/]), function (require, exports, codeEditorService_1, openerService_1, diffNavigator_1, editorOptions_1, fontInfo_1, editorCommon_1, model_1, modes, nullMode_1, editorWorkerService_1, resolverService_1, webWorker_1, standaloneEnums, colorizer_1, simpleServices_1, standaloneCodeEditor_1, standaloneServices_1, standaloneThemeService_1, commands_1, configuration_1, contextkey_1, contextView_1, instantiation_1, keybinding_1, notification_1, opener_1, accessibility_1, configuration_2, progress_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function withAllStandaloneServices(domElement, override, callback) { var services = new standaloneServices_1.DynamicStandaloneServices(domElement, override); var simpleEditorModelResolverService = null; if (!services.has(resolverService_1.ITextModelService)) { simpleEditorModelResolverService = new simpleServices_1.SimpleEditorModelResolverService(standaloneServices_1.StaticServices.modelService.get()); services.set(resolverService_1.ITextModelService, simpleEditorModelResolverService); } if (!services.has(opener_1.IOpenerService)) { services.set(opener_1.IOpenerService, new openerService_1.OpenerService(services.get(codeEditorService_1.ICodeEditorService), services.get(commands_1.ICommandService))); } var result = callback(services); if (simpleEditorModelResolverService) { simpleEditorModelResolverService.setEditor(result); } return result; } /** * Create a new editor under `domElement`. * `domElement` should be empty (not contain other dom nodes). * The editor will read the size of `domElement`. */ function create(domElement, options, override) { return withAllStandaloneServices(domElement, override || {}, function (services) { return new standaloneCodeEditor_1.StandaloneEditor(domElement, options, services, services.get(instantiation_1.IInstantiationService), services.get(codeEditorService_1.ICodeEditorService), services.get(commands_1.ICommandService), services.get(contextkey_1.IContextKeyService), services.get(keybinding_1.IKeybindingService), services.get(contextView_1.IContextViewService), services.get(standaloneThemeService_1.IStandaloneThemeService), services.get(notification_1.INotificationService), services.get(configuration_1.IConfigurationService), services.get(accessibility_1.IAccessibilityService)); }); } exports.create = create; /** * Emitted when an editor is created. * Creating a diff editor might cause this listener to be invoked with the two editors. * @event */ function onDidCreateEditor(listener) { return standaloneServices_1.StaticServices.codeEditorService.get().onCodeEditorAdd(function (editor) { listener(editor); }); } exports.onDidCreateEditor = onDidCreateEditor; /** * Create a new diff editor under `domElement`. * `domElement` should be empty (not contain other dom nodes). * The editor will read the size of `domElement`. */ function createDiffEditor(domElement, options, override) { return withAllStandaloneServices(domElement, override || {}, function (services) { return new standaloneCodeEditor_1.StandaloneDiffEditor(domElement, options, services, services.get(instantiation_1.IInstantiationService), services.get(contextkey_1.IContextKeyService), services.get(keybinding_1.IKeybindingService), services.get(contextView_1.IContextViewService), services.get(editorWorkerService_1.IEditorWorkerService), services.get(codeEditorService_1.ICodeEditorService), services.get(standaloneThemeService_1.IStandaloneThemeService), services.get(notification_1.INotificationService), services.get(configuration_1.IConfigurationService), services.get(contextView_1.IContextMenuService), services.get(progress_1.IEditorProgressService), null); }); } exports.createDiffEditor = createDiffEditor; function createDiffNavigator(diffEditor, opts) { return new diffNavigator_1.DiffNavigator(diffEditor, opts); } exports.createDiffNavigator = createDiffNavigator; function doCreateModel(value, languageSelection, uri) { return standaloneServices_1.StaticServices.modelService.get().createModel(value, languageSelection, uri); } /** * Create a new editor model. * You can specify the language that should be set for this model or let the language be inferred from the `uri`. */ function createModel(value, language, uri) { value = value || ''; if (!language) { var firstLF = value.indexOf('\n'); var firstLine = value; if (firstLF !== -1) { firstLine = value.substring(0, firstLF); } return doCreateModel(value, standaloneServices_1.StaticServices.modeService.get().createByFilepathOrFirstLine(uri || null, firstLine), uri); } return doCreateModel(value, standaloneServices_1.StaticServices.modeService.get().create(language), uri); } exports.createModel = createModel; /** * Change the language for a model. */ function setModelLanguage(model, languageId) { standaloneServices_1.StaticServices.modelService.get().setMode(model, standaloneServices_1.StaticServices.modeService.get().create(languageId)); } exports.setModelLanguage = setModelLanguage; /** * Set the markers for a model. */ function setModelMarkers(model, owner, markers) { if (model) { standaloneServices_1.StaticServices.markerService.get().changeOne(owner, model.uri, markers); } } exports.setModelMarkers = setModelMarkers; /** * Get markers for owner and/or resource * * @returns list of markers */ function getModelMarkers(filter) { return standaloneServices_1.StaticServices.markerService.get().read(filter); } exports.getModelMarkers = getModelMarkers; /** * Get the model that has `uri` if it exists. */ function getModel(uri) { return standaloneServices_1.StaticServices.modelService.get().getModel(uri); } exports.getModel = getModel; /** * Get all the created models. */ function getModels() { return standaloneServices_1.StaticServices.modelService.get().getModels(); } exports.getModels = getModels; /** * Emitted when a model is created. * @event */ function onDidCreateModel(listener) { return standaloneServices_1.StaticServices.modelService.get().onModelAdded(listener); } exports.onDidCreateModel = onDidCreateModel; /** * Emitted right before a model is disposed. * @event */ function onWillDisposeModel(listener) { return standaloneServices_1.StaticServices.modelService.get().onModelRemoved(listener); } exports.onWillDisposeModel = onWillDisposeModel; /** * Emitted when a different language is set to a model. * @event */ function onDidChangeModelLanguage(listener) { return standaloneServices_1.StaticServices.modelService.get().onModelModeChanged(function (e) { listener({ model: e.model, oldLanguage: e.oldModeId }); }); } exports.onDidChangeModelLanguage = onDidChangeModelLanguage; /** * Create a new web worker that has model syncing capabilities built in. * Specify an AMD module to load that will `create` an object that will be proxied. */ function createWebWorker(opts) { return webWorker_1.createWebWorker(standaloneServices_1.StaticServices.modelService.get(), opts); } exports.createWebWorker = createWebWorker; /** * Colorize the contents of `domNode` using attribute `data-lang`. */ function colorizeElement(domNode, options) { return colorizer_1.Colorizer.colorizeElement(standaloneServices_1.StaticServices.standaloneThemeService.get(), standaloneServices_1.StaticServices.modeService.get(), domNode, options); } exports.colorizeElement = colorizeElement; /** * Colorize `text` using language `languageId`. */ function colorize(text, languageId, options) { return colorizer_1.Colorizer.colorize(standaloneServices_1.StaticServices.modeService.get(), text, languageId, options); } exports.colorize = colorize; /** * Colorize a line in a model. */ function colorizeModelLine(model, lineNumber, tabSize) { if (tabSize === void 0) { tabSize = 4; } return colorizer_1.Colorizer.colorizeModelLine(model, lineNumber, tabSize); } exports.colorizeModelLine = colorizeModelLine; /** * @internal */ function getSafeTokenizationSupport(language) { var tokenizationSupport = modes.TokenizationRegistry.get(language); if (tokenizationSupport) { return tokenizationSupport; } return { getInitialState: function () { return nullMode_1.NULL_STATE; }, tokenize: function (line, state, deltaOffset) { return nullMode_1.nullTokenize(language, line, state, deltaOffset); } }; } /** * Tokenize `text` using language `languageId` */ function tokenize(text, languageId) { var modeService = standaloneServices_1.StaticServices.modeService.get(); // Needed in order to get the mode registered for subsequent look-ups modeService.triggerMode(languageId); var tokenizationSupport = getSafeTokenizationSupport(languageId); var lines = text.split(/\r\n|\r|\n/); var result = []; var state = tokenizationSupport.getInitialState(); for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; var tokenizationResult = tokenizationSupport.tokenize(line, state, 0); result[i] = tokenizationResult.tokens; state = tokenizationResult.endState; } return result; } exports.tokenize = tokenize; /** * Define a new theme or update an existing theme. */ function defineTheme(themeName, themeData) { standaloneServices_1.StaticServices.standaloneThemeService.get().defineTheme(themeName, themeData); } exports.defineTheme = defineTheme; /** * Switches to a theme. */ function setTheme(themeName) { standaloneServices_1.StaticServices.standaloneThemeService.get().setTheme(themeName); } exports.setTheme = setTheme; /** * Clears all cached font measurements and triggers re-measurement. */ function remeasureFonts() { configuration_2.clearAllFontInfos(); } exports.remeasureFonts = remeasureFonts; /** * @internal */ function createMonacoEditorAPI() { return { // methods create: create, onDidCreateEditor: onDidCreateEditor, createDiffEditor: createDiffEditor, createDiffNavigator: createDiffNavigator, createModel: createModel, setModelLanguage: setModelLanguage, setModelMarkers: setModelMarkers, getModelMarkers: getModelMarkers, getModels: getModels, getModel: getModel, onDidCreateModel: onDidCreateModel, onWillDisposeModel: onWillDisposeModel, onDidChangeModelLanguage: onDidChangeModelLanguage, createWebWorker: createWebWorker, colorizeElement: colorizeElement, colorize: colorize, colorizeModelLine: colorizeModelLine, tokenize: tokenize, defineTheme: defineTheme, setTheme: setTheme, remeasureFonts: remeasureFonts, // enums AccessibilitySupport: standaloneEnums.AccessibilitySupport, ContentWidgetPositionPreference: standaloneEnums.ContentWidgetPositionPreference, CursorChangeReason: standaloneEnums.CursorChangeReason, DefaultEndOfLine: standaloneEnums.DefaultEndOfLine, EditorAutoIndentStrategy: standaloneEnums.EditorAutoIndentStrategy, EditorOption: standaloneEnums.EditorOption, EndOfLinePreference: standaloneEnums.EndOfLinePreference, EndOfLineSequence: standaloneEnums.EndOfLineSequence, MinimapPosition: standaloneEnums.MinimapPosition, MouseTargetType: standaloneEnums.MouseTargetType, OverlayWidgetPositionPreference: standaloneEnums.OverlayWidgetPositionPreference, OverviewRulerLane: standaloneEnums.OverviewRulerLane, RenderLineNumbersType: standaloneEnums.RenderLineNumbersType, RenderMinimap: standaloneEnums.RenderMinimap, ScrollbarVisibility: standaloneEnums.ScrollbarVisibility, ScrollType: standaloneEnums.ScrollType, TextEditorCursorBlinkingStyle: standaloneEnums.TextEditorCursorBlinkingStyle, TextEditorCursorStyle: standaloneEnums.TextEditorCursorStyle, TrackedRangeStickiness: standaloneEnums.TrackedRangeStickiness, WrappingIndent: standaloneEnums.WrappingIndent, // classes ConfigurationChangedEvent: editorOptions_1.ConfigurationChangedEvent, BareFontInfo: fontInfo_1.BareFontInfo, FontInfo: fontInfo_1.FontInfo, TextModelResolvedOptions: model_1.TextModelResolvedOptions, FindMatch: model_1.FindMatch, // vars EditorType: editorCommon_1.EditorType, EditorOptions: editorOptions_1.EditorOptions }; } exports.createMonacoEditorAPI = createMonacoEditorAPI; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[604/*vs/editor/standalone/browser/standaloneLanguages*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,107/*vs/editor/common/core/token*/,17/*vs/editor/common/modes*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/,118/*vs/editor/common/modes/modesRegistry*/,147/*vs/editor/common/standalone/standaloneEnums*/,238/*vs/editor/standalone/browser/standaloneServices*/,393/*vs/editor/standalone/common/monarch/monarchCompile*/,216/*vs/editor/standalone/common/monarch/monarchLexer*/]), function (require, exports, range_1, token_1, modes, languageConfigurationRegistry_1, modesRegistry_1, standaloneEnums, standaloneServices_1, monarchCompile_1, monarchLexer_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Register information about a new language. */ function register(language) { modesRegistry_1.ModesRegistry.registerLanguage(language); } exports.register = register; /** * Get the information of all the registered languages. */ function getLanguages() { var result = []; result = result.concat(modesRegistry_1.ModesRegistry.getLanguages()); return result; } exports.getLanguages = getLanguages; function getEncodedLanguageId(languageId) { var lid = standaloneServices_1.StaticServices.modeService.get().getLanguageIdentifier(languageId); return lid ? lid.id : 0; } exports.getEncodedLanguageId = getEncodedLanguageId; /** * An event emitted when a language is first time needed (e.g. a model has it set). * @event */ function onLanguage(languageId, callback) { var disposable = standaloneServices_1.StaticServices.modeService.get().onDidCreateMode(function (mode) { if (mode.getId() === languageId) { // stop listening disposable.dispose(); // invoke actual listener callback(); } }); return disposable; } exports.onLanguage = onLanguage; /** * Set the editing configuration for a language. */ function setLanguageConfiguration(languageId, configuration) { var languageIdentifier = standaloneServices_1.StaticServices.modeService.get().getLanguageIdentifier(languageId); if (!languageIdentifier) { throw new Error("Cannot set configuration for unknown language " + languageId); } return languageConfigurationRegistry_1.LanguageConfigurationRegistry.register(languageIdentifier, configuration); } exports.setLanguageConfiguration = setLanguageConfiguration; /** * @internal */ var EncodedTokenizationSupport2Adapter = /** @class */ (function () { function EncodedTokenizationSupport2Adapter(actual) { this._actual = actual; } EncodedTokenizationSupport2Adapter.prototype.getInitialState = function () { return this._actual.getInitialState(); }; EncodedTokenizationSupport2Adapter.prototype.tokenize = function (line, state, offsetDelta) { throw new Error('Not supported!'); }; EncodedTokenizationSupport2Adapter.prototype.tokenize2 = function (line, state) { var result = this._actual.tokenizeEncoded(line, state); return new token_1.TokenizationResult2(result.tokens, result.endState); }; return EncodedTokenizationSupport2Adapter; }()); exports.EncodedTokenizationSupport2Adapter = EncodedTokenizationSupport2Adapter; /** * @internal */ var TokenizationSupport2Adapter = /** @class */ (function () { function TokenizationSupport2Adapter(standaloneThemeService, languageIdentifier, actual) { this._standaloneThemeService = standaloneThemeService; this._languageIdentifier = languageIdentifier; this._actual = actual; } TokenizationSupport2Adapter.prototype.getInitialState = function () { return this._actual.getInitialState(); }; TokenizationSupport2Adapter.prototype._toClassicTokens = function (tokens, language, offsetDelta) { var result = []; var previousStartIndex = 0; for (var i = 0, len = tokens.length; i < len; i++) { var t = tokens[i]; var startIndex = t.startIndex; // Prevent issues stemming from a buggy external tokenizer. if (i === 0) { // Force first token to start at first index! startIndex = 0; } else if (startIndex < previousStartIndex) { // Force tokens to be after one another! startIndex = previousStartIndex; } result[i] = new token_1.Token(startIndex + offsetDelta, t.scopes, language); previousStartIndex = startIndex; } return result; }; TokenizationSupport2Adapter.prototype.tokenize = function (line, state, offsetDelta) { var actualResult = this._actual.tokenize(line, state); var tokens = this._toClassicTokens(actualResult.tokens, this._languageIdentifier.language, offsetDelta); var endState; // try to save an object if possible if (actualResult.endState.equals(state)) { endState = state; } else { endState = actualResult.endState; } return new token_1.TokenizationResult(tokens, endState); }; TokenizationSupport2Adapter.prototype._toBinaryTokens = function (tokens, offsetDelta) { var languageId = this._languageIdentifier.id; var tokenTheme = this._standaloneThemeService.getTheme().tokenTheme; var result = [], resultLen = 0; var previousStartIndex = 0; for (var i = 0, len = tokens.length; i < len; i++) { var t = tokens[i]; var metadata = tokenTheme.match(languageId, t.scopes); if (resultLen > 0 && result[resultLen - 1] === metadata) { // same metadata continue; } var startIndex = t.startIndex; // Prevent issues stemming from a buggy external tokenizer. if (i === 0) { // Force first token to start at first index! startIndex = 0; } else if (startIndex < previousStartIndex) { // Force tokens to be after one another! startIndex = previousStartIndex; } result[resultLen++] = startIndex + offsetDelta; result[resultLen++] = metadata; previousStartIndex = startIndex; } var actualResult = new Uint32Array(resultLen); for (var i = 0; i < resultLen; i++) { actualResult[i] = result[i]; } return actualResult; }; TokenizationSupport2Adapter.prototype.tokenize2 = function (line, state, offsetDelta) { var actualResult = this._actual.tokenize(line, state); var tokens = this._toBinaryTokens(actualResult.tokens, offsetDelta); var endState; // try to save an object if possible if (actualResult.endState.equals(state)) { endState = state; } else { endState = actualResult.endState; } return new token_1.TokenizationResult2(tokens, endState); }; return TokenizationSupport2Adapter; }()); exports.TokenizationSupport2Adapter = TokenizationSupport2Adapter; function isEncodedTokensProvider(provider) { return 'tokenizeEncoded' in provider; } function isThenable(obj) { return obj && typeof obj.then === 'function'; } /** * Set the tokens provider for a language (manual implementation). */ function setTokensProvider(languageId, provider) { var languageIdentifier = standaloneServices_1.StaticServices.modeService.get().getLanguageIdentifier(languageId); if (!languageIdentifier) { throw new Error("Cannot set tokens provider for unknown language " + languageId); } var create = function (provider) { if (isEncodedTokensProvider(provider)) { return new EncodedTokenizationSupport2Adapter(provider); } else { return new TokenizationSupport2Adapter(standaloneServices_1.StaticServices.standaloneThemeService.get(), languageIdentifier, provider); } }; if (isThenable(provider)) { return modes.TokenizationRegistry.registerPromise(languageId, provider.then(function (provider) { return create(provider); })); } return modes.TokenizationRegistry.register(languageId, create(provider)); } exports.setTokensProvider = setTokensProvider; /** * Set the tokens provider for a language (monarch implementation). */ function setMonarchTokensProvider(languageId, languageDef) { var create = function (languageDef) { return monarchLexer_1.createTokenizationSupport(standaloneServices_1.StaticServices.modeService.get(), standaloneServices_1.StaticServices.standaloneThemeService.get(), languageId, monarchCompile_1.compile(languageId, languageDef)); }; if (isThenable(languageDef)) { return modes.TokenizationRegistry.registerPromise(languageId, languageDef.then(function (languageDef) { return create(languageDef); })); } return modes.TokenizationRegistry.register(languageId, create(languageDef)); } exports.setMonarchTokensProvider = setMonarchTokensProvider; /** * Register a reference provider (used by e.g. reference search). */ function registerReferenceProvider(languageId, provider) { return modes.ReferenceProviderRegistry.register(languageId, provider); } exports.registerReferenceProvider = registerReferenceProvider; /** * Register a rename provider (used by e.g. rename symbol). */ function registerRenameProvider(languageId, provider) { return modes.RenameProviderRegistry.register(languageId, provider); } exports.registerRenameProvider = registerRenameProvider; /** * Register a signature help provider (used by e.g. parameter hints). */ function registerSignatureHelpProvider(languageId, provider) { return modes.SignatureHelpProviderRegistry.register(languageId, provider); } exports.registerSignatureHelpProvider = registerSignatureHelpProvider; /** * Register a hover provider (used by e.g. editor hover). */ function registerHoverProvider(languageId, provider) { return modes.HoverProviderRegistry.register(languageId, { provideHover: function (model, position, token) { var word = model.getWordAtPosition(position); return Promise.resolve(provider.provideHover(model, position, token)).then(function (value) { if (!value) { return undefined; } if (!value.range && word) { value.range = new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn); } if (!value.range) { value.range = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column); } return value; }); } }); } exports.registerHoverProvider = registerHoverProvider; /** * Register a document symbol provider (used by e.g. outline). */ function registerDocumentSymbolProvider(languageId, provider) { return modes.DocumentSymbolProviderRegistry.register(languageId, provider); } exports.registerDocumentSymbolProvider = registerDocumentSymbolProvider; /** * Register a document highlight provider (used by e.g. highlight occurrences). */ function registerDocumentHighlightProvider(languageId, provider) { return modes.DocumentHighlightProviderRegistry.register(languageId, provider); } exports.registerDocumentHighlightProvider = registerDocumentHighlightProvider; /** * Register a definition provider (used by e.g. go to definition). */ function registerDefinitionProvider(languageId, provider) { return modes.DefinitionProviderRegistry.register(languageId, provider); } exports.registerDefinitionProvider = registerDefinitionProvider; /** * Register a implementation provider (used by e.g. go to implementation). */ function registerImplementationProvider(languageId, provider) { return modes.ImplementationProviderRegistry.register(languageId, provider); } exports.registerImplementationProvider = registerImplementationProvider; /** * Register a type definition provider (used by e.g. go to type definition). */ function registerTypeDefinitionProvider(languageId, provider) { return modes.TypeDefinitionProviderRegistry.register(languageId, provider); } exports.registerTypeDefinitionProvider = registerTypeDefinitionProvider; /** * Register a code lens provider (used by e.g. inline code lenses). */ function registerCodeLensProvider(languageId, provider) { return modes.CodeLensProviderRegistry.register(languageId, provider); } exports.registerCodeLensProvider = registerCodeLensProvider; /** * Register a code action provider (used by e.g. quick fix). */ function registerCodeActionProvider(languageId, provider) { return modes.CodeActionProviderRegistry.register(languageId, { provideCodeActions: function (model, range, context, token) { var markers = standaloneServices_1.StaticServices.markerService.get().read({ resource: model.uri }).filter(function (m) { return range_1.Range.areIntersectingOrTouching(m, range); }); return provider.provideCodeActions(model, range, { markers: markers, only: context.only }, token); } }); } exports.registerCodeActionProvider = registerCodeActionProvider; /** * Register a formatter that can handle only entire models. */ function registerDocumentFormattingEditProvider(languageId, provider) { return modes.DocumentFormattingEditProviderRegistry.register(languageId, provider); } exports.registerDocumentFormattingEditProvider = registerDocumentFormattingEditProvider; /** * Register a formatter that can handle a range inside a model. */ function registerDocumentRangeFormattingEditProvider(languageId, provider) { return modes.DocumentRangeFormattingEditProviderRegistry.register(languageId, provider); } exports.registerDocumentRangeFormattingEditProvider = registerDocumentRangeFormattingEditProvider; /** * Register a formatter than can do formatting as the user types. */ function registerOnTypeFormattingEditProvider(languageId, provider) { return modes.OnTypeFormattingEditProviderRegistry.register(languageId, provider); } exports.registerOnTypeFormattingEditProvider = registerOnTypeFormattingEditProvider; /** * Register a link provider that can find links in text. */ function registerLinkProvider(languageId, provider) { return modes.LinkProviderRegistry.register(languageId, provider); } exports.registerLinkProvider = registerLinkProvider; /** * Register a completion item provider (use by e.g. suggestions). */ function registerCompletionItemProvider(languageId, provider) { return modes.CompletionProviderRegistry.register(languageId, provider); } exports.registerCompletionItemProvider = registerCompletionItemProvider; /** * Register a document color provider (used by Color Picker, Color Decorator). */ function registerColorProvider(languageId, provider) { return modes.ColorProviderRegistry.register(languageId, provider); } exports.registerColorProvider = registerColorProvider; /** * Register a folding range provider */ function registerFoldingRangeProvider(languageId, provider) { return modes.FoldingRangeProviderRegistry.register(languageId, provider); } exports.registerFoldingRangeProvider = registerFoldingRangeProvider; /** * Register a declaration provider */ function registerDeclarationProvider(languageId, provider) { return modes.DeclarationProviderRegistry.register(languageId, provider); } exports.registerDeclarationProvider = registerDeclarationProvider; /** * Register a selection range provider */ function registerSelectionRangeProvider(languageId, provider) { return modes.SelectionRangeRegistry.register(languageId, provider); } exports.registerSelectionRangeProvider = registerSelectionRangeProvider; /** * Register a document semantic tokens provider */ function registerDocumentSemanticTokensProvider(languageId, provider) { return modes.DocumentSemanticTokensProviderRegistry.register(languageId, provider); } exports.registerDocumentSemanticTokensProvider = registerDocumentSemanticTokensProvider; /** * Register a document range semantic tokens provider */ function registerDocumentRangeSemanticTokensProvider(languageId, provider) { return modes.DocumentRangeSemanticTokensProviderRegistry.register(languageId, provider); } exports.registerDocumentRangeSemanticTokensProvider = registerDocumentRangeSemanticTokensProvider; /** * @internal */ function createMonacoLanguagesAPI() { return { register: register, getLanguages: getLanguages, onLanguage: onLanguage, getEncodedLanguageId: getEncodedLanguageId, // provider methods setLanguageConfiguration: setLanguageConfiguration, setTokensProvider: setTokensProvider, setMonarchTokensProvider: setMonarchTokensProvider, registerReferenceProvider: registerReferenceProvider, registerRenameProvider: registerRenameProvider, registerCompletionItemProvider: registerCompletionItemProvider, registerSignatureHelpProvider: registerSignatureHelpProvider, registerHoverProvider: registerHoverProvider, registerDocumentSymbolProvider: registerDocumentSymbolProvider, registerDocumentHighlightProvider: registerDocumentHighlightProvider, registerDefinitionProvider: registerDefinitionProvider, registerImplementationProvider: registerImplementationProvider, registerTypeDefinitionProvider: registerTypeDefinitionProvider, registerCodeLensProvider: registerCodeLensProvider, registerCodeActionProvider: registerCodeActionProvider, registerDocumentFormattingEditProvider: registerDocumentFormattingEditProvider, registerDocumentRangeFormattingEditProvider: registerDocumentRangeFormattingEditProvider, registerOnTypeFormattingEditProvider: registerOnTypeFormattingEditProvider, registerLinkProvider: registerLinkProvider, registerColorProvider: registerColorProvider, registerFoldingRangeProvider: registerFoldingRangeProvider, registerDeclarationProvider: registerDeclarationProvider, registerSelectionRangeProvider: registerSelectionRangeProvider, registerDocumentSemanticTokensProvider: registerDocumentSemanticTokensProvider, registerDocumentRangeSemanticTokensProvider: registerDocumentRangeSemanticTokensProvider, // enums DocumentHighlightKind: standaloneEnums.DocumentHighlightKind, CompletionItemKind: standaloneEnums.CompletionItemKind, CompletionItemTag: standaloneEnums.CompletionItemTag, CompletionItemInsertTextRule: standaloneEnums.CompletionItemInsertTextRule, SymbolKind: standaloneEnums.SymbolKind, SymbolTag: standaloneEnums.SymbolTag, IndentAction: standaloneEnums.IndentAction, CompletionTriggerKind: standaloneEnums.CompletionTriggerKind, SignatureHelpTriggerKind: standaloneEnums.SignatureHelpTriggerKind, // classes FoldingRangeKind: modes.FoldingRangeKind, }; } exports.createMonacoLanguagesAPI = createMonacoLanguagesAPI; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[605/*vs/editor/editor.api*/], __M([0/*require*/,1/*exports*/,33/*vs/editor/common/config/editorOptions*/,192/*vs/editor/common/standalone/standaloneBase*/,603/*vs/editor/standalone/browser/standaloneEditor*/,604/*vs/editor/standalone/browser/standaloneLanguages*/]), function (require, exports, editorOptions_1, standaloneBase_1, standaloneEditor_1, standaloneLanguages_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var global = self; // Set defaults for standalone editor editorOptions_1.EditorOptions.wrappingIndent.defaultValue = 0 /* None */; editorOptions_1.EditorOptions.glyphMargin.defaultValue = false; editorOptions_1.EditorOptions.autoIndent.defaultValue = 3 /* Advanced */; editorOptions_1.EditorOptions.overviewRulerLanes.defaultValue = 2; var api = standaloneBase_1.createMonacoBaseAPI(); api.editor = standaloneEditor_1.createMonacoEditorAPI(); api.languages = standaloneLanguages_1.createMonacoLanguagesAPI(); exports.CancellationTokenSource = api.CancellationTokenSource; exports.Emitter = api.Emitter; exports.KeyCode = api.KeyCode; exports.KeyMod = api.KeyMod; exports.Position = api.Position; exports.Range = api.Range; exports.Selection = api.Selection; exports.SelectionDirection = api.SelectionDirection; exports.MarkerSeverity = api.MarkerSeverity; exports.MarkerTag = api.MarkerTag; exports.Uri = api.Uri; exports.Token = api.Token; exports.editor = api.editor; exports.languages = api.languages; global.monaco = api; if (typeof global.require !== 'undefined' && typeof global.require.config === 'function') { global.require.config({ ignoreDuplicateModules: [ 'vscode-languageserver-types', 'vscode-languageserver-types/main', 'vscode-nls', 'vscode-nls/vscode-nls', 'jsonc-parser', 'jsonc-parser/main', 'vscode-uri', 'vscode-uri/index', 'vs/basic-languages/typescript/typescript' ] }); } }); define(__m[606/*vs/platform/workspaces/common/workspaces*/], __M([0/*require*/,1/*exports*/,25/*vs/base/common/uri*/]), function (require, exports, uri_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WORKSPACE_EXTENSION = 'code-workspace'; function isSingleFolderWorkspaceIdentifier(obj) { return obj instanceof uri_1.URI; } exports.isSingleFolderWorkspaceIdentifier = isSingleFolderWorkspaceIdentifier; function toWorkspaceIdentifier(workspace) { if (workspace.configuration) { return { configPath: workspace.configuration, id: workspace.id }; } if (workspace.folders.length === 1) { return workspace.folders[0].uri; } // Empty workspace return undefined; } exports.toWorkspaceIdentifier = toWorkspaceIdentifier; }); //#endregion /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[607/*vs/editor/contrib/snippet/snippetVariables*/], __M([0/*require*/,1/*exports*/,466/*vs/nls!vs/editor/contrib/snippet/snippetVariables*/,77/*vs/base/common/path*/,39/*vs/base/common/resources*/,151/*vs/editor/contrib/snippet/snippetParser*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/,5/*vs/base/common/strings*/,606/*vs/platform/workspaces/common/workspaces*/,136/*vs/base/common/labels*/]), function (require, exports, nls, path, resources_1, snippetParser_1, languageConfigurationRegistry_1, strings_1, workspaces_1, labels_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CompositeSnippetVariableResolver = /** @class */ (function () { function CompositeSnippetVariableResolver(_delegates) { this._delegates = _delegates; // } CompositeSnippetVariableResolver.prototype.resolve = function (variable) { for (var _i = 0, _a = this._delegates; _i < _a.length; _i++) { var delegate = _a[_i]; var value = delegate.resolve(variable); if (value !== undefined) { return value; } } return undefined; }; return CompositeSnippetVariableResolver; }()); exports.CompositeSnippetVariableResolver = CompositeSnippetVariableResolver; var SelectionBasedVariableResolver = /** @class */ (function () { function SelectionBasedVariableResolver(_model, _selection) { this._model = _model; this._selection = _selection; // } SelectionBasedVariableResolver.prototype.resolve = function (variable) { var name = variable.name; if (name === 'SELECTION' || name === 'TM_SELECTED_TEXT') { var value = this._model.getValueInRange(this._selection) || undefined; if (value && this._selection.startLineNumber !== this._selection.endLineNumber && variable.snippet) { // Selection is a multiline string which we indentation we now // need to adjust. We compare the indentation of this variable // with the indentation at the editor position and add potential // extra indentation to the value var line = this._model.getLineContent(this._selection.startLineNumber); var lineLeadingWhitespace = strings_1.getLeadingWhitespace(line, 0, this._selection.startColumn - 1); var varLeadingWhitespace_1 = lineLeadingWhitespace; variable.snippet.walk(function (marker) { if (marker === variable) { return false; } if (marker instanceof snippetParser_1.Text) { varLeadingWhitespace_1 = strings_1.getLeadingWhitespace(marker.value.split(/\r\n|\r|\n/).pop()); } return true; }); var whitespaceCommonLength_1 = strings_1.commonPrefixLength(varLeadingWhitespace_1, lineLeadingWhitespace); value = value.replace(/(\r\n|\r|\n)(.*)/g, function (m, newline, rest) { return "" + newline + varLeadingWhitespace_1.substr(whitespaceCommonLength_1) + rest; }); } return value; } else if (name === 'TM_CURRENT_LINE') { return this._model.getLineContent(this._selection.positionLineNumber); } else if (name === 'TM_CURRENT_WORD') { var info = this._model.getWordAtPosition({ lineNumber: this._selection.positionLineNumber, column: this._selection.positionColumn }); return info && info.word || undefined; } else if (name === 'TM_LINE_INDEX') { return String(this._selection.positionLineNumber - 1); } else if (name === 'TM_LINE_NUMBER') { return String(this._selection.positionLineNumber); } return undefined; }; return SelectionBasedVariableResolver; }()); exports.SelectionBasedVariableResolver = SelectionBasedVariableResolver; var ModelBasedVariableResolver = /** @class */ (function () { function ModelBasedVariableResolver(_labelService, _model) { this._labelService = _labelService; this._model = _model; // } ModelBasedVariableResolver.prototype.resolve = function (variable) { var name = variable.name; if (name === 'TM_FILENAME') { return path.basename(this._model.uri.fsPath); } else if (name === 'TM_FILENAME_BASE') { var name_1 = path.basename(this._model.uri.fsPath); var idx = name_1.lastIndexOf('.'); if (idx <= 0) { return name_1; } else { return name_1.slice(0, idx); } } else if (name === 'TM_DIRECTORY' && this._labelService) { if (path.dirname(this._model.uri.fsPath) === '.') { return ''; } return this._labelService.getUriLabel(resources_1.dirname(this._model.uri)); } else if (name === 'TM_FILEPATH' && this._labelService) { return this._labelService.getUriLabel(this._model.uri); } return undefined; }; return ModelBasedVariableResolver; }()); exports.ModelBasedVariableResolver = ModelBasedVariableResolver; var ClipboardBasedVariableResolver = /** @class */ (function () { function ClipboardBasedVariableResolver(_readClipboardText, _selectionIdx, _selectionCount, _spread) { this._readClipboardText = _readClipboardText; this._selectionIdx = _selectionIdx; this._selectionCount = _selectionCount; this._spread = _spread; // } ClipboardBasedVariableResolver.prototype.resolve = function (variable) { if (variable.name !== 'CLIPBOARD') { return undefined; } var clipboardText = this._readClipboardText(); if (!clipboardText) { return undefined; } // `spread` is assigning each cursor a line of the clipboard // text whenever there the line count equals the cursor count // and when enabled if (this._spread) { var lines = clipboardText.split(/\r\n|\n|\r/).filter(function (s) { return !strings_1.isFalsyOrWhitespace(s); }); if (lines.length === this._selectionCount) { return lines[this._selectionIdx]; } } return clipboardText; }; return ClipboardBasedVariableResolver; }()); exports.ClipboardBasedVariableResolver = ClipboardBasedVariableResolver; var CommentBasedVariableResolver = /** @class */ (function () { function CommentBasedVariableResolver(_model) { this._model = _model; // } CommentBasedVariableResolver.prototype.resolve = function (variable) { var name = variable.name; var language = this._model.getLanguageIdentifier(); var config = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getComments(language.id); if (!config) { return undefined; } if (name === 'LINE_COMMENT') { return config.lineCommentToken || undefined; } else if (name === 'BLOCK_COMMENT_START') { return config.blockCommentStartToken || undefined; } else if (name === 'BLOCK_COMMENT_END') { return config.blockCommentEndToken || undefined; } return undefined; }; return CommentBasedVariableResolver; }()); exports.CommentBasedVariableResolver = CommentBasedVariableResolver; var TimeBasedVariableResolver = /** @class */ (function () { function TimeBasedVariableResolver() { } TimeBasedVariableResolver.prototype.resolve = function (variable) { var name = variable.name; if (name === 'CURRENT_YEAR') { return String(new Date().getFullYear()); } else if (name === 'CURRENT_YEAR_SHORT') { return String(new Date().getFullYear()).slice(-2); } else if (name === 'CURRENT_MONTH') { return strings_1.pad((new Date().getMonth().valueOf() + 1), 2); } else if (name === 'CURRENT_DATE') { return strings_1.pad(new Date().getDate().valueOf(), 2); } else if (name === 'CURRENT_HOUR') { return strings_1.pad(new Date().getHours().valueOf(), 2); } else if (name === 'CURRENT_MINUTE') { return strings_1.pad(new Date().getMinutes().valueOf(), 2); } else if (name === 'CURRENT_SECOND') { return strings_1.pad(new Date().getSeconds().valueOf(), 2); } else if (name === 'CURRENT_DAY_NAME') { return TimeBasedVariableResolver.dayNames[new Date().getDay()]; } else if (name === 'CURRENT_DAY_NAME_SHORT') { return TimeBasedVariableResolver.dayNamesShort[new Date().getDay()]; } else if (name === 'CURRENT_MONTH_NAME') { return TimeBasedVariableResolver.monthNames[new Date().getMonth()]; } else if (name === 'CURRENT_MONTH_NAME_SHORT') { return TimeBasedVariableResolver.monthNamesShort[new Date().getMonth()]; } else if (name === 'CURRENT_SECONDS_UNIX') { return String(Math.floor(Date.now() / 1000)); } return undefined; }; TimeBasedVariableResolver.dayNames = [nls.localize(0, null), nls.localize(1, null), nls.localize(2, null), nls.localize(3, null), nls.localize(4, null), nls.localize(5, null), nls.localize(6, null)]; TimeBasedVariableResolver.dayNamesShort = [nls.localize(7, null), nls.localize(8, null), nls.localize(9, null), nls.localize(10, null), nls.localize(11, null), nls.localize(12, null), nls.localize(13, null)]; TimeBasedVariableResolver.monthNames = [nls.localize(14, null), nls.localize(15, null), nls.localize(16, null), nls.localize(17, null), nls.localize(18, null), nls.localize(19, null), nls.localize(20, null), nls.localize(21, null), nls.localize(22, null), nls.localize(23, null), nls.localize(24, null), nls.localize(25, null)]; TimeBasedVariableResolver.monthNamesShort = [nls.localize(26, null), nls.localize(27, null), nls.localize(28, null), nls.localize(29, null), nls.localize(30, null), nls.localize(31, null), nls.localize(32, null), nls.localize(33, null), nls.localize(34, null), nls.localize(35, null), nls.localize(36, null), nls.localize(37, null)]; return TimeBasedVariableResolver; }()); exports.TimeBasedVariableResolver = TimeBasedVariableResolver; var WorkspaceBasedVariableResolver = /** @class */ (function () { function WorkspaceBasedVariableResolver(_workspaceService) { this._workspaceService = _workspaceService; // } WorkspaceBasedVariableResolver.prototype.resolve = function (variable) { if (!this._workspaceService) { return undefined; } var workspaceIdentifier = workspaces_1.toWorkspaceIdentifier(this._workspaceService.getWorkspace()); if (!workspaceIdentifier) { return undefined; } if (variable.name === 'WORKSPACE_NAME') { return this._resolveWorkspaceName(workspaceIdentifier); } else if (variable.name === 'WORKSPACE_FOLDER') { return this._resoveWorkspacePath(workspaceIdentifier); } return undefined; }; WorkspaceBasedVariableResolver.prototype._resolveWorkspaceName = function (workspaceIdentifier) { if (workspaces_1.isSingleFolderWorkspaceIdentifier(workspaceIdentifier)) { return path.basename(workspaceIdentifier.path); } var filename = path.basename(workspaceIdentifier.configPath.path); if (strings_1.endsWith(filename, workspaces_1.WORKSPACE_EXTENSION)) { filename = filename.substr(0, filename.length - workspaces_1.WORKSPACE_EXTENSION.length - 1); } return filename; }; WorkspaceBasedVariableResolver.prototype._resoveWorkspacePath = function (workspaceIdentifier) { if (workspaces_1.isSingleFolderWorkspaceIdentifier(workspaceIdentifier)) { return labels_1.normalizeDriveLetter(workspaceIdentifier.fsPath); } var filename = path.basename(workspaceIdentifier.configPath.path); var folderpath = workspaceIdentifier.configPath.fsPath; if (strings_1.endsWith(folderpath, filename)) { folderpath = folderpath.substr(0, folderpath.length - filename.length - 1); } return (folderpath ? labels_1.normalizeDriveLetter(folderpath) : '/'); }; return WorkspaceBasedVariableResolver; }()); exports.WorkspaceBasedVariableResolver = WorkspaceBasedVariableResolver; var RandomBasedVariableResolver = /** @class */ (function () { function RandomBasedVariableResolver() { } RandomBasedVariableResolver.prototype.resolve = function (variable) { var name = variable.name; if (name === 'RANDOM') { return Math.random().toString().slice(-6); } else if (name === 'RANDOM_HEX') { return Math.random().toString(16).slice(-6); } return undefined; }; return RandomBasedVariableResolver; }()); exports.RandomBasedVariableResolver = RandomBasedVariableResolver; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[608/*vs/editor/contrib/snippet/snippetSession*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,58/*vs/editor/common/core/editOperation*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,30/*vs/editor/common/model/textModel*/,162/*vs/platform/clipboard/common/clipboardService*/,171/*vs/platform/workspace/common/workspace*/,11/*vs/platform/instantiation/common/instantiation*/,151/*vs/editor/contrib/snippet/snippetParser*/,607/*vs/editor/contrib/snippet/snippetVariables*/,14/*vs/platform/theme/common/themeService*/,20/*vs/platform/theme/common/colorRegistry*/,116/*vs/platform/label/common/label*/,321/*vs/css!vs/editor/contrib/snippet/snippetSession*/]), function (require, exports, arrays_1, lifecycle_1, strings_1, editOperation_1, range_1, selection_1, textModel_1, clipboardService_1, workspace_1, instantiation_1, snippetParser_1, snippetVariables_1, themeService_1, colors, label_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); themeService_1.registerThemingParticipant(function (theme, collector) { function getColorGraceful(name) { var color = theme.getColor(name); return color ? color.toString() : 'transparent'; } collector.addRule(".monaco-editor .snippet-placeholder { background-color: " + getColorGraceful(colors.snippetTabstopHighlightBackground) + "; outline-color: " + getColorGraceful(colors.snippetTabstopHighlightBorder) + "; }"); collector.addRule(".monaco-editor .finish-snippet-placeholder { background-color: " + getColorGraceful(colors.snippetFinalTabstopHighlightBackground) + "; outline-color: " + getColorGraceful(colors.snippetFinalTabstopHighlightBorder) + "; }"); }); var OneSnippet = /** @class */ (function () { function OneSnippet(editor, snippet, offset) { this._nestingLevel = 1; this._editor = editor; this._snippet = snippet; this._offset = offset; this._placeholderGroups = arrays_1.groupBy(snippet.placeholders, snippetParser_1.Placeholder.compareByIndex); this._placeholderGroupsIdx = -1; } OneSnippet.prototype.dispose = function () { if (this._placeholderDecorations) { var toRemove_1 = []; this._placeholderDecorations.forEach(function (handle) { return toRemove_1.push(handle); }); this._editor.deltaDecorations(toRemove_1, []); } this._placeholderGroups.length = 0; }; OneSnippet.prototype._initDecorations = function () { var _this = this; if (this._placeholderDecorations) { // already initialized return; } this._placeholderDecorations = new Map(); var model = this._editor.getModel(); this._editor.changeDecorations(function (accessor) { // create a decoration for each placeholder for (var _i = 0, _a = _this._snippet.placeholders; _i < _a.length; _i++) { var placeholder = _a[_i]; var placeholderOffset = _this._snippet.offset(placeholder); var placeholderLen = _this._snippet.fullLen(placeholder); var range = range_1.Range.fromPositions(model.getPositionAt(_this._offset + placeholderOffset), model.getPositionAt(_this._offset + placeholderOffset + placeholderLen)); var options = placeholder.isFinalTabstop ? OneSnippet._decor.inactiveFinal : OneSnippet._decor.inactive; var handle = accessor.addDecoration(range, options); _this._placeholderDecorations.set(placeholder, handle); } }); }; OneSnippet.prototype.move = function (fwd) { var _this = this; if (!this._editor.hasModel()) { return []; } this._initDecorations(); // Transform placeholder text if necessary if (this._placeholderGroupsIdx >= 0) { var operations = []; for (var _i = 0, _a = this._placeholderGroups[this._placeholderGroupsIdx]; _i < _a.length; _i++) { var placeholder = _a[_i]; // Check if the placeholder has a transformation if (placeholder.transform) { var id = this._placeholderDecorations.get(placeholder); var range = this._editor.getModel().getDecorationRange(id); var currentValue = this._editor.getModel().getValueInRange(range); operations.push(editOperation_1.EditOperation.replaceMove(range, placeholder.transform.resolve(currentValue))); } } if (operations.length > 0) { this._editor.executeEdits('snippet.placeholderTransform', operations); } } var couldSkipThisPlaceholder = false; if (fwd === true && this._placeholderGroupsIdx < this._placeholderGroups.length - 1) { this._placeholderGroupsIdx += 1; couldSkipThisPlaceholder = true; } else if (fwd === false && this._placeholderGroupsIdx > 0) { this._placeholderGroupsIdx -= 1; couldSkipThisPlaceholder = true; } else { // the selection of the current placeholder might // not acurate any more -> simply restore it } var newSelections = this._editor.getModel().changeDecorations(function (accessor) { var activePlaceholders = new Set(); // change stickiness to always grow when typing at its edges // because these decorations represent the currently active // tabstop. // Special case #1: reaching the final tabstop // Special case #2: placeholders enclosing active placeholders var selections = []; for (var _i = 0, _a = _this._placeholderGroups[_this._placeholderGroupsIdx]; _i < _a.length; _i++) { var placeholder = _a[_i]; var id = _this._placeholderDecorations.get(placeholder); var range = _this._editor.getModel().getDecorationRange(id); selections.push(new selection_1.Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn)); // consider to skip this placeholder index when the decoration // range is empty but when the placeholder wasn't. that's a strong // hint that the placeholder has been deleted. (all placeholder must match this) couldSkipThisPlaceholder = couldSkipThisPlaceholder && _this._hasPlaceholderBeenCollapsed(placeholder); accessor.changeDecorationOptions(id, placeholder.isFinalTabstop ? OneSnippet._decor.activeFinal : OneSnippet._decor.active); activePlaceholders.add(placeholder); for (var _b = 0, _c = _this._snippet.enclosingPlaceholders(placeholder); _b < _c.length; _b++) { var enclosingPlaceholder = _c[_b]; var id_1 = _this._placeholderDecorations.get(enclosingPlaceholder); accessor.changeDecorationOptions(id_1, enclosingPlaceholder.isFinalTabstop ? OneSnippet._decor.activeFinal : OneSnippet._decor.active); activePlaceholders.add(enclosingPlaceholder); } } // change stickness to never grow when typing at its edges // so that in-active tabstops never grow _this._placeholderDecorations.forEach(function (id, placeholder) { if (!activePlaceholders.has(placeholder)) { accessor.changeDecorationOptions(id, placeholder.isFinalTabstop ? OneSnippet._decor.inactiveFinal : OneSnippet._decor.inactive); } }); return selections; }); return !couldSkipThisPlaceholder ? newSelections : this.move(fwd); }; OneSnippet.prototype._hasPlaceholderBeenCollapsed = function (placeholder) { // A placeholder is empty when it wasn't empty when authored but // when its tracking decoration is empty. This also applies to all // potential parent placeholders var marker = placeholder; while (marker) { if (marker instanceof snippetParser_1.Placeholder) { var id = this._placeholderDecorations.get(marker); var range = this._editor.getModel().getDecorationRange(id); if (range.isEmpty() && marker.toString().length > 0) { return true; } } marker = marker.parent; } return false; }; Object.defineProperty(OneSnippet.prototype, "isAtFirstPlaceholder", { get: function () { return this._placeholderGroupsIdx <= 0 || this._placeholderGroups.length === 0; }, enumerable: true, configurable: true }); Object.defineProperty(OneSnippet.prototype, "isAtLastPlaceholder", { get: function () { return this._placeholderGroupsIdx === this._placeholderGroups.length - 1; }, enumerable: true, configurable: true }); Object.defineProperty(OneSnippet.prototype, "hasPlaceholder", { get: function () { return this._snippet.placeholders.length > 0; }, enumerable: true, configurable: true }); OneSnippet.prototype.computePossibleSelections = function () { var result = new Map(); for (var _i = 0, _a = this._placeholderGroups; _i < _a.length; _i++) { var placeholdersWithEqualIndex = _a[_i]; var ranges = void 0; for (var _b = 0, placeholdersWithEqualIndex_1 = placeholdersWithEqualIndex; _b < placeholdersWithEqualIndex_1.length; _b++) { var placeholder = placeholdersWithEqualIndex_1[_b]; if (placeholder.isFinalTabstop) { // ignore those break; } if (!ranges) { ranges = []; result.set(placeholder.index, ranges); } var id = this._placeholderDecorations.get(placeholder); var range = this._editor.getModel().getDecorationRange(id); if (!range) { // one of the placeholder lost its decoration and // therefore we bail out and pretend the placeholder // (with its mirrors) doesn't exist anymore. result.delete(placeholder.index); break; } ranges.push(range); } } return result; }; Object.defineProperty(OneSnippet.prototype, "choice", { get: function () { return this._placeholderGroups[this._placeholderGroupsIdx][0].choice; }, enumerable: true, configurable: true }); OneSnippet.prototype.merge = function (others) { var _this = this; var model = this._editor.getModel(); this._nestingLevel *= 10; this._editor.changeDecorations(function (accessor) { // For each active placeholder take one snippet and merge it // in that the placeholder (can be many for `$1foo$1foo`). Because // everything is sorted by editor selection we can simply remove // elements from the beginning of the array for (var _i = 0, _a = _this._placeholderGroups[_this._placeholderGroupsIdx]; _i < _a.length; _i++) { var placeholder = _a[_i]; var nested = others.shift(); console.assert(!nested._placeholderDecorations); // Massage placeholder-indicies of the nested snippet to be // sorted right after the insertion point. This ensures we move // through the placeholders in the correct order var indexLastPlaceholder = nested._snippet.placeholderInfo.last.index; for (var _b = 0, _c = nested._snippet.placeholderInfo.all; _b < _c.length; _b++) { var nestedPlaceholder = _c[_b]; if (nestedPlaceholder.isFinalTabstop) { nestedPlaceholder.index = placeholder.index + ((indexLastPlaceholder + 1) / _this._nestingLevel); } else { nestedPlaceholder.index = placeholder.index + (nestedPlaceholder.index / _this._nestingLevel); } } _this._snippet.replace(placeholder, nested._snippet.children); // Remove the placeholder at which position are inserting // the snippet and also remove its decoration. var id = _this._placeholderDecorations.get(placeholder); accessor.removeDecoration(id); _this._placeholderDecorations.delete(placeholder); // For each *new* placeholder we create decoration to monitor // how and if it grows/shrinks. for (var _d = 0, _e = nested._snippet.placeholders; _d < _e.length; _d++) { var placeholder_1 = _e[_d]; var placeholderOffset = nested._snippet.offset(placeholder_1); var placeholderLen = nested._snippet.fullLen(placeholder_1); var range = range_1.Range.fromPositions(model.getPositionAt(nested._offset + placeholderOffset), model.getPositionAt(nested._offset + placeholderOffset + placeholderLen)); var handle = accessor.addDecoration(range, OneSnippet._decor.inactive); _this._placeholderDecorations.set(placeholder_1, handle); } } // Last, re-create the placeholder groups by sorting placeholders by their index. _this._placeholderGroups = arrays_1.groupBy(_this._snippet.placeholders, snippetParser_1.Placeholder.compareByIndex); }); }; OneSnippet._decor = { active: textModel_1.ModelDecorationOptions.register({ stickiness: 0 /* AlwaysGrowsWhenTypingAtEdges */, className: 'snippet-placeholder' }), inactive: textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'snippet-placeholder' }), activeFinal: textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'finish-snippet-placeholder' }), inactiveFinal: textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'finish-snippet-placeholder' }), }; return OneSnippet; }()); exports.OneSnippet = OneSnippet; var _defaultOptions = { overwriteBefore: 0, overwriteAfter: 0, adjustWhitespace: true, clipboardText: undefined }; var SnippetSession = /** @class */ (function () { function SnippetSession(editor, template, options) { if (options === void 0) { options = _defaultOptions; } this._templateMerges = []; this._snippets = []; this._editor = editor; this._template = template; this._options = options; } SnippetSession.adjustWhitespace = function (model, position, snippet, adjustIndentation, adjustNewlines) { var line = model.getLineContent(position.lineNumber); var lineLeadingWhitespace = strings_1.getLeadingWhitespace(line, 0, position.column - 1); snippet.walk(function (marker) { if (marker instanceof snippetParser_1.Text && !(marker.parent instanceof snippetParser_1.Choice)) { // adjust indentation of text markers, except for choise elements // which get adjusted when being selected var lines = marker.value.split(/\r\n|\r|\n/); if (adjustIndentation) { for (var i = 1; i < lines.length; i++) { var templateLeadingWhitespace = strings_1.getLeadingWhitespace(lines[i]); lines[i] = model.normalizeIndentation(lineLeadingWhitespace + templateLeadingWhitespace) + lines[i].substr(templateLeadingWhitespace.length); } } if (adjustNewlines) { var newValue = lines.join(model.getEOL()); if (newValue !== marker.value) { marker.parent.replace(marker, [new snippetParser_1.Text(newValue)]); } } } return true; }); }; SnippetSession.adjustSelection = function (model, selection, overwriteBefore, overwriteAfter) { if (overwriteBefore !== 0 || overwriteAfter !== 0) { // overwrite[Before|After] is compute using the position, not the whole // selection. therefore we adjust the selection around that position var positionLineNumber = selection.positionLineNumber, positionColumn = selection.positionColumn; var positionColumnBefore = positionColumn - overwriteBefore; var positionColumnAfter = positionColumn + overwriteAfter; var range = model.validateRange({ startLineNumber: positionLineNumber, startColumn: positionColumnBefore, endLineNumber: positionLineNumber, endColumn: positionColumnAfter }); selection = selection_1.Selection.createWithDirection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn, selection.getDirection()); } return selection; }; SnippetSession.createEditsAndSnippets = function (editor, template, overwriteBefore, overwriteAfter, enforceFinalTabstop, adjustWhitespace, clipboardText) { var edits = []; var snippets = []; if (!editor.hasModel()) { return { edits: edits, snippets: snippets }; } var model = editor.getModel(); var workspaceService = editor.invokeWithinContext(function (accessor) { return accessor.get(workspace_1.IWorkspaceContextService, instantiation_1.optional); }); var modelBasedVariableResolver = editor.invokeWithinContext(function (accessor) { return new snippetVariables_1.ModelBasedVariableResolver(accessor.get(label_1.ILabelService, instantiation_1.optional), model); }); var clipboardService = editor.invokeWithinContext(function (accessor) { return accessor.get(clipboardService_1.IClipboardService, instantiation_1.optional); }); var readClipboardText = function () { return clipboardText || clipboardService && clipboardService.readTextSync(); }; var delta = 0; // know what text the overwrite[Before|After] extensions // of the primary curser have selected because only when // secondary selections extend to the same text we can grow them var firstBeforeText = model.getValueInRange(SnippetSession.adjustSelection(model, editor.getSelection(), overwriteBefore, 0)); var firstAfterText = model.getValueInRange(SnippetSession.adjustSelection(model, editor.getSelection(), 0, overwriteAfter)); // remember the first non-whitespace column to decide if // `keepWhitespace` should be overruled for secondary selections var firstLineFirstNonWhitespace = model.getLineFirstNonWhitespaceColumn(editor.getSelection().positionLineNumber); // sort selections by their start position but remeber // the original index. that allows you to create correct // offset-based selection logic without changing the // primary selection var indexedSelections = editor.getSelections() .map(function (selection, idx) { return ({ selection: selection, idx: idx }); }) .sort(function (a, b) { return range_1.Range.compareRangesUsingStarts(a.selection, b.selection); }); for (var _i = 0, indexedSelections_1 = indexedSelections; _i < indexedSelections_1.length; _i++) { var _a = indexedSelections_1[_i], selection = _a.selection, idx = _a.idx; // extend selection with the `overwriteBefore` and `overwriteAfter` and then // compare if this matches the extensions of the primary selection var extensionBefore = SnippetSession.adjustSelection(model, selection, overwriteBefore, 0); var extensionAfter = SnippetSession.adjustSelection(model, selection, 0, overwriteAfter); if (firstBeforeText !== model.getValueInRange(extensionBefore)) { extensionBefore = selection; } if (firstAfterText !== model.getValueInRange(extensionAfter)) { extensionAfter = selection; } // merge the before and after selection into one var snippetSelection = selection .setStartPosition(extensionBefore.startLineNumber, extensionBefore.startColumn) .setEndPosition(extensionAfter.endLineNumber, extensionAfter.endColumn); var snippet = new snippetParser_1.SnippetParser().parse(template, true, enforceFinalTabstop); // adjust the template string to match the indentation and // whitespace rules of this insert location (can be different for each cursor) // happens when being asked for (default) or when this is a secondary // cursor and the leading whitespace is different var start = snippetSelection.getStartPosition(); SnippetSession.adjustWhitespace(model, start, snippet, adjustWhitespace || (idx > 0 && firstLineFirstNonWhitespace !== model.getLineFirstNonWhitespaceColumn(selection.positionLineNumber)), true); snippet.resolveVariables(new snippetVariables_1.CompositeSnippetVariableResolver([ modelBasedVariableResolver, new snippetVariables_1.ClipboardBasedVariableResolver(readClipboardText, idx, indexedSelections.length, editor.getOption(60 /* multiCursorPaste */) === 'spread'), new snippetVariables_1.SelectionBasedVariableResolver(model, selection), new snippetVariables_1.CommentBasedVariableResolver(model), new snippetVariables_1.TimeBasedVariableResolver, new snippetVariables_1.WorkspaceBasedVariableResolver(workspaceService), new snippetVariables_1.RandomBasedVariableResolver, ])); var offset = model.getOffsetAt(start) + delta; delta += snippet.toString().length - model.getValueLengthInRange(snippetSelection); // store snippets with the index of their originating selection. // that ensures the primiary cursor stays primary despite not being // the one with lowest start position edits[idx] = editOperation_1.EditOperation.replace(snippetSelection, snippet.toString()); snippets[idx] = new OneSnippet(editor, snippet, offset); } return { edits: edits, snippets: snippets }; }; SnippetSession.prototype.dispose = function () { lifecycle_1.dispose(this._snippets); }; SnippetSession.prototype._logInfo = function () { return "template=\"" + this._template + "\", merged_templates=\"" + this._templateMerges.join(' -> ') + "\""; }; SnippetSession.prototype.insert = function () { var _this = this; if (!this._editor.hasModel()) { return; } // make insert edit and start with first selections var _a = SnippetSession.createEditsAndSnippets(this._editor, this._template, this._options.overwriteBefore, this._options.overwriteAfter, false, this._options.adjustWhitespace, this._options.clipboardText), edits = _a.edits, snippets = _a.snippets; this._snippets = snippets; this._editor.executeEdits('snippet', edits, function (undoEdits) { if (_this._snippets[0].hasPlaceholder) { return _this._move(true); } else { return undoEdits.map(function (edit) { return selection_1.Selection.fromPositions(edit.range.getEndPosition()); }); } }); this._editor.revealRange(this._editor.getSelections()[0]); }; SnippetSession.prototype.merge = function (template, options) { var _this = this; if (options === void 0) { options = _defaultOptions; } if (!this._editor.hasModel()) { return; } this._templateMerges.push([this._snippets[0]._nestingLevel, this._snippets[0]._placeholderGroupsIdx, template]); var _a = SnippetSession.createEditsAndSnippets(this._editor, template, options.overwriteBefore, options.overwriteAfter, true, options.adjustWhitespace, options.clipboardText), edits = _a.edits, snippets = _a.snippets; this._editor.executeEdits('snippet', edits, function (undoEdits) { for (var _i = 0, _a = _this._snippets; _i < _a.length; _i++) { var snippet = _a[_i]; snippet.merge(snippets); } console.assert(snippets.length === 0); if (_this._snippets[0].hasPlaceholder) { return _this._move(undefined); } else { return undoEdits.map(function (edit) { return selection_1.Selection.fromPositions(edit.range.getEndPosition()); }); } }); }; SnippetSession.prototype.next = function () { var newSelections = this._move(true); this._editor.setSelections(newSelections); this._editor.revealPositionInCenterIfOutsideViewport(newSelections[0].getPosition()); }; SnippetSession.prototype.prev = function () { var newSelections = this._move(false); this._editor.setSelections(newSelections); this._editor.revealPositionInCenterIfOutsideViewport(newSelections[0].getPosition()); }; SnippetSession.prototype._move = function (fwd) { var selections = []; for (var _i = 0, _a = this._snippets; _i < _a.length; _i++) { var snippet = _a[_i]; var oneSelection = snippet.move(fwd); selections.push.apply(selections, oneSelection); } return selections; }; Object.defineProperty(SnippetSession.prototype, "isAtFirstPlaceholder", { get: function () { return this._snippets[0].isAtFirstPlaceholder; }, enumerable: true, configurable: true }); Object.defineProperty(SnippetSession.prototype, "isAtLastPlaceholder", { get: function () { return this._snippets[0].isAtLastPlaceholder; }, enumerable: true, configurable: true }); Object.defineProperty(SnippetSession.prototype, "hasPlaceholder", { get: function () { return this._snippets[0].hasPlaceholder; }, enumerable: true, configurable: true }); Object.defineProperty(SnippetSession.prototype, "choice", { get: function () { return this._snippets[0].choice; }, enumerable: true, configurable: true }); SnippetSession.prototype.isSelectionWithinPlaceholders = function () { if (!this.hasPlaceholder) { return false; } var selections = this._editor.getSelections(); if (selections.length < this._snippets.length) { // this means we started snippet mode with N // selections and have M (N > M) selections. // So one snippet is without selection -> cancel return false; } var allPossibleSelections = new Map(); var _loop_1 = function (snippet) { var possibleSelections = snippet.computePossibleSelections(); // for the first snippet find the placeholder (and its ranges) // that contain at least one selection. for all remaining snippets // the same placeholder (and their ranges) must be used. if (allPossibleSelections.size === 0) { possibleSelections.forEach(function (ranges, index) { ranges.sort(range_1.Range.compareRangesUsingStarts); for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) { var selection = selections_1[_i]; if (ranges[0].containsRange(selection)) { allPossibleSelections.set(index, []); break; } } }); } if (allPossibleSelections.size === 0) { return { value: false }; } // add selections from 'this' snippet so that we know all // selections for this placeholder allPossibleSelections.forEach(function (array, index) { array.push.apply(array, possibleSelections.get(index)); }); }; for (var _i = 0, _a = this._snippets; _i < _a.length; _i++) { var snippet = _a[_i]; var state_1 = _loop_1(snippet); if (typeof state_1 === "object") return state_1.value; } // sort selections (and later placeholder-ranges). then walk both // arrays and make sure the placeholder-ranges contain the corresponding // selection selections.sort(range_1.Range.compareRangesUsingStarts); allPossibleSelections.forEach(function (ranges, index) { if (ranges.length !== selections.length) { allPossibleSelections.delete(index); return; } ranges.sort(range_1.Range.compareRangesUsingStarts); for (var i = 0; i < ranges.length; i++) { if (!ranges[i].containsRange(selections[i])) { allPossibleSelections.delete(index); return; } } }); // from all possible selections we have deleted those // that don't match with the current selection. if we don't // have any left, we don't have a selection anymore return allPossibleSelections.size > 0; }; return SnippetSession; }()); exports.SnippetSession = SnippetSession; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[173/*vs/editor/contrib/snippet/snippetController2*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,12/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,23/*vs/editor/common/editorContextKeys*/,120/*vs/editor/contrib/suggest/suggest*/,18/*vs/platform/contextkey/common/contextkey*/,95/*vs/platform/log/common/log*/,608/*vs/editor/contrib/snippet/snippetSession*/]), function (require, exports, lifecycle_1, strings_1, editorExtensions_1, range_1, selection_1, editorContextKeys_1, suggest_1, contextkey_1, log_1, snippetSession_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _defaultOptions = { overwriteBefore: 0, overwriteAfter: 0, undoStopBefore: true, undoStopAfter: true, adjustWhitespace: true, clipboardText: undefined }; var SnippetController2 = /** @class */ (function () { function SnippetController2(_editor, _logService, contextKeyService) { this._editor = _editor; this._logService = _logService; this._snippetListener = new lifecycle_1.DisposableStore(); this._modelVersionId = -1; this._inSnippet = SnippetController2.InSnippetMode.bindTo(contextKeyService); this._hasNextTabstop = SnippetController2.HasNextTabstop.bindTo(contextKeyService); this._hasPrevTabstop = SnippetController2.HasPrevTabstop.bindTo(contextKeyService); } SnippetController2.get = function (editor) { return editor.getContribution(SnippetController2.ID); }; SnippetController2.prototype.dispose = function () { this._inSnippet.reset(); this._hasPrevTabstop.reset(); this._hasNextTabstop.reset(); lifecycle_1.dispose(this._session); this._snippetListener.dispose(); }; SnippetController2.prototype.insert = function (template, opts) { // this is here to find out more about the yet-not-understood // error that sometimes happens when we fail to inserted a nested // snippet try { this._doInsert(template, typeof opts === 'undefined' ? _defaultOptions : __assign(__assign({}, _defaultOptions), opts)); } catch (e) { this.cancel(); this._logService.error(e); this._logService.error('snippet_error'); this._logService.error('insert_template=', template); this._logService.error('existing_template=', this._session ? this._session._logInfo() : ''); } }; SnippetController2.prototype._doInsert = function (template, opts) { var _this = this; if (!this._editor.hasModel()) { return; } // don't listen while inserting the snippet // as that is the inflight state causing cancelation this._snippetListener.clear(); if (opts.undoStopBefore) { this._editor.getModel().pushStackElement(); } if (!this._session) { this._modelVersionId = this._editor.getModel().getAlternativeVersionId(); this._session = new snippetSession_1.SnippetSession(this._editor, template, opts); this._session.insert(); } else { this._session.merge(template, opts); } if (opts.undoStopAfter) { this._editor.getModel().pushStackElement(); } this._updateState(); this._snippetListener.add(this._editor.onDidChangeModelContent(function (e) { return e.isFlush && _this.cancel(); })); this._snippetListener.add(this._editor.onDidChangeModel(function () { return _this.cancel(); })); this._snippetListener.add(this._editor.onDidChangeCursorSelection(function () { return _this._updateState(); })); }; SnippetController2.prototype._updateState = function () { if (!this._session || !this._editor.hasModel()) { // canceled in the meanwhile return; } if (this._modelVersionId === this._editor.getModel().getAlternativeVersionId()) { // undo until the 'before' state happened // and makes use cancel snippet mode return this.cancel(); } if (!this._session.hasPlaceholder) { // don't listen for selection changes and don't // update context keys when the snippet is plain text return this.cancel(); } if (this._session.isAtLastPlaceholder || !this._session.isSelectionWithinPlaceholders()) { return this.cancel(); } this._inSnippet.set(true); this._hasPrevTabstop.set(!this._session.isAtFirstPlaceholder); this._hasNextTabstop.set(!this._session.isAtLastPlaceholder); this._handleChoice(); }; SnippetController2.prototype._handleChoice = function () { var _this = this; if (!this._session || !this._editor.hasModel()) { this._currentChoice = undefined; return; } var choice = this._session.choice; if (!choice) { this._currentChoice = undefined; return; } if (this._currentChoice !== choice) { this._currentChoice = choice; this._editor.setSelections(this._editor.getSelections() .map(function (s) { return selection_1.Selection.fromPositions(s.getStartPosition()); })); var first_1 = choice.options[0]; suggest_1.showSimpleSuggestions(this._editor, choice.options.map(function (option, i) { // let before = choice.options.slice(0, i); // let after = choice.options.slice(i); return { kind: 13 /* Value */, label: option.value, insertText: option.value, // insertText: `\${1|${after.concat(before).join(',')}|}$0`, // snippetType: 'textmate', sortText: strings_1.repeat('a', i + 1), range: range_1.Range.fromPositions(_this._editor.getPosition(), _this._editor.getPosition().delta(0, first_1.value.length)) }; })); } }; SnippetController2.prototype.finish = function () { while (this._inSnippet.get()) { this.next(); } }; SnippetController2.prototype.cancel = function (resetSelection) { if (resetSelection === void 0) { resetSelection = false; } this._inSnippet.reset(); this._hasPrevTabstop.reset(); this._hasNextTabstop.reset(); this._snippetListener.clear(); lifecycle_1.dispose(this._session); this._session = undefined; this._modelVersionId = -1; if (resetSelection) { // reset selection to the primary cursor when being asked // for. this happens when explicitly cancelling snippet mode, // e.g. when pressing ESC this._editor.setSelections([this._editor.getSelection()]); } }; SnippetController2.prototype.prev = function () { if (this._session) { this._session.prev(); } this._updateState(); }; SnippetController2.prototype.next = function () { if (this._session) { this._session.next(); } this._updateState(); }; SnippetController2.prototype.isInSnippet = function () { return Boolean(this._inSnippet.get()); }; SnippetController2.ID = 'snippetController2'; SnippetController2.InSnippetMode = new contextkey_1.RawContextKey('inSnippetMode', false); SnippetController2.HasNextTabstop = new contextkey_1.RawContextKey('hasNextTabstop', false); SnippetController2.HasPrevTabstop = new contextkey_1.RawContextKey('hasPrevTabstop', false); SnippetController2 = __decorate([ __param(1, log_1.ILogService), __param(2, contextkey_1.IContextKeyService) ], SnippetController2); return SnippetController2; }()); exports.SnippetController2 = SnippetController2; editorExtensions_1.registerEditorContribution(SnippetController2.ID, SnippetController2); var CommandCtor = editorExtensions_1.EditorCommand.bindToContribution(SnippetController2.get); editorExtensions_1.registerEditorCommand(new CommandCtor({ id: 'jumpToNextSnippetPlaceholder', precondition: contextkey_1.ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasNextTabstop), handler: function (ctrl) { return ctrl.next(); }, kbOpts: { weight: 100 /* EditorContrib */ + 30, kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2 /* Tab */ } })); editorExtensions_1.registerEditorCommand(new CommandCtor({ id: 'jumpToPrevSnippetPlaceholder', precondition: contextkey_1.ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasPrevTabstop), handler: function (ctrl) { return ctrl.prev(); }, kbOpts: { weight: 100 /* EditorContrib */ + 30, kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 1024 /* Shift */ | 2 /* Tab */ } })); editorExtensions_1.registerEditorCommand(new CommandCtor({ id: 'leaveSnippet', precondition: SnippetController2.InSnippetMode, handler: function (ctrl) { return ctrl.cancel(true); }, kbOpts: { weight: 100 /* EditorContrib */ + 30, kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 9 /* Escape */, secondary: [1024 /* Shift */ | 9 /* Escape */] } })); editorExtensions_1.registerEditorCommand(new CommandCtor({ id: 'acceptSnippet', precondition: SnippetController2.InSnippetMode, handler: function (ctrl) { return ctrl.finish(); }, })); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[609/*vs/editor/contrib/suggest/suggestModel*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,15/*vs/base/common/async*/,10/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,22/*vs/editor/common/core/selection*/,17/*vs/editor/common/modes*/,389/*vs/editor/contrib/suggest/completionModel*/,120/*vs/editor/contrib/suggest/suggest*/,173/*vs/editor/contrib/snippet/snippetController2*/,26/*vs/base/common/cancellation*/,392/*vs/editor/contrib/suggest/wordDistance*/,5/*vs/base/common/strings*/]), function (require, exports, arrays_1, async_1, errors_1, event_1, lifecycle_1, selection_1, modes_1, completionModel_1, suggest_1, snippetController2_1, cancellation_1, wordDistance_1, strings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LineContext = /** @class */ (function () { function LineContext(model, position, auto, shy) { this.leadingLineContent = model.getLineContent(position.lineNumber).substr(0, position.column - 1); this.leadingWord = model.getWordUntilPosition(position); this.lineNumber = position.lineNumber; this.column = position.column; this.auto = auto; this.shy = shy; } LineContext.shouldAutoTrigger = function (editor) { if (!editor.hasModel()) { return false; } var model = editor.getModel(); var pos = editor.getPosition(); model.tokenizeIfCheap(pos.lineNumber); var word = model.getWordAtPosition(pos); if (!word) { return false; } if (word.endColumn !== pos.column) { return false; } if (!isNaN(Number(word.word))) { return false; } return true; }; return LineContext; }()); exports.LineContext = LineContext; var SuggestModel = /** @class */ (function () { function SuggestModel(_editor, _editorWorker) { var _this = this; this._editor = _editor; this._editorWorker = _editorWorker; this._toDispose = new lifecycle_1.DisposableStore(); this._quickSuggestDelay = 10; this._triggerCharacterListener = new lifecycle_1.DisposableStore(); this._triggerQuickSuggest = new async_1.TimeoutTimer(); this._state = 0 /* Idle */; this._completionDisposables = new lifecycle_1.DisposableStore(); this._onDidCancel = new event_1.Emitter(); this._onDidTrigger = new event_1.Emitter(); this._onDidSuggest = new event_1.Emitter(); this.onDidCancel = this._onDidCancel.event; this.onDidTrigger = this._onDidTrigger.event; this.onDidSuggest = this._onDidSuggest.event; this._currentSelection = this._editor.getSelection() || new selection_1.Selection(1, 1, 1, 1); // wire up various listeners this._toDispose.add(this._editor.onDidChangeModel(function () { _this._updateTriggerCharacters(); _this.cancel(); })); this._toDispose.add(this._editor.onDidChangeModelLanguage(function () { _this._updateTriggerCharacters(); _this.cancel(); })); this._toDispose.add(this._editor.onDidChangeConfiguration(function () { _this._updateTriggerCharacters(); _this._updateQuickSuggest(); })); this._toDispose.add(modes_1.CompletionProviderRegistry.onDidChange(function () { _this._updateTriggerCharacters(); _this._updateActiveSuggestSession(); })); this._toDispose.add(this._editor.onDidChangeCursorSelection(function (e) { _this._onCursorChange(e); })); var editorIsComposing = false; this._toDispose.add(this._editor.onDidCompositionStart(function () { editorIsComposing = true; })); this._toDispose.add(this._editor.onDidCompositionEnd(function () { // refilter when composition ends editorIsComposing = false; _this._refilterCompletionItems(); })); this._toDispose.add(this._editor.onDidChangeModelContent(function () { // only filter completions when the editor isn't // composing a character, e.g. ¨ + u makes ü but just // ¨ cannot be used for filtering if (!editorIsComposing) { _this._refilterCompletionItems(); } })); this._updateTriggerCharacters(); this._updateQuickSuggest(); } SuggestModel.prototype.dispose = function () { lifecycle_1.dispose(this._triggerCharacterListener); lifecycle_1.dispose([this._onDidCancel, this._onDidSuggest, this._onDidTrigger, this._triggerQuickSuggest]); this._toDispose.dispose(); this._completionDisposables.dispose(); this.cancel(); }; // --- handle configuration & precondition changes SuggestModel.prototype._updateQuickSuggest = function () { this._quickSuggestDelay = this._editor.getOption(67 /* quickSuggestionsDelay */); if (isNaN(this._quickSuggestDelay) || (!this._quickSuggestDelay && this._quickSuggestDelay !== 0) || this._quickSuggestDelay < 0) { this._quickSuggestDelay = 10; } }; SuggestModel.prototype._updateTriggerCharacters = function () { var _this = this; this._triggerCharacterListener.clear(); if (this._editor.getOption(68 /* readOnly */) || !this._editor.hasModel() || !this._editor.getOption(92 /* suggestOnTriggerCharacters */)) { return; } var supportsByTriggerCharacter = new Map(); for (var _i = 0, _a = modes_1.CompletionProviderRegistry.all(this._editor.getModel()); _i < _a.length; _i++) { var support = _a[_i]; for (var _b = 0, _c = support.triggerCharacters || []; _b < _c.length; _b++) { var ch = _c[_b]; var set = supportsByTriggerCharacter.get(ch); if (!set) { set = new Set(); set.add(suggest_1.getSnippetSuggestSupport()); supportsByTriggerCharacter.set(ch, set); } set.add(support); } } var checkTriggerCharacter = function (text) { if (!text) { // came here from the compositionEnd-event var position = _this._editor.getPosition(); var model = _this._editor.getModel(); text = model.getLineContent(position.lineNumber).substr(0, position.column - 1); } var lastChar = ''; if (strings_1.isLowSurrogate(text.charCodeAt(text.length - 1))) { if (strings_1.isHighSurrogate(text.charCodeAt(text.length - 2))) { lastChar = text.substr(text.length - 2); } } else { lastChar = text.charAt(text.length - 1); } var supports = supportsByTriggerCharacter.get(lastChar); if (supports) { // keep existing items that where not computed by the // supports/providers that want to trigger now var items = _this._completionModel ? _this._completionModel.adopt(supports) : undefined; _this.trigger({ auto: true, shy: false, triggerCharacter: lastChar }, Boolean(_this._completionModel), supports, items); } }; this._triggerCharacterListener.add(this._editor.onDidType(checkTriggerCharacter)); this._triggerCharacterListener.add(this._editor.onDidCompositionEnd(checkTriggerCharacter)); }; Object.defineProperty(SuggestModel.prototype, "state", { // --- trigger/retrigger/cancel suggest get: function () { return this._state; }, enumerable: true, configurable: true }); SuggestModel.prototype.cancel = function (retrigger) { if (retrigger === void 0) { retrigger = false; } if (this._state !== 0 /* Idle */) { this._triggerQuickSuggest.cancel(); if (this._requestToken) { this._requestToken.cancel(); this._requestToken = undefined; } this._state = 0 /* Idle */; this._completionModel = undefined; this._context = undefined; this._onDidCancel.fire({ retrigger: retrigger }); } }; SuggestModel.prototype.clear = function () { this._completionDisposables.clear(); }; SuggestModel.prototype._updateActiveSuggestSession = function () { if (this._state !== 0 /* Idle */) { if (!this._editor.hasModel() || !modes_1.CompletionProviderRegistry.has(this._editor.getModel())) { this.cancel(); } else { this.trigger({ auto: this._state === 2 /* Auto */, shy: false }, true); } } }; SuggestModel.prototype._onCursorChange = function (e) { var _this = this; if (!this._editor.hasModel()) { return; } var model = this._editor.getModel(); var prevSelection = this._currentSelection; this._currentSelection = this._editor.getSelection(); if (!e.selection.isEmpty() || e.reason !== 0 /* NotSet */ || (e.source !== 'keyboard' && e.source !== 'deleteLeft')) { // Early exit if nothing needs to be done! // Leave some form of early exit check here if you wish to continue being a cursor position change listener ;) this.cancel(); return; } if (!modes_1.CompletionProviderRegistry.has(model)) { return; } if (this._state === 0 /* Idle */) { if (this._editor.getOption(66 /* quickSuggestions */) === false) { // not enabled return; } if (!prevSelection.containsRange(this._currentSelection) && !prevSelection.getEndPosition().isBeforeOrEqual(this._currentSelection.getPosition())) { // cursor didn't move RIGHT return; } if (this._editor.getOption(89 /* suggest */).snippetsPreventQuickSuggestions && snippetController2_1.SnippetController2.get(this._editor).isInSnippet()) { // no quick suggestion when in snippet mode return; } this.cancel(); this._triggerQuickSuggest.cancelAndSet(function () { if (_this._state !== 0 /* Idle */) { return; } if (!LineContext.shouldAutoTrigger(_this._editor)) { return; } if (!_this._editor.hasModel()) { return; } var model = _this._editor.getModel(); var pos = _this._editor.getPosition(); // validate enabled now var quickSuggestions = _this._editor.getOption(66 /* quickSuggestions */); if (quickSuggestions === false) { return; } else if (quickSuggestions === true) { // all good } else { // Check the type of the token that triggered this model.tokenizeIfCheap(pos.lineNumber); var lineTokens = model.getLineTokens(pos.lineNumber); var tokenType = lineTokens.getStandardTokenType(lineTokens.findTokenIndexAtOffset(Math.max(pos.column - 1 - 1, 0))); var inValidScope = quickSuggestions.other && tokenType === 0 /* Other */ || quickSuggestions.comments && tokenType === 1 /* Comment */ || quickSuggestions.strings && tokenType === 2 /* String */; if (!inValidScope) { return; } } // we made it till here -> trigger now _this.trigger({ auto: true, shy: false }); }, this._quickSuggestDelay); } }; SuggestModel.prototype._refilterCompletionItems = function () { var _this = this; // Re-filter suggestions. This MUST run async because filtering/scoring // uses the model content AND the cursor position. The latter is NOT // updated when the document has changed (the event which drives this method) // and therefore a little pause (next mirco task) is needed. See: // https://stackoverflow.com/questions/25915634/difference-between-microtask-and-macrotask-within-an-event-loop-context#25933985 Promise.resolve().then(function () { if (_this._state === 0 /* Idle */) { return; } if (!_this._editor.hasModel()) { return; } var model = _this._editor.getModel(); var position = _this._editor.getPosition(); var ctx = new LineContext(model, position, _this._state === 2 /* Auto */, false); _this._onNewContext(ctx); }); }; SuggestModel.prototype.trigger = function (context, retrigger, onlyFrom, existingItems) { var _this = this; if (retrigger === void 0) { retrigger = false; } if (!this._editor.hasModel()) { return; } var model = this._editor.getModel(); var auto = context.auto; var ctx = new LineContext(model, this._editor.getPosition(), auto, context.shy); // Cancel previous requests, change state & update UI this.cancel(retrigger); this._state = auto ? 2 /* Auto */ : 1 /* Manual */; this._onDidTrigger.fire({ auto: auto, shy: context.shy, position: this._editor.getPosition() }); // Capture context when request was sent this._context = ctx; // Build context for request var suggestCtx; if (context.triggerCharacter) { suggestCtx = { triggerKind: 1 /* TriggerCharacter */, triggerCharacter: context.triggerCharacter }; } else if (onlyFrom && onlyFrom.size > 0) { suggestCtx = { triggerKind: 2 /* TriggerForIncompleteCompletions */ }; } else { suggestCtx = { triggerKind: 0 /* Invoke */ }; } this._requestToken = new cancellation_1.CancellationTokenSource(); // kind filter and snippet sort rules var snippetSuggestions = this._editor.getOption(86 /* snippetSuggestions */); var snippetSortOrder = 1 /* Inline */; switch (snippetSuggestions) { case 'top': snippetSortOrder = 0 /* Top */; break; // ↓ that's the default anyways... // case 'inline': // snippetSortOrder = SnippetSortOrder.Inline; // break; case 'bottom': snippetSortOrder = 2 /* Bottom */; break; } var itemKindFilter = SuggestModel._createItemKindFilter(this._editor); var wordDistance = wordDistance_1.WordDistance.create(this._editorWorker, this._editor); var items = suggest_1.provideSuggestionItems(model, this._editor.getPosition(), new suggest_1.CompletionOptions(snippetSortOrder, itemKindFilter, onlyFrom), suggestCtx, this._requestToken.token); Promise.all([items, wordDistance]).then(function (_a) { var items = _a[0], wordDistance = _a[1]; lifecycle_1.dispose(_this._requestToken); if (_this._state === 0 /* Idle */) { return; } if (!_this._editor.hasModel()) { return; } var model = _this._editor.getModel(); if (arrays_1.isNonEmptyArray(existingItems)) { var cmpFn = suggest_1.getSuggestionComparator(snippetSortOrder); items = items.concat(existingItems).sort(cmpFn); } var ctx = new LineContext(model, _this._editor.getPosition(), auto, context.shy); _this._completionModel = new completionModel_1.CompletionModel(items, _this._context.column, { leadingLineContent: ctx.leadingLineContent, characterCountDelta: ctx.column - _this._context.column }, wordDistance, _this._editor.getOption(89 /* suggest */), _this._editor.getOption(86 /* snippetSuggestions */)); // store containers so that they can be disposed later for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { var item = items_1[_i]; if (lifecycle_1.isDisposable(item.container)) { _this._completionDisposables.add(item.container); } } _this._onNewContext(ctx); }).catch(errors_1.onUnexpectedError); }; SuggestModel._createItemKindFilter = function (editor) { // kind filter and snippet sort rules var result = new Set(); // snippet setting var snippetSuggestions = editor.getOption(86 /* snippetSuggestions */); if (snippetSuggestions === 'none') { result.add(25 /* Snippet */); } // type setting var suggestOptions = editor.getOption(89 /* suggest */); if (!suggestOptions.showMethods) { result.add(0 /* Method */); } if (!suggestOptions.showFunctions) { result.add(1 /* Function */); } if (!suggestOptions.showConstructors) { result.add(2 /* Constructor */); } if (!suggestOptions.showFields) { result.add(3 /* Field */); } if (!suggestOptions.showVariables) { result.add(4 /* Variable */); } if (!suggestOptions.showClasses) { result.add(5 /* Class */); } if (!suggestOptions.showStructs) { result.add(6 /* Struct */); } if (!suggestOptions.showInterfaces) { result.add(7 /* Interface */); } if (!suggestOptions.showModules) { result.add(8 /* Module */); } if (!suggestOptions.showProperties) { result.add(9 /* Property */); } if (!suggestOptions.showEvents) { result.add(10 /* Event */); } if (!suggestOptions.showOperators) { result.add(11 /* Operator */); } if (!suggestOptions.showUnits) { result.add(12 /* Unit */); } if (!suggestOptions.showValues) { result.add(13 /* Value */); } if (!suggestOptions.showConstants) { result.add(14 /* Constant */); } if (!suggestOptions.showEnums) { result.add(15 /* Enum */); } if (!suggestOptions.showEnumMembers) { result.add(16 /* EnumMember */); } if (!suggestOptions.showKeywords) { result.add(17 /* Keyword */); } if (!suggestOptions.showWords) { result.add(18 /* Text */); } if (!suggestOptions.showColors) { result.add(19 /* Color */); } if (!suggestOptions.showFiles) { result.add(20 /* File */); } if (!suggestOptions.showReferences) { result.add(21 /* Reference */); } if (!suggestOptions.showColors) { result.add(22 /* Customcolor */); } if (!suggestOptions.showFolders) { result.add(23 /* Folder */); } if (!suggestOptions.showTypeParameters) { result.add(24 /* TypeParameter */); } if (!suggestOptions.showSnippets) { result.add(25 /* Snippet */); } return result; }; SuggestModel.prototype._onNewContext = function (ctx) { if (!this._context) { // happens when 24x7 IntelliSense is enabled and still in its delay return; } if (ctx.lineNumber !== this._context.lineNumber) { // e.g. happens when pressing Enter while IntelliSense is computed this.cancel(); return; } if (ctx.leadingWord.startColumn < this._context.leadingWord.startColumn) { // happens when the current word gets outdented this.cancel(); return; } if (ctx.column < this._context.column) { // typed -> moved cursor LEFT -> retrigger if still on a word if (ctx.leadingWord.word) { this.trigger({ auto: this._context.auto, shy: false }, true); } else { this.cancel(); } return; } if (!this._completionModel) { // happens when IntelliSense is not yet computed return; } if (ctx.column > this._context.column && this._completionModel.incomplete.size > 0 && ctx.leadingWord.word.length !== 0) { // typed -> moved cursor RIGHT & incomple model & still on a word -> retrigger var incomplete = this._completionModel.incomplete; var adopted = this._completionModel.adopt(incomplete); this.trigger({ auto: this._state === 2 /* Auto */, shy: false }, true, incomplete, adopted); } else { // typed -> moved cursor RIGHT -> update UI var oldLineContext = this._completionModel.lineContext; var isFrozen = false; this._completionModel.lineContext = { leadingLineContent: ctx.leadingLineContent, characterCountDelta: ctx.column - this._context.column }; if (this._completionModel.items.length === 0) { if (LineContext.shouldAutoTrigger(this._editor) && this._context.leadingWord.endColumn < ctx.leadingWord.startColumn) { // retrigger when heading into a new word this.trigger({ auto: this._context.auto, shy: false }, true); return; } if (!this._context.auto) { // freeze when IntelliSense was manually requested this._completionModel.lineContext = oldLineContext; isFrozen = this._completionModel.items.length > 0; if (isFrozen && ctx.leadingWord.word.length === 0) { // there were results before but now there aren't // and also we are not on a word anymore -> cancel this.cancel(); return; } } else { // nothing left this.cancel(); return; } } this._onDidSuggest.fire({ completionModel: this._completionModel, auto: this._context.auto, shy: this._context.shy, isFrozen: isFrozen, }); } }; return SuggestModel; }()); exports.SuggestModel = SuggestModel; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 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; }; define(__m[610/*vs/editor/contrib/suggest/suggestController*/], __M([0/*require*/,1/*exports*/,50/*vs/base/browser/ui/aria/aria*/,19/*vs/base/common/arrays*/,10/*vs/base/common/errors*/,36/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,12/*vs/editor/browser/editorExtensions*/,58/*vs/editor/common/core/editOperation*/,3/*vs/editor/common/core/range*/,23/*vs/editor/common/editorContextKeys*/,173/*vs/editor/contrib/snippet/snippetController2*/,151/*vs/editor/contrib/snippet/snippetParser*/,521/*vs/editor/contrib/suggest/suggestMemory*/,467/*vs/nls!vs/editor/contrib/suggest/suggestController*/,29/*vs/platform/commands/common/commands*/,18/*vs/platform/contextkey/common/contextkey*/,11/*vs/platform/instantiation/common/instantiation*/,86/*vs/platform/keybinding/common/keybindingsRegistry*/,120/*vs/editor/contrib/suggest/suggest*/,497/*vs/editor/contrib/suggest/suggestAlternatives*/,609/*vs/editor/contrib/suggest/suggestModel*/,585/*vs/editor/contrib/suggest/suggestWidget*/,498/*vs/editor/contrib/suggest/wordContextKey*/,4/*vs/base/common/event*/,62/*vs/editor/common/services/editorWorkerService*/,15/*vs/base/common/async*/,21/*vs/base/common/types*/,390/*vs/editor/contrib/suggest/suggestCommitCharacters*/,16/*vs/base/common/platform*/,391/*vs/editor/contrib/suggest/suggestRangeHighlighter*/]), function (require, exports, aria_1, arrays_1, errors_1, keyCodes_1, lifecycle_1, editorExtensions_1, editOperation_1, range_1, editorContextKeys_1, snippetController2_1, snippetParser_1, suggestMemory_1, nls, commands_1, contextkey_1, instantiation_1, keybindingsRegistry_1, suggest_1, suggestAlternatives_1, suggestModel_1, suggestWidget_1, wordContextKey_1, event_1, editorWorkerService_1, async_1, types_1, suggestCommitCharacters_1, platform, suggestRangeHighlighter_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Stop suggest widget from disappearing when clicking into other areas * For development purpose only */ var _sticky = false; var LineSuffix = /** @class */ (function () { function LineSuffix(_model, _position) { this._model = _model; this._position = _position; // spy on what's happening right of the cursor. two cases: // 1. end of line -> check that it's still end of line // 2. mid of line -> add a marker and compute the delta var maxColumn = _model.getLineMaxColumn(_position.lineNumber); if (maxColumn !== _position.column) { var offset = _model.getOffsetAt(_position); var end = _model.getPositionAt(offset + 1); this._marker = _model.deltaDecorations([], [{ range: range_1.Range.fromPositions(_position, end), options: { stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ } }]); } } LineSuffix.prototype.dispose = function () { if (this._marker && !this._model.isDisposed()) { this._model.deltaDecorations(this._marker, []); } }; LineSuffix.prototype.delta = function (position) { if (this._model.isDisposed() || this._position.lineNumber !== position.lineNumber) { // bail out early if things seems fishy return 0; } // read the marker (in case suggest was triggered at line end) or compare // the cursor to the line end. if (this._marker) { var range = this._model.getDecorationRange(this._marker[0]); var end = this._model.getOffsetAt(range.getStartPosition()); return end - this._model.getOffsetAt(position); } else { return this._model.getLineMaxColumn(position.lineNumber) - position.column; } }; return LineSuffix; }()); var SuggestController = /** @class */ (function () { function SuggestController(editor, editorWorker, _memoryService, _commandService, _contextKeyService, _instantiationService) { var _this = this; this._memoryService = _memoryService; this._commandService = _commandService; this._contextKeyService = _contextKeyService; this._instantiationService = _instantiationService; this._lineSuffix = new lifecycle_1.MutableDisposable(); this._toDispose = new lifecycle_1.DisposableStore(); this.editor = editor; this.model = new suggestModel_1.SuggestModel(this.editor, editorWorker); this.widget = this._toDispose.add(new async_1.IdleValue(function () { var widget = _this._instantiationService.createInstance(suggestWidget_1.SuggestWidget, _this.editor); _this._toDispose.add(widget); _this._toDispose.add(widget.onDidSelect(function (item) { return _this._insertSuggestion(item, 0); }, _this)); // Wire up logic to accept a suggestion on certain characters var commitCharacterController = new suggestCommitCharacters_1.CommitCharacterController(_this.editor, widget, function (item) { return _this._insertSuggestion(item, 2 /* NoAfterUndoStop */); }); _this._toDispose.add(commitCharacterController); _this._toDispose.add(_this.model.onDidSuggest(function (e) { if (e.completionModel.items.length === 0) { commitCharacterController.reset(); } })); // Wire up makes text edit context key var makesTextEdit = suggest_1.Context.MakesTextEdit.bindTo(_this._contextKeyService); _this._toDispose.add(widget.onDidFocus(function (_a) { var item = _a.item; var position = _this.editor.getPosition(); var startColumn = item.editStart.column; var endColumn = position.column; var value = true; if (_this.editor.getOption(1 /* acceptSuggestionOnEnter */) === 'smart' && _this.model.state === 2 /* Auto */ && !item.completion.command && !item.completion.additionalTextEdits && !(item.completion.insertTextRules & 4 /* InsertAsSnippet */) && endColumn - startColumn === item.completion.insertText.length) { var oldText = _this.editor.getModel().getValueInRange({ startLineNumber: position.lineNumber, startColumn: startColumn, endLineNumber: position.lineNumber, endColumn: endColumn }); value = oldText !== item.completion.insertText; } makesTextEdit.set(value); })); _this._toDispose.add(lifecycle_1.toDisposable(function () { return makesTextEdit.reset(); })); _this._toDispose.add(widget.onDetailsKeyDown(function (e) { // cmd + c on macOS, ctrl + c on Win / Linux if (e.toKeybinding().equals(new keyCodes_1.SimpleKeybinding(true, false, false, false, 33 /* KEY_C */)) || (platform.isMacintosh && e.toKeybinding().equals(new keyCodes_1.SimpleKeybinding(false, false, false, true, 33 /* KEY_C */)))) { e.stopPropagation(); return; } if (!e.toKeybinding().isModifierKey()) { _this.editor.focus(); } })); return widget; })); this._alternatives = this._toDispose.add(new async_1.IdleValue(function () { return _this._toDispose.add(new suggestAlternatives_1.SuggestAlternatives(_this.editor, _this._contextKeyService)); })); this._toDispose.add(_instantiationService.createInstance(wordContextKey_1.WordContextKey, editor)); this._toDispose.add(this.model.onDidTrigger(function (e) { _this.widget.getValue().showTriggered(e.auto, e.shy ? 250 : 50); _this._lineSuffix.value = new LineSuffix(_this.editor.getModel(), e.position); })); this._toDispose.add(this.model.onDidSuggest(function (e) { if (!e.shy) { var index = _this._memoryService.select(_this.editor.getModel(), _this.editor.getPosition(), e.completionModel.items); _this.widget.getValue().showSuggestions(e.completionModel, index, e.isFrozen, e.auto); } })); this._toDispose.add(this.model.onDidCancel(function (e) { if (!e.retrigger) { _this.widget.getValue().hideWidget(); } })); this._toDispose.add(this.editor.onDidBlurEditorWidget(function () { if (!_sticky) { _this.model.cancel(); _this.model.clear(); } })); // Manage the acceptSuggestionsOnEnter context key var acceptSuggestionsOnEnter = suggest_1.Context.AcceptSuggestionsOnEnter.bindTo(_contextKeyService); var updateFromConfig = function () { var acceptSuggestionOnEnter = _this.editor.getOption(1 /* acceptSuggestionOnEnter */); acceptSuggestionsOnEnter.set(acceptSuggestionOnEnter === 'on' || acceptSuggestionOnEnter === 'smart'); }; this._toDispose.add(this.editor.onDidChangeConfiguration(function () { return updateFromConfig(); })); updateFromConfig(); // create range highlighter this._toDispose.add(new suggestRangeHighlighter_1.SuggestRangeHighlighter(this)); } SuggestController.get = function (editor) { return editor.getContribution(SuggestController.ID); }; SuggestController.prototype.dispose = function () { this._alternatives.dispose(); this._toDispose.dispose(); this.widget.dispose(); this.model.dispose(); this._lineSuffix.dispose(); }; SuggestController.prototype._insertSuggestion = function (event, flags) { var _a; var _this = this; if (!event || !event.item) { this._alternatives.getValue().reset(); this.model.cancel(); this.model.clear(); return; } if (!this.editor.hasModel()) { return; } var model = this.editor.getModel(); var modelVersionNow = model.getAlternativeVersionId(); var item = event.item; var suggestion = item.completion; // pushing undo stops *before* additional text edits and // *after* the main edit if (!(flags & 1 /* NoBeforeUndoStop */)) { this.editor.pushUndoStop(); } // compute overwrite[Before|After] deltas BEFORE applying extra edits var info = this.getOverwriteInfo(item, Boolean(flags & 8 /* AlternativeOverwriteConfig */)); // keep item in memory this._memoryService.memorize(model, this.editor.getPosition(), item); if (Array.isArray(suggestion.additionalTextEdits)) { this.editor.executeEdits('suggestController.additionalTextEdits', suggestion.additionalTextEdits.map(function (edit) { return editOperation_1.EditOperation.replace(range_1.Range.lift(edit.range), edit.text); })); } var insertText = suggestion.insertText; if (!(suggestion.insertTextRules & 4 /* InsertAsSnippet */)) { insertText = snippetParser_1.SnippetParser.escape(insertText); } snippetController2_1.SnippetController2.get(this.editor).insert(insertText, { overwriteBefore: info.overwriteBefore, overwriteAfter: info.overwriteAfter, undoStopBefore: false, undoStopAfter: false, adjustWhitespace: !(suggestion.insertTextRules & 1 /* KeepWhitespace */) }); if (!(flags & 2 /* NoAfterUndoStop */)) { this.editor.pushUndoStop(); } if (!suggestion.command) { // done this.model.cancel(); this.model.clear(); } else if (suggestion.command.id === TriggerSuggestAction.id) { // retigger this.model.trigger({ auto: true, shy: false }, true); } else { // exec command, done (_a = this._commandService).executeCommand.apply(_a, __spreadArrays([suggestion.command.id], (suggestion.command.arguments ? __spreadArrays(suggestion.command.arguments) : []))).catch(errors_1.onUnexpectedError) .finally(function () { return _this.model.clear(); }); // <- clear only now, keep commands alive this.model.cancel(); } if (flags & 4 /* KeepAlternativeSuggestions */) { this._alternatives.getValue().set(event, function (next) { // this is not so pretty. when inserting the 'next' // suggestion we undo until we are at the state at // which we were before inserting the previous suggestion... while (model.canUndo()) { if (modelVersionNow !== model.getAlternativeVersionId()) { model.undo(); } _this._insertSuggestion(next, 1 /* NoBeforeUndoStop */ | 2 /* NoAfterUndoStop */ | (flags & 8 /* AlternativeOverwriteConfig */ ? 8 /* AlternativeOverwriteConfig */ : 0)); break; } }); } this._alertCompletionItem(event.item); }; SuggestController.prototype.getOverwriteInfo = function (item, toggleMode) { types_1.assertType(this.editor.hasModel()); var replace = this.editor.getOption(89 /* suggest */).insertMode === 'replace'; if (toggleMode) { replace = !replace; } var overwriteBefore = item.position.column - item.editStart.column; var overwriteAfter = (replace ? item.editReplaceEnd.column : item.editInsertEnd.column) - item.position.column; var columnDelta = this.editor.getPosition().column - item.position.column; var suffixDelta = this._lineSuffix.value ? this._lineSuffix.value.delta(this.editor.getPosition()) : 0; return { overwriteBefore: overwriteBefore + columnDelta, overwriteAfter: overwriteAfter + suffixDelta }; }; SuggestController.prototype._alertCompletionItem = function (_a) { var suggestion = _a.completion; var textLabel = typeof suggestion.label === 'string' ? suggestion.label : suggestion.label.name; if (arrays_1.isNonEmptyArray(suggestion.additionalTextEdits)) { var msg = nls.localize(0, null, textLabel, suggestion.additionalTextEdits.length); aria_1.alert(msg); } }; SuggestController.prototype.triggerSuggest = function (onlyFrom) { if (this.editor.hasModel()) { this.model.trigger({ auto: false, shy: false }, false, onlyFrom); this.editor.revealLine(this.editor.getPosition().lineNumber, 0 /* Smooth */); this.editor.focus(); } }; SuggestController.prototype.triggerSuggestAndAcceptBest = function (arg) { var _this = this; if (!this.editor.hasModel()) { return; } var positionNow = this.editor.getPosition(); var fallback = function () { if (positionNow.equals(_this.editor.getPosition())) { _this._commandService.executeCommand(arg.fallback); } }; var makesTextEdit = function (item) { if (item.completion.insertTextRules & 4 /* InsertAsSnippet */ || item.completion.additionalTextEdits) { // snippet, other editor -> makes edit return true; } var position = _this.editor.getPosition(); var startColumn = item.editStart.column; var endColumn = position.column; if (endColumn - startColumn !== item.completion.insertText.length) { // unequal lengths -> makes edit return true; } var textNow = _this.editor.getModel().getValueInRange({ startLineNumber: position.lineNumber, startColumn: startColumn, endLineNumber: position.lineNumber, endColumn: endColumn }); // unequal text -> makes edit return textNow !== item.completion.insertText; }; event_1.Event.once(this.model.onDidTrigger)(function (_) { // wait for trigger because only then the cancel-event is trustworthy var listener = []; event_1.Event.any(_this.model.onDidTrigger, _this.model.onDidCancel)(function () { // retrigger or cancel -> try to type default text lifecycle_1.dispose(listener); fallback(); }, undefined, listener); _this.model.onDidSuggest(function (_a) { var completionModel = _a.completionModel; lifecycle_1.dispose(listener); if (completionModel.items.length === 0) { fallback(); return; } var index = _this._memoryService.select(_this.editor.getModel(), _this.editor.getPosition(), completionModel.items); var item = completionModel.items[index]; if (!makesTextEdit(item)) { fallback(); return; } _this.editor.pushUndoStop(); _this._insertSuggestion({ index: index, item: item, model: completionModel }, 4 /* KeepAlternativeSuggestions */ | 1 /* NoBeforeUndoStop */ | 2 /* NoAfterUndoStop */); }, undefined, listener); }); this.model.trigger({ auto: false, shy: true }); this.editor.revealLine(positionNow.lineNumber, 0 /* Smooth */); this.editor.focus(); }; SuggestController.prototype.acceptSelectedSuggestion = function (keepAlternativeSuggestions, alternativeOverwriteConfig) { var item = this.widget.getValue().getFocusedItem(); var flags = 0; if (keepAlternativeSuggestions) { flags |= 4 /* KeepAlternativeSuggestions */; } if (alternativeOverwriteConfig) { flags |= 8 /* AlternativeOverwriteConfig */; } this._insertSuggestion(item, flags); }; SuggestController.prototype.acceptNextSuggestion = function () { this._alternatives.getValue().next(); }; SuggestController.prototype.acceptPrevSuggestion = function () { this._alternatives.getValue().prev(); }; SuggestController.prototype.cancelSuggestWidget = function () { this.model.cancel(); this.model.clear(); this.widget.getValue().hideWidget(); }; SuggestController.prototype.selectNextSuggestion = function () { this.widget.getValue().selectNext(); }; SuggestController.prototype.selectNextPageSuggestion = function () { this.widget.getValue().selectNextPage(); }; SuggestController.prototype.selectLastSuggestion = function () { this.widget.getValue().selectLast(); }; SuggestController.prototype.selectPrevSuggestion = function () { this.widget.getValue().selectPrevious(); }; SuggestController.prototype.selectPrevPageSuggestion = function () { this.widget.getValue().selectPreviousPage(); }; SuggestController.prototype.selectFirstSuggestion = function () { this.widget.getValue().selectFirst(); }; SuggestController.prototype.toggleSuggestionDetails = function () { this.widget.getValue().toggleDetails(); }; SuggestController.prototype.toggleExplainMode = function () { this.widget.getValue().toggleExplainMode(); }; SuggestController.prototype.toggleSuggestionFocus = function () { this.widget.getValue().toggleDetailsFocus(); }; SuggestController.ID = 'editor.contrib.suggestController'; SuggestController = __decorate([ __param(1, editorWorkerService_1.IEditorWorkerService), __param(2, suggestMemory_1.ISuggestMemoryService), __param(3, commands_1.ICommandService), __param(4, contextkey_1.IContextKeyService), __param(5, instantiation_1.IInstantiationService) ], SuggestController); return SuggestController; }()); exports.SuggestController = SuggestController; var TriggerSuggestAction = /** @class */ (function (_super) { __extends(TriggerSuggestAction, _super); function TriggerSuggestAction() { return _super.call(this, { id: TriggerSuggestAction.id, label: nls.localize(1, null), alias: 'Trigger Suggest', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasCompletionItemProvider), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 10 /* Space */, mac: { primary: 256 /* WinCtrl */ | 10 /* Space */, secondary: [512 /* Alt */ | 9 /* Escape */] }, weight: 100 /* EditorContrib */ } }) || this; } TriggerSuggestAction.prototype.run = function (accessor, editor) { var controller = SuggestController.get(editor); if (!controller) { return; } controller.triggerSuggest(); }; TriggerSuggestAction.id = 'editor.action.triggerSuggest'; return TriggerSuggestAction; }(editorExtensions_1.EditorAction)); exports.TriggerSuggestAction = TriggerSuggestAction; editorExtensions_1.registerEditorContribution(SuggestController.ID, SuggestController); editorExtensions_1.registerEditorAction(TriggerSuggestAction); var weight = 100 /* EditorContrib */ + 90; var SuggestCommand = editorExtensions_1.EditorCommand.bindToContribution(SuggestController.get); editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'acceptSelectedSuggestion', precondition: suggest_1.Context.Visible, handler: function (x) { x.acceptSelectedSuggestion(true, false); } })); // normal tab keybindingsRegistry_1.KeybindingsRegistry.registerKeybindingRule({ id: 'acceptSelectedSuggestion', when: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, editorContextKeys_1.EditorContextKeys.textInputFocus), primary: 2 /* Tab */, weight: weight }); // accept on enter has special rules keybindingsRegistry_1.KeybindingsRegistry.registerKeybindingRule({ id: 'acceptSelectedSuggestion', when: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, editorContextKeys_1.EditorContextKeys.textInputFocus, suggest_1.Context.AcceptSuggestionsOnEnter, suggest_1.Context.MakesTextEdit), primary: 3 /* Enter */, weight: weight }); // todo@joh control enablement via context key // shift+enter and shift+tab use the alternative-flag so that the suggest controller // is doing the opposite of the editor.suggest.overwriteOnAccept-configuration editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'acceptAlternativeSelectedSuggestion', precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, editorContextKeys_1.EditorContextKeys.textInputFocus), kbOpts: { weight: weight, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 1024 /* Shift */ | 3 /* Enter */, secondary: [1024 /* Shift */ | 2 /* Tab */], }, handler: function (x) { x.acceptSelectedSuggestion(false, true); }, })); // continue to support the old command commands_1.CommandsRegistry.registerCommandAlias('acceptSelectedSuggestionOnEnter', 'acceptSelectedSuggestion'); editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'hideSuggestWidget', precondition: suggest_1.Context.Visible, handler: function (x) { return x.cancelSuggestWidget(); }, kbOpts: { weight: weight, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 9 /* Escape */, secondary: [1024 /* Shift */ | 9 /* Escape */] } })); editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'selectNextSuggestion', precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.MultipleSuggestions), handler: function (c) { return c.selectNextSuggestion(); }, kbOpts: { weight: weight, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 18 /* DownArrow */, secondary: [2048 /* CtrlCmd */ | 18 /* DownArrow */], mac: { primary: 18 /* DownArrow */, secondary: [2048 /* CtrlCmd */ | 18 /* DownArrow */, 256 /* WinCtrl */ | 44 /* KEY_N */] } } })); editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'selectNextPageSuggestion', precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.MultipleSuggestions), handler: function (c) { return c.selectNextPageSuggestion(); }, kbOpts: { weight: weight, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 12 /* PageDown */, secondary: [2048 /* CtrlCmd */ | 12 /* PageDown */] } })); editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'selectLastSuggestion', precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.MultipleSuggestions), handler: function (c) { return c.selectLastSuggestion(); } })); editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'selectPrevSuggestion', precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.MultipleSuggestions), handler: function (c) { return c.selectPrevSuggestion(); }, kbOpts: { weight: weight, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 16 /* UpArrow */, secondary: [2048 /* CtrlCmd */ | 16 /* UpArrow */], mac: { primary: 16 /* UpArrow */, secondary: [2048 /* CtrlCmd */ | 16 /* UpArrow */, 256 /* WinCtrl */ | 46 /* KEY_P */] } } })); editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'selectPrevPageSuggestion', precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.MultipleSuggestions), handler: function (c) { return c.selectPrevPageSuggestion(); }, kbOpts: { weight: weight, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 11 /* PageUp */, secondary: [2048 /* CtrlCmd */ | 11 /* PageUp */] } })); editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'selectFirstSuggestion', precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.MultipleSuggestions), handler: function (c) { return c.selectFirstSuggestion(); } })); editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'toggleSuggestionDetails', precondition: suggest_1.Context.Visible, handler: function (x) { return x.toggleSuggestionDetails(); }, kbOpts: { weight: weight, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 10 /* Space */, mac: { primary: 256 /* WinCtrl */ | 10 /* Space */ } } })); editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'toggleExplainMode', precondition: suggest_1.Context.Visible, handler: function (x) { return x.toggleExplainMode(); }, kbOpts: { weight: 100 /* EditorContrib */, primary: 2048 /* CtrlCmd */ | 85 /* US_SLASH */, } })); editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'toggleSuggestionFocus', precondition: suggest_1.Context.Visible, handler: function (x) { return x.toggleSuggestionFocus(); }, kbOpts: { weight: weight, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 10 /* Space */, mac: { primary: 256 /* WinCtrl */ | 512 /* Alt */ | 10 /* Space */ } } })); //#region tab completions editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'insertBestCompletion', precondition: contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.equals('config.editor.tabCompletion', 'on'), wordContextKey_1.WordContextKey.AtEnd, suggest_1.Context.Visible.toNegated(), suggestAlternatives_1.SuggestAlternatives.OtherSuggestions.toNegated(), snippetController2_1.SnippetController2.InSnippetMode.toNegated()), handler: function (x, arg) { x.triggerSuggestAndAcceptBest(types_1.isObject(arg) ? __assign({ fallback: 'tab' }, arg) : { fallback: 'tab' }); }, kbOpts: { weight: weight, primary: 2 /* Tab */ } })); editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'insertNextSuggestion', precondition: contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.equals('config.editor.tabCompletion', 'on'), suggestAlternatives_1.SuggestAlternatives.OtherSuggestions, suggest_1.Context.Visible.toNegated(), snippetController2_1.SnippetController2.InSnippetMode.toNegated()), handler: function (x) { return x.acceptNextSuggestion(); }, kbOpts: { weight: weight, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2 /* Tab */ } })); editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'insertPrevSuggestion', precondition: contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.equals('config.editor.tabCompletion', 'on'), suggestAlternatives_1.SuggestAlternatives.OtherSuggestions, suggest_1.Context.Visible.toNegated(), snippetController2_1.SnippetController2.InSnippetMode.toNegated()), handler: function (x) { return x.acceptPrevSuggestion(); }, kbOpts: { weight: weight, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 1024 /* Shift */ | 2 /* Tab */ } })); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[611/*vs/editor/editor.all*/], __M([0/*require*/,1/*exports*/,164/*vs/editor/browser/controller/coreCommands*/,121/*vs/editor/browser/widget/codeEditorWidget*/,230/*vs/editor/browser/widget/diffEditorWidget*/,188/*vs/editor/browser/widget/diffNavigator*/,566/*vs/editor/contrib/bracketMatching/bracketMatching*/,524/*vs/editor/contrib/caretOperations/caretOperations*/,525/*vs/editor/contrib/caretOperations/transpose*/,526/*vs/editor/contrib/clipboard/clipboard*/,579/*vs/editor/contrib/codeAction/codeActionContributions*/,569/*vs/editor/contrib/codelens/codelensController*/,223/*vs/editor/contrib/colorPicker/colorDetector*/,530/*vs/editor/contrib/comment/comment*/,531/*vs/editor/contrib/contextmenu/contextmenu*/,532/*vs/editor/contrib/cursorUndo/cursorUndo*/,533/*vs/editor/contrib/dnd/dnd*/,232/*vs/editor/contrib/find/findController*/,574/*vs/editor/contrib/folding/folding*/,534/*vs/editor/contrib/fontZoom/fontZoom*/,536/*vs/editor/contrib/format/formatActions*/,235/*vs/editor/contrib/gotoSymbol/goToCommands*/,236/*vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/,237/*vs/editor/contrib/gotoError/gotoError*/,601/*vs/editor/contrib/hover/hover*/,576/*vs/editor/contrib/inPlaceReplace/inPlaceReplace*/,539/*vs/editor/contrib/linesOperations/linesOperations*/,577/*vs/editor/contrib/links/links*/,580/*vs/editor/contrib/multicursor/multicursor*/,582/*vs/editor/contrib/parameterHints/parameterHints*/,584/*vs/editor/contrib/rename/rename*/,541/*vs/editor/contrib/smartSelect/smartSelect*/,173/*vs/editor/contrib/snippet/snippetController2*/,610/*vs/editor/contrib/suggest/suggestController*/,542/*vs/editor/contrib/tokenization/tokenization*/,225/*vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/,586/*vs/editor/contrib/wordHighlighter/wordHighlighter*/,226/*vs/editor/contrib/wordOperations/wordOperations*/,543/*vs/editor/contrib/wordPartOperations/wordPartOperations*/,59/*vs/editor/common/standaloneStrings*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[615/*vs/editor/editor.main*/], __M([0/*require*/,1/*exports*/,605/*vs/editor/editor.api*/,611/*vs/editor/editor.all*/,587/*vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/,544/*vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/,588/*vs/editor/standalone/browser/inspectTokens/inspectTokens*/,589/*vs/editor/standalone/browser/quickOpen/gotoLine*/,590/*vs/editor/standalone/browser/quickOpen/quickCommand*/,591/*vs/editor/standalone/browser/quickOpen/quickOutline*/,597/*vs/editor/standalone/browser/referenceSearch/standaloneReferenceSearch*/,545/*vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast*/]), function (require, exports, editor_api_1) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(editor_api_1); }); }).call(this); define("vs/language/typescript/monaco.contribution",["require", "exports", "./lib/typescriptServicesMetadata","vs/editor/editor.api"], function (require, exports, typescriptServicesMetadata_1) { /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var Emitter = monaco.Emitter; var LanguageServiceDefaultsImpl = /** @class */ (function () { function LanguageServiceDefaultsImpl(compilerOptions, diagnosticsOptions) { this._onDidChange = new Emitter(); this._onDidExtraLibsChange = new Emitter(); this._extraLibs = Object.create(null); this._eagerModelSync = false; this.setCompilerOptions(compilerOptions); this.setDiagnosticsOptions(diagnosticsOptions); this._onDidExtraLibsChangeTimeout = -1; } Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "onDidChange", { get: function () { return this._onDidChange.event; }, enumerable: true, configurable: true }); Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "onDidExtraLibsChange", { get: function () { return this._onDidExtraLibsChange.event; }, enumerable: true, configurable: true }); LanguageServiceDefaultsImpl.prototype.getExtraLibs = function () { return this._extraLibs; }; LanguageServiceDefaultsImpl.prototype.addExtraLib = function (content, _filePath) { var _this = this; var filePath; if (typeof _filePath === 'undefined') { filePath = "ts:extralib-" + Math.random().toString(36).substring(2, 15); } else { filePath = _filePath; } if (this._extraLibs[filePath] && this._extraLibs[filePath].content === content) { // no-op, there already exists an extra lib with this content return { dispose: function () { } }; } var myVersion = 1; if (this._extraLibs[filePath]) { myVersion = this._extraLibs[filePath].version + 1; } this._extraLibs[filePath] = { content: content, version: myVersion, }; this._fireOnDidExtraLibsChangeSoon(); return { dispose: function () { var extraLib = _this._extraLibs[filePath]; if (!extraLib) { return; } if (extraLib.version !== myVersion) { return; } delete _this._extraLibs[filePath]; _this._fireOnDidExtraLibsChangeSoon(); } }; }; LanguageServiceDefaultsImpl.prototype.setExtraLibs = function (libs) { // clear out everything this._extraLibs = Object.create(null); if (libs && libs.length > 0) { for (var _i = 0, libs_1 = libs; _i < libs_1.length; _i++) { var lib = libs_1[_i]; var filePath = lib.filePath || "ts:extralib-" + Math.random().toString(36).substring(2, 15); var content = lib.content; this._extraLibs[filePath] = { content: content, version: 1 }; } } this._fireOnDidExtraLibsChangeSoon(); }; LanguageServiceDefaultsImpl.prototype._fireOnDidExtraLibsChangeSoon = function () { var _this = this; if (this._onDidExtraLibsChangeTimeout !== -1) { // already scheduled return; } this._onDidExtraLibsChangeTimeout = setTimeout(function () { _this._onDidExtraLibsChangeTimeout = -1; _this._onDidExtraLibsChange.fire(undefined); }, 0); }; LanguageServiceDefaultsImpl.prototype.getCompilerOptions = function () { return this._compilerOptions; }; LanguageServiceDefaultsImpl.prototype.setCompilerOptions = function (options) { this._compilerOptions = options || Object.create(null); this._onDidChange.fire(undefined); }; LanguageServiceDefaultsImpl.prototype.getDiagnosticsOptions = function () { return this._diagnosticsOptions; }; LanguageServiceDefaultsImpl.prototype.setDiagnosticsOptions = function (options) { this._diagnosticsOptions = options || Object.create(null); this._onDidChange.fire(undefined); }; LanguageServiceDefaultsImpl.prototype.setMaximumWorkerIdleTime = function (value) { }; LanguageServiceDefaultsImpl.prototype.setEagerModelSync = function (value) { // doesn't fire an event since no // worker restart is required here this._eagerModelSync = value; }; LanguageServiceDefaultsImpl.prototype.getEagerModelSync = function () { return this._eagerModelSync; }; return LanguageServiceDefaultsImpl; }()); exports.LanguageServiceDefaultsImpl = LanguageServiceDefaultsImpl; //#region enums copied from typescript to prevent loading the entire typescriptServices --- var ModuleKind; (function (ModuleKind) { ModuleKind[ModuleKind["None"] = 0] = "None"; ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; ModuleKind[ModuleKind["System"] = 4] = "System"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext"; })(ModuleKind || (ModuleKind = {})); var JsxEmit; (function (JsxEmit) { JsxEmit[JsxEmit["None"] = 0] = "None"; JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; JsxEmit[JsxEmit["React"] = 2] = "React"; JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; })(JsxEmit || (JsxEmit = {})); var NewLineKind; (function (NewLineKind) { NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; })(NewLineKind || (NewLineKind = {})); var ScriptTarget; (function (ScriptTarget) { ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019"; ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020"; ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext"; ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest"; })(ScriptTarget || (ScriptTarget = {})); var ModuleResolutionKind; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; })(ModuleResolutionKind || (ModuleResolutionKind = {})); //#endregion var typescriptDefaults = new LanguageServiceDefaultsImpl({ allowNonTsExtensions: true, target: ScriptTarget.Latest }, { noSemanticValidation: false, noSyntaxValidation: false }); var javascriptDefaults = new LanguageServiceDefaultsImpl({ allowNonTsExtensions: true, allowJs: true, target: ScriptTarget.Latest }, { noSemanticValidation: true, noSyntaxValidation: false }); function getTypeScriptWorker() { return getMode().then(function (mode) { return mode.getTypeScriptWorker(); }); } function getJavaScriptWorker() { return getMode().then(function (mode) { return mode.getJavaScriptWorker(); }); } // Export API function createAPI() { return { ModuleKind: ModuleKind, JsxEmit: JsxEmit, NewLineKind: NewLineKind, ScriptTarget: ScriptTarget, ModuleResolutionKind: ModuleResolutionKind, typescriptVersion: typescriptServicesMetadata_1.typescriptVersion, typescriptDefaults: typescriptDefaults, javascriptDefaults: javascriptDefaults, getTypeScriptWorker: getTypeScriptWorker, getJavaScriptWorker: getJavaScriptWorker }; } monaco.languages.typescript = createAPI(); // --- Registration to monaco editor --- function getMode() { return new Promise(function (resolve_1, reject_1) { require(['./tsMode'], resolve_1, reject_1); }); } monaco.languages.onLanguage('typescript', function () { return getMode().then(function (mode) { return mode.setupTypeScript(typescriptDefaults); }); }); monaco.languages.onLanguage('javascript', function () { return getMode().then(function (mode) { return mode.setupJavaScript(javascriptDefaults); }); }); }); define('vs/language/css/monaco.contribution',["require", "exports","vs/editor/editor.api"], function (require, exports) { /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var Emitter = monaco.Emitter; // --- CSS configuration and defaults --------- var LanguageServiceDefaultsImpl = /** @class */ (function () { function LanguageServiceDefaultsImpl(languageId, diagnosticsOptions, modeConfiguration) { this._onDidChange = new Emitter(); this._languageId = languageId; this.setDiagnosticsOptions(diagnosticsOptions); this.setModeConfiguration(modeConfiguration); } Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "onDidChange", { get: function () { return this._onDidChange.event; }, enumerable: true, configurable: true }); Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "languageId", { get: function () { return this._languageId; }, enumerable: true, configurable: true }); Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "modeConfiguration", { get: function () { return this._modeConfiguration; }, enumerable: true, configurable: true }); Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "diagnosticsOptions", { get: function () { return this._diagnosticsOptions; }, enumerable: true, configurable: true }); LanguageServiceDefaultsImpl.prototype.setDiagnosticsOptions = function (options) { this._diagnosticsOptions = options || Object.create(null); this._onDidChange.fire(this); }; LanguageServiceDefaultsImpl.prototype.setModeConfiguration = function (modeConfiguration) { this._modeConfiguration = modeConfiguration || Object.create(null); this._onDidChange.fire(this); }; ; return LanguageServiceDefaultsImpl; }()); exports.LanguageServiceDefaultsImpl = LanguageServiceDefaultsImpl; var diagnosticDefault = { validate: true, lint: { compatibleVendorPrefixes: 'ignore', vendorPrefix: 'warning', duplicateProperties: 'warning', emptyRules: 'warning', importStatement: 'ignore', boxModel: 'ignore', universalSelector: 'ignore', zeroUnits: 'ignore', fontFaceProperties: 'warning', hexColorLength: 'error', argumentsInColorFunction: 'error', unknownProperties: 'warning', ieHack: 'ignore', unknownVendorSpecificProperties: 'ignore', propertyIgnoredDueToDisplay: 'warning', important: 'ignore', float: 'ignore', idSelector: 'ignore' } }; var modeConfigurationDefault = { completionItems: true, hovers: true, documentSymbols: true, definitions: true, references: true, documentHighlights: true, rename: true, colors: true, foldingRanges: true, diagnostics: true, selectionRanges: true }; var cssDefaults = new LanguageServiceDefaultsImpl('css', diagnosticDefault, modeConfigurationDefault); var scssDefaults = new LanguageServiceDefaultsImpl('scss', diagnosticDefault, modeConfigurationDefault); var lessDefaults = new LanguageServiceDefaultsImpl('less', diagnosticDefault, modeConfigurationDefault); // Export API function createAPI() { return { cssDefaults: cssDefaults, lessDefaults: lessDefaults, scssDefaults: scssDefaults }; } monaco.languages.css = createAPI(); // --- Registration to monaco editor --- function getMode() { return new Promise(function (resolve_1, reject_1) { require(['./cssMode'], resolve_1, reject_1); }); } monaco.languages.onLanguage('less', function () { getMode().then(function (mode) { return mode.setupMode(lessDefaults); }); }); monaco.languages.onLanguage('scss', function () { getMode().then(function (mode) { return mode.setupMode(scssDefaults); }); }); monaco.languages.onLanguage('css', function () { getMode().then(function (mode) { return mode.setupMode(cssDefaults); }); }); }); define('vs/language/json/monaco.contribution',["require", "exports","vs/editor/editor.api"], function (require, exports) { /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var Emitter = monaco.Emitter; // --- JSON configuration and defaults --------- var LanguageServiceDefaultsImpl = /** @class */ (function () { function LanguageServiceDefaultsImpl(languageId, diagnosticsOptions, modeConfiguration) { this._onDidChange = new Emitter(); this._languageId = languageId; this.setDiagnosticsOptions(diagnosticsOptions); this.setModeConfiguration(modeConfiguration); } Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "onDidChange", { get: function () { return this._onDidChange.event; }, enumerable: true, configurable: true }); Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "languageId", { get: function () { return this._languageId; }, enumerable: true, configurable: true }); Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "modeConfiguration", { get: function () { return this._modeConfiguration; }, enumerable: true, configurable: true }); Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "diagnosticsOptions", { get: function () { return this._diagnosticsOptions; }, enumerable: true, configurable: true }); LanguageServiceDefaultsImpl.prototype.setDiagnosticsOptions = function (options) { this._diagnosticsOptions = options || Object.create(null); this._onDidChange.fire(this); }; LanguageServiceDefaultsImpl.prototype.setModeConfiguration = function (modeConfiguration) { this._modeConfiguration = modeConfiguration || Object.create(null); this._onDidChange.fire(this); }; ; return LanguageServiceDefaultsImpl; }()); exports.LanguageServiceDefaultsImpl = LanguageServiceDefaultsImpl; var diagnosticDefault = { validate: true, allowComments: true, schemas: [], enableSchemaRequest: false }; var modeConfigurationDefault = { documentFormattingEdits: true, documentRangeFormattingEdits: true, completionItems: true, hovers: true, documentSymbols: true, tokens: true, colors: true, foldingRanges: true, diagnostics: true, selectionRanges: true }; var jsonDefaults = new LanguageServiceDefaultsImpl('json', diagnosticDefault, modeConfigurationDefault); // Export API function createAPI() { return { jsonDefaults: jsonDefaults }; } monaco.languages.json = createAPI(); // --- Registration to monaco editor --- function getMode() { return new Promise(function (resolve_1, reject_1) { require(['./jsonMode'], resolve_1, reject_1); }); } monaco.languages.register({ id: 'json', extensions: ['.json', '.bowerrc', '.jshintrc', '.jscsrc', '.eslintrc', '.babelrc', '.har'], aliases: ['JSON', 'json'], mimetypes: ['application/json'], }); monaco.languages.onLanguage('json', function () { getMode().then(function (mode) { return mode.setupMode(jsonDefaults); }); }); }); define('vs/language/html/monaco.contribution',["require", "exports","vs/editor/editor.api"], function (require, exports) { /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var Emitter = monaco.Emitter; // --- HTML configuration and defaults --------- var LanguageServiceDefaultsImpl = /** @class */ (function () { function LanguageServiceDefaultsImpl(languageId, options, modeConfiguration) { this._onDidChange = new Emitter(); this._languageId = languageId; this.setOptions(options); this.setModeConfiguration(modeConfiguration); } Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "onDidChange", { get: function () { return this._onDidChange.event; }, enumerable: true, configurable: true }); Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "languageId", { get: function () { return this._languageId; }, enumerable: true, configurable: true }); Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "options", { get: function () { return this._options; }, enumerable: true, configurable: true }); Object.defineProperty(LanguageServiceDefaultsImpl.prototype, "modeConfiguration", { get: function () { return this._modeConfiguration; }, enumerable: true, configurable: true }); LanguageServiceDefaultsImpl.prototype.setOptions = function (options) { this._options = options || Object.create(null); this._onDidChange.fire(this); }; LanguageServiceDefaultsImpl.prototype.setModeConfiguration = function (modeConfiguration) { this._modeConfiguration = modeConfiguration || Object.create(null); this._onDidChange.fire(this); }; ; return LanguageServiceDefaultsImpl; }()); exports.LanguageServiceDefaultsImpl = LanguageServiceDefaultsImpl; var formatDefaults = { tabSize: 4, insertSpaces: false, wrapLineLength: 120, unformatted: 'default": "a, abbr, acronym, b, bdo, big, br, button, cite, code, dfn, em, i, img, input, kbd, label, map, object, q, samp, select, small, span, strong, sub, sup, textarea, tt, var', contentUnformatted: 'pre', indentInnerHtml: false, preserveNewLines: true, maxPreserveNewLines: null, indentHandlebars: false, endWithNewline: false, extraLiners: 'head, body, /html', wrapAttributes: 'auto' }; var htmlOptionsDefault = { format: formatDefaults, suggest: { html5: true, angular1: true, ionic: true } }; var handlebarOptionsDefault = { format: formatDefaults, suggest: { html5: true } }; var razorOptionsDefault = { format: formatDefaults, suggest: { html5: true, razor: true } }; function getConfigurationDefault(languageId) { return { completionItems: true, hovers: true, documentSymbols: true, links: true, documentHighlights: true, rename: true, colors: true, foldingRanges: true, selectionRanges: true, diagnostics: languageId === htmlLanguageId, documentFormattingEdits: languageId === htmlLanguageId, documentRangeFormattingEdits: languageId === htmlLanguageId // turned off for Razor and Handlebar }; } var htmlLanguageId = 'html'; var handlebarsLanguageId = 'handlebars'; var razorLanguageId = 'razor'; var htmlDefaults = new LanguageServiceDefaultsImpl(htmlLanguageId, htmlOptionsDefault, getConfigurationDefault(htmlLanguageId)); var handlebarDefaults = new LanguageServiceDefaultsImpl(handlebarsLanguageId, handlebarOptionsDefault, getConfigurationDefault(handlebarsLanguageId)); var razorDefaults = new LanguageServiceDefaultsImpl(razorLanguageId, razorOptionsDefault, getConfigurationDefault(razorLanguageId)); // Export API function createAPI() { return { htmlDefaults: htmlDefaults, razorDefaults: razorDefaults, handlebarDefaults: handlebarDefaults }; } monaco.languages.html = createAPI(); // --- Registration to monaco editor --- function getMode() { return new Promise(function (resolve_1, reject_1) { require(['./htmlMode'], resolve_1, reject_1); }); } monaco.languages.onLanguage(htmlLanguageId, function () { getMode().then(function (mode) { return mode.setupMode(htmlDefaults); }); }); monaco.languages.onLanguage(handlebarsLanguageId, function () { getMode().then(function (mode) { return mode.setupMode(handlebarDefaults); }); }); monaco.languages.onLanguage(razorLanguageId, function () { getMode().then(function (mode) { return mode.setupMode(razorDefaults); }); }); }); define("vs/basic-languages/monaco.contribution",["require", "exports", "./abap/abap.contribution", "./apex/apex.contribution", "./azcli/azcli.contribution", "./bat/bat.contribution", "./cameligo/cameligo.contribution", "./clojure/clojure.contribution", "./coffee/coffee.contribution", "./cpp/cpp.contribution", "./csharp/csharp.contribution", "./csp/csp.contribution", "./css/css.contribution", "./dockerfile/dockerfile.contribution", "./fsharp/fsharp.contribution", "./go/go.contribution", "./graphql/graphql.contribution", "./handlebars/handlebars.contribution", "./html/html.contribution", "./ini/ini.contribution", "./java/java.contribution", "./javascript/javascript.contribution", "./kotlin/kotlin.contribution", "./less/less.contribution", "./lua/lua.contribution", "./markdown/markdown.contribution", "./mips/mips.contribution", "./msdax/msdax.contribution", "./mysql/mysql.contribution", "./objective-c/objective-c.contribution", "./pascal/pascal.contribution", "./pascaligo/pascaligo.contribution", "./perl/perl.contribution", "./pgsql/pgsql.contribution", "./php/php.contribution", "./postiats/postiats.contribution", "./powerquery/powerquery.contribution", "./powershell/powershell.contribution", "./pug/pug.contribution", "./python/python.contribution", "./r/r.contribution", "./razor/razor.contribution", "./redis/redis.contribution", "./redshift/redshift.contribution", "./restructuredtext/restructuredtext.contribution", "./ruby/ruby.contribution", "./rust/rust.contribution", "./sb/sb.contribution", "./scheme/scheme.contribution", "./scss/scss.contribution", "./shell/shell.contribution", "./solidity/solidity.contribution", "./sophia/sophia.contribution", "./sql/sql.contribution", "./st/st.contribution", "./swift/swift.contribution", "./tcl/tcl.contribution", "./twig/twig.contribution", "./typescript/typescript.contribution", "./vb/vb.contribution", "./xml/xml.contribution", "./yaml/yaml.contribution","vs/editor/editor.api"], function (require, exports) { /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); }); define("vs/editor/editor.main", ["vs/editor/edcore.main","vs/language/typescript/monaco.contribution","vs/language/css/monaco.contribution","vs/language/json/monaco.contribution","vs/language/html/monaco.contribution","vs/basic-languages/monaco.contribution"], function(api) { return api; }); //# sourceMappingURL=editor.main.js.map